~emersion/mrsh

ref: ee4a9ab74c4bfed2eeafad1437ee363b67b946f6 mrsh/shell/task/function_definition.c -rw-r--r-- 1.2 KiB
ee4a9ab7Drew DeVault Introduce function definition task 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "shell/task.h"
#include "shell/tasks.h"
#include <mrsh/hashtable.h>
#include <stdlib.h>

struct task_function_definition {
	struct task task;
	char *name;
	struct mrsh_command *body;
};

static void task_function_definition_destroy(struct task *task) {
	struct task_function_definition *tfn =
		(struct task_function_definition *)task;
	free(tfn->name);
	free(tfn);
}

static int task_function_definition_poll(
		struct task *task, struct context *ctx) {
	struct task_function_definition *tfn =
		(struct task_function_definition *)task;
	struct mrsh_function *fn = calloc(1, sizeof(struct mrsh_function));
	fn->body = tfn->body;
	struct mrsh_function *oldfn = mrsh_hashtable_set(
			&ctx->state->functions, tfn->name, fn);
	if (oldfn) {
		free(oldfn);
	}
	return 0;
}

static const struct task_interface task_function_definition_impl = {
	.destroy = task_function_definition_destroy,
	.poll = task_function_definition_poll,
};

struct task *task_function_definition_create(
		char *name, struct mrsh_command *body) {
	struct task_function_definition *tfn = calloc(
			1, sizeof(struct task_function_definition));
	task_init(&tfn->task, &task_function_definition_impl);
	tfn->name = name;
	tfn->body = body;
	return (struct task *)tfn;
}