mv: consistently warn about multiply specified source dirs
[coreutils.git] / src / du.c
blob45c37037c38d864010dc2a4988e05ca43572a141
1 /* du -- summarize disk usage
2 Copyright (C) 1988-2016 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 "mountlist.h"
39 #include "quote.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 to help identify files and directories
64 whose sizes have already been counted. */
65 static struct di_set *di_files;
67 /* A set containing a dev/ino pair for each local mount point directory. */
68 static struct di_set *di_mnt;
70 /* Keep track of the preceding "level" (depth in hierarchy)
71 from one call of process_file to the next. */
72 static size_t prev_level;
74 /* Define a class for collecting directory information. */
75 struct duinfo
77 /* Size of files in directory. */
78 uintmax_t size;
80 /* Number of inodes in directory. */
81 uintmax_t inodes;
83 /* Latest time stamp found. If tmax.tv_sec == TYPE_MINIMUM (time_t)
84 && tmax.tv_nsec < 0, no time stamp has been found. */
85 struct timespec tmax;
88 /* Initialize directory data. */
89 static inline void
90 duinfo_init (struct duinfo *a)
92 a->size = 0;
93 a->inodes = 0;
94 a->tmax.tv_sec = TYPE_MINIMUM (time_t);
95 a->tmax.tv_nsec = -1;
98 /* Set directory data. */
99 static inline void
100 duinfo_set (struct duinfo *a, uintmax_t size, struct timespec tmax)
102 a->size = size;
103 a->inodes = 1;
104 a->tmax = tmax;
107 /* Accumulate directory data. */
108 static inline void
109 duinfo_add (struct duinfo *a, struct duinfo const *b)
111 uintmax_t sum = a->size + b->size;
112 a->size = a->size <= sum ? sum : UINTMAX_MAX;
113 a->inodes = a->inodes + b->inodes;
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, hash all files to look for hard links. */
139 static bool hash_all;
141 /* If true, output the NUL byte instead of a newline at the end of each line. */
142 static bool opt_nul_terminate_output = false;
144 /* If true, print a grand total at the end. */
145 static bool print_grand_total = false;
147 /* If nonzero, do not add sizes of subdirectories. */
148 static bool opt_separate_dirs = false;
150 /* Show the total for each directory (and file if --all) that is at
151 most MAX_DEPTH levels down from the root of the hierarchy. The root
152 is at level 0, so 'du --max-depth=0' is equivalent to 'du -s'. */
153 static size_t max_depth = SIZE_MAX;
155 /* Only output entries with at least this SIZE if positive,
156 or at most if negative. See --threshold option. */
157 static intmax_t opt_threshold = 0;
159 /* Human-readable options for output. */
160 static int human_output_opts;
162 /* Output inodes count instead of blocks used. */
163 static bool opt_inodes = false;
165 /* If true, print most recently modified date, using the specified format. */
166 static bool opt_time = false;
168 /* Type of time to display. controlled by --time. */
170 enum time_type
172 time_mtime, /* default */
173 time_ctime,
174 time_atime
177 static enum time_type time_type = time_mtime;
179 /* User specified date / time style */
180 static char const *time_style = NULL;
182 /* Format used to display date / time. Controlled by --time-style */
183 static char const *time_format = NULL;
185 /* The units to use when printing sizes. */
186 static uintmax_t output_block_size;
188 /* File name patterns to exclude. */
189 static struct exclude *exclude;
191 /* Grand total size of all args, in bytes. Also latest modified date. */
192 static struct duinfo tot_dui;
194 #define IS_DIR_TYPE(Type) \
195 ((Type) == FTS_DP \
196 || (Type) == FTS_DNR)
198 /* For long options that have no equivalent short option, use a
199 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
200 enum
202 APPARENT_SIZE_OPTION = CHAR_MAX + 1,
203 EXCLUDE_OPTION,
204 FILES0_FROM_OPTION,
205 HUMAN_SI_OPTION,
206 FTS_DEBUG,
207 TIME_OPTION,
208 TIME_STYLE_OPTION,
209 INODES_OPTION
212 static struct option const long_options[] =
214 {"all", no_argument, NULL, 'a'},
215 {"apparent-size", no_argument, NULL, APPARENT_SIZE_OPTION},
216 {"block-size", required_argument, NULL, 'B'},
217 {"bytes", no_argument, NULL, 'b'},
218 {"count-links", no_argument, NULL, 'l'},
219 /* {"-debug", no_argument, NULL, FTS_DEBUG}, */
220 {"dereference", no_argument, NULL, 'L'},
221 {"dereference-args", no_argument, NULL, 'D'},
222 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
223 {"exclude-from", required_argument, NULL, 'X'},
224 {"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
225 {"human-readable", no_argument, NULL, 'h'},
226 {"inodes", no_argument, NULL, INODES_OPTION},
227 {"si", no_argument, NULL, HUMAN_SI_OPTION},
228 {"max-depth", required_argument, NULL, 'd'},
229 {"null", no_argument, NULL, '0'},
230 {"no-dereference", no_argument, NULL, 'P'},
231 {"one-file-system", no_argument, NULL, 'x'},
232 {"separate-dirs", no_argument, NULL, 'S'},
233 {"summarize", no_argument, NULL, 's'},
234 {"total", no_argument, NULL, 'c'},
235 {"threshold", required_argument, NULL, 't'},
236 {"time", optional_argument, NULL, TIME_OPTION},
237 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
238 {GETOPT_HELP_OPTION_DECL},
239 {GETOPT_VERSION_OPTION_DECL},
240 {NULL, 0, NULL, 0}
243 static char const *const time_args[] =
245 "atime", "access", "use", "ctime", "status", NULL
247 static enum time_type const time_types[] =
249 time_atime, time_atime, time_atime, time_ctime, time_ctime
251 ARGMATCH_VERIFY (time_args, time_types);
253 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
254 ISO-style time stamps, though shorter than 'full-iso'. 'iso' uses shorter
255 ISO-style time stamps. */
256 enum time_style
258 full_iso_time_style, /* --time-style=full-iso */
259 long_iso_time_style, /* --time-style=long-iso */
260 iso_time_style /* --time-style=iso */
263 static char const *const time_style_args[] =
265 "full-iso", "long-iso", "iso", NULL
267 static enum time_style const time_style_types[] =
269 full_iso_time_style, long_iso_time_style, iso_time_style
271 ARGMATCH_VERIFY (time_style_args, time_style_types);
273 void
274 usage (int status)
276 if (status != EXIT_SUCCESS)
277 emit_try_help ();
278 else
280 printf (_("\
281 Usage: %s [OPTION]... [FILE]...\n\
282 or: %s [OPTION]... --files0-from=F\n\
283 "), program_name, program_name);
284 fputs (_("\
285 Summarize disk usage of the set of FILEs, recursively for directories.\n\
286 "), stdout);
288 emit_mandatory_arg_note ();
290 fputs (_("\
291 -0, --null end each output line with NUL, not newline\n\
292 -a, --all write counts for all files, not just directories\n\
293 --apparent-size print apparent sizes, rather than disk usage; although\
295 the apparent size is usually smaller, it may be\n\
296 larger due to holes in ('sparse') files, internal\n\
297 fragmentation, indirect blocks, and the like\n\
298 "), stdout);
299 fputs (_("\
300 -B, --block-size=SIZE scale sizes by SIZE before printing them; e.g.,\n\
301 '-BM' prints sizes in units of 1,048,576 bytes;\n\
302 see SIZE format below\n\
303 -b, --bytes equivalent to '--apparent-size --block-size=1'\n\
304 -c, --total produce a grand total\n\
305 -D, --dereference-args dereference only symlinks that are listed on the\n\
306 command line\n\
307 -d, --max-depth=N print the total for a directory (or file, with --all)\n\
308 only if it is N or fewer levels below the command\n\
309 line argument; --max-depth=0 is the same as\n\
310 --summarize\n\
311 "), stdout);
312 fputs (_("\
313 --files0-from=F summarize disk usage of the\n\
314 NUL-terminated file names specified in file F;\n\
315 if F is -, then read names from standard input\n\
316 -H equivalent to --dereference-args (-D)\n\
317 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\
319 --inodes list inode usage information instead of block usage\n\
320 "), stdout);
321 fputs (_("\
322 -k like --block-size=1K\n\
323 -L, --dereference dereference all symbolic links\n\
324 -l, --count-links count sizes many times if hard linked\n\
325 -m like --block-size=1M\n\
326 "), stdout);
327 fputs (_("\
328 -P, --no-dereference don't follow any symbolic links (this is the default)\n\
329 -S, --separate-dirs for directories do not include size of subdirectories\n\
330 --si like -h, but use powers of 1000 not 1024\n\
331 -s, --summarize display only a total for each argument\n\
332 "), stdout);
333 fputs (_("\
334 -t, --threshold=SIZE exclude entries smaller than SIZE if positive,\n\
335 or entries greater than SIZE if negative\n\
336 --time show time of the last modification of any file in the\n\
337 directory, or any of its subdirectories\n\
338 --time=WORD show time as WORD instead of modification time:\n\
339 atime, access, use, ctime or status\n\
340 --time-style=STYLE show times using STYLE, which can be:\n\
341 full-iso, long-iso, iso, or +FORMAT;\n\
342 FORMAT is interpreted like in 'date'\n\
343 "), stdout);
344 fputs (_("\
345 -X, --exclude-from=FILE exclude files that match any pattern in FILE\n\
346 --exclude=PATTERN exclude files that match PATTERN\n\
347 -x, --one-file-system skip directories on different file systems\n\
348 "), stdout);
349 fputs (HELP_OPTION_DESCRIPTION, stdout);
350 fputs (VERSION_OPTION_DESCRIPTION, stdout);
351 emit_blocksize_note ("DU");
352 emit_size_note ();
353 emit_ancillary_info (PROGRAM_NAME);
355 exit (status);
358 /* Try to insert the INO/DEV pair into DI_SET.
359 Return true if the pair is successfully inserted,
360 false if the pair was already there. */
361 static bool
362 hash_ins (struct di_set *di_set, ino_t ino, dev_t dev)
364 int inserted = di_set_insert (di_set, dev, ino);
365 if (inserted < 0)
366 xalloc_die ();
367 return inserted;
370 /* FIXME: this code is nearly identical to code in date.c */
371 /* Display the date and time in WHEN according to the format specified
372 in FORMAT. */
374 static void
375 show_date (const char *format, struct timespec when)
377 struct tm *tm = localtime (&when.tv_sec);
378 if (! tm)
380 char buf[INT_BUFSIZE_BOUND (intmax_t)];
381 char *when_str = timetostr (when.tv_sec, buf);
382 error (0, 0, _("time %s is out of range"), quote (when_str));
383 fputs (when_str, stdout);
384 return;
387 fprintftime (stdout, format, tm, 0, when.tv_nsec);
390 /* Print N_BYTES. Convert it to a readable value before printing. */
392 static void
393 print_only_size (uintmax_t n_bytes)
395 char buf[LONGEST_HUMAN_READABLE + 1];
396 fputs ((n_bytes == UINTMAX_MAX
397 ? _("Infinity")
398 : human_readable (n_bytes, buf, human_output_opts,
399 1, output_block_size)),
400 stdout);
403 /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */
405 static void
406 print_size (const struct duinfo *pdui, const char *string)
408 print_only_size (opt_inodes
409 ? pdui->inodes
410 : pdui->size);
412 if (opt_time)
414 putchar ('\t');
415 show_date (time_format, pdui->tmax);
417 printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
418 fflush (stdout);
421 /* Fill the di_mnt set with local mount point dev/ino pairs. */
423 static void
424 fill_mount_table (void)
426 struct mount_entry *mnt_ent = read_file_system_list (false);
427 while (mnt_ent)
429 struct mount_entry *mnt_free;
430 if (!mnt_ent->me_remote && !mnt_ent->me_dummy)
432 struct stat buf;
433 if (!stat (mnt_ent->me_mountdir, &buf))
434 hash_ins (di_mnt, buf.st_ino, buf.st_dev);
435 else
437 /* Ignore stat failure. False positives are too common.
438 E.g., "Permission denied" on /run/user/<name>/gvfs. */
442 mnt_free = mnt_ent;
443 mnt_ent = mnt_ent->me_next;
444 free_mount_entry (mnt_free);
448 /* This function checks whether any of the directories in the cycle that
449 fts detected is a mount point. */
451 static bool
452 mount_point_in_fts_cycle (FTSENT const *ent)
454 FTSENT const *cycle_ent = ent->fts_cycle;
456 if (!di_mnt)
458 /* Initialize the set of dev,inode pairs. */
459 di_mnt = di_set_alloc ();
460 if (!di_mnt)
461 xalloc_die ();
463 fill_mount_table ();
466 while (ent && ent != cycle_ent)
468 if (di_set_lookup (di_mnt, ent->fts_statp->st_dev,
469 ent->fts_statp->st_ino) > 0)
471 return true;
473 ent = ent->fts_parent;
476 return false;
479 /* This function is called once for every file system object that fts
480 encounters. fts does a depth-first traversal. This function knows
481 that and accumulates per-directory totals based on changes in
482 the depth of the current entry. It returns true on success. */
484 static bool
485 process_file (FTS *fts, FTSENT *ent)
487 bool ok = true;
488 struct duinfo dui;
489 struct duinfo dui_to_print;
490 size_t level;
491 static size_t n_alloc;
492 /* First element of the structure contains:
493 The sum of the st_size values of all entries in the single directory
494 at the corresponding level. Although this does include the st_size
495 corresponding to each subdirectory, it does not include the size of
496 any file in a subdirectory. Also corresponding last modified date.
497 Second element of the structure contains:
498 The sum of the sizes of all entries in the hierarchy at or below the
499 directory at the specified level. */
500 static struct dulevel *dulvl;
502 const char *file = ent->fts_path;
503 const struct stat *sb = ent->fts_statp;
504 int info = ent->fts_info;
506 if (info == FTS_DNR)
508 /* An error occurred, but the size is known, so count it. */
509 error (0, ent->fts_errno, _("cannot read directory %s"), quoteaf (file));
510 ok = false;
512 else if (info != FTS_DP)
514 bool excluded = excluded_file_name (exclude, file);
515 if (! excluded)
517 /* Make the stat buffer *SB valid, or fail noisily. */
519 if (info == FTS_NSOK)
521 fts_set (fts, ent, FTS_AGAIN);
522 FTSENT const *e = fts_read (fts);
523 assert (e == ent);
524 info = ent->fts_info;
527 if (info == FTS_NS || info == FTS_SLNONE)
529 error (0, ent->fts_errno, _("cannot access %s"), quoteaf (file));
530 return false;
533 /* The --one-file-system (-x) option cannot exclude anything
534 specified on the command-line. By definition, it can exclude
535 a file or directory only when its device number is different
536 from that of its just-processed parent directory, and du does
537 not process the parent of a command-line argument. */
538 if (fts->fts_options & FTS_XDEV
539 && FTS_ROOTLEVEL < ent->fts_level
540 && fts->fts_dev != sb->st_dev)
541 excluded = true;
544 if (excluded
545 || (! opt_count_all
546 && (hash_all || (! S_ISDIR (sb->st_mode) && 1 < sb->st_nlink))
547 && ! hash_ins (di_files, sb->st_ino, sb->st_dev)))
549 /* If ignoring a directory in preorder, skip its children.
550 Ignore the next fts_read output too, as it's a postorder
551 visit to the same directory. */
552 if (info == FTS_D)
554 fts_set (fts, ent, FTS_SKIP);
555 FTSENT const *e = fts_read (fts);
556 assert (e == ent);
559 return true;
562 switch (info)
564 case FTS_D:
565 return true;
567 case FTS_ERR:
568 /* An error occurred, but the size is known, so count it. */
569 error (0, ent->fts_errno, "%s", quotef (file));
570 ok = false;
571 break;
573 case FTS_DC:
574 /* If not following symlinks and not a (bind) mount point. */
575 if (cycle_warning_required (fts, ent)
576 && ! mount_point_in_fts_cycle (ent))
578 emit_cycle_warning (file);
579 return false;
581 return true;
585 duinfo_set (&dui,
586 (apparent_size
587 ? MAX (0, sb->st_size)
588 : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
589 (time_type == time_mtime ? get_stat_mtime (sb)
590 : time_type == time_atime ? get_stat_atime (sb)
591 : get_stat_ctime (sb)));
593 level = ent->fts_level;
594 dui_to_print = dui;
596 if (n_alloc == 0)
598 n_alloc = level + 10;
599 dulvl = xcalloc (n_alloc, sizeof *dulvl);
601 else
603 if (level == prev_level)
605 /* This is usually the most common case. Do nothing. */
607 else if (level > prev_level)
609 /* Descending the hierarchy.
610 Clear the accumulators for *all* levels between prev_level
611 and the current one. The depth may change dramatically,
612 e.g., from 1 to 10. */
613 size_t i;
615 if (n_alloc <= level)
617 dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
618 n_alloc = level * 2;
621 for (i = prev_level + 1; i <= level; i++)
623 duinfo_init (&dulvl[i].ent);
624 duinfo_init (&dulvl[i].subdir);
627 else /* level < prev_level */
629 /* Ascending the hierarchy.
630 Process a directory only after all entries in that
631 directory have been processed. When the depth decreases,
632 propagate sums from the children (prev_level) to the parent.
633 Here, the current level is always one smaller than the
634 previous one. */
635 assert (level == prev_level - 1);
636 duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
637 if (!opt_separate_dirs)
638 duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
639 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
640 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
644 prev_level = level;
646 /* Let the size of a directory entry contribute to the total for the
647 containing directory, unless --separate-dirs (-S) is specified. */
648 if (! (opt_separate_dirs && IS_DIR_TYPE (info)))
649 duinfo_add (&dulvl[level].ent, &dui);
651 /* Even if this directory is unreadable or we can't chdir into it,
652 do let its size contribute to the total. */
653 duinfo_add (&tot_dui, &dui);
655 if ((IS_DIR_TYPE (info) && level <= max_depth)
656 || (opt_all && level <= max_depth)
657 || level == 0)
659 /* Print or elide this entry according to the --threshold option. */
660 uintmax_t v = opt_inodes ? dui_to_print.inodes : dui_to_print.size;
661 if (opt_threshold < 0
662 ? v <= -opt_threshold
663 : v >= opt_threshold)
664 print_size (&dui_to_print, file);
667 return ok;
670 /* Recursively print the sizes of the directories (and, if selected, files)
671 named in FILES, the last entry of which is NULL.
672 BIT_FLAGS controls how fts works.
673 Return true if successful. */
675 static bool
676 du_files (char **files, int bit_flags)
678 bool ok = true;
680 if (*files)
682 FTS *fts = xfts_open (files, bit_flags, NULL);
684 while (1)
686 FTSENT *ent;
688 ent = fts_read (fts);
689 if (ent == NULL)
691 if (errno != 0)
693 error (0, errno, _("fts_read failed: %s"),
694 quotef (fts->fts_path));
695 ok = false;
698 /* When exiting this loop early, be careful to reset the
699 global, prev_level, used in process_file. Otherwise, its
700 (level == prev_level - 1) assertion could fail. */
701 prev_level = 0;
702 break;
704 FTS_CROSS_CHECK (fts);
706 ok &= process_file (fts, ent);
709 if (fts_close (fts) != 0)
711 error (0, errno, _("fts_close failed"));
712 ok = false;
716 return ok;
720 main (int argc, char **argv)
722 char *cwd_only[2];
723 bool max_depth_specified = false;
724 bool ok = true;
725 char *files_from = NULL;
727 /* Bit flags that control how fts works. */
728 int bit_flags = FTS_NOSTAT;
730 /* Select one of the three FTS_ options that control if/when
731 to follow a symlink. */
732 int symlink_deref_bits = FTS_PHYSICAL;
734 /* If true, display only a total for each argument. */
735 bool opt_summarize_only = false;
737 cwd_only[0] = bad_cast (".");
738 cwd_only[1] = NULL;
740 initialize_main (&argc, &argv);
741 set_program_name (argv[0]);
742 setlocale (LC_ALL, "");
743 bindtextdomain (PACKAGE, LOCALEDIR);
744 textdomain (PACKAGE);
746 atexit (close_stdout);
748 exclude = new_exclude ();
750 human_options (getenv ("DU_BLOCK_SIZE"),
751 &human_output_opts, &output_block_size);
753 while (true)
755 int oi = -1;
756 int c = getopt_long (argc, argv, "0abd:chHklmst:xB:DLPSX:",
757 long_options, &oi);
758 if (c == -1)
759 break;
761 switch (c)
763 #if DU_DEBUG
764 case FTS_DEBUG:
765 fts_debug = true;
766 break;
767 #endif
769 case '0':
770 opt_nul_terminate_output = true;
771 break;
773 case 'a':
774 opt_all = true;
775 break;
777 case APPARENT_SIZE_OPTION:
778 apparent_size = true;
779 break;
781 case 'b':
782 apparent_size = true;
783 human_output_opts = 0;
784 output_block_size = 1;
785 break;
787 case 'c':
788 print_grand_total = true;
789 break;
791 case 'h':
792 human_output_opts = human_autoscale | human_SI | human_base_1024;
793 output_block_size = 1;
794 break;
796 case HUMAN_SI_OPTION:
797 human_output_opts = human_autoscale | human_SI;
798 output_block_size = 1;
799 break;
801 case 'k':
802 human_output_opts = 0;
803 output_block_size = 1024;
804 break;
806 case 'd': /* --max-depth=N */
808 unsigned long int tmp_ulong;
809 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
810 && tmp_ulong <= SIZE_MAX)
812 max_depth_specified = true;
813 max_depth = tmp_ulong;
815 else
817 error (0, 0, _("invalid maximum depth %s"),
818 quote (optarg));
819 ok = false;
822 break;
824 case 'm':
825 human_output_opts = 0;
826 output_block_size = 1024 * 1024;
827 break;
829 case 'l':
830 opt_count_all = true;
831 break;
833 case 's':
834 opt_summarize_only = true;
835 break;
837 case 't':
839 enum strtol_error e;
840 e = xstrtoimax (optarg, NULL, 0, &opt_threshold, "kKmMGTPEZY0");
841 if (e != LONGINT_OK)
842 xstrtol_fatal (e, oi, c, long_options, optarg);
843 if (opt_threshold == 0 && *optarg == '-')
845 /* Do not allow -0, as this wouldn't make sense anyway. */
846 error (EXIT_FAILURE, 0, _("invalid --threshold argument '-0'"));
849 break;
851 case 'x':
852 bit_flags |= FTS_XDEV;
853 break;
855 case 'B':
857 enum strtol_error e = human_options (optarg, &human_output_opts,
858 &output_block_size);
859 if (e != LONGINT_OK)
860 xstrtol_fatal (e, oi, c, long_options, optarg);
862 break;
864 case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */
865 case 'D':
866 symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
867 break;
869 case 'L': /* --dereference */
870 symlink_deref_bits = FTS_LOGICAL;
871 break;
873 case 'P': /* --no-dereference */
874 symlink_deref_bits = FTS_PHYSICAL;
875 break;
877 case 'S':
878 opt_separate_dirs = true;
879 break;
881 case 'X':
882 if (add_exclude_file (add_exclude, exclude, optarg,
883 EXCLUDE_WILDCARDS, '\n'))
885 error (0, errno, "%s", quotef (optarg));
886 ok = false;
888 break;
890 case FILES0_FROM_OPTION:
891 files_from = optarg;
892 break;
894 case EXCLUDE_OPTION:
895 add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
896 break;
898 case INODES_OPTION:
899 opt_inodes = true;
900 break;
902 case TIME_OPTION:
903 opt_time = true;
904 time_type =
905 (optarg
906 ? XARGMATCH ("--time", optarg, time_args, time_types)
907 : time_mtime);
908 break;
910 case TIME_STYLE_OPTION:
911 time_style = optarg;
912 break;
914 case_GETOPT_HELP_CHAR;
916 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
918 default:
919 ok = false;
923 if (!ok)
924 usage (EXIT_FAILURE);
926 if (opt_all && opt_summarize_only)
928 error (0, 0, _("cannot both summarize and show all entries"));
929 usage (EXIT_FAILURE);
932 if (opt_summarize_only && max_depth_specified && max_depth == 0)
934 error (0, 0,
935 _("warning: summarizing is the same as using --max-depth=0"));
938 if (opt_summarize_only && max_depth_specified && max_depth != 0)
940 unsigned long int d = max_depth;
941 error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
942 usage (EXIT_FAILURE);
945 if (opt_summarize_only)
946 max_depth = 0;
948 if (opt_inodes)
950 if (apparent_size)
952 error (0, 0, _("warning: options --apparent-size and -b are "
953 "ineffective with --inodes"));
955 output_block_size = 1;
958 /* Process time style if printing last times. */
959 if (opt_time)
961 if (! time_style)
963 time_style = getenv ("TIME_STYLE");
965 /* Ignore TIMESTYLE="locale", for compatibility with ls. */
966 if (! time_style || STREQ (time_style, "locale"))
967 time_style = "long-iso";
968 else if (*time_style == '+')
970 /* Ignore anything after a newline, for compatibility
971 with ls. */
972 char *p = strchr (time_style, '\n');
973 if (p)
974 *p = '\0';
976 else
978 /* Ignore "posix-" prefix, for compatibility with ls. */
979 static char const posix_prefix[] = "posix-";
980 static const size_t prefix_len = sizeof posix_prefix - 1;
981 while (STREQ_LEN (time_style, posix_prefix, prefix_len))
982 time_style += prefix_len;
986 if (*time_style == '+')
987 time_format = time_style + 1;
988 else
990 switch (XARGMATCH ("time style", time_style,
991 time_style_args, time_style_types))
993 case full_iso_time_style:
994 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
995 break;
997 case long_iso_time_style:
998 time_format = "%Y-%m-%d %H:%M";
999 break;
1001 case iso_time_style:
1002 time_format = "%Y-%m-%d";
1003 break;
1008 struct argv_iterator *ai;
1009 if (files_from)
1011 /* When using --files0-from=F, you may not specify any files
1012 on the command-line. */
1013 if (optind < argc)
1015 error (0, 0, _("extra operand %s"), quote (argv[optind]));
1016 fprintf (stderr, "%s\n",
1017 _("file operands cannot be combined with --files0-from"));
1018 usage (EXIT_FAILURE);
1021 if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
1022 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
1023 quoteaf (files_from));
1025 ai = argv_iter_init_stream (stdin);
1027 /* It's not easy here to count the arguments, so assume the
1028 worst. */
1029 hash_all = true;
1031 else
1033 char **files = (optind < argc ? argv + optind : cwd_only);
1034 ai = argv_iter_init_argv (files);
1036 /* Hash all dev,ino pairs if there are multiple arguments, or if
1037 following non-command-line symlinks, because in either case a
1038 file with just one hard link might be seen more than once. */
1039 hash_all = (optind + 1 < argc || symlink_deref_bits == FTS_LOGICAL);
1042 if (!ai)
1043 xalloc_die ();
1045 /* Initialize the set of dev,inode pairs. */
1046 di_files = di_set_alloc ();
1047 if (!di_files)
1048 xalloc_die ();
1050 /* If not hashing everything, process_file won't find cycles on its
1051 own, so ask fts_read to check for them accurately. */
1052 if (opt_count_all || ! hash_all)
1053 bit_flags |= FTS_TIGHT_CYCLE_CHECK;
1055 bit_flags |= symlink_deref_bits;
1056 static char *temp_argv[] = { NULL, NULL };
1058 while (true)
1060 bool skip_file = false;
1061 enum argv_iter_err ai_err;
1062 char *file_name = argv_iter (ai, &ai_err);
1063 if (!file_name)
1065 switch (ai_err)
1067 case AI_ERR_EOF:
1068 goto argv_iter_done;
1069 case AI_ERR_READ:
1070 error (0, errno, _("%s: read error"),
1071 quotef (files_from));
1072 ok = false;
1073 goto argv_iter_done;
1074 case AI_ERR_MEM:
1075 xalloc_die ();
1076 default:
1077 assert (!"unexpected error code from argv_iter");
1080 if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-"))
1082 /* Give a better diagnostic in an unusual case:
1083 printf - | du --files0-from=- */
1084 error (0, 0, _("when reading file names from stdin, "
1085 "no file name of %s allowed"),
1086 quoteaf (file_name));
1087 skip_file = true;
1090 /* Report and skip any empty file names before invoking fts.
1091 This works around a glitch in fts, which fails immediately
1092 (without looking at the other file names) when given an empty
1093 file name. */
1094 if (!file_name[0])
1096 /* Diagnose a zero-length file name. When it's one
1097 among many, knowing the record number may help.
1098 FIXME: currently print the record number only with
1099 --files0-from=FILE. Maybe do it for argv, too? */
1100 if (files_from == NULL)
1101 error (0, 0, "%s", _("invalid zero-length file name"));
1102 else
1104 /* Using the standard 'filename:line-number:' prefix here is
1105 not totally appropriate, since NUL is the separator, not NL,
1106 but it might be better than nothing. */
1107 unsigned long int file_number = argv_iter_n_args (ai);
1108 error (0, 0, "%s:%lu: %s", quotef (files_from),
1109 file_number, _("invalid zero-length file name"));
1111 skip_file = true;
1114 if (skip_file)
1115 ok = false;
1116 else
1118 temp_argv[0] = file_name;
1119 ok &= du_files (temp_argv, bit_flags);
1122 argv_iter_done:
1124 argv_iter_free (ai);
1125 di_set_free (di_files);
1126 if (di_mnt)
1127 di_set_free (di_mnt);
1129 if (files_from && (ferror (stdin) || fclose (stdin) != 0) && ok)
1130 error (EXIT_FAILURE, 0, _("error reading %s"), quoteaf (files_from));
1132 if (print_grand_total)
1133 print_size (&tot_dui, _("total"));
1135 return ok ? EXIT_SUCCESS : EXIT_FAILURE;