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