1 /* vi: set sw=4 ts=4: */
3 * tiny-ls.c version 0.1.0: A minimalist 'ls'
4 * Copyright (C) 1996 Brian Candler <B.Candler@pobox.com>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 * To achieve a small memory footprint, this version of 'ls' doesn't do any
23 * file sorting, and only has the most essential command line switches
24 * (i.e. the ones I couldn't live without :-) All features which involve
25 * linking in substantial chunks of libc can be disabled.
27 * Although I don't really want to add new features to this program to
28 * keep it small, I *am* interested to receive bug fixes and ways to make
32 * 1. ls -l of a directory doesn't give "total <blocks>" header
33 * 2. ls of a symlink to a directory doesn't list directory contents
34 * 3. hidden files can make column width too large
36 * NON-OPTIMAL BEHAVIOUR:
37 * 1. autowidth reads directories twice
38 * 2. if you do a short directory listing without filetype characters
39 * appended, there's no need to stat each one
41 * 1. requires lstat (BSD) - how do you do it without?
44 #define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */
45 #define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */
46 #define COLUMN_GAP 2 /* includes the file type char, if present */
49 /************************************************************************/
52 # include <sys/types.h>
58 #ifdef BB_FEATURE_LS_TIMESTAMPS
62 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
63 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
64 #ifdef BB_FEATURE_LS_FILETYPES
65 #define APPCHAR(mode) ("\0|\0\0/\0\0\0\0\0@\0=\0\0\0" [TYPEINDEX(mode)])
69 #define FMT_LONG 1 /* one record per line, extended info */
70 #define FMT_SINGLE 2 /* one record per line */
71 #define FMT_ROWS 3 /* print across rows */
72 #define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */
78 #define DISP_FTYPE 1 /* show character for file type */
79 #define DISP_EXEC 2 /* show '*' if regular executable file */
80 #define DISP_HIDDEN 4 /* show files starting . (except . and ..) */
81 #define DISP_DOT 8 /* show . and .. */
82 #define DISP_NUMERIC 16 /* numeric uid and gid */
83 #define DISP_FULLTIME 32 /* show extended time display */
84 #define DIR_NOLIST 64 /* show directory as itself, not contents */
85 #define DISP_DIRNAME 128 /* show directory name (for internal use) */
86 #define DISP_RECURSIVE 256 /* Do a recursive listing */
89 #define MAJOR(dev) (((dev)>>8)&0xff)
90 #define MINOR(dev) ((dev)&0xff)
93 #ifdef BB_FEATURE_LS_SORTFILES
94 struct dnode { /* the basic node */
95 char *name; /* the dir entry name */
96 char *fullname; /* the dir entry name */
97 struct stat dstat; /* the file stat info */
99 typedef struct dnode dnode_t;
101 static unsigned char display_fmt = FMT_AUTO;
102 static unsigned short opts = 0;
103 static unsigned short column = 0;
105 #ifdef BB_FEATURE_AUTOWIDTH
106 static unsigned short terminal_width = 0;
107 static unsigned short column_width = 0;
108 static unsigned short toplevel_column_width = 0;
110 #define terminal_width TERMINAL_WIDTH
111 #define column_width COLUMN_WIDTH
114 #ifdef BB_FEATURE_LS_TIMESTAMPS
115 static unsigned char time_fmt = TIME_MOD;
118 #define wr(data,len) fwrite(data, 1, len, stdout)
120 static void writenum(long val, short minwidth)
124 char *p = scratch + sizeof(scratch);
126 short neg = (val < 0);
131 *--p = (val % 10) + '0', len++, val /= 10;
135 while (len < minwidth)
141 static void newline(void)
149 static void tab(short col)
151 static const char spaces[] = " ";
153 #define nspaces ((sizeof spaces)-1) /* null terminator! */
155 short n = col - column;
159 while (n > nspaces) {
163 /* must be 1...(sizeof spaces) left */
169 #ifdef BB_FEATURE_LS_FILETYPES
170 static char append_char(mode_t mode)
172 if (!(opts & DISP_FTYPE))
174 if ((opts & DISP_EXEC) && S_ISREG(mode)
175 && (mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return '*';
176 return APPCHAR(mode);
182 ** Display a file or directory as a single item
183 ** (in either long or short format)
187 static void list_single(const char *name, struct stat *info,
188 const char *fullname)
190 char scratch[BUFSIZ + 1];
191 short len = strlen(name);
193 #ifdef BB_FEATURE_LS_FILETYPES
194 char append = append_char(info->st_mode);
197 if (display_fmt == FMT_LONG) {
198 mode_t mode = info->st_mode;
201 wr(modeString(mode), 10);
203 writenum((long) info->st_nlink, (short) 5);
205 #ifdef BB_FEATURE_LS_USERNAME
206 if (!(opts & DISP_NUMERIC)) {
207 memset(scratch, 0, sizeof(scratch));
208 my_getpwuid(scratch, info->st_uid);
210 fputs(scratch, stdout);
211 if (strlen(scratch) <= 8)
212 wr(" ", 9 - strlen(scratch));
214 writenum((long) info->st_uid, (short) 8);
220 writenum((long) info->st_uid, (short) 8);
223 #ifdef BB_FEATURE_LS_USERNAME
224 if (!(opts & DISP_NUMERIC)) {
225 memset(scratch, 0, sizeof(scratch));
226 my_getgrgid(scratch, info->st_gid);
228 fputs(scratch, stdout);
229 if (strlen(scratch) <= 8)
230 wr(" ", 8 - strlen(scratch));
232 writenum((long) info->st_gid, (short) 8);
235 writenum((long) info->st_gid, (short) 8);
237 if (S_ISBLK(mode) || S_ISCHR(mode)) {
238 writenum((long) MAJOR(info->st_rdev), (short) 3);
240 writenum((long) MINOR(info->st_rdev), (short) 3);
242 writenum((long) info->st_size, (short) 8);
245 #ifdef BB_FEATURE_LS_TIMESTAMPS
252 cal = info->st_ctime;
255 cal = info->st_atime;
258 cal = info->st_mtime;
261 string = ctime(&cal);
262 if (opts & DISP_FULLTIME)
265 time_t age = time(NULL) - cal;
267 wr(string + 4, 7); /* mmm_dd_ */
268 if (age < 3600L * 24 * 365 / 2 && age > -15 * 60)
269 /* hh:mm if less than 6 months old */
272 /* _yyyy otherwise */
278 fputs("--- -- ----- ", stdout);
283 len = readlink(fullname, scratch, sizeof scratch);
285 fwrite(scratch, 1, len, stdout);
286 #ifdef BB_FEATURE_LS_FILETYPES
287 /* show type of destination */
288 if (opts & DISP_FTYPE) {
289 if (!stat(fullname, info)) {
290 append = append_char(info->st_mode);
292 fputc(append, stdout);
297 #ifdef BB_FEATURE_LS_FILETYPES
302 static short nexttab = 0;
304 /* sort out column alignment */
305 if (column == 0); /* nothing to do */
306 else if (display_fmt == FMT_SINGLE)
309 if (nexttab + column_width > terminal_width
310 #ifndef BB_FEATURE_AUTOWIDTH
311 || nexttab + len >= terminal_width
318 /* work out where next column starts */
319 #ifdef BB_FEATURE_AUTOWIDTH
320 /* we know the calculated width is big enough */
321 nexttab = column + column_width + COLUMN_GAP;
323 /* might cover more than one fixed-width column */
326 nexttab += column_width + COLUMN_GAP;
327 while (nexttab < (column + len + COLUMN_GAP));
329 /* now write the data */
331 column = column + len;
332 #ifdef BB_FEATURE_LS_FILETYPES
334 wr(&append, 1), column++;
339 #ifdef BB_FEATURE_LS_SORTFILES
340 void shellsort(struct dnode *dn[], int size)
345 /* shell short the array */
346 for (gap= size/2; gap>0; gap /=2) {
347 for (i=gap; i<size; i++) {
348 for (j= i-gap; j>=0; j-=gap) {
349 if (strcmp(dn[j]->name, dn[j+gap]->name) <= 0)
359 void showdnodes(struct dnode *dn[], int nfiles)
364 ncols= (int)(terminal_width / (column_width + COLUMN_GAP));
365 /* files per column. The +1 means the last col is shorter than others */
366 fpc= (nfiles / ncols) + 1;
367 for (nf=0; nf<fpc; nf++) {
368 for (nc=0; nc<ncols; nc++) {
369 /* reach into the array based on the column and row */
374 list_single(dn[i]->name, &dn[i]->dstat, dn[i]->fullname);
383 ** List the given file or directory, expanding a directory
384 ** to show its contents if required
388 static int list_item(const char *name)
392 struct dirent *entry;
393 char fullname[BUFSIZ + 1], *fnend;
394 #ifdef BB_FEATURE_LS_SORTFILES
400 if (lstat(name, &info))
403 if (!S_ISDIR(info.st_mode) || (opts & DIR_NOLIST)) {
404 #ifdef BB_FEATURE_AUTOWIDTH
405 column_width = toplevel_column_width;
407 list_single(name, &info, name);
411 /* Otherwise, it's a directory we want to list the contents of */
413 if (opts & DISP_DIRNAME) { /* identify the directory */
415 wr("\n\n", 2), column = 0;
416 wr(name, strlen(name));
423 #ifdef BB_FEATURE_AUTOWIDTH
425 while ((entry = readdir(dir)) != NULL) {
426 short w = strlen(entry->d_name);
427 #ifdef BB_FEATURE_LS_SORTFILES
428 const char *en = entry->d_name;
431 if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
432 if (!(opts & DISP_DOT))
434 } else if (!(opts & DISP_HIDDEN))
437 nfiles++; /* count how many files there will be */
440 if (column_width < w)
452 #ifdef BB_FEATURE_LS_SORTFILES
453 /* now that we know how many files there are
454 * allocate memory for an array to hold dnode pointers
456 dnp= (struct dnode **)calloc((size_t)nfiles, (size_t)(sizeof(struct dnode *)));
459 /* List the contents */
461 strcpy(fullname, name); /* *** ignore '.' by itself */
462 fnend = fullname + strlen(fullname);
463 if (fnend[-1] != '/')
466 while ((entry = readdir(dir)) != NULL) {
467 const char *en = entry->d_name;
470 if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
471 if (!(opts & DISP_DOT))
473 } else if (!(opts & DISP_HIDDEN))
476 /* FIXME: avoid stat if not required */
477 strcpy(fnend, entry->d_name);
478 #ifdef BB_FEATURE_LS_SORTFILES
479 /* allocate memory for a node and memory for the file name */
480 cur= (struct dnode *)malloc(sizeof(struct dnode));
481 cur->fullname= strcpy((char *)malloc(strlen(fullname)+1), fullname);
482 cur->name= cur->fullname + (int)(fnend - fullname) ;
483 lstat(fullname, &cur->dstat); /* get file stat info into node */
484 dnp[ni++]= cur; /* save pointer to node in array */
486 if (lstat(fullname, &info)) {
488 goto listerr; /* (shouldn't fail) */
490 list_single(entry->d_name, &info, fullname);
494 #ifdef BB_FEATURE_LS_SORTFILES
495 shellsort(dnp, nfiles);
496 showdnodes(dnp, nfiles);
499 if (opts & DISP_DIRNAME) { /* separate the directory */
515 #ifdef BB_FEATURE_LS_RECURSIVE
516 static int dirAction(const char *fileName, struct stat *statbuf, void* junk)
519 fprintf(stdout, "\n%s:\n", fileName);
520 i = list_item(fileName);
526 extern int ls_main(int argc, char **argv)
530 /* process options */
531 while (argi < argc && argv[argi][0] == '-') {
532 const char *p = &argv[argi][1];
535 goto print_usage_message; /* "-" by itself not allowed */
537 if (!p[1]) { /* "--" forces end of options */
541 /* it's a long option name - we don't support them */
542 goto print_usage_message;
548 display_fmt = FMT_LONG;
551 display_fmt = FMT_SINGLE;
554 display_fmt = FMT_ROWS;
557 display_fmt = FMT_COLUMNS;
559 #ifdef BB_FEATURE_LS_FILETYPES
564 opts |= DISP_FTYPE | DISP_EXEC;
571 opts |= DISP_HIDDEN | DISP_DOT;
574 opts |= DISP_NUMERIC;
579 #ifdef BB_FEATURE_LS_TIMESTAMPS
581 time_fmt = TIME_ACCESS;
584 time_fmt = TIME_CHANGE;
587 opts |= DISP_FULLTIME;
590 #ifdef BB_FEATURE_LS_RECURSIVE
592 opts |= DISP_RECURSIVE;
595 case 'g': /* ignore -- for ftp servers */
598 goto print_usage_message;
604 /* choose a display format */
605 if (display_fmt == FMT_AUTO)
606 display_fmt = isatty(fileno(stdout)) ? FMT_COLUMNS : FMT_SINGLE;
608 opts |= DISP_DIRNAME; /* 2 or more items? label directories */
609 #ifdef BB_FEATURE_AUTOWIDTH
610 /* could add a -w option and/or TIOCGWINSZ call */
611 if (terminal_width < 1)
612 terminal_width = TERMINAL_WIDTH;
614 for (i = argi; i < argc; i++) {
615 int len = strlen(argv[i]);
617 if (toplevel_column_width < len)
618 toplevel_column_width = len;
622 /* process files specified, or current directory if none */
623 #ifdef BB_FEATURE_LS_RECURSIVE
624 if (opts & DISP_RECURSIVE) {
627 i = recursiveAction(".", TRUE, FALSE, FALSE, NULL, dirAction, NULL);
629 while (argi < argc) {
630 i |= recursiveAction(argv[argi++], TRUE, FALSE, FALSE, NULL, dirAction, NULL);
639 i |= list_item(argv[argi++]);