realpath: let --relative-to default to --relative-base
[coreutils.git] / src / du.c
blob41c9535410056dd61771c40cfd958ffc6d1cb35d
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 a->size += b->size;
103 if (timespec_cmp (a->tmax, b->tmax) < 0)
104 a->tmax = b->tmax;
107 /* A structure for per-directory level information. */
108 struct dulevel
110 /* Entries in this directory. */
111 struct duinfo ent;
113 /* Total for subdirectories. */
114 struct duinfo subdir;
117 /* If true, display counts for all files, not just directories. */
118 static bool opt_all = false;
120 /* If true, rather than using the disk usage of each file,
121 use the apparent size (a la stat.st_size). */
122 static bool apparent_size = false;
124 /* If true, count each hard link of files with multiple links. */
125 static bool opt_count_all = false;
127 /* If true, hash all files to look for hard links. */
128 static bool hash_all;
130 /* If true, output the NUL byte instead of a newline at the end of each line. */
131 static bool opt_nul_terminate_output = false;
133 /* If true, print a grand total at the end. */
134 static bool print_grand_total = false;
136 /* If nonzero, do not add sizes of subdirectories. */
137 static bool opt_separate_dirs = false;
139 /* Show the total for each directory (and file if --all) that is at
140 most MAX_DEPTH levels down from the root of the hierarchy. The root
141 is at level 0, so 'du --max-depth=0' is equivalent to 'du -s'. */
142 static size_t max_depth = SIZE_MAX;
144 /* Human-readable options for output. */
145 static int human_output_opts;
147 /* If true, print most recently modified date, using the specified format. */
148 static bool opt_time = false;
150 /* Type of time to display. controlled by --time. */
152 enum time_type
154 time_mtime, /* default */
155 time_ctime,
156 time_atime
159 static enum time_type time_type = time_mtime;
161 /* User specified date / time style */
162 static char const *time_style = NULL;
164 /* Format used to display date / time. Controlled by --time-style */
165 static char const *time_format = NULL;
167 /* The units to use when printing sizes. */
168 static uintmax_t output_block_size;
170 /* File name patterns to exclude. */
171 static struct exclude *exclude;
173 /* Grand total size of all args, in bytes. Also latest modified date. */
174 static struct duinfo tot_dui;
176 #define IS_DIR_TYPE(Type) \
177 ((Type) == FTS_DP \
178 || (Type) == FTS_DNR)
180 /* For long options that have no equivalent short option, use a
181 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
182 enum
184 APPARENT_SIZE_OPTION = CHAR_MAX + 1,
185 EXCLUDE_OPTION,
186 FILES0_FROM_OPTION,
187 HUMAN_SI_OPTION,
188 FTS_DEBUG,
189 TIME_OPTION,
190 TIME_STYLE_OPTION
193 static struct option const long_options[] =
195 {"all", no_argument, NULL, 'a'},
196 {"apparent-size", no_argument, NULL, APPARENT_SIZE_OPTION},
197 {"block-size", required_argument, NULL, 'B'},
198 {"bytes", no_argument, NULL, 'b'},
199 {"count-links", no_argument, NULL, 'l'},
200 /* {"-debug", no_argument, NULL, FTS_DEBUG}, */
201 {"dereference", no_argument, NULL, 'L'},
202 {"dereference-args", no_argument, NULL, 'D'},
203 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
204 {"exclude-from", required_argument, NULL, 'X'},
205 {"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
206 {"human-readable", no_argument, NULL, 'h'},
207 {"si", no_argument, NULL, HUMAN_SI_OPTION},
208 {"max-depth", required_argument, NULL, 'd'},
209 {"null", no_argument, NULL, '0'},
210 {"no-dereference", no_argument, NULL, 'P'},
211 {"one-file-system", no_argument, NULL, 'x'},
212 {"separate-dirs", no_argument, NULL, 'S'},
213 {"summarize", no_argument, NULL, 's'},
214 {"total", no_argument, NULL, 'c'},
215 {"time", optional_argument, NULL, TIME_OPTION},
216 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
217 {GETOPT_HELP_OPTION_DECL},
218 {GETOPT_VERSION_OPTION_DECL},
219 {NULL, 0, NULL, 0}
222 static char const *const time_args[] =
224 "atime", "access", "use", "ctime", "status", NULL
226 static enum time_type const time_types[] =
228 time_atime, time_atime, time_atime, time_ctime, time_ctime
230 ARGMATCH_VERIFY (time_args, time_types);
232 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
233 ISO-style time stamps, though shorter than 'full-iso'. 'iso' uses shorter
234 ISO-style time stamps. */
235 enum time_style
237 full_iso_time_style, /* --time-style=full-iso */
238 long_iso_time_style, /* --time-style=long-iso */
239 iso_time_style /* --time-style=iso */
242 static char const *const time_style_args[] =
244 "full-iso", "long-iso", "iso", NULL
246 static enum time_style const time_style_types[] =
248 full_iso_time_style, long_iso_time_style, iso_time_style
250 ARGMATCH_VERIFY (time_style_args, time_style_types);
252 void
253 usage (int status)
255 if (status != EXIT_SUCCESS)
256 emit_try_help ();
257 else
259 printf (_("\
260 Usage: %s [OPTION]... [FILE]...\n\
261 or: %s [OPTION]... --files0-from=F\n\
262 "), program_name, program_name);
263 fputs (_("\
264 Summarize disk usage of each FILE, recursively for directories.\n\
266 "), stdout);
267 fputs (_("\
268 Mandatory arguments to long options are mandatory for short options too.\n\
269 "), stdout);
270 fputs (_("\
271 -a, --all write counts for all files, not just directories\n\
272 --apparent-size print apparent sizes, rather than disk usage; although\
274 the apparent size is usually smaller, it may be\n\
275 larger due to holes in ('sparse') files, internal\n\
276 fragmentation, indirect blocks, and the like\n\
277 "), stdout);
278 fputs (_("\
279 -B, --block-size=SIZE scale sizes by SIZE before printing them. E.g.,\n\
280 '-BM' prints sizes in units of 1,048,576 bytes.\n\
281 See SIZE format below.\n\
282 -b, --bytes equivalent to '--apparent-size --block-size=1'\n\
283 -c, --total produce a grand total\n\
284 -D, --dereference-args dereference only symlinks that are listed on the\n\
285 command line\n\
286 "), stdout);
287 fputs (_("\
288 --files0-from=F summarize disk usage of the NUL-terminated file\n\
289 names specified in file F;\n\
290 If F is - then read names from standard input\n\
291 -H equivalent to --dereference-args (-D)\n\
292 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\
294 --si like -h, but use powers of 1000 not 1024\n\
295 "), stdout);
296 fputs (_("\
297 -k like --block-size=1K\n\
298 -l, --count-links count sizes many times if hard linked\n\
299 -m like --block-size=1M\n\
300 "), stdout);
301 fputs (_("\
302 -L, --dereference dereference all symbolic links\n\
303 -P, --no-dereference don't follow any symbolic links (this is the default)\n\
304 -0, --null end each output line with 0 byte rather than newline\n\
305 -S, --separate-dirs do not include size of subdirectories\n\
306 -s, --summarize display only a total for each argument\n\
307 "), stdout);
308 fputs (_("\
309 -x, --one-file-system skip directories on different file systems\n\
310 -X, --exclude-from=FILE exclude files that match any pattern in FILE\n\
311 --exclude=PATTERN exclude files that match PATTERN\n\
312 -d, --max-depth=N print the total for a directory (or file, with --all)\n\
313 only if it is N or fewer levels below the command\n\
314 line argument; --max-depth=0 is the same as\n\
315 --summarize\n\
316 "), stdout);
317 fputs (_("\
318 --time show time of the last modification of any file in the\n\
319 directory, or any of its subdirectories\n\
320 --time=WORD show time as WORD instead of modification time:\n\
321 atime, access, use, ctime or status\n\
322 --time-style=STYLE show times using style STYLE:\n\
323 full-iso, long-iso, iso, +FORMAT\n\
324 FORMAT is interpreted like 'date'\n\
325 "), stdout);
326 fputs (HELP_OPTION_DESCRIPTION, stdout);
327 fputs (VERSION_OPTION_DESCRIPTION, stdout);
328 emit_blocksize_note ("DU");
329 emit_size_note ();
330 emit_ancillary_info ();
332 exit (status);
335 /* Try to insert the INO/DEV pair into the global table, HTAB.
336 Return true if the pair is successfully inserted,
337 false if the pair is already in the table. */
338 static bool
339 hash_ins (ino_t ino, dev_t dev)
341 int inserted = di_set_insert (di_set, dev, ino);
342 if (inserted < 0)
343 xalloc_die ();
344 return inserted;
347 /* FIXME: this code is nearly identical to code in date.c */
348 /* Display the date and time in WHEN according to the format specified
349 in FORMAT. */
351 static void
352 show_date (const char *format, struct timespec when)
354 struct tm *tm = localtime (&when.tv_sec);
355 if (! tm)
357 char buf[INT_BUFSIZE_BOUND (intmax_t)];
358 char *when_str = timetostr (when.tv_sec, buf);
359 error (0, 0, _("time %s is out of range"), when_str);
360 fputs (when_str, stdout);
361 return;
364 fprintftime (stdout, format, tm, 0, when.tv_nsec);
367 /* Print N_BYTES. Convert it to a readable value before printing. */
369 static void
370 print_only_size (uintmax_t n_bytes)
372 char buf[LONGEST_HUMAN_READABLE + 1];
373 fputs (human_readable (n_bytes, buf, human_output_opts,
374 1, output_block_size), stdout);
377 /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */
379 static void
380 print_size (const struct duinfo *pdui, const char *string)
382 print_only_size (pdui->size);
383 if (opt_time)
385 putchar ('\t');
386 show_date (time_format, pdui->tmax);
388 printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
389 fflush (stdout);
392 /* This function is called once for every file system object that fts
393 encounters. fts does a depth-first traversal. This function knows
394 that and accumulates per-directory totals based on changes in
395 the depth of the current entry. It returns true on success. */
397 static bool
398 process_file (FTS *fts, FTSENT *ent)
400 bool ok = true;
401 struct duinfo dui;
402 struct duinfo dui_to_print;
403 size_t level;
404 static size_t n_alloc;
405 /* First element of the structure contains:
406 The sum of the st_size values of all entries in the single directory
407 at the corresponding level. Although this does include the st_size
408 corresponding to each subdirectory, it does not include the size of
409 any file in a subdirectory. Also corresponding last modified date.
410 Second element of the structure contains:
411 The sum of the sizes of all entries in the hierarchy at or below the
412 directory at the specified level. */
413 static struct dulevel *dulvl;
415 const char *file = ent->fts_path;
416 const struct stat *sb = ent->fts_statp;
417 int info = ent->fts_info;
419 if (info == FTS_DNR)
421 /* An error occurred, but the size is known, so count it. */
422 error (0, ent->fts_errno, _("cannot read directory %s"), quote (file));
423 ok = false;
425 else if (info != FTS_DP)
427 bool excluded = excluded_file_name (exclude, file);
428 if (! excluded)
430 /* Make the stat buffer *SB valid, or fail noisily. */
432 if (info == FTS_NSOK)
434 fts_set (fts, ent, FTS_AGAIN);
435 FTSENT const *e = fts_read (fts);
436 assert (e == ent);
437 info = ent->fts_info;
440 if (info == FTS_NS || info == FTS_SLNONE)
442 error (0, ent->fts_errno, _("cannot access %s"), quote (file));
443 return false;
446 /* The --one-file-system (-x) option cannot exclude anything
447 specified on the command-line. By definition, it can exclude
448 a file or directory only when its device number is different
449 from that of its just-processed parent directory, and du does
450 not process the parent of a command-line argument. */
451 if (fts->fts_options & FTS_XDEV
452 && FTS_ROOTLEVEL < ent->fts_level
453 && fts->fts_dev != sb->st_dev)
454 excluded = true;
457 if (excluded
458 || (! opt_count_all
459 && (hash_all || (! S_ISDIR (sb->st_mode) && 1 < sb->st_nlink))
460 && ! hash_ins (sb->st_ino, sb->st_dev)))
462 /* If ignoring a directory in preorder, skip its children.
463 Ignore the next fts_read output too, as it's a postorder
464 visit to the same directory. */
465 if (info == FTS_D)
467 fts_set (fts, ent, FTS_SKIP);
468 FTSENT const *e = fts_read (fts);
469 assert (e == ent);
472 return true;
475 switch (info)
477 case FTS_D:
478 return true;
480 case FTS_ERR:
481 /* An error occurred, but the size is known, so count it. */
482 error (0, ent->fts_errno, "%s", quote (file));
483 ok = false;
484 break;
486 case FTS_DC:
487 if (cycle_warning_required (fts, ent))
489 emit_cycle_warning (file);
490 return false;
492 return true;
496 duinfo_set (&dui,
497 (apparent_size
498 ? sb->st_size
499 : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
500 (time_type == time_mtime ? get_stat_mtime (sb)
501 : time_type == time_atime ? get_stat_atime (sb)
502 : get_stat_ctime (sb)));
504 level = ent->fts_level;
505 dui_to_print = dui;
507 if (n_alloc == 0)
509 n_alloc = level + 10;
510 dulvl = xcalloc (n_alloc, sizeof *dulvl);
512 else
514 if (level == prev_level)
516 /* This is usually the most common case. Do nothing. */
518 else if (level > prev_level)
520 /* Descending the hierarchy.
521 Clear the accumulators for *all* levels between prev_level
522 and the current one. The depth may change dramatically,
523 e.g., from 1 to 10. */
524 size_t i;
526 if (n_alloc <= level)
528 dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
529 n_alloc = level * 2;
532 for (i = prev_level + 1; i <= level; i++)
534 duinfo_init (&dulvl[i].ent);
535 duinfo_init (&dulvl[i].subdir);
538 else /* level < prev_level */
540 /* Ascending the hierarchy.
541 Process a directory only after all entries in that
542 directory have been processed. When the depth decreases,
543 propagate sums from the children (prev_level) to the parent.
544 Here, the current level is always one smaller than the
545 previous one. */
546 assert (level == prev_level - 1);
547 duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
548 if (!opt_separate_dirs)
549 duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
550 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
551 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
555 prev_level = level;
557 /* Let the size of a directory entry contribute to the total for the
558 containing directory, unless --separate-dirs (-S) is specified. */
559 if (! (opt_separate_dirs && IS_DIR_TYPE (info)))
560 duinfo_add (&dulvl[level].ent, &dui);
562 /* Even if this directory is unreadable or we can't chdir into it,
563 do let its size contribute to the total. */
564 duinfo_add (&tot_dui, &dui);
566 if ((IS_DIR_TYPE (info) && level <= max_depth)
567 || ((opt_all && level <= max_depth) || level == 0))
568 print_size (&dui_to_print, file);
570 return ok;
573 /* Recursively print the sizes of the directories (and, if selected, files)
574 named in FILES, the last entry of which is NULL.
575 BIT_FLAGS controls how fts works.
576 Return true if successful. */
578 static bool
579 du_files (char **files, int bit_flags)
581 bool ok = true;
583 if (*files)
585 FTS *fts = xfts_open (files, bit_flags, NULL);
587 while (1)
589 FTSENT *ent;
591 ent = fts_read (fts);
592 if (ent == NULL)
594 if (errno != 0)
596 error (0, errno, _("fts_read failed: %s"),
597 quotearg_colon (fts->fts_path));
598 ok = false;
601 /* When exiting this loop early, be careful to reset the
602 global, prev_level, used in process_file. Otherwise, its
603 (level == prev_level - 1) assertion could fail. */
604 prev_level = 0;
605 break;
607 FTS_CROSS_CHECK (fts);
609 ok &= process_file (fts, ent);
612 if (fts_close (fts) != 0)
614 error (0, errno, _("fts_close failed"));
615 ok = false;
619 return ok;
623 main (int argc, char **argv)
625 char *cwd_only[2];
626 bool max_depth_specified = false;
627 bool ok = true;
628 char *files_from = NULL;
630 /* Bit flags that control how fts works. */
631 int bit_flags = FTS_NOSTAT;
633 /* Select one of the three FTS_ options that control if/when
634 to follow a symlink. */
635 int symlink_deref_bits = FTS_PHYSICAL;
637 /* If true, display only a total for each argument. */
638 bool opt_summarize_only = false;
640 cwd_only[0] = bad_cast (".");
641 cwd_only[1] = NULL;
643 initialize_main (&argc, &argv);
644 set_program_name (argv[0]);
645 setlocale (LC_ALL, "");
646 bindtextdomain (PACKAGE, LOCALEDIR);
647 textdomain (PACKAGE);
649 atexit (close_stdout);
651 exclude = new_exclude ();
653 human_options (getenv ("DU_BLOCK_SIZE"),
654 &human_output_opts, &output_block_size);
656 while (true)
658 int oi = -1;
659 int c = getopt_long (argc, argv, "0abd:chHklmsxB:DLPSX:",
660 long_options, &oi);
661 if (c == -1)
662 break;
664 switch (c)
666 #if DU_DEBUG
667 case FTS_DEBUG:
668 fts_debug = true;
669 break;
670 #endif
672 case '0':
673 opt_nul_terminate_output = true;
674 break;
676 case 'a':
677 opt_all = true;
678 break;
680 case APPARENT_SIZE_OPTION:
681 apparent_size = true;
682 break;
684 case 'b':
685 apparent_size = true;
686 human_output_opts = 0;
687 output_block_size = 1;
688 break;
690 case 'c':
691 print_grand_total = true;
692 break;
694 case 'h':
695 human_output_opts = human_autoscale | human_SI | human_base_1024;
696 output_block_size = 1;
697 break;
699 case HUMAN_SI_OPTION:
700 human_output_opts = human_autoscale | human_SI;
701 output_block_size = 1;
702 break;
704 case 'k':
705 human_output_opts = 0;
706 output_block_size = 1024;
707 break;
709 case 'd': /* --max-depth=N */
711 unsigned long int tmp_ulong;
712 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
713 && tmp_ulong <= SIZE_MAX)
715 max_depth_specified = true;
716 max_depth = tmp_ulong;
718 else
720 error (0, 0, _("invalid maximum depth %s"),
721 quote (optarg));
722 ok = false;
725 break;
727 case 'm':
728 human_output_opts = 0;
729 output_block_size = 1024 * 1024;
730 break;
732 case 'l':
733 opt_count_all = true;
734 break;
736 case 's':
737 opt_summarize_only = true;
738 break;
740 case 'x':
741 bit_flags |= FTS_XDEV;
742 break;
744 case 'B':
746 enum strtol_error e = human_options (optarg, &human_output_opts,
747 &output_block_size);
748 if (e != LONGINT_OK)
749 xstrtol_fatal (e, oi, c, long_options, optarg);
751 break;
753 case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */
754 case 'D':
755 symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
756 break;
758 case 'L': /* --dereference */
759 symlink_deref_bits = FTS_LOGICAL;
760 break;
762 case 'P': /* --no-dereference */
763 symlink_deref_bits = FTS_PHYSICAL;
764 break;
766 case 'S':
767 opt_separate_dirs = true;
768 break;
770 case 'X':
771 if (add_exclude_file (add_exclude, exclude, optarg,
772 EXCLUDE_WILDCARDS, '\n'))
774 error (0, errno, "%s", quotearg_colon (optarg));
775 ok = false;
777 break;
779 case FILES0_FROM_OPTION:
780 files_from = optarg;
781 break;
783 case EXCLUDE_OPTION:
784 add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
785 break;
787 case TIME_OPTION:
788 opt_time = true;
789 time_type =
790 (optarg
791 ? XARGMATCH ("--time", optarg, time_args, time_types)
792 : time_mtime);
793 break;
795 case TIME_STYLE_OPTION:
796 time_style = optarg;
797 break;
799 case_GETOPT_HELP_CHAR;
801 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
803 default:
804 ok = false;
808 if (!ok)
809 usage (EXIT_FAILURE);
811 if (opt_all && opt_summarize_only)
813 error (0, 0, _("cannot both summarize and show all entries"));
814 usage (EXIT_FAILURE);
817 if (opt_summarize_only && max_depth_specified && max_depth == 0)
819 error (0, 0,
820 _("warning: summarizing is the same as using --max-depth=0"));
823 if (opt_summarize_only && max_depth_specified && max_depth != 0)
825 unsigned long int d = max_depth;
826 error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
827 usage (EXIT_FAILURE);
830 if (opt_summarize_only)
831 max_depth = 0;
833 /* Process time style if printing last times. */
834 if (opt_time)
836 if (! time_style)
838 time_style = getenv ("TIME_STYLE");
840 /* Ignore TIMESTYLE="locale", for compatibility with ls. */
841 if (! time_style || STREQ (time_style, "locale"))
842 time_style = "long-iso";
843 else if (*time_style == '+')
845 /* Ignore anything after a newline, for compatibility
846 with ls. */
847 char *p = strchr (time_style, '\n');
848 if (p)
849 *p = '\0';
851 else
853 /* Ignore "posix-" prefix, for compatibility with ls. */
854 static char const posix_prefix[] = "posix-";
855 while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1)
856 == 0)
857 time_style += sizeof posix_prefix - 1;
861 if (*time_style == '+')
862 time_format = time_style + 1;
863 else
865 switch (XARGMATCH ("time style", time_style,
866 time_style_args, time_style_types))
868 case full_iso_time_style:
869 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
870 break;
872 case long_iso_time_style:
873 time_format = "%Y-%m-%d %H:%M";
874 break;
876 case iso_time_style:
877 time_format = "%Y-%m-%d";
878 break;
883 struct argv_iterator *ai;
884 if (files_from)
886 /* When using --files0-from=F, you may not specify any files
887 on the command-line. */
888 if (optind < argc)
890 error (0, 0, _("extra operand %s"), quote (argv[optind]));
891 fprintf (stderr, "%s\n",
892 _("file operands cannot be combined with --files0-from"));
893 usage (EXIT_FAILURE);
896 if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
897 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
898 quote (files_from));
900 ai = argv_iter_init_stream (stdin);
902 /* It's not easy here to count the arguments, so assume the
903 worst. */
904 hash_all = true;
906 else
908 char **files = (optind < argc ? argv + optind : cwd_only);
909 ai = argv_iter_init_argv (files);
911 /* Hash all dev,ino pairs if there are multiple arguments, or if
912 following non-command-line symlinks, because in either case a
913 file with just one hard link might be seen more than once. */
914 hash_all = (optind + 1 < argc || symlink_deref_bits == FTS_LOGICAL);
917 if (!ai)
918 xalloc_die ();
920 /* Initialize the set of dev,inode pairs. */
921 di_set = di_set_alloc ();
922 if (!di_set)
923 xalloc_die ();
925 /* If not hashing everything, process_file won't find cycles on its
926 own, so ask fts_read to check for them accurately. */
927 if (opt_count_all || ! hash_all)
928 bit_flags |= FTS_TIGHT_CYCLE_CHECK;
930 bit_flags |= symlink_deref_bits;
931 static char *temp_argv[] = { NULL, NULL };
933 while (true)
935 bool skip_file = false;
936 enum argv_iter_err ai_err;
937 char *file_name = argv_iter (ai, &ai_err);
938 if (!file_name)
940 switch (ai_err)
942 case AI_ERR_EOF:
943 goto argv_iter_done;
944 case AI_ERR_READ:
945 error (0, errno, _("%s: read error"),
946 quotearg_colon (files_from));
947 ok = false;
948 goto argv_iter_done;
949 case AI_ERR_MEM:
950 xalloc_die ();
951 default:
952 assert (!"unexpected error code from argv_iter");
955 if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-"))
957 /* Give a better diagnostic in an unusual case:
958 printf - | du --files0-from=- */
959 error (0, 0, _("when reading file names from stdin, "
960 "no file name of %s allowed"),
961 quote (file_name));
962 skip_file = true;
965 /* Report and skip any empty file names before invoking fts.
966 This works around a glitch in fts, which fails immediately
967 (without looking at the other file names) when given an empty
968 file name. */
969 if (!file_name[0])
971 /* Diagnose a zero-length file name. When it's one
972 among many, knowing the record number may help.
973 FIXME: currently print the record number only with
974 --files0-from=FILE. Maybe do it for argv, too? */
975 if (files_from == NULL)
976 error (0, 0, "%s", _("invalid zero-length file name"));
977 else
979 /* Using the standard 'filename:line-number:' prefix here is
980 not totally appropriate, since NUL is the separator, not NL,
981 but it might be better than nothing. */
982 unsigned long int file_number = argv_iter_n_args (ai);
983 error (0, 0, "%s:%lu: %s", quotearg_colon (files_from),
984 file_number, _("invalid zero-length file name"));
986 skip_file = true;
989 if (skip_file)
990 ok = false;
991 else
993 temp_argv[0] = file_name;
994 ok &= du_files (temp_argv, bit_flags);
997 argv_iter_done:
999 argv_iter_free (ai);
1000 di_set_free (di_set);
1002 if (files_from && (ferror (stdin) || fclose (stdin) != 0) && ok)
1003 error (EXIT_FAILURE, 0, _("error reading %s"), quote (files_from));
1005 if (print_grand_total)
1006 print_size (&tot_dui, _("total"));
1008 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);