3 * Copyright 2012 Andre Renaud <andre@bluewatersys.com>
4 * Copyright 2012 Rob Landley <rob@landley.net>
6 * See http://opengroup.org/onlinepubs/9699919799/utilities/ls.html
8 USE_LS(NEWTOY(ls, USE_LS_COLOR("(color):;")"goACFHLRSacdfiklmnpqrstux1[-1Cglmnox][-cu][-ftS][-HL]", TOYFLAG_BIN|TOYFLAG_LOCALE))
14 usage: ls [-ACFHLRSacdfiklmnpqrstux1] [directory...]
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
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)
32 sorting (default is alphabetical):
33 -f unsorted -r reverse -t timestamp -S size
40 usage: ls --color[=auto]
42 --color device=yellow symlink=turquoise/red dir=blue socket=purple
43 files: exe=green suid=red suidfile=redback stickydir=greenback
44 =auto means detect if output is a tty.
50 // test sst output (suid/sticky in ls flaglist)
52 // ls -lR starts .: then ./subdir:
57 struct dirtree *files;
59 unsigned screen_width;
61 char uid_buf[12], gid_buf[12];
64 // Does two things: 1) Returns wcwidth(utf8) version of strlen,
65 // 2) replaces unprintable characters input string with '?' wildcard char.
68 int total = 0, width, len;
71 if (!CFG_TOYBOX_I18N) {
73 if (toys.optflags & FLAG_q) for (; *s; s++) if (!isprint(*s)) *s = '?';
75 len = mbrtowc(&c, s, MB_CUR_MAX, 0);
76 if (len < 1 || (width = wcwidth(c)) < 0) {
78 if (toys.optflags & FLAG_q) *s = '?';
89 void dlist_to_dirtree(struct dirtree *parent)
91 // Turn double_list into dirtree
92 struct dirtree *dt = parent->child;
94 dt->parent->next = NULL;
102 static char endtype(struct stat *st)
104 mode_t mode = st->st_mode;
105 if ((toys.optflags&(FLAG_F|FLAG_p)) && S_ISDIR(mode)) return '/';
106 if (toys.optflags & FLAG_F) {
107 if (S_ISLNK(mode)) return '@';
108 if (S_ISREG(mode) && (mode&0111)) return '*';
109 if (S_ISFIFO(mode)) return '|';
110 if (S_ISSOCK(mode)) return '=';
115 static char *getusername(uid_t uid)
117 struct passwd *pw = getpwuid(uid);
119 sprintf(TT.uid_buf, "%u", (unsigned)uid);
120 return pw ? pw->pw_name : TT.uid_buf;
123 static char *getgroupname(gid_t gid)
125 struct group *gr = getgrgid(gid);
127 sprintf(TT.gid_buf, "%u", (unsigned)gid);
128 return gr ? gr->gr_name : TT.gid_buf;
131 // Figure out size of printable entry fields for display indent/wrap
133 static void entrylen(struct dirtree *dt, unsigned *len)
135 struct stat *st = &(dt->st);
136 unsigned flags = toys.optflags;
138 *len = strwidth(dt->name);
139 if (endtype(st)) ++*len;
140 if (flags & FLAG_m) ++*len;
142 if (flags & FLAG_i) *len += (len[1] = numlen(st->st_ino));
143 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
144 unsigned fn = flags & FLAG_n;
145 len[2] = numlen(st->st_nlink);
146 len[3] = fn ? snprintf(0, 0, "%u", (unsigned)st->st_uid)
147 : strwidth(getusername(st->st_uid));
148 len[4] = fn ? snprintf(0, 0, "%u", (unsigned)st->st_gid)
149 : strwidth(getgroupname(st->st_gid));
150 if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
151 // cheating slightly here: assuming minor is always 3 digits to avoid
152 // tracking another column
153 len[5] = numlen(major(st->st_rdev))+5;
154 } else len[5] = numlen(st->st_size);
156 if (flags & FLAG_s) *len += (len[6] = numlen(st->st_blocks));
159 static int compare(void *a, void *b)
161 struct dirtree *dta = *(struct dirtree **)a;
162 struct dirtree *dtb = *(struct dirtree **)b;
163 int ret = 0, reverse = (toys.optflags & FLAG_r) ? -1 : 1;
165 if (toys.optflags & FLAG_S) {
166 if (dta->st.st_size > dtb->st.st_size) ret = -1;
167 else if (dta->st.st_size < dtb->st.st_size) ret = 1;
169 if (toys.optflags & FLAG_t) {
170 if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
171 else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
173 if (!ret) ret = strcmp(dta->name, dtb->name);
174 return ret * reverse;
177 // callback from dirtree_recurse() determining how to handle this entry.
179 static int filter(struct dirtree *new)
181 int flags = toys.optflags;
183 // Special case to handle enormous dirs without running out of memory.
184 if (flags == (FLAG_1|FLAG_f)) {
185 xprintf("%s\n", new->name);
189 if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
190 if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
191 if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
193 if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
194 if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
196 return dirtree_notdotdot(new) & DIRTREE_SAVE;
199 // For column view, calculate horizontal position (for padding) and return
200 // index of next entry to display.
202 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
203 unsigned columns, unsigned *xpos)
205 unsigned long transition;
206 unsigned height, widecols;
208 // Horizontal sort is easy
209 if (!(toys.optflags & FLAG_C)) {
210 *xpos = ul % columns;
216 // For -x, calculate height of display, rounded up
217 height = (dtlen+columns-1)/columns;
219 // Sanity check: does wrapping render this column count impossible
220 // due to the right edge wrapping eating a whole row?
221 if (height*columns - dtlen >= height) {
226 // Uneven rounding goes along right edge
227 widecols = dtlen % height;
228 if (!widecols) widecols = height;
229 transition = widecols * columns;
230 if (ul < transition) {
231 *xpos = ul % columns;
232 return (*xpos*height) + (ul/columns);
236 *xpos = ul % (columns-1);
238 return (*xpos*height) + widecols + (ul/(columns-1));
241 int color_from_mode(mode_t mode)
245 if (S_ISDIR(mode)) color = 256+34;
246 else if (S_ISLNK(mode)) color = 256+36;
247 else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
248 else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
249 else if (S_ISFIFO(mode)) color = 33;
250 else if (S_ISSOCK(mode)) color = 256+35;
255 // Display a list of dirtree entries, according to current format
256 // Output types -1, -l, -C, or stream
258 static void listfiles(int dirfd, struct dirtree *indir)
260 struct dirtree *dt, **sort = 0;
261 unsigned long dtlen = 0, ul = 0;
262 unsigned width, flags = toys.optflags, totals[7], len[7],
263 *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
265 memset(totals, 0, sizeof(totals));
267 // Silently descend into single directory listed by itself on command line.
268 // In this case only show dirname/total header when given -R.
269 if (!indir->parent) {
270 if (!(dt = indir->child)) return;
271 if (S_ISDIR(dt->st.st_mode) && !dt->next && !(flags & FLAG_d)) {
273 listfiles(open(dt->name, 0), dt);
277 // Read directory contents. We dup() the fd because this will close it.
278 indir->data = dup(dirfd);
279 dirtree_recurse(indir, filter, (flags&FLAG_L) ? DIRTREE_SYMFOLLOW : 0);
282 // Copy linked list to array and sort it. Directories go in array because
283 // we visit them in sorted order.
286 for (dt = indir->child; dt; dt = dt->next) {
287 if (sort) sort[dtlen] = dt;
291 sort = xmalloc(dtlen * sizeof(void *));
296 // Label directory if not top of tree, or if -R
297 if (indir->parent && (!indir->extra || (flags & FLAG_R)))
299 char *path = dirtree_path(indir, 0);
301 if (TT.nl_title++) xputc('\n');
302 xprintf("%s:\n", path);
306 if (!(flags & FLAG_f)) qsort(sort, dtlen, sizeof(void *), (void *)compare);
308 // Find largest entry in each field for display alignment
309 if (flags & (FLAG_C|FLAG_x)) {
311 // columns can't be more than toybuf can hold, or more than files,
312 // or > 1/2 screen width (one char filename, one space).
313 if (columns > TT.screen_width/2) columns = TT.screen_width/2;
314 if (columns > dtlen) columns = dtlen;
316 // Try to fit as many columns as we can, dropping down by one each time
317 for (;columns > 1; columns--) {
318 unsigned c, totlen = columns;
320 memset(colsizes, 0, columns*sizeof(unsigned));
321 for (ul=0; ul<dtlen; ul++) {
322 entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
323 if (c == columns) break;
324 // Does this put us over budget?
325 if (*len > colsizes[c]) {
326 totlen += *len-colsizes[c];
328 if (totlen > TT.screen_width) break;
331 // If it fit, stop here
332 if (ul == dtlen) break;
334 } else if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) {
335 unsigned long blocks = 0;
337 for (ul = 0; ul<dtlen; ul++)
339 entrylen(sort[ul], len);
340 for (width=0; width<6; width++)
341 if (len[width] > totals[width]) totals[width] = len[width];
342 blocks += sort[ul]->st.st_blocks;
345 if (indir->parent) xprintf("total %lu\n", blocks);
348 // Loop through again to produce output.
349 memset(toybuf, ' ', 256);
351 for (ul = 0; ul<dtlen; ul++) {
352 unsigned curcol, color = 0;
353 unsigned long next = next_column(ul, dtlen, columns, &curcol);
354 struct stat *st = &(sort[next]->st);
355 mode_t mode = st->st_mode;
356 char et = endtype(st);
358 // Skip directories at the top of the tree when -d isn't set
359 if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
362 // Handle padding and wrapping for display purposes
363 entrylen(sort[next], len);
365 if (flags & FLAG_m) xputc(',');
366 if (flags & (FLAG_C|FLAG_x)) {
367 if (!curcol) xputc('\n');
368 } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
378 if (flags & FLAG_i) xprintf("% *lu ", len[1], (unsigned long)st->st_ino);
379 if (flags & FLAG_s) xprintf("% *lu ", len[6], (unsigned long)st->st_blocks);
381 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
383 char perm[11], thyme[64], *usr, *upad, *grp, *grpad;
385 mode_to_string(mode, perm);
387 if (flags&FLAG_o) grp = grpad = toybuf+256;
389 if (flags&FLAG_n) sprintf(grp = thyme, "%u", (unsigned)st->st_gid);
390 else strwidth(grp = getgroupname(st->st_gid));
391 grpad = toybuf+256-(totals[4]-len[4]);
394 if (flags&FLAG_g) usr = upad = toybuf+256;
396 upad = toybuf+255-(totals[3]-len[3]);
397 if (flags&FLAG_n) sprintf(usr = TT.uid_buf, "%u", (unsigned)st->st_uid);
398 else strwidth(usr = getusername(st->st_uid));
401 // Coerce the st types into something we know we can print.
402 printf("%s% *ld %s%s%s%s", perm, totals[2]+1, (long)st->st_nlink,
403 usr, upad, grp, grpad);
405 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
406 printf("% *d,% 4d", totals[5]-4, major(st->st_rdev),minor(st->st_rdev));
407 else printf("% *"PRId64, totals[5]+1, (int64_t)st->st_size);
409 tm = localtime(&(st->st_mtime));
410 strftime(thyme, sizeof(thyme), "%F %H:%M", tm);
411 xprintf(" %s ", thyme);
414 if (flags & FLAG_color) {
415 color = color_from_mode(st->st_mode);
416 if (color) printf("\033[%d;%dm", color>>8, color&255);
419 if (flags & FLAG_q) {
421 for (p=sort[next]->name; *p; p++) fputc(isprint(*p) ? *p : '?', stdout);
422 } else xprintf("%s", sort[next]->name);
423 if (color) xprintf("\033[0m");
425 if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
427 if (flags & FLAG_color) {
430 if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
431 else color = color_from_mode(st2.st_mode);
433 if (color) printf("\033[%d;%dm", color>>8, color&255);
436 printf("%s", sort[next]->symlink);
437 if (color) printf("\033[0m");
443 if (flags & (FLAG_C|FLAG_x)) {
444 curcol = colsizes[curcol] - *len;
445 if (curcol < 255) xprintf("%s", toybuf+255-curcol);
449 if (width) xputc('\n');
451 // Free directory entries, recursing first if necessary.
453 for (ul = 0; ul<dtlen; free(sort[ul++])) {
454 if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)
455 || !dirtree_notdotdot(sort[ul])) continue;
457 // Recurse into dirs if at top of the tree or given -R
458 if (!indir->parent || (flags & FLAG_R))
459 listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
462 if (dirfd != AT_FDCWD) close(dirfd);
467 char **s, *noargs[] = {".", 0};
470 TT.screen_width = 80;
471 terminal_size(&TT.screen_width, NULL);
472 if (TT.screen_width<2) TT.screen_width = 2;
474 // Do we have an implied -1
476 toys.optflags |= FLAG_1;
477 if (TT.color) toys.optflags ^= FLAG_color;
478 } else if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g))
479 toys.optflags |= FLAG_1;
480 else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
481 // The optflags parsing infrastructure should really do this for us,
482 // but currently it has "switch off when this is set", so "-dR" and "-Rd"
483 // behave differently
484 if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
486 // Iterate through command line arguments, collecting directories and files.
487 // Non-absolute paths are relative to current directory.
488 TT.files = dirtree_add_node(0, 0, 0);
489 for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
490 dt = dirtree_add_node(0, *s,
491 (toys.optflags & (FLAG_L|FLAG_H|FLAG_l))^FLAG_l);
498 // Typecast means double_list->prev temporarirly goes in dirtree->parent
499 dlist_add_nomalloc((void *)&TT.files->child, (struct double_list *)dt);
502 // Turn double_list into dirtree
503 dlist_to_dirtree(TT.files);
505 // Display the files we collected
506 listfiles(AT_FDCWD, TT.files);
508 if (CFG_TOYBOX_FREE) free(TT.files);