fe
terminal file explorer and picker
git clone https://9o.is/git/fe.git
options.c
(3048B)
1 #include <getopt.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <limits.h>
6 #include "options.h"
7
8 static const char *usage_str =
9 ""
10 "Usage: fe [OPTION] [path]\n"
11 " -n, --num-files=LINES Specify how many files to display\n"
12 " -t, --tty=TTY Specify file to use as TTY device (default /dev/tty)\n"
13 " -r, --run=file Run program when file is selected\n"
14 " -d, --sort-directory Sort by directories first\n"
15 " -m, --sort-mtime Sort by time modified\n"
16 " -i, --sort-icase Sort case insensitively\n"
17 " -a, --all Show all hidden files\n"
18 " -h, --help Display this help and exit\n"
19 " -v, --version Output version information and exit\n";
20
21 static void usage(const char *argv0) {
22 fprintf(stderr, usage_str, argv0);
23 }
24
25 static struct option longopts[] = {
26 {"num-files", required_argument, NULL, 'l'},
27 {"tty", required_argument, NULL, 't'},
28 {"run", required_argument, NULL, 'r'},
29 {"sort-directory", no_argument, NULL, 'd'},
30 {"sort-mtime", no_argument, NULL, 'm'},
31 {"sort-icase", no_argument, NULL, 'i'},
32 {"all", no_argument, NULL, 'a'},
33 {"version", no_argument, NULL, 'v'},
34 {"help", no_argument, NULL, 'h'},
35 {NULL, 0, NULL, 0}
36 };
37
38 void options_parse(options_t *options, int argc, char *argv[]) {
39 int c;
40 while ((c = getopt_long(argc, argv, "vhadmr:i:n:t:", longopts, NULL)) != -1) {
41 switch (c) {
42 case 't':
43 options->tty_filename = optarg;
44 break;
45 case 'r':
46 options->run = optarg;
47 break;
48 case 'n': {
49 int n;
50 if (!strcmp(optarg, "max")) {
51 n = INT_MAX;
52 } else if (sscanf(optarg, "%d", &n) != 1 || n < 3) {
53 fprintf(stderr, "Invalid format for --num-files: %s\n", optarg);
54 fprintf(stderr, "Must be integer in range 3..\n");
55 usage(argv[0]);
56 exit(EXIT_FAILURE);
57 }
58 options->num_files = n;
59 } break;
60 case 'd':
61 options->sort_dir = 1;
62 break;
63 case 'm':
64 options->sort_mtime = 1;
65 break;
66 case 'i':
67 options->sort_icase = 1;
68 break;
69 case 'a':
70 options->show_hidden = 1;
71 break;
72 case 'v':
73 printf("%s " VERSION " © 2025 Jul\n", argv[0]);
74 exit(EXIT_SUCCESS);
75 case 'h':
76 default:
77 usage(argv[0]);
78 exit(EXIT_SUCCESS);
79 }
80 }
81
82 if (argc - optind > 1) {
83 usage(argv[0]);
84 exit(EXIT_FAILURE);
85 }
86
87 if (optind < argc) {
88 options->path = argv[optind];
89 }
90 }