add a --with_base option to fetch

with_base option adds a <base> tag to the dump for better offline preview.
This commit is contained in:
Pierre Tachoire
2025-08-08 15:18:11 +02:00
parent ea1bca05c7
commit 3d0928a449
2 changed files with 29 additions and 2 deletions

View File

@@ -23,6 +23,7 @@ const Walker = @import("dom/walker.zig").WalkerChildren;
pub const Opts = struct {
exclude_scripts: bool = false,
include_base: ?[]const u8 = null,
};
// writer must be a std.io.Writer
@@ -91,6 +92,14 @@ pub fn writeNode(node: *parser.Node, opts: Opts, writer: anytype) anyerror!void
// void elements can't have any content.
if (try isVoid(parser.nodeToElement(node))) return;
// If we wrote the <header> and we want to include a <base>, add it
// now.
if (opts.include_base != null and tag_type == .head) {
try writer.writeAll("<base href=\"");
try writer.writeAll(opts.include_base.?);
try writer.writeAll("\">");
}
if (tag_type == .script) {
try writer.writeAll(try parser.nodeTextContent(node) orelse "");
} else {

View File

@@ -134,7 +134,10 @@ fn run(alloc: Allocator) !void {
// dump
if (opts.dump) {
try page.dump(.{ .exclude_scripts = opts.noscript }, std.io.getStdOut());
try page.dump(.{
.exclude_scripts = opts.noscript,
.include_base = if (opts.withbase) page.url.raw else null,
}, std.io.getStdOut());
}
},
else => unreachable,
@@ -213,6 +216,7 @@ const Command = struct {
dump: bool = false,
common: Common,
noscript: bool = false,
withbase: bool = false,
};
const Common = struct {
@@ -277,6 +281,7 @@ const Command = struct {
\\--dump Dumps document to stdout.
\\ Defaults to false.
\\--noscript Exclude <script> tags in dump. Defaults to false.
\\--with_base Add a <base> tag in dump. Defaults to false.
\\
++ common_options ++
\\
@@ -351,13 +356,19 @@ fn inferMode(opt: []const u8) ?App.RunMode {
return .serve;
}
if (std.mem.startsWith(u8, opt, "--") == false) {
return .fetch;
}
if (std.mem.eql(u8, opt, "--dump")) {
return .fetch;
}
if (std.mem.eql(u8, opt, "--noscript")) {
return .fetch;
}
if (std.mem.startsWith(u8, opt, "--") == false) {
if (std.mem.eql(u8, opt, "--with_base")) {
return .fetch;
}
@@ -443,6 +454,7 @@ fn parseFetchArgs(
) !Command.Fetch {
var dump: bool = false;
var noscript: bool = false;
var withbase: bool = false;
var url: ?[]const u8 = null;
var common: Command.Common = .{};
@@ -457,6 +469,11 @@ fn parseFetchArgs(
continue;
}
if (std.mem.eql(u8, "--with_base", opt)) {
withbase = true;
continue;
}
if (try parseCommonArg(allocator, opt, args, &common)) {
continue;
}
@@ -483,6 +500,7 @@ fn parseFetchArgs(
.dump = dump,
.common = common,
.noscript = noscript,
.withbase = withbase,
};
}