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, "goACFHLRSacdfiklmnpqrstux1[-1Cglmnox][-cu][-ftS][-HL]", TOYFLAG_BIN))
14 usage: ls [-ACFHLRSacdfiklmnpqrstux1] [directory...]
18 -a all files including .hidden
19 -c use ctime for timestamps
20 -d directory, not contents
22 -k block sizes in kilobytes
23 -p put a '/' after directory names
24 -q unprintable chars as '?'
26 -u use access time for timestamps
27 -A list all files except . and ..
28 -H follow command line symlinks
30 -R recursively list files in subdirectories
31 -F append file type indicator (/=dir, *=exe, @=symlink, |=FIFO)
34 -1 list one file per line
35 -C columns (sorted vertically)
36 -g like -l but no owner
37 -l long (show full details for each file)
39 -n like -l but numeric uid/gid
40 -o like -l but no group
41 -x columns (sorted horizontally)
43 sorting (default is alphabetical):
53 // test sst output (suid/sticky in ls flaglist)
55 // ls -lR starts .: then ./subdir:
58 struct dirtree *files;
60 unsigned screen_width;
63 // group and user can make overlapping use of the utoa() buf, so move it
67 void dlist_to_dirtree(struct dirtree *parent)
69 // Turn double_list into dirtree
70 struct dirtree *dt = parent->child;
72 dt->parent->next = NULL;
80 static char endtype(struct stat *st)
82 mode_t mode = st->st_mode;
83 if ((toys.optflags&(FLAG_F|FLAG_p)) && S_ISDIR(mode)) return '/';
84 if (toys.optflags & FLAG_F) {
85 if (S_ISLNK(mode)) return '@';
86 if (S_ISREG(mode) && (mode&0111)) return '*';
87 if (S_ISFIFO(mode)) return '|';
88 if (S_ISSOCK(mode)) return '=';
93 static char *getusername(uid_t uid)
95 struct passwd *pw = getpwuid(uid);
96 utoa_to_buf(uid, TT.uid_buf, 12);
97 return pw ? pw->pw_name : TT.uid_buf;
100 static char *getgroupname(gid_t gid)
102 struct group *gr = getgrgid(gid);
103 return gr ? gr->gr_name : utoa(gid);
106 // Figure out size of printable entry fields for display indent/wrap
108 static void entrylen(struct dirtree *dt, unsigned *len)
110 struct stat *st = &(dt->st);
111 unsigned flags = toys.optflags;
113 *len = strlen(dt->name);
114 if (endtype(st)) ++*len;
115 if (flags & FLAG_m) ++*len;
117 if (flags & FLAG_i) *len += (len[1] = numlen(st->st_ino));
118 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
119 unsigned fn = flags & FLAG_n;
120 len[2] = numlen(st->st_nlink);
121 len[3] = strlen(fn ? utoa(st->st_uid) : getusername(st->st_uid));
122 len[4] = strlen(fn ? utoa(st->st_gid) : getgroupname(st->st_gid));
123 len[5] = numlen(st->st_size);
125 if (flags & FLAG_s) *len += (len[6] = numlen(st->st_blocks));
128 static int compare(void *a, void *b)
130 struct dirtree *dta = *(struct dirtree **)a;
131 struct dirtree *dtb = *(struct dirtree **)b;
132 int ret = 0, reverse = (toys.optflags & FLAG_r) ? -1 : 1;
134 if (toys.optflags & FLAG_S) {
135 if (dta->st.st_size > dtb->st.st_size) ret = -1;
136 else if (dta->st.st_size < dtb->st.st_size) ret = 1;
138 if (toys.optflags & FLAG_t) {
139 if (dta->st.st_mtime > dtb->st.st_mtime) ret = -1;
140 else if (dta->st.st_mtime < dtb->st.st_mtime) ret = 1;
142 if (!ret) ret = strcmp(dta->name, dtb->name);
143 return ret * reverse;
146 // callback from dirtree_recurse() determining how to handle this entry.
148 static int filter(struct dirtree *new)
150 int flags = toys.optflags;
152 // Special case to handle enormous dirs without running out of memory.
153 if (flags == (FLAG_1|FLAG_f)) {
154 xprintf("%s\n", new->name);
158 if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
159 if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
160 if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
162 if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
163 if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
165 return dirtree_notdotdot(new) & DIRTREE_SAVE;
168 // For column view, calculate horizontal position (for padding) and return
169 // index of next entry to display.
171 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
172 unsigned columns, unsigned *xpos)
174 unsigned long transition;
175 unsigned height, widecols;
177 // Horizontal sort is easy
178 if (!(toys.optflags & FLAG_C)) {
179 *xpos = ul % columns;
185 // For -x, calculate height of display, rounded up
186 height = (dtlen+columns-1)/columns;
188 // Sanity check: does wrapping render this column count impossible
189 // due to the right edge wrapping eating a whole row?
190 if (height*columns - dtlen >= height) {
195 // Uneven rounding goes along right edge
196 widecols = dtlen % height;
197 if (!widecols) widecols = height;
198 transition = widecols * columns;
199 if (ul < transition) {
200 *xpos = ul % columns;
201 return (*xpos*height) + (ul/columns);
205 *xpos = ul % (columns-1);
207 return (*xpos*height) + widecols + (ul/(columns-1));
210 // Display a list of dirtree entries, according to current format
211 // Output types -1, -l, -C, or stream
213 static void listfiles(int dirfd, struct dirtree *indir)
215 struct dirtree *dt, **sort = 0;
216 unsigned long dtlen = 0, ul = 0;
217 unsigned width, flags = toys.optflags, totals[7], len[7],
218 *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
220 memset(totals, 0, sizeof(totals));
222 // Silently descend into single directory listed by itself on command line.
223 // In this case only show dirname/total header when given -R.
224 if (!indir->parent) {
225 if (!(dt = indir->child)) return;
226 if (S_ISDIR(dt->st.st_mode) && !dt->next && !(flags & FLAG_d)) {
228 listfiles(open(dt->name, 0), dt);
232 // Read directory contents. We dup() the fd because this will close it.
233 indir->data = dup(dirfd);
234 dirtree_recurse(indir, filter, (flags&FLAG_L));
237 // Copy linked list to array and sort it. Directories go in array because
238 // we visit them in sorted order.
241 for (dt = indir->child; dt; dt = dt->next) {
242 if (sort) sort[dtlen] = dt;
246 sort = xmalloc(dtlen * sizeof(void *));
251 // Label directory if not top of tree, or if -R
252 if (indir->parent && (!indir->extra || (flags & FLAG_R)))
254 char *path = dirtree_path(indir, 0);
256 if (TT.nl_title++) xputc('\n');
257 xprintf("%s:\n", path);
261 if (!(flags & FLAG_f)) qsort(sort, dtlen, sizeof(void *), (void *)compare);
263 // Find largest entry in each field for display alignment
264 if (flags & (FLAG_C|FLAG_x)) {
266 // columns can't be more than toybuf can hold, or more than files,
267 // or > 1/2 screen width (one char filename, one space).
268 if (columns > TT.screen_width/2) columns = TT.screen_width/2;
269 if (columns > dtlen) columns = dtlen;
271 // Try to fit as many columns as we can, dropping down by one each time
272 for (;columns > 1; columns--) {
273 unsigned c, totlen = columns;
275 memset(colsizes, 0, columns*sizeof(unsigned));
276 for (ul=0; ul<dtlen; ul++) {
277 entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
278 if (c == columns) break;
279 // Does this put us over budget?
280 if (*len > colsizes[c]) {
281 totlen += *len-colsizes[c];
283 if (totlen > TT.screen_width) break;
286 // If it fit, stop here
287 if (ul == dtlen) break;
289 } else if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) {
290 unsigned long blocks = 0;
292 for (ul = 0; ul<dtlen; ul++)
294 entrylen(sort[ul], len);
295 for (width=0; width<6; width++)
296 if (len[width] > totals[width]) totals[width] = len[width];
297 blocks += sort[ul]->st.st_blocks;
300 if (indir->parent) xprintf("total %lu\n", blocks);
303 // Loop through again to produce output.
304 memset(toybuf, ' ', 256);
306 for (ul = 0; ul<dtlen; ul++) {
308 unsigned long next = next_column(ul, dtlen, columns, &curcol);
309 struct stat *st = &(sort[next]->st);
310 mode_t mode = st->st_mode;
311 char et = endtype(st);
313 // Skip directories at the top of the tree when -d isn't set
314 if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
317 // Handle padding and wrapping for display purposes
318 entrylen(sort[next], len);
320 if (flags & FLAG_m) xputc(',');
321 if (flags & (FLAG_C|FLAG_x)) {
322 if (!curcol) xputc('\n');
323 } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
333 if (flags & FLAG_i) xprintf("% *lu ", len[1], (unsigned long)st->st_ino);
334 if (flags & FLAG_s) xprintf("% *lu ", len[6], (unsigned long)st->st_blocks);
336 if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
338 char perm[11], thyme[64], c, d, *usr, *upad, *grp, *grpad;
342 for (i=0; i<9; i++) {
345 if (!c && (mode & (1<<((d=i/3)+9)))) {
347 if (!bit) c &= ~0x20;
348 } else c = bit ? "xwr"[c] : '-';
352 if (S_ISDIR(mode)) c = 'd';
353 else if (S_ISBLK(mode)) c = 'b';
354 else if (S_ISCHR(mode)) c = 'c';
355 else if (S_ISLNK(mode)) c = 'l';
356 else if (S_ISFIFO(mode)) c = 'p';
357 else if (S_ISSOCK(mode)) c = 's';
361 tm = localtime(&(st->st_mtime));
362 strftime(thyme, sizeof(thyme), "%F %H:%M", tm);
364 if (flags&FLAG_o) grp = grpad = toybuf+256;
366 grp = (flags&FLAG_n) ? utoa(st->st_gid) : getgroupname(st->st_gid);
367 grpad = toybuf+256-(totals[4]-len[4]);
370 if (flags&FLAG_g) usr = upad = toybuf+256;
372 upad = toybuf+255-(totals[3]-len[3]);
375 utoa_to_buf(st->st_uid, TT.uid_buf, 12);
376 } else usr = getusername(st->st_uid);
379 // Coerce the st types into something we know we can print.
380 xprintf("%s% *ld %s%s%s%s% *"PRId64" %s ", perm, totals[2]+1,
381 (long)st->st_nlink, usr, upad, grp, grpad, totals[5]+1,
382 (int64_t)st->st_size, thyme);
385 if (flags & FLAG_q) {
387 for (p=sort[next]->name; *p; p++) xputc(isprint(*p) ? *p : '?');
388 } else xprintf("%s", sort[next]->name);
389 if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode))
390 xprintf(" -> %s", sort[next]->symlink);
395 if (flags & (FLAG_C|FLAG_x)) {
396 curcol = colsizes[curcol] - *len;
397 if (curcol >= 0) xprintf("%s", toybuf+255-curcol);
401 if (width) xputc('\n');
403 // Free directory entries, recursing first if necessary.
405 for (ul = 0; ul<dtlen; free(sort[ul++])) {
406 if ((flags & FLAG_d) || !S_ISDIR(sort[ul]->st.st_mode)
407 || !dirtree_notdotdot(sort[ul])) continue;
409 // Recurse into dirs if at top of the tree or given -R
410 if (!indir->parent || (flags & FLAG_R))
411 listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
414 if (dirfd != AT_FDCWD) close(indir->data);
419 char **s, *noargs[] = {".", 0};
422 // Do we have an implied -1
423 if (!isatty(1) || (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g)))
424 toys.optflags |= FLAG_1;
426 TT.screen_width = 80;
427 terminal_size(&TT.screen_width, NULL);
428 if (!(toys.optflags&(FLAG_1|FLAG_x|FLAG_m))) toys.optflags |= FLAG_C;
430 // The optflags parsing infrastructure should really do this for us,
431 // but currently it has "switch off when this is set", so "-dR" and "-Rd"
432 // behave differently
433 if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
435 // Iterate through command line arguments, collecting directories and files.
436 // Non-absolute paths are relative to current directory.
437 TT.files = dirtree_add_node(0, 0, 0);
438 for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
439 dt = dirtree_add_node(0, *s,
440 (toys.optflags & (FLAG_L|FLAG_H|FLAG_l))^FLAG_l);
447 // Typecast means double_list->prev temporarirly goes in dirtree->parent
448 dlist_add_nomalloc((void *)&TT.files->child, (struct double_list *)dt);
451 // Turn double_list into dirtree
452 dlist_to_dirtree(TT.files);
454 // Display the files we collected
455 listfiles(AT_FDCWD, TT.files);
457 if (CFG_TOYBOX_FREE) free(TT.files);