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
|
const std = @import("std");
const parser = @import("parser.zig");
const shell = @import("shell.zig");
const builtins = @import("builtins.zig");
const BUILTINS = [_][]const u8{ "echo", "exit" };
fn longestCommonPrefix(strings: []const []const u8) []const u8 {
if (strings.len == 0) return "";
var min_len: usize = strings[0].len;
for (strings[1..]) |s| {
if (s.len < min_len) min_len = s.len;
}
var i: usize = 0;
while (i < min_len) : (i += 1) {
const c = strings[0][i];
for (strings[1..]) |s| {
if (s[i] != c) return strings[0][0..i];
}
}
return strings[0][0..min_len];
}
fn findAllMatches(allocator: std.mem.Allocator, partial: []const u8) !std.ArrayList([]const u8) {
var matches = std.ArrayList([]const u8){};
for (BUILTINS) |builtin| {
if (std.mem.startsWith(u8, builtin, partial)) {
const duped = try allocator.dupe(u8, builtin);
try matches.append(allocator, duped);
}
}
const path_env = std.posix.getenv("PATH") orelse return matches;
var path_iter = std.mem.splitScalar(u8, path_env, ':');
while (path_iter.next()) |dir_path| {
if (dir_path.len == 0) continue;
var dir = std.fs.openDirAbsolute(dir_path, .{ .iterate = true }) catch continue;
defer dir.close();
var iter = dir.iterate();
while (iter.next() catch continue) |entry| {
if (entry.kind == .file or entry.kind == .sym_link) {
if (std.mem.startsWith(u8, entry.name, partial)) {
const stat = dir.statFile(entry.name) catch continue;
if (stat.mode & 0o111 != 0) {
var already_exists = false;
for (matches.items) |existing| {
if (std.mem.eql(u8, existing, entry.name)) {
already_exists = true;
break;
}
}
if (!already_exists) {
const duped = allocator.dupe(u8, entry.name) catch continue;
matches.append(allocator, duped) catch {
allocator.free(duped);
continue;
};
}
}
}
}
}
}
return matches;
}
fn tryComplete(allocator: std.mem.Allocator, partial: []const u8) ?[]const u8 {
var matches: usize = 0;
var match: ?[]const u8 = null;
var match_is_builtin = false;
for (BUILTINS) |builtin| {
if (std.mem.startsWith(u8, builtin, partial)) {
matches += 1;
if (matches == 1) {
match = builtin;
match_is_builtin = true;
}
if (matches > 1) {
if (match != null and !match_is_builtin) {
allocator.free(match.?);
}
return null;
}
}
}
const path_env = std.posix.getenv("PATH") orelse {
if (matches == 1 and match != null) {
return allocator.dupe(u8, match.?) catch null;
}
return null;
};
var path_iter = std.mem.splitScalar(u8, path_env, ':');
while (path_iter.next()) |dir_path| {
if (dir_path.len == 0) continue;
var dir = std.fs.openDirAbsolute(dir_path, .{ .iterate = true }) catch continue;
defer dir.close();
var iter = dir.iterate();
while (iter.next() catch continue) |entry| {
if (entry.kind == .file or entry.kind == .sym_link) {
if (std.mem.startsWith(u8, entry.name, partial)) {
const stat = dir.statFile(entry.name) catch continue;
if (stat.mode & 0o111 != 0) {
if (match != null and match_is_builtin and std.mem.eql(u8, match.?, entry.name)) {
continue;
}
matches += 1;
if (matches == 1) {
match = allocator.dupe(u8, entry.name) catch continue;
match_is_builtin = false;
} else {
if (match != null and !match_is_builtin) {
allocator.free(match.?);
}
return null;
}
}
}
}
}
}
if (matches == 1 and match != null) {
if (match_is_builtin) {
return allocator.dupe(u8, match.?) catch null;
} else {
return match.?;
}
}
return null;
}
fn enableRawMode(fd: std.posix.fd_t) !std.posix.termios {
const original = try std.posix.tcgetattr(fd);
var raw = original;
raw.lflag.ICANON = false;
raw.lflag.ECHO = false;
raw.cc[@intFromEnum(std.posix.V.MIN)] = 1;
raw.cc[@intFromEnum(std.posix.V.TIME)] = 0;
try std.posix.tcsetattr(fd, .FLUSH, raw);
return original;
}
fn disableRawMode(fd: std.posix.fd_t, original: std.posix.termios) !void {
try std.posix.tcsetattr(fd, .FLUSH, original);
}
fn readCommand(allocator: std.mem.Allocator, history: std.ArrayList([]const u8)) !?[]const u8 {
const stdin = std.fs.File.stdin();
const stdout = std.fs.File.stdout();
const stdin_fd = stdin.handle;
const is_tty = std.posix.isatty(stdin_fd);
const original_termios = if (is_tty) try enableRawMode(stdin_fd) else null;
defer if (original_termios) |orig| disableRawMode(stdin_fd, orig) catch {};
var buffer = std.ArrayList(u8){};
defer buffer.deinit(allocator);
var byte: [1]u8 = undefined;
var last_tab_partial: ?[]const u8 = null;
var last_was_tab = false;
var history_index: ?usize = null; // Track which history entry is displayed
while (true) {
const bytes_read = try stdin.read(&byte);
if (bytes_read == 0) return null;
const c = byte[0];
if (c == '\n' or c == '\r') {
if (last_tab_partial) |p| allocator.free(p);
return try buffer.toOwnedSlice(allocator);
} else if (c == 27 and is_tty) {
var seq: [2]u8 = undefined;
var seq_len: usize = 0;
if (try stdin.read(seq[0..1]) > 0) {
seq_len = 1;
if (seq[0] == '[') {
if (try stdin.read(seq[1..2]) > 0) {
seq_len = 2;
if (seq[1] == 'A') {
const new_index = if (history_index) |idx|
if (idx > 0) idx - 1 else idx
else if (history.items.len > 0)
history.items.len - 1
else
null;
if (new_index) |idx| {
history_index = idx;
while (buffer.items.len > 0) {
_ = buffer.pop();
try stdout.writeAll("\x08 \x08");
}
const cmd = history.items[idx];
try buffer.appendSlice(allocator, cmd);
try stdout.writeAll(cmd);
last_tab_partial = null;
last_was_tab = false;
}
} else if (seq[1] == 'B') {
if (history_index) |idx| {
if (idx + 1 < history.items.len) {
history_index = idx + 1;
while (buffer.items.len > 0) {
_ = buffer.pop();
try stdout.writeAll("\x08 \x08");
}
const cmd = history.items[idx + 1];
try buffer.appendSlice(allocator, cmd);
try stdout.writeAll(cmd);
} else {
while (buffer.items.len > 0) {
_ = buffer.pop();
try stdout.writeAll("\x08 \x08");
}
history_index = null;
}
last_tab_partial = null;
last_was_tab = false;
}
}
}
}
}
} else if (c == '\t' and is_tty) {
const partial = buffer.items;
if (partial.len > 0 and std.mem.indexOf(u8, partial, " ") == null) {
var matches = try findAllMatches(allocator, partial);
defer {
for (matches.items) |m| allocator.free(m);
matches.deinit(allocator);
}
const is_double_tab = last_was_tab and last_tab_partial != null and std.mem.eql(u8, last_tab_partial.?, partial);
if (matches.items.len == 0) {
try stdout.writeAll("\x07");
last_was_tab = true;
if (last_tab_partial) |p| allocator.free(p);
last_tab_partial = try allocator.dupe(u8, partial);
} else if (matches.items.len == 1) {
const completion = matches.items[0];
if (completion.len > partial.len) {
const remaining = completion[partial.len..];
try stdout.writeAll(remaining);
try buffer.appendSlice(allocator, remaining);
}
try stdout.writeAll(" ");
try buffer.append(allocator, ' ');
last_was_tab = false;
if (last_tab_partial) |p| allocator.free(p);
last_tab_partial = null;
} else {
const lcp = longestCommonPrefix(matches.items);
if (lcp.len > partial.len) {
const remaining = lcp[partial.len..];
try stdout.writeAll(remaining);
try buffer.appendSlice(allocator, remaining);
last_was_tab = false;
if (last_tab_partial) |p| allocator.free(p);
last_tab_partial = null;
} else if (is_double_tab) {
std.mem.sort([]const u8, matches.items, {}, struct {
fn lessThan(_: void, a: []const u8, b: []const u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
}.lessThan);
try stdout.writeAll("\n");
for (matches.items, 0..) |match, i| {
try stdout.writeAll(match);
if (i < matches.items.len - 1) {
try stdout.writeAll(" ");
}
}
try stdout.writeAll("\n$ ");
try stdout.writeAll(partial);
last_was_tab = false;
if (last_tab_partial) |p| {
allocator.free(p);
last_tab_partial = null;
}
} else {
try stdout.writeAll("\x07");
last_was_tab = true;
if (last_tab_partial) |p| allocator.free(p);
last_tab_partial = try allocator.dupe(u8, partial);
}
}
} else if (partial.len > 0) {
const space_idx = std.mem.lastIndexOf(u8, partial, " ").?;
const prefix = partial[space_idx + 1..];
var matches = std.ArrayList([]const u8){};
defer {
for (matches.items) |m| allocator.free(m);
matches.deinit(allocator);
}
if (std.fs.cwd().openDir(".", .{ .iterate = true })) |opened_dir| {
var dir = opened_dir;
defer dir.close();
var iter = dir.iterate();
while (iter.next() catch null) |entry| {
if (std.mem.startsWith(u8, entry.name, prefix)) {
if (allocator.dupe(u8, entry.name)) |duped| {
matches.append(allocator, duped) catch {
allocator.free(duped);
};
} else |_| {}
}
}
} else |_| {}
if (matches.items.len == 0) {
try stdout.writeAll("\x07");
} else if (matches.items.len == 1) {
const completion = matches.items[0];
if (completion.len > prefix.len) {
const remaining = completion[prefix.len..];
try stdout.writeAll(remaining);
try buffer.appendSlice(allocator, remaining);
}
try stdout.writeAll(" ");
try buffer.append(allocator, ' ');
last_was_tab = false;
if (last_tab_partial) |p| allocator.free(p);
last_tab_partial = null;
} else {
try stdout.writeAll("\x07");
}
}
} else if ((c == 127 or c == 8) and is_tty) {
if (buffer.items.len > 0) {
_ = buffer.pop();
try stdout.writeAll("\x08 \x08");
}
last_was_tab = false;
if (last_tab_partial) |p| {
allocator.free(p);
last_tab_partial = null;
}
} else if (c >= 32 and c < 127) {
try buffer.append(allocator, c);
if (is_tty) {
try stdout.writeAll(&[_]u8{c});
}
last_was_tab = false;
if (last_tab_partial) |p| {
allocator.free(p);
last_tab_partial = null;
}
} else if (c == '\t' and !is_tty) {
try buffer.append(allocator, c);
}
}
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var history = std.ArrayList([]const u8){};
defer {
for (history.items) |cmd| allocator.free(cmd);
history.deinit(allocator);
}
var last_written_index: usize = 0;
if (std.posix.getenv("HISTFILE")) |histfile_path| {
const file = std.fs.cwd().openFile(histfile_path, .{}) catch null;
if (file) |f| {
defer f.close();
const file_size = f.getEndPos() catch 0;
if (file_size > 0) {
const buffer = allocator.alloc(u8, file_size) catch null;
if (buffer) |buf| {
defer allocator.free(buf);
const bytes_read = f.readAll(buf) catch 0;
if (bytes_read > 0) {
var line_iter = std.mem.splitScalar(u8, buf[0..bytes_read], '\n');
while (line_iter.next()) |line| {
const trimmed = std.mem.trim(u8, line, " \r");
if (trimmed.len > 0) {
const line_copy = allocator.dupe(u8, trimmed) catch continue;
history.append(allocator, line_copy) catch {
allocator.free(line_copy);
continue;
};
}
}
}
}
}
}
}
const stdout = std.fs.File.stdout();
while (true) {
try stdout.writeAll("$ ");
const command = try readCommand(allocator, history);
if (command) |cmd| {
defer allocator.free(cmd);
try stdout.writeAll("\n");
var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
const stdout_iface = &stdout_writer.interface;
const cmd_copy = try allocator.dupe(u8, cmd);
try history.append(allocator, cmd_copy);
if (std.mem.indexOfScalar(u8, cmd, '|')) |_| {
var segments = std.ArrayList([]const u8){};
defer segments.deinit(allocator);
var invalid = false;
var start: usize = 0;
for (cmd, 0..) |ch, i| {
if (ch == '|') {
const seg = std.mem.trim(u8, cmd[start..i], " ");
if (seg.len == 0) {
try stdout.writeAll("pipe: command not found\n");
invalid = true;
break;
}
try segments.append(allocator, seg);
start = i + 1;
}
}
if (invalid) continue;
const last_seg = std.mem.trim(u8, cmd[start..], " ");
if (last_seg.len == 0) {
try stdout.writeAll("pipe: command not found\n");
continue;
}
try segments.append(allocator, last_seg);
if (segments.items.len == 1) {
const parsed = parser.parseCommand(cmd);
const result = try shell.executeCommand(allocator, stdout_iface, parsed.name, parsed.args, parsed.output_redirect, parsed.error_redirect, parsed.append_output, parsed.append_error, &history, &last_written_index);
if (result == .exit_shell) break;
} else {
const result = try shell.executePipeline(allocator, stdout_iface, segments.items);
if (result == .exit_shell) break;
}
} else {
const parsed = parser.parseCommand(cmd);
const result = try shell.executeCommand(allocator, stdout_iface, parsed.name, parsed.args, parsed.output_redirect, parsed.error_redirect, parsed.append_output, parsed.append_error, &history, &last_written_index);
if (result == .exit_shell) break;
}
} else {
break;
}
}
if (std.posix.getenv("HISTFILE")) |histfile_path| {
const file = std.fs.cwd().createFile(histfile_path, .{}) catch null;
if (file) |f| {
defer f.close();
for (history.items) |cmd| {
_ = f.writeAll(cmd) catch {};
_ = f.writeAll("\n") catch {};
}
}
}
}
|