2 * Copyright (c) 2002 John Rochester
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer,
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * $FreeBSD: src/usr.bin/makewhatis/makewhatis.c,v 1.9 2002/09/04 23:29:04 dwmalone Exp $
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <sys/queue.h>
42 #include <stringlist.h>
46 #define DEFAULT_MANPATH "/usr/share/man"
47 #define LINE_ALLOC 4096
49 static char blank[] = "";
52 * Information collected about each man page in a section.
63 * An entry kept for each visited directory.
68 SLIST_ENTRY(visited_dir) next;
75 char * content; /* the start of the buffer */
76 char * end; /* just past the end of the content */
77 char * last; /* the last allocated character */
81 * Removes the last amount characters from the sbuf.
83 #define sbuf_retract(sbuf, amount) \
84 ((sbuf)->end -= (amount))
86 * Returns the length of the sbuf content.
88 #define sbuf_length(sbuf) \
89 ((sbuf)->end - (sbuf)->content)
91 typedef char *edited_copy(char *from, char *to, int length);
93 static int append; /* -a flag: append to existing whatis */
94 static int verbose; /* -v flag: be verbose with warnings */
95 static int indent = 24; /* -i option: description indentation */
96 static const char *whatis_name="whatis";/* -n option: the name */
97 static char *common_output; /* -o option: the single output file */
98 static char *locale; /* user's locale if -L is used */
99 static char *lang_locale; /* short form of locale */
100 static const char *machine;
102 static int exit_code; /* exit code to use when finished */
103 static SLIST_HEAD(, visited_dir) visited_dirs =
104 SLIST_HEAD_INITIALIZER(visited_dirs);
107 * While the whatis line is being formed, it is stored in whatis_proto.
108 * When finished, it is reformatted into whatis_final and then appended
111 static struct sbuf *whatis_proto;
112 static struct sbuf *whatis_final;
113 static StringList *whatis_lines; /* collected output lines */
115 static char tmp_file[MAXPATHLEN]; /* path of temporary file, if any */
117 /* A set of possible names for the NAME man page section */
118 static const char *name_section_titles[] = {
119 "NAME", "Name", "NAMN", "BEZEICHNUNG", "\xcc\xbe\xbe\xce",
120 "\xee\xe1\xfa\xf7\xe1\xee\xe9\xe5", NULL
123 /* A subset of the mdoc(7) commands to ignore */
124 static char mdoc_commands[] = "ArDvErEvFlLiNmPa";
127 * Frees a struct page_info and its content.
130 free_page_info(struct page_info *info)
132 free(info->filename);
139 * Allocates and fills in a new struct page_info given the
140 * name of the man section directory and the dirent of the file.
141 * If the file is not a man page, returns NULL.
143 static struct page_info *
144 new_page_info(char *dir, struct dirent *dirent)
146 struct page_info *info;
151 info = malloc(sizeof(struct page_info));
154 basename_length = strlen(dirent->d_name);
155 suffix = &dirent->d_name[basename_length];
156 asprintf(&info->filename, "%s/%s", dir, dirent->d_name);
157 if ((info->gzipped = basename_length >= 4 &&
158 strcmp(&dirent->d_name[basename_length - 3], ".gz") == 0)) {
163 if (--suffix == dirent->d_name || !isalnum(*suffix)) {
167 warnx("%s: invalid man page name",
169 free(info->filename);
175 info->name = strdup(dirent->d_name);
176 info->suffix = strdup(suffix);
177 if (stat(info->filename, &st) < 0) {
178 warn("%s", info->filename);
179 free_page_info(info);
182 if (!S_ISREG(st.st_mode)) {
183 if (verbose && !S_ISDIR(st.st_mode))
184 warnx("%s: not a regular file", info->filename);
185 free_page_info(info);
188 info->inode = st.st_ino;
193 * Reset an sbuf's length to 0.
196 sbuf_clear(struct sbuf *sbuf)
198 sbuf->end = sbuf->content;
202 * Allocate a new sbuf.
207 struct sbuf *sbuf = (struct sbuf *) malloc(sizeof(struct sbuf));
208 sbuf->content = malloc(LINE_ALLOC);
209 sbuf->last = sbuf->content + LINE_ALLOC - 1;
215 * Ensure that there is enough room in the sbuf for nchars more characters.
218 sbuf_need(struct sbuf *sbuf, int nchars)
221 size_t size, cntsize;
223 /* double the size of the allocation until the buffer is big enough */
224 while (sbuf->end + nchars > sbuf->last) {
225 size = sbuf->last + 1 - sbuf->content;
227 cntsize = sbuf->end - sbuf->content;
229 new_content = malloc(size);
230 memcpy(new_content, sbuf->content, cntsize);
232 sbuf->content = new_content;
233 sbuf->end = new_content + cntsize;
234 sbuf->last = new_content + size - 1;
239 * Appends a string of a given length to the sbuf.
242 sbuf_append(struct sbuf *sbuf, const char *text, int length)
245 sbuf_need(sbuf, length);
246 memcpy(sbuf->end, text, length);
252 * Appends a null-terminated string to the sbuf.
255 sbuf_append_str(struct sbuf *sbuf, char *text)
257 sbuf_append(sbuf, text, strlen(text));
261 * Appends an edited null-terminated string to the sbuf.
264 sbuf_append_edited(struct sbuf *sbuf, char *text, edited_copy copy)
266 int length = strlen(text);
268 sbuf_need(sbuf, length);
269 sbuf->end = copy(text, sbuf->end, length);
274 * Strips any of a set of chars from the end of the sbuf.
277 sbuf_strip(struct sbuf *sbuf, const char *set)
279 while (sbuf->end > sbuf->content && strchr(set, sbuf->end[-1]) != NULL)
284 * Returns the null-terminated string built by the sbuf.
287 sbuf_content(struct sbuf *sbuf)
290 return(sbuf->content);
294 * Returns true if no man page exists in the directory with
295 * any of the names in the StringList.
298 no_page_exists(char *dir, StringList *names, char *suffix)
300 char path[MAXPATHLEN];
303 for (i = 0; i < names->sl_cur; i++) {
304 snprintf(path, sizeof path, "%s/%s.%s.gz", dir, names->sl_str[i], suffix);
305 if (access(path, F_OK) < 0) {
306 path[strlen(path) - 3] = '\0';
307 if (access(path, F_OK) < 0)
316 trap_signal(int sig __unused)
318 if (tmp_file[0] != '\0')
324 * Attempts to open an output file. Returns NULL if unsuccessful.
327 open_output(char *name)
331 whatis_lines = sl_init();
333 char line[LINE_ALLOC];
335 output = fopen(name, "r");
336 if (output == NULL) {
341 while (fgets(line, sizeof line, output) != NULL) {
342 line[strlen(line) - 1] = '\0';
343 sl_add(whatis_lines, strdup(line));
346 if (common_output == NULL) {
347 snprintf(tmp_file, sizeof tmp_file, "%s.tmp", name);
350 output = fopen(name, "w");
351 if (output == NULL) {
360 linesort(const void *a, const void *b)
362 return(strcmp((*(const char * const *)a), (*(const char * const *)b)));
366 * Writes the unique sorted lines to the output file.
369 finish_output(FILE *output, char *name)
374 qsort(whatis_lines->sl_str, whatis_lines->sl_cur, sizeof(char *),
376 for (i = 0; i < whatis_lines->sl_cur; i++) {
377 char *line = whatis_lines->sl_str[i];
378 if (i > 0 && strcmp(line, prev) == 0)
385 sl_free(whatis_lines, 1);
386 if (common_output == NULL) {
387 rename(tmp_file, name);
393 open_whatis(char *mandir)
395 char filename[MAXPATHLEN];
397 snprintf(filename, sizeof filename, "%s/%s", mandir, whatis_name);
398 return(open_output(filename));
402 finish_whatis(FILE *output, char *mandir)
404 char filename[MAXPATHLEN];
406 snprintf(filename, sizeof filename, "%s/%s", mandir, whatis_name);
407 finish_output(output, filename);
411 * Tests to see if the given directory has already been visited.
414 already_visited(char *dir)
417 struct visited_dir *visit;
419 if (stat(dir, &st) < 0) {
424 SLIST_FOREACH(visit, &visited_dirs, next) {
425 if (visit->inode == st.st_ino &&
426 visit->device == st.st_dev) {
427 warnx("already visited %s", dir);
431 visit = (struct visited_dir *) malloc(sizeof(struct visited_dir));
432 visit->device = st.st_dev;
433 visit->inode = st.st_ino;
434 SLIST_INSERT_HEAD(&visited_dirs, visit, next);
439 * Removes trailing spaces from a string, returning a pointer to just
440 * beyond the new last character.
445 char *rhs = &str[strlen(str)];
446 while (--rhs > str && isspace(*rhs))
453 * Returns a pointer to the next non-space character in the string.
458 while (*s != '\0' && isspace(*s))
464 * Returns whether the string contains only digits.
467 only_digits(char *line)
469 if (!isdigit(*line++))
471 while (isdigit(*line))
473 return(*line == '\0');
477 * Returns whether the line is of one of the forms:
481 * assuming that section_start is ".Sh".
484 name_section_line(char *line, const char *section_start)
489 if (strncmp(line, section_start, 3) != 0)
491 line = skip_spaces(line + 3);
492 rhs = trim_rhs(line);
498 for (title = name_section_titles; *title != NULL; title++)
499 if (strcmp(*title, line) == 0)
505 * Copies characters while removing the most common nroff/troff
507 * \(em, \(mi, \s[+-N], \&
508 * \fF, \f(fo, \f[font]
509 * \*s, \*(st, \*[stringvar]
512 de_nroff_copy(char *from, char *to, int fromlen)
514 char *from_end = &from[fromlen];
515 while (from < from_end) {
520 if (strncmp(&from[1], "em", 2) == 0 ||
521 strncmp(&from[1], "mi", 2) == 0) {
529 while (isdigit(*from))
536 else if (*from == '[') {
537 while (*++from != ']' && from < from_end)
555 * Appends a string with the nroff formatting removed.
558 add_nroff(char *text)
560 sbuf_append_edited(whatis_proto, text, de_nroff_copy);
564 * Appends "name(suffix), " to whatis_final.
567 add_whatis_name(char *name, char *suffix)
570 sbuf_append_str(whatis_final, name);
571 sbuf_append(whatis_final, "(", 1);
572 sbuf_append_str(whatis_final, suffix);
573 sbuf_append(whatis_final, "), ", 3);
578 * Processes an old-style man(7) line. This ignores commands with only
579 * a single number argument.
582 process_man_line(char *line)
585 while (isalpha(*++line))
587 line = skip_spaces(line);
588 if (only_digits(line))
591 line = skip_spaces(line);
594 sbuf_append(whatis_proto, " ", 1);
599 * Processes a new-style mdoc(7) line.
602 process_mdoc_line(char *line)
606 char *line_end = &line[strlen(line)];
607 int orig_length = sbuf_length(whatis_proto);
612 if (line[0] != '.' || !isupper(line[1]) || !islower(line[2])) {
613 add_nroff(skip_spaces(line));
614 sbuf_append(whatis_proto, " ", 1);
617 xref = strncmp(line, ".Xr", 3) == 0;
619 while ((line = skip_spaces(line)) < line_end) {
623 next = strchr(next, '"');
626 memmove(next, next + 1, strlen(next));
633 next = strpbrk(line, " \t");
638 if (isupper(*line) && islower(line[1]) && line[2] == '\0') {
639 if (strcmp(line, "Ns") == 0) {
644 if (strstr(mdoc_commands, line) != NULL) {
649 if (arg > 0 && strchr(",.:;?!)]", *line) == 0) {
651 sbuf_append(whatis_proto, "(", 1);
653 sbuf_append(whatis_proto, ")", 1);
657 sbuf_append(whatis_proto, " ", 1);
663 if (sbuf_length(whatis_proto) > orig_length)
664 sbuf_append(whatis_proto, " ", 1);
668 * Collects a list of comma-separated names from the text.
671 collect_names(StringList *names, char *text)
677 text = strchr(text, ',');
688 enum { STATE_UNKNOWN, STATE_MANSTYLE, STATE_MDOCNAME, STATE_MDOCDESC };
691 * Processes a man page source into a single whatis line and adds it
695 process_page(struct page_info *page, char *section_dir)
702 int state = STATE_UNKNOWN;
705 sbuf_clear(whatis_proto);
706 if ((in = gzopen(page->filename, "r")) == NULL) {
707 warn("%s", page->filename);
711 while (gzgets(in, buffer, sizeof buffer) != NULL) {
713 if (strncmp(line, ".\\\"", 3) == 0) /* ignore comments */
717 * haven't reached the NAME section yet.
720 if (name_section_line(line, ".SH"))
721 state = STATE_MANSTYLE;
722 else if (name_section_line(line, ".Sh"))
723 state = STATE_MDOCNAME;
726 * Inside an old-style .SH NAME section.
729 if (strncmp(line, ".SH", 3) == 0)
732 if (strcmp(line, ".") == 0)
734 if (strncmp(line, ".IX", 3) == 0) {
736 line = skip_spaces(line);
738 process_man_line(line);
741 * Inside a new-style .Sh NAME section (the .Nm part).
745 if (strncmp(line, ".Nm", 3) == 0) {
746 process_mdoc_line(line);
749 if (strcmp(line, ".") == 0)
751 sbuf_append(whatis_proto, "- ", 2);
752 state = STATE_MDOCDESC;
756 * Inside a new-style .Sh NAME section (after the .Nm-s).
759 if (strncmp(line, ".Sh", 3) == 0)
762 if (strcmp(line, ".") == 0)
764 process_mdoc_line(line);
770 sbuf_strip(whatis_proto, " \t.-");
771 line = sbuf_content(whatis_proto);
773 * line now contains the appropriate data, but without
774 * the proper indentation or the section appended to each name.
776 descr = strstr(line, " - ");
778 descr = strchr(line, ' ');
782 "\tignoring junk description \"%s\"\n",
792 collect_names(names, line);
793 sbuf_clear(whatis_final);
794 if (!sl_find(names, page->name) &&
795 no_page_exists(section_dir, names, page->suffix)) {
797 * Add the page name since that's the only thing that
800 add_whatis_name(page->name, page->suffix);
802 for (i = 0; i < names->sl_cur; i++)
803 add_whatis_name(names->sl_str[i], page->suffix);
805 sbuf_retract(whatis_final, 2); /* remove last ", " */
806 while (sbuf_length(whatis_final) < indent)
807 sbuf_append(whatis_final, " ", 1);
808 sbuf_append(whatis_final, " - ", 3);
809 sbuf_append_str(whatis_final, skip_spaces(descr));
810 sl_add(whatis_lines, strdup(sbuf_content(whatis_final)));
814 * Sorts pages first by inode number, then by name.
817 pagesort(const void *a, const void *b)
819 const struct page_info *p1 = *(const struct page_info * const *)a;
820 const struct page_info *p2 = *(const struct page_info * const *)b;
821 if (p1->inode == p2->inode)
822 return(strcmp(p1->name, p2->name));
823 return(p1->inode - p2->inode);
827 * Processes a single man section.
830 process_section(char *section_dir)
832 struct dirent **entries;
834 struct page_info **pages;
837 ino_t prev_inode = 0;
840 fprintf(stderr, " %s\n", section_dir);
843 * scan the man section directory for pages
845 nentries = scandir(section_dir, &entries, NULL, alphasort);
847 warn("%s", section_dir);
852 * collect information about man pages
854 pages = calloc(nentries, sizeof(struct page_info *));
855 for (i = 0; i < nentries; i++) {
856 struct page_info *info = new_page_info(section_dir, entries[i]);
858 pages[npages++] = info;
862 qsort(pages, npages, sizeof(struct page_info *), pagesort);
864 * process each unique page
866 for (i = 0; i < npages; i++) {
867 struct page_info *page = pages[i];
868 if (page->inode != prev_inode) {
869 prev_inode = page->inode;
871 fprintf(stderr, "\treading %s\n",
873 process_page(page, section_dir);
875 fprintf(stderr, "\tskipping %s, duplicate\n",
877 free_page_info(page);
883 * Returns whether the directory entry is a man page section.
886 select_sections(const struct dirent *entry)
888 const char *p = &entry->d_name[3];
890 if (strncmp(entry->d_name, "man", 3) != 0)
900 * Processes a single top-level man directory by finding all the
901 * sub-directories named man* and processing each one in turn.
904 process_mandir(char *dir_name)
906 struct dirent **entries;
912 if (already_visited(dir_name))
915 fprintf(stderr, "man directory %s\n", dir_name);
916 nsections = scandir(dir_name, &entries, select_sections, alphasort);
918 warn("%s", dir_name);
922 if (common_output == NULL && (fp = open_whatis(dir_name)) == NULL)
924 for (i = 0; i < nsections; i++) {
925 char section_dir[MAXPATHLEN];
926 snprintf(section_dir, sizeof section_dir, "%s/%s", dir_name,
928 process_section(section_dir);
929 snprintf(section_dir, sizeof section_dir, "%s/%s/%s", dir_name,
930 entries[i]->d_name, machine);
931 if (stat(section_dir, &st) == 0 && S_ISDIR(st.st_mode))
932 process_section(section_dir);
936 if (common_output == NULL)
937 finish_whatis(fp, dir_name);
941 * Processes one argument, which may be a colon-separated list of
945 process_argument(const char *arg)
953 err(1, "out of memory");
954 while ((dir = strsep(&parg, ":")) != NULL) {
955 if (locale != NULL) {
956 asprintf(&mandir, "%s/%s", dir, locale);
957 process_mandir(mandir);
959 if (lang_locale != NULL) {
960 asprintf(&mandir, "%s/%s", dir, lang_locale);
961 process_mandir(mandir);
973 main(int argc, char **argv)
978 while ((opt = getopt(argc, argv, "ai:n:o:vL")) != -1) {
984 indent = atoi(optarg);
987 whatis_name = optarg;
990 common_output = optarg;
996 locale = getenv("LC_ALL");
998 locale = getenv("LC_CTYPE");
1000 locale = getenv("LANG");
1001 if (locale != NULL) {
1002 char *sep = strchr(locale, '_');
1003 if (sep != NULL && isupper(sep[1]) &&
1005 asprintf(&lang_locale, "%.*s%s",
1006 (int)(sep - locale),
1012 fprintf(stderr, "usage: %s [-a] [-i indent] [-n name] [-o output_file] [-v] [-L] [directories...]\n", argv[0]);
1017 signal(SIGINT, trap_signal);
1018 signal(SIGHUP, trap_signal);
1019 signal(SIGQUIT, trap_signal);
1020 signal(SIGTERM, trap_signal);
1021 SLIST_INIT(&visited_dirs);
1022 whatis_proto = new_sbuf();
1023 whatis_final = new_sbuf();
1025 if ((machine = getenv("MACHINE")) == NULL)
1028 if (common_output != NULL && (fp = open_output(common_output)) == NULL)
1029 err(1, "%s", common_output);
1030 if (optind == argc) {
1031 const char *manpath = getenv("MANPATH");
1032 if (manpath == NULL)
1033 manpath = DEFAULT_MANPATH;
1034 process_argument(manpath);
1036 while (optind < argc)
1037 process_argument(argv[optind++]);
1039 if (common_output != NULL)
1040 finish_output(fp, common_output);