-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathalias.c
55 lines (47 loc) · 1.3 KB
/
alias.c
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 <mrsh/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[]) {
mrsh_optind = 0;
if (mrsh_getopt(argc, argv, ":") != -1) {
fprintf(stderr, "alias: unknown option -- %c\n", mrsh_optopt);
fprintf(stderr, "%s", alias_usage);
return 1;
}
if (mrsh_optind == argc) {
mrsh_hashtable_for_each(&state->aliases, print_alias_iterator, NULL);
return 0;
}
for (int i = mrsh_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 1;
}
printf("%s=", alias);
print_escaped(value);
printf("\n");
}
}
return 0;
}