xref: /haiku/src/tools/fs_shell/fs_shell_command.cpp (revision 16d5c24e533eb14b7b8a99ee9f3ec9ba66335b1e)
1 /*
2  * Copyright 2005-2007, Ingo Weinhold, bonefish@cs.tu-berlin.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 #include "fs_shell_command.h"
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 
13 static void
14 add_char(char *&buffer, int &bufferSize, char c)
15 {
16 	if (bufferSize <= 0) {
17 		fprintf(stderr, "Error: Command line too long\n");
18 		exit(1);
19 	}
20 
21 	*buffer = c;
22 	buffer++;
23 	bufferSize--;
24 }
25 
26 
27 static void
28 prepare_command_string(const char *const *argv, int argc, char *buffer,
29 		int bufferSize)
30 {
31 	for (int argi = 0; argi < argc; argi++) {
32 		const char *arg = argv[argi];
33 
34 		if (argi > 0)
35 			add_char(buffer, bufferSize, ' ');
36 
37 		while (*arg) {
38 			if (strchr(" \"'\\", *arg))
39 				add_char(buffer, bufferSize, '\\');
40 			add_char(buffer, bufferSize, *arg);
41 			arg++;
42 		}
43 	}
44 
45 	add_char(buffer, bufferSize, '\0');
46 }
47 
48 
49 int
50 main(int argc, const char *const *argv)
51 {
52 	if (argc < 2) {
53 		fprintf(stderr, "Error: No command given.\n");
54 		exit(1);
55 	}
56 
57 	// prepare the command string
58 	char command[102400];
59 	prepare_command_string(argv + 1, argc - 1, command, sizeof(command));
60 
61 	// send the command
62 	int result;
63 	if (!send_external_command(command, &result))
64 		exit(1);
65 
66 	// evaluate result
67 	if (result != 0) {
68 		fprintf(stderr, "Error: Command failed: %s\n", strerror(result));
69 		fprintf(stderr, "Error: Command was:\n  %s\n", command);
70 		exit(1);
71 	}
72 
73 	return 0;
74 }
75 
76