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
|
const std = @import("std");
const print = std.debug.print;
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const Thread = std.Thread;
const Mutex = std.Thread.Mutex;
const c = @cImport({
@cInclude("errno.h");
@cInclude("stdio.h");
if (@import("builtin").os.tag != .windows) {
@cInclude("sys/statvfs.h");
}
});
const cmd = @import("cmd.zig");
const Command = cmd.Command;
const BuiltinCommand = cmd.BuiltinCommand;
const syntax = @import("syntax.zig");
const FileSpec = syntax.FileSpec;
const RedirectType = syntax.RedirectType;
const Redirect = syntax.Redirect;
const paths = @import("paths.zig");
const formatDosPath = paths.formatDosPath;
const convertTo83 = paths.convertTo83;
const cmdTypes = @import("cmd/types.zig");
pub const CommandStatus = cmdTypes.CommandStatus;
const OutputCapture = cmdTypes.OutputCapture;
const InputSource = cmdTypes.InputSource;
const STDOUT_BUFFER_SIZE: usize = 1024;
const STDERR_BUFFER_SIZE: usize = 1024;
fn formatDosDateTime(allocator: Allocator, timestamp_secs: i64) ![]const u8 {
const epoch_seconds = @as(u64, @intCast(@max(timestamp_secs, 0)));
const epoch_day = @divFloor(epoch_seconds, std.time.s_per_day);
const day_seconds = epoch_seconds % std.time.s_per_day;
// Calculate date (simplified)
var year: u32 = 1970; // Start from Unix epoch year
var remaining_days = epoch_day;
// Simple year calculation
while (remaining_days >= 365) {
const days_in_year: u64 = if (isLeapYear(year)) 366 else 365;
if (remaining_days < days_in_year) break;
remaining_days -= days_in_year;
year += 1;
}
// Simple month/day calculation (approximate)
const month = @min(@divFloor(remaining_days, 30) + 1, 12);
const day = @min(remaining_days % 30 + 1, 31);
// Calculate time
const hours = day_seconds / std.time.s_per_hour;
const minutes = (day_seconds % std.time.s_per_hour) / std.time.s_per_min;
// Format as MM-DD-YY HH:MMa (DOS style)
const am_pm = if (hours < 12) "a" else "p";
const display_hour = if (hours == 0) 12 else if (hours > 12) hours - 12 else hours;
return try std.fmt.allocPrint(allocator, "{d:0>2}-{d:0>2}-{d:0>2} {d:>2}:{d:0>2}{s}", .{ @as(u32, @intCast(month)), @as(u32, @intCast(day)), @as(u32, @intCast(year % 100)), @as(u32, @intCast(display_hour)), @as(u32, @intCast(minutes)), am_pm });
}
pub fn executeCommand(command: Command, allocator: Allocator) !CommandStatus {
return executeCommandWithOutput(command, allocator, null, null);
}
fn executeCommandWithOutput(command: Command, allocator: Allocator, output_capture: ?*OutputCapture, input_source: ?*InputSource) !CommandStatus {
switch (command) {
.Empty => return CommandStatus{ .Code = 0 },
.Builtin => |builtin_cmd| {
switch (builtin_cmd) {
.EchoText => |echo| {
const output = try std.fmt.allocPrint(allocator, "{s}\n", .{echo.message});
defer allocator.free(output);
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
.Cls => {
if (output_capture == null) {
// Clear screen - only works when not redirected
print("\x1B[2J\x1B[H", .{});
}
return CommandStatus{ .Code = 0 };
},
.Exit => {
return CommandStatus.ExitShell;
},
.EchoPlain => {
const output = "ECHO is on\n";
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
.EchoOn => {
const output = "ECHO is on\n";
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
.EchoOff => {
return CommandStatus{ .Code = 0 };
},
.Ver => {
const output = "MB-DOSE Version 6.22\n";
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
.Date => {
const timestamp = std.time.timestamp();
const epoch_seconds = @as(u64, @intCast(timestamp));
const epoch_day = @divFloor(epoch_seconds, std.time.s_per_day);
// Calculate days since Unix epoch (1970-01-01)
// Unix epoch is 719163 days since year 1 AD
const days_since_year_1 = epoch_day + 719163;
// Simple algorithm to convert days to year/month/day
var year: u32 = 1;
var remaining_days = days_since_year_1;
// Find the year
while (true) {
const days_in_year: u64 = if (isLeapYear(year)) 366 else 365;
if (remaining_days < days_in_year) break;
remaining_days -= days_in_year;
year += 1;
}
// Days in each month (non-leap year)
const days_in_month = [_]u32{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
var month: u32 = 1;
for (days_in_month, 1..) |days, m| {
var month_days = days;
// Adjust February for leap years
if (m == 2 and isLeapYear(year)) {
month_days = 29;
}
if (remaining_days < month_days) {
month = @intCast(m);
break;
}
remaining_days -= month_days;
}
const day = remaining_days + 1; // Days are 1-indexed
const output = try std.fmt.allocPrint(allocator, "Current date is {d:0>2}/{d:0>2}/{d}\n", .{ month, day, year });
defer allocator.free(output);
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
.Time => {
const timestamp = std.time.timestamp();
const epoch_seconds = @as(u64, @intCast(timestamp));
const day_seconds = epoch_seconds % std.time.s_per_day;
const hours = day_seconds / std.time.s_per_hour;
const minutes = (day_seconds % std.time.s_per_hour) / std.time.s_per_min;
const seconds = day_seconds % std.time.s_per_min;
const output = try std.fmt.allocPrint(allocator, "Current time is {d:0>2}:{d:0>2}:{d:0>2}\n", .{ hours, minutes, seconds });
defer allocator.free(output);
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
.Dir => |dir| {
var output_buffer = ArrayList(u8).init(allocator);
defer output_buffer.deinit();
// Format path in DOS style with backslashes and uppercase drive letter
const formatted_path = try formatDosPath(allocator, dir.path);
defer allocator.free(formatted_path);
// Get volume label (simplified - just show drive)
const drive_letter = if (formatted_path.len >= 2 and formatted_path[1] == ':')
formatted_path[0]
else
'C';
try output_buffer.writer().print(" Volume in drive {c} has no label\n", .{drive_letter});
try output_buffer.writer().print(" Volume Serial Number is 1234-5678\n", .{});
try output_buffer.writer().print("\n Directory of {s}\n\n", .{formatted_path});
var dir_iterator = std.fs.cwd().openDir(dir.path, .{ .iterate = true }) catch {
const error_msg = "File not found\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
defer dir_iterator.close();
var iterator = dir_iterator.iterate();
var file_count: u32 = 0;
var dir_count: u32 = 0;
var total_file_bytes: u64 = 0;
while (try iterator.next()) |entry| {
const stat = dir_iterator.statFile(entry.name) catch continue;
// Convert timestamp to DOS date/time format
const mtime_secs = @divFloor(stat.mtime, std.time.ns_per_s);
const date_time = try formatDosDateTime(allocator, @intCast(mtime_secs));
defer allocator.free(date_time);
// Convert filename to 8.3 format
const short_name = try convertTo83(allocator, entry.name);
defer allocator.free(short_name);
switch (entry.kind) {
.directory => {
try output_buffer.writer().print("{s} <DIR> {s}\n", .{ date_time, short_name });
dir_count += 1;
},
.file => {
try output_buffer.writer().print("{s} {d:>14} {s}\n", .{ date_time, stat.size, short_name });
file_count += 1;
total_file_bytes += stat.size;
},
else => {},
}
}
// Get free disk space using statvfs
const path = try std.fs.cwd().realpathAlloc(allocator, dir.path);
defer allocator.free(path);
const bytes_free = getFreeDiskSpace(path) catch |err| switch (err) {
error.AccessDenied => 0,
error.NotImplemented => 0,
};
try output_buffer.writer().print(" {d} File(s) {d:>14} bytes\n", .{ file_count, total_file_bytes });
try output_buffer.writer().print(" {d} Dir(s) {d:>14} bytes free\n", .{ dir_count, bytes_free });
if (output_capture) |capture| {
try capture.write(output_buffer.items);
} else {
print("{s}", .{output_buffer.items});
}
return CommandStatus{ .Code = 0 };
},
.Type => |type_cmd| {
const file_path = switch (type_cmd.file) {
.Con => {
const error_msg = "Cannot TYPE from CON\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
.Lpt1, .Lpt2, .Lpt3, .Prn => {
const error_msg = "Cannot TYPE from device\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
.Path => |path| path,
};
const file = std.fs.cwd().openFile(file_path, .{}) catch |err| {
const error_msg = switch (err) {
error.FileNotFound => "The system cannot find the file specified.\n",
error.IsDir => "Access is denied.\n",
error.AccessDenied => "Access is denied.\n",
else => "Cannot access file.\n",
};
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
defer file.close();
// Read and display file contents
var buffer: [4096]u8 = undefined;
while (true) {
const bytes_read = file.readAll(&buffer) catch |err| {
const error_msg = switch (err) {
error.AccessDenied => "Access is denied.\n",
else => "Error reading file.\n",
};
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
if (bytes_read == 0) break;
// Process buffer contents for output
var processed_output = ArrayList(u8).init(allocator);
defer processed_output.deinit();
for (buffer[0..bytes_read]) |byte| {
// Convert to printable characters, similar to DOS TYPE behavior
if (byte >= 32 and byte <= 126) {
try processed_output.append(byte);
} else if (byte == '\n') {
try processed_output.append('\n');
} else if (byte == '\r') {
// Skip carriage return in DOS-style line endings
continue;
} else if (byte == '\t') {
try processed_output.append('\t');
} else {
// Replace non-printable characters with '?'
try processed_output.append('?');
}
}
if (output_capture) |capture| {
try capture.write(processed_output.items);
} else {
print("{s}", .{processed_output.items});
}
// If we read less than the buffer size, we're done
if (bytes_read < buffer.len) break;
}
return CommandStatus{ .Code = 0 };
},
.Sort => {
var lines = ArrayList([]const u8).init(allocator);
defer {
for (lines.items) |line| {
allocator.free(line);
}
lines.deinit();
}
// Read input lines
if (input_source) |source| {
// Read from input redirection
while (try source.readLine(allocator)) |line| {
try lines.append(line);
}
} else {
// Read from stdin (simplified - just show message)
const msg = "SORT: Use input redirection (< file.txt) to sort file contents\n";
if (output_capture) |capture| {
try capture.write(msg);
} else {
print("{s}", .{msg});
}
return CommandStatus{ .Code = 0 };
}
// Sort the lines
std.mem.sort([]const u8, lines.items, {}, struct {
fn lessThan(_: void, lhs: []const u8, rhs: []const u8) bool {
return std.mem.order(u8, lhs, rhs) == .lt;
}
}.lessThan);
// Output sorted lines
var output_buffer = ArrayList(u8).init(allocator);
defer output_buffer.deinit();
for (lines.items) |line| {
try output_buffer.writer().print("{s}\n", .{line});
}
if (output_capture) |capture| {
try capture.write(output_buffer.items);
} else {
print("{s}", .{output_buffer.items});
}
return CommandStatus{ .Code = 0 };
},
.Chdir => |chdir| {
if (chdir.path.len == 0) {
// No arguments - display current directory
const cwd = std.fs.cwd().realpathAlloc(allocator, ".") catch {
const error_msg = "Unable to determine current directory\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
defer allocator.free(cwd);
const formatted_path = try formatDosPath(allocator, cwd);
defer allocator.free(formatted_path);
const output = try std.fmt.allocPrint(allocator, "{s}\n", .{formatted_path});
defer allocator.free(output);
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
} else {
// Change directory
const target_path = chdir.path;
// Handle special cases
if (std.mem.eql(u8, target_path, "..")) {
// Go to parent directory
std.process.changeCurDir("..") catch {
const error_msg = "The system cannot find the path specified.\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
} else if (std.mem.eql(u8, target_path, "\\") or std.mem.eql(u8, target_path, "/")) {
// Go to root directory - simplified to just go to "/"
std.process.changeCurDir("/") catch {
const error_msg = "The system cannot find the path specified.\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
} else {
// Regular directory change
// Make sure the path doesn't contain null bytes
for (target_path) |ch| {
if (ch == 0) {
const error_msg = "Invalid path: contains null character\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
}
}
std.process.changeCurDir(target_path) catch {
const error_msg = "The system cannot find the path specified.\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
}
return CommandStatus{ .Code = 0 };
}
},
.Copy => |copy| {
return copy.eval(allocator, output_capture, input_source);
},
.Remove => |remove| {
const file_path = remove.path;
// Check for wildcards (basic support)
if (std.mem.indexOf(u8, file_path, "*") != null or std.mem.indexOf(u8, file_path, "?") != null) {
// Simple wildcard deletion - just show error for now
const error_msg = "Wildcard deletion not yet implemented\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
}
// Delete single file
std.fs.cwd().deleteFile(file_path) catch |err| {
const error_msg = switch (err) {
error.FileNotFound => "File not found\n",
error.AccessDenied => "Access denied\n",
error.IsDir => "Access denied - cannot delete directory\n",
else => "Cannot delete file\n",
};
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
// No output for successful deletion (DOS style)
return CommandStatus{ .Code = 0 };
},
.Mkdir => |mkdir| {
const dir_path = mkdir.path;
std.fs.cwd().makeDir(dir_path) catch |err| {
const error_msg = switch (err) {
error.PathAlreadyExists => "A subdirectory or file already exists\n",
error.AccessDenied => "Access denied\n",
error.FileNotFound => "The system cannot find the path specified\n",
error.NotDir => "The system cannot find the path specified\n",
else => "Unable to create directory\n",
};
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
// No output for successful creation (DOS style)
return CommandStatus{ .Code = 0 };
},
.Rmdir => |rmdir| {
const dir_path = rmdir.path;
std.fs.cwd().deleteDir(dir_path) catch |err| {
const error_msg = switch (err) {
error.FileNotFound => "The system cannot find the path specified\n",
error.AccessDenied => "Access denied\n",
error.DirNotEmpty => "The directory is not empty\n",
error.FileBusy => "The directory is in use\n",
error.NotDir => "The system cannot find the path specified\n",
else => "Unable to remove directory\n",
};
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
// No output for successful removal (DOS style)
return CommandStatus{ .Code = 0 };
},
.Rename => |rename| {
const from_path = switch (rename.from) {
.Con, .Lpt1, .Lpt2, .Lpt3, .Prn => {
const error_msg = "Cannot rename device\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
.Path => |path| path,
};
const to_path = switch (rename.to) {
.Con, .Lpt1, .Lpt2, .Lpt3, .Prn => {
const error_msg = "Cannot rename to device\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
.Path => |path| path,
};
std.fs.cwd().rename(from_path, to_path) catch |err| {
const error_msg = switch (err) {
error.FileNotFound => "The system cannot find the file specified\n",
error.AccessDenied => "Access denied\n",
error.PathAlreadyExists => "A duplicate file name exists, or the file cannot be found\n",
error.RenameAcrossMountPoints => "Cannot rename across different drives\n",
else => "Cannot rename file\n",
};
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
// No output for successful rename (DOS style)
return CommandStatus{ .Code = 0 };
},
.Move => {
const error_msg = "MOVE command not yet implemented\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
.PathGet => {
const current_path = std.process.getEnvVarOwned(allocator, "PATH") catch |err| switch (err) {
error.EnvironmentVariableNotFound => {
// PATH not set, show empty
const output = "PATH=(not set)\n";
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
else => {
const error_msg = "Cannot access PATH environment variable\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
};
defer allocator.free(current_path);
const output = try std.fmt.allocPrint(allocator, "PATH={s}\n", .{current_path});
defer allocator.free(output);
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
.PathSet => |pathset| {
// Note: In a real DOS system, this would persist for the session
// Here we just show what would be set but don't actually set it
// since Zig's std.process doesn't provide a simple way to set env vars
const output = try std.fmt.allocPrint(allocator, "PATH would be set to: {s}\n(Note: Environment variable setting not implemented in this shell)\n", .{pathset.value});
defer allocator.free(output);
if (output_capture) |capture| {
try capture.write(output);
} else {
print("{s}", .{output});
}
return CommandStatus{ .Code = 0 };
},
else => {
const error_msg = try std.fmt.allocPrint(allocator, "Command not implemented: {any}\n", .{builtin_cmd});
defer allocator.free(error_msg);
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
}
},
.External => |external| {
// Try to execute external command
var child_args = ArrayList([]const u8).init(allocator);
defer child_args.deinit();
try child_args.append(external.program);
for (external.args.items) |arg| {
try child_args.append(arg);
}
var child = std.process.Child.init(child_args.items, allocator);
// Set up pipes for capturing output
child.stdin_behavior = if (input_source != null) .Pipe else .Inherit;
child.stdout_behavior = if (output_capture != null) .Pipe else .Inherit;
child.stderr_behavior = if (output_capture != null) .Pipe else .Inherit;
const spawn_result = child.spawn();
if (spawn_result) |_| {
// Spawn succeeded, continue with execution
} else |err| switch (err) {
error.FileNotFound => {
const error_msg = try std.fmt.allocPrint(allocator, "'{s}' is not recognized as an internal or external command,\noperable program or batch file.\n", .{external.program});
defer allocator.free(error_msg);
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
error.AccessDenied => {
const error_msg = "Access is denied.\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
else => {
const error_msg = try std.fmt.allocPrint(allocator, "Cannot execute '{s}': {}\n", .{ external.program, err });
defer allocator.free(error_msg);
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
}
// Handle input redirection
if (input_source) |source| {
if (child.stdin) |stdin| {
const writer = stdin.writer();
// Reset source position for reading
var temp_source = source.*;
temp_source.position = 0;
while (try temp_source.readLine(allocator)) |line| {
defer allocator.free(line);
try writer.print("{s}\n", .{line});
}
child.stdin.?.close();
child.stdin = null;
}
}
// Handle output capture
if (output_capture) |capture| {
// Read stdout
if (child.stdout) |stdout| {
var buffer: [4096]u8 = undefined;
while (true) {
const bytes_read = stdout.read(&buffer) catch break;
if (bytes_read == 0) break;
try capture.write(buffer[0..bytes_read]);
}
}
// Read stderr
if (child.stderr) |stderr| {
var buffer: [4096]u8 = undefined;
while (true) {
const bytes_read = stderr.read(&buffer) catch break;
if (bytes_read == 0) break;
try capture.write(buffer[0..bytes_read]);
}
}
}
// Wait for process to complete
const term = child.wait() catch |err| {
const error_msg = switch (err) {
error.FileNotFound => try std.fmt.allocPrint(allocator, "'{s}' is not recognized as an internal or external command,\noperable program or batch file.\n", .{external.program}),
else => try std.fmt.allocPrint(allocator, "Error waiting for command: {}\n", .{err}),
};
defer allocator.free(error_msg);
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
};
// Return exit code
switch (term) {
.Exited => |code| return CommandStatus{ .Code = @intCast(code) },
.Signal => |_| return CommandStatus{ .Code = 1 },
.Stopped => |_| return CommandStatus{ .Code = 1 },
.Unknown => |_| return CommandStatus{ .Code = 1 },
}
},
.Redirect => |redirect| {
// Check if we have any output redirections
var has_output_redirect = false;
for (redirect.redirects.items) |redir| {
if (redir.redirect_type == .OutputOverwrite or redir.redirect_type == .OutputAppend) {
has_output_redirect = true;
break;
}
}
var captured_output = OutputCapture.init(allocator);
defer captured_output.deinit();
// Prepare input redirection if needed
var input_data: ?[]const u8 = null;
var redirect_input_source: ?InputSource = null;
defer if (input_data) |data| allocator.free(data);
// Process input redirections first
for (redirect.redirects.items) |redir| {
if (redir.redirect_type == .InputFrom) {
const file_path = switch (redir.target) {
.Con => {
print("Input redirection from CON not supported\n", .{});
return CommandStatus{ .Code = 1 };
},
.Lpt1, .Lpt2, .Lpt3, .Prn => {
print("Cannot redirect input from device\n", .{});
return CommandStatus{ .Code = 1 };
},
.Path => |path| path,
};
// Read input file
const file = std.fs.cwd().openFile(file_path, .{}) catch |err| {
switch (err) {
error.FileNotFound => print("The system cannot find the file specified.\n", .{}),
error.AccessDenied => print("Access is denied.\n", .{}),
else => print("Cannot open input file.\n", .{}),
}
return CommandStatus{ .Code = 1 };
};
defer file.close();
input_data = file.readToEndAlloc(allocator, std.math.maxInt(usize)) catch |err| {
switch (err) {
error.AccessDenied => print("Access is denied.\n", .{}),
else => print("Cannot read input file.\n", .{}),
}
return CommandStatus{ .Code = 1 };
};
redirect_input_source = InputSource.init(input_data.?);
break; // Only handle first input redirection
}
}
// Execute the command with input and output capture (only capture output if needed)
const status = try executeCommandWithOutput(redirect.command.*, allocator, if (has_output_redirect) &captured_output else null, if (redirect_input_source) |*source| source else null);
// Handle output redirections
for (redirect.redirects.items) |redir| {
if (redir.redirect_type == .InputFrom) continue; // Already handled
const file_path = switch (redir.target) {
.Con => {
// Redirect to console - just print normally
print("{s}", .{captured_output.getContents()});
continue;
},
.Lpt1, .Lpt2, .Lpt3, .Prn => {
print("Cannot redirect to device\n", .{});
return CommandStatus{ .Code = 1 };
},
.Path => |path| path,
};
// Handle different redirect types
switch (redir.redirect_type) {
.OutputOverwrite => {
// Write to file, overwriting existing content
const file = std.fs.cwd().createFile(file_path, .{}) catch |err| {
switch (err) {
error.AccessDenied => print("Access is denied.\n", .{}),
else => print("Cannot create file.\n", .{}),
}
return CommandStatus{ .Code = 1 };
};
defer file.close();
file.writeAll(captured_output.getContents()) catch |err| {
switch (err) {
error.AccessDenied => print("Access is denied.\n", .{}),
else => print("Cannot write to file.\n", .{}),
}
return CommandStatus{ .Code = 1 };
};
},
.OutputAppend => {
// Append to file
const file = std.fs.cwd().openFile(file_path, .{ .mode = .write_only }) catch |err| {
switch (err) {
error.FileNotFound => {
// Create new file if it doesn't exist
const new_file = std.fs.cwd().createFile(file_path, .{}) catch |create_err| {
switch (create_err) {
error.AccessDenied => print("Access is denied.\n", .{}),
else => print("Cannot create file.\n", .{}),
}
return CommandStatus{ .Code = 1 };
};
defer new_file.close();
new_file.writeAll(captured_output.getContents()) catch {
print("Cannot write to file.\n", .{});
return CommandStatus{ .Code = 1 };
};
continue;
},
error.AccessDenied => {
print("Access is denied.\n", .{});
return CommandStatus{ .Code = 1 };
},
else => {
print("Cannot open file.\n", .{});
return CommandStatus{ .Code = 1 };
},
}
};
defer file.close();
// Seek to end for append
file.seekFromEnd(0) catch {
print("Cannot seek to end of file.\n", .{});
return CommandStatus{ .Code = 1 };
};
file.writeAll(captured_output.getContents()) catch |err| {
switch (err) {
error.AccessDenied => print("Access is denied.\n", .{}),
else => print("Cannot write to file.\n", .{}),
}
return CommandStatus{ .Code = 1 };
};
},
.InputFrom => {
// Input redirection already handled above
continue;
},
}
}
return status;
},
else => {
const error_msg = "Command type not implemented\n";
if (output_capture) |capture| {
try capture.write(error_msg);
} else {
print("{s}", .{error_msg});
}
return CommandStatus{ .Code = 1 };
},
}
}
fn isLeapYear(year: u32) bool {
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0);
}
const GetFreeDiskSpaceError = error{ NotImplemented, AccessDenied };
fn getFreeDiskSpace(path: []const u8) GetFreeDiskSpaceError!u64 {
if (@import("builtin").os.tag == .windows) {
return error.NotImplemented;
}
var stat: c.struct_statvfs = undefined;
if (c.statvfs(path.ptr, &stat) != 0) {
_ = c.perror("statvfs");
return error.AccessDenied;
}
return stat.f_bsize * stat.f_bfree;
}
|