Skip to content

Commit 927435c

Browse files
zig init: allow specifying project path
1 parent fc2c188 commit 927435c

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
@@ -4612,10 +4612,11 @@ fn cmdTranslateC(
46124612
}
46134613

46144614
const usage_init =
4615-
\\Usage: zig init
4615+
\\Usage: zig init [path]
46164616
\\
4617-
\\ Initializes a `zig build` project in the current working
4618-
\\ directory.
4617+
\\ Initializes a `zig build` project in the specified
4618+
\\ path. If path is not provided, initialize in the
4619+
\\ current working directory.
46194620
\\
46204621
\\Options:
46214622
\\ -s, --strip Generate files without comments
@@ -4628,6 +4629,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46284629
dev.check(.init_command);
46294630

46304631
var strip = false;
4632+
var path: ?[]const u8 = "";
46314633
{
46324634
var i: usize = 0;
46334635
while (i < args.len) : (i += 1) {
@@ -4642,7 +4644,10 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46424644
fatal("unrecognized parameter: '{s}'", .{arg});
46434645
}
46444646
} else {
4645-
fatal("unexpected extra parameter: '{s}'", .{arg});
4647+
if (path != null) {
4648+
fatal("more than one path specified", .{});
4649+
}
4650+
path = arg;
46464651
}
46474652
}
46484653
}
@@ -4654,6 +4659,19 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46544659
const cwd_basename = fs.path.basename(cwd_path);
46554660
const sanitized_root_name = try sanitizeExampleName(arena, cwd_basename);
46564661

4662+
var out_dir = fs.cwd();
4663+
if (path != null) {
4664+
fs.cwd().makePath(path.?) catch |e|
4665+
switch (e) {
4666+
error.PathAlreadyExists => return,
4667+
error.NotDir => {
4668+
fatal("specified path contains non-directory", .{});
4669+
},
4670+
else => return e,
4671+
};
4672+
out_dir = try fs.cwd().openDir(path.?, .{});
4673+
}
4674+
46574675
const s = fs.path.sep_str;
46584676
const template_paths = [_][]const u8{
46594677
Package.build_zig_basename,
@@ -4666,7 +4684,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46664684
const fingerprint: Package.Fingerprint = .generate(sanitized_root_name);
46674685

46684686
for (template_paths) |template_path| {
4669-
if (templates.write(arena, fs.cwd(), sanitized_root_name, template_path, fingerprint)) |_| {
4687+
if (templates.write(arena, out_dir, sanitized_root_name, template_path, fingerprint)) |_| {
46704688
std.log.info("created {s}", .{template_path});
46714689
ok_count += 1;
46724690
} else |err| switch (err) {

0 commit comments

Comments
 (0)