summaryrefslogtreecommitdiffstats
path: root/wd.c
blob: 3fb2b46b7729d3391f5460caa699406d65886cf4 (plain) (blame)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <linux/limits.h>
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>

static void
die(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	fprintf(stderr, "wd: ");
	vfprintf(stderr, fmt, ap);
	if (*fmt && fmt[strlen(fmt)-1] == ':') {
		fputc(' ', stderr);
		perror(NULL);
	} else {
		fputc('\n', stderr);
	}
	va_end(ap);

	exit(1);
}

static void
findbin(char *dst, const char *name)
{
	char *env, *tok;
	struct dirent *ent;
	int len;
	DIR *d;

	env = getenv("PATH");
	if (!env) die("PATH not set");

	env = strdup(env);
	if (!env) die("strdup:");

	for (tok = strtok(env, ":"); tok; tok = strtok(NULL, ":")) {
		if (!*tok) continue;
		d = opendir(tok);
		if (!d) continue;
		while ((ent = readdir(d))) {
			if (!strcmp(ent->d_name, name)) {
				closedir(d);
				free(env);
				len = snprintf(dst, PATH_MAX,
					"%s/%s", tok, ent->d_name);
				if (len > PATH_MAX) abort();
				return;
			}
		}
		closedir(d);
	}

	free(env);

	die("'%s' not found", name);
}

int
main(int argc, char **argv)
{
	char binpath[PATH_MAX];

	if (argc < 3) {
		fprintf(stderr, "Usage: wd DIR CMD..\n");
		return 1;
	}

	if (chdir(argv[1])) die("chdir:");

	findbin(binpath, argv[2]);

	execv(binpath, argv + 2);

	die("execv:");
}