summaryrefslogtreecommitdiffstats
path: root/bfs.c
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@tavianator.com>2015-06-20 00:04:59 -0400
committerTavian Barnes <tavianator@tavianator.com>2015-06-20 00:04:59 -0400
commit22291402d329a49ab8ab4a272344cab902b2ab3b (patch)
treeb1337c8e1dbfe6ae1b9d79e2b16af210562c2e17 /bfs.c
parentad628c395cc45add3e3a87f21250cbd0df1d860e (diff)
downloadbfs-22291402d329a49ab8ab4a272344cab902b2ab3b.tar.xz
Add initial support for colorized output.
Diffstat (limited to 'bfs.c')
-rw-r--r--bfs.c51
1 files changed, 36 insertions, 15 deletions
diff --git a/bfs.c b/bfs.c
index 6c0e07c..c637ba3 100644
--- a/bfs.c
+++ b/bfs.c
@@ -10,50 +10,61 @@
*********************************************************************/
#include "bftw.h"
+#include "color.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
typedef struct {
const char *path;
+ color_table *colors;
bool hidden;
} options;
static int callback(const char *fpath, const struct stat *sb, int typeflag, void *ptr) {
const options *opts = ptr;
- const char *filename = strrchr(fpath, '/');
- if (filename) {
- ++filename;
- } else {
- filename = fpath + strlen(fpath);
- }
-
- if (!opts->hidden && filename[0] == '.') {
- return BFTW_SKIP_SUBTREE;
+ if (!opts->hidden) {
+ const char *filename = strrchr(fpath, '/');
+ if (filename && filename[1] == '.') {
+ return BFTW_SKIP_SUBTREE;
+ }
}
- printf("%s\n", fpath);
+ pretty_print(opts->colors, fpath, sb);
return BFTW_CONTINUE;
}
int main(int argc, char* argv[]) {
+ int ret = EXIT_FAILURE;
+
options opts;
opts.path = NULL;
+ opts.colors = NULL;
opts.hidden = true;
+ bool color = isatty(STDOUT_FILENO);
+
for (int i = 1; i < argc; ++i) {
const char *arg = argv[i];
- if (strcmp(arg, "-hidden") == 0) {
+ if (strcmp(arg, "-color") == 0) {
+ color = true;
+ } else if (strcmp(arg, "-nocolor") == 0) {
+ color = false;
+ } else if (strcmp(arg, "-hidden") == 0) {
opts.hidden = true;
} else if (strcmp(arg, "-nohidden") == 0) {
opts.hidden = false;
+ } else if (arg[0] == '-') {
+ fprintf(stderr, "Unknown option `%s`.", arg);
+ goto done;
} else {
if (opts.path) {
fprintf(stderr, "Duplicate path `%s` on command line.", arg);
- return EXIT_FAILURE;
+ goto done;
}
opts.path = arg;
}
@@ -63,11 +74,21 @@ int main(int argc, char* argv[]) {
opts.path = ".";
}
+ int flags = 0;
+
+ if (color) {
+ flags |= BFTW_STAT;
+ opts.colors = parse_colors(getenv("LS_COLORS"));
+ }
+
// TODO: getrlimit(RLIMIT_NOFILE)
- if (bftw(opts.path, callback, 1024, 0, &opts) != 0) {
+ if (bftw(opts.path, callback, 1024, flags, &opts) != 0) {
perror("bftw()");
- return EXIT_FAILURE;
+ goto done;
}
- return EXIT_SUCCESS;
+ ret = EXIT_SUCCESS;
+done:
+ free_colors(opts.colors);
+ return ret;
}