-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock.go
More file actions
50 lines (37 loc) · 813 Bytes
/
lock.go
File metadata and controls
50 lines (37 loc) · 813 Bytes
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
package fskv
import (
"bytes"
"errors"
"github.com/spf13/afero"
"math/rand"
"strconv"
)
// ErrLocked returned in case is key locked for modifications
var ErrLocked = errors.New("Locked")
type lock struct {
path string
id []byte
}
func getLock(fs afero.Fs, path string) (*lock, error) {
lockFile := path + ".lock"
exists, err := afero.Exists(fs, lockFile)
if err == nil && exists {
return nil, ErrLocked
}
id := []byte(strconv.FormatUint(rand.Uint64(), 10))
err = afero.WriteFile(fs, lockFile, id, 0777)
if err != nil {
return nil, err
}
return &lock{path: lockFile, id: id}, nil
}
func (l *lock) unlock(fs afero.Fs) error {
id, err := afero.ReadFile(fs, l.path)
if err != nil {
return err
}
if !bytes.Equal(l.id, id) {
return ErrLocked
}
return fs.RemoveAll(l.path)
}