comparison toys/basename.c @ 409:55598a9b8f21

'env' and 'basename' refactored
author Tryn Mirell <tryn@mirell.org>
date Fri, 20 Jan 2012 00:02:37 -0600
parents 8506c538f26a
children eda61bcf575a
comparison
equal deleted inserted replaced
408:8506c538f26a 409:55598a9b8f21
5 * Copyright 2012 Tryn Mirell <tryn@mirell.org> 5 * Copyright 2012 Tryn Mirell <tryn@mirell.org>
6 * 6 *
7 * See http://opengroup.org/onlinepubs/9699919799/utilities/basename.html 7 * See http://opengroup.org/onlinepubs/9699919799/utilities/basename.html
8 8
9 9
10 USE_BASENAME(NEWTOY(basename, NULL, TOYFLAG_USR|TOYFLAG_BIN)) 10 USE_BASENAME(NEWTOY(basename, "<1>2", TOYFLAG_USR|TOYFLAG_BIN))
11 11
12 config BASENAME 12 config BASENAME
13 bool "basename" 13 bool "basename"
14 default n 14 default n
15 help 15 help
20 20
21 #include "toys.h" 21 #include "toys.h"
22 22
23 void basename_main(void) 23 void basename_main(void)
24 { 24 {
25 char *arg, *suffix, *base; 25 char *arg = toys.optargs[0], *suffix = toys.optargs[1], *base;
26 int arglen;
27 26
28 arg = toys.optargs[0]; 27 while ((base = strrchr(arg, '/'))) {
29 suffix = toys.optargs[1]; 28 if (base == arg) break;
30 29 if (!base[1]) *base = 0;
31 // return null string if nothing provided 30 else {
32 if (!arg) return; 31 base++;
33 32 break;
34 arglen = strlen(arg); 33 }
35
36 // handle the case where we only have single slash
37 if (arglen == 1 && arg[0] == '/') {
38 puts("/");
39 return;
40 } 34 }
41 35
42 // remove trailing slash
43 if (arg[arglen - 1] == '/') {
44 arg[arglen - 1] = 0;
45 }
46
47 // get everything past the last /
48 base = strrchr(arg, '/');
49
50 if (!base) base = arg; 36 if (!base) base = arg;
51 else base++;
52
53 // handle the case where we have all slashes
54 if (base[0] == 0) base = "/";
55 37
56 // chop off the suffix if provided 38 // chop off the suffix if provided
57 if (suffix) { 39 if (suffix) {
58 strstr(base, suffix)[0] = 0; 40 char *s = strstr(base, suffix);
41 if (s && s != base) *s = 0;
59 } 42 }
60 43
61 puts(base); 44 puts(base);
62 } 45 }