maint: handle file sizes more reliably
[coreutils.git] / src / du.c
blob733394126496e9e7d1fe4c54930e879d1d0ae165
1 /* du -- summarize disk usage
2 Copyright (C) 1988-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 /* 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 <getopt.h>
28 #include <sys/types.h>
29 #include <assert.h>
30 #include "system.h"
31 #include "argmatch.h"
32 #include "argv-iter.h"
33 #include "di-set.h"
34 #include "error.h"
35 #include "exclude.h"
36 #include "fprintftime.h"
37 #include "human.h"
38 #include "quote.h"
39 #include "quotearg.h"
40 #include "stat-size.h"
41 #include "stat-time.h"
42 #include "stdio--.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 #else
60 # define FTS_CROSS_CHECK(Fts)
61 #endif
63 /* A set of dev/ino pairs. */
64 static struct di_set *di_set;
66 /* Keep track of the preceding "level" (depth in hierarchy)
67 from one call of process_file to the next. */
68 static size_t prev_level;
70 /* Define a class for collecting directory information. */
71 struct duinfo
73 /* Size of files in directory. */
74 uintmax_t size;
76 /* Latest time stamp found. If tmax.tv_sec == TYPE_MINIMUM (time_t)
77 && tmax.tv_nsec < 0, no time stamp has been found. */
78 struct timespec tmax;
81 /* Initialize directory data. */
82 static inline void
83 duinfo_init (struct duinfo *a)
85 a->size = 0;
86 a->tmax.tv_sec = TYPE_MINIMUM (time_t);
87 a->tmax.tv_nsec = -1;
90 /* Set directory data. */
91 static inline void
92 duinfo_set (struct duinfo *a, uintmax_t size, struct timespec tmax)
94 a->size = size;
95 a->tmax = tmax;
98 /* Accumulate directory data. */
99 static inline void
100 duinfo_add (struct duinfo *a, struct duinfo const *b)
102 uintmax_t sum = a->size + b->size;
103 a->size = a->size <= sum ? sum : UINTMAX_MAX;
104 if (timespec_cmp (a->tmax, b->tmax) < 0)
105 a->tmax = b->tmax;
108 /* A structure for per-directory level information. */
109 struct dulevel
111 /* Entries in this directory. */
112 struct duinfo ent;
114 /* Total for subdirectories. */
115 struct duinfo subdir;
118 /* If true, display counts for all files, not just directories. */
119 static bool opt_all = false;
121 /* If true, rather than using the disk usage of each file,
122 use the apparent size (a la stat.st_size). */
123 static bool apparent_size = false;
125 /* If true, count each hard link of files with multiple links. */
126 static bool opt_count_all = false;
128 /* If true, hash all files to look for hard links. */
129 static bool hash_all;
131 /* If true, output the NUL byte instead of a newline at the end of each line. */
132 static bool opt_nul_terminate_output = false;
134 /* If true, print a grand total at the end. */
135 static bool print_grand_total = false;
137 /* If nonzero, do not add sizes of subdirectories. */
138 static bool opt_separate_dirs = false;
140 /* Show the total for each directory (and file if --all) that is at
141 most MAX_DEPTH levels down from the root of the hierarchy. The root
142 is at level 0, so 'du --max-depth=0' is equivalent to 'du -s'. */
143 static size_t max_depth = SIZE_MAX;
145 /* Human-readable options for output. */
146 static int human_output_opts;
148 /* If true, print most recently modified date, using the specified format. */
149 static bool opt_time = false;
151 /* Type of time to display. controlled by --time. */
153 enum time_type
155 time_mtime, /* default */
156 time_ctime,
157 time_atime
160 static enum time_type time_type = time_mtime;
162 /* User specified date / time style */
163 static char const *time_style = NULL;
165 /* Format used to display date / time. Controlled by --time-style */
166 static char const *time_format = NULL;
168 /* The units to use when printing sizes. */
169 static uintmax_t output_block_size;
171 /* File name patterns to exclude. */
172 static struct exclude *exclude;
174 /* Grand total size of all args, in bytes. Also latest modified date. */
175 static struct duinfo tot_dui;
177 #define IS_DIR_TYPE(Type) \
178 ((Type) == FTS_DP \
179 || (Type) == FTS_DNR)
181 /* For long options that have no equivalent short option, use a
182 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
183 enum
185 APPARENT_SIZE_OPTION = CHAR_MAX + 1,
186 EXCLUDE_OPTION,
187 FILES0_FROM_OPTION,
188 HUMAN_SI_OPTION,
189 FTS_DEBUG,
190 TIME_OPTION,
191 TIME_STYLE_OPTION
194 static struct option const long_options[] =
196 {"all", no_argument, NULL, 'a'},
197 {"apparent-size", no_argument, NULL, APPARENT_SIZE_OPTION},
198 {"block-size", required_argument, NULL, 'B'},
199 {"bytes", no_argument, NULL, 'b'},
200 {"count-links", no_argument, NULL, 'l'},
201 /* {"-debug", no_argument, NULL, FTS_DEBUG}, */
202 {"dereference", no_argument, NULL, 'L'},
203 {"dereference-args", no_argument, NULL, 'D'},
204 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
205 {"exclude-from", required_argument, NULL, 'X'},
206 {"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
207 {"human-readable", no_argument, NULL, 'h'},
208 {"si", no_argument, NULL, HUMAN_SI_OPTION},
209 {"max-depth", required_argument, NULL, 'd'},
210 {"null", no_argument, NULL, '0'},
211 {"no-dereference", no_argument, NULL, 'P'},
212 {"one-file-system", no_argument, NULL, 'x'},
213 {"separate-dirs", no_argument, NULL, 'S'},
214 {"summarize", no_argument, NULL, 's'},
215 {"total", no_argument, NULL, 'c'},
216 {"time", optional_argument, NULL, TIME_OPTION},
217 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
218 {GETOPT_HELP_OPTION_DECL},
219 {GETOPT_VERSION_OPTION_DECL},
220 {NULL, 0, NULL, 0}
223 static char const *const time_args[] =
225 "atime", "access", "use", "ctime", "status", NULL
227 static enum time_type const time_types[] =
229 time_atime, time_atime, time_atime, time_ctime, time_ctime
231 ARGMATCH_VERIFY (time_args, time_types);
233 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
234 ISO-style time stamps, though shorter than 'full-iso'. 'iso' uses shorter
235 ISO-style time stamps. */
236 enum time_style
238 full_iso_time_style, /* --time-style=full-iso */
239 long_iso_time_style, /* --time-style=long-iso */
240 iso_time_style /* --time-style=iso */
243 static char const *const time_style_args[] =
245 "full-iso", "long-iso", "iso", NULL
247 static enum time_style const time_style_types[] =
249 full_iso_time_style, long_iso_time_style, iso_time_style
251 ARGMATCH_VERIFY (time_style_args, time_style_types);
253 void
254 usage (int status)
256 if (status != EXIT_SUCCESS)
257 emit_try_help ();
258 else
260 printf (_("\
261 Usage: %s [OPTION]... [FILE]...\n\
262 or: %s [OPTION]... --files0-from=F\n\
263 "), program_name, program_name);
264 fputs (_("\
265 Summarize disk usage of each FILE, recursively for directories.\n\
267 "), stdout);
268 fputs (_("\
269 Mandatory arguments to long options are mandatory for short options too.\n\
270 "), stdout);
271 fputs (_("\
272 -a, --all write counts for all files, not just directories\n\
273 --apparent-size print apparent sizes, rather than disk usage; although\
275 the apparent size is usually smaller, it may be\n\
276 larger due to holes in ('sparse') files, internal\n\
277 fragmentation, indirect blocks, and the like\n\
278 "), stdout);
279 fputs (_("\
280 -B, --block-size=SIZE scale sizes by SIZE before printing them. E.g.,\n\
281 '-BM' prints sizes in units of 1,048,576 bytes.\n\
282 See SIZE format below.\n\
283 -b, --bytes equivalent to '--apparent-size --block-size=1'\n\
284 -c, --total produce a grand total\n\
285 -D, --dereference-args dereference only symlinks that are listed on the\n\
286 command line\n\
287 "), stdout);
288 fputs (_("\
289 --files0-from=F summarize disk usage of the NUL-terminated file\n\
290 names specified in file F;\n\
291 If F is - then read names from standard input\n\
292 -H equivalent to --dereference-args (-D)\n\
293 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\
295 --si like -h, but use powers of 1000 not 1024\n\
296 "), stdout);
297 fputs (_("\
298 -k like --block-size=1K\n\
299 -l, --count-links count sizes many times if hard linked\n\
300 -m like --block-size=1M\n\
301 "), stdout);
302 fputs (_("\
303 -L, --dereference dereference all symbolic links\n\
304 -P, --no-dereference don't follow any symbolic links (this is the default)\n\
305 -0, --null end each output line with 0 byte rather than newline\n\
306 -S, --separate-dirs do not include size of subdirectories\n\
307 -s, --summarize display only a total for each argument\n\
308 "), stdout);
309 fputs (_("\
310 -x, --one-file-system skip directories on different file systems\n\
311 -X, --exclude-from=FILE exclude files that match any pattern in FILE\n\
312 --exclude=PATTERN exclude files that match PATTERN\n\
313 -d, --max-depth=N print the total for a directory (or file, with --all)\n\
314 only if it is N or fewer levels below the command\n\
315 line argument; --max-depth=0 is the same as\n\
316 --summarize\n\
317 "), stdout);
318 fputs (_("\
319 --time show time of the last modification of any file in the\n\
320 directory, or any of its subdirectories\n\
321 --time=WORD show time as WORD instead of modification time:\n\
322 atime, access, use, ctime or status\n\
323 --time-style=STYLE show times using style STYLE:\n\
324 full-iso, long-iso, iso, +FORMAT\n\
325 FORMAT is interpreted like 'date'\n\
326 "), stdout);
327 fputs (HELP_OPTION_DESCRIPTION, stdout);
328 fputs (VERSION_OPTION_DESCRIPTION, stdout);
329 emit_blocksize_note ("DU");
330 emit_size_note ();
331 emit_ancillary_info ();
333 exit (status);
336 /* Try to insert the INO/DEV pair into the global table, HTAB.
337 Return true if the pair is successfully inserted,
338 false if the pair is already in the table. */
339 static bool
340 hash_ins (ino_t ino, dev_t dev)
342 int inserted = di_set_insert (di_set, dev, ino);
343 if (inserted < 0)
344 xalloc_die ();
345 return inserted;
348 /* FIXME: this code is nearly identical to code in date.c */
349 /* Display the date and time in WHEN according to the format specified
350 in FORMAT. */
352 static void
353 show_date (const char *format, struct timespec when)
355 struct tm *tm = localtime (&when.tv_sec);
356 if (! tm)
358 char buf[INT_BUFSIZE_BOUND (intmax_t)];
359 char *when_str = timetostr (when.tv_sec, buf);
360 error (0, 0, _("time %s is out of range"), when_str);
361 fputs (when_str, stdout);
362 return;
365 fprintftime (stdout, format, tm, 0, when.tv_nsec);
368 /* Print N_BYTES. Convert it to a readable value before printing. */
370 static void
371 print_only_size (uintmax_t n_bytes)
373 char buf[LONGEST_HUMAN_READABLE + 1];
374 fputs ((n_bytes == UINTMAX_MAX
375 ? _("Infinity")
376 : human_readable (n_bytes, buf, human_output_opts,
377 1, output_block_size)),
378 stdout);
381 /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */
383 static void
384 print_size (const struct duinfo *pdui, const char *string)
386 print_only_size (pdui->size);
387 if (opt_time)
389 putchar ('\t');
390 show_date (time_format, pdui->tmax);
392 printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
393 fflush (stdout);
396 /* This function is called once for every file system object that fts
397 encounters. fts does a depth-first traversal. This function knows
398 that and accumulates per-directory totals based on changes in
399 the depth of the current entry. It returns true on success. */
401 static bool
402 process_file (FTS *fts, FTSENT *ent)
404 bool ok = true;
405 struct duinfo dui;
406 struct duinfo dui_to_print;
407 size_t level;
408 static size_t n_alloc;
409 /* First element of the structure contains:
410 The sum of the st_size values of all entries in the single directory
411 at the corresponding level. Although this does include the st_size
412 corresponding to each subdirectory, it does not include the size of
413 any file in a subdirectory. Also corresponding last modified date.
414 Second element of the structure contains:
415 The sum of the sizes of all entries in the hierarchy at or below the
416 directory at the specified level. */
417 static struct dulevel *dulvl;
419 const char *file = ent->fts_path;
420 const struct stat *sb = ent->fts_statp;
421 int info = ent->fts_info;
423 if (info == FTS_DNR)
425 /* An error occurred, but the size is known, so count it. */
426 error (0, ent->fts_errno, _("cannot read directory %s"), quote (file));
427 ok = false;
429 else if (info != FTS_DP)
431 bool excluded = excluded_file_name (exclude, file);
432 if (! excluded)
434 /* Make the stat buffer *SB valid, or fail noisily. */
436 if (info == FTS_NSOK)
438 fts_set (fts, ent, FTS_AGAIN);
439 FTSENT const *e = fts_read (fts);
440 assert (e == ent);
441 info = ent->fts_info;
444 if (info == FTS_NS || info == FTS_SLNONE)
446 error (0, ent->fts_errno, _("cannot access %s"), quote (file));
447 return false;
450 /* The --one-file-system (-x) option cannot exclude anything
451 specified on the command-line. By definition, it can exclude
452 a file or directory only when its device number is different
453 from that of its just-processed parent directory, and du does
454 not process the parent of a command-line argument. */
455 if (fts->fts_options & FTS_XDEV
456 && FTS_ROOTLEVEL < ent->fts_level
457 && fts->fts_dev != sb->st_dev)
458 excluded = true;
461 if (excluded
462 || (! opt_count_all
463 && (hash_all || (! S_ISDIR (sb->st_mode) && 1 < sb->st_nlink))
464 && ! hash_ins (sb->st_ino, sb->st_dev)))
466 /* If ignoring a directory in preorder, skip its children.
467 Ignore the next fts_read output too, as it's a postorder
468 visit to the same directory. */
469 if (info == FTS_D)
471 fts_set (fts, ent, FTS_SKIP);
472 FTSENT const *e = fts_read (fts);
473 assert (e == ent);
476 return true;
479 switch (info)
481 case FTS_D:
482 return true;
484 case FTS_ERR:
485 /* An error occurred, but the size is known, so count it. */
486 error (0, ent->fts_errno, "%s", quote (file));
487 ok = false;
488 break;
490 case FTS_DC:
491 if (cycle_warning_required (fts, ent))
493 emit_cycle_warning (file);
494 return false;
496 return true;
500 duinfo_set (&dui,
501 (apparent_size
502 ? MAX (0, sb->st_size)
503 : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
504 (time_type == time_mtime ? get_stat_mtime (sb)
505 : time_type == time_atime ? get_stat_atime (sb)
506 : get_stat_ctime (sb)));
508 level = ent->fts_level;
509 dui_to_print = dui;
511 if (n_alloc == 0)
513 n_alloc = level + 10;
514 dulvl = xcalloc (n_alloc, sizeof *dulvl);
516 else
518 if (level == prev_level)
520 /* This is usually the most common case. Do nothing. */
522 else if (level > prev_level)
524 /* Descending the hierarchy.
525 Clear the accumulators for *all* levels between prev_level
526 and the current one. The depth may change dramatically,
527 e.g., from 1 to 10. */
528 size_t i;
530 if (n_alloc <= level)
532 dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
533 n_alloc = level * 2;
536 for (i = prev_level + 1; i <= level; i++)
538 duinfo_init (&dulvl[i].ent);
539 duinfo_init (&dulvl[i].subdir);
542 else /* level < prev_level */
544 /* Ascending the hierarchy.
545 Process a directory only after all entries in that
546 directory have been processed. When the depth decreases,
547 propagate sums from the children (prev_level) to the parent.
548 Here, the current level is always one smaller than the
549 previous one. */
550 assert (level == prev_level - 1);
551 duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
552 if (!opt_separate_dirs)
553 duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
554 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
555 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
559 prev_level = level;
561 /* Let the size of a directory entry contribute to the total for the
562 containing directory, unless --separate-dirs (-S) is specified. */
563 if (! (opt_separate_dirs && IS_DIR_TYPE (info)))
564 duinfo_add (&dulvl[level].ent, &dui);
566 /* Even if this directory is unreadable or we can't chdir into it,
567 do let its size contribute to the total. */
568 duinfo_add (&tot_dui, &dui);
570 if ((IS_DIR_TYPE (info) && level <= max_depth)
571 || ((opt_all && level <= max_depth) || level == 0))
572 print_size (&dui_to_print, file);
574 return ok;
577 /* Recursively print the sizes of the directories (and, if selected, files)
578 named in FILES, the last entry of which is NULL.
579 BIT_FLAGS controls how fts works.
580 Return true if successful. */
582 static bool
583 du_files (char **files, int bit_flags)
585 bool ok = true;
587 if (*files)
589 FTS *fts = xfts_open (files, bit_flags, NULL);
591 while (1)
593 FTSENT *ent;
595 ent = fts_read (fts);
596 if (ent == NULL)
598 if (errno != 0)
600 error (0, errno, _("fts_read failed: %s"),
601 quotearg_colon (fts->fts_path));
602 ok = false;
605 /* When exiting this loop early, be careful to reset the
606 global, prev_level, used in process_file. Otherwise, its
607 (level == prev_level - 1) assertion could fail. */
608 prev_level = 0;
609 break;
611 FTS_CROSS_CHECK (fts);
613 ok &= process_file (fts, ent);
616 if (fts_close (fts) != 0)
618 error (0, errno, _("fts_close failed"));
619 ok = false;
623 return ok;
627 main (int argc, char **argv)
629 char *cwd_only[2];
630 bool max_depth_specified = false;
631 bool ok = true;
632 char *files_from = NULL;
634 /* Bit flags that control how fts works. */
635 int bit_flags = FTS_NOSTAT;
637 /* Select one of the three FTS_ options that control if/when
638 to follow a symlink. */
639 int symlink_deref_bits = FTS_PHYSICAL;
641 /* If true, display only a total for each argument. */
642 bool opt_summarize_only = false;
644 cwd_only[0] = bad_cast (".");
645 cwd_only[1] = NULL;
647 initialize_main (&argc, &argv);
648 set_program_name (argv[0]);
649 setlocale (LC_ALL, "");
650 bindtextdomain (PACKAGE, LOCALEDIR);
651 textdomain (PACKAGE);
653 atexit (close_stdout);
655 exclude = new_exclude ();
657 human_options (getenv ("DU_BLOCK_SIZE"),
658 &human_output_opts, &output_block_size);
660 while (true)
662 int oi = -1;
663 int c = getopt_long (argc, argv, "0abd:chHklmsxB:DLPSX:",
664 long_options, &oi);
665 if (c == -1)
666 break;
668 switch (c)
670 #if DU_DEBUG
671 case FTS_DEBUG:
672 fts_debug = true;
673 break;
674 #endif
676 case '0':
677 opt_nul_terminate_output = true;
678 break;
680 case 'a':
681 opt_all = true;
682 break;
684 case APPARENT_SIZE_OPTION:
685 apparent_size = true;
686 break;
688 case 'b':
689 apparent_size = true;
690 human_output_opts = 0;
691 output_block_size = 1;
692 break;
694 case 'c':
695 print_grand_total = true;
696 break;
698 case 'h':
699 human_output_opts = human_autoscale | human_SI | human_base_1024;
700 output_block_size = 1;
701 break;
703 case HUMAN_SI_OPTION:
704 human_output_opts = human_autoscale | human_SI;
705 output_block_size = 1;
706 break;
708 case 'k':
709 human_output_opts = 0;
710 output_block_size = 1024;
711 break;
713 case 'd': /* --max-depth=N */
715 unsigned long int tmp_ulong;
716 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
717 && tmp_ulong <= SIZE_MAX)
719 max_depth_specified = true;
720 max_depth = tmp_ulong;
722 else
724 error (0, 0, _("invalid maximum depth %s"),
725 quote (optarg));
726 ok = false;
729 break;
731 case 'm':
732 human_output_opts = 0;
733 output_block_size = 1024 * 1024;
734 break;
736 case 'l':
737 opt_count_all = true;
738 break;
740 case 's':
741 opt_summarize_only = true;
742 break;
744 case 'x':
745 bit_flags |= FTS_XDEV;
746 break;
748 case 'B':
750 enum strtol_error e = human_options (optarg, &human_output_opts,
751 &output_block_size);
752 if (e != LONGINT_OK)
753 xstrtol_fatal (e, oi, c, long_options, optarg);
755 break;
757 case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */
758 case 'D':
759 symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
760 break;
762 case 'L': /* --dereference */
763 symlink_deref_bits = FTS_LOGICAL;
764 break;
766 case 'P': /* --no-dereference */
767 symlink_deref_bits = FTS_PHYSICAL;
768 break;
770 case 'S':
771 opt_separate_dirs = true;
772 break;
774 case 'X':
775 if (add_exclude_file (add_exclude, exclude, optarg,
776 EXCLUDE_WILDCARDS, '\n'))
778 error (0, errno, "%s", quotearg_colon (optarg));
779 ok = false;
781 break;
783 case FILES0_FROM_OPTION:
784 files_from = optarg;
785 break;
787 case EXCLUDE_OPTION:
788 add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
789 break;
791 case TIME_OPTION:
792 opt_time = true;
793 time_type =
794 (optarg
795 ? XARGMATCH ("--time", optarg, time_args, time_types)
796 : time_mtime);
797 break;
799 case TIME_STYLE_OPTION:
800 time_style = optarg;
801 break;
803 case_GETOPT_HELP_CHAR;
805 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
807 default:
808 ok = false;
812 if (!ok)
813 usage (EXIT_FAILURE);
815 if (opt_all && opt_summarize_only)
817 error (0, 0, _("cannot both summarize and show all entries"));
818 usage (EXIT_FAILURE);
821 if (opt_summarize_only && max_depth_specified && max_depth == 0)
823 error (0, 0,
824 _("warning: summarizing is the same as using --max-depth=0"));
827 if (opt_summarize_only && max_depth_specified && max_depth != 0)
829 unsigned long int d = max_depth;
830 error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
831 usage (EXIT_FAILURE);
834 if (opt_summarize_only)
835 max_depth = 0;
837 /* Process time style if printing last times. */
838 if (opt_time)
840 if (! time_style)
842 time_style = getenv ("TIME_STYLE");
844 /* Ignore TIMESTYLE="locale", for compatibility with ls. */
845 if (! time_style || STREQ (time_style, "locale"))
846 time_style = "long-iso";
847 else if (*time_style == '+')
849 /* Ignore anything after a newline, for compatibility
850 with ls. */
851 char *p = strchr (time_style, '\n');
852 if (p)
853 *p = '\0';
855 else
857 /* Ignore "posix-" prefix, for compatibility with ls. */
858 static char const posix_prefix[] = "posix-";
859 while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1)
860 == 0)
861 time_style += sizeof posix_prefix - 1;
865 if (*time_style == '+')
866 time_format = time_style + 1;
867 else
869 switch (XARGMATCH ("time style", time_style,
870 time_style_args, time_style_types))
872 case full_iso_time_style:
873 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
874 break;
876 case long_iso_time_style:
877 time_format = "%Y-%m-%d %H:%M";
878 break;
880 case iso_time_style:
881 time_format = "%Y-%m-%d";
882 break;
887 struct argv_iterator *ai;
888 if (files_from)
890 /* When using --files0-from=F, you may not specify any files
891 on the command-line. */
892 if (optind < argc)
894 error (0, 0, _("extra operand %s"), quote (argv[optind]));
895 fprintf (stderr, "%s\n",
896 _("file operands cannot be combined with --files0-from"));
897 usage (EXIT_FAILURE);
900 if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
901 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
902 quote (files_from));
904 ai = argv_iter_init_stream (stdin);
906 /* It's not easy here to count the arguments, so assume the
907 worst. */
908 hash_all = true;
910 else
912 char **files = (optind < argc ? argv + optind : cwd_only);
913 ai = argv_iter_init_argv (files);
915 /* Hash all dev,ino pairs if there are multiple arguments, or if
916 following non-command-line symlinks, because in either case a
917 file with just one hard link might be seen more than once. */
918 hash_all = (optind + 1 < argc || symlink_deref_bits == FTS_LOGICAL);
921 if (!ai)
922 xalloc_die ();
924 /* Initialize the set of dev,inode pairs. */
925 di_set = di_set_alloc ();
926 if (!di_set)
927 xalloc_die ();
929 /* If not hashing everything, process_file won't find cycles on its
930 own, so ask fts_read to check for them accurately. */
931 if (opt_count_all || ! hash_all)
932 bit_flags |= FTS_TIGHT_CYCLE_CHECK;
934 bit_flags |= symlink_deref_bits;
935 static char *temp_argv[] = { NULL, NULL };
937 while (true)
939 bool skip_file = false;
940 enum argv_iter_err ai_err;
941 char *file_name = argv_iter (ai, &ai_err);
942 if (!file_name)
944 switch (ai_err)
946 case AI_ERR_EOF:
947 goto argv_iter_done;
948 case AI_ERR_READ:
949 error (0, errno, _("%s: read error"),
950 quotearg_colon (files_from));
951 ok = false;
952 goto argv_iter_done;
953 case AI_ERR_MEM:
954 xalloc_die ();
955 default:
956 assert (!"unexpected error code from argv_iter");
959 if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-"))
961 /* Give a better diagnostic in an unusual case:
962 printf - | du --files0-from=- */
963 error (0, 0, _("when reading file names from stdin, "
964 "no file name of %s allowed"),
965 quote (file_name));
966 skip_file = true;
969 /* Report and skip any empty file names before invoking fts.
970 This works around a glitch in fts, which fails immediately
971 (without looking at the other file names) when given an empty
972 file name. */
973 if (!file_name[0])
975 /* Diagnose a zero-length file name. When it's one
976 among many, knowing the record number may help.
977 FIXME: currently print the record number only with
978 --files0-from=FILE. Maybe do it for argv, too? */
979 if (files_from == NULL)
980 error (0, 0, "%s", _("invalid zero-length file name"));
981 else
983 /* Using the standard 'filename:line-number:' prefix here is
984 not totally appropriate, since NUL is the separator, not NL,
985 but it might be better than nothing. */
986 unsigned long int file_number = argv_iter_n_args (ai);
987 error (0, 0, "%s:%lu: %s", quotearg_colon (files_from),
988 file_number, _("invalid zero-length file name"));
990 skip_file = true;
993 if (skip_file)
994 ok = false;
995 else
997 temp_argv[0] = file_name;
998 ok &= du_files (temp_argv, bit_flags);
1001 argv_iter_done:
1003 argv_iter_free (ai);
1004 di_set_free (di_set);
1006 if (files_from && (ferror (stdin) || fclose (stdin) != 0) && ok)
1007 error (EXIT_FAILURE, 0, _("error reading %s"), quote (files_from));
1009 if (print_grand_total)
1010 print_size (&tot_dui, _("total"));
1012 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);