summaryrefslogtreecommitdiff
path: root/src/cmd/external.zig
blob: 0f4e65fc2999a4fdf0e5f493dce5eb6cda3a75b9 (plain)
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
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;

const types = @import("./lib/types.zig");
const CommandStatus = types.CommandStatus;
const CommandContext = types.CommandContext;
const OutputCapture = types.OutputCapture;
const InputSource = types.InputSource;

pub const External = struct {
    program: []const u8,
    args: ArrayList([]const u8),

    pub fn eval(external: External, ctx: CommandContext) !CommandStatus {
        const allocator = ctx.allocator;
        const input_source = ctx.input_source;

        // Check if we need to capture output (not going to stdout)
        const needs_capture = switch (ctx.output_writer) {
            .stdout => false,
            .capture => true,
        };
        // 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 (needs_capture) .Pipe else .Inherit;
        child.stderr_behavior = if (needs_capture) .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);

                var writer = ctx.output_writer;
                try writer.write(error_msg);
                return CommandStatus{ .Code = 1 };
            },
            error.AccessDenied => {
                const error_msg = "Access is denied.\n";
                var writer = ctx.output_writer;
                try writer.write(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);

                var writer = ctx.output_writer;
                try writer.write(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 (needs_capture) {
            var writer = ctx.output_writer;
            // 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 writer.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 writer.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);

            var writer = ctx.output_writer;
            try writer.write(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 },
        }
    }
};