-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnote.go
115 lines (96 loc) · 2.28 KB
/
note.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"errors"
"fmt"
"github.com/google/uuid"
"io"
"log"
"os"
"path/filepath"
"regexp"
)
// Generate a uuid from a abbreviated uuid string.
// The abbreviated string must be at the start of the uuid and be
// 8 bytes long.
// In order to get the real uuid, it must exist in note directory.
// Example: 1cf77aeb => 1cf77aeb-fcb2-44ad-87d6-69717dba1d0c
func uuidByAbbr(x string) (r uuid.UUID, err error) {
if isUuidAbbr(x) == false {
//err = errors.New("%s: No such note id")
err = fmt.Errorf(`No such note: %s`, r.String())
return
}
matches, err := filepath.Glob(filepath.Clean(notemanager.NoteDir + "/" + x + "*"))
if (err != nil) {
return
}
switch len(matches) {
case 0:
err = errors.New("No such note id")
case 1:
r, err = uuid.Parse(filepath.Base(matches[0]))
default:
err = errors.New("At least 2 notes found starting with " + x + ", use full uuid")
}
return
}
// Checks if input string is a valid Uuid abbreviation.
// Should be syntax: [a-f0-9]{8}
func isUuidAbbr(x string) (bool) {
reg := regexp.MustCompile(`^[a-f0-9]{8}$`)
if reg.MatchString(x) {
return true
}
return false
}
// Copies a regular file from src path to dst path.
// if dst already exists return an error.
func copyRegularFile(src string, dst string) (err error) {
sfh, err := os.Stat(src)
if err != nil {
return
}
if sfh.Mode().IsRegular() == false {
err = errors.New("Not a regular file: " + src)
return
}
// check if file exists
_, err = os.Stat(dst)
if err == nil {
err = errors.New("File already exists. Aborting.")
return err
}
sf, err := os.Open(src)
if err != nil {
return
}
defer sf.Close()
//df, err := os.Create(dst)
//df, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL, notemanager.FilePermissionReadonly)
df, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL|os.O_WRONLY, notemanager.FilePermissionReadonly)
if err != nil {
return
}
defer df.Close()
// copy file
_, err = io.Copy(df, sf)
if err != nil {
log.Fatal("Error copying file")
}
// compare checksums
srcHash, err := fileSha1(src)
if err != nil {
log.Fatal(err)
}
dstHash, err := fileSha1(dst)
if err != nil {
log.Fatal(err)
}
if srcHash == dstHash {
// files are same, OK
return
} else {
err = errors.New("Copy failed")
return
}
}