cmd.exe: Add DIR /X support.
[wine] / programs / cmd / directory.c
1 /*
2  * CMD - Wine-compatible command line interface - Directory functions.
3  *
4  * Copyright (C) 1999 D A Pickles
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /*
22  * NOTES:
23  * On entry, global variables quals, param1, param2 contain
24  * the qualifiers (uppercased and concatenated) and parameters entered, with
25  * environment-variable and batch parameter substitution already done.
26  */
27
28 #define WIN32_LEAN_AND_MEAN
29
30 #include "wcmd.h"
31
32 int WCMD_dir_sort (const void *a, const void *b);
33 void WCMD_list_directory (char *path, int level);
34 char * WCMD_filesize64 (ULONGLONG free);
35 char * WCMD_strrev (char *buff);
36
37
38 extern int echo_mode;
39 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
40 extern DWORD errorlevel;
41
42 typedef enum _DISPLAYTIME
43 {
44     Creation = 0,
45     Access,
46     Written
47 } DISPLAYTIME;
48
49 static int file_total, dir_total, recurse, wide, bare, max_width, lower;
50 static int shortname;
51 static ULONGLONG byte_total;
52 static DISPLAYTIME dirTime;
53
54 /*****************************************************************************
55  * WCMD_directory
56  *
57  * List a file directory.
58  *
59  */
60
61 void WCMD_directory (void) {
62
63   char path[MAX_PATH], drive[8];
64   int status, paged_mode;
65   ULARGE_INTEGER avail, total, free;
66   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
67   char *p;
68
69   byte_total = 0;
70   file_total = dir_total = 0;
71   dirTime = Written;
72
73   /* Handle args */
74   paged_mode = (strstr(quals, "/P") != NULL);
75   recurse    = (strstr(quals, "/S") != NULL);
76   wide       = (strstr(quals, "/W") != NULL);
77   bare       = (strstr(quals, "/B") != NULL);
78   lower      = (strstr(quals, "/L") != NULL);
79   shortname  = (strstr(quals, "/X") != NULL);
80
81   if ((p = strstr(quals, "/T")) != NULL) {
82     p = p + 2;
83     if (*p==':') p++;  /* Skip optional : */
84
85     if (*p == 'A') dirTime = Access;
86     else if (*p == 'C') dirTime = Creation;
87     else if (*p == 'W') dirTime = Written;
88
89     /* Support /T and /T: with no parms, default to written */
90     else if (*p == '/') dirTime = Written;
91     else {
92       SetLastError(ERROR_INVALID_PARAMETER);
93       WCMD_print_error();
94       return;
95     }
96   }
97
98   /* Handle conflicting args and initialization */
99   if (bare || shortname) wide = FALSE;
100   if (bare) shortname = FALSE;
101
102   if (wide) {
103       if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
104           max_width = consoleInfo.dwSize.X;
105       else
106           max_width = 80;
107   }
108   if (paged_mode) {
109      WCMD_enter_paged_mode();
110   }
111
112   if (param1[0] == '\0') strcpy (param1, ".");
113   status = GetFullPathName (param1, sizeof(path), path, NULL);
114   if (!status) {
115     WCMD_print_error();
116     if (paged_mode) WCMD_leave_paged_mode();
117     return;
118   }
119   lstrcpyn (drive, path, 3);
120
121   if (!bare) {
122      status = WCMD_volume (0, drive);
123      if (!status) {
124          if (paged_mode) WCMD_leave_paged_mode();
125        return;
126      }
127   }
128
129   WCMD_list_directory (path, 0);
130   lstrcpyn (drive, path, 4);
131   GetDiskFreeSpaceEx (drive, &avail, &total, &free);
132
133   if (!bare) {
134      if (recurse) {
135        WCMD_output ("\n\n     Total files listed:\n%8d files%25s bytes\n",
136             file_total, WCMD_filesize64 (byte_total));
137        WCMD_output ("%8d directories %18s bytes free\n\n",
138             dir_total, WCMD_filesize64 (free.QuadPart));
139      } else {
140        WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free.QuadPart));
141      }
142   }
143   if (paged_mode) WCMD_leave_paged_mode();
144 }
145
146 /*****************************************************************************
147  * WCMD_list_directory
148  *
149  * List a single file directory. This function (and those below it) can be called
150  * recursively when the /S switch is used.
151  *
152  * FIXME: Entries sorted by name only. Should we support DIRCMD??
153  * FIXME: Assumes 24-line display for the /P qualifier.
154  * FIXME: Other command qualifiers not supported.
155  * FIXME: DIR /S FILENAME fails if at least one matching file is not found in the top level.
156  */
157
158 void WCMD_list_directory (char *search_path, int level) {
159
160   char string[1024], datestring[32], timestring[32];
161   char *p;
162   char real_path[MAX_PATH];
163   WIN32_FIND_DATA *fd;
164   FILETIME ft;
165   SYSTEMTIME st;
166   HANDLE hff;
167   int status, dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
168   ULARGE_INTEGER byte_count, file_size;
169
170   dir_count = 0;
171   file_count = 0;
172   entry_count = 0;
173   byte_count.QuadPart = 0;
174   widest = 0;
175   cur_width = 0;
176
177 /*
178  *  If the path supplied does not include a wildcard, and the endpoint of the
179  *  path references a directory, we need to list the *contents* of that
180  *  directory not the directory file itself.
181  */
182
183   if ((strchr(search_path, '*') == NULL) && (strchr(search_path, '%') == NULL)) {
184     status = GetFileAttributes (search_path);
185     if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
186       if (search_path[strlen(search_path)-1] == '\\') {
187         strcat (search_path, "*");
188       }
189       else {
190         strcat (search_path, "\\*");
191       }
192     }
193   }
194
195   /* Work out the actual current directory name */
196   p = strrchr (search_path, '\\');
197   memset(real_path, 0x00, sizeof(real_path));
198   lstrcpyn (real_path, search_path, (p-search_path+2));
199
200   /* Load all files into an in memory structure */
201   fd = malloc (sizeof(WIN32_FIND_DATA));
202   hff = FindFirstFile (search_path, fd);
203   if (hff == INVALID_HANDLE_VALUE) {
204     SetLastError (ERROR_FILE_NOT_FOUND);
205     WCMD_print_error ();
206     free (fd);
207     return;
208   }
209   do {
210     entry_count++;
211
212     /* Keep running track of longest filename for wide output */
213     if (wide) {
214        int tmpLen = strlen((fd+(entry_count-1))->cFileName) + 3;
215        if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
216        if (tmpLen > widest) widest = tmpLen;
217     }
218
219     fd = realloc (fd, (entry_count+1)*sizeof(WIN32_FIND_DATA));
220     if (fd == NULL) {
221       FindClose (hff);
222       WCMD_output ("Memory Allocation Error");
223        return;
224     }
225   } while (FindNextFile(hff, (fd+entry_count)) != 0);
226   FindClose (hff);
227
228   /* Sort the list of files */
229   qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
230
231   /* Output the results */
232   if (!bare) {
233      if (level != 0) WCMD_output ("\n\n");
234      WCMD_output ("Directory of %s\n\n", real_path);
235   }
236
237   for (i=0; i<entry_count; i++) {
238
239     /* /L convers all names to lower case */
240     if (lower) {
241         char *p = (fd+i)->cFileName;
242         while ( (*p = tolower(*p)) ) ++p;
243     }
244
245     if (dirTime == Written) {
246       FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
247     } else if (dirTime == Access) {
248       FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
249     } else {
250       FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
251     }
252     FileTimeToSystemTime (&ft, &st);
253     GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
254                 sizeof(datestring));
255     GetTimeFormat (0, TIME_NOSECONDS, &st,
256                 NULL, timestring, sizeof(timestring));
257
258     if (wide) {
259
260       tmp_width = cur_width;
261       if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
262           WCMD_output ("[%s]", (fd+i)->cFileName);
263           dir_count++;
264           tmp_width = tmp_width + strlen((fd+i)->cFileName) + 2;
265       } else {
266           WCMD_output ("%s", (fd+i)->cFileName);
267           tmp_width = tmp_width + strlen((fd+i)->cFileName) ;
268           file_count++;
269           file_size.u.LowPart = (fd+i)->nFileSizeLow;
270           file_size.u.HighPart = (fd+i)->nFileSizeHigh;
271       byte_count.QuadPart += file_size.QuadPart;
272       }
273       cur_width = cur_width + widest;
274
275       if ((cur_width + widest) > max_width) {
276           WCMD_output ("\n");
277           cur_width = 0;
278       } else {
279           WCMD_output ("%*.s", (tmp_width - cur_width) ,"");
280       }
281
282     } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
283       dir_count++;
284
285       if (!bare) {
286          if (shortname) {
287              WCMD_output ("%10s  %8s  <DIR>         %-13s%s\n",
288                      datestring, timestring, (fd+i)->cAlternateFileName, (fd+i)->cFileName);
289          } else {
290              WCMD_output ("%10s  %8s  <DIR>         %s\n",
291                      datestring, timestring, (fd+i)->cFileName);
292          }
293       } else {
294          if (!((strcmp((fd+i)->cFileName, ".") == 0) ||
295                (strcmp((fd+i)->cFileName, "..") == 0))) {
296             WCMD_output ("%s%s\n", recurse?real_path:"", (fd+i)->cFileName);
297          }
298       }
299     }
300     else {
301       file_count++;
302       file_size.u.LowPart = (fd+i)->nFileSizeLow;
303       file_size.u.HighPart = (fd+i)->nFileSizeHigh;
304       byte_count.QuadPart += file_size.QuadPart;
305       if (!bare) {
306          if (shortname) {
307              WCMD_output ("%10s  %8s    %10s  %-13s%s\n",
308                  datestring, timestring,
309                  WCMD_filesize64(file_size.QuadPart), (fd+i)->cAlternateFileName, (fd+i)->cFileName);
310          } else {
311              WCMD_output ("%10s  %8s    %10s  %s\n",
312                  datestring, timestring,
313                  WCMD_filesize64(file_size.QuadPart), (fd+i)->cFileName);
314          }
315       } else {
316          WCMD_output ("%s%s\n", recurse?real_path:"", (fd+i)->cFileName);
317       }
318     }
319   }
320
321   if (wide && cur_width>0) {
322       WCMD_output ("\n");
323   }
324
325   if (!bare) {
326      if (file_count == 1) {
327        WCMD_output ("       1 file %25s bytes\n", WCMD_filesize64 (byte_count.QuadPart));
328      }
329      else {
330        WCMD_output ("%8d files %24s bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
331      }
332   }
333   byte_total = byte_total + byte_count.QuadPart;
334   file_total = file_total + file_count;
335   dir_total = dir_total + dir_count;
336
337   if (!bare) {
338      if (dir_count == 1) WCMD_output ("1 directory         ");
339      else WCMD_output ("%8d directories", dir_count);
340   }
341   for (i=0; i<entry_count; i++) {
342     if ((recurse) &&
343           ((fd+i)->cFileName[0] != '.') &&
344           ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
345 #if 0
346       GetFullPathName ((fd+i)->cFileName, sizeof(string), string, NULL);
347 #endif
348       p = strrchr (search_path, '\\');
349       lstrcpyn (string, search_path, (p-search_path+2));
350       lstrcat (string, (fd+i)->cFileName);
351       lstrcat (string, p);
352       WCMD_list_directory (string, 1);
353     }
354   }
355   free (fd);
356   return;
357 }
358
359 /*****************************************************************************
360  * WCMD_filesize64
361  *
362  * Convert a 64-bit number into a character string, with commas every three digits.
363  * Result is returned in a static string overwritten with each call.
364  * FIXME: There must be a better algorithm!
365  */
366
367 char * WCMD_filesize64 (ULONGLONG n) {
368
369   ULONGLONG q;
370   unsigned int r, i;
371   char *p;
372   static char buff[32];
373
374   p = buff;
375   i = -3;
376   do {
377     if ((++i)%3 == 1) *p++ = ',';
378     q = n / 10;
379     r = n - (q * 10);
380     *p++ = r + '0';
381     *p = '\0';
382     n = q;
383   } while (n != 0);
384   WCMD_strrev (buff);
385   return buff;
386 }
387
388 /*****************************************************************************
389  * WCMD_strrev
390  *
391  * Reverse a character string in-place (strrev() is not available under unixen :-( ).
392  */
393
394 char * WCMD_strrev (char *buff) {
395
396   int r, i;
397   char b;
398
399   r = lstrlen (buff);
400   for (i=0; i<r/2; i++) {
401     b = buff[i];
402     buff[i] = buff[r-i-1];
403     buff[r-i-1] = b;
404   }
405   return (buff);
406 }
407
408
409 int WCMD_dir_sort (const void *a, const void *b)
410 {
411   return (lstrcmpi(((const WIN32_FIND_DATA *)a)->cFileName,
412                    ((const WIN32_FIND_DATA *)b)->cFileName));
413 }