OSDN Git Service

Condense ls help text.
[android-x86/external-toybox.git] / toys / posix / ls.c
1 /* ls.c - list files
2  *
3  * Copyright 2012 Andre Renaud <andre@bluewatersys.com>
4  * Copyright 2012 Rob Landley <rob@landley.net>
5  *
6  * See http://opengroup.org/onlinepubs/9699919799/utilities/ls.html
7
8 USE_LS(NEWTOY(ls, "goACFHLRSacdfiklmnpqrstux1[-1Cglmnox][-cu][-ftS][-HL]", TOYFLAG_BIN))
9
10 config LS
11   bool "ls"
12   default y
13   help
14     usage: ls [-ACFHLRSacdfiklmnpqrstux1] [directory...]
15     list files
16
17     what to show:
18     -a  all files including .hidden             -c  use ctime for timestamps
19     -d  directory, not contents                 -i  inode number
20     -k  block sizes in kilobytes                -p  put a '/' after dir names
21     -q  unprintable chars as '?'                -s  size (in blocks)
22     -u  use access time for timestamps          -A  list all files but . and ..
23     -H  follow command line symlinks            -L  follow symlinks
24     -R  recursively list files in subdirs       -F  append /dir *exe @sym |FIFO
25
26     output formats:
27     -1  list one file per line                  -C  columns (sorted vertically)
28     -g  like -l but no owner                    -l  long (show full details)
29     -m  comma separated                         -n  like -l but numeric uid/gid
30     -o  like -l but no group                    -x  columns (horizontal sort)
31
32     sorting (default is alphabetical):
33     -f  unsorted        -r  reverse     -t  timestamp   -S  size
34 */
35
36 #define FOR_ls
37 #include "toys.h"
38
39 // test sst output (suid/sticky in ls flaglist)
40
41 // ls -lR starts .: then ./subdir:
42
43 GLOBALS(
44   struct dirtree *files;
45
46   unsigned screen_width;
47   int nl_title;
48
49   // group and user can make overlapping use of the utoa() buf, so move it
50   char uid_buf[12];
51 )
52
53 void dlist_to_dirtree(struct dirtree *parent)
54 {
55   // Turn double_list into dirtree
56   struct dirtree *dt = parent->child;
57   if (dt) {
58     dt->parent->next = NULL;
59     while (dt) {
60       dt->parent = parent;
61       dt = dt->next;
62     }
63   }
64 }
65
66 static char endtype(struct stat *st)
67 {
68   mode_t mode = st->st_mode;
69   if ((toys.optflags&(FLAG_F|FLAG_p)) && S_ISDIR(mode)) return '/';
70   if (toys.optflags & FLAG_F) {
71     if (S_ISLNK(mode)) return '@';
72     if (S_ISREG(mode) && (mode&0111)) return '*';
73     if (S_ISFIFO(mode)) return '|';
74     if (S_ISSOCK(mode)) return '=';
75   }
76   return 0;
77 }
78
79 static char *getusername(uid_t uid)
80 {
81   struct passwd *pw = getpwuid(uid);
82   utoa_to_buf(uid, TT.uid_buf, 12);
83   return pw ? pw->pw_name : TT.uid_buf;
84 }
85
86 static char *getgroupname(gid_t gid)
87 {
88   struct group *gr = getgrgid(gid);
89   return gr ? gr->gr_name : utoa(gid);
90 }
91
92 // Figure out size of printable entry fields for display indent/wrap
93
94 static void entrylen(struct dirtree *dt, unsigned *len)
95 {
96   struct stat *st = &(dt->st);
97   unsigned flags = toys.optflags;
98
99   *len = strlen(dt->name);
100   if (endtype(st)) ++*len;
101   if (flags & FLAG_m) ++*len;
102
103   if (flags & FLAG_i) *len += (len[1] = numlen(st->st_ino));
104   if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
105     unsigned fn = flags & FLAG_n;
106     len[2] = numlen(st->st_nlink);
107     len[3] = strlen(fn ? utoa(st->st_uid) : getusername(st->st_uid));
108     len[4] = strlen(fn ? utoa(st->st_gid) : getgroupname(st->st_gid));
109     len[5] = numlen(st->st_size);
110   }
111   if (flags & FLAG_s) *len += (len[6] = numlen(st->st_blocks));
112 }
113
114 static int compare(void *a, void *b)
115 {
116   struct dirtree *dta = *(struct dirtree **)a;
117   struct dirtree *dtb = *(struct dirtree **)b;
118   int ret = 0, reverse = (toys.optflags & FLAG_r) ? -1 : 1;
119
120   if (toys.optflags & FLAG_S) {
121     if (dta->st.st_size > dtb->st.st_size) ret = -1;
122     else if (dta->st.st_size < dtb->st.st_size) ret = 1;
123   }
124   if (toys.optflags & FLAG_t) {
125     if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
126     else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
127   }
128   if (!ret) ret = strcmp(dta->name, dtb->name);
129   return ret * reverse;
130 }
131
132 // callback from dirtree_recurse() determining how to handle this entry.
133
134 static int filter(struct dirtree *new)
135 {
136   int flags = toys.optflags;
137
138   // Special case to handle enormous dirs without running out of memory.
139   if (flags == (FLAG_1|FLAG_f)) {
140     xprintf("%s\n", new->name);
141     return 0;
142   }
143
144   if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
145   if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
146   if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
147
148   if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
149   if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
150
151   return dirtree_notdotdot(new) & DIRTREE_SAVE;
152 }
153
154 // For column view, calculate horizontal position (for padding) and return
155 // index of next entry to display.
156
157 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
158   unsigned columns, unsigned *xpos)
159 {
160   unsigned long transition;
161   unsigned height, widecols;
162
163   // Horizontal sort is easy
164   if (!(toys.optflags & FLAG_C)) {
165     *xpos = ul % columns;
166     return ul;
167   }
168
169   // vertical sort
170
171   // For -x, calculate height of display, rounded up
172   height = (dtlen+columns-1)/columns;
173
174   // Sanity check: does wrapping render this column count impossible
175   // due to the right edge wrapping eating a whole row?
176   if (height*columns - dtlen >= height) {
177     *xpos = columns;
178     return 0;
179   }
180
181   // Uneven rounding goes along right edge
182   widecols = dtlen % height;
183   if (!widecols) widecols = height;
184   transition = widecols * columns;
185   if (ul < transition) {
186     *xpos =  ul % columns;
187     return (*xpos*height) + (ul/columns);
188   }
189
190   ul -= transition;
191   *xpos = ul % (columns-1);
192
193   return (*xpos*height) + widecols + (ul/(columns-1));
194 }
195
196 // Display a list of dirtree entries, according to current format
197 // Output types -1, -l, -C, or stream
198
199 static void listfiles(int dirfd, struct dirtree *indir)
200 {
201   struct dirtree *dt, **sort = 0;
202   unsigned long dtlen = 0, ul = 0;
203   unsigned width, flags = toys.optflags, totals[7], len[7],
204     *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
205
206   memset(totals, 0, sizeof(totals));
207
208   // Silently descend into single directory listed by itself on command line.
209   // In this case only show dirname/total header when given -R.
210   if (!indir->parent) {
211     if (!(dt = indir->child)) return;
212     if (S_ISDIR(dt->st.st_mode) && !dt->next && !(flags & FLAG_d)) {
213       dt->extra = 1;
214       listfiles(open(dt->name, 0), dt);
215       return;
216     }
217   } else {
218     // Read directory contents. We dup() the fd because this will close it.
219     indir->data = dup(dirfd);
220     dirtree_recurse(indir, filter, (flags&FLAG_L));
221   }
222
223   // Copy linked list to array and sort it. Directories go in array because
224   // we visit them in sorted order.
225
226   for (;;) {
227     for (dt = indir->child; dt; dt = dt->next) {
228       if (sort) sort[dtlen] = dt;
229       dtlen++;
230     }
231     if (sort) break;
232     sort = xmalloc(dtlen * sizeof(void *));
233     dtlen = 0;
234     continue;
235   }
236
237   // Label directory if not top of tree, or if -R
238   if (indir->parent && (!indir->extra || (flags & FLAG_R)))
239   {
240     char *path = dirtree_path(indir, 0);
241
242     if (TT.nl_title++) xputc('\n');
243     xprintf("%s:\n", path);
244     free(path);
245   }
246
247   if (!(flags & FLAG_f)) qsort(sort, dtlen, sizeof(void *), (void *)compare);
248
249   // Find largest entry in each field for display alignment
250   if (flags & (FLAG_C|FLAG_x)) {
251
252     // columns can't be more than toybuf can hold, or more than files,
253     // or > 1/2 screen width (one char filename, one space).
254     if (columns > TT.screen_width/2) columns = TT.screen_width/2;
255     if (columns > dtlen) columns = dtlen;
256
257     // Try to fit as many columns as we can, dropping down by one each time
258     for (;columns > 1; columns--) {
259       unsigned c, totlen = columns;
260
261       memset(colsizes, 0, columns*sizeof(unsigned));
262       for (ul=0; ul<dtlen; ul++) {
263         entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
264         if (c == columns) break;
265         // Does this put us over budget?
266         if (*len > colsizes[c]) {
267           totlen += *len-colsizes[c];
268           colsizes[c] = *len;
269           if (totlen > TT.screen_width) break;
270         }
271       }
272       // If it fit, stop here
273       if (ul == dtlen) break;
274     }
275   } else if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) {
276     unsigned long blocks = 0;
277
278     for (ul = 0; ul<dtlen; ul++)
279     {
280       entrylen(sort[ul], len);
281       for (width=0; width<6; width++)
282         if (len[width] > totals[width]) totals[width] = len[width];
283       blocks += sort[ul]->st.st_blocks;
284     }
285
286     if (indir->parent) xprintf("total %lu\n", blocks);
287   }
288
289   // Loop through again to produce output.
290   memset(toybuf, ' ', 256);
291   width = 0;
292   for (ul = 0; ul<dtlen; ul++) {
293     unsigned curcol;
294     unsigned long next = next_column(ul, dtlen, columns, &curcol);
295     struct stat *st = &(sort[next]->st);
296     mode_t mode = st->st_mode;
297     char et = endtype(st);
298
299     // Skip directories at the top of the tree when -d isn't set
300     if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
301     TT.nl_title=1;
302
303     // Handle padding and wrapping for display purposes
304     entrylen(sort[next], len);
305     if (ul) {
306       if (flags & FLAG_m) xputc(',');
307       if (flags & (FLAG_C|FLAG_x)) {
308         if (!curcol) xputc('\n');
309       } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
310         xputc('\n');
311         width = 0;
312       } else {
313         xputc(' ');
314         width++;
315       }
316     }
317     width += *len;
318
319     if (flags & FLAG_i) xprintf("% *lu ", len[1], (unsigned long)st->st_ino);
320     if (flags & FLAG_s) xprintf("% *lu ", len[6], (unsigned long)st->st_blocks);
321
322     if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
323       struct tm *tm;
324       char perm[11], thyme[64], *usr, *upad, *grp, *grpad;
325
326       mode_to_string(mode, perm);
327
328       tm = localtime(&(st->st_mtime));
329       strftime(thyme, sizeof(thyme), "%F %H:%M", tm);
330
331       if (flags&FLAG_o) grp = grpad = toybuf+256;
332       else {
333         grp = (flags&FLAG_n) ? utoa(st->st_gid) : getgroupname(st->st_gid);
334         grpad = toybuf+256-(totals[4]-len[4]);
335       }
336
337       if (flags&FLAG_g) usr = upad = toybuf+256;
338       else {
339         upad = toybuf+255-(totals[3]-len[3]);
340         if (flags&FLAG_n) {
341           usr = TT.uid_buf;
342           utoa_to_buf(st->st_uid, TT.uid_buf, 12);
343         } else usr = getusername(st->st_uid);
344       }
345
346       // Coerce the st types into something we know we can print.
347       xprintf("%s% *ld %s%s%s%s% *"PRId64" %s ", perm, totals[2]+1,
348         (long)st->st_nlink, usr, upad, grp, grpad, totals[5]+1,
349         (int64_t)st->st_size, thyme);
350     }
351
352     if (flags & FLAG_q) {
353       char *p;
354       for (p=sort[next]->name; *p; p++) xputc(isprint(*p) ? *p : '?');
355     } else xprintf("%s", sort[next]->name);
356     if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode))
357       xprintf(" -> %s", sort[next]->symlink);
358
359     if (et) xputc(et);
360
361     // Pad columns
362     if (flags & (FLAG_C|FLAG_x)) {
363       curcol = colsizes[curcol] - *len;
364       if (curcol < 255) xprintf("%s", toybuf+255-curcol);
365     }
366   }
367
368   if (width) xputc('\n');
369
370   // Free directory entries, recursing first if necessary.
371
372   for (ul = 0; ul<dtlen; free(sort[ul++])) {
373     if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)
374       || !dirtree_notdotdot(sort[ul])) continue;
375
376     // Recurse into dirs if at top of the tree or given -R
377     if (!indir->parent || (flags & FLAG_R))
378       listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
379   }
380   free(sort);
381   if (dirfd != AT_FDCWD) close(indir->data);
382 }
383
384 void ls_main(void)
385 {
386   char **s, *noargs[] = {".", 0};
387   struct dirtree *dt;
388
389   // Do we have an implied -1
390   if (!isatty(1) || (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g)))
391     toys.optflags |= FLAG_1;
392   else {
393     TT.screen_width = 80;
394     terminal_size(&TT.screen_width, NULL);
395     if (TT.screen_width<2) TT.screen_width = 2;
396     if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
397   }
398   // The optflags parsing infrastructure should really do this for us,
399   // but currently it has "switch off when this is set", so "-dR" and "-Rd"
400   // behave differently
401   if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
402
403   // Iterate through command line arguments, collecting directories and files.
404   // Non-absolute paths are relative to current directory.
405   TT.files = dirtree_add_node(0, 0, 0);
406   for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
407     dt = dirtree_add_node(0, *s,
408       (toys.optflags & (FLAG_L|FLAG_H|FLAG_l))^FLAG_l);
409
410     if (!dt) {
411       toys.exitval = 1;
412       continue;
413     }
414
415     // Typecast means double_list->prev temporarirly goes in dirtree->parent
416     dlist_add_nomalloc((void *)&TT.files->child, (struct double_list *)dt);
417   }
418
419   // Turn double_list into dirtree
420   dlist_to_dirtree(TT.files);
421
422   // Display the files we collected
423   listfiles(AT_FDCWD, TT.files);
424
425   if (CFG_TOYBOX_FREE) free(TT.files);
426 }