-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbundle.go
70 lines (65 loc) · 1.81 KB
/
bundle.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
66
67
68
69
70
package enex
import (
"fmt"
"io"
"net/url"
"os"
"path"
"path/filepath"
)
// Bundle is a type that contains information about attachments.
type Bundle struct {
Resource map[string]*Resource
BaseName string
Dir string
dirEscape string
serialNo _SerialNo
sanitizer func(string) string
}
func newBundle(note *Note, sanitizer func(string) string) *Bundle {
baseName := sanitizer(note.Title)
dir := baseName + ".files"
dirEscape := url.PathEscape(dir)
return &Bundle{
Resource: make(map[string]*Resource),
BaseName: baseName,
Dir: dir,
dirEscape: dirEscape,
serialNo: make(_SerialNo),
sanitizer: sanitizer,
}
}
func (B *Bundle) makeUrlFor(rsc *Resource) string {
name := B.sanitizer(B.serialNo.ToUniqName(rsc.Mime, rsc.FileName, rsc.Hash))
rsc.NewFileName = name
B.Resource[filepath.Join(B.Dir, name)] = rsc
return path.Join(B.dirEscape, url.PathEscape(name))
}
// Extract saves all attachments into subdirectories under rootDir.
// Each attachment is saved in a subdirectory named after the original note's name,
// formatted as "(note-name).files", with its respective filename.
func (B *Bundle) Extract(rootDir string, log io.Writer) error {
for _fname, data := range B.Resource {
fname := filepath.Join(rootDir, _fname)
dir := filepath.Dir(fname)
if stat, err := os.Stat(dir); os.IsNotExist(err) {
fmt.Fprintln(log, "Create Dir:", dir)
if err := os.Mkdir(dir, 0755); err != nil {
return err
}
} else if err != nil {
return err
} else if !stat.IsDir() {
return fmt.Errorf("Can not mkdir %s because the file same name already exists", dir)
}
data, err := data.Data()
if err != nil {
return err
}
if err := os.WriteFile(fname, data, 0644); err != nil {
return err
}
fmt.Fprintf(log, "Create File: %s (%d bytes)\n", fname, len(data))
}
return nil
}