make Package.Path support string escape formatting

This commit is contained in:
Andrew Kelley 2023-10-06 23:59:26 -07:00
parent cbb9b5d9f0
commit 9eb21541ec
3 changed files with 21 additions and 5 deletions

View File

@ -1,6 +1,6 @@
const std = @import("std.zig");
const tokenizer = @import("zig/tokenizer.zig");
const fmt = @import("zig/fmt.zig");
pub const fmt = @import("zig/fmt.zig");
const assert = std.debug.assert;
pub const ErrorBundle = @import("zig/ErrorBundle.zig");

View File

@ -13,7 +13,7 @@ fn formatId(
return writer.writeAll(bytes);
}
try writer.writeAll("@\"");
try formatEscapes(bytes, "", options, writer);
try stringEscape(bytes, "", options, writer);
try writer.writeByte('"');
}
@ -47,7 +47,7 @@ test "isValidId" {
/// Print the string as escaped contents of a double quoted or single-quoted string.
/// Format `{}` treats contents as a double-quoted string.
/// Format `{'}` treats contents as a single-quoted string.
fn formatEscapes(
pub fn stringEscape(
bytes: []const u8,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
@ -90,7 +90,7 @@ fn formatEscapes(
/// The format specifier must be one of:
/// * `{}` treats contents as a double-quoted string.
/// * `{'}` treats contents as a single-quoted string.
pub fn fmtEscapes(bytes: []const u8) std.fmt.Formatter(formatEscapes) {
pub fn fmtEscapes(bytes: []const u8) std.fmt.Formatter(stringEscape) {
return .{ .data = bytes };
}

View File

@ -89,7 +89,23 @@ pub const Path = struct {
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt_string.len == 1) {
// Quote-escape the string.
const stringEscape = std.zig.fmt.stringEscape;
const f = switch (fmt_string[0]) {
'q' => "",
'\'' => '\'',
else => @compileError("unsupported format string: " ++ fmt_string),
};
if (self.root_dir.path) |p| {
try stringEscape(p, f, options, writer);
if (self.sub_path.len > 0) try writer.writeAll(fs.path.sep_str);
}
if (self.sub_path.len > 0) {
try stringEscape(self.sub_path, f, options, writer);
}
return;
}
if (fmt_string.len > 0)
std.fmt.invalidFmtError(fmt_string, self);
if (self.root_dir.path) |p| {