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