A few minor updates. ;-)
[oweals/busybox.git] / coreutils / ls.c
1 /*
2  * tiny-ls.c version 0.1.0: A minimalist 'ls'
3  * Copyright (C) 1996 Brian Candler <B.Candler@pobox.com>
4  * 
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 /*
21  * To achieve a small memory footprint, this version of 'ls' doesn't do any
22  * file sorting, and only has the most essential command line switches
23  * (i.e. the ones I couldn't live without :-) All features which involve
24  * linking in substantial chunks of libc can be disabled.
25  *
26  * Although I don't really want to add new features to this program to
27  * keep it small, I *am* interested to receive bug fixes and ways to make
28  * it more portable.
29  *
30  * KNOWN BUGS:
31  * 1. messy output if you mix files and directories on the command line
32  * 2. ls -l of a directory doesn't give "total <blocks>" header
33  * 3. ls of a symlink to a directory doesn't list directory contents
34  * 4. hidden files can make column width too large
35  * NON-OPTIMAL BEHAVIOUR:
36  * 1. autowidth reads directories twice
37  * 2. if you do a short directory listing without filetype characters
38  *    appended, there's no need to stat each one
39  * PORTABILITY:
40  * 1. requires lstat (BSD) - how do you do it without?
41  */
42
43 #define TERMINAL_WIDTH  80      /* use 79 if your terminal has linefold bug */
44 #define COLUMN_WIDTH    14      /* default if AUTOWIDTH not defined */
45 #define COLUMN_GAP      2       /* includes the file type char, if present */
46 #define HAS_REWINDDIR
47
48 /************************************************************************/
49
50 #include "internal.h"
51 #if !defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
52 # include <linux/types.h> 
53 #else
54 # include <sys/types.h> 
55 #endif
56 #include <sys/stat.h>
57 #include <stdio.h>
58 #include <unistd.h>
59 #include <dirent.h>
60 #include <errno.h>
61 #include <stdio.h>
62 #ifdef BB_FEATURE_LS_TIMESTAMPS
63 #include <time.h>
64 #endif
65
66 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
67 #define TYPECHAR(mode)  ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
68 #ifdef BB_FEATURE_LS_FILETYPES
69 #define APPCHAR(mode)   ("\0|\0\0/\0\0\0\0\0@\0=\0\0\0" [TYPEINDEX(mode)])
70 #endif
71
72 #ifndef MAJOR
73 #define MAJOR(dev) (((dev)>>8)&0xff)
74 #define MINOR(dev) ((dev)&0xff)
75 #endif
76
77 #define FMT_AUTO        0
78 #define FMT_LONG        1       /* one record per line, extended info */
79 #define FMT_SINGLE      2       /* one record per line */
80 #define FMT_ROWS        3       /* print across rows */
81 #define FMT_COLUMNS     3       /* fill columns (same, since we don't sort) */
82
83 #define TIME_MOD        0
84 #define TIME_CHANGE     1
85 #define TIME_ACCESS     2
86
87 #define DISP_FTYPE      1       /* show character for file type */
88 #define DISP_EXEC       2       /* show '*' if regular executable file */
89 #define DISP_HIDDEN     4       /* show files starting . (except . and ..) */
90 #define DISP_DOT        8       /* show . and .. */
91 #define DISP_NUMERIC    16      /* numeric uid and gid */
92 #define DISP_FULLTIME   32      /* show extended time display */
93 #define DIR_NOLIST      64      /* show directory as itself, not contents */
94 #define DISP_DIRNAME    128     /* show directory name (for internal use) */
95 #define DIR_RECURSE     256     /* -R (not yet implemented) */
96
97 static unsigned char    display_fmt = FMT_AUTO;
98 static unsigned short   opts = 0;
99 static unsigned short   column = 0;
100
101 #ifdef BB_FEATURE_AUTOWIDTH
102 static unsigned short terminal_width = 0, column_width = 0;
103 #else
104 #define terminal_width  TERMINAL_WIDTH
105 #define column_width    COLUMN_WIDTH
106 #endif
107
108 #ifdef BB_FEATURE_LS_TIMESTAMPS
109 static unsigned char time_fmt = TIME_MOD;
110 #endif
111
112 #define wr(data,len) fwrite(data, 1, len, stdout)
113
114 static void writenum(long val, short minwidth)
115 {
116         char    scratch[128];
117
118         char *p = scratch + sizeof(scratch);
119         short len = 0;
120         short neg = (val < 0);
121         
122         if (neg) val = -val;
123         do
124                 *--p = (val % 10) + '0', len++, val /= 10;
125         while (val);
126         if (neg)
127                 *--p = '-', len++;
128         while (len < minwidth)
129                 *--p = ' ', len++;
130         wr(p, len);
131         column += len;
132 }
133
134 static void newline(void)
135 {
136         if (column > 0) {
137                 wr("\n", 1);
138                 column = 0;
139         }
140 }
141
142 static void tab(short col)
143 {
144         static const char spaces[] = "                ";
145         #define nspaces ((sizeof spaces)-1)     /* null terminator! */
146         
147         short n = col - column;
148
149         if (n > 0) {
150                 column = col;
151                 while (n > nspaces) {
152                         wr(spaces, nspaces);
153                         n -= nspaces;
154                 }
155                 /* must be 1...(sizeof spaces) left */
156                 wr(spaces, n);
157         }
158         #undef nspaces
159 }
160
161 #ifdef BB_FEATURE_LS_FILETYPES
162 static char append_char(mode_t mode)
163 {
164         if (!(opts & DISP_FTYPE))
165                 return '\0';
166         if ((opts & DISP_EXEC) && S_ISREG(mode) && (mode & (S_IXUSR|S_IXGRP|S_IXOTH)))
167                 return '*';
168         return APPCHAR(mode);
169 }
170 #endif
171
172 /**
173  **
174  ** Display a file or directory as a single item
175  ** (in either long or short format)
176  **
177  **/
178
179 static void list_single(const char *name, struct stat *info, const char *fullname)
180 {
181         char scratch[PATH_MAX + 1];
182         short len = strlen(name);
183 #ifdef BB_FEATURE_LS_FILETYPES
184         char append = append_char(info->st_mode);
185 #endif
186         
187         if (display_fmt == FMT_LONG) {
188                 mode_t mode = info->st_mode; 
189                 newline();
190                 wr(modeString(mode), 10);
191                 column=10;
192                 writenum((long)info->st_nlink,(short)5);
193                 fputs(" ", stdout);
194 #ifdef BB_FEATURE_LS_USERNAME
195                 if (!(opts & DISP_NUMERIC)) {
196                         memset ( scratch, 0, sizeof (scratch));
197                         my_getpwuid( scratch, info->st_uid);
198                         if (*scratch) {
199                             fputs(scratch, stdout);
200                             if ( strlen( scratch) <= 8 )
201                                 wr("          ", 9-strlen( scratch));
202                         }
203                         else {
204                                 writenum((long) info->st_uid,(short)8);
205                                 fputs(" ", stdout);
206                         }
207                 } else
208 #endif
209                 {
210                     writenum((long) info->st_uid,(short)8);
211                     fputs(" ", stdout);
212                 }
213 #ifdef BB_FEATURE_LS_USERNAME
214                 if (!(opts & DISP_NUMERIC)) {
215                         memset ( scratch, 0, sizeof (scratch));
216                         my_getgrgid( scratch, info->st_gid);
217                         if (*scratch) {
218                             fputs(scratch, stdout);
219                             if ( strlen( scratch) <= 8 )
220                                 wr("         ", 8-strlen( scratch));
221                         }
222                         else 
223                             writenum((long) info->st_gid,(short)8);
224                 } else
225 #endif
226                 writenum((long) info->st_gid,(short)8);
227                 //tab(26);
228                 if (S_ISBLK(mode) || S_ISCHR(mode)) {
229                         writenum((long)MAJOR(info->st_rdev),(short)3);
230                         fputs(", ", stdout);
231                         writenum((long)MINOR(info->st_rdev),(short)3);
232                 }
233                 else
234                         writenum((long)info->st_size,(short)8);
235                 fputs(" ", stdout);
236                 //tab(32);
237 #ifdef BB_FEATURE_LS_TIMESTAMPS
238                 {
239                         time_t cal;
240                         char *string;
241                         
242                         switch(time_fmt) {
243                         case TIME_CHANGE:
244                                 cal=info->st_ctime; break;
245                         case TIME_ACCESS:
246                                 cal=info->st_atime; break;
247                         default:
248                                 cal=info->st_mtime; break;
249                         }
250                         string=ctime(&cal);
251                         if (opts & DISP_FULLTIME)
252                                 wr(string,24);
253                         else {
254                                 time_t age = time(NULL) - cal;
255                                 wr(string+4,7); /* mmm_dd_ */
256                                 if(age < 3600L*24*365/2 && age > -15*60)
257                                         /* hh:mm if less than 6 months old */
258                                         wr(string+11,5);
259                                 else
260                                         /* _yyyy otherwise */
261                                         wr(string+19,5);
262                         }
263                         wr(" ", 1);
264                 }
265 #else
266                 fputs("--- -- ----- ", stdout);
267 #endif
268                 wr(name, len);
269                 if (S_ISLNK(mode)) {
270                         wr(" -> ", 4);
271                         len = readlink(fullname, scratch, sizeof scratch);
272                         if (len > 0) fwrite(scratch, 1, len, stdout);
273 #ifdef BB_FEATURE_LS_FILETYPES
274                         /* show type of destination */
275                         if (opts & DISP_FTYPE) {
276                                 if (!stat(fullname, info)) {
277                                         append = append_char(info->st_mode);
278                                         if (append)
279                                                 fputc(append, stdout);
280                                 }
281                         }
282 #endif
283                 }
284 #ifdef BB_FEATURE_LS_FILETYPES
285                 else if (append)
286                         wr(&append, 1);
287 #endif
288         } else {
289                 static short nexttab = 0;
290                 
291                 /* sort out column alignment */
292                 if (column == 0)
293                         ; /* nothing to do */
294                 else if (display_fmt == FMT_SINGLE)
295                         newline();
296                 else {
297                         if (nexttab + column_width > terminal_width
298 #ifndef BB_FEATURE_AUTOWIDTH
299                         || nexttab + len >= terminal_width
300 #endif
301                         )
302                                 newline();
303                         else
304                                 tab(nexttab);
305                 }
306                 /* work out where next column starts */
307 #ifdef BB_FEATURE_AUTOWIDTH
308                 /* we know the calculated width is big enough */
309                 nexttab = column + column_width + COLUMN_GAP;
310 #else
311                 /* might cover more than one fixed-width column */
312                 nexttab = column;
313                 do
314                         nexttab += column_width + COLUMN_GAP;
315                 while (nexttab < (column + len + COLUMN_GAP));
316 #endif
317                 /* now write the data */
318                 wr(name, len);
319                 column = column + len;
320 #ifdef BB_FEATURE_LS_FILETYPES
321                 if (append)
322                         wr(&append, 1), column++;
323 #endif
324         }
325 }
326
327 /**
328  **
329  ** List the given file or directory, expanding a directory
330  ** to show its contents if required
331  **
332  **/
333
334 static int list_item(const char *name)
335 {
336         struct stat info;
337         DIR *dir;
338         struct dirent *entry;
339         char fullname[MAXNAMLEN+1], *fnend;
340         
341         if (lstat(name, &info))
342                 goto listerr;
343         
344         if (!S_ISDIR(info.st_mode) || 
345             (opts & DIR_NOLIST)) {
346                 list_single(name, &info, name);
347                 return 0;
348         }
349
350         /* Otherwise, it's a directory we want to list the contents of */
351
352         if (opts & DISP_DIRNAME) {   /* identify the directory */
353                 if (column)
354                         wr("\n\n", 2), column = 0;
355                 wr(name, strlen(name));
356                 wr(":\n", 2);
357         }
358         
359         dir = opendir(name);
360         if (!dir) goto listerr;
361 #ifdef BB_FEATURE_AUTOWIDTH
362         column_width = 0;
363         while ((entry = readdir(dir)) != NULL) {
364                 short w = strlen(entry->d_name);
365                 if (column_width < w)
366                         column_width = w;
367         }
368 #ifdef HAS_REWINDDIR
369         rewinddir(dir);
370 #else
371         closedir(dir);
372         dir = opendir(name);
373         if (!dir) goto listerr;
374 #endif
375 #endif
376
377         /* List the contents */
378         
379         strcpy(fullname,name);  /* *** ignore '.' by itself */
380         fnend=fullname+strlen(fullname);
381         if (fnend[-1] != '/')
382                 *fnend++ = '/';
383         
384         while ((entry = readdir(dir)) != NULL) {
385                 const char *en=entry->d_name;
386                 if (en[0] == '.') {
387                         if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
388                                 if (!(opts & DISP_DOT))
389                                         continue;
390                         }
391                         else if (!(opts & DISP_HIDDEN))
392                                 continue;
393                 }
394                 /* FIXME: avoid stat if not required */
395                 strcpy(fnend, entry->d_name);
396                 if (lstat(fullname, &info))
397                         goto direrr; /* (shouldn't fail) */
398                 list_single(entry->d_name, &info, fullname);
399         }
400         closedir(dir);
401         return 0;
402
403 direrr:
404         closedir(dir);  
405 listerr:
406         newline();
407         perror(name);
408         return 1;
409 }
410
411 static const char ls_usage[] = "ls [-1a"
412 #ifdef BB_FEATURE_LS_TIMESTAMPS
413         "c"
414 #endif
415         "d"
416 #ifdef BB_FEATURE_LS_TIMESTAMPS
417         "e"
418 #endif
419         "ln"
420 #ifdef BB_FEATURE_LS_FILETYPES
421         "p"
422 #endif
423 #ifdef BB_FEATURE_LS_TIMESTAMPS
424         "u"
425 #endif
426         "xAC"
427 #ifdef BB_FEATURE_LS_FILETYPES
428         "F"
429 #endif
430 #ifdef FEATURE_RECURSIVE
431         "R"
432 #endif
433         "] [filenames...]\n";
434
435 extern int
436 ls_main(int argc, char * * argv)
437 {
438         int argi=1, i;
439         
440         /* process options */
441         while (argi < argc && argv[argi][0] == '-') {
442                 const char *p = &argv[argi][1];
443                 
444                 if (!*p) goto print_usage_message;      /* "-" by itself not allowed */
445                 if (*p == '-') {
446                         if (!p[1]) {    /* "--" forces end of options */
447                                 argi++;
448                                 break;
449                         }
450                         /* it's a long option name - we don't support them */
451                         goto print_usage_message;
452                 }
453                 
454                 while (*p)
455                         switch (*p++) {
456                         case 'l':       display_fmt = FMT_LONG; break;
457                         case '1':       display_fmt = FMT_SINGLE; break;
458                         case 'x':       display_fmt = FMT_ROWS; break;
459                         case 'C':       display_fmt = FMT_COLUMNS; break;
460 #ifdef BB_FEATURE_LS_FILETYPES
461                         case 'p':       opts |= DISP_FTYPE; break;
462                         case 'F':       opts |= DISP_FTYPE|DISP_EXEC; break;
463 #endif
464                         case 'A':       opts |= DISP_HIDDEN; break;
465                         case 'a':       opts |= DISP_HIDDEN|DISP_DOT; break;
466                         case 'n':       opts |= DISP_NUMERIC; break;
467                         case 'd':       opts |= DIR_NOLIST; break;
468 #ifdef FEATURE_RECURSIVE
469                         case 'R':       opts |= DIR_RECURSE; break;
470 #endif
471 #ifdef BB_FEATURE_LS_TIMESTAMPS
472                         case 'u':       time_fmt = TIME_ACCESS; break;
473                         case 'c':       time_fmt = TIME_CHANGE; break;
474                         case 'e':       opts |= DISP_FULLTIME; break;
475 #endif
476                         default:        goto print_usage_message;
477                         }
478                 
479                 argi++;
480         }
481
482         /* choose a display format */
483         if (display_fmt == FMT_AUTO)
484                 display_fmt = isatty(fileno(stdout)) ? FMT_COLUMNS : FMT_SINGLE;
485         if (argi < argc - 1)
486                 opts |= DISP_DIRNAME; /* 2 or more items? label directories */
487 #ifdef BB_FEATURE_AUTOWIDTH
488         /* could add a -w option and/or TIOCGWINSZ call */
489         if (terminal_width < 1) terminal_width = TERMINAL_WIDTH;
490         
491         for (i = argi; i < argc; i++) {
492                 int len = strlen(argv[i]);
493                 if (column_width < len)
494                         column_width = len;
495         }
496 #endif
497
498         /* process files specified, or current directory if none */
499         i=0;
500         if (argi == argc)
501                 i = list_item(".");
502         while (argi < argc)
503                 i |= list_item(argv[argi++]);
504         newline();
505         exit( i);
506
507 print_usage_message:
508         usage (ls_usage);
509         exit( FALSE);
510 }
511