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
40 void WCMD_execute (char *orig_command, char *parameter, char *substitution);
44 struct env_stack *next;
48 struct env_stack *saved_environment;
49 struct env_stack *pushd_directories;
51 extern HINSTANCE hinst;
52 extern char *inbuilt[];
53 extern int echo_mode, verify_mode;
54 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
55 extern BATCH_CONTEXT *context;
56 extern DWORD errorlevel;
60 /****************************************************************************
63 * Clear the terminal screen.
66 void WCMD_clear_screen (void) {
68 /* Emulate by filling the screen from the top left to bottom right with
69 spaces, then moving the cursor to the top left afterwards */
70 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
71 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
73 if (GetConsoleScreenBufferInfo(hStdOut, &consoleInfo))
78 screenSize = consoleInfo.dwSize.X * (consoleInfo.dwSize.Y + 1);
82 FillConsoleOutputCharacter(hStdOut, ' ', screenSize, topLeft, &screenSize);
83 SetConsoleCursorPosition(hStdOut, topLeft);
87 /****************************************************************************
90 * Change the default i/o device (ie redirect STDin/STDout).
93 void WCMD_change_tty (void) {
99 /****************************************************************************
102 * Copy a file or wildcarded set.
103 * FIXME: No wildcard support
106 void WCMD_copy (void) {
112 static const char overwrite[] = "Overwrite file (Y/N)?";
113 char string[8], outpath[MAX_PATH], inpath[MAX_PATH], *infile, copycmd[3];
116 if (param1[0] == 0x00) {
117 WCMD_output ("Argument missing\n");
121 if ((strchr(param1,'*') != NULL) && (strchr(param1,'%') != NULL)) {
122 WCMD_output ("Wildcards not yet supported\n");
126 /* If no destination supplied, assume current directory */
127 if (param2[0] == 0x00) {
131 GetFullPathName (param2, sizeof(outpath), outpath, NULL);
132 if (outpath[strlen(outpath) - 1] == '\\')
133 outpath[strlen(outpath) - 1] = '\0';
134 hff = FindFirstFile (outpath, &fd);
135 if (hff != INVALID_HANDLE_VALUE) {
136 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
137 GetFullPathName (param1, sizeof(inpath), inpath, &infile);
138 strcat (outpath, "\\");
139 strcat (outpath, infile);
144 /* /-Y has the highest priority, then /Y and finally the COPYCMD env. variable */
145 if (strstr (quals, "/-Y"))
147 else if (strstr (quals, "/Y"))
150 len = GetEnvironmentVariable ("COPYCMD", copycmd, sizeof(copycmd));
151 force = (len && len < sizeof(copycmd) && ! lstrcmpi (copycmd, "/Y"));
155 hff = FindFirstFile (outpath, &fd);
156 if (hff != INVALID_HANDLE_VALUE) {
158 WCMD_output (overwrite);
159 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
160 if (toupper(string[0]) == 'Y') force = TRUE;
165 status = CopyFile (param1, outpath, FALSE);
166 if (!status) WCMD_print_error ();
170 /****************************************************************************
173 * Create a directory.
175 * this works recursivly. so mkdir dir1\dir2\dir3 will create dir1 and dir2 if
176 * they do not already exist.
179 BOOL create_full_path(CHAR* path)
185 new_path = HeapAlloc(GetProcessHeap(),0,strlen(path)+1);
186 strcpy(new_path,path);
188 while ((len = strlen(new_path)) && new_path[len - 1] == '\\')
189 new_path[len - 1] = 0;
191 while (!CreateDirectory(new_path,NULL))
194 DWORD last_error = GetLastError();
195 if (last_error == ERROR_ALREADY_EXISTS)
198 if (last_error != ERROR_PATH_NOT_FOUND)
204 if (!(slash = strrchr(new_path,'\\')) && ! (slash = strrchr(new_path,'/')))
210 len = slash - new_path;
212 if (!create_full_path(new_path))
217 new_path[len] = '\\';
219 HeapFree(GetProcessHeap(),0,new_path);
223 void WCMD_create_dir (void) {
225 if (param1[0] == 0x00) {
226 WCMD_output ("Argument missing\n");
229 if (!create_full_path(param1)) WCMD_print_error ();
232 /****************************************************************************
235 * Delete a file or wildcarded set.
238 * - Testing shows /A is repeatable, eg. /a-r /ar matches all files
239 * - Each set is a pattern, eg /ahr /as-r means
240 * readonly+hidden OR nonreadonly system files
241 * - The '-' applies to a single field, ie /a:-hr means read only
245 void WCMD_delete (int recurse) {
249 char fpath[MAX_PATH];
252 if (param1[0] == 0x00) {
253 WCMD_output ("Argument missing\n");
257 /* If filename part of parameter is * or *.*, prompt unless
259 if ((strstr (quals, "/Q") == NULL) && (strstr (quals, "/P") == NULL)) {
263 char fname[MAX_PATH];
266 /* Convert path into actual directory spec */
267 GetFullPathName (param1, sizeof(fpath), fpath, NULL);
268 WCMD_splitpath(fpath, drive, dir, fname, ext);
270 /* Only prompt for * and *.*, not *a, a*, *.a* etc */
271 if ((strcmp(fname, "*") == 0) &&
272 (*ext == 0x00 || (strcmp(ext, ".*") == 0))) {
274 char question[MAXSTRING];
276 /* Ask for confirmation */
277 sprintf(question, "%s, ", fpath);
278 ok = WCMD_ask_confirm(question, TRUE);
280 /* Abort if answer is 'N' */
285 hff = FindFirstFile (param1, &fd);
286 if (hff == INVALID_HANDLE_VALUE) {
287 WCMD_output ("%s :File Not Found\n",param1);
290 /* Support del <dirname> by just deleting all files dirname\* */
291 if ((strchr(param1,'*') == NULL) && (strchr(param1,'?') == NULL)
292 && (!recurse) && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
293 strcat (param1, "\\*");
300 /* Build the filename to delete as <supplied directory>\<findfirst filename> */
301 strcpy (fpath, param1);
303 p = strrchr (fpath, '\\');
306 strcat (fpath, fd.cFileName);
308 else strcpy (fpath, fd.cFileName);
309 if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
311 char *nextA = strstr (quals, "/A");
313 /* Handle attribute matching (/A) */
316 while (nextA != NULL && !ok) {
318 char *thisA = (nextA+2);
321 /* Skip optional : */
322 if (*thisA == ':') thisA++;
324 /* Parse each of the /A[:]xxx in turn */
325 while (*thisA && *thisA != '/') {
327 BOOL attribute = FALSE;
329 /* Match negation of attribute first */
335 /* Match attribute */
337 case 'R': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY);
339 case 'H': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
341 case 'S': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM);
343 case 'A': attribute = (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE);
346 WCMD_output ("Syntax error\n");
349 /* Now check result, keeping a running boolean about whether it
350 matches all parsed attribues so far */
351 if (attribute && !negate) {
353 } else if (!attribute && negate) {
361 /* Save the running total as the final result */
364 /* Step on to next /A set */
365 nextA = strstr (nextA+1, "/A");
369 /* /P means prompt for each file */
370 if (ok && strstr (quals, "/P") != NULL) {
371 char question[MAXSTRING];
373 /* Ask for confirmation */
374 sprintf(question, "%s, Delete", fpath);
375 ok = WCMD_ask_confirm(question, FALSE);
378 /* Only proceed if ok to */
381 /* If file is read only, and /F supplied, delete it */
382 if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY &&
383 strstr (quals, "/F") != NULL) {
384 SetFileAttributes(fpath, fd.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
387 /* Now do the delete */
388 if (!DeleteFile (fpath)) WCMD_print_error ();
392 } while (FindNextFile(hff, &fd) != 0);
397 /****************************************************************************
400 * Echo input to the screen (or not). We don't try to emulate the bugs
401 * in DOS (try typing "ECHO ON AGAIN" for an example).
404 void WCMD_echo (const char *command) {
406 static const char eon[] = "Echo is ON\n", eoff[] = "Echo is OFF\n";
409 if ((command[0] == '.') && (command[1] == 0)) {
410 WCMD_output (newline);
415 count = strlen(command);
417 if (echo_mode) WCMD_output (eon);
418 else WCMD_output (eoff);
421 if (lstrcmpi(command, "ON") == 0) {
425 if (lstrcmpi(command, "OFF") == 0) {
429 WCMD_output_asis (command);
430 WCMD_output (newline);
434 /**************************************************************************
437 * Batch file loop processing.
438 * FIXME: We don't exhaustively check syntax. Any command which works in MessDOS
439 * will probably work here, but the reverse is not necessarily the case...
442 void WCMD_for (char *p) {
447 char set[MAX_PATH], param[MAX_PATH];
450 if (lstrcmpi (WCMD_parameter (p, 1, NULL), "in")
451 || lstrcmpi (WCMD_parameter (p, 3, NULL), "do")
452 || (param1[0] != '%')) {
453 WCMD_output ("Syntax error\n");
456 lstrcpyn (set, WCMD_parameter (p, 2, NULL), sizeof(set));
457 WCMD_parameter (p, 4, &cmd);
458 lstrcpy (param, param1);
461 * If the parameter within the set has a wildcard then search for matching files
462 * otherwise do a literal substitution.
466 while (*(item = WCMD_parameter (set, i, NULL))) {
467 if (strpbrk (item, "*?")) {
468 hff = FindFirstFile (item, &fd);
469 if (hff == INVALID_HANDLE_VALUE) {
473 WCMD_execute (cmd, param, fd.cFileName);
474 } while (FindNextFile(hff, &fd) != 0);
478 WCMD_execute (cmd, param, item);
484 /*****************************************************************************
487 * Execute a command after substituting variable text for the supplied parameter
490 void WCMD_execute (char *orig_cmd, char *param, char *subst) {
492 char *new_cmd, *p, *s, *dup;
495 size = lstrlen (orig_cmd);
496 new_cmd = (char *) LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, size);
497 dup = s = strdup (orig_cmd);
499 while ((p = strstr (s, param))) {
501 size += lstrlen (subst);
502 new_cmd = (char *) LocalReAlloc ((HANDLE)new_cmd, size, 0);
504 strcat (new_cmd, subst);
505 s = p + lstrlen (param);
508 WCMD_process_command (new_cmd);
510 LocalFree ((HANDLE)new_cmd);
514 /**************************************************************************
517 * Simple on-line help. Help text is stored in the resource file.
520 void WCMD_give_help (char *command) {
525 command = WCMD_strtrim_leading_spaces(command);
526 if (lstrlen(command) == 0) {
527 LoadString (hinst, 1000, buffer, sizeof(buffer));
528 WCMD_output_asis (buffer);
531 for (i=0; i<=WCMD_EXIT; i++) {
532 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
533 param1, -1, inbuilt[i], -1) == 2) {
534 LoadString (hinst, i, buffer, sizeof(buffer));
535 WCMD_output_asis (buffer);
539 WCMD_output ("No help available for %s\n", param1);
544 /****************************************************************************
547 * Batch file jump instruction. Not the most efficient algorithm ;-)
548 * Prints error message if the specified label cannot be found - the file pointer is
549 * then at EOF, effectively stopping the batch file.
550 * FIXME: DOS is supposed to allow labels with spaces - we don't.
553 void WCMD_goto (void) {
555 char string[MAX_PATH];
557 if (param1[0] == 0x00) {
558 WCMD_output ("Argument missing\n");
561 if (context != NULL) {
562 char *paramStart = param1;
564 /* Handle special :EOF label */
565 if (lstrcmpi (":eof", param1) == 0) {
566 context -> skip_rest = TRUE;
570 /* Support goto :label as well as goto label */
571 if (*paramStart == ':') paramStart++;
573 SetFilePointer (context -> h, 0, NULL, FILE_BEGIN);
574 while (WCMD_fgets (string, sizeof(string), context -> h)) {
575 if ((string[0] == ':') && (lstrcmpi (&string[1], paramStart) == 0)) return;
577 WCMD_output ("Target to GOTO not found\n");
582 /*****************************************************************************
585 * Push a directory onto the stack
588 void WCMD_pushd (void) {
589 struct env_stack *curdir;
593 curdir = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
594 thisdir = LocalAlloc (LMEM_FIXED, 1024 * sizeof(WCHAR));
595 if( !curdir || !thisdir ) {
598 WCMD_output ("out of memory\n");
602 GetCurrentDirectoryW (1024, thisdir);
603 status = SetCurrentDirectoryA (param1);
610 curdir -> next = pushd_directories;
611 curdir -> strings = thisdir;
612 pushd_directories = curdir;
617 /*****************************************************************************
620 * Pop a directory from the stack
623 void WCMD_popd (void) {
624 struct env_stack *temp = pushd_directories;
626 if (!pushd_directories)
629 /* pop the old environment from the stack, and make it the current dir */
630 pushd_directories = temp->next;
631 SetCurrentDirectoryW(temp->strings);
632 LocalFree (temp->strings);
636 /****************************************************************************
639 * Batch file conditional.
640 * FIXME: Much more syntax checking needed!
643 void WCMD_if (char *p) {
645 int negate = 0, test = 0;
646 char condition[MAX_PATH], *command, *s;
648 if (!lstrcmpi (param1, "not")) {
650 lstrcpy (condition, param2);
653 lstrcpy (condition, param1);
655 if (!lstrcmpi (condition, "errorlevel")) {
656 if (errorlevel >= atoi(WCMD_parameter (p, 1+negate, NULL))) test = 1;
657 WCMD_parameter (p, 2+negate, &command);
659 else if (!lstrcmpi (condition, "exist")) {
660 if (GetFileAttributesA(WCMD_parameter (p, 1+negate, NULL)) != INVALID_FILE_ATTRIBUTES) {
663 WCMD_parameter (p, 2+negate, &command);
665 else if (!lstrcmpi (condition, "defined")) {
666 if (GetEnvironmentVariableA(WCMD_parameter (p, 1+negate, NULL), NULL, 0) > 0) {
669 WCMD_parameter (p, 2+negate, &command);
671 else if ((s = strstr (p, "=="))) {
673 if (!lstrcmpi (condition, WCMD_parameter (s, 0, NULL))) test = 1;
674 WCMD_parameter (s, 1, &command);
677 WCMD_output ("Syntax error\n");
680 if (test != negate) {
681 command = strdup (command);
682 WCMD_process_command (command);
687 /****************************************************************************
690 * Move a file, directory tree or wildcarded set of files.
691 * FIXME: Needs input and output files to be fully specified.
694 void WCMD_move (void) {
697 char outpath[MAX_PATH], inpath[MAX_PATH], *infile;
701 if (param1[0] == 0x00) {
702 WCMD_output ("Argument missing\n");
706 if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
707 WCMD_output ("Wildcards not yet supported\n");
711 /* If no destination supplied, assume current directory */
712 if (param2[0] == 0x00) {
716 /* If 2nd parm is directory, then use original filename */
717 GetFullPathName (param2, sizeof(outpath), outpath, NULL);
718 if (outpath[strlen(outpath) - 1] == '\\')
719 outpath[strlen(outpath) - 1] = '\0';
720 hff = FindFirstFile (outpath, &fd);
721 if (hff != INVALID_HANDLE_VALUE) {
722 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
723 GetFullPathName (param1, sizeof(inpath), inpath, &infile);
724 strcat (outpath, "\\");
725 strcat (outpath, infile);
730 status = MoveFile (param1, outpath);
731 if (!status) WCMD_print_error ();
734 /****************************************************************************
737 * Wait for keyboard input.
740 void WCMD_pause (void) {
745 WCMD_output (anykey);
746 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
749 /****************************************************************************
752 * Delete a directory.
755 void WCMD_remove_dir (void) {
757 if (param1[0] == 0x00) {
758 WCMD_output ("Argument missing\n");
762 /* If subdirectory search not supplied, just try to remove
763 and report error if it fails (eg if it contains a file) */
764 if (strstr (quals, "/S") == NULL) {
765 if (!RemoveDirectory (param1)) WCMD_print_error ();
767 /* Otherwise use ShFileOp to recursively remove a directory */
770 SHFILEOPSTRUCT lpDir;
773 if (strstr (quals, "/Q") == NULL) {
775 char question[MAXSTRING];
777 /* Ask for confirmation */
778 sprintf(question, "%s, ", param1);
779 ok = WCMD_ask_confirm(question, TRUE);
781 /* Abort if answer is 'N' */
788 lpDir.pFrom = param1;
789 lpDir.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI;
790 lpDir.wFunc = FO_DELETE;
791 if (SHFileOperationA(&lpDir)) WCMD_print_error ();
795 /****************************************************************************
799 * FIXME: Needs input and output files to be fully specified.
802 void WCMD_rename (void) {
806 if (param1[0] == 0x00 || param2[0] == 0x00) {
807 WCMD_output ("Argument missing\n");
810 if ((strchr(param1,'*') != NULL) || (strchr(param1,'%') != NULL)) {
811 WCMD_output ("Wildcards not yet supported\n");
814 status = MoveFile (param1, param2);
815 if (!status) WCMD_print_error ();
818 /*****************************************************************************
821 * Make a copy of the environment.
823 static WCHAR *WCMD_dupenv( const WCHAR *env )
833 len += (lstrlenW(&env[len]) + 1);
835 env_copy = LocalAlloc (LMEM_FIXED, (len+1) * sizeof (WCHAR) );
838 WCMD_output ("out of memory\n");
841 memcpy (env_copy, env, len*sizeof (WCHAR));
847 /*****************************************************************************
850 * setlocal pushes the environment onto a stack
851 * Save the environment as unicode so we don't screw anything up.
853 void WCMD_setlocal (const char *s) {
855 struct env_stack *env_copy;
857 /* DISABLEEXTENSIONS ignored */
859 env_copy = LocalAlloc (LMEM_FIXED, sizeof (struct env_stack));
862 WCMD_output ("out of memory\n");
866 env = GetEnvironmentStringsW ();
868 env_copy->strings = WCMD_dupenv (env);
869 if (env_copy->strings)
871 env_copy->next = saved_environment;
872 saved_environment = env_copy;
875 LocalFree (env_copy);
877 FreeEnvironmentStringsW (env);
880 /*****************************************************************************
883 static inline WCHAR *WCMD_strchrW(WCHAR *str, WCHAR ch)
894 /*****************************************************************************
897 * endlocal pops the environment off a stack
899 void WCMD_endlocal (void) {
900 WCHAR *env, *old, *p;
901 struct env_stack *temp;
904 if (!saved_environment)
907 /* pop the old environment from the stack */
908 temp = saved_environment;
909 saved_environment = temp->next;
911 /* delete the current environment, totally */
912 env = GetEnvironmentStringsW ();
913 old = WCMD_dupenv (GetEnvironmentStringsW ());
916 n = lstrlenW(&old[len]) + 1;
917 p = WCMD_strchrW(&old[len], '=');
921 SetEnvironmentVariableW (&old[len], NULL);
926 FreeEnvironmentStringsW (env);
928 /* restore old environment */
932 n = lstrlenW(&env[len]) + 1;
933 p = WCMD_strchrW(&env[len], '=');
937 SetEnvironmentVariableW (&env[len], p);
945 /*****************************************************************************
946 * WCMD_setshow_attrib
948 * Display and optionally sets DOS attributes on a file or directory
950 * FIXME: Wine currently uses the Unix stat() function to get file attributes.
951 * As a result only the Readonly flag is correctly reported, the Archive bit
952 * is always set and the rest are not implemented. We do the Right Thing anyway.
954 * FIXME: No SET functionality.
958 void WCMD_setshow_attrib (void) {
963 char flags[9] = {" "};
965 if (param1[0] == '-') {
970 if (lstrlen(param1) == 0) {
971 GetCurrentDirectory (sizeof(param1), param1);
972 strcat (param1, "\\*");
975 hff = FindFirstFile (param1, &fd);
976 if (hff == INVALID_HANDLE_VALUE) {
977 WCMD_output ("%s: File Not Found\n",param1);
981 if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
982 if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
985 if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
988 if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
991 if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
994 if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
997 if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
1000 WCMD_output ("%s %s\n", flags, fd.cFileName);
1001 for (count=0; count < 8; count++) flags[count] = ' ';
1003 } while (FindNextFile(hff, &fd) != 0);
1008 /*****************************************************************************
1009 * WCMD_setshow_default
1011 * Set/Show the current default directory
1014 void WCMD_setshow_default (void) {
1019 if (strlen(param1) == 0) {
1020 GetCurrentDirectory (sizeof(string), string);
1021 strcat (string, "\n");
1022 WCMD_output (string);
1025 status = SetCurrentDirectory (param1);
1027 WCMD_print_error ();
1034 /****************************************************************************
1037 * Set/Show the system date
1038 * FIXME: Can't change date yet
1041 void WCMD_setshow_date (void) {
1043 char curdate[64], buffer[64];
1046 if (lstrlen(param1) == 0) {
1047 if (GetDateFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL,
1048 curdate, sizeof(curdate))) {
1049 WCMD_output ("Current Date is %s\nEnter new date: ", curdate);
1050 ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1055 else WCMD_print_error ();
1062 /****************************************************************************
1065 static int WCMD_compare( const void *a, const void *b )
1068 const char * const *str_a = a, * const *str_b = b;
1069 r = CompareString( LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1070 *str_a, -1, *str_b, -1 );
1071 if( r == CSTR_LESS_THAN ) return -1;
1072 if( r == CSTR_GREATER_THAN ) return 1;
1076 /****************************************************************************
1077 * WCMD_setshow_sortenv
1079 * sort variables into order for display
1080 * Optionally only display those who start with a stub
1081 * returns the count displayed
1083 static int WCMD_setshow_sortenv(const char *s, const char *stub)
1085 UINT count=0, len=0, i, displayedcount=0, stublen=0;
1088 if (stub) stublen = strlen(stub);
1090 /* count the number of strings, and the total length */
1092 len += (lstrlen(&s[len]) + 1);
1096 /* add the strings to an array */
1097 str = LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, count * sizeof (char*) );
1101 for( i=1; i<count; i++ )
1102 str[i] = str[i-1] + lstrlen(str[i-1]) + 1;
1104 /* sort the array */
1105 qsort( str, count, sizeof (char*), WCMD_compare );
1108 for( i=0; i<count; i++ ) {
1109 if (!stub || CompareString (LOCALE_USER_DEFAULT,
1110 NORM_IGNORECASE | SORT_STRINGSORT,
1111 str[i], stublen, stub, -1) == 2) {
1112 WCMD_output_asis(str[i]);
1113 WCMD_output_asis("\n");
1119 return displayedcount;
1122 /****************************************************************************
1125 * Set/Show the environment variables
1128 void WCMD_setshow_env (char *s) {
1134 if (strlen(param1) == 0) {
1135 env = GetEnvironmentStrings ();
1136 WCMD_setshow_sortenv( env, NULL );
1139 p = strchr (s, '=');
1141 env = GetEnvironmentStrings ();
1142 if (WCMD_setshow_sortenv( env, s ) == 0) {
1143 WCMD_output ("Environment variable %s not defined\n", s);
1149 if (strlen(p) == 0) p = NULL;
1150 status = SetEnvironmentVariable (s, p);
1151 if ((!status) & (GetLastError() != ERROR_ENVVAR_NOT_FOUND)) WCMD_print_error();
1155 /****************************************************************************
1158 * Set/Show the path environment variable
1161 void WCMD_setshow_path (char *command) {
1166 if (strlen(param1) == 0) {
1167 status = GetEnvironmentVariable ("PATH", string, sizeof(string));
1169 WCMD_output_asis ( "PATH=");
1170 WCMD_output_asis ( string);
1171 WCMD_output_asis ( "\n");
1174 WCMD_output ("PATH not found\n");
1178 if (*command == '=') command++; /* Skip leading '=' */
1179 status = SetEnvironmentVariable ("PATH", command);
1180 if (!status) WCMD_print_error();
1184 /****************************************************************************
1185 * WCMD_setshow_prompt
1187 * Set or show the command prompt.
1190 void WCMD_setshow_prompt (void) {
1194 if (strlen(param1) == 0) {
1195 SetEnvironmentVariable ("PROMPT", NULL);
1199 while ((*s == '=') || (*s == ' ')) s++;
1200 if (strlen(s) == 0) {
1201 SetEnvironmentVariable ("PROMPT", NULL);
1203 else SetEnvironmentVariable ("PROMPT", s);
1207 /****************************************************************************
1210 * Set/Show the system time
1211 * FIXME: Can't change time yet
1214 void WCMD_setshow_time (void) {
1216 char curtime[64], buffer[64];
1220 if (strlen(param1) == 0) {
1222 if (GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, NULL,
1223 curtime, sizeof(curtime))) {
1224 WCMD_output ("Current Time is %s\nEnter new time: ", curtime);
1225 ReadFile (GetStdHandle(STD_INPUT_HANDLE), buffer, sizeof(buffer), &count, NULL);
1230 else WCMD_print_error ();
1237 /****************************************************************************
1240 * Shift batch parameters.
1243 void WCMD_shift (void) {
1245 if (context != NULL) context -> shift_count++;
1249 /****************************************************************************
1252 * Set the console title
1254 void WCMD_title (char *command) {
1255 SetConsoleTitle(command);
1258 /****************************************************************************
1261 * Copy a file to standard output.
1264 void WCMD_type (void) {
1270 if (param1[0] == 0x00) {
1271 WCMD_output ("Argument missing\n");
1274 h = CreateFile (param1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1275 FILE_ATTRIBUTE_NORMAL, NULL);
1276 if (h == INVALID_HANDLE_VALUE) {
1277 WCMD_print_error ();
1280 while (ReadFile (h, buffer, sizeof(buffer), &count, NULL)) {
1281 if (count == 0) break; /* ReadFile reports success on EOF! */
1283 WCMD_output_asis (buffer);
1288 /****************************************************************************
1291 * Display verify flag.
1292 * FIXME: We don't actually do anything with the verify flag other than toggle
1296 void WCMD_verify (char *command) {
1298 static const char von[] = "Verify is ON\n", voff[] = "Verify is OFF\n";
1301 count = strlen(command);
1303 if (verify_mode) WCMD_output (von);
1304 else WCMD_output (voff);
1307 if (lstrcmpi(command, "ON") == 0) {
1311 else if (lstrcmpi(command, "OFF") == 0) {
1315 else WCMD_output ("Verify must be ON or OFF\n");
1318 /****************************************************************************
1321 * Display version info.
1324 void WCMD_version (void) {
1326 WCMD_output (version_string);
1330 /****************************************************************************
1333 * Display volume info and/or set volume label. Returns 0 if error.
1336 int WCMD_volume (int mode, char *path) {
1338 DWORD count, serial;
1339 char string[MAX_PATH], label[MAX_PATH], curdir[MAX_PATH];
1342 if (lstrlen(path) == 0) {
1343 status = GetCurrentDirectory (sizeof(curdir), curdir);
1345 WCMD_print_error ();
1348 status = GetVolumeInformation (NULL, label, sizeof(label), &serial, NULL,
1352 if ((path[1] != ':') || (lstrlen(path) != 2)) {
1353 WCMD_output_asis("Syntax Error\n\n");
1356 wsprintf (curdir, "%s\\", path);
1357 status = GetVolumeInformation (curdir, label, sizeof(label), &serial, NULL,
1361 WCMD_print_error ();
1364 WCMD_output ("Volume in drive %c is %s\nVolume Serial Number is %04x-%04x\n\n",
1365 curdir[0], label, HIWORD(serial), LOWORD(serial));
1367 WCMD_output ("Volume label (11 characters, ENTER for none)?");
1368 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
1370 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
1371 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
1373 if (lstrlen(path) != 0) {
1374 if (!SetVolumeLabel (curdir, string)) WCMD_print_error ();
1377 if (!SetVolumeLabel (NULL, string)) WCMD_print_error ();
1383 /**************************************************************************
1386 * Exit either the process, or just this batch program
1390 void WCMD_exit (void) {
1392 int rc = atoi(param1); /* Note: atoi of empty parameter is 0 */
1394 if (context && lstrcmpi(quals, "/B") == 0) {
1396 context -> skip_rest = TRUE;
1402 /**************************************************************************
1405 * Issue a message and ask 'Are you sure (Y/N)', waiting on a valid
1408 * Returns True if Y answer is selected
1411 BOOL WCMD_ask_confirm (char *message, BOOL showSureText) {
1413 char msgbuffer[MAXSTRING];
1414 char Ybuffer[MAXSTRING];
1415 char Nbuffer[MAXSTRING];
1416 char answer[MAX_PATH] = "";
1419 /* Load the translated 'Are you sure', plus valid answers */
1420 LoadString (hinst, WCMD_CONFIRM, msgbuffer, sizeof(msgbuffer));
1421 LoadString (hinst, WCMD_YES, Ybuffer, sizeof(Ybuffer));
1422 LoadString (hinst, WCMD_NO, Nbuffer, sizeof(Nbuffer));
1424 /* Loop waiting on a Y or N */
1425 while (answer[0] != Ybuffer[0] && answer[0] != Nbuffer[0]) {
1426 WCMD_output_asis (message);
1428 WCMD_output_asis (msgbuffer);
1430 WCMD_output_asis (" (");
1431 WCMD_output_asis (Ybuffer);
1432 WCMD_output_asis ("/");
1433 WCMD_output_asis (Nbuffer);
1434 WCMD_output_asis (")?");
1435 ReadFile (GetStdHandle(STD_INPUT_HANDLE), answer, sizeof(answer),
1437 answer[0] = toupper(answer[0]);
1440 /* Return the answer */
1441 return (answer[0] == Ybuffer[0]);