authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-01-10 00:38:18-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-01-11 15:39:49-08:00
logd4e829d0a0f260e4dacbe293cd282af8ba2e4a30
tree029ec7922710bd7ce6dc2ce287185992c709e33f
parentf104cfa1eb154ad51876270e10e8786b863d05f1

std.tar: add strip_components option


1 files changed, 31 insertions(+), 5 deletions(-)

lib/std/tar.zig+31-5
......@@ -1,4 +1,7 @@
1pub const Options = struct {};
1pub const Options = struct {
2 /// Number of directory levels to skip when extracting files.
3 strip_components: u32 = 0,
4};
25
36pub const Header = struct {
47 bytes: *const [512]u8,
......@@ -69,7 +72,6 @@ pub const Header = struct {
6972};
7073
7174pub fn pipeToFileSystem(dir: std.fs.Dir, reader: anytype, options: Options) !void {
72 _ = options;
7375 var file_name_buffer: [255]u8 = undefined;
7476 var buffer: [512 * 8]u8 = undefined;
7577 var start: usize = 0;
......@@ -92,13 +94,17 @@ pub fn pipeToFileSystem(dir: std.fs.Dir, reader: anytype, options: Options) !voi
9294 const file_size = try header.fileSize();
9395 const rounded_file_size = std.mem.alignForwardGeneric(u64, file_size, 512);
9496 const pad_len = rounded_file_size - file_size;
95 const file_name = try header.fullFileName(&file_name_buffer);
97 const unstripped_file_name = try header.fullFileName(&file_name_buffer);
9698 switch (header.fileType()) {
9799 .directory => {
98 try dir.makeDir(file_name);
100 const file_name = try stripComponents(unstripped_file_name, options.strip_components);
101 if (file_name.len != 0) {
102 try dir.makeDir(file_name);
103 }
99104 },
100105 .normal => {
101 if (file_size == 0 and file_name.len == 0) return;
106 if (file_size == 0 and unstripped_file_name.len == 0) return;
107 const file_name = try stripComponents(unstripped_file_name, options.strip_components);
102108
103109 var file = try dir.createFile(file_name, .{});
104110 defer file.close();
......@@ -140,5 +146,25 @@ pub fn pipeToFileSystem(dir: std.fs.Dir, reader: anytype, options: Options) !voi
140146 }
141147}
142148
149fn stripComponents(path: []const u8, count: u32) ![]const u8 {
150 var i: usize = 0;
151 var c = count;
152 while (c > 0) : (c -= 1) {
153 if (std.mem.indexOfScalarPos(u8, path, i, '/')) |pos| {
154 i = pos + 1;
155 } else {
156 return error.TarComponentsOutsideStrippedPrefix;
157 }
158 }
159 return path[i..];
160}
161
162test stripComponents {
163 const expectEqualStrings = std.testing.expectEqualStrings;
164 try expectEqualStrings("a/b/c", try stripComponents("a/b/c", 0));
165 try expectEqualStrings("b/c", try stripComponents("a/b/c", 1));
166 try expectEqualStrings("c", try stripComponents("a/b/c", 2));
167}
168
143169const std = @import("std.zig");
144170const assert = std.debug.assert;