global: convert indentation-TABs to spaces
[coreutils.git] / src / du.c
blobf746c277c307a7dd360aeada1100403b9e840b81
1 /* du -- summarize disk usage
2 Copyright (C) 1988-1991, 1995-2009 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 /* Differences from the Unix du:
18 * Doesn't simply ignore the names of regular files given as arguments
19 when -a is given.
21 By tege@sics.se, Torbjorn Granlund,
22 and djm@ai.mit.edu, David MacKenzie.
23 Variable blocks added by lm@sgi.com and eggert@twinsun.com.
24 Rewritten to use nftw, then to use fts by Jim Meyering. */
26 #include <config.h>
27 #include <stdio.h>
28 #include <getopt.h>
29 #include <sys/types.h>
30 #include <assert.h>
31 #include "system.h"
32 #include "argmatch.h"
33 #include "argv-iter.h"
34 #include "error.h"
35 #include "exclude.h"
36 #include "fprintftime.h"
37 #include "hash.h"
38 #include "human.h"
39 #include "quote.h"
40 #include "quotearg.h"
41 #include "same.h"
42 #include "stat-time.h"
43 #include "xfts.h"
44 #include "xstrtol.h"
46 extern bool fts_debug;
48 /* The official name of this program (e.g., no `g' prefix). */
49 #define PROGRAM_NAME "du"
51 #define AUTHORS \
52 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
53 proper_name ("David MacKenzie"), \
54 proper_name ("Paul Eggert"), \
55 proper_name ("Jim Meyering")
57 #if DU_DEBUG
58 # define FTS_CROSS_CHECK(Fts) fts_cross_check (Fts)
59 # define DEBUG_OPT "d"
60 #else
61 # define FTS_CROSS_CHECK(Fts)
62 # define DEBUG_OPT
63 #endif
65 /* Initial size of the hash table. */
66 #define INITIAL_TABLE_SIZE 103
68 /* Hash structure for inode and device numbers. The separate entry
69 structure makes it easier to rehash "in place". */
71 struct entry
73 ino_t st_ino;
74 dev_t st_dev;
77 /* A set of dev/ino pairs. */
78 static Hash_table *htab;
80 /* Define a class for collecting directory information. */
82 struct duinfo
84 /* Size of files in directory. */
85 uintmax_t size;
87 /* Latest time stamp found. If tmax.tv_sec == TYPE_MINIMUM (time_t)
88 && tmax.tv_nsec < 0, no time stamp has been found. */
89 struct timespec tmax;
92 /* Initialize directory data. */
93 static inline void
94 duinfo_init (struct duinfo *a)
96 a->size = 0;
97 a->tmax.tv_sec = TYPE_MINIMUM (time_t);
98 a->tmax.tv_nsec = -1;
101 /* Set directory data. */
102 static inline void
103 duinfo_set (struct duinfo *a, uintmax_t size, struct timespec tmax)
105 a->size = size;
106 a->tmax = tmax;
109 /* Accumulate directory data. */
110 static inline void
111 duinfo_add (struct duinfo *a, struct duinfo const *b)
113 a->size += b->size;
114 if (timespec_cmp (a->tmax, b->tmax) < 0)
115 a->tmax = b->tmax;
118 /* A structure for per-directory level information. */
119 struct dulevel
121 /* Entries in this directory. */
122 struct duinfo ent;
124 /* Total for subdirectories. */
125 struct duinfo subdir;
128 /* If true, display counts for all files, not just directories. */
129 static bool opt_all = false;
131 /* If true, rather than using the disk usage of each file,
132 use the apparent size (a la stat.st_size). */
133 static bool apparent_size = false;
135 /* If true, count each hard link of files with multiple links. */
136 static bool opt_count_all = false;
138 /* If true, output the NUL byte instead of a newline at the end of each line. */
139 static bool opt_nul_terminate_output = false;
141 /* If true, print a grand total at the end. */
142 static bool print_grand_total = false;
144 /* If nonzero, do not add sizes of subdirectories. */
145 static bool opt_separate_dirs = false;
147 /* Show the total for each directory (and file if --all) that is at
148 most MAX_DEPTH levels down from the root of the hierarchy. The root
149 is at level 0, so `du --max-depth=0' is equivalent to `du -s'. */
150 static size_t max_depth = SIZE_MAX;
152 /* Human-readable options for output. */
153 static int human_output_opts;
155 /* If true, print most recently modified date, using the specified format. */
156 static bool opt_time = false;
158 /* Type of time to display. controlled by --time. */
160 enum time_type
162 time_mtime, /* default */
163 time_ctime,
164 time_atime
167 static enum time_type time_type = time_mtime;
169 /* User specified date / time style */
170 static char const *time_style = NULL;
172 /* Format used to display date / time. Controlled by --time-style */
173 static char const *time_format = NULL;
175 /* The units to use when printing sizes. */
176 static uintmax_t output_block_size;
178 /* File name patterns to exclude. */
179 static struct exclude *exclude;
181 /* Grand total size of all args, in bytes. Also latest modified date. */
182 static struct duinfo tot_dui;
184 #define IS_DIR_TYPE(Type) \
185 ((Type) == FTS_DP \
186 || (Type) == FTS_DNR)
188 /* For long options that have no equivalent short option, use a
189 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
190 enum
192 APPARENT_SIZE_OPTION = CHAR_MAX + 1,
193 EXCLUDE_OPTION,
194 FILES0_FROM_OPTION,
195 HUMAN_SI_OPTION,
196 MAX_DEPTH_OPTION,
197 MEGABYTES_LONG_OPTION,
198 TIME_OPTION,
199 TIME_STYLE_OPTION
202 static struct option const long_options[] =
204 {"all", no_argument, NULL, 'a'},
205 {"apparent-size", no_argument, NULL, APPARENT_SIZE_OPTION},
206 {"block-size", required_argument, NULL, 'B'},
207 {"bytes", no_argument, NULL, 'b'},
208 {"count-links", no_argument, NULL, 'l'},
209 {"dereference", no_argument, NULL, 'L'},
210 {"dereference-args", no_argument, NULL, 'D'},
211 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
212 {"exclude-from", required_argument, NULL, 'X'},
213 {"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
214 {"human-readable", no_argument, NULL, 'h'},
215 {"si", no_argument, NULL, HUMAN_SI_OPTION},
216 {"max-depth", required_argument, NULL, MAX_DEPTH_OPTION},
217 {"null", no_argument, NULL, '0'},
218 {"no-dereference", no_argument, NULL, 'P'},
219 {"one-file-system", no_argument, NULL, 'x'},
220 {"separate-dirs", no_argument, NULL, 'S'},
221 {"summarize", no_argument, NULL, 's'},
222 {"total", no_argument, NULL, 'c'},
223 {"time", optional_argument, NULL, TIME_OPTION},
224 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
225 {GETOPT_HELP_OPTION_DECL},
226 {GETOPT_VERSION_OPTION_DECL},
227 {NULL, 0, NULL, 0}
230 static char const *const time_args[] =
232 "atime", "access", "use", "ctime", "status", NULL
234 static enum time_type const time_types[] =
236 time_atime, time_atime, time_atime, time_ctime, time_ctime
238 ARGMATCH_VERIFY (time_args, time_types);
240 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
241 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
242 ISO-style time stamps. */
243 enum time_style
245 full_iso_time_style, /* --time-style=full-iso */
246 long_iso_time_style, /* --time-style=long-iso */
247 iso_time_style /* --time-style=iso */
250 static char const *const time_style_args[] =
252 "full-iso", "long-iso", "iso", NULL
254 static enum time_style const time_style_types[] =
256 full_iso_time_style, long_iso_time_style, iso_time_style
258 ARGMATCH_VERIFY (time_style_args, time_style_types);
260 void
261 usage (int status)
263 if (status != EXIT_SUCCESS)
264 fprintf (stderr, _("Try `%s --help' for more information.\n"),
265 program_name);
266 else
268 printf (_("\
269 Usage: %s [OPTION]... [FILE]...\n\
270 or: %s [OPTION]... --files0-from=F\n\
271 "), program_name, program_name);
272 fputs (_("\
273 Summarize disk usage of each FILE, recursively for directories.\n\
275 "), stdout);
276 fputs (_("\
277 Mandatory arguments to long options are mandatory for short options too.\n\
278 "), stdout);
279 fputs (_("\
280 -a, --all write counts for all files, not just directories\n\
281 --apparent-size print apparent sizes, rather than disk usage; although\n\
282 the apparent size is usually smaller, it may be\n\
283 larger due to holes in (`sparse') files, internal\n\
284 fragmentation, indirect blocks, and the like\n\
285 "), stdout);
286 fputs (_("\
287 -B, --block-size=SIZE use SIZE-byte blocks\n\
288 -b, --bytes equivalent to `--apparent-size --block-size=1'\n\
289 -c, --total produce a grand total\n\
290 -D, --dereference-args dereference only symlinks that are listed on the\n\
291 command line\n\
292 "), stdout);
293 fputs (_("\
294 --files0-from=F summarize disk usage of the NUL-terminated file\n\
295 names specified in file F;\n\
296 If F is - then read names from standard input\n\
297 -H equivalent to --dereference-args (-D)\n\
298 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
299 --si like -h, but use powers of 1000 not 1024\n\
300 "), stdout);
301 fputs (_("\
302 -k like --block-size=1K\n\
303 -l, --count-links count sizes many times if hard linked\n\
304 -m like --block-size=1M\n\
305 "), stdout);
306 fputs (_("\
307 -L, --dereference dereference all symbolic links\n\
308 -P, --no-dereference don't follow any symbolic links (this is the default)\n\
309 -0, --null end each output line with 0 byte rather than newline\n\
310 -S, --separate-dirs do not include size of subdirectories\n\
311 -s, --summarize display only a total for each argument\n\
312 "), stdout);
313 fputs (_("\
314 -x, --one-file-system skip directories on different file systems\n\
315 -X, --exclude-from=FILE exclude files that match any pattern in FILE\n\
316 --exclude=PATTERN exclude files that match PATTERN\n\
317 --max-depth=N print the total for a directory (or file, with --all)\n\
318 only if it is N or fewer levels below the command\n\
319 line argument; --max-depth=0 is the same as\n\
320 --summarize\n\
321 "), stdout);
322 fputs (_("\
323 --time show time of the last modification of any file in the\n\
324 directory, or any of its subdirectories\n\
325 --time=WORD show time as WORD instead of modification time:\n\
326 atime, access, use, ctime or status\n\
327 --time-style=STYLE show times using style STYLE:\n\
328 full-iso, long-iso, iso, +FORMAT\n\
329 FORMAT is interpreted like `date'\n\
330 "), stdout);
331 fputs (HELP_OPTION_DESCRIPTION, stdout);
332 fputs (VERSION_OPTION_DESCRIPTION, stdout);
333 fputs (_("\n\
334 SIZE may be (or may be an integer optionally followed by) one of following:\n\
335 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
336 "), stdout);
337 emit_bug_reporting_address ();
339 exit (status);
342 static size_t
343 entry_hash (void const *x, size_t table_size)
345 struct entry const *p = x;
347 /* Ignoring the device number here should be fine. */
348 /* The cast to uintmax_t prevents negative remainders
349 if st_ino is negative. */
350 return (uintmax_t) p->st_ino % table_size;
353 /* Compare two dev/ino pairs. Return true if they are the same. */
354 static bool
355 entry_compare (void const *x, void const *y)
357 struct entry const *a = x;
358 struct entry const *b = y;
359 return SAME_INODE (*a, *b) ? true : false;
362 /* Try to insert the INO/DEV pair into the global table, HTAB.
363 Return true if the pair is successfully inserted,
364 false if the pair is already in the table. */
365 static bool
366 hash_ins (ino_t ino, dev_t dev)
368 struct entry *ent;
369 struct entry *ent_from_table;
371 ent = xmalloc (sizeof *ent);
372 ent->st_ino = ino;
373 ent->st_dev = dev;
375 ent_from_table = hash_insert (htab, ent);
376 if (ent_from_table == NULL)
378 /* Insertion failed due to lack of memory. */
379 xalloc_die ();
382 if (ent_from_table == ent)
384 /* Insertion succeeded. */
385 return true;
388 /* That pair is already in the table, so ENT was not inserted. Free it. */
389 free (ent);
391 return false;
394 /* Initialize the hash table. */
395 static void
396 hash_init (void)
398 htab = hash_initialize (INITIAL_TABLE_SIZE, NULL,
399 entry_hash, entry_compare, free);
400 if (htab == NULL)
401 xalloc_die ();
404 /* FIXME: this code is nearly identical to code in date.c */
405 /* Display the date and time in WHEN according to the format specified
406 in FORMAT. */
408 static void
409 show_date (const char *format, struct timespec when)
411 struct tm *tm = localtime (&when.tv_sec);
412 if (! tm)
414 char buf[INT_BUFSIZE_BOUND (intmax_t)];
415 error (0, 0, _("time %s is out of range"), timetostr (when.tv_sec, buf));
416 fputs (buf, stdout);
417 return;
420 fprintftime (stdout, format, tm, 0, when.tv_nsec);
423 /* Print N_BYTES. Convert it to a readable value before printing. */
425 static void
426 print_only_size (uintmax_t n_bytes)
428 char buf[LONGEST_HUMAN_READABLE + 1];
429 fputs (human_readable (n_bytes, buf, human_output_opts,
430 1, output_block_size), stdout);
433 /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */
435 static void
436 print_size (const struct duinfo *pdui, const char *string)
438 print_only_size (pdui->size);
439 if (opt_time)
441 putchar ('\t');
442 show_date (time_format, pdui->tmax);
444 printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
445 fflush (stdout);
448 /* This function is called once for every file system object that fts
449 encounters. fts does a depth-first traversal. This function knows
450 that and accumulates per-directory totals based on changes in
451 the depth of the current entry. It returns true on success. */
453 static bool
454 process_file (FTS *fts, FTSENT *ent)
456 bool ok;
457 struct duinfo dui;
458 struct duinfo dui_to_print;
459 size_t level;
460 static size_t prev_level;
461 static size_t n_alloc;
462 /* First element of the structure contains:
463 The sum of the st_size values of all entries in the single directory
464 at the corresponding level. Although this does include the st_size
465 corresponding to each subdirectory, it does not include the size of
466 any file in a subdirectory. Also corresponding last modified date.
467 Second element of the structure contains:
468 The sum of the sizes of all entries in the hierarchy at or below the
469 directory at the specified level. */
470 static struct dulevel *dulvl;
471 bool print = true;
473 const char *file = ent->fts_path;
474 const struct stat *sb = ent->fts_statp;
475 bool skip;
477 /* If necessary, set FTS_SKIP before returning. */
478 skip = excluded_file_name (exclude, file);
479 if (skip)
480 fts_set (fts, ent, FTS_SKIP);
482 switch (ent->fts_info)
484 case FTS_NS:
485 error (0, ent->fts_errno, _("cannot access %s"), quote (file));
486 return false;
488 case FTS_ERR:
489 /* if (S_ISDIR (ent->fts_statp->st_mode) && FIXME */
490 error (0, ent->fts_errno, _("%s"), quote (file));
491 return false;
493 case FTS_DNR:
494 /* Don't return just yet, since although the directory is not readable,
495 we were able to stat it, so we do have a size. */
496 error (0, ent->fts_errno, _("cannot read directory %s"), quote (file));
497 ok = false;
498 break;
500 default:
501 ok = true;
502 break;
505 /* If this is the first (pre-order) encounter with a directory,
506 or if it's the second encounter for a skipped directory, then
507 return right away. */
508 if (ent->fts_info == FTS_D || skip)
509 return ok;
511 /* If the file is being excluded or if it has already been counted
512 via a hard link, then don't let it contribute to the sums. */
513 if (skip
514 || (!opt_count_all
515 && ! S_ISDIR (sb->st_mode)
516 && 1 < sb->st_nlink
517 && ! hash_ins (sb->st_ino, sb->st_dev)))
519 /* Note that we must not simply return here.
520 We still have to update prev_level and maybe propagate
521 some sums up the hierarchy. */
522 duinfo_init (&dui);
523 print = false;
525 else
527 duinfo_set (&dui,
528 (apparent_size
529 ? sb->st_size
530 : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
531 (time_type == time_mtime ? get_stat_mtime (sb)
532 : time_type == time_atime ? get_stat_atime (sb)
533 : get_stat_ctime (sb)));
536 level = ent->fts_level;
537 dui_to_print = dui;
539 if (n_alloc == 0)
541 n_alloc = level + 10;
542 dulvl = xcalloc (n_alloc, sizeof *dulvl);
544 else
546 if (level == prev_level)
548 /* This is usually the most common case. Do nothing. */
550 else if (level > prev_level)
552 /* Descending the hierarchy.
553 Clear the accumulators for *all* levels between prev_level
554 and the current one. The depth may change dramatically,
555 e.g., from 1 to 10. */
556 size_t i;
558 if (n_alloc <= level)
560 dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
561 n_alloc = level * 2;
564 for (i = prev_level + 1; i <= level; i++)
566 duinfo_init (&dulvl[i].ent);
567 duinfo_init (&dulvl[i].subdir);
570 else /* level < prev_level */
572 /* Ascending the hierarchy.
573 Process a directory only after all entries in that
574 directory have been processed. When the depth decreases,
575 propagate sums from the children (prev_level) to the parent.
576 Here, the current level is always one smaller than the
577 previous one. */
578 assert (level == prev_level - 1);
579 duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
580 if (!opt_separate_dirs)
581 duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
582 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
583 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
587 prev_level = level;
589 /* Let the size of a directory entry contribute to the total for the
590 containing directory, unless --separate-dirs (-S) is specified. */
591 if ( ! (opt_separate_dirs && IS_DIR_TYPE (ent->fts_info)))
592 duinfo_add (&dulvl[level].ent, &dui);
594 /* Even if this directory is unreadable or we can't chdir into it,
595 do let its size contribute to the total. */
596 duinfo_add (&tot_dui, &dui);
598 /* If we're not counting an entry, e.g., because it's a hard link
599 to a file we've already counted (and --count-links), then don't
600 print a line for it. */
601 if (!print)
602 return ok;
604 if ((IS_DIR_TYPE (ent->fts_info) && level <= max_depth)
605 || ((opt_all && level <= max_depth) || level == 0))
606 print_size (&dui_to_print, file);
608 return ok;
611 /* Recursively print the sizes of the directories (and, if selected, files)
612 named in FILES, the last entry of which is NULL.
613 BIT_FLAGS controls how fts works.
614 Return true if successful. */
616 static bool
617 du_files (char **files, int bit_flags)
619 bool ok = true;
621 if (*files)
623 FTS *fts = xfts_open (files, bit_flags, NULL);
625 while (1)
627 FTSENT *ent;
629 ent = fts_read (fts);
630 if (ent == NULL)
632 if (errno != 0)
634 /* FIXME: try to give a better message */
635 error (0, errno, _("fts_read failed"));
636 ok = false;
638 break;
640 FTS_CROSS_CHECK (fts);
642 ok &= process_file (fts, ent);
645 /* Ignore failure, since the only way it can do so is in failing to
646 return to the original directory, and since we're about to exit,
647 that doesn't matter. */
648 fts_close (fts);
651 return ok;
655 main (int argc, char **argv)
657 char *cwd_only[2];
658 bool max_depth_specified = false;
659 bool ok = true;
660 char *files_from = NULL;
662 /* Bit flags that control how fts works. */
663 int bit_flags = FTS_TIGHT_CYCLE_CHECK | FTS_DEFER_STAT;
665 /* Select one of the three FTS_ options that control if/when
666 to follow a symlink. */
667 int symlink_deref_bits = FTS_PHYSICAL;
669 /* If true, display only a total for each argument. */
670 bool opt_summarize_only = false;
672 cwd_only[0] = bad_cast (".");
673 cwd_only[1] = NULL;
675 initialize_main (&argc, &argv);
676 set_program_name (argv[0]);
677 setlocale (LC_ALL, "");
678 bindtextdomain (PACKAGE, LOCALEDIR);
679 textdomain (PACKAGE);
681 atexit (close_stdout);
683 exclude = new_exclude ();
685 human_options (getenv ("DU_BLOCK_SIZE"),
686 &human_output_opts, &output_block_size);
688 for (;;)
690 int oi = -1;
691 int c = getopt_long (argc, argv, DEBUG_OPT "0abchHklmsxB:DLPSX:",
692 long_options, &oi);
693 if (c == -1)
694 break;
696 switch (c)
698 #if DU_DEBUG
699 case 'd':
700 fts_debug = true;
701 break;
702 #endif
704 case '0':
705 opt_nul_terminate_output = true;
706 break;
708 case 'a':
709 opt_all = true;
710 break;
712 case APPARENT_SIZE_OPTION:
713 apparent_size = true;
714 break;
716 case 'b':
717 apparent_size = true;
718 human_output_opts = 0;
719 output_block_size = 1;
720 break;
722 case 'c':
723 print_grand_total = true;
724 break;
726 case 'h':
727 human_output_opts = human_autoscale | human_SI | human_base_1024;
728 output_block_size = 1;
729 break;
731 case HUMAN_SI_OPTION:
732 human_output_opts = human_autoscale | human_SI;
733 output_block_size = 1;
734 break;
736 case 'k':
737 human_output_opts = 0;
738 output_block_size = 1024;
739 break;
741 case MAX_DEPTH_OPTION: /* --max-depth=N */
743 unsigned long int tmp_ulong;
744 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
745 && tmp_ulong <= SIZE_MAX)
747 max_depth_specified = true;
748 max_depth = tmp_ulong;
750 else
752 error (0, 0, _("invalid maximum depth %s"),
753 quote (optarg));
754 ok = false;
757 break;
759 case MEGABYTES_LONG_OPTION: /* FIXME: remove in 2009 */
760 error (0, 0,
761 _("the --megabytes option is deprecated; use -m instead"));
762 /* fall through */
763 case 'm':
764 human_output_opts = 0;
765 output_block_size = 1024 * 1024;
766 break;
768 case 'l':
769 opt_count_all = true;
770 break;
772 case 's':
773 opt_summarize_only = true;
774 break;
776 case 'x':
777 bit_flags |= FTS_XDEV;
778 break;
780 case 'B':
782 enum strtol_error e = human_options (optarg, &human_output_opts,
783 &output_block_size);
784 if (e != LONGINT_OK)
785 xstrtol_fatal (e, oi, c, long_options, optarg);
787 break;
789 case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */
790 case 'D':
791 symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
792 break;
794 case 'L': /* --dereference */
795 symlink_deref_bits = FTS_LOGICAL;
796 break;
798 case 'P': /* --no-dereference */
799 symlink_deref_bits = FTS_PHYSICAL;
800 break;
802 case 'S':
803 opt_separate_dirs = true;
804 break;
806 case 'X':
807 if (add_exclude_file (add_exclude, exclude, optarg,
808 EXCLUDE_WILDCARDS, '\n'))
810 error (0, errno, "%s", quotearg_colon (optarg));
811 ok = false;
813 break;
815 case FILES0_FROM_OPTION:
816 files_from = optarg;
817 break;
819 case EXCLUDE_OPTION:
820 add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
821 break;
823 case TIME_OPTION:
824 opt_time = true;
825 time_type =
826 (optarg
827 ? XARGMATCH ("--time", optarg, time_args, time_types)
828 : time_mtime);
829 break;
831 case TIME_STYLE_OPTION:
832 time_style = optarg;
833 break;
835 case_GETOPT_HELP_CHAR;
837 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
839 default:
840 ok = false;
844 if (!ok)
845 usage (EXIT_FAILURE);
847 if (opt_all & opt_summarize_only)
849 error (0, 0, _("cannot both summarize and show all entries"));
850 usage (EXIT_FAILURE);
853 if (opt_summarize_only && max_depth_specified && max_depth == 0)
855 error (0, 0,
856 _("warning: summarizing is the same as using --max-depth=0"));
859 if (opt_summarize_only && max_depth_specified && max_depth != 0)
861 unsigned long int d = max_depth;
862 error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
863 usage (EXIT_FAILURE);
866 if (opt_summarize_only)
867 max_depth = 0;
869 /* Process time style if printing last times. */
870 if (opt_time)
872 if (! time_style)
874 time_style = getenv ("TIME_STYLE");
876 /* Ignore TIMESTYLE="locale", for compatibility with ls. */
877 if (! time_style || STREQ (time_style, "locale"))
878 time_style = "long-iso";
879 else if (*time_style == '+')
881 /* Ignore anything after a newline, for compatibility
882 with ls. */
883 char *p = strchr (time_style, '\n');
884 if (p)
885 *p = '\0';
887 else
889 /* Ignore "posix-" prefix, for compatibility with ls. */
890 static char const posix_prefix[] = "posix-";
891 while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1)
892 == 0)
893 time_style += sizeof posix_prefix - 1;
897 if (*time_style == '+')
898 time_format = time_style + 1;
899 else
901 switch (XARGMATCH ("time style", time_style,
902 time_style_args, time_style_types))
904 case full_iso_time_style:
905 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
906 break;
908 case long_iso_time_style:
909 time_format = "%Y-%m-%d %H:%M";
910 break;
912 case iso_time_style:
913 time_format = "%Y-%m-%d";
914 break;
919 struct argv_iterator *ai;
920 if (files_from)
922 /* When using --files0-from=F, you may not specify any files
923 on the command-line. */
924 if (optind < argc)
926 error (0, 0, _("extra operand %s"), quote (argv[optind]));
927 fprintf (stderr, "%s\n",
928 _("file operands cannot be combined with --files0-from"));
929 usage (EXIT_FAILURE);
932 if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
933 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
934 quote (files_from));
936 ai = argv_iter_init_stream (stdin);
938 else
940 char **files = (optind < argc ? argv + optind : cwd_only);
941 ai = argv_iter_init_argv (files);
944 if (!ai)
945 xalloc_die ();
947 /* Initialize the hash structure for inode numbers. */
948 hash_init ();
950 bit_flags |= symlink_deref_bits;
951 static char *temp_argv[] = { NULL, NULL };
953 while (true)
955 bool skip_file = false;
956 enum argv_iter_err ai_err;
957 char *file_name = argv_iter (ai, &ai_err);
958 if (ai_err == AI_ERR_EOF)
959 break;
960 if (!file_name)
962 switch (ai_err)
964 case AI_ERR_READ:
965 error (0, errno, _("%s: read error"), quote (files_from));
966 skip_file = true;
967 continue;
969 case AI_ERR_MEM:
970 xalloc_die ();
972 default:
973 assert (!"unexpected error code from argv_iter");
976 if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-"))
978 /* Give a better diagnostic in an unusual case:
979 printf - | du --files0-from=- */
980 error (0, 0, _("when reading file names from stdin, "
981 "no file name of %s allowed"),
982 quote (file_name));
983 skip_file = true;
986 /* Report and skip any empty file names before invoking fts.
987 This works around a glitch in fts, which fails immediately
988 (without looking at the other file names) when given an empty
989 file name. */
990 if (!file_name[0])
992 /* Diagnose a zero-length file name. When it's one
993 among many, knowing the record number may help.
994 FIXME: currently print the record number only with
995 --files0-from=FILE. Maybe do it for argv, too? */
996 if (files_from == NULL)
997 error (0, 0, "%s", _("invalid zero-length file name"));
998 else
1000 /* Using the standard `filename:line-number:' prefix here is
1001 not totally appropriate, since NUL is the separator, not NL,
1002 but it might be better than nothing. */
1003 unsigned long int file_number = argv_iter_n_args (ai);
1004 error (0, 0, "%s:%lu: %s", quotearg_colon (files_from),
1005 file_number, _("invalid zero-length file name"));
1007 skip_file = true;
1010 if (skip_file)
1011 ok = false;
1012 else
1014 temp_argv[0] = file_name;
1015 ok &= du_files (temp_argv, bit_flags);
1019 argv_iter_free (ai);
1021 if (files_from && (ferror (stdin) || fclose (stdin) != 0))
1022 error (EXIT_FAILURE, 0, _("error reading %s"), quote (files_from));
1024 if (print_grand_total)
1025 print_size (&tot_dui, _("total"));
1027 hash_free (htab);
1029 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);