1 /* SPDX-License-Identifier: GPL-3.0-only */
20 #include "tfortune.lsg.h"
22 #define TF_SEP "---- "
24 static struct lls_parse_result *lpr, *sublpr;
25 #define CMD_PTR(_cname) lls_cmd(LSG_TFORTUNE_CMD_ ## _cname, tfortune_suite)
26 #define OPT_RESULT(_cname, _oname) (lls_opt_result(\
27 LSG_TFORTUNE_ ## _cname ## _OPT_ ## _oname, \
28 (CMD_PTR(_cname) == CMD_PTR(TFORTUNE))? lpr : sublpr))
29 #define OPT_GIVEN(_cname, _oname) (lls_opt_given(OPT_RESULT(_cname, _oname)))
30 #define OPT_STRING_VAL(_cname, _oname) (lls_string_val(0, \
31 OPT_RESULT(_cname, _oname)))
32 #define OPT_UINT32_VAL(_cname, _oname) (lls_uint32_val(0, \
33 OPT_RESULT(_cname, _oname)))
37 struct tf_user_data {int (*handler)(void);};
38 #define EXPORT_CMD_HANDLER(_cmd) const struct tf_user_data \
39 lsg_tfortune_com_ ## _cmd ## _user_data = { \
40 .handler = com_ ## _cmd \
49 struct map_chunk epi, tags;
52 static int lopsub_error(int lopsub_ret, char **errctx)
54 const char *msg = lls_strerror(-lopsub_ret);
56 ERROR_LOG("%s: %s\n", *errctx, msg);
58 ERROR_LOG("%s\n", msg);
64 /* per epigram context for the tag expression parser */
65 struct epi_properties {
66 const struct map_chunk *chunk; /* only the epigram */
67 struct linhash_table *tagtab;
71 unsigned epi_len(const struct epi_properties *props)
73 return props->chunk->len;
76 char *epi_text(const struct epi_properties *props)
78 const char *txt = props->chunk->base;
79 char *result = malloc(props->chunk->len + 1);
80 memcpy(result, txt, props->chunk->len);
81 result[props->chunk->len] = '\0';
85 bool epi_has_tag(const char *tag, const struct epi_properties *props)
87 return linhash_lookup(tag, props->tagtab);
92 char *saveptr; /* for strtok_r(3) */
96 static struct tag_iter *tag_iter_new(const struct map_chunk *tags)
98 struct tag_iter *titer = xmalloc(sizeof(*titer));
100 titer->str = xmalloc(tags->len + 1);
101 memcpy(titer->str, tags->base, tags->len);
102 titer->str[tags->len] = '\0';
103 titer->token = strtok_r(titer->str, ",", &titer->saveptr);
107 static const char *tag_iter_get(const struct tag_iter *titer)
112 static void tag_iter_next(struct tag_iter *titer)
114 titer->token = strtok_r(NULL, ",", &titer->saveptr);
117 static void tag_iter_free(struct tag_iter *titer)
125 static bool epi_admissible(const struct epigram *epi,
126 const struct txp_context *ast)
130 struct epi_properties props = {
132 .tagtab = linhash_new(3),
135 struct tag_iter *titer;
139 titer = tag_iter_new(&epi->tags);
140 (p = tag_iter_get(titer));
143 struct linhash_item item = {.key = p};
144 linhash_insert(&item, props.tagtab, NULL);
148 admissible = txp_eval_ast(ast, &props);
149 linhash_free(props.tagtab);
150 tag_iter_free(titer);
154 static void print_epigram(const struct epigram *epi, bool print_tags)
156 printf("%.*s", (int)epi->epi.len, epi->epi.base);
158 printf(TF_SEP "%.*s\n", (int)epi->tags.len, epi->tags.base);
161 static void print_admissible_epigrams(const struct epigram *epis,
166 for (n = 0; n < num_epis; n++)
167 print_epigram(epis + n, OPT_GIVEN(PRINT, TAGS));
170 static void print_random_epigram(const struct epigram *epis, unsigned num_epis)
173 const struct epigram *epi;
177 ERROR_LOG("no matching epigram\n");
180 gettimeofday(&tv, NULL);
181 srandom((unsigned)tv.tv_usec);
182 r = (num_epis + 0.0) * (random() / (RAND_MAX + 1.0));
183 assert(r < num_epis);
185 print_epigram(epi, OPT_GIVEN(PRINT, TAGS));
188 static int read_tag_expression(struct iovec *result)
190 const char *tx = OPT_STRING_VAL(PRINT, EXPRESSION);
194 if (strcmp(tx, "-")) {
197 char *home = get_homedir();
198 xasprintf(&filename, "%s/.tfortune/expressions/%s",
202 filename = xstrdup(tx);
203 ret = open(filename, O_RDONLY);
205 ret = -ERRNO_TO_TF_ERROR(errno);
206 ERROR_LOG("could not open %s\n", filename);
214 ret = fd2buf(fd, result);
219 static int tx2ast(const struct iovec *tx, struct txp_context **ast)
224 ret = txp_init(tx, ast, &errmsg);
226 ERROR_LOG("could not parse tag expression: %s\n", errmsg);
241 static bool get_next_epi(struct epi_iter *eiter)
243 const char *epi_start = NULL;
245 for (; eiter->map_num < eiter->num_maps; eiter->map_num++) {
246 struct iovec *iov = eiter->maps + eiter->map_num;
247 const char *buf, *end = iov->iov_base + iov->iov_len;
249 if (!epi_start && eiter->epi.tags.base)
250 epi_start = eiter->epi.tags.base
251 + eiter->epi.tags.len + 1;
253 epi_start = iov->iov_base;
256 const size_t sep_len = strlen(TF_SEP);
257 const char *p, *cr, *tags;
260 cr = memchr(buf, '\n', end - buf);
264 if (p + sep_len >= end)
266 if (strncmp(p, TF_SEP, sep_len) != 0) {
271 cr = memchr(tags, '\n', end - tags);
275 tag_len = end - tags;
276 eiter->epi.epi.base = epi_start;
277 eiter->epi.epi.len = p - epi_start;
278 eiter->epi.tags.base = tags;
279 eiter->epi.tags.len = tag_len;
284 eiter->epi.epi.base = NULL;
285 eiter->epi.epi.len = 0;
286 eiter->epi.tags.base = NULL;
287 eiter->epi.tags.len = 0;
291 static char *get_basedir(void)
293 char *home, *basedir;
294 if (OPT_GIVEN(TFORTUNE, BASEDIR))
295 return xstrdup(OPT_STRING_VAL(TFORTUNE, BASEDIR));
296 home = get_homedir();
297 xasprintf(&basedir, "%s/.tfortune", home);
302 static char *get_epidir(void)
304 char *basedir, *epidir;
307 basedir = get_basedir();
308 xasprintf(&epidir, "%s/epigrams", basedir);
310 if (!OPT_GIVEN(TFORTUNE, BASEDIR) && stat(epidir, &s) < 0) {
312 epidir = xstrdup(DATADIR "/tfortunes/epigrams");
313 INFO_LOG("falling back to system-wide epidir %s\n", epidir);
318 static char *get_xdir(void)
320 char *basedir = get_basedir(), *xdir;
321 xasprintf(&xdir, "%s/expressions", basedir);
326 static struct epi_iter *epi_iter_new(void)
328 struct epi_iter *eiter = xmalloc(sizeof(*eiter));
329 unsigned num_inputs = lls_num_inputs(sublpr);
331 if (num_inputs == 0) {
332 struct regfile_iter *riter;
334 char *epidir = get_epidir();
336 regfile_iter_new(epidir, &riter);
341 regfile_iter_map(riter, &iov);
342 regfile_iter_next(riter)
345 eiter->maps = xrealloc(eiter->maps,
346 eiter->num_maps * sizeof(*eiter->maps));
347 eiter->maps[eiter->num_maps - 1] = iov;
349 regfile_iter_free(riter);
352 eiter->maps = xmalloc(num_inputs * sizeof(*eiter->maps));
353 for (n = 0; n < num_inputs; n++)
354 mmap_file(lls_input(n, sublpr), eiter->maps + n);
355 eiter->num_maps = num_inputs;
358 eiter->epi.epi.base = NULL;
359 eiter->epi.epi.len = 0;
360 eiter->epi.tags.base = NULL;
361 eiter->epi.tags.len = 0;
367 static const struct epigram *epi_iter_get(const struct epi_iter *eiter)
369 return (eiter->epi.epi.base && eiter->epi.tags.base)?
373 static unsigned epi_iter_num_maps(const struct epi_iter *eiter)
375 return eiter->num_maps;
378 static unsigned epi_iter_num_epis(const struct epi_iter *eiter)
380 return eiter->num_epis;
383 static void epi_iter_next(struct epi_iter *eiter)
388 static void epi_iter_free(struct epi_iter *eiter)
394 for (n = 0; n < eiter->num_maps; n++)
395 munmap(eiter->maps[n].iov_base, eiter->maps[n].iov_len);
400 static int com_print(void)
403 struct epigram *epis = NULL;
404 unsigned epis_sz = 0, nae = 0; /* number of admissible epis */
406 struct txp_context *ast;
407 struct epi_iter *eiter;
408 const struct epigram *epi;
410 ret = read_tag_expression(&tx);
413 ret = tx2ast(&tx, &ast);
417 eiter = epi_iter_new();
418 (epi = epi_iter_get(eiter));
421 if (!epi_admissible(epi, ast))
423 if (nae >= epis_sz) {
424 epis_sz = 2 * epis_sz + 1;
425 epis = xrealloc(epis, epis_sz * sizeof(*epis));
429 if (OPT_GIVEN(PRINT, ALL))
430 print_admissible_epigrams(epis, nae);
432 print_random_epigram(epis, nae);
433 epi_iter_free(eiter);
441 EXPORT_CMD_HANDLER(print);
443 static char *get_editor(void)
445 char *val = getenv("TFORTUNE_EDITOR");
449 val = getenv("EDITOR");
452 return xstrdup("vi");
455 static void open_editor(const char *dir)
460 unsigned n, num_inputs = lls_num_inputs(sublpr);
462 if ((pid = fork()) < 0) {
463 EMERG_LOG("fork error: %s\n", strerror(errno));
466 if (pid) { /* parent */
470 editor = get_editor();
471 argv = xmalloc((num_inputs + 2) * sizeof(*argv));
473 for (n = 0; n < num_inputs; n++)
474 xasprintf(&argv[n + 1], "%s/%s", dir, lls_input(n, sublpr));
475 argv[num_inputs + 1] = NULL;
476 execvp(editor, argv);
477 EMERG_LOG("execvp error: %s\n", strerror(errno));
481 static int create_dir(const char *path)
485 ret = mkdir(path, 0777); /* rely on umask */
489 ERROR_LOG("could not create %s\n", path);
490 return -ERRNO_TO_TF_ERROR(errno);
492 NOTICE_LOG("created directory %s\n", path);
496 static int create_basedir(void)
501 basedir = get_basedir();
502 ret = create_dir(basedir);
507 static int generic_edit(const char *dir)
511 bool basedir_given = OPT_GIVEN(TFORTUNE, BASEDIR);
513 ret = lls_check_arg_count(sublpr, 1, INT_MAX, &errctx);
515 ret = lopsub_error(ret, &errctx);
518 if (!basedir_given) {
519 ret = create_basedir();
522 ret = create_dir(dir);
531 static int com_ede(void)
534 char *epidir = get_epidir();
535 ret = generic_edit(epidir);
539 EXPORT_CMD_HANDLER(ede);
541 static int com_edx(void)
544 char *xdir = get_xdir();
545 ret = generic_edit(xdir);
549 EXPORT_CMD_HANDLER(edx);
551 static int item_alpha_compare(const struct linhash_item **i1,
552 const struct linhash_item **i2)
554 return strcmp((*i1)->key, (*i2)->key);
557 static int item_num_compare(const struct linhash_item **i1,
558 const struct linhash_item **i2)
560 long unsigned v1 = (long unsigned)(*i1)->object;
561 long unsigned v2 = (long unsigned)(*i2)->object;
563 return v1 < v2? -1 : (v1 == v2? 0 : 1);
575 static void make_dentry(const char *name, const struct stat *stat,
578 mode_t m = stat->st_mode;
580 struct passwd *pwentry;
582 sprintf(d->mode, "----------");
589 else if ((S_ISBLK(m)))
593 else if (S_ISFIFO(m))
595 else if ((S_ISSOCK(m)))
609 } else if (m & S_ISUID)
621 } else if (m & S_ISGID)
633 } else if (m & S_ISVTX)
636 d->nlink = stat->st_nlink;
638 pwentry = getpwuid(stat->st_uid);
639 if (pwentry && pwentry->pw_name)
640 d->user = xstrdup(pwentry->pw_name);
642 xasprintf(&d->user, "%u", stat->st_uid);
644 g = getgrgid(stat->st_gid);
646 d->group = xstrdup(g->gr_name);
648 xasprintf(&d->group, "%u", stat->st_gid);
649 d->size = stat->st_size;
650 d->mtime = stat->st_mtime;
651 d->name = xstrdup(name);
654 static int num_digits(uint64_t x)
666 enum var_length_dentry_fields {
674 static void update_field_field_widths(int field_widths[NUM_VLDF],
675 const struct dentry *d)
679 w = field_widths + VLDF_NLINKS;
680 n = num_digits(d->nlink);
683 w = field_widths + VLDF_USER;
687 w = field_widths + VLDF_GROUP;
688 n = strlen(d->group);
691 w = field_widths + VLDF_SIZE;
692 n = num_digits(d->size);
696 static void format_time(uint64_t seconds, uint64_t now, struct iovec *result)
699 const uint64_t m = 6 * 30 * 24 * 3600; /* six months */
702 tm = localtime((time_t *)&seconds);
705 if (seconds > now - m && seconds < now + m) {
706 nbytes = strftime(result->iov_base, result->iov_len,
710 nbytes = strftime(result->iov_base, result->iov_len,
716 static int list_directory(const char *dir, bool long_listing)
718 struct regfile_iter *riter;
719 const char *basename;
720 int ret, field_widths[NUM_VLDF] = {0};
721 struct dentry *dentries = NULL;
722 unsigned n, num_dentries = 0, dentries_size = 0;
726 regfile_iter_new(dir, &riter);
727 (basename = regfile_iter_basename(riter));
728 regfile_iter_next(riter)
730 const struct stat *stat;
731 struct dentry *dentry;
733 printf("%s\n", basename);
737 if (num_dentries > dentries_size) {
738 dentries_size = 2 * dentries_size + 1;
739 dentries = xrealloc(dentries,
740 dentries_size * sizeof(*dentries));
742 dentry = dentries + num_dentries - 1;
743 stat = regfile_iter_stat(riter);
744 make_dentry(basename, stat, dentry);
745 update_field_field_widths(field_widths, dentry);
747 regfile_iter_free(riter);
750 ret = clock_gettime(CLOCK_REALTIME, &now);
752 for (n = 0; n < num_dentries; n++) {
753 struct dentry *d = dentries + n;
755 struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)};
757 format_time(d->mtime, now.tv_sec, &iov);
758 printf("%s %*lu %*s %*s %*" PRIu64 " %s %s\n",
760 field_widths[VLDF_NLINKS], (long unsigned)d->nlink,
761 field_widths[VLDF_USER], d->user,
762 field_widths[VLDF_GROUP], d->group,
763 field_widths[VLDF_SIZE], (uint64_t)d->size,
775 static int com_lse(void)
778 char *dir = get_epidir();
780 ret = list_directory(dir, OPT_GIVEN(LSE, LONG));
784 EXPORT_CMD_HANDLER(lse);
786 static int com_lsx(void)
789 char *dir = get_xdir();
791 ret = list_directory(dir, OPT_GIVEN(LSE, LONG));
795 EXPORT_CMD_HANDLER(lsx);
797 static struct linhash_table *hash_tags(unsigned *num_epi_files,
800 struct linhash_table *tagtab = linhash_new(3);
801 struct epi_iter *eiter;
802 const struct epigram *epi;
805 eiter = epi_iter_new();
806 (epi = epi_iter_get(eiter));
809 struct tag_iter *titer;
812 titer = tag_iter_new(&epi->tags);
813 (tag = tag_iter_get(titer));
816 struct linhash_item item = {
818 .object = (void *)1LU
821 if (linhash_insert(&item, tagtab, &object) < 0) {
822 long unsigned val = (long unsigned)*object;
824 *object = (void *)val;
825 free((char *)item.key);
828 tag_iter_free(titer);
831 *num_epi_files = epi_iter_num_maps(eiter);
833 *num_epis = epi_iter_num_epis(eiter);
834 epi_iter_free(eiter);
838 static int com_lst(void)
840 struct linhash_table *tagtab;
841 struct linhash_iterator *liter;
842 struct linhash_item *itemp;
843 linhash_comparator *comp = OPT_GIVEN(LST, SORT_BY_COUNT)?
844 item_num_compare : item_alpha_compare;
845 bool reverse = OPT_GIVEN(LST, REVERSE);
847 tagtab = hash_tags(NULL, NULL);
849 liter = linhash_iterator_new(tagtab, comp, reverse);
850 (itemp = linhash_iterator_item(liter));
851 linhash_iterator_next(liter)
853 if (OPT_GIVEN(LST, LONG))
854 printf("%lu\t%s\n", (long unsigned)itemp->object,
857 printf("%s\n", itemp->key);
858 free((char *)itemp->key);
860 linhash_iterator_free(liter);
861 linhash_free(tagtab);
864 EXPORT_CMD_HANDLER(lst);
866 static int com_stats(void)
868 struct linhash_table *tagtab;
869 struct linhash_iterator *liter;
870 struct linhash_item *itemp;
871 unsigned num_epi_files, num_epis, num_unique_tags, num_x = 0;
872 long unsigned num_tags = 0;
874 struct regfile_iter *riter;
876 tagtab = hash_tags(&num_epi_files, &num_epis);
878 liter = linhash_iterator_new(tagtab, NULL, false);
879 (itemp = linhash_iterator_item(liter));
880 linhash_iterator_next(liter)
882 free((char *)itemp->key);
883 num_tags += (long unsigned)itemp->object;
885 num_unique_tags = linhash_num_items(tagtab);
886 linhash_iterator_free(liter);
889 regfile_iter_new(xdir, &riter);
890 regfile_iter_basename(riter);
891 regfile_iter_next(riter)
894 regfile_iter_free(riter);
896 printf("number of tag expressions.......... %5u\n", num_x);
897 printf("number of epigram files............ %5u\n", num_epi_files);
898 printf("number of epigrams................. %5u\n", num_epis);
899 printf("number of tags..................... %5lu\n", num_tags);
900 printf("number of unique tags.............. %5u\n", num_unique_tags);
901 printf("average number of epigrams per file %8.02f\n",
902 num_epi_files > 0? (float)num_epis / num_epi_files : 0);
903 printf("average number of tags per epigram. %8.02f\n", num_epis > 0?
904 (float)num_tags / num_epis : 0);
905 printf("average number of tag recurrence... %8.02f\n", num_unique_tags > 0?
906 (float)num_tags / num_unique_tags : 0);
907 if (OPT_GIVEN(STATS, VERBOSE)) {
908 char *lh_stats = linhash_statistics(tagtab);
909 printf("\nlinear hashing statistics:\n%s\n", lh_stats);
912 linhash_free(tagtab);
915 EXPORT_CMD_HANDLER(stats);
917 #define LSG_TFORTUNE_CMD(_name) #_name
918 static const char * const subcommand_names[] = {LSG_TFORTUNE_SUBCOMMANDS NULL};
919 #undef LSG_TFORTUNE_CMD
921 static void show_subcommand_summary(bool verbose)
925 printf("Available subcommands:\n");
927 const struct lls_command *cmd;
928 for (i = 1; (cmd = lls_cmd(i, tfortune_suite)); i++) {
929 const char *purpose = lls_purpose(cmd);
930 const char *name = lls_command_name(cmd);
931 printf("%-11s%s\n", name, purpose);
936 for (i = 0; i < LSG_NUM_TFORTUNE_SUBCOMMANDS; i++) {
943 n += printf("%s", subcommand_names[i]);
949 static int com_help(void)
954 const struct lls_command *cmd;
956 ret = lls_check_arg_count(sublpr, 0, 1, &errctx);
958 return lopsub_error(ret, &errctx);
959 if (lls_num_inputs(sublpr) == 0) {
960 show_subcommand_summary(OPT_GIVEN(HELP, LONG));
963 arg = lls_input(0, sublpr);
964 ret = lls_lookup_subcmd(arg, tfortune_suite, &errctx);
966 return lopsub_error(ret, &errctx);
967 cmd = lls_cmd(ret, tfortune_suite);
968 if (OPT_GIVEN(HELP, LONG))
969 help = lls_long_help(cmd);
971 help = lls_short_help(cmd);
972 printf("%s\n", help);
976 EXPORT_CMD_HANDLER(help);
978 const char *GET_VERSION(void);
979 static void handle_help_and_version(void)
983 const struct lls_command *cmd;
985 if (OPT_GIVEN(TFORTUNE, VERSION)) {
986 printf(PACKAGE " %s\n"
987 "Copyright (C) " COPYRIGHT_YEAR " " AUTHOR ".\n"
988 "License: " LICENSE ": <" LICENSE_URL ">.\n"
989 "This is free software: you are free to change and redistribute it.\n"
990 "There is NO WARRANTY, to the extent permitted by law.\n"
992 "Web page: " PACKAGE_HOMEPAGE "\n"
993 "Clone URL: " CLONE_URL "\n"
994 "Gitweb: " GITWEB_URL "\n"
995 "Author's Home Page: " HOME_URL "\n"
996 "Send feedback to: " AUTHOR " <" EMAIL ">\n"
1002 cmd = CMD_PTR(TFORTUNE);
1003 if (OPT_GIVEN(TFORTUNE, DETAILED_HELP))
1004 help = lls_long_help(cmd);
1005 else if (OPT_GIVEN(TFORTUNE, HELP))
1006 help = lls_short_help(cmd);
1009 printf("%s\n", help);
1011 if (OPT_GIVEN(TFORTUNE, DETAILED_HELP))
1012 for (i = 1; (cmd = lls_cmd(i, tfortune_suite)); i++) {
1013 help = lls_short_help(cmd);
1014 printf("%s\n---\n", help);
1018 show_subcommand_summary(true /* verbose */);
1024 WT_DOUBLE_DASH, /* -- */
1025 WT_SHORT_OPT_WITH_ARG, /* -l */
1026 WT_SHORT_OPT_WITHOUT_ARG, /* -V, -abc=d */
1027 WT_LONG_OPT_WITH_ARG, /* --loglevel */
1028 WT_LONG_OPT_WITHOUT_ARG, /* --foo=bar --help */
1034 static bool is_short_opt(const char *word)
1040 if (word[1] == '\0')
1045 static bool is_long_opt(const char *word)
1051 if (word[2] == '\0')
1056 /* whether the next word will be an arg to this short opt */
1057 static int short_opt_needs_arg(const char *word,
1058 const char * const *short_opts)
1062 if (strchr(word, '='))
1065 for (n = 0; short_opts[n]; n++) {
1066 const char *opt = short_opts[n];
1067 if (word[len - 1] != opt[1])
1077 /* whether the next word will be an arg to this long opt */
1078 static int long_opt_needs_arg(const char *word,
1079 const char * const *long_opts)
1083 if (strchr(word, '='))
1085 for (n = 0; long_opts[n]; n++) {
1086 const char *opt = long_opts[n];
1087 size_t len = strlen(opt);
1089 if (opt[len - 1] == '=')
1091 if (strncmp(word + 2, opt + 2, len - 2))
1093 if (opt[len] == '=')
1101 static bool get_word_types(unsigned cword, unsigned arg0,
1102 const char * const *short_opts, const char * const *long_opts,
1103 enum tf_word_type *result)
1107 bool have_dd = false;
1110 /* index zero is always the command name */
1111 assert(cword > arg0);
1112 result[arg0] = WT_COMMAND_NAME;
1113 for (n = arg0 + 1; n < cword; n++) {
1114 enum tf_word_type prev_type = result[n - 1];
1117 result[n] = WT_NON_OPTION_ARG;
1120 if (prev_type == WT_SHORT_OPT_WITH_ARG) {
1121 result[n] = WT_OPTION_ARG;
1124 if (prev_type == WT_LONG_OPT_WITH_ARG) {
1125 result[n] = WT_OPTION_ARG;
1128 word = lls_input(n, sublpr);
1129 if (strcmp(word, "--") == 0) {
1130 result[n] = WT_DOUBLE_DASH;
1134 if (is_short_opt(word)) {
1135 ret = short_opt_needs_arg(word, short_opts);
1139 result[n] = WT_SHORT_OPT_WITH_ARG;
1141 result[n] = WT_SHORT_OPT_WITHOUT_ARG;
1144 if (is_long_opt(word)) {
1145 ret = long_opt_needs_arg(word, long_opts);
1149 result[n] = WT_LONG_OPT_WITH_ARG;
1151 result[n] = WT_LONG_OPT_WITHOUT_ARG;
1154 result[n] = WT_NON_OPTION_ARG;
1158 for (; n <= cword; n++)
1159 result[n] = WT_DUNNO;
1163 #define DUMMY_COMPLETER(_name) static char **complete_ ## _name( \
1164 __attribute__ ((unused)) uint32_t cword, \
1165 __attribute__ ((unused)) unsigned arg0, \
1166 __attribute__ ((unused)) bool have_dd \
1169 DUMMY_COMPLETER(tfortune)
1170 DUMMY_COMPLETER(compgen)
1171 DUMMY_COMPLETER(completer)
1173 static const char * const supercmd_opts[] = {LSG_TFORTUNE_TFORTUNE_OPTS, NULL};
1175 static void print_zero_terminated_list(const char * const *list)
1177 const char * const *c;
1178 for (c = list; *c; c++)
1179 printf("%s%c", *c, '\0');
1182 static void print_option_list(const char * const *opts)
1184 const char * const *c;
1186 for (c = opts; *c; c++) {
1187 int len = strlen(*c);
1189 if ((*c)[len - 1] == '=')
1191 printf("%.*s%c", len, *c, '\0');
1195 static void activate_dirname_completion(void)
1198 printf("-o dirnames%c", '\0');
1201 static void complete_loglevels(void)
1204 const struct lls_option *opt = lls_opt(LSG_TFORTUNE_TFORTUNE_OPT_LOGLEVEL,
1207 for (n = 0; n < LSG_NUM_TFORTUNE_TFORTUNE_LOGLEVEL_VALUES; n++) {
1208 const char *v = lls_enum_string_val(n, opt);
1209 printf("%s%c", v, '\0');
1213 static char **complete_dentries(const char *dir)
1216 struct regfile_iter *riter;
1218 char **result = NULL;
1220 regfile_iter_new(dir, &riter);
1223 (bn = regfile_iter_basename(riter));
1224 regfile_iter_next(riter), n++
1226 result = xrealloc(result, (n + 2) * sizeof(*result));
1227 result[n] = xstrdup(bn);
1228 result[n + 1] = NULL;
1233 static char **complete_ede(__attribute__ ((unused)) uint32_t cword,
1234 __attribute__ ((unused)) unsigned arg0,
1235 __attribute__ ((unused)) bool have_dd)
1237 char **result, *epidir = get_epidir();
1239 result = complete_dentries(epidir);
1244 static char **complete_edx(__attribute__ ((unused)) uint32_t cword,
1245 __attribute__ ((unused)) unsigned arg0,
1246 __attribute__ ((unused)) bool have_dd)
1248 char **result, *xdir = get_xdir();
1250 result = complete_dentries(xdir);
1255 static char **complete_std_opts(bool have_dd, const char * const *opts)
1258 print_option_list(opts);
1260 print_option_list(supercmd_opts);
1264 static char **complete_stats(__attribute__ ((unused)) uint32_t cword,
1265 __attribute__ ((unused)) unsigned arg0, bool have_dd)
1267 const char * const opts[] = {LSG_TFORTUNE_STATS_OPTS, NULL};
1268 return complete_std_opts(have_dd, opts);
1271 static char **complete_lse(__attribute__ ((unused)) uint32_t cword,
1272 __attribute__ ((unused)) unsigned arg0, bool have_dd)
1274 const char * const opts[] = {LSG_TFORTUNE_LSE_OPTS, NULL};
1275 return complete_std_opts(have_dd, opts);
1278 static char **complete_lst(__attribute__ ((unused)) uint32_t cword,
1279 __attribute__ ((unused)) unsigned arg0, bool have_dd)
1281 const char * const opts[] = {LSG_TFORTUNE_LST_OPTS, NULL};
1282 return complete_std_opts(have_dd, opts);
1285 static char **complete_lsx(__attribute__ ((unused)) uint32_t cword,
1286 __attribute__ ((unused)) unsigned arg0, bool have_dd)
1288 const char * const opts[] = {LSG_TFORTUNE_LSX_OPTS, NULL};
1289 return complete_std_opts(have_dd, opts);
1292 static char **complete_help(__attribute__ ((unused)) uint32_t cword,
1293 __attribute__ ((unused)) unsigned arg0, bool have_dd)
1295 const char * const opts[] = {LSG_TFORTUNE_HELP_OPTS, NULL};
1298 print_option_list(supercmd_opts);
1300 print_option_list(opts);
1301 print_zero_terminated_list(subcommand_names);
1305 static char **complete_print(uint32_t cword, unsigned arg0, bool have_dd)
1307 const char * const short_opts[] = {LSG_TFORTUNE_PRINT_SHORT_OPTS, NULL};
1308 const char * const long_opts[] = {LSG_TFORTUNE_PRINT_LONG_OPTS, NULL};
1309 const char * const opts[] = {LSG_TFORTUNE_PRINT_OPTS, NULL};
1310 enum tf_word_type *word_types, prev_type;
1312 char **result, *xdir;
1314 word_types = xmalloc(cword * sizeof(*word_types));
1315 get_word_types(cword, arg0, short_opts, long_opts, word_types);
1316 prev = lls_input(cword - 1, sublpr);
1317 prev_type = word_types[cword - 1];
1319 switch (prev_type) {
1320 case WT_COMMAND_NAME:
1321 case WT_SHORT_OPT_WITHOUT_ARG:
1323 case WT_LONG_OPT_WITHOUT_ARG:
1324 case WT_DOUBLE_DASH:
1326 print_option_list(supercmd_opts);
1328 print_option_list(opts);
1330 case WT_SHORT_OPT_WITH_ARG:
1331 if (strcmp(prev, "-x") == 0)
1332 goto complete_expression;
1334 case WT_LONG_OPT_WITH_ARG:
1335 if (strcmp(prev, "--expression") == 0)
1336 goto complete_expression;
1341 complete_expression:
1343 result = complete_dentries(xdir);
1348 typedef char **(*completer)(uint32_t cword, unsigned arg0, bool have_dd);
1350 #define LSG_TFORTUNE_CMD(_name) complete_ ## _name
1351 static const completer completers[] = {LSG_TFORTUNE_COMMANDS};
1352 #undef LSG_TFORTUNE_CMD
1354 static int call_subcmd_completer(unsigned cmd_num, int arg0, uint32_t cword,
1357 char **c, **candidates = completers[cmd_num](cword, arg0, have_dd);
1361 for (c = candidates; *c; c++) {
1362 printf("%s%c", *c, '\0');
1369 static bool need_subcommand_completer(uint32_t cword, unsigned subcmd_idx,
1370 const enum tf_word_type *word_types, bool have_dd)
1372 enum tf_word_type prev_type;
1375 if (subcmd_idx == 0)
1379 prev_type = word_types[cword - 1];
1380 assert(prev_type != WT_COMMAND_NAME);
1381 switch (prev_type) {
1382 case WT_SHORT_OPT_WITH_ARG:
1383 case WT_LONG_OPT_WITH_ARG:
1389 word = lls_input(cword, sublpr);
1390 if (is_short_opt(word))
1392 if (is_long_opt(word))
1397 static int com_compgen(void)
1400 uint32_t cword = OPT_UINT32_VAL(COMPGEN, CURRENT_WORD_INDEX);
1402 unsigned subcmd_idx;
1403 const char *word, *prev;
1404 const char * const short_opts[] = {LSG_TFORTUNE_TFORTUNE_SHORT_OPTS, NULL};
1405 const char * const long_opts[] = {LSG_TFORTUNE_TFORTUNE_LONG_OPTS, NULL};
1406 enum tf_word_type *word_types, prev_type;
1409 if (cword == 0 || cword > lls_num_inputs(sublpr)) {
1410 ERROR_LOG("current word index == %u!?\n", cword);
1411 return -ERRNO_TO_TF_ERROR(EINVAL);
1413 word_types = xmalloc(cword * sizeof(*word_types));
1414 have_dd = get_word_types(cword, 0, short_opts, long_opts, word_types);
1416 * Locate the subcommand argument, if present. It is always the first
1417 * non-option argument.
1420 for (n = 1; n < cword; n++) {
1421 if (word_types[n] != WT_NON_OPTION_ARG)
1426 if (need_subcommand_completer(cword, subcmd_idx, word_types, have_dd)) {
1428 word = lls_input(subcmd_idx, sublpr);
1429 ret = lls_lookup_subcmd(word, tfortune_suite, NULL);
1430 if (ret < 0) /* invalid subcommand */
1432 return call_subcmd_completer(ret, subcmd_idx, cword, have_dd);
1435 prev_type = word_types[cword - 1];
1436 prev = lls_input(cword - 1, sublpr);
1438 switch (prev_type) {
1441 case WT_COMMAND_NAME:
1442 case WT_SHORT_OPT_WITHOUT_ARG:
1444 case WT_NON_OPTION_ARG:
1445 case WT_LONG_OPT_WITHOUT_ARG:
1447 print_option_list(supercmd_opts);
1449 case WT_DOUBLE_DASH:
1450 print_zero_terminated_list(subcommand_names);
1452 case WT_SHORT_OPT_WITH_ARG:
1453 if (strcmp(prev, "-b") == 0) {
1454 activate_dirname_completion();
1457 if (strcmp(prev, "-l") == 0) {
1458 complete_loglevels();
1462 case WT_LONG_OPT_WITH_ARG:
1463 if (strcmp(prev, "--basedir") == 0) {
1464 activate_dirname_completion();
1467 if (strcmp(prev, "--loglevel") == 0) {
1468 complete_loglevels();
1475 EXPORT_CMD_HANDLER(compgen);
1477 static int com_completer(void)
1482 "local -i i offset=${TF_OFFSET:-0} \n"
1483 "local w compopts= have_empty=false\n"
1484 "local cur=\"${COMP_WORDS[$COMP_CWORD]}\" \n"
1488 "while read -d '' w; do \n"
1489 "[[ -z \"$w\" ]] && { have_empty=true; continue; }\n"
1490 "if [[ $have_empty == true ]]; then\n"
1493 "[[ \"$w\" != \"$cur\"* ]] && continue \n"
1494 "COMPREPLY[i]=\"$w\" \n"
1497 "done < <(tfortune -- compgen --current-word-index \\\n"
1498 "\"$((COMP_CWORD + offset))\" -- $TF_EXTRA \"${COMP_WORDS[@]}\")\n"
1500 "complete -F _tfortune tfortune \n"
1502 if (OPT_GIVEN(COMPLETER, ALIAS)) {
1503 const char *ali = OPT_STRING_VAL(PRINT, EXPRESSION);
1504 printf("alias %s=\"tfortune --\"\n", ali);
1506 "COMP_WORDS[0]='--'\n"
1509 "_tfortune \"$@\" \n"
1510 "unset TF_EXTRA TF_OFFSET\n"
1514 printf("complete -F _%s %s \n", ali, ali);
1518 EXPORT_CMD_HANDLER(completer);
1520 int main(int argc, char **argv)
1524 const struct lls_command *cmd = CMD_PTR(TFORTUNE), *subcmd;
1525 const struct tf_user_data *ud;
1526 unsigned num_inputs;
1528 ret = lls_parse(argc, argv, cmd, &lpr, &errctx);
1530 lopsub_error(ret, &errctx);
1533 loglevel_arg_val = OPT_UINT32_VAL(TFORTUNE, LOGLEVEL);
1534 handle_help_and_version();
1535 num_inputs = lls_num_inputs(lpr);
1536 if (num_inputs == 0) {
1537 show_subcommand_summary(true /* verbose */);
1541 ret = lls_lookup_subcmd(argv[argc - num_inputs], tfortune_suite, &errctx);
1543 ret = lopsub_error(ret, &errctx);
1546 subcmd = lls_cmd(ret, tfortune_suite);
1547 ret = lls_parse(num_inputs, argv + argc - num_inputs, subcmd,
1550 ret = lopsub_error(ret, &errctx);
1553 ud = lls_user_data(subcmd);
1554 ret = ud->handler();
1555 lls_free_parse_result(sublpr, subcmd);
1557 ERROR_LOG("%s\n", tf_strerror(-ret));
1559 lls_free_parse_result(lpr, cmd);
1560 exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);