ls: optimize for when getfilecon would often fail (~33% perf. gain)
[coreutils.git] / src / nl.c
blob21d4c4d9b6cf4cf8ef647eeac74ddbbe8b194614
1 /* nl -- number lines of files
2 Copyright (C) 1989-2012 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Scott Bartram (nancy!scott@uunet.uu.net)
18 Revised by David MacKenzie (djm@gnu.ai.mit.edu) */
20 #include <config.h>
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <getopt.h>
26 #include "system.h"
28 #include <regex.h>
30 #include "error.h"
31 #include "fadvise.h"
32 #include "linebuffer.h"
33 #include "quote.h"
34 #include "xstrtol.h"
36 /* The official name of this program (e.g., no 'g' prefix). */
37 #define PROGRAM_NAME "nl"
39 #define AUTHORS \
40 proper_name ("Scott Bartram"), \
41 proper_name ("David MacKenzie")
43 /* Line-number formats. They are given an int width, an intmax_t
44 value, and a string separator. */
46 /* Right justified, no leading zeroes. */
47 static char const FORMAT_RIGHT_NOLZ[] = "%*" PRIdMAX "%s";
49 /* Right justified, leading zeroes. */
50 static char const FORMAT_RIGHT_LZ[] = "%0*" PRIdMAX "%s";
52 /* Left justified, no leading zeroes. */
53 static char const FORMAT_LEFT[] = "%-*" PRIdMAX "%s";
55 /* Default section delimiter characters. */
56 static char const DEFAULT_SECTION_DELIMITERS[] = "\\:";
58 /* Types of input lines: either one of the section delimiters,
59 or text to output. */
60 enum section
62 Header, Body, Footer, Text
65 /* Format of body lines (-b). */
66 static char const *body_type = "t";
68 /* Format of header lines (-h). */
69 static char const *header_type = "n";
71 /* Format of footer lines (-f). */
72 static char const *footer_type = "n";
74 /* Format currently being used (body, header, or footer). */
75 static char const *current_type;
77 /* Regex for body lines to number (-bp). */
78 static struct re_pattern_buffer body_regex;
80 /* Regex for header lines to number (-hp). */
81 static struct re_pattern_buffer header_regex;
83 /* Regex for footer lines to number (-fp). */
84 static struct re_pattern_buffer footer_regex;
86 /* Fastmaps for the above. */
87 static char body_fastmap[UCHAR_MAX + 1];
88 static char header_fastmap[UCHAR_MAX + 1];
89 static char footer_fastmap[UCHAR_MAX + 1];
91 /* Pointer to current regex, if any. */
92 static struct re_pattern_buffer *current_regex = NULL;
94 /* Separator string to print after line number (-s). */
95 static char const *separator_str = "\t";
97 /* Input section delimiter string (-d). */
98 static char const *section_del = DEFAULT_SECTION_DELIMITERS;
100 /* Header delimiter string. */
101 static char *header_del = NULL;
103 /* Header section delimiter length. */
104 static size_t header_del_len;
106 /* Body delimiter string. */
107 static char *body_del = NULL;
109 /* Body section delimiter length. */
110 static size_t body_del_len;
112 /* Footer delimiter string. */
113 static char *footer_del = NULL;
115 /* Footer section delimiter length. */
116 static size_t footer_del_len;
118 /* Input buffer. */
119 static struct linebuffer line_buf;
121 /* printf format string for unnumbered lines. */
122 static char *print_no_line_fmt = NULL;
124 /* Starting line number on each page (-v). */
125 static intmax_t starting_line_number = 1;
127 /* Line number increment (-i). */
128 static intmax_t page_incr = 1;
130 /* If true, reset line number at start of each page (-p). */
131 static bool reset_numbers = true;
133 /* Number of blank lines to consider to be one line for numbering (-l). */
134 static intmax_t blank_join = 1;
136 /* Width of line numbers (-w). */
137 static int lineno_width = 6;
139 /* Line number format (-n). */
140 static char const *lineno_format = FORMAT_RIGHT_NOLZ;
142 /* Current print line number. */
143 static intmax_t line_no;
145 /* True if we have ever read standard input. */
146 static bool have_read_stdin;
148 enum
150 PAGE_INCREMENT_OPTION_DEPRECATED = CHAR_MAX + 1
153 static struct option const longopts[] =
155 {"header-numbering", required_argument, NULL, 'h'},
156 {"body-numbering", required_argument, NULL, 'b'},
157 {"footer-numbering", required_argument, NULL, 'f'},
158 {"starting-line-number", required_argument, NULL, 'v'},
159 {"line-increment", required_argument, NULL, 'i'},
160 /* FIXME: page-increment is deprecated, remove in dec-2011. */
161 {"page-increment", required_argument, NULL, PAGE_INCREMENT_OPTION_DEPRECATED},
162 {"no-renumber", no_argument, NULL, 'p'},
163 {"join-blank-lines", required_argument, NULL, 'l'},
164 {"number-separator", required_argument, NULL, 's'},
165 {"number-width", required_argument, NULL, 'w'},
166 {"number-format", required_argument, NULL, 'n'},
167 {"section-delimiter", required_argument, NULL, 'd'},
168 {GETOPT_HELP_OPTION_DECL},
169 {GETOPT_VERSION_OPTION_DECL},
170 {NULL, 0, NULL, 0}
173 /* Print a usage message and quit. */
175 void
176 usage (int status)
178 if (status != EXIT_SUCCESS)
179 emit_try_help ();
180 else
182 printf (_("\
183 Usage: %s [OPTION]... [FILE]...\n\
185 program_name);
186 fputs (_("\
187 Write each FILE to standard output, with line numbers added.\n\
188 With no FILE, or when FILE is -, read standard input.\n\
190 "), stdout);
191 fputs (_("\
192 Mandatory arguments to long options are mandatory for short options too.\n\
193 "), stdout);
194 fputs (_("\
195 -b, --body-numbering=STYLE use STYLE for numbering body lines\n\
196 -d, --section-delimiter=CC use CC for separating logical pages\n\
197 -f, --footer-numbering=STYLE use STYLE for numbering footer lines\n\
198 "), stdout);
199 fputs (_("\
200 -h, --header-numbering=STYLE use STYLE for numbering header lines\n\
201 -i, --line-increment=NUMBER line number increment at each line\n\
202 -l, --join-blank-lines=NUMBER group of NUMBER empty lines counted as one\n\
203 -n, --number-format=FORMAT insert line numbers according to FORMAT\n\
204 -p, --no-renumber do not reset line numbers at logical pages\n\
205 -s, --number-separator=STRING add STRING after (possible) line number\n\
206 "), stdout);
207 fputs (_("\
208 -v, --starting-line-number=NUMBER first line number on each logical page\n\
209 -w, --number-width=NUMBER use NUMBER columns for line numbers\n\
210 "), stdout);
211 fputs (HELP_OPTION_DESCRIPTION, stdout);
212 fputs (VERSION_OPTION_DESCRIPTION, stdout);
213 fputs (_("\
215 By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn. CC are\n\
216 two delimiter characters for separating logical pages, a missing\n\
217 second character implies :. Type \\\\ for \\. STYLE is one of:\n\
218 "), stdout);
219 fputs (_("\
221 a number all lines\n\
222 t number only nonempty lines\n\
223 n number no lines\n\
224 pBRE number only lines that contain a match for the basic regular\n\
225 expression, BRE\n\
227 FORMAT is one of:\n\
229 ln left justified, no leading zeros\n\
230 rn right justified, no leading zeros\n\
231 rz right justified, leading zeros\n\
233 "), stdout);
234 emit_ancillary_info ();
236 exit (status);
239 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
240 according to 'optarg'. */
242 static bool
243 build_type_arg (char const **typep,
244 struct re_pattern_buffer *regexp, char *fastmap)
246 char const *errmsg;
247 bool rval = true;
249 switch (*optarg)
251 case 'a':
252 case 't':
253 case 'n':
254 *typep = optarg;
255 break;
256 case 'p':
257 *typep = optarg++;
258 regexp->buffer = NULL;
259 regexp->allocated = 0;
260 regexp->fastmap = fastmap;
261 regexp->translate = NULL;
262 re_syntax_options =
263 RE_SYNTAX_POSIX_BASIC & ~RE_CONTEXT_INVALID_DUP & ~RE_NO_EMPTY_RANGES;
264 errmsg = re_compile_pattern (optarg, strlen (optarg), regexp);
265 if (errmsg)
266 error (EXIT_FAILURE, 0, "%s", errmsg);
267 break;
268 default:
269 rval = false;
270 break;
272 return rval;
275 /* Print the line number and separator; increment the line number. */
277 static void
278 print_lineno (void)
280 intmax_t next_line_no;
282 printf (lineno_format, lineno_width, line_no, separator_str);
284 next_line_no = line_no + page_incr;
285 if (next_line_no < line_no)
286 error (EXIT_FAILURE, 0, _("line number overflow"));
287 line_no = next_line_no;
290 /* Switch to a header section. */
292 static void
293 proc_header (void)
295 current_type = header_type;
296 current_regex = &header_regex;
297 if (reset_numbers)
298 line_no = starting_line_number;
299 putchar ('\n');
302 /* Switch to a body section. */
304 static void
305 proc_body (void)
307 current_type = body_type;
308 current_regex = &body_regex;
309 putchar ('\n');
312 /* Switch to a footer section. */
314 static void
315 proc_footer (void)
317 current_type = footer_type;
318 current_regex = &footer_regex;
319 putchar ('\n');
322 /* Process a regular text line in 'line_buf'. */
324 static void
325 proc_text (void)
327 static intmax_t blank_lines = 0; /* Consecutive blank lines so far. */
329 switch (*current_type)
331 case 'a':
332 if (blank_join > 1)
334 if (1 < line_buf.length || ++blank_lines == blank_join)
336 print_lineno ();
337 blank_lines = 0;
339 else
340 fputs (print_no_line_fmt, stdout);
342 else
343 print_lineno ();
344 break;
345 case 't':
346 if (1 < line_buf.length)
347 print_lineno ();
348 else
349 fputs (print_no_line_fmt, stdout);
350 break;
351 case 'n':
352 fputs (print_no_line_fmt, stdout);
353 break;
354 case 'p':
355 switch (re_search (current_regex, line_buf.buffer, line_buf.length - 1,
356 0, line_buf.length - 1, NULL))
358 case -2:
359 error (EXIT_FAILURE, errno, _("error in regular expression search"));
361 case -1:
362 fputs (print_no_line_fmt, stdout);
363 break;
365 default:
366 print_lineno ();
367 break;
370 fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
373 /* Return the type of line in 'line_buf'. */
375 static enum section
376 check_section (void)
378 size_t len = line_buf.length - 1;
380 if (len < 2 || memcmp (line_buf.buffer, section_del, 2))
381 return Text;
382 if (len == header_del_len
383 && !memcmp (line_buf.buffer, header_del, header_del_len))
384 return Header;
385 if (len == body_del_len
386 && !memcmp (line_buf.buffer, body_del, body_del_len))
387 return Body;
388 if (len == footer_del_len
389 && !memcmp (line_buf.buffer, footer_del, footer_del_len))
390 return Footer;
391 return Text;
394 /* Read and process the file pointed to by FP. */
396 static void
397 process_file (FILE *fp)
399 while (readlinebuffer (&line_buf, fp))
401 switch (check_section ())
403 case Header:
404 proc_header ();
405 break;
406 case Body:
407 proc_body ();
408 break;
409 case Footer:
410 proc_footer ();
411 break;
412 case Text:
413 proc_text ();
414 break;
419 /* Process file FILE to standard output.
420 Return true if successful. */
422 static bool
423 nl_file (char const *file)
425 FILE *stream;
427 if (STREQ (file, "-"))
429 have_read_stdin = true;
430 stream = stdin;
432 else
434 stream = fopen (file, "r");
435 if (stream == NULL)
437 error (0, errno, "%s", file);
438 return false;
442 fadvise (stream, FADVISE_SEQUENTIAL);
444 process_file (stream);
446 if (ferror (stream))
448 error (0, errno, "%s", file);
449 return false;
451 if (STREQ (file, "-"))
452 clearerr (stream); /* Also clear EOF. */
453 else if (fclose (stream) == EOF)
455 error (0, errno, "%s", file);
456 return false;
458 return true;
462 main (int argc, char **argv)
464 int c;
465 size_t len;
466 bool ok = true;
468 initialize_main (&argc, &argv);
469 set_program_name (argv[0]);
470 setlocale (LC_ALL, "");
471 bindtextdomain (PACKAGE, LOCALEDIR);
472 textdomain (PACKAGE);
474 atexit (close_stdout);
476 have_read_stdin = false;
478 while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
479 NULL)) != -1)
481 switch (c)
483 case 'h':
484 if (! build_type_arg (&header_type, &header_regex, header_fastmap))
486 error (0, 0, _("invalid header numbering style: %s"),
487 quote (optarg));
488 ok = false;
490 break;
491 case 'b':
492 if (! build_type_arg (&body_type, &body_regex, body_fastmap))
494 error (0, 0, _("invalid body numbering style: %s"),
495 quote (optarg));
496 ok = false;
498 break;
499 case 'f':
500 if (! build_type_arg (&footer_type, &footer_regex, footer_fastmap))
502 error (0, 0, _("invalid footer numbering style: %s"),
503 quote (optarg));
504 ok = false;
506 break;
507 case 'v':
508 if (xstrtoimax (optarg, NULL, 10, &starting_line_number, "")
509 != LONGINT_OK)
511 error (0, 0, _("invalid starting line number: %s"),
512 quote (optarg));
513 ok = false;
515 break;
516 case PAGE_INCREMENT_OPTION_DEPRECATED:
517 error (0, 0, _("WARNING: --page-increment is deprecated; "
518 "use --line-increment instead"));
519 /* fall through */
520 case 'i':
521 if (! (xstrtoimax (optarg, NULL, 10, &page_incr, "") == LONGINT_OK
522 && 0 < page_incr))
524 error (0, 0, _("invalid line number increment: %s"),
525 quote (optarg));
526 ok = false;
528 break;
529 case 'p':
530 reset_numbers = false;
531 break;
532 case 'l':
533 if (! (xstrtoimax (optarg, NULL, 10, &blank_join, "") == LONGINT_OK
534 && 0 < blank_join))
536 error (0, 0, _("invalid number of blank lines: %s"),
537 quote (optarg));
538 ok = false;
540 break;
541 case 's':
542 separator_str = optarg;
543 break;
544 case 'w':
546 long int tmp_long;
547 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
548 || tmp_long <= 0 || tmp_long > INT_MAX)
550 error (0, 0, _("invalid line number field width: %s"),
551 quote (optarg));
552 ok = false;
554 else
556 lineno_width = tmp_long;
559 break;
560 case 'n':
561 if (STREQ (optarg, "ln"))
562 lineno_format = FORMAT_LEFT;
563 else if (STREQ (optarg, "rn"))
564 lineno_format = FORMAT_RIGHT_NOLZ;
565 else if (STREQ (optarg, "rz"))
566 lineno_format = FORMAT_RIGHT_LZ;
567 else
569 error (0, 0, _("invalid line numbering format: %s"),
570 quote (optarg));
571 ok = false;
573 break;
574 case 'd':
575 section_del = optarg;
576 break;
577 case_GETOPT_HELP_CHAR;
578 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
579 default:
580 ok = false;
581 break;
585 if (!ok)
586 usage (EXIT_FAILURE);
588 /* Initialize the section delimiters. */
589 len = strlen (section_del);
591 header_del_len = len * 3;
592 header_del = xmalloc (header_del_len + 1);
593 stpcpy (stpcpy (stpcpy (header_del, section_del), section_del), section_del);
595 body_del_len = len * 2;
596 body_del = xmalloc (body_del_len + 1);
597 stpcpy (stpcpy (body_del, section_del), section_del);
599 footer_del_len = len;
600 footer_del = xmalloc (footer_del_len + 1);
601 stpcpy (footer_del, section_del);
603 /* Initialize the input buffer. */
604 initbuffer (&line_buf);
606 /* Initialize the printf format for unnumbered lines. */
607 len = strlen (separator_str);
608 print_no_line_fmt = xmalloc (lineno_width + len + 1);
609 memset (print_no_line_fmt, ' ', lineno_width + len);
610 print_no_line_fmt[lineno_width + len] = '\0';
612 line_no = starting_line_number;
613 current_type = body_type;
614 current_regex = &body_regex;
616 /* Main processing. */
618 if (optind == argc)
619 ok = nl_file ("-");
620 else
621 for (; optind < argc; optind++)
622 ok &= nl_file (argv[optind]);
624 if (have_read_stdin && fclose (stdin) == EOF)
625 error (EXIT_FAILURE, errno, "-");
627 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);