v
Зеркало из https://github.com/vlang/v
1module txtar
2
3import os
4
5// pack will create a txtar archive, given a path.
6// When the path is a folder, it will walk over all files in that base folder, read their contents and create a File entry for each.
7// When the path is a file, it will create an Archive, that contains just a single File entry, for that single file.
8pub fn pack(path string, comment string) !Archive {
9if !os.exists(path) {
10return error('file or folder ${path} does not exist')
11}
12npath := path.replace(os.path_separator, '/')
13mut a := Archive{
14comment: comment
15}
16if os.is_file(npath) {
17fname := os.file_name(npath)
18fcontent := os.read_file(npath)!
19a.files << File{fname, fcontent}
20return a
21}
22files := os.walk_ext(npath, '').map(it.replace(os.path_separator, '/'))
23for f in files {
24frelative := f.replace_once(npath, '').trim_left('/')
25fcontent := os.read_file(f)!
26a.files << File{frelative, fcontent}
27}
28return a
29}
30
31// unpack will extract *all files* in the archive `a`, into the base folder `path`.
32// Note that all file paths will be appended to the base folder `path`, i.e.
33// if you have a File with `path` field == 'abc/def/x.v', and base folder path == '/tmp',
34// then the final path for that File, will be '/tmp/abc/def/x.v'
35// Note that unpack will try to create any of the intermediate folders like
36// /tmp, /tmp/abc, /tmp/abc/def, if they do not already exist.
37pub fn unpack(a &Archive, path string) ! {
38for f in a.files {
39full_path := os.join_path(path, f.path)
40folder := os.dir(full_path)
41if !os.exists(folder) {
42os.mkdir_all(folder)!
43}
44os.write_file(full_path, f.content)!
45}
46}
47
48// parse_file parses the given `file_path` as an archive.
49// It will return an error, only if the `file_path` is not readable.
50// See the README.md, or the test txtar_test.v, for a description of the format.
51pub fn parse_file(file_path string) !Archive {
52content := os.read_file(file_path)!
53return parse(content)
54}
55
56// unpack_to extracts the content of the archive `a`, into the folder `path`.
57pub fn (a &Archive) unpack_to(path string) ! {
58unpack(a, path)!
59}
60