Repository navigation
Expand file tree
/
Copy pathwsh.c
More file actions
1059 lines (919 loc) · 25.9 KB
/
Copy pathwsh.c
File metadata and controls
1059 lines (919 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "wsh.h"
#include "dynamic_array.h"
#include "utils.h"
#include "hash_map.h"
#include <stdio.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
DynamicArray *history_da = NULL;
char *current_path = NULL;
int rc;
HashMap *alias_hm = NULL;
/***************************************************
* Helper Functions
***************************************************/
//Remove in a bit
void *debug_strdup(const char *s, const char *file, int line) {
void *result = strdup(s);
fprintf(stderr, "STRDUP: %p '%s' at %s:%d\n", result, s, file, line);
return result;
}
/**
* @Brief Free any allocated global resources
*/
void wsh_free(void)
{
// Free any allocated resources here
if (alias_hm != NULL) {
hm_free(alias_hm);
alias_hm = NULL;
}
if (history_da != NULL) {
da_free(history_da);
history_da = NULL;
}
if (current_path != NULL) {
free(current_path);
current_path = NULL;
}
}
/**
* @Brief Cleanly exit the shell after freeing resources
*
* @param return_code The exit code to return
*/
void clean_exit(int return_code)
{
wsh_free();
exit(return_code);
}
/**
* @Brief Print a warning message to stderr and set the return code
*
* @param msg The warning message format string
* @param ... Additional arguments for the format string
*/
void wsh_warn(const char *msg, ...)
{
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
rc = EXIT_FAILURE;
}
/**
* @brief Read a line from a file descriptor
*/
ssize_t read_line(int fd, char *buffer, size_t size)
{
size_t i = 0;
char c;
ssize_t bytes_read = 0;
while (i < size - 1) {
bytes_read = read(fd, &c, 1);
if (bytes_read == 0) {
break; // EOF
}
if (bytes_read < 0) {
return -1; // Error
}
buffer[i++] = c;
if (c == '\n') {
break; // End of line
}
}
buffer[i] = '\0';
return (i > 0 || bytes_read > 0) ? i : 0;
}
/**
* @Brief Main entry point for the shell
*
* @param argc Number of arguments
* @param argv Array of argument strings
* @return
*/
int main(int argc, char **argv)
{
alias_hm = hm_create();
setenv("PATH", "/bin", 1);
if (argc > 2)
{
wsh_warn(INVALID_WSH_USE);
return EXIT_FAILURE;
}
switch (argc)
{
case 1:
interactive_main();
break;
case 2:
rc = batch_main(argv[1]);
break;
default:
break;
}
wsh_free();
return rc;
}
/**
* @brief Parse a command line into pipeline segments
*/
int parse_pipeline(const char *cmdline, char ***commands, int *argcs)
{
char *copy = strdup(cmdline);
char *segment;
char *saveptr = NULL;
int num_commands = 0;
// Split by | to get pipeline segments
segment = strtok_r(copy, "|", &saveptr);
while (segment && num_commands < 128) {
while (*segment == ' ') segment++;
char *end = segment + strlen(segment) - 1;
while (end > segment && *end == ' ') end--;
*(end + 1) = '\0';
// Parse each segment into arguments
char *argv[MAX_ARGS];
int argc = 0;
parseline_no_subst(segment, argv, &argc);
// store the segment, even if empty
commands[num_commands] = malloc(sizeof(char*) * (argc + 1));
for (int i = 0; i < argc; i++) {
commands[num_commands][i] = strdup(argv[i]);
}
commands[num_commands][argc] = NULL;
argcs[num_commands] = argc;
num_commands++;
// Free the parsed arguments
for (int i = 0; i < argc; i++) free(argv[i]);
segment = strtok_r(NULL, "|", &saveptr);
}
free(copy);
copy = NULL;
segment = NULL;
saveptr = NULL;
return num_commands;
}
/**
* @brief Add command to history
*/
void add_to_history(const char *cmdline)
{
if (!history_da) {
history_da = da_create(100);
}
// Skip empty commands
if (!cmdline || strlen(cmdline) == 0) return;
// Don't add duplicate consecutive commands
if (history_da->size > 0) {
char *last = da_get(history_da, history_da->size - 1);
if (last && strcmp(last, cmdline) == 0) return;
}
da_put(history_da, cmdline);
}
/**
* @Brief Expand aliases in command line (only first token)
*/
char *expand_aliases(const char *cmdline)
{
if (!cmdline || !alias_hm || strlen(cmdline) == 0) {
return strdup(cmdline);
}
// Parse first token only
char *argv[MAX_ARGS];
int argc = 0;
parseline_no_subst(cmdline, argv, &argc);
if (argc == 0) {
return strdup(cmdline);
}
// Check if first token is an alias
char *alias_cmd = hm_get(alias_hm, argv[0]);
if (!alias_cmd) {
// Free parsed arguments and return original
for (int i = 0; i < argc; i++) free(argv[i]);
return strdup(cmdline);
}
// Handle empty alias command
if (strlen(alias_cmd) == 0) {
// If alias is empty, just use the remaining arguments
if (argc == 1) {
// No arguments, return empty string
for (int i = 0; i < argc; i++) free(argv[i]);
return strdup("");
} else {
// Skip the first token (the alias name)
char *new_cmd = strdup(argv[1]);
for (int i = 2; i < argc; i++) {
new_cmd = append(new_cmd, " ");
new_cmd = append(new_cmd, argv[i]);
}
for (int i = 0; i < argc; i++) free(argv[i]);
return new_cmd;
}
}
// Build new command with alias expansion
char *new_cmd = strdup(alias_cmd);
for (int i = 1; i < argc; i++) {
new_cmd = append(new_cmd, " ");
new_cmd = append(new_cmd, argv[i]);
}
// Free parsed arguments
for (int i = 0; i < argc; i++) free(argv[i]);
return new_cmd;
}
/**
* @Brief Find executable in PATH
*/
char *find_executable(const char *cmd)
{
if (!cmd || strlen(cmd) == 0) return NULL;
// If command starts with . or /, it's a path - check if executable
if (cmd[0] == '.' || cmd[0] == '/') {
if (access(cmd, X_OK) == 0) {
return strdup(cmd);
}
return NULL;
}
// Get PATH
char *path_env = getenv("PATH");
if (!path_env || strlen(path_env) == 0) {
return NULL;
}
// Search in PATH directories
char *path_copy = strdup(path_env);
if (!path_copy) {
perror("strdup");
return NULL;
}
char *dir = strtok(path_copy, ":");
char *result = NULL;
while (dir) {
// Build full path: dir/cmd
size_t full_len = strlen(dir) + strlen(cmd) + 2;
char *full_path = malloc(full_len);
if (!full_path) {
perror("malloc");
free(path_copy);
return NULL;
}
snprintf(full_path, full_len, "%s/%s", dir, cmd);
if (access(full_path, X_OK) == 0) {
result = full_path; // Found it
break;
}
free(full_path);
dir = strtok(NULL, ":");
}
free(path_copy);
return result;
}
/**
* @Brief Execute external command
*/
int find_and_execute(char **argv, int argc)
{
if (argc == 0) return EXIT_SUCCESS;
// Check for empty PATH first
char *path_env = getenv("PATH");
if (!path_env || strlen(path_env) == 0) {
wsh_warn(EMPTY_PATH);
return EXIT_FAILURE;
}
// Find executable
char *exec_path = find_executable(argv[0]);
if (!exec_path) {
wsh_warn(CMD_NOT_FOUND, argv[0]);
return EXIT_FAILURE;
}
// Execute
pid_t pid = fork();
if (pid == 0) {
// Child process
execv(exec_path, argv);
// If execv returns, there was an error
perror("execv");
free(exec_path);
exit(EXIT_FAILURE);
} else if (pid > 0) {
// Parent process - WAIT for child to complete
int status;
waitpid(pid, &status, 0);
free(exec_path);
if (WIFEXITED(status)) {
return WEXITSTATUS(status);
} else {
return EXIT_FAILURE;
}
} else {
// Fork failed
perror("fork");
free(exec_path);
return EXIT_FAILURE;
}
}
/**
* @brief Execute pipeline of commands
*/
int execute_pipeline(char ***commands, int *argcs, int num_commands)
{
if (num_commands == 0) return EXIT_SUCCESS;
if (num_commands == 1) return execute_command(commands[0], argcs[0]);
int prev_pipe[2] = {-1, -1};
int next_pipe[2];
pid_t pids[num_commands];
int overall_status = EXIT_SUCCESS;
// Create all processes
for (int i = 0; i < num_commands; i++) {
// Create pipe for all but last command
if (i < num_commands - 1) {
if (pipe(next_pipe) == -1) {
perror("pipe");
return EXIT_FAILURE;
}
}
pids[i] = fork();
if (pids[i] == 0) {
// Child process
if (i > 0) {
dup2(prev_pipe[0], STDIN_FILENO);
}
if (i < num_commands - 1) {
dup2(next_pipe[1], STDOUT_FILENO);
}
if (i > 0) {
close(prev_pipe[0]);
close(prev_pipe[1]);
}
if (i < num_commands - 1) {
close(next_pipe[0]);
close(next_pipe[1]);
}
// Execute command
execute_command(commands[i], argcs[i]);
exit(overall_status); // Should never reach here
} else if (pids[i] < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (i > 0) {
close(prev_pipe[0]);
close(prev_pipe[1]);
}
if (i < num_commands - 1) {
prev_pipe[0] = next_pipe[0];
prev_pipe[1] = next_pipe[1];
}
}
if (num_commands > 1) {
close(prev_pipe[0]);
close(prev_pipe[1]);
}
// Wait for all children
for (int i = 0; i < num_commands; i++) {
int status;
waitpid(pids[i], &status, 0);
if (i == num_commands - 1) {
overall_status = WEXITSTATUS(status);
}
}
return overall_status;
}
/**
* @Brief Execute a single command (builtin or external)
*/
int execute_command(char **argv, int argc)
{
if (argc == 0) return EXIT_SUCCESS;
if (strcmp(argv[0], "exit") == 0) {
int result = wsh_exit(argv, argc);
return result;
} else if (strcmp(argv[0], "alias") == 0) {
int result = wsh_alias(argv, argc);
return result;
} else if (strcmp(argv[0], "unalias") == 0) {
int result = wsh_unalias(argv, argc);
return result;
} else if (strcmp(argv[0], "which") == 0) {
int result = wsh_which(argv, argc);
return result;
} else if (strcmp(argv[0], "path") == 0) {
int result = wsh_path(argv, argc);
return result;
} else if (strcmp(argv[0], "cd") == 0) {
int result = wsh_cd(argv, argc);
return result;
} else if (strcmp(argv[0], "history") == 0) {
int result = wsh_history(argv, argc);
return result;
} else {
// External command
int result = find_and_execute(argv, argc);
return result;
}
}
/**
* @Brief Exit built-in command
*/
int wsh_exit(char **argv, int argc)
{
(void)argv; // Mark parameter as unused to avoid warning
if (argc > 1) {
wsh_warn(INVALID_EXIT_USE);
return EXIT_FAILURE;
}
clean_exit(rc);
return EXIT_SUCCESS; // Never reached
}
/**
* @brief Alias built-in command
*/
int wsh_alias(char **argv, int argc)
{
if (argc == 1) {
// Print all aliases sorted
hm_print_sorted(alias_hm);
return EXIT_SUCCESS;
}
if (argc == 4 && strcmp(argv[2], "=") == 0) {
char *name = argv[1];
char *command = argv[3];
// Validate name
if (strlen(name) == 0) {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
// Remove surrounding single quotes if present
char *clean_command;
size_t cmd_len = strlen(command);
if (cmd_len >= 2 && command[0] == '\'' && command[cmd_len-1] == '\'') {
clean_command = malloc(cmd_len - 1);
strncpy(clean_command, command + 1, cmd_len - 2);
clean_command[cmd_len - 2] = '\0';
} else {
clean_command = strdup(command);
}
hm_put(alias_hm, name, clean_command);
free(clean_command);
return EXIT_SUCCESS;
}
else if (argc >= 5 && strcmp(argv[2], "=") == 0) {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
else if (argc >= 4 && strcmp(argv[2], "=") != 0) {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
else if (argc == 4 && strcmp(argv[2], "=") == 0) {
char *name = argv[1];
char *command = argv[3];
// Validate name
if (strlen(name) == 0) {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
hm_put(alias_hm, name, command);
return EXIT_SUCCESS;
}
else if (argc == 3 && strcmp(argv[2], "=") != 0) {
char *name = argv[1];
char *command = argv[2];
// Validate name
if (strlen(name) == 0) {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
hm_put(alias_hm, name, command);
return EXIT_SUCCESS;
}
else if (argc == 3 && strcmp(argv[2], "=") == 0) {
char *name = argv[1];
// Validate name
if (strlen(name) == 0) {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
hm_put(alias_hm, name, "");
return EXIT_SUCCESS;
}
else if (argc == 2) {
char *arg = argv[1];
char *equals = strchr(arg, '=');
if (!equals) {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
// Split without modifying original
size_t name_len = equals - arg;
char *name = malloc(name_len + 1);
strncpy(name, arg, name_len);
name[name_len] = '\0';
char *command = strdup(equals + 1);
// Validate name
if (strlen(name) == 0) {
wsh_warn(INVALID_ALIAS_USE);
free(name);
free(command);
return EXIT_SUCCESS;
}
hm_put(alias_hm, name, command);
free(name);
free(command);
return EXIT_SUCCESS;
}
else {
wsh_warn(INVALID_ALIAS_USE);
return EXIT_SUCCESS;
}
}
/**
* @brief Unalias built-in command
*/
int wsh_unalias(char **argv, int argc)
{
if (argc != 2) {
wsh_warn(INVALID_UNALIAS_USE);
return EXIT_FAILURE;
}
hm_delete(alias_hm, argv[1]);
return EXIT_SUCCESS;
}
/**
* @brief Which built-in command
*/
int wsh_which(char **argv, int argc)
{
if (argc != 2) {
wsh_warn(INVALID_WHICH_USE);
return EXIT_FAILURE;
}
char *name = argv[1];
// Check if it's an alias
char *alias_cmd = hm_get(alias_hm, name);
if (alias_cmd) {
printf(WHICH_ALIAS, name, alias_cmd);
return EXIT_SUCCESS;
}
// Check if it's a built-in
if (strcmp(name, "exit") == 0 || strcmp(name, "alias") == 0 ||
strcmp(name, "unalias") == 0 || strcmp(name, "which") == 0 ||
strcmp(name, "path") == 0 || strcmp(name, "cd") == 0 ||
strcmp(name, "history") == 0) {
printf(WHICH_BUILTIN, name);
return EXIT_SUCCESS;
}
// Check if it's an executable
char *exec_path = find_executable(name);
if (exec_path) {
printf(WHICH_EXTERNAL, name, exec_path);
free(exec_path);
return EXIT_SUCCESS;
}
// Not found
printf(WHICH_NOT_FOUND, name);
return EXIT_FAILURE;
}
/**
* @brief Path built-in command
*/
int wsh_path(char **argv, int argc)
{
if (argc == 1) {
// Print current PATH
char *path = getenv("PATH");
if (path) {
printf("%s\n", path);
} else {
printf("\n"); // Print empty line if PATH not set
}
return EXIT_SUCCESS;
}
if (argc > 2) {
wsh_warn(INVALID_PATH_USE);
return EXIT_FAILURE;
}
// Set new PATH
if (setenv("PATH", argv[1], 1) != 0) {
perror("setenv");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief Change directory built-in command
*/
int wsh_cd(char **argv, int argc)
{
char *target_dir = NULL;
if (argc == 1) {
// cd with no arguments - go to HOME
target_dir = getenv("HOME");
if (!target_dir) {
wsh_warn(CD_NO_HOME);
return EXIT_FAILURE;
}
} else if (argc == 2) {
target_dir = argv[1];
} else {
wsh_warn(INVALID_CD_USE);
return EXIT_FAILURE;
}
if (chdir(target_dir) != 0) {
perror("cd");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief History built-in command
*/
int wsh_history(char **argv, int argc)
{
if (!history_da || history_da->size == 0) {
return EXIT_SUCCESS;
}
if (argc == 1) {
// Print all history WITHOUT line numbers
for (size_t i = 0; i < history_da->size; i++) {
printf("%s\n", da_get(history_da, i));
}
return EXIT_SUCCESS;
}
if (argc == 2) {
// Print specific history entry: history n
char *endptr;
long n = strtol(argv[1], &endptr, 10);
// Validate argument - must be a number
if (*endptr != '\0' || n < 1) {
wsh_warn(HISTORY_INVALID_ARG);
return EXIT_FAILURE;
}
// If n > history size, print the last command
if ((size_t)n > history_da->size) {
n = history_da->size;
}
// Print the nth command (1-based index)
printf("%s\n", da_get(history_da, n - 1));
return EXIT_SUCCESS;
}
wsh_warn(INVALID_HISTORY_USE);
return EXIT_FAILURE;
}
/***************************************************
* Modes of Execution
***************************************************/
/**
* @Brief Interactive mode: print prompt and wait for user input
* execute the given input and repeat
*/
void interactive_main(void)
{
char line[MAX_LINE];
while (1) {
printf(PROMPT);
fflush(stdout);
if (fgets(line, sizeof(line), stdin) == NULL) {
if (feof(stdin)) {
printf("\n");
break;
} else {
wsh_warn("fgets error\n");
continue;
}
}
line[strcspn(line, "\n")] = 0;
if (strlen(line) == 0) continue;
char *expanded = expand_aliases(line);
// Check if this is a pipeline
if (strchr(expanded, '|') != NULL) {
// Handle as pipeline
char **commands[128]; // Array of command arrays (char**)
int argcs[128]; // Array of argument counts
int num_commands = parse_pipeline(expanded, commands, argcs);
if (num_commands > 0) {
// Check for empty segments
int has_empty_segment = 0;
for (int i = 0; i < num_commands; i++) {
if (argcs[i] == 0) {
wsh_warn(EMPTY_PIPE_SEGMENT);
has_empty_segment = 1;
break;
}
}
if (!has_empty_segment) {
rc = execute_pipeline(commands, argcs, num_commands);
for (int i = 0; i < num_commands; i++) {
for (int j = 0; j < argcs[i]; j++) {
free(commands[i][j]);
}
free(commands[i]);
}
} else {
rc = EXIT_FAILURE;
for (int i = 0; i < num_commands; i++) {
for (int j = 0; j < argcs[i]; j++) {
free(commands[i][j]);
}
free(commands[i]);
}
}
}
} else {
// Handle as single command
char *argv[MAX_ARGS];
int argc = 0;
parseline_no_subst(expanded, argv, &argc);
if (argc > 0) {
rc = execute_command(argv, argc);
}
for (int i = 0; i < argc; i++) {
free(argv[i]);
}
}
add_to_history(line);
free(expanded);
}
wsh_free();
clean_exit(EXIT_SUCCESS); // Clean exit
}
/**
* @brief Batch mode: read commands from script file line by line
*/
int batch_main(const char *script_file)
{
int fd = open(script_file, O_RDONLY);
if (fd == -1) {
// File doesn't exist - print the expected error message
perror("fopen");
return EXIT_FAILURE;
}
char line[MAX_LINE];
int line_num = 0;
int last_status = EXIT_SUCCESS;
while (1) {
ssize_t bytes_read = read_line(fd, line, sizeof(line));
if (bytes_read < 0) {
perror("read");
break;
}
if (bytes_read == 0) {
break;
}
line_num++;
// Remove trailing newline if present
if (bytes_read > 0 && line[bytes_read - 1] == '\n') {
line[bytes_read - 1] = '\0';
}
// Skip empty lines and comments
if (strlen(line) == 0 || line[0] == '#') {
continue;
}
// Expand aliases
char *expanded = expand_aliases(line);
// Check if this is a pipeline
if (strchr(expanded, '|') != NULL) {
// Handle as pipeline
char **commands[128];
int argcs[128];
int num_commands = parse_pipeline(expanded, commands, argcs);
if (num_commands > 0) {
// Check for empty segments
int has_empty_segment = 0;
for (int i = 0; i < num_commands; i++) {
if (argcs[i] == 0) {
wsh_warn(EMPTY_PIPE_SEGMENT);
has_empty_segment = 1;
break;
}
}
if (!has_empty_segment) {
last_status = execute_pipeline(commands, argcs, num_commands);
} else {
last_status = EXIT_FAILURE;
}
}
for (int i = 0; i < num_commands; i++) {
for (int j = 0; j < argcs[i]; j++) {
free(commands[i][j]);
}
free(commands[i]);
}
} else {
// Handle as single command
char *argv[MAX_ARGS];
int argc = 0;
parseline_no_subst(expanded, argv, &argc);
if (argc > 0) {
last_status = execute_command(argv, argc);
}
for (int i = 0; i < argc; i++) {
free(argv[i]);
}
}
// Add to history
add_to_history(line);
free(expanded);
// Flush output
fflush(stdout);
fflush(stderr);
}
close(fd);
return last_status;
}
/***************************************************
* Parsing
***************************************************/
/**
* @Brief Parse a command line into arguments without doing
* any alias substitutions.
* Handles single quotes to allow spaces within arguments.
*
* @param cmdline The command line to parse
* @param argv Array to store the parsed arguments (must be preallocated)
* @param argc Pointer to store the number of parsed arguments
*/
void parseline_no_subst(const char *cmdline, char **argv, int *argc)
{
if (!cmdline)
{
*argc = 0;
argv[0] = NULL;
return;
}
char *buf = strdup(cmdline);
if (!buf)
{
perror("strdup");
clean_exit(EXIT_FAILURE);
}
/* Replace trailing newline with space */
const size_t len = strlen(buf);
if (len > 0 && buf[len - 1] == '\n')
buf[len - 1] = ' ';
else
{
char *new_buf = realloc(buf, len + 2);