Skip to content

Commit e873dc5

Browse files
zig init: allow specifying project path
1 parent e837765 commit e873dc5

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

src/main.zig

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4624,10 +4624,11 @@ fn cmdTranslateC(
46244624
}
46254625

46264626
const usage_init =
4627-
\\Usage: zig init
4627+
\\Usage: zig init [path]
46284628
\\
4629-
\\ Initializes a `zig build` project in the current working
4630-
\\ directory.
4629+
\\ Initializes a `zig build` project in the specified
4630+
\\ path. If path is not provided, initialize in the
4631+
\\ current working directory.
46314632
\\
46324633
\\Options:
46334634
\\ -s, --strip Generate files without comments
@@ -4640,6 +4641,8 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46404641
dev.check(.init_command);
46414642

46424643
var strip = false;
4644+
var path_specified = false;
4645+
var path: []const u8 = "";
46434646
{
46444647
var i: usize = 0;
46454648
while (i < args.len) : (i += 1) {
@@ -4654,7 +4657,12 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46544657
fatal("unrecognized parameter: '{s}'", .{arg});
46554658
}
46564659
} else {
4657-
fatal("unexpected extra parameter: '{s}'", .{arg});
4660+
if (path_specified) {
4661+
fatal("more than one path specified", .{});
4662+
}
4663+
path_specified = true;
4664+
4665+
path = arg;
46584666
}
46594667
}
46604668
}
@@ -4666,6 +4674,19 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46664674
const cwd_basename = fs.path.basename(cwd_path);
46674675
const sanitized_root_name = try sanitizeExampleName(arena, cwd_basename);
46684676

4677+
var out_dir = fs.cwd();
4678+
if (path_specified) {
4679+
fs.cwd().makePath(path) catch |e|
4680+
switch (e) {
4681+
error.PathAlreadyExists => return,
4682+
error.NotDir => {
4683+
fatal("specified path contains non-directory", .{});
4684+
},
4685+
else => return e,
4686+
};
4687+
out_dir = try fs.cwd().openDir(path, .{});
4688+
}
4689+
46694690
const s = fs.path.sep_str;
46704691
const template_paths = [_][]const u8{
46714692
Package.build_zig_basename,
@@ -4678,7 +4699,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
46784699
const fingerprint: Package.Fingerprint = .generate(sanitized_root_name);
46794700

46804701
for (template_paths) |template_path| {
4681-
if (templates.write(arena, fs.cwd(), sanitized_root_name, template_path, fingerprint)) |_| {
4702+
if (templates.write(arena, out_dir, sanitized_root_name, template_path, fingerprint)) |_| {
46824703
std.log.info("created {s}", .{template_path});
46834704
ok_count += 1;
46844705
} else |err| switch (err) {

0 commit comments

Comments
 (0)