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):;")"goACFHLR"USE_LS_SMACK("Z")"Sacdfiklmnpqrstux1[-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
38 depends on LS && TOYBOX_SMACK
49 usage: ls --color[=auto]
51 --color device=yellow symlink=turquoise/red dir=blue socket=purple
52 files: exe=green suid=red suidfile=redback stickydir=greenback
53 =auto means detect if output is a tty.
59 // test sst output (suid/sticky in ls flaglist)
61 // ls -lR starts .: then ./subdir:
66 struct dirtree *files;
68 unsigned screen_width;
70 char uid_buf[12], gid_buf[12];
73 // Does two things: 1) Returns wcwidth(utf8) version of strlen,
74 // 2) replaces unprintable characters input string with '?' wildcard char.
77 int total = 0, width, len;
80 if (!CFG_TOYBOX_I18N) {
82 if (toys.optflags & FLAG_q) for (; *s; s++) if (!isprint(*s)) *s = '?';
84 len = mbrtowc(&c, s, MB_CUR_MAX, 0);
85 if (len < 1 || (width = wcwidth(c)) < 0) {
87 if (toys.optflags & FLAG_q) *s = '?';
98 void dlist_to_dirtree(struct dirtree *parent)
100 // Turn double_list into dirtree
101 struct dirtree *dt = parent->child;
103 dt->parent->next = NULL;
111 static char endtype(struct stat *st)
113 mode_t mode = st->st_mode;
114 if ((toys.optflags&(FLAG_F|FLAG_p)) && S_ISDIR(mode)) return '/';
115 if (toys.optflags & FLAG_F) {
116 if (S_ISLNK(mode)) return '@';
117 if (S_ISREG(mode) && (mode&0111)) return '*';
118 if (S_ISFIFO(mode)) return '|';
119 if (S_ISSOCK(mode)) return '=';
124 static char *getusername(uid_t uid)
126 struct passwd *pw = getpwuid(uid);
128 sprintf(TT.uid_buf, "%u", (unsigned)uid);
129 return pw ? pw->pw_name : TT.uid_buf;
132 static char *getgroupname(gid_t gid)
134 struct group *gr = getgrgid(gid);
136 sprintf(TT.gid_buf, "%u", (unsigned)gid);
137 return gr ? gr->gr_name : TT.gid_buf;
140 static int numlen(long long ll)
142 return snprintf(0, 0, "%llu", ll);
145 // Figure out size of printable entry fields for display indent/wrap
147 static void entrylen(struct dirtree *dt, unsigned *len)
149 struct stat *st = &(dt->st);
150 unsigned flags = toys.optflags;
152 *len = strwidth(dt->name);
153 if (endtype(st)) ++*len;
154 if (flags & FLAG_m) ++*len;
156 len[1] = (flags & FLAG_i) ? numlen(st->st_ino) : 0;
157 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
158 unsigned fn = flags & FLAG_n;
159 len[2] = numlen(st->st_nlink);
160 len[3] = fn ? numlen(st->st_uid) : strwidth(getusername(st->st_uid));
161 len[4] = fn ? numlen(st->st_gid) : strwidth(getgroupname(st->st_gid));
162 if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
163 // cheating slightly here: assuming minor is always 3 digits to avoid
164 // tracking another column
165 len[5] = numlen(major(st->st_rdev))+5;
166 } else len[5] = numlen(st->st_size);
169 len[6] = (flags & FLAG_s) ? numlen(st->st_blocks) : 0;
171 if (CFG_LS_SMACK && (flags & FLAG_Z)) {
172 char *zpath = dirtree_path(dt, 0);
173 ssize_t zlen = lgetxattr(zpath, XATTR_NAME_SMACK, 0, 0);
175 len[7] = (zlen <= 0) || (zlen > SMACK_LABEL_LEN) ? 0 : (int)zlen;
180 static int compare(void *a, void *b)
182 struct dirtree *dta = *(struct dirtree **)a;
183 struct dirtree *dtb = *(struct dirtree **)b;
184 int ret = 0, reverse = (toys.optflags & FLAG_r) ? -1 : 1;
186 if (toys.optflags & FLAG_S) {
187 if (dta->st.st_size > dtb->st.st_size) ret = -1;
188 else if (dta->st.st_size < dtb->st.st_size) ret = 1;
190 if (toys.optflags & FLAG_t) {
191 if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
192 else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
194 if (!ret) ret = strcmp(dta->name, dtb->name);
195 return ret * reverse;
198 // callback from dirtree_recurse() determining how to handle this entry.
200 static int filter(struct dirtree *new)
202 int flags = toys.optflags;
204 // Special case to handle enormous dirs without running out of memory.
205 if (flags == (FLAG_1|FLAG_f)) {
206 xprintf("%s\n", new->name);
210 if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
211 if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
212 if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
214 if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
215 if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
217 return dirtree_notdotdot(new) & DIRTREE_SAVE;
220 // For column view, calculate horizontal position (for padding) and return
221 // index of next entry to display.
223 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
224 unsigned columns, unsigned *xpos)
226 unsigned long transition;
227 unsigned height, widecols;
229 // Horizontal sort is easy
230 if (!(toys.optflags & FLAG_C)) {
231 *xpos = ul % columns;
237 // For -x, calculate height of display, rounded up
238 height = (dtlen+columns-1)/columns;
240 // Sanity check: does wrapping render this column count impossible
241 // due to the right edge wrapping eating a whole row?
242 if (height*columns - dtlen >= height) {
247 // Uneven rounding goes along right edge
248 widecols = dtlen % height;
249 if (!widecols) widecols = height;
250 transition = widecols * columns;
251 if (ul < transition) {
252 *xpos = ul % columns;
253 return (*xpos*height) + (ul/columns);
257 *xpos = ul % (columns-1);
259 return (*xpos*height) + widecols + (ul/(columns-1));
262 int color_from_mode(mode_t mode)
266 if (S_ISDIR(mode)) color = 256+34;
267 else if (S_ISLNK(mode)) color = 256+36;
268 else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
269 else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
270 else if (S_ISFIFO(mode)) color = 33;
271 else if (S_ISSOCK(mode)) color = 256+35;
276 // Display a list of dirtree entries, according to current format
277 // Output types -1, -l, -C, or stream
279 static void listfiles(int dirfd, struct dirtree *indir)
281 struct dirtree *dt, **sort = 0;
282 unsigned long dtlen = 0, ul = 0;
283 unsigned width, flags = toys.optflags, totals[8], len[8], totpad = 0,
284 *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
286 memset(totals, 0, sizeof(totals));
288 // Silently descend into single directory listed by itself on command line.
289 // In this case only show dirname/total header when given -R.
290 if (!indir->parent) {
291 if (!(dt = indir->child)) return;
292 if (S_ISDIR(dt->st.st_mode) && !dt->next && !(flags & FLAG_d)) {
294 listfiles(open(dt->name, 0), dt);
298 // Read directory contents. We dup() the fd because this will close it.
299 indir->data = dup(dirfd);
300 dirtree_recurse(indir, filter, (flags&FLAG_L) ? DIRTREE_SYMFOLLOW : 0);
303 // Copy linked list to array and sort it. Directories go in array because
304 // we visit them in sorted order.
307 for (dt = indir->child; dt; dt = dt->next) {
308 if (sort) sort[dtlen] = dt;
312 sort = xmalloc(dtlen * sizeof(void *));
317 // Label directory if not top of tree, or if -R
318 if (indir->parent && (!indir->extra || (flags & FLAG_R)))
320 char *path = dirtree_path(indir, 0);
322 if (TT.nl_title++) xputc('\n');
323 xprintf("%s:\n", path);
327 if (!(flags & FLAG_f)) {
328 unsigned long long blocks = 0;
330 qsort(sort, dtlen, sizeof(void *), (void *)compare);
331 for (ul = 0; ul<dtlen; ul++) {
332 entrylen(sort[ul], len);
333 for (width = 0; width<8; width++)
334 if (len[width]>totals[width]) totals[width] = len[width];
335 totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6];
336 blocks += sort[ul]->st.st_blocks;
338 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s) && indir->parent)
339 xprintf("total %llu\n", blocks);
342 // Find largest entry in each field for display alignment
343 if (flags & (FLAG_C|FLAG_x)) {
345 // columns can't be more than toybuf can hold, or more than files,
346 // or > 1/2 screen width (one char filename, one space).
347 if (columns > TT.screen_width/2) columns = TT.screen_width/2;
348 if (columns > dtlen) columns = dtlen;
350 // Try to fit as many columns as we can, dropping down by one each time
351 for (;columns > 1; columns--) {
352 unsigned c, totlen = columns;
354 memset(colsizes, 0, columns*sizeof(unsigned));
355 for (ul=0; ul<dtlen; ul++) {
356 entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
358 if (c == columns) break;
359 // Expand this column if necessary, break if that puts us over budget
360 if (*len > colsizes[c]) {
361 totlen += (*len)-colsizes[c];
363 if (totlen > TT.screen_width) break;
366 // If everything fit, stop here
367 if (ul == dtlen) break;
371 // Loop through again to produce output.
372 memset(toybuf, ' ', 256);
374 for (ul = 0; ul<dtlen; ul++) {
375 unsigned curcol, color = 0;
376 unsigned long next = next_column(ul, dtlen, columns, &curcol);
377 struct stat *st = &(sort[next]->st);
378 mode_t mode = st->st_mode;
379 char et = endtype(st);
381 // Skip directories at the top of the tree when -d isn't set
382 if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
385 // Handle padding and wrapping for display purposes
386 entrylen(sort[next], len);
388 if (flags & FLAG_m) xputc(',');
389 if (flags & (FLAG_C|FLAG_x)) {
390 if (!curcol) xputc('\n');
391 } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
402 xprintf("%*lu ", totals[1], (unsigned long)st->st_ino);
404 xprintf("%*lu ", totals[6], (unsigned long)st->st_blocks);
406 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
408 char perm[11], thyme[64], *usr, *upad, *grp, *grpad;
410 mode_to_string(mode, perm);
412 if (flags&FLAG_o) grp = grpad = toybuf+256;
414 if (flags&FLAG_n) sprintf(grp = thyme, "%u", (unsigned)st->st_gid);
415 else strwidth(grp = getgroupname(st->st_gid));
416 grpad = toybuf+256-(totals[4]-len[4]);
419 if (flags&FLAG_g) usr = upad = toybuf+256;
421 upad = toybuf+255-(totals[3]-len[3]);
422 if (flags&FLAG_n) sprintf(usr = TT.uid_buf, "%u", (unsigned)st->st_uid);
423 else strwidth(usr = getusername(st->st_uid));
426 // Coerce the st types into something we know we can print.
427 printf("%s% *ld %s%s%s%s", perm, totals[2]+1, (long)st->st_nlink,
428 usr, upad, grp, grpad);
431 if (flags & FLAG_Z) {
432 char zbuf[SMACK_LABEL_LEN + 1];
433 char *zpath = dirtree_path(sort[next], 0);
434 ssize_t zlen = getxattr(zpath, XATTR_NAME_SMACK, zbuf, sizeof(zbuf));
436 if ((zlen <= 0) || (zlen > SMACK_LABEL_LEN)) zbuf[0] = '?', zlen = 1;
438 xprintf(" %s%s", zbuf, toybuf+256-(totals[7]-(int)zlen));
442 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
443 printf("% *d,% 4d", totals[5]-4, major(st->st_rdev),minor(st->st_rdev));
444 else printf("% *"PRId64, totals[5]+1, (int64_t)st->st_size);
446 tm = localtime(&(st->st_mtime));
447 strftime(thyme, sizeof(thyme), "%F %H:%M", tm);
448 xprintf(" %s ", thyme);
449 } else if (CFG_LS_SMACK) {
450 if (flags & FLAG_Z) {
451 char zbuf[SMACK_LABEL_LEN + 1];
452 char *zpath = dirtree_path(sort[next], 0);
453 ssize_t zlen = getxattr(zpath, XATTR_NAME_SMACK, zbuf, sizeof(zbuf));
455 if ((zlen <= 0) || (zlen > SMACK_LABEL_LEN)) zbuf[0] = '?', zlen = 1;
457 xprintf("%s%s ", toybuf+256-(totals[7]-(int)(zlen-1)), zbuf);
461 if (flags & FLAG_color) {
462 color = color_from_mode(st->st_mode);
463 if (color) printf("\033[%d;%dm", color>>8, color&255);
466 if (flags & FLAG_q) {
468 for (p=sort[next]->name; *p; p++) fputc(isprint(*p) ? *p : '?', stdout);
469 } else xprintf("%s", sort[next]->name);
470 if (color) xprintf("\033[0m");
472 if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
474 if (flags & FLAG_color) {
477 if (fstatat(dirfd, sort[next]->symlink, &st2, 0)) color = 256+31;
478 else color = color_from_mode(st2.st_mode);
480 if (color) printf("\033[%d;%dm", color>>8, color&255);
483 printf("%s", sort[next]->symlink);
484 if (color) printf("\033[0m");
490 if (flags & (FLAG_C|FLAG_x)) {
491 curcol = colsizes[curcol]-(*len)-totpad;
492 if (curcol < 255) xprintf("%s", toybuf+255-curcol);
496 if (width) xputc('\n');
498 // Free directory entries, recursing first if necessary.
500 for (ul = 0; ul<dtlen; free(sort[ul++])) {
501 if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)
502 || !dirtree_notdotdot(sort[ul])) continue;
504 // Recurse into dirs if at top of the tree or given -R
505 if (!indir->parent || (flags & FLAG_R))
506 listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
509 if (dirfd != AT_FDCWD) close(dirfd);
514 char **s, *noargs[] = {".", 0};
517 TT.screen_width = 80;
518 terminal_size(&TT.screen_width, NULL);
519 if (TT.screen_width<2) TT.screen_width = 2;
521 // Do we have an implied -1
523 toys.optflags |= FLAG_1;
524 if (TT.color) toys.optflags ^= FLAG_color;
525 } else if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g))
526 toys.optflags |= FLAG_1;
527 else if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
528 // The optflags parsing infrastructure should really do this for us,
529 // but currently it has "switch off when this is set", so "-dR" and "-Rd"
530 // behave differently
531 if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
533 // Iterate through command line arguments, collecting directories and files.
534 // Non-absolute paths are relative to current directory.
535 TT.files = dirtree_add_node(0, 0, 0);
536 for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
537 dt = dirtree_add_node(0, *s, !(toys.optflags & (FLAG_l|FLAG_d|FLAG_F))
538 || (toys.optflags & (FLAG_L|FLAG_H)));
545 // Typecast means double_list->prev temporarirly goes in dirtree->parent
546 dlist_add_nomalloc((void *)&TT.files->child, (struct double_list *)dt);
549 // Turn double_list into dirtree
550 dlist_to_dirtree(TT.files);
552 // Display the files we collected
553 listfiles(AT_FDCWD, TT.files);
555 if (CFG_TOYBOX_FREE) free(TT.files);