~emersion/mrsh

ref: 22232fa45aebd16dba5668440fcb974be9d08254 mrsh/builtin/alias.c -rw-r--r-- 1.3 KiB View raw
                                                                                
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
47
48
49
50
51
52
53
54
55
#define _POSIX_C_SOURCE 200809L
#include <getopt.h>
#include <mrsh/builtin.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "builtin.h"

static const char alias_usage[] = "usage: alias [alias-name[=string]...]\n";

static void print_alias_iterator(const char *key, void *_value,
		void *user_data) {
	const char *value = _value;
	printf("%s=", key);
	print_escaped(value);
	printf("\n");
}

int builtin_alias(struct mrsh_state *state, int argc, char *argv[]) {
	optind = 0;
	if (getopt(argc, argv, ":") != -1) {
		fprintf(stderr, "alias: unknown option -- %c\n", optopt);
		fprintf(stderr, alias_usage);
		return EXIT_FAILURE;
	}

	if (optind == argc) {
		mrsh_hashtable_for_each(&state->aliases, print_alias_iterator, NULL);
		return EXIT_SUCCESS;
	}

	for (int i = optind; i < argc; ++i) {
		char *alias = argv[i];
		char *equal = strchr(alias, '=');
		if (equal != NULL) {
			char *value = strdup(equal + 1);
			*equal = '\0';

			char *old_value = mrsh_hashtable_set(&state->aliases, alias, value);
			free(old_value);
		} else {
			const char *value = mrsh_hashtable_get(&state->aliases, alias);
			if (value == NULL) {
				fprintf(stderr, "%s: %s not found\n", argv[0], alias);
				return EXIT_FAILURE;
			}

			printf("%s=", alias);
			print_escaped(value);
			printf("\n");
		}
	}

	return EXIT_SUCCESS;
}