| 1 | module txtar |
| 2 | |
| 3 | import 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. |
| 8 | pub fn pack(path string, comment string) !Archive { |
| 9 | if !os.exists(path) { |
| 10 | return error('file or folder ${path} does not exist') |
| 11 | } |
| 12 | npath := path.replace(os.path_separator, '/') |
| 13 | mut a := Archive{ |
| 14 | comment: comment |
| 15 | } |
| 16 | if os.is_file(npath) { |
| 17 | fname := os.file_name(npath) |
| 18 | fcontent := os.read_file(npath)! |
| 19 | a.files << File{fname, fcontent} |
| 20 | return a |
| 21 | } |
| 22 | files := os.walk_ext(npath, '').map(it.replace(os.path_separator, '/')) |
| 23 | for f in files { |
| 24 | frelative := f.replace_once(npath, '').trim_left('/') |
| 25 | fcontent := os.read_file(f)! |
| 26 | a.files << File{frelative, fcontent} |
| 27 | } |
| 28 | return 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. |
| 37 | pub fn unpack(a &Archive, path string) ! { |
| 38 | for f in a.files { |
| 39 | full_path := os.join_path(path, f.path) |
| 40 | folder := os.dir(full_path) |
| 41 | if !os.exists(folder) { |
| 42 | os.mkdir_all(folder)! |
| 43 | } |
| 44 | os.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. |
| 51 | pub fn parse_file(file_path string) !Archive { |
| 52 | content := os.read_file(file_path)! |
| 53 | return parse(content) |
| 54 | } |
| 55 | |
| 56 | // unpack_to extracts the content of the archive `a`, into the folder `path`. |
| 57 | pub fn (a &Archive) unpack_to(path string) ! { |
| 58 | unpack(a, path)! |
| 59 | } |
| 60 | |