Debian Codegraph @

src/shared/help-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdlib.h>
4
5 #include "alloc-util.h"
6 #include "ansi-color.h"
7 #include "help-util.h"
8 #include "path-util.h"
9 #include "pretty-print.h"
10
11 /* These are helpers for putting together --help texts in a uniform way with a common output style. Each
12 * function generates a separate part of the --help text:
13 *
14 * 1. help_cmdline() outputs a brief summary of the command line syntax. This shall be used at least once,
15 * in some cases multiple times. This generally comes first in the output.
16 *
17 * 2. help_abstract() outputs a brief prose abstract of the command, should carry a single line of text
18 * that gives the user a hint what this tool does. Use only once, right after the last help_cmdline().
19 *
20 * 3. help_section() can be used to format multiple sections of the --help text. It should be used at least
21 * once for an "Options:" section, but can be used more than once, for programs with many
22 * options/verbs. The first invocation should come right after help_abstract().
23 *
24 * 4. Finally, help_man_page_reference() adds a final line linking the man page of the tool. This should be
25 * used only once, and terminates the --help text.
26 *
27 * Switches and verbs documentation should be inserted after each help_section(). For that ideally use
28 * options.[ch] APIs. */
29
30 void help_cmdline(const char *arguments) {
31 const char *progname =
32 last_path_component(secure_getenv("SYSTEMD_INVOKED_AS"))
33 ?: program_invocation_short_name;
34
35 assert(arguments);
36
37 printf("%s>%s %s %s\n",
38 ansi_grey(),
39 ansi_normal(),
40 progname,
41 arguments);
42 }
43
44 void help_abstract(const char *text) {
45 assert(text);
46
47 printf("\n%s%s%s%s\n",
48 ansi_highlight(),
49 ansi_add_italics(),
50 text,
51 ansi_normal());
52 }
53
54 void help_section(const char *title) {
55 assert(title);
56
57 printf("\n%s%s:%s\n",
58 ansi_underline(),
59 title,
60 ansi_normal());
61 }
62
63 void help_man_page_reference(const char *page, const char *section) {
64 assert(page);
65 assert(section);
66
67 /* Displaying --help texts generally should not fail, hence let's fall back to a simple string in
68 * case of OOM. */
69 _cleanup_free_ char *link = NULL;
70 if (terminal_urlify_man(page, section, &link) < 0)
71 printf("\nSee the %s(%s) man page for details.\n", page, section);
72 else
73 printf("\nSee the %s for details.\n", link);
74 }