maint: revert "build: update gnulib submodule to latest"
[coreutils/ericb.git] / src / du.c
blobfba7f7d600cfa6018bcb7b2a2e68f90f99fc525e
1 /* du -- summarize disk usage
2 Copyright (C) 1988-1991, 1995-2011 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 fprintf (stderr, _("Try `%s --help' for more information.\n"),
257 program_name);
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 (human_readable (n_bytes, buf, human_output_opts,
375 1, output_block_size), stdout);
378 /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */
380 static void
381 print_size (const struct duinfo *pdui, const char *string)
383 print_only_size (pdui->size);
384 if (opt_time)
386 putchar ('\t');
387 show_date (time_format, pdui->tmax);
389 printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
390 fflush (stdout);
393 /* This function is called once for every file system object that fts
394 encounters. fts does a depth-first traversal. This function knows
395 that and accumulates per-directory totals based on changes in
396 the depth of the current entry. It returns true on success. */
398 static bool
399 process_file (FTS *fts, FTSENT *ent)
401 bool ok = true;
402 struct duinfo dui;
403 struct duinfo dui_to_print;
404 size_t level;
405 static size_t n_alloc;
406 /* First element of the structure contains:
407 The sum of the st_size values of all entries in the single directory
408 at the corresponding level. Although this does include the st_size
409 corresponding to each subdirectory, it does not include the size of
410 any file in a subdirectory. Also corresponding last modified date.
411 Second element of the structure contains:
412 The sum of the sizes of all entries in the hierarchy at or below the
413 directory at the specified level. */
414 static struct dulevel *dulvl;
416 const char *file = ent->fts_path;
417 const struct stat *sb = ent->fts_statp;
418 int info = ent->fts_info;
420 if (info == FTS_DNR)
422 /* An error occurred, but the size is known, so count it. */
423 error (0, ent->fts_errno, _("cannot read directory %s"), quote (file));
424 ok = false;
426 else if (info != FTS_DP)
428 bool excluded = excluded_file_name (exclude, file);
429 if (! excluded)
431 /* Make the stat buffer *SB valid, or fail noisily. */
433 if (info == FTS_NSOK)
435 fts_set (fts, ent, FTS_AGAIN);
436 FTSENT const *e = fts_read (fts);
437 assert (e == ent);
438 info = ent->fts_info;
441 if (info == FTS_NS || info == FTS_SLNONE)
443 error (0, ent->fts_errno, _("cannot access %s"), quote (file));
444 return false;
448 if (excluded
449 || (! opt_count_all
450 && (hash_all || (! S_ISDIR (sb->st_mode) && 1 < sb->st_nlink))
451 && ! hash_ins (sb->st_ino, sb->st_dev)))
453 /* If ignoring a directory in preorder, skip its children.
454 Ignore the next fts_read output too, as it's a postorder
455 visit to the same directory. */
456 if (info == FTS_D)
458 fts_set (fts, ent, FTS_SKIP);
459 FTSENT const *e = fts_read (fts);
460 assert (e == ent);
463 return true;
466 switch (info)
468 case FTS_D:
469 return true;
471 case FTS_ERR:
472 /* An error occurred, but the size is known, so count it. */
473 error (0, ent->fts_errno, "%s", quote (file));
474 ok = false;
475 break;
477 case FTS_DC:
478 if (cycle_warning_required (fts, ent))
480 emit_cycle_warning (file);
481 return false;
483 return true;
487 duinfo_set (&dui,
488 (apparent_size
489 ? sb->st_size
490 : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
491 (time_type == time_mtime ? get_stat_mtime (sb)
492 : time_type == time_atime ? get_stat_atime (sb)
493 : get_stat_ctime (sb)));
495 level = ent->fts_level;
496 dui_to_print = dui;
498 if (n_alloc == 0)
500 n_alloc = level + 10;
501 dulvl = xcalloc (n_alloc, sizeof *dulvl);
503 else
505 if (level == prev_level)
507 /* This is usually the most common case. Do nothing. */
509 else if (level > prev_level)
511 /* Descending the hierarchy.
512 Clear the accumulators for *all* levels between prev_level
513 and the current one. The depth may change dramatically,
514 e.g., from 1 to 10. */
515 size_t i;
517 if (n_alloc <= level)
519 dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
520 n_alloc = level * 2;
523 for (i = prev_level + 1; i <= level; i++)
525 duinfo_init (&dulvl[i].ent);
526 duinfo_init (&dulvl[i].subdir);
529 else /* level < prev_level */
531 /* Ascending the hierarchy.
532 Process a directory only after all entries in that
533 directory have been processed. When the depth decreases,
534 propagate sums from the children (prev_level) to the parent.
535 Here, the current level is always one smaller than the
536 previous one. */
537 assert (level == prev_level - 1);
538 duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
539 if (!opt_separate_dirs)
540 duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
541 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
542 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
546 prev_level = level;
548 /* Let the size of a directory entry contribute to the total for the
549 containing directory, unless --separate-dirs (-S) is specified. */
550 if (! (opt_separate_dirs && IS_DIR_TYPE (info)))
551 duinfo_add (&dulvl[level].ent, &dui);
553 /* Even if this directory is unreadable or we can't chdir into it,
554 do let its size contribute to the total. */
555 duinfo_add (&tot_dui, &dui);
557 if ((IS_DIR_TYPE (info) && level <= max_depth)
558 || ((opt_all && level <= max_depth) || level == 0))
559 print_size (&dui_to_print, file);
561 return ok;
564 /* Recursively print the sizes of the directories (and, if selected, files)
565 named in FILES, the last entry of which is NULL.
566 BIT_FLAGS controls how fts works.
567 Return true if successful. */
569 static bool
570 du_files (char **files, int bit_flags)
572 bool ok = true;
574 if (*files)
576 FTS *fts = xfts_open (files, bit_flags, NULL);
578 while (1)
580 FTSENT *ent;
582 ent = fts_read (fts);
583 if (ent == NULL)
585 if (errno != 0)
587 error (0, errno, _("fts_read failed: %s"),
588 quotearg_colon (fts->fts_path));
589 ok = false;
592 /* When exiting this loop early, be careful to reset the
593 global, prev_level, used in process_file. Otherwise, its
594 (level == prev_level - 1) assertion could fail. */
595 prev_level = 0;
596 break;
598 FTS_CROSS_CHECK (fts);
600 ok &= process_file (fts, ent);
603 if (fts_close (fts) != 0)
605 error (0, errno, _("fts_close failed"));
606 ok = false;
610 return ok;
614 main (int argc, char **argv)
616 char *cwd_only[2];
617 bool max_depth_specified = false;
618 bool ok = true;
619 char *files_from = NULL;
621 /* Bit flags that control how fts works. */
622 int bit_flags = FTS_NOSTAT;
624 /* Select one of the three FTS_ options that control if/when
625 to follow a symlink. */
626 int symlink_deref_bits = FTS_PHYSICAL;
628 /* If true, display only a total for each argument. */
629 bool opt_summarize_only = false;
631 cwd_only[0] = bad_cast (".");
632 cwd_only[1] = NULL;
634 initialize_main (&argc, &argv);
635 set_program_name (argv[0]);
636 setlocale (LC_ALL, "");
637 bindtextdomain (PACKAGE, LOCALEDIR);
638 textdomain (PACKAGE);
640 atexit (close_stdout);
642 exclude = new_exclude ();
644 human_options (getenv ("DU_BLOCK_SIZE"),
645 &human_output_opts, &output_block_size);
647 while (true)
649 int oi = -1;
650 int c = getopt_long (argc, argv, "0abd:chHklmsxB:DLPSX:",
651 long_options, &oi);
652 if (c == -1)
653 break;
655 switch (c)
657 #if DU_DEBUG
658 case FTS_DEBUG:
659 fts_debug = true;
660 break;
661 #endif
663 case '0':
664 opt_nul_terminate_output = true;
665 break;
667 case 'a':
668 opt_all = true;
669 break;
671 case APPARENT_SIZE_OPTION:
672 apparent_size = true;
673 break;
675 case 'b':
676 apparent_size = true;
677 human_output_opts = 0;
678 output_block_size = 1;
679 break;
681 case 'c':
682 print_grand_total = true;
683 break;
685 case 'h':
686 human_output_opts = human_autoscale | human_SI | human_base_1024;
687 output_block_size = 1;
688 break;
690 case HUMAN_SI_OPTION:
691 human_output_opts = human_autoscale | human_SI;
692 output_block_size = 1;
693 break;
695 case 'k':
696 human_output_opts = 0;
697 output_block_size = 1024;
698 break;
700 case 'd': /* --max-depth=N */
702 unsigned long int tmp_ulong;
703 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
704 && tmp_ulong <= SIZE_MAX)
706 max_depth_specified = true;
707 max_depth = tmp_ulong;
709 else
711 error (0, 0, _("invalid maximum depth %s"),
712 quote (optarg));
713 ok = false;
716 break;
718 case 'm':
719 human_output_opts = 0;
720 output_block_size = 1024 * 1024;
721 break;
723 case 'l':
724 opt_count_all = true;
725 break;
727 case 's':
728 opt_summarize_only = true;
729 break;
731 case 'x':
732 bit_flags |= FTS_XDEV;
733 break;
735 case 'B':
737 enum strtol_error e = human_options (optarg, &human_output_opts,
738 &output_block_size);
739 if (e != LONGINT_OK)
740 xstrtol_fatal (e, oi, c, long_options, optarg);
742 break;
744 case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */
745 case 'D':
746 symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
747 break;
749 case 'L': /* --dereference */
750 symlink_deref_bits = FTS_LOGICAL;
751 break;
753 case 'P': /* --no-dereference */
754 symlink_deref_bits = FTS_PHYSICAL;
755 break;
757 case 'S':
758 opt_separate_dirs = true;
759 break;
761 case 'X':
762 if (add_exclude_file (add_exclude, exclude, optarg,
763 EXCLUDE_WILDCARDS, '\n'))
765 error (0, errno, "%s", quotearg_colon (optarg));
766 ok = false;
768 break;
770 case FILES0_FROM_OPTION:
771 files_from = optarg;
772 break;
774 case EXCLUDE_OPTION:
775 add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
776 break;
778 case TIME_OPTION:
779 opt_time = true;
780 time_type =
781 (optarg
782 ? XARGMATCH ("--time", optarg, time_args, time_types)
783 : time_mtime);
784 break;
786 case TIME_STYLE_OPTION:
787 time_style = optarg;
788 break;
790 case_GETOPT_HELP_CHAR;
792 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
794 default:
795 ok = false;
799 if (!ok)
800 usage (EXIT_FAILURE);
802 if (opt_all && opt_summarize_only)
804 error (0, 0, _("cannot both summarize and show all entries"));
805 usage (EXIT_FAILURE);
808 if (opt_summarize_only && max_depth_specified && max_depth == 0)
810 error (0, 0,
811 _("warning: summarizing is the same as using --max-depth=0"));
814 if (opt_summarize_only && max_depth_specified && max_depth != 0)
816 unsigned long int d = max_depth;
817 error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
818 usage (EXIT_FAILURE);
821 if (opt_summarize_only)
822 max_depth = 0;
824 /* Process time style if printing last times. */
825 if (opt_time)
827 if (! time_style)
829 time_style = getenv ("TIME_STYLE");
831 /* Ignore TIMESTYLE="locale", for compatibility with ls. */
832 if (! time_style || STREQ (time_style, "locale"))
833 time_style = "long-iso";
834 else if (*time_style == '+')
836 /* Ignore anything after a newline, for compatibility
837 with ls. */
838 char *p = strchr (time_style, '\n');
839 if (p)
840 *p = '\0';
842 else
844 /* Ignore "posix-" prefix, for compatibility with ls. */
845 static char const posix_prefix[] = "posix-";
846 while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1)
847 == 0)
848 time_style += sizeof posix_prefix - 1;
852 if (*time_style == '+')
853 time_format = time_style + 1;
854 else
856 switch (XARGMATCH ("time style", time_style,
857 time_style_args, time_style_types))
859 case full_iso_time_style:
860 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
861 break;
863 case long_iso_time_style:
864 time_format = "%Y-%m-%d %H:%M";
865 break;
867 case iso_time_style:
868 time_format = "%Y-%m-%d";
869 break;
874 struct argv_iterator *ai;
875 if (files_from)
877 /* When using --files0-from=F, you may not specify any files
878 on the command-line. */
879 if (optind < argc)
881 error (0, 0, _("extra operand %s"), quote (argv[optind]));
882 fprintf (stderr, "%s\n",
883 _("file operands cannot be combined with --files0-from"));
884 usage (EXIT_FAILURE);
887 if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
888 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
889 quote (files_from));
891 ai = argv_iter_init_stream (stdin);
893 /* It's not easy here to count the arguments, so assume the
894 worst. */
895 hash_all = true;
897 else
899 char **files = (optind < argc ? argv + optind : cwd_only);
900 ai = argv_iter_init_argv (files);
902 /* Hash all dev,ino pairs if there are multiple arguments, or if
903 following non-command-line symlinks, because in either case a
904 file with just one hard link might be seen more than once. */
905 hash_all = (optind + 1 < argc || symlink_deref_bits == FTS_LOGICAL);
908 if (!ai)
909 xalloc_die ();
911 /* Initialize the set of dev,inode pairs. */
912 di_set = di_set_alloc ();
913 if (!di_set)
914 xalloc_die ();
916 /* If not hashing everything, process_file won't find cycles on its
917 own, so ask fts_read to check for them accurately. */
918 if (opt_count_all || ! hash_all)
919 bit_flags |= FTS_TIGHT_CYCLE_CHECK;
921 bit_flags |= symlink_deref_bits;
922 static char *temp_argv[] = { NULL, NULL };
924 while (true)
926 bool skip_file = false;
927 enum argv_iter_err ai_err;
928 char *file_name = argv_iter (ai, &ai_err);
929 if (!file_name)
931 switch (ai_err)
933 case AI_ERR_EOF:
934 goto argv_iter_done;
935 case AI_ERR_READ:
936 error (0, errno, _("%s: read error"),
937 quotearg_colon (files_from));
938 ok = false;
939 goto argv_iter_done;
940 case AI_ERR_MEM:
941 xalloc_die ();
942 default:
943 assert (!"unexpected error code from argv_iter");
946 if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-"))
948 /* Give a better diagnostic in an unusual case:
949 printf - | du --files0-from=- */
950 error (0, 0, _("when reading file names from stdin, "
951 "no file name of %s allowed"),
952 quote (file_name));
953 skip_file = true;
956 /* Report and skip any empty file names before invoking fts.
957 This works around a glitch in fts, which fails immediately
958 (without looking at the other file names) when given an empty
959 file name. */
960 if (!file_name[0])
962 /* Diagnose a zero-length file name. When it's one
963 among many, knowing the record number may help.
964 FIXME: currently print the record number only with
965 --files0-from=FILE. Maybe do it for argv, too? */
966 if (files_from == NULL)
967 error (0, 0, "%s", _("invalid zero-length file name"));
968 else
970 /* Using the standard `filename:line-number:' prefix here is
971 not totally appropriate, since NUL is the separator, not NL,
972 but it might be better than nothing. */
973 unsigned long int file_number = argv_iter_n_args (ai);
974 error (0, 0, "%s:%lu: %s", quotearg_colon (files_from),
975 file_number, _("invalid zero-length file name"));
977 skip_file = true;
980 if (skip_file)
981 ok = false;
982 else
984 temp_argv[0] = file_name;
985 ok &= du_files (temp_argv, bit_flags);
988 argv_iter_done:
990 argv_iter_free (ai);
991 di_set_free (di_set);
993 if (files_from && (ferror (stdin) || fclose (stdin) != 0) && ok)
994 error (EXIT_FAILURE, 0, _("error reading %s"), quote (files_from));
996 if (print_grand_total)
997 print_size (&tot_dui, _("total"));
999 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);