summaryrefslogtreecommitdiff
path: root/src/cmd/rename.zig
blob: 58a57027c50df0d243a132d42c5dbb89f34f4fbc (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
const std = @import("std");
const Allocator = std.mem.Allocator;

const syntax = @import("../syntax.zig");
const FileSpec = syntax.FileSpec;

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

pub const Rename = struct {
    from: FileSpec,
    to: FileSpec,

    pub fn eval(rename: Rename, ctx: CommandContext) !CommandStatus {
        const from_path = switch (rename.from) {
            .Con, .Lpt1, .Lpt2, .Lpt3, .Prn => {
                const error_msg = "Cannot rename device\n";
                var writer = ctx.output_writer;
                try writer.write(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";
                var writer = ctx.output_writer;
                try writer.write(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",
            };
            var writer = ctx.output_writer;
            try writer.write(error_msg);
            return CommandStatus{ .Code = 1 };
        };

        // No output for successful rename (DOS style)
        return CommandStatus{ .Code = 0 };
    }
};