01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
|
// basename.c, version 1.0.1
// OMKOV coreutils implementation of POSIX basename
// Copyright (C) 2020, Jakob Wakeling
// MIT Licence
#include "util/error.h"
#include "util/optget.h"
#include <stdio.h>
#define VERSION "1.0.1"
static struct lop lops[] = {
{ "help", ARG_NUL, 256 },
{ "version", ARG_NUL, 257 },
{ NULL, 0, 0 }
};
static void hlp(void);
static void ver(void);
int main(int ac, char *av[]) { A0 = av[0];
struct opt opt = OPTGET_INIT; opt.str = ""; opt.lops = lops;
for (int o; (o = optget(&opt, av, 1)) != -1;) switch (o) {
case 256: { hlp(); return 0; }
case 257: { ver(); return 0; }
default: { return 1; }
}
if (opt.ind == ac) { error(1, "missing operand"); }
register char *p = av[opt.ind];
// If the string is empty, print "."
if (!*p) { fputc('.', stdout); fputc('\n', stdout); return 0; }
// From the end of the string, move left to the first non '/' character
for (++p; *p; ++p) {} for (--p; *p == '/'; --p);
// If the string contains only '/' characters, print "/"
if (p + 1 == av[opt.ind]) { fputs("/\n", stdout); return 0; }
else { p[1] = 0; } // Otherwise remove the trailing '/' characters
if (av[opt.ind + 1]) { // If a suffix operand is provided
register char *s = av[opt.ind + 1]; for (; *s; ++s);
// Move left through string and suffix as long as they are the same
for (--s; *p && *p != '/' && *s && *p == *s; --p, --s);
// If the suffix is matched completely and characters remain in the
// string without it, remove the suffix from the string
if (!*s && *p && *p != '/') { p[1] = 0; }
}
// Move pointer left until the start of the string or '/' is found and print
for (; *p && *p != '/'; --p) {} fputs(p + 1, stdout); fputc('\n', stdout);
return 0;
}
/* Print help information */
static void hlp(void) {
puts("basename - return the non-directory portion of a path\n");
puts("usage: basename string [suffix]\n");
puts("options:");
puts(" --help Display help information");
puts(" --version Display version information");
}
/* Print version information */
static void ver(void) {
puts("OMKOV coreutils basename, version " VERSION);
puts("Copyright (C) 2020, Jakob Wakeling");
puts("MIT Licence (https://opensource.org/licenses/MIT)");
}
|