1 /* dircolors - output commands to set the LS_COLOR environment variable
2 Copyright (C) 1996-2023 Free Software Foundation, Inc.
3 Copyright (C) 1994, 1995, 1997, 1998, 1999, 2000 H. Peter Anvin
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20 #include <sys/types.h>
25 #include "dircolors.h"
26 #include "c-strcase.h"
33 /* The official name of this program (e.g., no 'g' prefix). */
34 #define PROGRAM_NAME "dircolors"
36 #define AUTHORS proper_name ("H. Peter Anvin")
38 #define obstack_chunk_alloc malloc
39 #define obstack_chunk_free free
48 #define APPEND_CHAR(C) obstack_1grow (&lsc_obstack, C)
50 /* Accumulate in this obstack the value for the LS_COLORS environment
52 static struct obstack lsc_obstack
;
54 static char const *const slack_codes
[] =
56 "NORMAL", "NORM", "FILE", "RESET", "DIR", "LNK", "LINK",
57 "SYMLINK", "ORPHAN", "MISSING", "FIFO", "PIPE", "SOCK", "BLK", "BLOCK",
58 "CHR", "CHAR", "DOOR", "EXEC", "LEFT", "LEFTCODE", "RIGHT", "RIGHTCODE",
59 "END", "ENDCODE", "SUID", "SETUID", "SGID", "SETGID", "STICKY",
60 "OTHER_WRITABLE", "OWR", "STICKY_OTHER_WRITABLE", "OWT", "CAPABILITY",
61 "MULTIHARDLINK", "CLRTOEOL", nullptr
64 static char const *const ls_codes
[] =
66 "no", "no", "fi", "rs", "di", "ln", "ln", "ln", "or", "mi", "pi", "pi",
67 "so", "bd", "bd", "cd", "cd", "do", "ex", "lc", "lc", "rc", "rc", "ec", "ec",
68 "su", "su", "sg", "sg", "st", "ow", "ow", "tw", "tw", "ca", "mh", "cl",
71 static_assert (ARRAY_CARDINALITY (slack_codes
) == ARRAY_CARDINALITY (ls_codes
));
73 /* Whether to output escaped ls color codes for display. */
74 static bool print_ls_colors
;
76 /* For long options that have no equivalent short option, use a
77 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
80 PRINT_LS_COLORS_OPTION
= CHAR_MAX
+ 1,
83 static struct option
const long_options
[] =
85 {"bourne-shell", no_argument
, nullptr, 'b'},
86 {"sh", no_argument
, nullptr, 'b'},
87 {"csh", no_argument
, nullptr, 'c'},
88 {"c-shell", no_argument
, nullptr, 'c'},
89 {"print-database", no_argument
, nullptr, 'p'},
90 {"print-ls-colors", no_argument
, nullptr, PRINT_LS_COLORS_OPTION
},
91 {GETOPT_HELP_OPTION_DECL
},
92 {GETOPT_VERSION_OPTION_DECL
},
93 {nullptr, 0, nullptr, 0}
99 if (status
!= EXIT_SUCCESS
)
103 printf (_("Usage: %s [OPTION]... [FILE]\n"), program_name
);
105 Output commands to set the LS_COLORS environment variable.\n\
107 Determine format of output:\n\
108 -b, --sh, --bourne-shell output Bourne shell code to set LS_COLORS\n\
109 -c, --csh, --c-shell output C shell code to set LS_COLORS\n\
110 -p, --print-database output defaults\n\
111 --print-ls-colors output fully escaped colors for display\n\
113 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
114 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
117 If FILE is specified, read it to determine which colors to use for which\n\
118 file types and extensions. Otherwise, a precompiled database is used.\n\
119 For details on the format of these files, run 'dircolors --print-database'.\n\
121 emit_ancillary_info (PROGRAM_NAME
);
127 /* If the SHELL environment variable is set to 'csh' or 'tcsh,'
128 assume C shell. Else Bourne shell. */
130 static enum Shell_syntax
131 guess_shell_syntax (void)
135 shell
= getenv ("SHELL");
136 if (shell
== nullptr || *shell
== '\0')
137 return SHELL_SYNTAX_UNKNOWN
;
139 shell
= last_component (shell
);
141 if (STREQ (shell
, "csh") || STREQ (shell
, "tcsh"))
142 return SHELL_SYNTAX_C
;
144 return SHELL_SYNTAX_BOURNE
;
148 parse_line (char const *line
, char **keyword
, char **arg
)
151 char const *keyword_start
;
152 char const *arg_start
;
157 for (p
= line
; isspace (to_uchar (*p
)); ++p
)
160 /* Ignore blank lines and shell-style comments. */
161 if (*p
== '\0' || *p
== '#')
166 while (!isspace (to_uchar (*p
)) && *p
!= '\0')
171 *keyword
= ximemdup0 (keyword_start
, p
- keyword_start
);
179 while (isspace (to_uchar (*p
)));
181 if (*p
== '\0' || *p
== '#')
186 while (*p
!= '\0' && *p
!= '#')
189 for (--p
; isspace (to_uchar (*p
)); --p
)
193 *arg
= ximemdup0 (arg_start
, p
- arg_start
);
196 /* Accumulate STR to LS_COLORS data.
197 If outputting shell syntax, then escape appropriately. */
200 append_quoted (char const *str
)
202 bool need_backslash
= true;
206 if (! print_ls_colors
)
213 need_backslash
= true;
218 need_backslash
= !need_backslash
;
228 need_backslash
= true;
237 /* Accumulate entry to LS_COLORS data.
238 Use shell syntax unless PRINT_LS_COLORS is set. */
241 append_entry (char prefix
, char const *item
, char const *arg
)
245 append_quoted ("\x1B[");
250 APPEND_CHAR (prefix
);
251 append_quoted (item
);
252 APPEND_CHAR (print_ls_colors
? '\t' : '=');
255 append_quoted ("\x1B[0m");
256 APPEND_CHAR (print_ls_colors
? '\n' : ':');
259 /* Read the file open on FP (with name FILENAME). First, look for a
260 'TERM name' directive where name matches the current terminal type.
261 Once found, translate and accumulate the associated directives onto
262 the global obstack LSC_OBSTACK. Give a diagnostic
263 upon failure (unrecognized keyword is the only way to fail here).
264 Return true if successful. */
267 dc_parse_stream (FILE *fp
, char const *filename
)
269 size_t line_number
= 0;
270 char const *next_G_line
= G_line
;
271 char *input_line
= nullptr;
272 size_t input_line_size
= 0;
275 char const *colorterm
;
278 /* State for the parser. */
279 enum { ST_TERMNO
, ST_TERMYES
, ST_TERMSURE
, ST_GLOBAL
} state
= ST_GLOBAL
;
281 /* Get terminal type */
282 term
= getenv ("TERM");
283 if (term
== nullptr || *term
== '\0')
286 /* Also match $COLORTERM. */
287 colorterm
= getenv ("COLORTERM");
288 if (colorterm
== nullptr)
289 colorterm
= ""; /* Doesn't match default "?*" */
300 if (getline (&input_line
, &input_line_size
, fp
) <= 0)
304 error (0, errno
, _("%s: read error"), quotef (filename
));
314 if (next_G_line
== G_line
+ sizeof G_line
)
317 next_G_line
+= strlen (next_G_line
) + 1;
320 parse_line (line
, &keywd
, &arg
);
322 if (keywd
== nullptr)
327 error (0, 0, _("%s:%lu: invalid line; missing second token"),
328 quotef (filename
), (unsigned long int) line_number
);
334 unrecognized
= false;
335 if (c_strcasecmp (keywd
, "TERM") == 0)
337 if (state
!= ST_TERMSURE
)
338 state
= fnmatch (arg
, term
, 0) == 0 ? ST_TERMSURE
: ST_TERMNO
;
340 else if (c_strcasecmp (keywd
, "COLORTERM") == 0)
342 if (state
!= ST_TERMSURE
)
343 state
= fnmatch (arg
, colorterm
, 0) == 0 ? ST_TERMSURE
: ST_TERMNO
;
347 if (state
== ST_TERMSURE
)
348 state
= ST_TERMYES
; /* Another {COLOR,}TERM can cancel. */
350 if (state
!= ST_TERMNO
)
353 append_entry ('*', keywd
, arg
);
354 else if (keywd
[0] == '*')
355 append_entry (0, keywd
, arg
);
356 else if (c_strcasecmp (keywd
, "OPTIONS") == 0
357 || c_strcasecmp (keywd
, "COLOR") == 0
358 || c_strcasecmp (keywd
, "EIGHTBIT") == 0)
366 for (i
= 0; slack_codes
[i
] != nullptr; ++i
)
367 if (c_strcasecmp (keywd
, slack_codes
[i
]) == 0)
370 if (slack_codes
[i
] != nullptr)
371 append_entry (0, ls_codes
[i
], arg
);
380 if (unrecognized
&& (state
== ST_TERMSURE
|| state
== ST_TERMYES
))
382 error (0, 0, _("%s:%lu: unrecognized keyword %s"),
383 (filename
? quotef (filename
) : _("<internal>")),
384 (unsigned long int) line_number
, keywd
);
396 dc_parse_file (char const *filename
)
400 if (! STREQ (filename
, "-") && freopen (filename
, "r", stdin
) == nullptr)
402 error (0, errno
, "%s", quotef (filename
));
406 ok
= dc_parse_stream (stdin
, filename
);
408 if (fclose (stdin
) != 0)
410 error (0, errno
, "%s", quotef (filename
));
418 main (int argc
, char **argv
)
422 enum Shell_syntax syntax
= SHELL_SYNTAX_UNKNOWN
;
423 bool print_database
= false;
425 initialize_main (&argc
, &argv
);
426 set_program_name (argv
[0]);
427 setlocale (LC_ALL
, "");
428 bindtextdomain (PACKAGE
, LOCALEDIR
);
429 textdomain (PACKAGE
);
431 atexit (close_stdout
);
433 while ((optc
= getopt_long (argc
, argv
, "bcp", long_options
, nullptr)) != -1)
436 case 'b': /* Bourne shell syntax. */
437 syntax
= SHELL_SYNTAX_BOURNE
;
440 case 'c': /* C shell syntax. */
441 syntax
= SHELL_SYNTAX_C
;
445 print_database
= true;
448 case PRINT_LS_COLORS_OPTION
:
449 print_ls_colors
= true;
452 case_GETOPT_HELP_CHAR
;
454 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
457 usage (EXIT_FAILURE
);
463 /* It doesn't make sense to use --print with either of
464 --bourne or --c-shell. */
465 if ((print_database
| print_ls_colors
) && syntax
!= SHELL_SYNTAX_UNKNOWN
)
468 _("the options to output non shell syntax,\n"
469 "and to select a shell syntax are mutually exclusive"));
470 usage (EXIT_FAILURE
);
473 if (print_database
&& print_ls_colors
)
476 _("options --print-database and --print-ls-colors "
477 "are mutually exclusive"));
478 usage (EXIT_FAILURE
);
481 if ((!print_database
) < argc
)
483 error (0, 0, _("extra operand %s"),
484 quote (argv
[!print_database
]));
486 fprintf (stderr
, "%s\n",
487 _("file operands cannot be combined with "
488 "--print-database (-p)"));
489 usage (EXIT_FAILURE
);
494 char const *p
= G_line
;
495 while (p
- G_line
< sizeof G_line
)
503 /* If shell syntax was not explicitly specified, try to guess it. */
504 if (syntax
== SHELL_SYNTAX_UNKNOWN
&& ! print_ls_colors
)
506 syntax
= guess_shell_syntax ();
507 if (syntax
== SHELL_SYNTAX_UNKNOWN
)
509 die (EXIT_FAILURE
, 0,
510 _("no SHELL environment variable, and no shell type option given"));
514 obstack_init (&lsc_obstack
);
516 ok
= dc_parse_stream (nullptr, nullptr);
518 ok
= dc_parse_file (argv
[0]);
522 size_t len
= obstack_object_size (&lsc_obstack
);
523 char *s
= obstack_finish (&lsc_obstack
);
527 if (syntax
== SHELL_SYNTAX_BOURNE
)
529 prefix
= "LS_COLORS='";
530 suffix
= "';\nexport LS_COLORS\n";
534 prefix
= "setenv LS_COLORS '";
537 if (! print_ls_colors
)
538 fputs (prefix
, stdout
);
539 fwrite (s
, 1, len
, stdout
);
540 if (! print_ls_colors
)
541 fputs (suffix
, stdout
);
545 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;