forked from josharian/txtarfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtxtarfs.go
65 lines (60 loc) · 1.76 KB
/
txtarfs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Package txtarfs turns a txtar into an fs.FS.
package txtarfs
import (
"io/fs"
"github.com/josharian/mapfs"
"golang.org/x/tools/txtar"
)
// As returns an fs.FS containing ar's contents.
// Subsequent changes to ar may or may not
// be reflected in the returned fs.FS.
func As(ar *txtar.Archive) fs.FS {
m := make(mapfs.MapFS, len(ar.Files))
for _, f := range ar.Files {
m[f.Name] = &mapfs.MapFile{
Data: f.Data,
// TODO: maybe ModTime: time.Now(),
Sys: f,
}
}
m.ChmodAll(0666)
return m
}
// From constructs a txtar.Archive with the contents of fsys and an empty Comment.
// Subsequent changes to fsys are not reflected in the returned archive.
//
// The transformation is lossy.
// For example, because directories are implicit in txtar archives,
// empty directories in fsys will be lost.
// And txtar does not represent file mode, mtime, or other file metadata.
//
// Note also this warning from function txtar.Format:
// > It is assumed that the Archive data structure is well-formed:
// > a.Comment and all a.File[i].Data contain no file marker lines,
// > and all a.File[i].Name is non-empty.
// From does not guarantee that a.File[i].Data contain no file marker lines.
//
// In short, it is unwise to use From/As as a generic filesystem serialization mechanism.
func From(fsys fs.FS) (*txtar.Archive, error) {
ar := new(txtar.Archive)
walkfn := func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
// Directories in txtar are implicit.
return nil
}
data, err := fs.ReadFile(fsys, path)
if err != nil {
return err
}
ar.Files = append(ar.Files, txtar.File{Name: path, Data: data})
return nil
}
err := fs.WalkDir(fsys, ".", walkfn)
if err != nil {
return nil, err
}
return ar, nil
}