-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlockfile.go
More file actions
106 lines (88 loc) · 1.78 KB
/
lockfile.go
File metadata and controls
106 lines (88 loc) · 1.78 KB
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
package gitgo
import (
"errors"
"log"
"os"
"sync"
"syscall"
)
var (
ErrMissingParent = errors.New("Missing Parent")
ErrNoPermission = errors.New("No Permission")
ErrStaleLock = errors.New("Stale Lock")
)
type lockFile struct {
FilePath string
LockPath string
Lock *os.File
mu sync.Mutex
}
func lockInitialize(path string) *lockFile {
lockPath := path + ".lock"
return &lockFile{
FilePath: path,
LockPath: lockPath,
}
}
func (l *lockFile) holdForUpdate() (bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.Lock != nil {
return true, nil // lock already aquired
}
file, err := os.OpenFile(l.LockPath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0644)
if err != nil {
var pathErr *os.PathError
if errors.As(err, &pathErr) {
switch pathErr.Err {
case syscall.EEXIST:
return false, ErrLockDenied
case syscall.ENOENT:
return false, ErrMissingParent
case syscall.EACCES:
return false, ErrNoPermission
}
}
return false, err
}
l.Lock = file
return true, nil
}
func (l *lockFile) write(data []byte) {
l.mu.Lock()
defer l.mu.Unlock()
l.errOnStaleLock()
_, err := l.Lock.Write(data)
if err != nil {
log.Fatalf("Write error: %s\n", err)
}
}
func (l *lockFile) commit() {
l.mu.Lock()
defer l.mu.Unlock()
l.errOnStaleLock()
err := l.Lock.Close()
if err != nil {
log.Fatalf("Err closing file: %s\n", err)
}
err = os.Rename(l.LockPath, l.FilePath)
if err != nil {
log.Fatalf("Err renaming file: %s\n", err)
}
l.Lock = nil
}
func (l *lockFile) rollback() error {
l.mu.Lock()
defer l.mu.Unlock()
err := os.Remove(l.LockPath)
if err != nil {
return err
}
l.Lock = nil
return nil
}
func (l *lockFile) errOnStaleLock() {
if l.Lock == nil {
log.Fatalf("Err: %s\nNot holding lock on file: %s", ErrStaleLock, l.LockPath)
}
}