2 * CMD - Wine-compatible command line interface - built-in functions.
4 * Copyright (C) 1999 D A Pickles
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.
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.
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
23 * On entry to each function, 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.
30 * - No support for pipes, shell parameters
31 * - Lots of functionality missing from builtins
32 * - Messages etc need international support
35 #define WIN32_LEAN_AND_MEAN
39 #include "wine/debug.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
43 void WCMD_execute (char *orig_command, char *parameter, char *substitution);
45 struct env_stack *saved_environment;
46 struct env_stack *pushd_directories;
48 extern HINSTANCE hinst;
49 extern char *inbuilt[];
50 extern int echo_mode, verify_mode, defaultColor;
51 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
52 extern BATCH_CONTEXT *context;
53 extern DWORD errorlevel;
57 /****************************************************************************
60 * Clear the terminal screen.
63 void WCMD_clear_screen (void) {
65 /* Emulate by filling the screen from the top left to bottom right with
66 spaces, then moving the cursor to the top left afterwards */
67 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
68 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
70 if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
75 screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
79 FillConsoleOutputCharacter(hStdOut, ' ', screenSize, topLeft, &screenSize);
80 SetConsoleCursorPosition(hStdOut, topLeft);
84 /****************************************************************************
87 * Change the default i/o device (ie redirect STDin/STDout).
90 void WCMD_change_tty (void) {
96 /****************************************************************************
99 * Copy a file or wildcarded set.
100 * FIXME: No wildcard support
103 void WCMD_copy (void) {
109 static const char overwrite[] = "Overwrite file (Y/N)?";
110 char string[8], outpath[MAX_PATH], inpath[MAX_PATH], *infile, copycmd[3];
113 if (param1[0] == 0x00) {
114 WCMD_output ("Argument missing\n");
118 if ((strchr(param1,'*') != NULL) && (strchr(param1,'%') != NULL)) {
119 WCMD_output ("Wildcards not yet supported\n");
123 /* If no destination supplied, assume current directory */
124 if (param2[0] == 0x00) {
128 GetFullPathName (param2, sizeof(outpath), outpath, NULL);
129 if (outpath[strlen(outpath) - 1] == '\\')
130 outpath[strlen(outpath) - 1] = '\0';
131 hff = FindFirstFile (outpath, &fd);
132 if (hff != INVALID_HANDLE_VALUE) {
133 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
134 GetFullPathName (param1, sizeof(inpath), inpath, &infile);
135 strcat (outpath, "\\");
136 strcat (outpath, infile);
141 /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
142 if (strstr (quals, "/-Y"))
144 else if (strstr (quals, "/Y"))
147 len = GetEnvironmentVariable ("COPYCMD", copycmd, sizeof(copycmd));
148 force = (len && len < sizeof(copycmd) && ! lstrcmpi (copycmd, "/Y"));
152 hff = FindFirstFile (outpath, &fd);
153 if (hff != INVALID_HANDLE_VALUE) {
155 WCMD_output (overwrite);
156 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
157 if (toupper(string[0]) == 'Y') force = TRUE;
162 status = CopyFile (param1, outpath, FALSE);
163 if (!status) WCMD_print_error ();
167 /****************************************************************************
170 * Create a directory.
172 * this works recursivly. so mkdir dir1\dir2\dir3 will create dir1 and dir2 if
173 * they do not already exist.
176 BOOL create_full_path(CHAR* path)
182 new_path = HeapAlloc(GetProcessHeap(),0,strlen(path)+1);
183 strcpy(new_path,path);
185 while ((len = strlen(new_path)) && new_path[len - 1] == '\\')
186 new_path[len - 1] = 0;
188 while (!CreateDirectory(new_path,NULL))
191 DWORD last_error = GetLastError();
192 if (last_error == ERROR_ALREADY_EXISTS)
195 if (last_error != ERROR_PATH_NOT_FOUND)
201 if (!(slash = strrchr(new_path,'\\')) && ! (slash = strrchr(new_path,'/')))
207 len = slash - new_path;
209 if (!create_full_path(new_path))
214 new_path[len] = '\\';
216 HeapFree(GetProcessHeap(),0,new_path);
220 void WCMD_create_dir (void) {
222 if (param1[0] == 0x00) {
223 WCMD_output ("Argument missing\n");
226 if (!create_full_path(param1)) WCMD_print_error ();
229 /****************************************************************************
232 * Delete a file or wildcarded set.
235 * - Testing shows /A is repeatable, eg. /a-r /ar matches all files
236 * - Each set is a pattern, eg /ahr /as-r means
237 * readonly+hidden OR nonreadonly system files
238 * - The '-' applies to a single field, ie /a:-hr means read only
242 void WCMD_delete (char *command) {
245 int argsProcessed = 0;
246 char *argN = command;
248 /* Loop through all args */
250 char *thisArg = WCMD_parameter (command, argno++, &argN);
251 if (argN && argN[0] != '/') {
255 char fpath[MAX_PATH];
259 WINE_TRACE("del: Processing arg %s (quals:%s)\n", thisArg, quals);
262 /* If filename part of parameter is * or *.*, prompt unless
264 if ((strstr (quals, "/Q") == NULL) && (strstr (quals, "/P") == NULL)) {
268 char fname[MAX_PATH];
271 /* Convert path into actual directory spec */
272 GetFullPathName (thisArg, sizeof(fpath), fpath, NULL);
273 WCMD_splitpath(fpath, drive, dir, fname, ext);
275 /* Only prompt for * and *.*, not *a, a*, *.a* etc */
276 if ((strcmp(fname, "*") == 0) &&
277 (*ext == 0x00 || (strcmp(ext, ".*") == 0))) {
279 char question[MAXSTRING];
281 /* Ask for confirmation */
282 sprintf(question, "%s, ", fpath);
283 ok = WCMD_ask_confirm(question, TRUE);
285 /* Abort if answer is 'N' */
290 hff = FindFirstFile (thisArg, &fd);
291 if (hff == INVALID_HANDLE_VALUE) {
292 WCMD_output ("%s :File Not Found\n", thisArg);
295 /* Support del <dirname> by just deleting all files dirname\* */
296 if ((strchr(thisArg,'*') == NULL) && (strchr(thisArg,'?') == NULL)
297 && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
298 char modifiedParm[MAX_PATH];
299 strcpy(modifiedParm, thisArg);
300 strcat(modifiedParm, "\\*");
302 WCMD_delete(modifiedParm);
307 /* Build the filename to delete as <supplied directory>\<findfirst filename> */
308 strcpy (fpath, thisArg);
310 p = strrchr (fpath, '\\');
313 strcat (fpath, fd.cFileName);
315 else strcpy (fpath, fd.cFileName);
316 if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
318 char *nextA = strstr (quals, "/A");
320 /* Handle attribute matching (/A) */
323 while (nextA != NULL && !ok) {
325 char *thisA = (nextA+2);
328 /* Skip optional : */
329 if (*thisA == ':') thisA++;
331 /* Parse each of the /A[:]xxx in turn */
332 while (*thisA && *thisA != '/') {
334 BOOL attribute = FALSE;
336 /* Match negation of attribute first */
342 /* Match attribute */
344 case 'R': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY);
346 case 'H': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
348 case 'S': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM);
350 case 'A': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE);
353 WCMD_output ("Syntax error\n");
356 /* Now check result, keeping a running boolean about whether it
357 matches all parsed attribues so far */
358 if (attribute && !negate) {
360 } else if (!attribute && negate) {
368 /* Save the running total as the final result */
371 /* Step on to next /A set */
372 nextA = strstr (nextA+1, "/A");
376 /* /P means prompt for each file */
377 if (ok && strstr (quals, "/P") != NULL) {
378 char question[MAXSTRING];
380 /* Ask for confirmation */
381 sprintf(question, "%s, Delete", fpath);
382 ok = WCMD_ask_confirm(question, FALSE);
385 /* Only proceed if ok to */
388 /* If file is read only, and /F supplied, delete it */
389 if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY &&
390 strstr (quals, "/F") != NULL) {
391 SetFileAttributes(fpath, fd.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
394 /* Now do the delete */
395 if (!DeleteFile (fpath)) WCMD_print_error ();
399 } while (FindNextFile(hff, &fd) != 0);
405 /* Handle no valid args */
406 if (argsProcessed == 0) {
407 WCMD_output ("Argument missing\n");
412 /****************************************************************************
415 * Echo input to the screen (or not). We don't try to emulate the bugs
416 * in DOS (try typing "ECHO ON AGAIN" for an example).
419 void WCMD_echo (const char *command) {
421 static const char eon[] = "Echo is ON\n", eoff[] = "Echo is OFF\n";
424 if ((command[0] == '.') && (command[1] == 0)) {
425 WCMD_output (newline);
430 count = strlen(command);
432 if (echo_mode) WCMD_output (eon);
433 else WCMD_output (eoff);
436 if (lstrcmpi(command, "ON") == 0) {
440 if (lstrcmpi(command, "OFF") == 0) {
444 WCMD_output_asis (command);
445 WCMD_output (newline);
449 /**************************************************************************
452 * Batch file loop processing.
453 * FIXME: We don't exhaustively check syntax. Any command which works in MessDOS
454 * will probably work here, but the reverse is not necessarily the case...
457 void WCMD_for (char *p) {
462 char set[MAX_PATH], param[MAX_PATH];
465 if (lstrcmpi (WCMD_parameter (p, 1, NULL), "in")
466 || lstrcmpi (WCMD_parameter (p, 3, NULL), "do")
467 || (param1[0] != '%')) {
468 WCMD_output ("Syntax error\n");
471 lstrcpyn (set, WCMD_parameter (p, 2, NULL), sizeof(set));
472 WCMD_parameter (p, 4, &cmd);
473 lstrcpy (param, param1);
476 * If the parameter within the set has a wildcard then search for matching files
477 * otherwise do a literal substitution.
481 while (*(item = WCMD_parameter (set, i, NULL))) {
482 if (strpbrk (item, "*?")) {
483 hff = FindFirstFile (item, &fd);
484 if (hff == INVALID_HANDLE_VALUE) {
488 WCMD_execute (cmd, param, fd.cFileName);
489 } while (FindNextFile(hff, &fd) != 0);
493 WCMD_execute (cmd, param, item);
499 /*****************************************************************************
502 * Execute a command after substituting variable text for the supplied parameter
505 void WCMD_execute (char *orig_cmd, char *param, char *subst) {
507 char *new_cmd, *p, *s, *dup;
510 size = lstrlen (orig_cmd);
511 new_cmd = (char *) LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, size);
512 dup = s = strdup (orig_cmd);
514 while ((p = strstr (s, param))) {
516 size += lstrlen (subst);
517 new_cmd = (char *) LocalReAlloc ((HANDLE)new_cmd, size, 0);
519 strcat (new_cmd, subst);
520 s = p + lstrlen (param);
523 WCMD_process_command (new_cmd);
525 LocalFree ((HANDLE)new_cmd);
529 /**************************************************************************
532 * Simple on-line help. Help text is stored in the resource file.
535 void WCMD_give_help (char *command) {
540 command = WCMD_strtrim_leading_spaces(command);
541 if (lstrlen(command) == 0) {
542 LoadString (hinst, 1000, buffer, sizeof(buffer));
543 WCMD_output_asis (buffer);
546 for (i=0; i<=WCMD_EXIT; i++) {
547 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
548 param1, -1, inbuilt[i], -1) == 2) {
549 LoadString (hinst, i, buffer, sizeof(buffer));
550 WCMD_output_asis (buffer);
554 WCMD_output ("No help available for %s\n", param1);
559 /****************************************************************************
562 * Batch file jump instruction. Not the most efficient algorithm ;-)
563 * Prints error message if the specified label cannot be found - the file pointer is
564 * then at EOF, effectively stopping the batch file.
565 * FIXME: DOS is supposed to allow labels with spaces - we don't.
568 void WCMD_goto (void) {
570 char string[MAX_PATH];
572 if (param1[0] == 0x00) {
573 WCMD_output ("Argument missing\n");
576 if (context != NULL) {
577 char *paramStart = param1;
579 /* Handle special :EOF label */
580 if (lstrcmpi (":eof", param1) == 0) {
581 context -> skip_rest = TRUE;
585 /* Support goto :label as well as goto label */
586 if (*paramStart == ':') paramStart++;
588 SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
589 while (WCMD_fgets (string, sizeof(string), context -> h)) {
590 if ((string[0] == ':') && (lstrcmpi (&string[1], paramStart) == 0)) return;
592 WCMD_output ("Target to GOTO not found\n");
597 /*****************************************************************************
600 * Push a directory onto the stack
603 void WCMD_pushd (char *command) {
604 struct env_stack *curdir;
607 if (strchr(command, '/') != NULL) {
608 SetLastError(ERROR_INVALID_PARAMETER);
613 curdir = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
614 thisdir = LocalAlloc (LMEM_FIXED, 1024 * sizeof(WCHAR));
615 if( !curdir || !thisdir ) {
618 WCMD_output ("out of memory\n");
622 GetCurrentDirectoryW (1024, thisdir);
624 WCMD_setshow_default(command);
630 curdir -> next = pushd_directories;
631 curdir -> strings = thisdir;
632 if (pushd_directories == NULL) {
633 curdir -> stackdepth = 1;
635 curdir -> stackdepth = pushd_directories -> stackdepth + 1;
637 pushd_directories = curdir;
642 /*****************************************************************************
645 * Pop a directory from the stack
648 void WCMD_popd (void) {
649 struct env_stack *temp = pushd_directories;
651 if (!pushd_directories)
654 /* pop the old environment from the stack, and make it the current dir */
655 pushd_directories = temp->next;
656 SetCurrentDirectoryW(temp->strings);
657 LocalFree (temp->strings);
661 /****************************************************************************
664 * Batch file conditional.
665 * FIXME: Much more syntax checking needed!
668 void WCMD_if (char *p) {
670 int negate = 0, test = 0;
671 char condition[MAX_PATH], *command, *s;
673 if (!lstrcmpi (param1, "not")) {
675 lstrcpy (condition, param2);
678 lstrcpy (condition, param1);
680 if (!lstrcmpi (condition, "errorlevel")) {
681 if (errorlevel >= atoi(WCMD_parameter (p, 1+negate, NULL))) test = 1;
682 WCMD_parameter (p, 2+negate, &command);
684 else if (!lstrcmpi (condition, "exist")) {
685 if (GetFileAttributesA(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
688 WCMD_parameter (p, 2+negate, &command);
690 else if (!lstrcmpi (condition, "defined")) {
691 if (GetEnvironmentVariableA(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
694 WCMD_parameter (p, 2+negate, &command);
696 else if ((s = strstr (p, "=="))) {
698 if (!lstrcmpi (condition, WCMD_parameter (s, 0, NULL))) test = 1;
699 WCMD_parameter (s, 1, &command);
702 WCMD_output ("Syntax error\n");
705 if (test != negate) {
706 command = strdup (command);
707 WCMD_process_command (command);
712 /****************************************************************************
715 * Move a file, directory tree or wildcarded set of files.
716 * FIXME: Needs input and output files to be fully specified.
719 void WCMD_move (void) {
722 char outpath[MAX_PATH], inpath[MAX_PATH], *infile;
726 if (param1[0] == 0x00) {
727 WCMD_output ("Argument missing\n");
731 if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
732 WCMD_output ("Wildcards not yet supported\n");
736 /* If no destination supplied, assume current directory */
737 if (param2[0] == 0x00) {
741 /* If 2nd parm is directory, then use original filename */
742 GetFullPathName (param2, sizeof(outpath), outpath, NULL);
743 if (outpath[strlen(outpath) - 1] == '\\')
744 outpath[strlen(outpath) - 1] = '\0';
745 hff = FindFirstFile (outpath, &fd);
746 if (hff != INVALID_HANDLE_VALUE) {
747 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
748 GetFullPathName (param1, sizeof(inpath), inpath, &infile);
749 strcat (outpath, "\\");
750 strcat (outpath, infile);
755 status = MoveFile (param1, outpath);
756 if (!status) WCMD_print_error ();
759 /****************************************************************************
762 * Wait for keyboard input.
765 void WCMD_pause (void) {
770 WCMD_output (anykey);
771 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
774 /****************************************************************************
777 * Delete a directory.
780 void WCMD_remove_dir (char *command) {
783 int argsProcessed = 0;
784 char *argN = command;
786 /* Loop through all args */
788 char *thisArg = WCMD_parameter (command, argno++, &argN);
789 if (argN && argN[0] != '/') {
790 WINE_TRACE("rd: Processing arg %s (quals:%s)\n", thisArg, quals);
793 /* If subdirectory search not supplied, just try to remove
794 and report error if it fails (eg if it contains a file) */
795 if (strstr (quals, "/S") == NULL) {
796 if (!RemoveDirectory (thisArg)) WCMD_print_error ();
798 /* Otherwise use ShFileOp to recursively remove a directory */
801 SHFILEOPSTRUCT lpDir;
804 if (strstr (quals, "/Q") == NULL) {
806 char question[MAXSTRING];
808 /* Ask for confirmation */
809 sprintf(question, "%s, ", thisArg);
810 ok = WCMD_ask_confirm(question, TRUE);
812 /* Abort if answer is 'N' */
819 lpDir.pFrom = thisArg;
820 lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
821 lpDir.wFunc = FO_DELETE;
822 if (SHFileOperationA(&lpDir)) WCMD_print_error ();
827 /* Handle no valid args */
828 if (argsProcessed == 0) {
829 WCMD_output ("Argument missing\n");
835 /****************************************************************************
839 * FIXME: Needs input and output files to be fully specified.
842 void WCMD_rename (void) {
846 if (param1[0] == 0x00 || param2[0] == 0x00) {
847 WCMD_output ("Argument missing\n");
850 if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
851 WCMD_output ("Wildcards not yet supported\n");
854 status = MoveFile (param1, param2);
855 if (!status) WCMD_print_error ();
858 /*****************************************************************************
861 * Make a copy of the environment.
863 static WCHAR *WCMD_dupenv( const WCHAR *env )
873 len += (lstrlenW(&env[len]) + 1);
875 env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
878 WCMD_output ("out of memory\n");
881 memcpy (env_copy, env, len*sizeof (WCHAR));
887 /*****************************************************************************
890 * setlocal pushes the environment onto a stack
891 * Save the environment as unicode so we don't screw anything up.
893 void WCMD_setlocal (const char *s) {
895 struct env_stack *env_copy;
897 /* DISABLEEXTENSIONS ignored */
899 env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
902 WCMD_output ("out of memory\n");
906 env = GetEnvironmentStringsW ();
908 env_copy->strings = WCMD_dupenv (env);
909 if (env_copy->strings)
911 env_copy->next = saved_environment;
912 saved_environment = env_copy;
915 LocalFree (env_copy);
917 FreeEnvironmentStringsW (env);
920 /*****************************************************************************
923 static inline WCHAR *WCMD_strchrW(WCHAR *str, WCHAR ch)
934 /*****************************************************************************
937 * endlocal pops the environment off a stack
939 void WCMD_endlocal (void) {
940 WCHAR *env, *old, *p;
941 struct env_stack *temp;
944 if (!saved_environment)
947 /* pop the old environment from the stack */
948 temp = saved_environment;
949 saved_environment = temp->next;
951 /* delete the current environment, totally */
952 env = GetEnvironmentStringsW ();
953 old = WCMD_dupenv (GetEnvironmentStringsW ());
956 n = lstrlenW(&old[len]) + 1;
957 p = WCMD_strchrW(&old[len], '=');
961 SetEnvironmentVariableW (&old[len], NULL);
966 FreeEnvironmentStringsW (env);
968 /* restore old environment */
972 n = lstrlenW(&env[len]) + 1;
973 p = WCMD_strchrW(&env[len], '=');
977 SetEnvironmentVariableW (&env[len], p);
985 /*****************************************************************************
986 * WCMD_setshow_attrib
988 * Display and optionally sets DOS attributes on a file or directory
990 * FIXME: Wine currently uses the Unix stat() function to get file attributes.
991 * As a result only the Readonly flag is correctly reported, the Archive bit
992 * is always set and the rest are not implemented. We do the Right Thing anyway.
994 * FIXME: No SET functionality.
998 void WCMD_setshow_attrib (void) {
1003 char flags[9] = {" "};
1005 if (param1[0] == '-') {
1010 if (lstrlen(param1) == 0) {
1011 GetCurrentDirectory (sizeof(param1), param1);
1012 strcat (param1, "\\*");
1015 hff = FindFirstFile (param1, &fd);
1016 if (hff == INVALID_HANDLE_VALUE) {
1017 WCMD_output ("%s: File Not Found\n",param1);
1021 if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1022 if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
1025 if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
1028 if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
1031 if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
1034 if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
1037 if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
1040 WCMD_output ("%s %s\n", flags, fd.cFileName);
1041 for (count=0; count < 8; count++) flags[count] = ' ';
1043 } while (FindNextFile(hff, &fd) != 0);
1048 /*****************************************************************************
1049 * WCMD_setshow_default
1051 * Set/Show the current default directory
1054 void WCMD_setshow_default (char *command) {
1062 WINE_TRACE("Request change to directory '%s'\n", command);
1063 if (strlen(command) == 0) {
1064 GetCurrentDirectory (sizeof(string), string);
1065 strcat (string, "\n");
1066 WCMD_output (string);
1069 /* Remove any double quotes, which may be in the
1070 middle, eg. cd "C:\Program Files"\Microsoft is ok */
1073 if (*command != '"') *pos++ = *command;
1078 /* Search for approprate directory */
1079 WINE_TRACE("Looking for directory '%s'\n", string);
1080 hff = FindFirstFile (string, &fd);
1081 while (hff != INVALID_HANDLE_VALUE) {
1082 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1083 char fpath[MAX_PATH];
1086 char fname[MAX_PATH];
1089 /* Convert path into actual directory spec */
1090 GetFullPathName (string, sizeof(fpath), fpath, NULL);
1091 WCMD_splitpath(fpath, drive, dir, fname, ext);
1094 sprintf(string, "%s%s%s", drive, dir, fd.cFileName);
1097 hff = INVALID_HANDLE_VALUE;
1101 /* Step on to next match */
1102 if (FindNextFile(hff, &fd) == 0) {
1104 hff = INVALID_HANDLE_VALUE;
1109 /* Change to that directory */
1110 WINE_TRACE("Really changing to directory '%s'\n", string);
1111 status = SetCurrentDirectory (string);
1114 WCMD_print_error ();
1121 /****************************************************************************
1124 * Set/Show the system date
1125 * FIXME: Can't change date yet
1128 void WCMD_setshow_date (void) {
1130 char curdate[64], buffer[64];
1133 if (lstrlen(param1) == 0) {
1134 if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
1135 curdate, sizeof(curdate))) {
1136 WCMD_output ("Current Date is %s\nEnter new date: ", curdate);
1137 ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1142 else WCMD_print_error ();
1149 /****************************************************************************
1152 static int WCMD_compare( const void *a, const void *b )
1155 const char * const *str_a = a, * const *str_b = b;
1156 r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1157 *str_a, -1, *str_b, -1 );
1158 if( r == CSTR_LESS_THAN ) return -1;
1159 if( r == CSTR_GREATER_THAN ) return 1;
1163 /****************************************************************************
1164 * WCMD_setshow_sortenv
1166 * sort variables into order for display
1167 * Optionally only display those who start with a stub
1168 * returns the count displayed
1170 static int WCMD_setshow_sortenv(const char *s, const char *stub)
1172 UINT count=0, len=0, i, displayedcount=0, stublen=0;
1175 if (stub) stublen = strlen(stub);
1177 /* count the number of strings, and the total length */
1179 len += (lstrlen(&s[len]) + 1);
1183 /* add the strings to an array */
1184 str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (char*) );
1188 for( i=1; i<count; i++ )
1189 str[i] = str[i-1] + lstrlen(str[i-1]) + 1;
1191 /* sort the array */
1192 qsort( str, count, sizeof (char*), WCMD_compare );
1195 for( i=0; i<count; i++ ) {
1196 if (!stub || CompareString (LOCALE_USER_DEFAULT,
1197 NORM_IGNORECASE | SORT_STRINGSORT,
1198 str[i], stublen, stub, -1) == 2) {
1199 WCMD_output_asis(str[i]);
1200 WCMD_output_asis("\n");
1206 return displayedcount;
1209 /****************************************************************************
1212 * Set/Show the environment variables
1215 void WCMD_setshow_env (char *s) {
1221 if (strlen(param1) == 0) {
1222 env = GetEnvironmentStrings ();
1223 WCMD_setshow_sortenv( env, NULL );
1226 p = strchr (s, '=');
1228 env = GetEnvironmentStrings ();
1229 if (WCMD_setshow_sortenv( env, s ) == 0) {
1230 WCMD_output ("Environment variable %s not defined\n", s);
1236 if (strlen(p) == 0) p = NULL;
1237 status = SetEnvironmentVariable (s, p);
1238 if ((!status) & (GetLastError() != ERROR_ENVVAR_NOT_FOUND)) WCMD_print_error();
1242 /****************************************************************************
1245 * Set/Show the path environment variable
1248 void WCMD_setshow_path (char *command) {
1253 if (strlen(param1) == 0) {
1254 status = GetEnvironmentVariable ("PATH", string, sizeof(string));
1256 WCMD_output_asis ( "PATH=");
1257 WCMD_output_asis ( string);
1258 WCMD_output_asis ( "\n");
1261 WCMD_output ("PATH not found\n");
1265 if (*command == '=') command++; /* Skip leading '=' */
1266 status = SetEnvironmentVariable ("PATH", command);
1267 if (!status) WCMD_print_error();
1271 /****************************************************************************
1272 * WCMD_setshow_prompt
1274 * Set or show the command prompt.
1277 void WCMD_setshow_prompt (void) {
1281 if (strlen(param1) == 0) {
1282 SetEnvironmentVariable ("PROMPT", NULL);
1286 while ((*s == '=') || (*s == ' ')) s++;
1287 if (strlen(s) == 0) {
1288 SetEnvironmentVariable ("PROMPT", NULL);
1290 else SetEnvironmentVariable ("PROMPT", s);
1294 /****************************************************************************
1297 * Set/Show the system time
1298 * FIXME: Can't change time yet
1301 void WCMD_setshow_time (void) {
1303 char curtime[64], buffer[64];
1307 if (strlen(param1) == 0) {
1309 if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
1310 curtime, sizeof(curtime))) {
1311 WCMD_output ("Current Time is %s\nEnter new time: ", curtime);
1312 ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1317 else WCMD_print_error ();
1324 /****************************************************************************
1327 * Shift batch parameters.
1330 void WCMD_shift (void) {
1332 if (context != NULL) context -> shift_count++;
1336 /****************************************************************************
1339 * Set the console title
1341 void WCMD_title (char *command) {
1342 SetConsoleTitle(command);
1345 /****************************************************************************
1348 * Copy a file to standard output.
1351 void WCMD_type (void) {
1357 if (param1[0] == 0x00) {
1358 WCMD_output ("Argument missing\n");
1361 h = CreateFile (param1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1362 FILE_ATTRIBUTE_NORMAL, NULL);
1363 if (h == INVALID_HANDLE_VALUE) {
1364 WCMD_print_error ();
1367 while (ReadFile (h, buffer, sizeof(buffer), &count, NULL)) {
1368 if (count == 0) break; /* ReadFile reports success on EOF! */
1370 WCMD_output_asis (buffer);
1375 /****************************************************************************
1378 * Display verify flag.
1379 * FIXME: We don't actually do anything with the verify flag other than toggle
1383 void WCMD_verify (char *command) {
1385 static const char von[] = "Verify is ON\n", voff[] = "Verify is OFF\n";
1388 count = strlen(command);
1390 if (verify_mode) WCMD_output (von);
1391 else WCMD_output (voff);
1394 if (lstrcmpi(command, "ON") == 0) {
1398 else if (lstrcmpi(command, "OFF") == 0) {
1402 else WCMD_output ("Verify must be ON or OFF\n");
1405 /****************************************************************************
1408 * Display version info.
1411 void WCMD_version (void) {
1413 WCMD_output (version_string);
1417 /****************************************************************************
1420 * Display volume info and/or set volume label. Returns 0 if error.
1423 int WCMD_volume (int mode, char *path) {
1425 DWORD count, serial;
1426 char string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
1429 if (lstrlen(path) == 0) {
1430 status = GetCurrentDirectory (sizeof(curdir), curdir);
1432 WCMD_print_error ();
1435 status = GetVolumeInformation (NULL, label, sizeof(label), &serial, NULL,
1439 if ((path[1] != ':') || (lstrlen(path) != 2)) {
1440 WCMD_output_asis("Syntax Error\n\n");
1443 wsprintf (curdir, "%s\\", path);
1444 status = GetVolumeInformation (curdir, label, sizeof(label), &serial, NULL,
1448 WCMD_print_error ();
1451 WCMD_output ("Volume in drive %c is %s\nVolume Serial Number is %04x-%04x\n\n",
1452 curdir[0], label, HIWORD(serial), LOWORD(serial));
1454 WCMD_output ("Volume label (11 characters, ENTER for none)?");
1455 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1457 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
1458 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1460 if (lstrlen(path) != 0) {
1461 if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
1464 if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
1470 /**************************************************************************
1473 * Exit either the process, or just this batch program
1477 void WCMD_exit (void) {
1479 int rc = atoi(param1); /* Note: atoi of empty parameter is 0 */
1481 if (context && lstrcmpi(quals, "/B") == 0) {
1483 context -> skip_rest = TRUE;
1489 /**************************************************************************
1492 * Issue a message and ask 'Are you sure (Y/N)', waiting on a valid
1495 * Returns True if Y answer is selected
1498 BOOL WCMD_ask_confirm (char *message, BOOL showSureText) {
1500 char msgbuffer[MAXSTRING];
1501 char Ybuffer[MAXSTRING];
1502 char Nbuffer[MAXSTRING];
1503 char answer[MAX_PATH] = "";
1506 /* Load the translated 'Are you sure', plus valid answers */
1507 LoadString (hinst, WCMD_CONFIRM, msgbuffer, sizeof(msgbuffer));
1508 LoadString (hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer));
1509 LoadString (hinst, WCMD_NO, Nbuffer, sizeof(Nbuffer));
1511 /* Loop waiting on a Y or N */
1512 while (answer[0] != Ybuffer[0] && answer[0] != Nbuffer[0]) {
1513 WCMD_output_asis (message);
1515 WCMD_output_asis (msgbuffer);
1517 WCMD_output_asis (" (");
1518 WCMD_output_asis (Ybuffer);
1519 WCMD_output_asis ("/");
1520 WCMD_output_asis (Nbuffer);
1521 WCMD_output_asis (")?");
1522 ReadFile (GetStdHandle(STD_INPUT_HANDLE), answer, sizeof(answer),
1524 answer[0] = toupper(answer[0]);
1527 /* Return the answer */
1528 return (answer[0] == Ybuffer[0]);
1531 /*****************************************************************************
1534 * Lists or sets file associations
1536 void WCMD_assoc (char *command) {
1539 DWORD accessOptions = KEY_READ;
1541 LONG rc = ERROR_SUCCESS;
1542 char keyValue[MAXSTRING];
1543 DWORD valueLen = MAXSTRING;
1547 /* See if parameter includes '=' */
1549 newValue = strchr(command, '=');
1550 if (newValue) accessOptions |= KEY_WRITE;
1552 /* Open a key to HKEY_CLASSES_ROOT for enumerating */
1553 if (RegOpenKeyEx(HKEY_CLASSES_ROOT, "", 0,
1554 accessOptions, &key) != ERROR_SUCCESS) {
1555 WINE_FIXME("Unexpected failure opening HKCR key: %d\n", GetLastError());
1559 /* If no parameters then list all associations */
1560 if (*command == 0x00) {
1563 /* Enumerate all the keys */
1564 while (rc != ERROR_NO_MORE_ITEMS) {
1565 char keyName[MAXSTRING];
1568 /* Find the next value */
1569 nameLen = MAXSTRING;
1570 rc = RegEnumKeyEx(key, index++,
1572 NULL, NULL, NULL, NULL);
1574 if (rc == ERROR_SUCCESS) {
1576 /* Only interested in extension ones */
1577 if (keyName[0] == '.') {
1579 if (RegOpenKeyEx(key, keyName, 0,
1580 accessOptions, &readKey) == ERROR_SUCCESS) {
1582 rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1583 (LPBYTE)keyValue, &valueLen);
1584 WCMD_output_asis(keyName);
1585 WCMD_output_asis("=");
1586 /* If no default value found, leave line empty after '=' */
1587 if (rc == ERROR_SUCCESS) {
1588 WCMD_output_asis(keyValue);
1590 WCMD_output_asis("\n");
1595 RegCloseKey(readKey);
1599 /* Parameter supplied - if no '=' on command line, its a query */
1600 if (newValue == NULL) {
1603 /* Query terminates the parameter at the first space */
1604 strcpy(keyValue, command);
1605 space = strchr(keyValue, ' ');
1606 if (space) *space=0x00;
1608 if (RegOpenKeyEx(key, keyValue, 0,
1609 accessOptions, &readKey) == ERROR_SUCCESS) {
1611 rc = RegQueryValueEx(readKey, NULL, NULL, NULL,
1612 (LPBYTE)keyValue, &valueLen);
1613 WCMD_output_asis(command);
1614 WCMD_output_asis("=");
1615 /* If no default value found, leave line empty after '=' */
1616 if (rc == ERROR_SUCCESS) WCMD_output_asis(keyValue);
1617 WCMD_output_asis("\n");
1618 RegCloseKey(readKey);
1621 char msgbuffer[MAXSTRING];
1622 char outbuffer[MAXSTRING];
1624 /* Load the translated 'File association not found' */
1625 LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1626 sprintf(outbuffer, msgbuffer, keyValue);
1627 WCMD_output_asis(outbuffer);
1631 /* Not a query - its a set or clear of a value */
1634 /* Get pointer to new value */
1638 /* If nothing after '=' then clear value */
1639 if (*newValue == 0x00) {
1641 rc = RegDeleteKey(key, command);
1642 if (rc == ERROR_SUCCESS) {
1643 WINE_TRACE("HKCR Key '%s' deleted\n", command);
1645 } else if (rc != ERROR_FILE_NOT_FOUND) {
1650 char msgbuffer[MAXSTRING];
1651 char outbuffer[MAXSTRING];
1653 /* Load the translated 'File association not found' */
1654 LoadString (hinst, WCMD_NOASSOC, msgbuffer, sizeof(msgbuffer));
1655 sprintf(outbuffer, msgbuffer, keyValue);
1656 WCMD_output_asis(outbuffer);
1660 /* It really is a set value = contents */
1662 rc = RegCreateKeyEx(key, command, 0, NULL, REG_OPTION_NON_VOLATILE,
1663 accessOptions, NULL, &readKey, NULL);
1664 if (rc == ERROR_SUCCESS) {
1665 rc = RegSetValueEx(readKey, NULL, 0, REG_SZ,
1666 (LPBYTE)newValue, strlen(newValue));
1667 RegCloseKey(readKey);
1670 if (rc != ERROR_SUCCESS) {
1674 WCMD_output_asis(command);
1675 WCMD_output_asis("=");
1676 WCMD_output_asis(newValue);
1677 WCMD_output_asis("\n");
1687 /****************************************************************************
1690 * Clear the terminal screen.
1693 void WCMD_color (void) {
1695 /* Emulate by filling the screen from the top left to bottom right with
1696 spaces, then moving the cursor to the top left afterwards */
1697 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
1698 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1700 if (param1[0] != 0x00 && strlen(param1) > 2) {
1701 WCMD_output ("Argument invalid\n");
1705 if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
1711 screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
1716 /* Convert the color hex digits */
1717 if (param1[0] == 0x00) {
1718 color = defaultColor;
1720 color = strtoul(param1, NULL, 16);
1723 /* Fail if fg == bg color */
1724 if (((color & 0xF0) >> 4) == (color & 0x0F)) {
1729 /* Set the current screen contents and ensure all future writes
1730 remain this color */
1731 FillConsoleOutputAttribute(hStdOut, color, screenSize, topLeft, &screenSize);
1732 SetConsoleTextAttribute(hStdOut, color);