~emersion/mrsh

ref: 448ee4f664f60d70d229af5462ef349240af8d7f mrsh/builtin/type.c -rw-r--r-- 1.1 KiB
448ee4f6 — Ben Brown Reset optind to 0 1 year, 9 months 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
47
48
49
#define _POSIX_C_SOURCE 200809L
#include <getopt.h>
#include <mrsh/builtin.h>
#include <mrsh/shell.h>
#include <shell/path.h>
#include <stdlib.h>
#include "builtin.h"

static const char type_usage[] = "usage: type name...\n";

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

	bool error = false;
	for (int i = optind; i < argc; ++i) {
		char *name = argv[i];

		char *alias = mrsh_hashtable_get(&state->aliases, name);
		if (alias != NULL) {
			fprintf(stdout, "%s is an alias for %s\n", name, alias);
			continue;
		}

		if (mrsh_has_builtin(name)) {
			fprintf(stdout, "%s is a shell builtin\n", name);
			continue;
		}

		const char *path = expand_path(state, name, true);
		if (path) {
			fprintf(stdout, "%s is %s\n", name, path);
			continue;
		}

		fprintf(stdout, "%s: not found\n", name);
		error = true;
	}

	return error ? EXIT_FAILURE : EXIT_SUCCESS;
}