Skip to content

Commit 70e0d5b

Browse files
zig init: allow specifying project path
1 parent 1a99888 commit 70e0d5b

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/main.zig

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4621,10 +4621,11 @@ fn cmdTranslateC(
46214621
}
46224622

46234623
const usage_init =
4624-
\\Usage: zig init
4624+
\\Usage: zig init [path]
46254625
\\
4626-
\\ Initializes a `zig build` project in the current working
4627-
\\ directory.
4626+
\\ Initializes a `zig build` project in the specified
4627+
\\ path. If path is not provided, initialize in the
4628+
\\ current working directory.
46284629
\\
46294630
\\Options:
46304631
\\ -s, --strip Generate files without comments
@@ -4637,6 +4638,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46374638
dev.check(.init_command);
46384639

46394640
var strip = false;
4641+
var path: ?[]const u8 = "";
46404642
{
46414643
var i: usize = 0;
46424644
while (i < args.len) : (i += 1) {
@@ -4651,7 +4653,10 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46514653
fatal("unrecognized parameter: '{s}'", .{arg});
46524654
}
46534655
} else {
4654-
fatal("unexpected extra parameter: '{s}'", .{arg});
4656+
if (path != null) {
4657+
fatal("more than one path specified", .{});
4658+
}
4659+
path = arg;
46554660
}
46564661
}
46574662
}
@@ -4663,6 +4668,19 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46634668
const cwd_basename = fs.path.basename(cwd_path);
46644669
const sanitized_root_name = try sanitizeExampleName(arena, cwd_basename);
46654670

4671+
var out_dir = fs.cwd();
4672+
if (path != null) {
4673+
fs.cwd().makePath(path.?) catch |e|
4674+
switch (e) {
4675+
error.PathAlreadyExists => return,
4676+
error.NotDir => {
4677+
fatal("specified path contains non-directory", .{});
4678+
},
4679+
else => return e,
4680+
};
4681+
out_dir = try fs.cwd().openDir(path.?, .{});
4682+
}
4683+
46664684
const s = fs.path.sep_str;
46674685
const template_paths = [_][]const u8{
46684686
Package.build_zig_basename,
@@ -4675,7 +4693,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46754693
const fingerprint: Package.Fingerprint = .generate(sanitized_root_name);
46764694

46774695
for (template_paths) |template_path| {
4678-
if (templates.write(arena, fs.cwd(), sanitized_root_name, template_path, fingerprint)) |_| {
4696+
if (templates.write(arena, out_dir, sanitized_root_name, template_path, fingerprint)) |_| {
46794697
std.log.info("created {s}", .{template_path});
46804698
ok_count += 1;
46814699
} else |err| switch (err) {

0 commit comments

Comments
 (0)