-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathzigup.zig
1285 lines (1167 loc) · 50.6 KB
/
zigup.zig
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
994
995
996
997
998
999
1000
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const ArrayList = std.ArrayList;
const Allocator = mem.Allocator;
const fixdeletetree = @import("fixdeletetree.zig");
const arch = switch (builtin.cpu.arch) {
.aarch64 => "aarch64",
.arm => "armv7a",
.powerpc64le => "powerpc64le",
.riscv64 => "riscv64",
.x86 => "x86",
.x86_64 => "x86_64",
else => @compileError("Unsupported CPU Architecture"),
};
const os = switch (builtin.os.tag) {
.linux => "linux",
.macos => "macos",
.windows => "windows",
else => @compileError("Unsupported OS"),
};
const url_platform = os ++ "-" ++ arch;
const json_platform = arch ++ "-" ++ os;
const archive_ext = if (builtin.os.tag == .windows) "zip" else "tar.xz";
var global_override_appdata: ?[]const u8 = null; // only used for testing
var global_optional_install_dir: ?[]const u8 = null;
var global_optional_path_link: ?[]const u8 = null;
var global_enable_log = true;
fn loginfo(comptime fmt: []const u8, args: anytype) void {
if (global_enable_log) {
std.debug.print(fmt ++ "\n", args);
}
}
pub fn oom(e: error{OutOfMemory}) noreturn {
@panic(@errorName(e));
}
const DownloadResult = union(enum) {
ok: void,
err: []u8,
pub fn deinit(self: DownloadResult, allocator: Allocator) void {
switch (self) {
.ok => {},
.err => |e| allocator.free(e),
}
}
};
fn download(allocator: Allocator, url: []const u8, writer: anytype) DownloadResult {
const uri = std.Uri.parse(url) catch |err| return .{ .err = std.fmt.allocPrint(
allocator,
"the URL is invalid ({s})",
.{@errorName(err)},
) catch |e| oom(e) };
var client = std.http.Client{ .allocator = allocator };
defer client.deinit();
client.initDefaultProxies(allocator) catch |err| return .{ .err = std.fmt.allocPrint(
allocator,
"failed to query the HTTP proxy settings with {s}",
.{@errorName(err)},
) catch |e| oom(e) };
var header_buffer: [4096]u8 = undefined;
var request = client.open(.GET, uri, .{
.server_header_buffer = &header_buffer,
.keep_alive = false,
}) catch |err| return .{ .err = std.fmt.allocPrint(
allocator,
"failed to connect to the HTTP server with {s}",
.{@errorName(err)},
) catch |e| oom(e) };
defer request.deinit();
request.send() catch |err| return .{ .err = std.fmt.allocPrint(
allocator,
"failed to send the HTTP request with {s}",
.{@errorName(err)},
) catch |e| oom(e) };
request.wait() catch |err| return .{ .err = std.fmt.allocPrint(
allocator,
"failed to read the HTTP response headers with {s}",
.{@errorName(err)},
) catch |e| oom(e) };
if (request.response.status != .ok) return .{ .err = std.fmt.allocPrint(
allocator,
"the HTTP server replied with unsuccessful response '{d} {s}'",
.{ @intFromEnum(request.response.status), request.response.status.phrase() orelse "" },
) catch |e| oom(e) };
// TODO: we take advantage of request.response.content_length
var buf: [4096]u8 = undefined;
while (true) {
const len = request.reader().read(&buf) catch |err| return .{ .err = std.fmt.allocPrint(
allocator,
"failed to read the HTTP response body with {s}'",
.{@errorName(err)},
) catch |e| oom(e) };
if (len == 0)
return .ok;
writer.writeAll(buf[0..len]) catch |err| return .{ .err = std.fmt.allocPrint(
allocator,
"failed to write the HTTP response body with {s}'",
.{@errorName(err)},
) catch |e| oom(e) };
}
}
const DownloadStringResult = union(enum) {
ok: []u8,
err: []u8,
};
fn downloadToString(allocator: Allocator, url: []const u8) DownloadStringResult {
var response_array_list = ArrayList(u8).initCapacity(allocator, 50 * 1024) catch |e| oom(e); // 50 KB (modify if response is expected to be bigger)
defer response_array_list.deinit();
switch (download(allocator, url, response_array_list.writer())) {
.ok => return .{ .ok = response_array_list.toOwnedSlice() catch |e| oom(e) },
.err => |e| return .{ .err = e },
}
}
fn ignoreHttpCallback(request: []const u8) void {
_ = request;
}
fn allocInstallDirStringXdg(allocator: Allocator) error{AlreadyReported}![]const u8 {
// see https://specifications.freedesktop.org/basedir-spec/latest/#variables
// try $XDG_DATA_HOME/zigup first
xdg_var: {
const xdg_data_home = std.posix.getenv("XDG_DATA_HOME") orelse break :xdg_var;
if (xdg_data_home.len == 0) break :xdg_var;
if (!std.fs.path.isAbsolute(xdg_data_home)) {
std.log.err("$XDG_DATA_HOME environment variable '{s}' is not an absolute path", .{xdg_data_home});
return error.AlreadyReported;
}
return std.fs.path.join(allocator, &[_][]const u8{ xdg_data_home, "zigup" }) catch |e| oom(e);
}
// .. then fallback to $HOME/.local/share/zigup
const home = std.posix.getenv("HOME") orelse {
std.log.err("cannot find install directory, neither $HOME nor $XDG_DATA_HOME environment variables are set", .{});
return error.AlreadyReported;
};
if (!std.fs.path.isAbsolute(home)) {
std.log.err("$HOME environment variable '{s}' is not an absolute path", .{home});
return error.AlreadyReported;
}
return std.fs.path.join(allocator, &[_][]const u8{ home, ".local", "share", "zigup" }) catch |e| oom(e);
}
fn getSettingsDir(allocator: Allocator) ?[]const u8 {
const appdata: ?[]const u8 = std.fs.getAppDataDir(allocator, "zigup") catch |err| switch (err) {
error.OutOfMemory => |e| oom(e),
error.AppDataDirUnavailable => null,
};
// just used for testing, but note we still test getting the builtin appdata dir either way
if (global_override_appdata) |appdata_override| {
if (appdata) |a| allocator.free(a);
return allocator.dupe(u8, appdata_override) catch |e| oom(e);
}
return appdata;
}
fn readInstallDir(allocator: Allocator) !?[]const u8 {
const settings_dir_path = getSettingsDir(allocator) orelse return null;
defer allocator.free(settings_dir_path);
const setting_path = std.fs.path.join(allocator, &.{ settings_dir_path, "install-dir" }) catch |e| oom(e);
defer allocator.free(setting_path);
const content = blk: {
var file = std.fs.cwd().openFile(setting_path, .{}) catch |err| switch (err) {
error.FileNotFound => return null,
else => |e| {
std.log.err("open '{s}' failed with {s}", .{ setting_path, @errorName(e) });
return error.AlreadyReported;
},
};
defer file.close();
break :blk file.readToEndAlloc(allocator, 9999) catch |err| {
std.log.err("read install dir from '{s}' failed with {s}", .{ setting_path, @errorName(err) });
return error.AlreadyReported;
};
};
errdefer allocator.free(content);
const stripped = std.mem.trimRight(u8, content, " \r\n");
if (!std.fs.path.isAbsolute(stripped)) {
std.log.err("install directory '{s}' is not an absolute path, fix this by running `zigup set-install-dir`", .{stripped});
return error.BadInstallDirSetting;
}
return allocator.realloc(content, stripped.len) catch |e| oom(e);
}
fn saveInstallDir(allocator: Allocator, maybe_dir: ?[]const u8) !void {
const settings_dir_path = getSettingsDir(allocator) orelse {
std.log.err("cannot save install dir, unable to find a suitable settings directory", .{});
return error.AlreadyReported;
};
defer allocator.free(settings_dir_path);
const setting_path = std.fs.path.join(allocator, &.{ settings_dir_path, "install-dir" }) catch |e| oom(e);
defer allocator.free(setting_path);
if (maybe_dir) |d| {
if (std.fs.path.dirname(setting_path)) |dir| try std.fs.cwd().makePath(dir);
{
const file = try std.fs.cwd().createFile(setting_path, .{});
defer file.close();
try file.writer().writeAll(d);
}
// sanity check, read it back
const readback = (try readInstallDir(allocator)) orelse {
std.log.err("unable to readback install-dir after saving it", .{});
return error.AlreadyReported;
};
defer allocator.free(readback);
if (!std.mem.eql(u8, readback, d)) {
std.log.err("saved install dir readback mismatch\nwrote: '{s}'\nread : '{s}'\n", .{ d, readback });
return error.AlreadyReported;
}
} else {
std.fs.cwd().deleteFile(setting_path) catch |err| switch (err) {
error.FileNotFound => {},
else => |e| return e,
};
}
}
fn getBuiltinInstallDir(allocator: Allocator) error{AlreadyReported}![]const u8 {
if (builtin.os.tag == .windows) {
const self_exe_dir = std.fs.selfExeDirPathAlloc(allocator) catch |e| {
std.log.err("failed to get exe dir path with {s}", .{@errorName(e)});
return error.AlreadyReported;
};
defer allocator.free(self_exe_dir);
return std.fs.path.join(allocator, &.{ self_exe_dir, "zig" }) catch |e| oom(e);
}
return allocInstallDirStringXdg(allocator);
}
fn allocInstallDirString(allocator: Allocator) error{ AlreadyReported, BadInstallDirSetting }![]const u8 {
if (try readInstallDir(allocator)) |d| return d;
return try getBuiltinInstallDir(allocator);
}
const GetInstallDirOptions = struct {
create: bool,
log: bool = true,
};
fn getInstallDir(allocator: Allocator, options: GetInstallDirOptions) ![]const u8 {
var optional_dir_to_free_on_error: ?[]const u8 = null;
errdefer if (optional_dir_to_free_on_error) |dir| allocator.free(dir);
const install_dir = init: {
if (global_optional_install_dir) |dir| break :init dir;
optional_dir_to_free_on_error = try allocInstallDirString(allocator);
break :init optional_dir_to_free_on_error.?;
};
std.debug.assert(std.fs.path.isAbsolute(install_dir));
if (options.log) {
loginfo("install directory '{s}'", .{install_dir});
}
if (options.create) {
loggyMakePath(install_dir) catch |e| switch (e) {
error.PathAlreadyExists => {},
else => return e,
};
}
return install_dir;
}
fn makeZigPathLinkString(allocator: Allocator) ![]const u8 {
if (global_optional_path_link) |path| return path;
const zigup_dir = try std.fs.selfExeDirPathAlloc(allocator);
defer allocator.free(zigup_dir);
return try std.fs.path.join(allocator, &[_][]const u8{ zigup_dir, comptime "zig" ++ builtin.target.exeFileExt() });
}
// TODO: this should be in standard lib
fn toAbsolute(allocator: Allocator, path: []const u8) ![]u8 {
std.debug.assert(!std.fs.path.isAbsolute(path));
const cwd = try std.process.getCwdAlloc(allocator);
defer allocator.free(cwd);
return std.fs.path.join(allocator, &[_][]const u8{ cwd, path });
}
fn help(allocator: Allocator) !void {
const builtin_install_dir = getBuiltinInstallDir(allocator) catch |err| switch (err) {
error.AlreadyReported => "unknown (see error printed above)",
};
const current_install_dir = allocInstallDirString(allocator) catch |err| switch (err) {
error.AlreadyReported => "unknown (see error printed above)",
error.BadInstallDirSetting => "invalid (fix with zigup set-install-dir)",
};
const setting_file: []const u8 = blk: {
if (getSettingsDir(allocator)) |d| break :blk std.fs.path.join(allocator, &.{ d, "install-dir" }) catch |e| oom(e);
break :blk "unavailable";
};
try std.io.getStdErr().writer().print(
\\Download and manage zig compilers.
\\
\\Common Usage:
\\
\\ zigup VERSION download and set VERSION compiler as default
\\ zigup fetch VERSION download VERSION compiler
\\ zigup default [VERSION] get or set the default compiler
\\ zigup list list installed compiler versions
\\ zigup clean [VERSION] deletes the given compiler version, otherwise, cleans all compilers
\\ that aren't the default, master, or marked to keep.
\\ zigup keep VERSION mark a compiler to be kept during clean
\\ zigup run VERSION ARGS... run the given VERSION of the compiler with the given ARGS...
\\
\\ zigup get-install-dir prints the install directory to stdout
\\ zigup set-install-dir [PATH] set the default install directory, omitting the PATH reverts to the builtin default
\\ current default: {s}
\\ setting file : {s}
\\ builtin default: {s}
\\
\\Uncommon Usage:
\\
\\ zigup fetch-index download and print the download index json
\\
\\Common Options:
\\ --install-dir DIR override the default install location
\\ --path-link PATH path to the `zig` symlink that points to the default compiler
\\ this will typically be a file path within a PATH directory so
\\ that the user can just run `zig`
\\ --index override the default index URL that zig versions/URLs are fetched from.
\\ default:
++ " " ++ default_index_url ++
\\
\\
,
.{
current_install_dir,
setting_file,
builtin_install_dir,
},
);
}
fn getCmdOpt(args: [][:0]u8, i: *usize) ![]const u8 {
i.* += 1;
if (i.* == args.len) {
std.log.err("option '{s}' requires an argument", .{args[i.* - 1]});
return error.AlreadyReported;
}
return args[i.*];
}
pub fn main() !u8 {
return main2() catch |e| switch (e) {
error.AlreadyReported => return 1,
else => return e,
};
}
pub fn main2() !u8 {
if (builtin.os.tag == .windows) {
_ = try std.os.windows.WSAStartup(2, 2);
}
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();
const args_array = try std.process.argsAlloc(allocator);
// no need to free, os will do it
//defer std.process.argsFree(allocator, argsArray);
var args = if (args_array.len == 0) args_array else args_array[1..];
// parse common options
var index_url: []const u8 = default_index_url;
{
var i: usize = 0;
var newlen: usize = 0;
while (i < args.len) : (i += 1) {
const arg = args[i];
if (std.mem.eql(u8, "--install-dir", arg)) {
global_optional_install_dir = try getCmdOpt(args, &i);
if (!std.fs.path.isAbsolute(global_optional_install_dir.?)) {
global_optional_install_dir = try toAbsolute(allocator, global_optional_install_dir.?);
}
} else if (std.mem.eql(u8, "--path-link", arg)) {
global_optional_path_link = try getCmdOpt(args, &i);
if (!std.fs.path.isAbsolute(global_optional_path_link.?)) {
global_optional_path_link = try toAbsolute(allocator, global_optional_path_link.?);
}
} else if (std.mem.eql(u8, "--index", arg)) {
index_url = try getCmdOpt(args, &i);
} else if (std.mem.eql(u8, "-h", arg) or std.mem.eql(u8, "--help", arg)) {
try help(allocator);
return 0;
} else if (std.mem.eql(u8, "--appdata", arg)) {
// NOTE: this is a private option just used for testing
global_override_appdata = try getCmdOpt(args, &i);
} else {
if (newlen == 0 and std.mem.eql(u8, "run", arg)) {
return try runCompiler(allocator, args[i + 1 ..]);
}
args[newlen] = args[i];
newlen += 1;
}
}
args = args[0..newlen];
}
if (args.len == 0) {
try help(allocator);
return 1;
}
if (std.mem.eql(u8, "get-install-dir", args[0])) {
if (args.len != 1) {
std.log.err("get-install-dir does not accept any cmdline arguments", .{});
return 1;
}
const install_dir = getInstallDir(allocator, .{ .create = false, .log = false }) catch |err| switch (err) {
error.AlreadyReported => return 1,
else => |e| return e,
};
try std.io.getStdOut().writer().writeAll(install_dir);
try std.io.getStdOut().writer().writeAll("\n");
return 0;
}
if (std.mem.eql(u8, "set-install-dir", args[0])) {
const set_args = args[1..];
switch (set_args.len) {
0 => try saveInstallDir(allocator, null),
1 => {
const path = set_args[0];
if (!std.fs.path.isAbsolute(path)) {
std.log.err("set-install-dir requires an absolute path", .{});
return 1;
}
try saveInstallDir(allocator, path);
},
else => |set_arg_count| {
std.log.err("set-install-dir requires 0 or 1 cmdline arg but got {}", .{set_arg_count});
return 1;
},
}
return 0;
}
if (std.mem.eql(u8, "fetch-index", args[0])) {
if (args.len != 1) {
std.log.err("'index' command requires 0 arguments but got {d}", .{args.len - 1});
return 1;
}
var download_index = try fetchDownloadIndex(allocator, index_url);
defer download_index.deinit(allocator);
try std.io.getStdOut().writeAll(download_index.text);
return 0;
}
if (std.mem.eql(u8, "fetch", args[0])) {
if (args.len != 2) {
std.log.err("'fetch' command requires 1 argument but got {d}", .{args.len - 1});
return 1;
}
try fetchCompiler(allocator, index_url, args[1], .leave_default);
return 0;
}
if (std.mem.eql(u8, "clean", args[0])) {
if (args.len == 1) {
try cleanCompilers(allocator, null);
} else if (args.len == 2) {
try cleanCompilers(allocator, args[1]);
} else {
std.log.err("'clean' command requires 0 or 1 arguments but got {d}", .{args.len - 1});
return 1;
}
return 0;
}
if (std.mem.eql(u8, "keep", args[0])) {
if (args.len != 2) {
std.log.err("'keep' command requires 1 argument but got {d}", .{args.len - 1});
return 1;
}
try keepCompiler(allocator, args[1]);
return 0;
}
if (std.mem.eql(u8, "list", args[0])) {
if (args.len != 1) {
std.log.err("'list' command requires 0 arguments but got {d}", .{args.len - 1});
return 1;
}
try listCompilers(allocator);
return 0;
}
if (std.mem.eql(u8, "default", args[0])) {
if (args.len == 1) {
try printDefaultCompiler(allocator);
return 0;
}
if (args.len == 2) {
const version_string = args[1];
const install_dir_string = try getInstallDir(allocator, .{ .create = true });
defer allocator.free(install_dir_string);
const resolved_version_string = init_resolved: {
if (!std.mem.eql(u8, version_string, "master"))
break :init_resolved version_string;
const optional_master_dir: ?[]const u8 = blk: {
var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
error.FileNotFound => break :blk null,
else => return e,
};
defer install_dir.close();
break :blk try getMasterDir(allocator, &install_dir);
};
// no need to free master_dir, this is a short lived program
break :init_resolved optional_master_dir orelse {
std.log.err("master has not been fetched", .{});
return 1;
};
};
const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir_string, resolved_version_string });
defer allocator.free(compiler_dir);
try setDefaultCompiler(allocator, compiler_dir, .verify_existence);
return 0;
}
std.log.err("'default' command requires 1 or 2 arguments but got {d}", .{args.len - 1});
return 1;
}
if (args.len == 1) {
try fetchCompiler(allocator, index_url, args[0], .set_default);
return 0;
}
const command = args[0];
args = args[1..];
std.log.err("command not impl '{s}'", .{command});
return 1;
//const optionalInstallPath = try find_zigs(allocator);
}
pub fn runCompiler(allocator: Allocator, args: []const []const u8) !u8 {
// disable log so we don't add extra output to whatever the compiler will output
global_enable_log = false;
if (args.len <= 1) {
std.log.err("zigup run requires at least 2 arguments: zigup run VERSION PROG ARGS...", .{});
return 1;
}
const version_string = args[0];
const install_dir_string = try getInstallDir(allocator, .{ .create = true });
defer allocator.free(install_dir_string);
const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir_string, version_string });
defer allocator.free(compiler_dir);
if (!try existsAbsolute(compiler_dir)) {
std.log.err("compiler '{s}' does not exist, fetch it first with: zigup fetch {0s}", .{version_string});
return 1;
}
var argv = std.ArrayList([]const u8).init(allocator);
try argv.append(try std.fs.path.join(allocator, &.{ compiler_dir, "files", comptime "zig" ++ builtin.target.exeFileExt() }));
try argv.appendSlice(args[1..]);
// TODO: use "execve" if on linux
var proc = std.process.Child.init(argv.items, allocator);
const ret_val = try proc.spawnAndWait();
switch (ret_val) {
.Exited => |code| return code,
else => |result| {
std.log.err("compiler exited with {}", .{result});
return 0xff;
},
}
}
const SetDefault = enum { set_default, leave_default };
fn fetchCompiler(
allocator: Allocator,
index_url: []const u8,
version_arg: []const u8,
set_default: SetDefault,
) !void {
const install_dir = try getInstallDir(allocator, .{ .create = true });
defer allocator.free(install_dir);
var optional_download_index: ?DownloadIndex = null;
// This is causing an LLVM error
//defer if (optionalDownloadIndex) |_| optionalDownloadIndex.?.deinit(allocator);
// Also I would rather do this, but it doesn't work because of const issues
//defer if (optionalDownloadIndex) |downloadIndex| downloadIndex.deinit(allocator);
const VersionUrl = struct { version: []const u8, url: []const u8 };
// NOTE: we only fetch the download index if the user wants to download 'master', we can skip
// this step for all other versions because the version to URL mapping is fixed (see getDefaultUrl)
const is_master = std.mem.eql(u8, version_arg, "master");
const version_url = blk: {
// For default index_url we can build the url so we avoid downloading the index
if (!is_master and std.mem.eql(u8, default_index_url, index_url))
break :blk VersionUrl{ .version = version_arg, .url = try getDefaultUrl(allocator, version_arg) };
optional_download_index = try fetchDownloadIndex(allocator, index_url);
const master = optional_download_index.?.json.value.object.get(version_arg).?;
const compiler_version = master.object.get("version").?.string;
const master_linux = master.object.get(json_platform).?;
const master_linux_tarball = master_linux.object.get("tarball").?.string;
break :blk VersionUrl{ .version = compiler_version, .url = master_linux_tarball };
};
const compiler_dir = try std.fs.path.join(allocator, &[_][]const u8{ install_dir, version_url.version });
defer allocator.free(compiler_dir);
try installCompiler(allocator, compiler_dir, version_url.url);
if (is_master) {
const master_symlink = try std.fs.path.join(allocator, &[_][]const u8{ install_dir, "master" });
defer allocator.free(master_symlink);
if (builtin.os.tag == .windows) {
var file = try std.fs.createFileAbsolute(master_symlink, .{});
defer file.close();
try file.writer().writeAll(version_url.version);
} else {
_ = try loggyUpdateSymlink(version_url.version, master_symlink, .{ .is_directory = true });
}
}
if (set_default == .set_default) {
try setDefaultCompiler(allocator, compiler_dir, .existence_verified);
}
}
const default_index_url = "https://ziglang.org/download/index.json";
const DownloadIndex = struct {
text: []u8,
json: std.json.Parsed(std.json.Value),
pub fn deinit(self: *DownloadIndex, allocator: Allocator) void {
self.json.deinit();
allocator.free(self.text);
}
};
fn fetchDownloadIndex(allocator: Allocator, index_url: []const u8) !DownloadIndex {
const text = switch (downloadToString(allocator, index_url)) {
.ok => |text| text,
.err => |err| {
std.log.err("could not download '{s}': {s}", .{ index_url, err });
return error.AlreadyReported;
},
};
errdefer allocator.free(text);
var json = std.json.parseFromSlice(std.json.Value, allocator, text, .{}) catch |e| {
std.log.err(
"failed to parse JSON content from index url '{s}' with {s}",
.{ index_url, @errorName(e) },
);
return error.AlreadyReported;
};
errdefer json.deinit();
return DownloadIndex{ .text = text, .json = json };
}
fn loggyMakePath(dir_absolute: []const u8) !void {
if (builtin.os.tag == .windows) {
loginfo("mkdir \"{s}\"", .{dir_absolute});
} else {
loginfo("mkdir -p '{s}'", .{dir_absolute});
}
try std.fs.cwd().makePath(dir_absolute);
}
fn loggyDeleteTreeAbsolute(dir_absolute: []const u8) !void {
if (builtin.os.tag == .windows) {
loginfo("rd /s /q \"{s}\"", .{dir_absolute});
} else {
loginfo("rm -rf '{s}'", .{dir_absolute});
}
try fixdeletetree.deleteTreeAbsolute(dir_absolute);
}
pub fn loggyRenameAbsolute(old_path: []const u8, new_path: []const u8) !void {
loginfo("mv '{s}' '{s}'", .{ old_path, new_path });
try std.fs.renameAbsolute(old_path, new_path);
}
pub fn loggySymlinkAbsolute(target_path: []const u8, sym_link_path: []const u8, flags: std.fs.Dir.SymLinkFlags) !void {
loginfo("ln -s '{s}' '{s}'", .{ target_path, sym_link_path });
// NOTE: can't use symLinkAbsolute because it requires target_path to be absolute but we don't want that
// not sure if it is a bug in the standard lib or not
//try std.fs.symLinkAbsolute(target_path, sym_link_path, flags);
_ = flags;
try std.posix.symlink(target_path, sym_link_path);
}
/// returns: true if the symlink was updated, false if it was already set to the given `target_path`
pub fn loggyUpdateSymlink(target_path: []const u8, sym_link_path: []const u8, flags: std.fs.Dir.SymLinkFlags) !bool {
var current_target_path_buffer: [std.fs.max_path_bytes]u8 = undefined;
if (std.fs.readLinkAbsolute(sym_link_path, ¤t_target_path_buffer)) |current_target_path| {
if (std.mem.eql(u8, target_path, current_target_path)) {
loginfo("symlink '{s}' already points to '{s}'", .{ sym_link_path, target_path });
return false; // already up-to-date
}
try std.posix.unlink(sym_link_path);
} else |e| switch (e) {
error.FileNotFound => {},
error.NotLink => {
std.debug.print(
"unable to update/overwrite the 'zig' PATH symlink, the file '{s}' already exists and is not a symlink\n",
.{sym_link_path},
);
std.process.exit(1);
},
else => return e,
}
try loggySymlinkAbsolute(target_path, sym_link_path, flags);
return true; // updated
}
// TODO: this should be in std lib somewhere
fn existsAbsolute(absolutePath: []const u8) !bool {
std.fs.cwd().access(absolutePath, .{}) catch |e| switch (e) {
error.FileNotFound => return false,
error.PermissionDenied => return e,
error.InputOutput => return e,
error.SystemResources => return e,
error.SymLinkLoop => return e,
error.FileBusy => return e,
error.Unexpected => unreachable,
error.InvalidUtf8 => return e,
error.InvalidWtf8 => return e,
error.ReadOnlyFileSystem => unreachable,
error.NameTooLong => unreachable,
error.BadPathName => unreachable,
};
return true;
}
fn listCompilers(allocator: Allocator) !void {
const install_dir_string = try getInstallDir(allocator, .{ .create = false });
defer allocator.free(install_dir_string);
var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
error.FileNotFound => return,
else => return e,
};
defer install_dir.close();
const stdout = std.io.getStdOut().writer();
{
var it = install_dir.iterate();
while (try it.next()) |entry| {
if (entry.kind != .directory)
continue;
if (std.mem.endsWith(u8, entry.name, ".installing"))
continue;
try stdout.print("{s}\n", .{entry.name});
}
}
}
fn keepCompiler(allocator: Allocator, compiler_version: []const u8) !void {
const install_dir_string = try getInstallDir(allocator, .{ .create = true });
defer allocator.free(install_dir_string);
var install_dir = try std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true });
defer install_dir.close();
var compiler_dir = install_dir.openDir(compiler_version, .{}) catch |e| switch (e) {
error.FileNotFound => {
std.log.err("compiler not found: {s}", .{compiler_version});
return error.AlreadyReported;
},
else => return e,
};
var keep_fd = try compiler_dir.createFile("keep", .{});
keep_fd.close();
loginfo("created '{s}{c}{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, compiler_version, std.fs.path.sep, "keep" });
}
fn cleanCompilers(allocator: Allocator, compiler_name_opt: ?[]const u8) !void {
const install_dir_string = try getInstallDir(allocator, .{ .create = true });
defer allocator.free(install_dir_string);
// getting the current compiler
const default_comp_opt = try getDefaultCompiler(allocator);
defer if (default_comp_opt) |default_compiler| allocator.free(default_compiler);
var install_dir = std.fs.openDirAbsolute(install_dir_string, .{ .iterate = true }) catch |e| switch (e) {
error.FileNotFound => return,
else => return e,
};
defer install_dir.close();
const master_points_to_opt = try getMasterDir(allocator, &install_dir);
defer if (master_points_to_opt) |master_points_to| allocator.free(master_points_to);
if (compiler_name_opt) |compiler_name| {
if (getKeepReason(master_points_to_opt, default_comp_opt, compiler_name)) |reason| {
std.log.err("cannot clean '{s}' ({s})", .{ compiler_name, reason });
return error.AlreadyReported;
}
loginfo("deleting '{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, compiler_name });
try fixdeletetree.deleteTree(install_dir, compiler_name);
} else {
var it = install_dir.iterate();
while (try it.next()) |entry| {
if (entry.kind != .directory)
continue;
if (getKeepReason(master_points_to_opt, default_comp_opt, entry.name)) |reason| {
loginfo("keeping '{s}' ({s})", .{ entry.name, reason });
continue;
}
{
var compiler_dir = try install_dir.openDir(entry.name, .{});
defer compiler_dir.close();
if (compiler_dir.access("keep", .{})) |_| {
loginfo("keeping '{s}' (has keep file)", .{entry.name});
continue;
} else |e| switch (e) {
error.FileNotFound => {},
else => return e,
}
}
loginfo("deleting '{s}{c}{s}'", .{ install_dir_string, std.fs.path.sep, entry.name });
try fixdeletetree.deleteTree(install_dir, entry.name);
}
}
}
fn readDefaultCompiler(allocator: Allocator, buffer: *[std.fs.max_path_bytes + 1]u8) !?[]const u8 {
const path_link = try makeZigPathLinkString(allocator);
defer allocator.free(path_link);
if (builtin.os.tag == .windows) {
var file = std.fs.openFileAbsolute(path_link, .{}) catch |e| switch (e) {
error.FileNotFound => return null,
else => return e,
};
defer file.close();
try file.seekTo(win32exelink.exe_offset);
const len = try file.readAll(buffer);
if (len != buffer.len) {
std.log.err("path link file '{s}' is too small", .{path_link});
return error.AlreadyReported;
}
const target_exe = std.mem.sliceTo(buffer, 0);
return try allocator.dupe(u8, targetPathToVersion(target_exe));
}
const target_path = std.fs.readLinkAbsolute(path_link, buffer[0..std.fs.max_path_bytes]) catch |e| switch (e) {
error.FileNotFound => return null,
else => return e,
};
defer allocator.free(target_path);
return try allocator.dupe(u8, targetPathToVersion(target_path));
}
fn targetPathToVersion(target_path: []const u8) []const u8 {
return std.fs.path.basename(std.fs.path.dirname(std.fs.path.dirname(target_path).?).?);
}
fn readMasterDir(buffer: *[std.fs.max_path_bytes]u8, install_dir: *std.fs.Dir) !?[]const u8 {
if (builtin.os.tag == .windows) {
var file = install_dir.openFile("master", .{}) catch |e| switch (e) {
error.FileNotFound => return null,
else => return e,
};
defer file.close();
return buffer[0..try file.readAll(buffer)];
}
return install_dir.readLink("master", buffer) catch |e| switch (e) {
error.FileNotFound => return null,
else => return e,
};
}
fn getDefaultCompiler(allocator: Allocator) !?[]const u8 {
var buffer: [std.fs.max_path_bytes + 1]u8 = undefined;
const slice_path = (try readDefaultCompiler(allocator, &buffer)) orelse return null;
const path_to_return = try allocator.alloc(u8, slice_path.len);
@memcpy(path_to_return, slice_path);
return path_to_return;
}
fn getMasterDir(allocator: Allocator, install_dir: *std.fs.Dir) !?[]const u8 {
var buffer: [std.fs.max_path_bytes]u8 = undefined;
const slice_path = (try readMasterDir(&buffer, install_dir)) orelse return null;
const path_to_return = try allocator.alloc(u8, slice_path.len);
@memcpy(path_to_return, slice_path);
return path_to_return;
}
fn printDefaultCompiler(allocator: Allocator) !void {
const default_compiler_opt = try getDefaultCompiler(allocator);
defer if (default_compiler_opt) |default_compiler| allocator.free(default_compiler);
const stdout = std.io.getStdOut().writer();
if (default_compiler_opt) |default_compiler| {
try stdout.print("{s}\n", .{default_compiler});
} else {
try stdout.writeAll("<no-default>\n");
}
}
const ExistVerify = enum { existence_verified, verify_existence };
fn setDefaultCompiler(allocator: Allocator, compiler_dir: []const u8, exist_verify: ExistVerify) !void {
switch (exist_verify) {
.existence_verified => {},
.verify_existence => {
var dir = std.fs.openDirAbsolute(compiler_dir, .{}) catch |err| switch (err) {
error.FileNotFound => {
std.log.err("compiler '{s}' is not installed", .{std.fs.path.basename(compiler_dir)});
return error.AlreadyReported;
},
else => |e| return e,
};
dir.close();
},
}
const path_link = try makeZigPathLinkString(allocator);
defer allocator.free(path_link);
const link_target = try std.fs.path.join(
allocator,
&[_][]const u8{ compiler_dir, "files", comptime "zig" ++ builtin.target.exeFileExt() },
);
defer allocator.free(link_target);
if (builtin.os.tag == .windows) {
try createExeLink(link_target, path_link);
} else {
_ = try loggyUpdateSymlink(link_target, path_link, .{});
}
try verifyPathLink(allocator, path_link);
}
/// Verify that path_link will work. It verifies that `path_link` is
/// in PATH and there is no zig executable in an earlier directory in PATH.
fn verifyPathLink(allocator: Allocator, path_link: []const u8) !void {
const path_link_dir = std.fs.path.dirname(path_link) orelse {
std.log.err("invalid '--path-link' '{s}', it must be a file (not the root directory)", .{path_link});
return error.AlreadyReported;
};
const path_link_dir_id = blk: {
var dir = std.fs.openDirAbsolute(path_link_dir, .{}) catch |err| {
std.log.err("unable to open the path-link directory '{s}': {s}", .{ path_link_dir, @errorName(err) });
return error.AlreadyReported;
};
defer dir.close();
break :blk try FileId.initFromDir(dir, path_link);
};
if (builtin.os.tag == .windows) {
const path_env = std.process.getEnvVarOwned(allocator, "PATH") catch |err| switch (err) {
error.EnvironmentVariableNotFound => return,
else => |e| return e,
};
defer allocator.free(path_env);
var free_pathext: ?[]const u8 = null;
defer if (free_pathext) |p| allocator.free(p);
const pathext_env = blk: {
if (std.process.getEnvVarOwned(allocator, "PATHEXT")) |env| {
free_pathext = env;
break :blk env;
} else |err| switch (err) {
error.EnvironmentVariableNotFound => break :blk "",
else => |e| return e,
}
break :blk "";
};
var path_it = std.mem.tokenizeScalar(u8, path_env, ';');
while (path_it.next()) |path| {
switch (try compareDir(path_link_dir_id, path)) {
.missing => continue,
// can't be the same directory because we were able to open and get
// the file id for path_link_dir_id
.access_denied => {},
.match => return,
.mismatch => {},
}
{
const exe = try std.fs.path.join(allocator, &.{ path, "zig" });
defer allocator.free(exe);
try enforceNoZig(path_link, exe);
}
var ext_it = std.mem.tokenizeScalar(u8, pathext_env, ';');
while (ext_it.next()) |ext| {
if (ext.len == 0) continue;
const basename = try std.mem.concat(allocator, u8, &.{ "zig", ext });
defer allocator.free(basename);
const exe = try std.fs.path.join(allocator, &.{ path, basename });
defer allocator.free(exe);
try enforceNoZig(path_link, exe);
}
}
} else {
var path_it = std.mem.tokenizeScalar(u8, std.posix.getenv("PATH") orelse "", ':');