Release 4.20.
[wine.git] / programs / cmd / directory.c
blobc38bdfce0413032ffbadef336f2970c273c78e19
1 /*
2 * CMD - Wine-compatible command line interface - Directory functions.
4 * Copyright (C) 1999 D A Pickles
5 * Copyright (C) 2007 J Edmeades
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #define WIN32_LEAN_AND_MEAN
24 #include "wcmd.h"
25 #include "wine/debug.h"
27 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
29 typedef enum _DISPLAYTIME
31 Creation = 0,
32 Access,
33 Written
34 } DISPLAYTIME;
36 typedef enum _DISPLAYORDER
38 Name = 0,
39 Extension,
40 Size,
41 Date
42 } DISPLAYORDER;
44 static int file_total, dir_total, max_width;
45 static ULONGLONG byte_total;
46 static DISPLAYTIME dirTime;
47 static DISPLAYORDER dirOrder;
48 static BOOL orderReverse, orderGroupDirs, orderGroupDirsReverse, orderByCol;
49 static BOOL paged_mode, recurse, wide, bare, lower, shortname, usernames, separator;
50 static ULONG showattrs, attrsbits;
52 /*****************************************************************************
53 * WCMD_strrev
55 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
57 static WCHAR * WCMD_strrev (WCHAR *buff) {
59 int r, i;
60 WCHAR b;
62 r = lstrlenW (buff);
63 for (i=0; i<r/2; i++) {
64 b = buff[i];
65 buff[i] = buff[r-i-1];
66 buff[r-i-1] = b;
68 return (buff);
71 /*****************************************************************************
72 * WCMD_filesize64
74 * Convert a 64-bit number into a WCHARacter string, with commas every three digits.
75 * Result is returned in a static string overwritten with each call.
76 * FIXME: There must be a better algorithm!
78 static WCHAR * WCMD_filesize64 (ULONGLONG n) {
80 ULONGLONG q;
81 unsigned int r, i;
82 WCHAR *p;
83 static WCHAR buff[32];
85 p = buff;
86 i = -3;
87 do {
88 if (separator && ((++i)%3 == 1)) *p++ = ',';
89 q = n / 10;
90 r = n - (q * 10);
91 *p++ = r + '0';
92 *p = '\0';
93 n = q;
94 } while (n != 0);
95 WCMD_strrev (buff);
96 return buff;
99 /*****************************************************************************
100 * WCMD_dir_sort
102 * Sort based on the /O options supplied on the command line
104 static int __cdecl WCMD_dir_sort (const void *a, const void *b)
106 const WIN32_FIND_DATAW *filea = (const WIN32_FIND_DATAW *)a;
107 const WIN32_FIND_DATAW *fileb = (const WIN32_FIND_DATAW *)b;
108 int result = 0;
110 /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
111 requested sort order for the directory components */
112 if (orderGroupDirs &&
113 ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
114 (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
116 BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
117 if (aDir) result = -1;
118 else result = 1;
119 if (orderGroupDirsReverse) result = -result;
120 return result;
122 /* Order by Name: */
123 } else if (dirOrder == Name) {
124 result = lstrcmpiW(filea->cFileName, fileb->cFileName);
126 /* Order by Size: */
127 } else if (dirOrder == Size) {
128 ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
129 ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
130 if( sizea < sizeb ) result = -1;
131 else if( sizea == sizeb ) result = 0;
132 else result = 1;
134 /* Order by Date: (Takes into account which date (/T option) */
135 } else if (dirOrder == Date) {
137 const FILETIME *ft;
138 ULONG64 timea, timeb;
140 if (dirTime == Written) {
141 ft = &filea->ftLastWriteTime;
142 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
143 ft = &fileb->ftLastWriteTime;
144 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
145 } else if (dirTime == Access) {
146 ft = &filea->ftLastAccessTime;
147 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
148 ft = &fileb->ftLastAccessTime;
149 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
150 } else {
151 ft = &filea->ftCreationTime;
152 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
153 ft = &fileb->ftCreationTime;
154 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
156 if( timea < timeb ) result = -1;
157 else if( timea == timeb ) result = 0;
158 else result = 1;
160 /* Order by Extension: (Takes into account which date (/T option) */
161 } else if (dirOrder == Extension) {
162 WCHAR drive[10];
163 WCHAR dir[MAX_PATH];
164 WCHAR fname[MAX_PATH];
165 WCHAR extA[MAX_PATH];
166 WCHAR extB[MAX_PATH];
168 /* Split into components */
169 WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
170 WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
171 result = lstrcmpiW(extA, extB);
174 if (orderReverse) result = -result;
175 return result;
178 /*****************************************************************************
179 * WCMD_getfileowner
181 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
183 static void WCMD_getfileowner(WCHAR *filename, WCHAR *owner, int ownerlen) {
185 ULONG sizeNeeded = 0;
186 DWORD rc;
187 WCHAR name[MAXSTRING];
188 WCHAR domain[MAXSTRING];
190 /* In case of error, return empty string */
191 *owner = 0x00;
193 /* Find out how much space we need for the owner security descriptor */
194 GetFileSecurityW(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
195 rc = GetLastError();
197 if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
199 LPBYTE secBuffer;
200 PSID pSID = NULL;
201 BOOL defaulted = FALSE;
202 ULONG nameLen = MAXSTRING;
203 ULONG domainLen = MAXSTRING;
204 SID_NAME_USE nameuse;
206 secBuffer = heap_xalloc(sizeNeeded * sizeof(BYTE));
208 /* Get the owners security descriptor */
209 if(!GetFileSecurityW(filename, OWNER_SECURITY_INFORMATION, secBuffer,
210 sizeNeeded, &sizeNeeded)) {
211 heap_free(secBuffer);
212 return;
215 /* Get the SID from the SD */
216 if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
217 heap_free(secBuffer);
218 return;
221 /* Convert to a username */
222 if (LookupAccountSidW(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
223 static const WCHAR fmt[] = {'%','s','%','c','%','s','\0'};
224 swprintf(owner, ownerlen, fmt, domain, '\\', name);
226 heap_free(secBuffer);
228 return;
231 /*****************************************************************************
232 * WCMD_list_directory
234 * List a single file directory. This function (and those below it) can be called
235 * recursively when the /S switch is used.
237 * FIXME: Assumes 24-line display for the /P qualifier.
240 static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *inputparms, int level) {
242 WCHAR string[1024], datestring[32], timestring[32];
243 WCHAR real_path[MAX_PATH];
244 WIN32_FIND_DATAW *fd;
245 FILETIME ft;
246 SYSTEMTIME st;
247 HANDLE hff;
248 int dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
249 int numCols, numRows;
250 int rows, cols;
251 ULARGE_INTEGER byte_count, file_size;
252 DIRECTORY_STACK *parms;
253 int concurrentDirs = 0;
254 BOOL done_header = FALSE;
256 static const WCHAR fmtDir[] = {'%','1','!','1','0','s','!',' ',' ','%','2','!','8','s','!',' ',' ',
257 '<','D','I','R','>',' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
258 static const WCHAR fmtFile[] = {'%','1','!','1','0','s','!',' ',' ','%','2','!','8','s','!',' ',' ',
259 ' ',' ','%','3','!','1','0','s','!',' ',' ','\0'};
260 static const WCHAR fmt2[] = {'%','1','!','-','1','3','s','!','\0'};
261 static const WCHAR fmt3[] = {'%','1','!','-','2','3','s','!','\0'};
262 static const WCHAR fmt4[] = {'%','1','\0'};
263 static const WCHAR fmt5[] = {'%','1','%','2','\0'};
265 dir_count = 0;
266 file_count = 0;
267 entry_count = 0;
268 byte_count.QuadPart = 0;
269 widest = 0;
270 cur_width = 0;
272 /* Loop merging all the files from consecutive parms which relate to the
273 same directory. Note issuing a directory header with no contents
274 mirrors what windows does */
275 parms = inputparms;
276 fd = heap_xalloc(sizeof(WIN32_FIND_DATAW));
277 while (parms && lstrcmpW(inputparms->dirName, parms->dirName) == 0) {
278 concurrentDirs++;
280 /* Work out the full path + filename */
281 lstrcpyW(real_path, parms->dirName);
282 lstrcatW(real_path, parms->fileName);
284 /* Load all files into an in memory structure */
285 WINE_TRACE("Looking for matches to '%s'\n", wine_dbgstr_w(real_path));
286 hff = FindFirstFileW(real_path, &fd[entry_count]);
287 if (hff != INVALID_HANDLE_VALUE) {
288 do {
289 /* Skip any which are filtered out by attribute */
290 if ((fd[entry_count].dwFileAttributes & attrsbits) != showattrs) continue;
292 entry_count++;
294 /* Keep running track of longest filename for wide output */
295 if (wide || orderByCol) {
296 int tmpLen = lstrlenW(fd[entry_count-1].cFileName) + 3;
297 if (fd[entry_count-1].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
298 if (tmpLen > widest) widest = tmpLen;
301 fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATAW));
302 if (fd == NULL) {
303 FindClose (hff);
304 WINE_ERR("Out of memory\n");
305 errorlevel = 1;
306 return parms->next;
308 } while (FindNextFileW(hff, &fd[entry_count]) != 0);
309 FindClose (hff);
312 /* Work out the actual current directory name without a trailing \ */
313 lstrcpyW(real_path, parms->dirName);
314 real_path[lstrlenW(parms->dirName)-1] = 0x00;
316 /* Output the results */
317 if (!bare) {
318 if (level != 0 && (entry_count > 0)) WCMD_output_asis (newlineW);
319 if (!recurse || ((entry_count > 0) && done_header==FALSE)) {
320 static const WCHAR headerW[] = {'D','i','r','e','c','t','o','r','y',' ','o','f',
321 ' ','%','1','\n','\n','\0'};
322 WCMD_output (headerW, real_path);
323 done_header = TRUE;
327 /* Move to next parm */
328 parms = parms->next;
331 /* Handle case where everything is filtered out */
332 if (entry_count > 0) {
334 /* Sort the list of files */
335 qsort (fd, entry_count, sizeof(WIN32_FIND_DATAW), WCMD_dir_sort);
337 /* Work out the number of columns */
338 WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
339 if (wide || orderByCol) {
340 numCols = max(1, max_width / widest);
341 numRows = entry_count / numCols;
342 if (entry_count % numCols) numRows++;
343 } else {
344 numCols = 1;
345 numRows = entry_count;
347 WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
349 for (rows=0; rows<numRows; rows++) {
350 BOOL addNewLine = TRUE;
351 for (cols=0; cols<numCols; cols++) {
352 WCHAR username[24];
354 /* Work out the index of the entry being pointed to */
355 if (orderByCol) {
356 i = (cols * numRows) + rows;
357 if (i >= entry_count) continue;
358 } else {
359 i = (rows * numCols) + cols;
360 if (i >= entry_count) continue;
363 /* /L convers all names to lower case */
364 if (lower) {
365 WCHAR *p = fd[i].cFileName;
366 while ( (*p = tolower(*p)) ) ++p;
369 /* /Q gets file ownership information */
370 if (usernames) {
371 lstrcpyW (string, inputparms->dirName);
372 lstrcatW (string, fd[i].cFileName);
373 WCMD_getfileowner(string, username, ARRAY_SIZE(username));
376 if (dirTime == Written) {
377 FileTimeToLocalFileTime (&fd[i].ftLastWriteTime, &ft);
378 } else if (dirTime == Access) {
379 FileTimeToLocalFileTime (&fd[i].ftLastAccessTime, &ft);
380 } else {
381 FileTimeToLocalFileTime (&fd[i].ftCreationTime, &ft);
383 FileTimeToSystemTime (&ft, &st);
384 GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring, ARRAY_SIZE(datestring));
385 GetTimeFormatW(0, TIME_NOSECONDS, &st, NULL, timestring, ARRAY_SIZE(timestring));
387 if (wide) {
389 tmp_width = cur_width;
390 if (fd[i].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
391 static const WCHAR fmt[] = {'[','%','1',']','\0'};
392 WCMD_output (fmt, fd[i].cFileName);
393 dir_count++;
394 tmp_width = tmp_width + lstrlenW(fd[i].cFileName) + 2;
395 } else {
396 static const WCHAR fmt[] = {'%','1','\0'};
397 WCMD_output (fmt, fd[i].cFileName);
398 tmp_width = tmp_width + lstrlenW(fd[i].cFileName) ;
399 file_count++;
400 file_size.u.LowPart = fd[i].nFileSizeLow;
401 file_size.u.HighPart = fd[i].nFileSizeHigh;
402 byte_count.QuadPart += file_size.QuadPart;
404 cur_width = cur_width + widest;
406 if ((cur_width + widest) > max_width) {
407 cur_width = 0;
408 } else {
409 static const WCHAR padfmt[] = {'%','1','!','*','s','!','\0'};
410 WCMD_output(padfmt, cur_width - tmp_width, nullW);
413 } else if (fd[i].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
414 dir_count++;
416 if (!bare) {
417 WCMD_output (fmtDir, datestring, timestring);
418 if (shortname) WCMD_output (fmt2, fd[i].cAlternateFileName);
419 if (usernames) WCMD_output (fmt3, username);
420 WCMD_output(fmt4,fd[i].cFileName);
421 } else {
422 if (!((lstrcmpW(fd[i].cFileName, dotW) == 0) ||
423 (lstrcmpW(fd[i].cFileName, dotdotW) == 0))) {
424 WCMD_output (fmt5, recurse?inputparms->dirName:nullW, fd[i].cFileName);
425 } else {
426 addNewLine = FALSE;
430 else {
431 file_count++;
432 file_size.u.LowPart = fd[i].nFileSizeLow;
433 file_size.u.HighPart = fd[i].nFileSizeHigh;
434 byte_count.QuadPart += file_size.QuadPart;
435 if (!bare) {
436 WCMD_output (fmtFile, datestring, timestring,
437 WCMD_filesize64(file_size.QuadPart));
438 if (shortname) WCMD_output (fmt2, fd[i].cAlternateFileName);
439 if (usernames) WCMD_output (fmt3, username);
440 WCMD_output(fmt4,fd[i].cFileName);
441 } else {
442 WCMD_output (fmt5, recurse?inputparms->dirName:nullW, fd[i].cFileName);
446 if (addNewLine) WCMD_output_asis (newlineW);
447 cur_width = 0;
450 if (!bare) {
451 if (file_count == 1) {
452 static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ',
453 '%','1','!','2','5','s','!',' ','b','y','t','e','s','\n','\0'};
454 WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart));
456 else {
457 static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','f','i','l','e','s',' ','%','2','!','2','4','s','!',
458 ' ','b','y','t','e','s','\n','\0'};
459 WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart));
462 byte_total = byte_total + byte_count.QuadPart;
463 file_total = file_total + file_count;
464 dir_total = dir_total + dir_count;
466 if (!bare && !recurse) {
467 if (dir_count == 1) {
468 static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','y',
469 ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
470 WCMD_output (fmt, 1);
471 } else {
472 static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','i',
473 'e','s','\0'};
474 WCMD_output (fmt, dir_count);
478 heap_free(fd);
480 /* When recursing, look in all subdirectories for matches */
481 if (recurse) {
482 DIRECTORY_STACK *dirStack = NULL;
483 DIRECTORY_STACK *lastEntry = NULL;
484 WIN32_FIND_DATAW finddata;
486 /* Build path to search */
487 lstrcpyW(string, inputparms->dirName);
488 lstrcatW(string, starW);
490 WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
491 hff = FindFirstFileW(string, &finddata);
492 if (hff != INVALID_HANDLE_VALUE) {
493 do {
494 if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
495 (lstrcmpW(finddata.cFileName, dotdotW) != 0) &&
496 (lstrcmpW(finddata.cFileName, dotW) != 0)) {
498 DIRECTORY_STACK *thisDir;
499 int dirsToCopy = concurrentDirs;
501 /* Loop creating list of subdirs for all concurrent entries */
502 parms = inputparms;
503 while (dirsToCopy > 0) {
504 dirsToCopy--;
506 /* Work out search parameter in sub dir */
507 lstrcpyW (string, inputparms->dirName);
508 lstrcatW (string, finddata.cFileName);
509 lstrcatW (string, slashW);
510 WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));
512 /* Allocate memory, add to list */
513 thisDir = heap_xalloc(sizeof(DIRECTORY_STACK));
514 if (dirStack == NULL) dirStack = thisDir;
515 if (lastEntry != NULL) lastEntry->next = thisDir;
516 lastEntry = thisDir;
517 thisDir->next = NULL;
518 thisDir->dirName = heap_strdupW(string);
519 thisDir->fileName = heap_strdupW(parms->fileName);
520 parms = parms->next;
523 } while (FindNextFileW(hff, &finddata) != 0);
524 FindClose (hff);
526 while (dirStack != NULL) {
527 DIRECTORY_STACK *thisDir = dirStack;
528 dirStack = WCMD_list_directory (thisDir, 1);
529 while (thisDir != dirStack) {
530 DIRECTORY_STACK *tempDir = thisDir->next;
531 heap_free(thisDir->dirName);
532 heap_free(thisDir->fileName);
533 heap_free(thisDir);
534 thisDir = tempDir;
540 /* Handle case where everything is filtered out */
541 if ((file_total + dir_total == 0) && (level == 0)) {
542 SetLastError (ERROR_FILE_NOT_FOUND);
543 WCMD_print_error ();
544 errorlevel = 1;
547 return parms;
550 /*****************************************************************************
551 * WCMD_dir_trailer
553 * Print out the trailer for the supplied drive letter
555 static void WCMD_dir_trailer(WCHAR drive) {
556 ULARGE_INTEGER avail, total, freebytes;
557 DWORD status;
558 WCHAR driveName[] = {'c',':','\\','\0'};
560 driveName[0] = drive;
561 status = GetDiskFreeSpaceExW(driveName, &avail, &total, &freebytes);
562 WINE_TRACE("Writing trailer for '%s' gave %d(%d)\n", wine_dbgstr_w(driveName),
563 status, GetLastError());
565 if (errorlevel==0 && !bare) {
566 if (recurse) {
567 static const WCHAR fmt1[] = {'\n',' ',' ',' ',' ',' ','T','o','t','a','l',' ','f','i','l','e','s',
568 ' ','l','i','s','t','e','d',':','\n','%','1','!','8','d','!',' ','f','i','l','e',
569 's','%','2','!','2','5','s','!',' ','b','y','t','e','s','\n','\0'};
570 static const WCHAR fmt2[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','i','e','s',' ','%',
571 '2','!','1','8','s','!',' ','b','y','t','e','s',' ','f','r','e','e','\n','\n',
572 '\0'};
573 WCMD_output (fmt1, file_total, WCMD_filesize64 (byte_total));
574 WCMD_output (fmt2, dir_total, WCMD_filesize64 (freebytes.QuadPart));
575 } else {
576 static const WCHAR fmt[] = {' ','%','1','!','1','8','s','!',' ','b','y','t','e','s',' ','f','r','e','e',
577 '\n','\n','\0'};
578 WCMD_output (fmt, WCMD_filesize64 (freebytes.QuadPart));
583 /*****************************************************************************
584 * WCMD_directory
586 * List a file directory.
590 void WCMD_directory (WCHAR *args)
592 WCHAR path[MAX_PATH], cwd[MAX_PATH];
593 DWORD status;
594 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
595 WCHAR *p;
596 WCHAR string[MAXSTRING];
597 int argno = 0;
598 WCHAR *argN = args;
599 WCHAR lastDrive;
600 BOOL trailerReqd = FALSE;
601 DIRECTORY_STACK *fullParms = NULL;
602 DIRECTORY_STACK *prevEntry = NULL;
603 DIRECTORY_STACK *thisEntry = NULL;
604 WCHAR drive[10];
605 WCHAR dir[MAX_PATH];
606 WCHAR fname[MAX_PATH];
607 WCHAR ext[MAX_PATH];
608 static const WCHAR dircmdW[] = {'D','I','R','C','M','D','\0'};
610 errorlevel = 0;
612 /* Prefill quals with (uppercased) DIRCMD env var */
613 if (GetEnvironmentVariableW(dircmdW, string, ARRAY_SIZE(string))) {
614 p = string;
615 while ( (*p = toupper(*p)) ) ++p;
616 lstrcatW(string,quals);
617 lstrcpyW(quals, string);
620 byte_total = 0;
621 file_total = dir_total = 0;
623 /* Initialize all flags to their defaults as if no DIRCMD or quals */
624 paged_mode = FALSE;
625 recurse = FALSE;
626 wide = FALSE;
627 bare = FALSE;
628 lower = FALSE;
629 shortname = FALSE;
630 usernames = FALSE;
631 orderByCol = FALSE;
632 separator = TRUE;
633 dirTime = Written;
634 dirOrder = Name;
635 orderReverse = FALSE;
636 orderGroupDirs = FALSE;
637 orderGroupDirsReverse = FALSE;
638 showattrs = 0;
639 attrsbits = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
641 /* Handle args - Loop through so right most is the effective one */
642 /* Note: /- appears to be a negate rather than an off, eg. dir
643 /-W is wide, or dir /w /-w /-w is also wide */
644 p = quals;
645 while (*p && (*p=='/' || *p==' ')) {
646 BOOL negate = FALSE;
647 if (*p++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
649 if (*p=='-') {
650 negate = TRUE;
651 p++;
654 WINE_TRACE("Processing arg '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
655 switch (*p) {
656 case 'P': if (negate) paged_mode = !paged_mode;
657 else paged_mode = TRUE;
658 break;
659 case 'S': if (negate) recurse = !recurse;
660 else recurse = TRUE;
661 break;
662 case 'W': if (negate) wide = !wide;
663 else wide = TRUE;
664 break;
665 case 'B': if (negate) bare = !bare;
666 else bare = TRUE;
667 break;
668 case 'L': if (negate) lower = !lower;
669 else lower = TRUE;
670 break;
671 case 'X': if (negate) shortname = !shortname;
672 else shortname = TRUE;
673 break;
674 case 'Q': if (negate) usernames = !usernames;
675 else usernames = TRUE;
676 break;
677 case 'D': if (negate) orderByCol = !orderByCol;
678 else orderByCol = TRUE;
679 break;
680 case 'C': if (negate) separator = !separator;
681 else separator = TRUE;
682 break;
683 case 'T': p = p + 1;
684 if (*p==':') p++; /* Skip optional : */
686 if (*p == 'A') dirTime = Access;
687 else if (*p == 'C') dirTime = Creation;
688 else if (*p == 'W') dirTime = Written;
690 /* Support /T and /T: with no parms, default to written */
691 else if (*p == 0x00 || *p == '/') {
692 dirTime = Written;
693 p = p - 1; /* So when step on, move to '/' */
694 } else {
695 SetLastError(ERROR_INVALID_PARAMETER);
696 WCMD_print_error();
697 errorlevel = 1;
698 return;
700 break;
701 case 'O': p = p + 1;
702 if (*p==':') p++; /* Skip optional : */
703 while (*p && *p != '/') {
704 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
705 switch (*p) {
706 case 'N': dirOrder = Name; break;
707 case 'E': dirOrder = Extension; break;
708 case 'S': dirOrder = Size; break;
709 case 'D': dirOrder = Date; break;
710 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
711 else orderReverse = TRUE;
712 break;
713 case 'G': orderGroupDirs = TRUE; break;
714 default:
715 SetLastError(ERROR_INVALID_PARAMETER);
716 WCMD_print_error();
717 errorlevel = 1;
718 return;
720 p++;
722 p = p - 1; /* So when step on, move to '/' */
723 break;
724 case 'A': p = p + 1;
725 showattrs = 0;
726 attrsbits = 0;
727 if (*p==':') p++; /* Skip optional : */
728 while (*p && *p != '/') {
729 BOOL anegate = FALSE;
730 ULONG mask;
732 /* Note /A: - options are 'offs' not toggles */
733 if (*p=='-') {
734 anegate = TRUE;
735 p++;
738 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
739 switch (*p) {
740 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
741 case 'H': mask = FILE_ATTRIBUTE_HIDDEN; break;
742 case 'S': mask = FILE_ATTRIBUTE_SYSTEM; break;
743 case 'R': mask = FILE_ATTRIBUTE_READONLY; break;
744 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE; break;
745 default:
746 SetLastError(ERROR_INVALID_PARAMETER);
747 WCMD_print_error();
748 errorlevel = 1;
749 return;
752 /* Keep running list of bits we care about */
753 attrsbits |= mask;
755 /* Mask shows what MUST be in the bits we care about */
756 if (anegate) showattrs = showattrs & ~mask;
757 else showattrs |= mask;
759 p++;
761 p = p - 1; /* So when step on, move to '/' */
762 WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
763 break;
764 default:
765 SetLastError(ERROR_INVALID_PARAMETER);
766 WCMD_print_error();
767 errorlevel = 1;
768 return;
770 p = p + 1;
773 /* Handle conflicting args and initialization */
774 if (bare || shortname) wide = FALSE;
775 if (bare) shortname = FALSE;
776 if (wide) usernames = FALSE;
777 if (orderByCol) wide = TRUE;
779 if (wide) {
780 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
781 max_width = consoleInfo.dwSize.X;
782 else
783 max_width = 80;
785 if (paged_mode) {
786 WCMD_enter_paged_mode(NULL);
789 argno = 0;
790 argN = args;
791 GetCurrentDirectoryW(MAX_PATH, cwd);
792 lstrcatW(cwd, slashW);
794 /* Loop through all args, calculating full effective directory */
795 fullParms = NULL;
796 prevEntry = NULL;
797 while (argN) {
798 WCHAR fullname[MAXSTRING];
799 WCHAR *thisArg = WCMD_parameter(args, argno++, &argN, FALSE, FALSE);
800 if (argN && argN[0] != '/') {
802 WINE_TRACE("Found parm '%s'\n", wine_dbgstr_w(thisArg));
803 if (thisArg[1] == ':' && thisArg[2] == '\\') {
804 lstrcpyW(fullname, thisArg);
805 } else if (thisArg[1] == ':' && thisArg[2] != '\\') {
806 WCHAR envvar[4];
807 static const WCHAR envFmt[] = {'=','%','c',':','\0'};
808 wsprintfW(envvar, envFmt, thisArg[0]);
809 if (!GetEnvironmentVariableW(envvar, fullname, MAX_PATH)) {
810 static const WCHAR noEnvFmt[] = {'%','c',':','\0'};
811 wsprintfW(fullname, noEnvFmt, thisArg[0]);
813 lstrcatW(fullname, slashW);
814 lstrcatW(fullname, &thisArg[2]);
815 } else if (thisArg[0] == '\\') {
816 memcpy(fullname, cwd, 2 * sizeof(WCHAR));
817 lstrcpyW(fullname+2, thisArg);
818 } else {
819 lstrcpyW(fullname, cwd);
820 lstrcatW(fullname, thisArg);
822 WINE_TRACE("Using location '%s'\n", wine_dbgstr_w(fullname));
824 status = GetFullPathNameW(fullname, ARRAY_SIZE(path), path, NULL);
827 * If the path supplied does not include a wildcard, and the endpoint of the
828 * path references a directory, we need to list the *contents* of that
829 * directory not the directory file itself.
831 if ((wcschr(path, '*') == NULL) && (wcschr(path, '%') == NULL)) {
832 status = GetFileAttributesW(path);
833 if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
834 if (!ends_with_backslash( path )) lstrcatW( path, slashW );
835 lstrcatW (path, starW);
837 } else {
838 /* Special case wildcard search with no extension (ie parameters ending in '.') as
839 GetFullPathName strips off the additional '.' */
840 if (fullname[lstrlenW(fullname)-1] == '.') lstrcatW(path, dotW);
843 WINE_TRACE("Using path '%s'\n", wine_dbgstr_w(path));
844 thisEntry = heap_xalloc(sizeof(DIRECTORY_STACK));
845 if (fullParms == NULL) fullParms = thisEntry;
846 if (prevEntry != NULL) prevEntry->next = thisEntry;
847 prevEntry = thisEntry;
848 thisEntry->next = NULL;
850 /* Split into components */
851 WCMD_splitpath(path, drive, dir, fname, ext);
852 WINE_TRACE("Path Parts: drive: '%s' dir: '%s' name: '%s' ext:'%s'\n",
853 wine_dbgstr_w(drive), wine_dbgstr_w(dir),
854 wine_dbgstr_w(fname), wine_dbgstr_w(ext));
856 thisEntry->dirName = heap_xalloc(sizeof(WCHAR) * (lstrlenW(drive)+lstrlenW(dir)+1));
857 lstrcpyW(thisEntry->dirName, drive);
858 lstrcatW(thisEntry->dirName, dir);
860 thisEntry->fileName = heap_xalloc(sizeof(WCHAR) * (lstrlenW(fname)+lstrlenW(ext)+1));
861 lstrcpyW(thisEntry->fileName, fname);
862 lstrcatW(thisEntry->fileName, ext);
867 /* If just 'dir' entered, a '*' parameter is assumed */
868 if (fullParms == NULL) {
869 WINE_TRACE("Inserting default '*'\n");
870 fullParms = heap_xalloc(sizeof(DIRECTORY_STACK));
871 fullParms->next = NULL;
872 fullParms->dirName = heap_strdupW(cwd);
873 fullParms->fileName = heap_strdupW(starW);
876 lastDrive = '?';
877 prevEntry = NULL;
878 thisEntry = fullParms;
879 trailerReqd = FALSE;
881 while (thisEntry != NULL) {
883 /* Output disk free (trailer) and volume information (header) if the drive
884 letter changes */
885 if (lastDrive != toupper(thisEntry->dirName[0])) {
887 /* Trailer Information */
888 if (lastDrive != '?') {
889 trailerReqd = FALSE;
890 WCMD_dir_trailer(prevEntry->dirName[0]);
893 lastDrive = toupper(thisEntry->dirName[0]);
895 if (!bare) {
896 WCHAR drive[3];
898 WINE_TRACE("Writing volume for '%c:'\n", thisEntry->dirName[0]);
899 memcpy(drive, thisEntry->dirName, 2 * sizeof(WCHAR));
900 drive[2] = 0x00;
901 status = WCMD_volume (0, drive);
902 trailerReqd = TRUE;
903 if (!status) {
904 errorlevel = 1;
905 goto exit;
908 } else {
909 static const WCHAR newLine2[] = {'\n','\n','\0'};
910 if (!bare) WCMD_output_asis (newLine2);
913 /* Clear any errors from previous invocations, and process it */
914 errorlevel = 0;
915 prevEntry = thisEntry;
916 thisEntry = WCMD_list_directory (thisEntry, 0);
919 /* Trailer Information */
920 if (trailerReqd) {
921 WCMD_dir_trailer(prevEntry->dirName[0]);
924 exit:
925 if (paged_mode) WCMD_leave_paged_mode();
927 /* Free storage allocated for parms */
928 while (fullParms != NULL) {
929 prevEntry = fullParms;
930 fullParms = prevEntry->next;
931 heap_free(prevEntry->dirName);
932 heap_free(prevEntry->fileName);
933 heap_free(prevEntry);