aboutsummaryrefslogtreecommitdiff
path: root/src/install/bin.zig
blob: d40c43a0404cc1601d7b08ed818765809a6dc9e3 (plain) (blame)
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
const ExternalStringList = @import("./install.zig").ExternalStringList;
const Semver = @import("./semver.zig");
const ExternalString = Semver.ExternalString;
const String = Semver.String;
const std = @import("std");
const strings = @import("strings");
const Environment = @import("../env.zig");
const Path = @import("../resolver/resolve_path.zig");
const C = @import("../c.zig");
/// Normalized `bin` field in [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json#bin)
/// Can be a:
/// - file path (relative to the package root)
/// - directory (relative to the package root)
/// - map where keys are names of the binaries and values are file paths to the binaries
pub const Bin = extern struct {
    tag: Tag = Tag.none,
    value: Value = Value{ .none = .{} },

    pub fn count(this: Bin, buf: []const u8, comptime StringBuilder: type, builder: StringBuilder) void {
        switch (this.tag) {
            .file => builder.count(this.value.file.slice(buf)),
            .named_file => {
                builder.count(this.value.named_file[0].slice(buf));
                builder.count(this.value.named_file[1].slice(buf));
            },
            .dir => builder.count(this.value.dir.slice(buf)),
            .map => @panic("Bin.map not implemented yet!!. That means \"bin\" as multiple specific files won't work just yet"),
            else => {},
        }
    }

    pub fn clone(this: Bin, buf: []const u8, comptime StringBuilder: type, builder: StringBuilder) Bin {
        return switch (this.tag) {
            .none => Bin{ .tag = .none, .value = .{ .none = .{} } },
            .file => Bin{
                .tag = .file,
                .value = .{ .file = builder.append(String, this.value.file.slice(buf)) },
            },
            .named_file => Bin{
                .tag = .named_file,
                .value = .{
                    .named_file = [2]String{
                        builder.append(String, this.value.named_file[0].slice(buf)),
                        builder.append(String, this.value.named_file[1].slice(buf)),
                    },
                },
            },
            .dir => Bin{
                .tag = .dir,
                .value = .{ .dir = builder.append(String, this.value.dir.slice(buf)) },
            },
            .map => @panic("Bin.map not implemented yet!!. That means \"bin\" as multiple specific files won't work just yet"),
        };
    }

    pub const Value = extern union {
        /// no "bin", or empty "bin"
        none: void,

        /// "bin" is a string
        /// ```
        /// "bin": "./bin/foo",
        /// ```
        file: String,

        // Single-entry map
        ///```
        /// "bin": {
        ///     "babel": "./cli.js",
        /// }
        ///```
        named_file: [2]String,

        /// "bin" is a directory
        ///```
        /// "dirs": {
        ///     "bin": "./bin",
        /// }
        ///```
        dir: String,
        // "bin" is a map
        ///```
        /// "bin": {
        ///     "babel": "./cli.js",
        ///     "babel-cli": "./cli.js",
        /// }
        ///```
        map: ExternalStringList,
    };

    pub const Tag = enum(u8) {
        /// no bin field
        none = 0,
        /// "bin" is a string
        /// ```
        /// "bin": "./bin/foo",
        /// ```
        file = 1,

        // Single-entry map
        ///```
        /// "bin": {
        ///     "babel": "./cli.js",
        /// }
        ///```
        named_file = 2,
        /// "bin" is a directory
        ///```
        /// "dirs": {
        ///     "bin": "./bin",
        /// }
        ///```
        dir = 3,
        // "bin" is a map
        ///```
        /// "bin": {
        ///     "babel": "./cli.js",
        ///     "babel-cli": "./cli.js",
        /// }
        ///```
        map = 4,
    };

    pub const Linker = struct {
        bin: Bin,

        package_installed_node_modules: std.os.fd_t = std.math.maxInt(std.os.fd_t),
        root_node_modules_folder: std.os.fd_t = std.math.maxInt(std.os.fd_t),

        /// Used for generating relative paths
        package_name: strings.StringOrTinyString,

        string_buf: []const u8,

        err: ?anyerror = null,

        pub var umask: std.os.mode_t = 0;

        pub const Error = error{
            NotImplementedYet,
        } || std.os.SymLinkError || std.os.OpenError || std.os.RealPathError;

        // It is important that we use symlinkat(2) with relative paths instead of symlink()
        // That way, if you move your node_modules folder around, the symlinks in .bin still work
        // If we used absolute paths for the symlinks, you'd end up with broken symlinks
        pub fn link(this: *Linker) void {
            var from_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
            var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;

            from_buf[0..".bin/".len].* = ".bin/".*;
            var from_remain: []u8 = from_buf[".bin/".len..];
            path_buf[0.."../".len].* = "../".*;

            var remain: []u8 = path_buf["../".len..];
            const name = this.package_name.slice();
            std.mem.copy(u8, remain, name);
            remain = remain[name.len..];
            remain[0] = std.fs.path.sep;
            remain = remain[1..];

            if (comptime Environment.isWindows) {
                @compileError("Bin.Linker.link() needs to be updated to generate .cmd files on Windows");
            }

            switch (this.bin.tag) {
                .none => {
                    if (comptime Environment.isDebug) {
                        unreachable;
                    }
                },
                .file => {
                    var target = this.bin.value.file.slice(this.string_buf);
                    if (strings.hasPrefix(target, "./")) {
                        target = target[2..];
                    }
                    std.mem.copy(u8, remain, target);
                    remain = remain[target.len..];
                    remain[0] = 0;
                    const target_len = @ptrToInt(remain.ptr) - @ptrToInt(&path_buf);
                    remain = remain[1..];

                    var target_path: [:0]u8 = path_buf[0..target_len :0];
                    std.mem.copy(u8, from_remain, name);
                    from_remain = from_remain[name.len..];
                    from_remain[0] = 0;
                    var dest_path: [:0]u8 = from_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&from_buf) :0];

                    _ = C.chmod(target_path, umask & 0o777);
                    std.os.symlinkatZ(target_path, this.root_node_modules_folder, dest_path) catch |err| {
                        // Silently ignore PathAlreadyExists
                        // Most likely, the symlink was already created by another package
                        if (err == error.PathAlreadyExists) return;

                        this.err = err;
                    };
                },
                .named_file => {
                    var target = this.bin.value.named_file[1].slice(this.string_buf);
                    if (strings.hasPrefix(target, "./")) {
                        target = target[2..];
                    }
                    std.mem.copy(u8, remain, target);
                    remain = remain[target.len..];
                    remain[0] = 0;
                    const target_len = @ptrToInt(remain.ptr) - @ptrToInt(&path_buf);
                    remain = remain[1..];

                    var target_path: [:0]u8 = path_buf[0..target_len :0];
                    var name_to_use = this.bin.value.named_file[0].slice(this.string_buf);
                    std.mem.copy(u8, from_remain, name_to_use);
                    from_remain = from_remain[name_to_use.len..];
                    from_remain[0] = 0;
                    var dest_path: [:0]u8 = from_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&from_buf) :0];

                    _ = C.chmod(target_path, umask & 0o777);
                    std.os.symlinkatZ(target_path, this.root_node_modules_folder, dest_path) catch |err| {
                        // Silently ignore PathAlreadyExists
                        // Most likely, the symlink was already created by another package
                        if (err == error.PathAlreadyExists) return;

                        this.err = err;
                    };
                },
                .dir => {
                    var target = this.bin.value.dir.slice(this.string_buf);
                    var parts = [_][]const u8{ name, target };
                    if (strings.hasPrefix(target, "./")) {
                        target = target[2..];
                    }
                    std.mem.copy(u8, remain, target);
                    remain = remain[target.len..];
                    remain[0] = 0;
                    var dir = std.fs.Dir{ .fd = this.package_installed_node_modules };

                    var joined = Path.joinStringBuf(&from_buf, &parts, .auto);
                    from_buf[joined.len] = 0;
                    var joined_: [:0]u8 = from_buf[0..joined.len :0];
                    var child_dir = dir.openDirZ(joined_, .{ .iterate = true }) catch |err| {
                        this.err = err;
                        return;
                    };
                    defer child_dir.close();

                    var iter = child_dir.iterate();

                    var basedir_path = std.os.getFdPath(child_dir.fd, &from_buf) catch |err| {
                        this.err = err;
                        return;
                    };
                    from_buf[basedir_path.len] = std.fs.path.sep;
                    var from_buf_remain = from_buf[basedir_path.len + 1 ..];

                    while (iter.next() catch null) |entry_| {
                        const entry: std.fs.Dir.Entry = entry_;
                        switch (entry.kind) {
                            std.fs.Dir.Entry.Kind.SymLink, std.fs.Dir.Entry.Kind.File => {
                                std.mem.copy(u8, from_buf_remain, entry.name);
                                from_buf_remain = from_buf_remain[entry.name.len..];
                                from_buf_remain[0] = 0;
                                var from_path: [:0]u8 = from_buf[0 .. @ptrToInt(from_buf_remain.ptr) - @ptrToInt(&from_buf) :0];
                                var to_path = std.fmt.bufPrintZ(&path_buf, ".bin/{s}", .{entry.name}) catch unreachable;
                                _ = C.chmod(from_path, umask & 0o777);
                                std.os.symlinkatZ(
                                    from_path,
                                    this.root_node_modules_folder,
                                    to_path,
                                ) catch |err| {
                                    // Silently ignore PathAlreadyExists
                                    // Most likely, the symlink was already created by another package
                                    if (err == error.PathAlreadyExists) return;

                                    this.err = err;
                                    return;
                                };
                            },
                            else => {},
                        }
                    }
                },
                .map => {
                    this.err = error.NotImplementedYet;
                },
            }
        }
    };
};