-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlock.go
111 lines (89 loc) · 2.47 KB
/
lock.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
package gitdb
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/bouggo/log"
)
func (g *gitdb) Lock(mo Model) error {
m := wrap(mo)
if _, ok := mo.(LockableModel); !ok {
return errors.New("Model is not lockable")
}
var lockFilesWritten []string
fullPath := g.lockDir(m)
if _, err := os.Stat(fullPath); err != nil {
err := os.MkdirAll(fullPath, 0755)
if err != nil {
return err
}
}
lockFiles := mo.(LockableModel).GetLockFileNames()
for _, file := range lockFiles {
lockFile := filepath.Join(fullPath, file+".lock")
g.events <- newWriteBeforeEvent("...", lockFile)
//when locking a model, lockfile should not exist
if _, err := os.Stat(lockFile); err == nil {
if derr := g.deleteLockFiles(lockFilesWritten); derr != nil {
log.Error(derr.Error())
}
return errors.New("Lock file already exist: " + lockFile)
}
err := ioutil.WriteFile(lockFile, []byte(""), 0644)
if err != nil {
if derr := g.deleteLockFiles(lockFilesWritten); derr != nil {
log.Error(derr.Error())
}
return errors.New("Failed to write lock " + lockFile + ": " + err.Error())
}
lockFilesWritten = append(lockFilesWritten, lockFile)
}
g.commit.Add(1)
commitMsg := "Created Lock Files for: " + ID(m)
g.events <- newWriteEvent(commitMsg, fullPath, g.autoCommit)
//block here until write has been committed
g.waitForCommit()
return nil
}
func (g *gitdb) Unlock(mo Model) error {
m := wrap(mo)
if _, ok := mo.(LockableModel); !ok {
return errors.New("Model is not lockable")
}
fullPath := g.lockDir(m)
lockFiles := mo.(LockableModel).GetLockFileNames()
for _, file := range lockFiles {
lockFile := filepath.Join(fullPath, file+".lock")
if _, err := os.Stat(lockFile); err == nil {
//log.PutInfo("Removing " + lockFile)
err := os.Remove(lockFile)
if err != nil {
return errors.New("Could not delete lock file: " + lockFile)
}
}
}
g.commit.Add(1)
commitMsg := "Removing Lock Files for: " + ID(m)
g.events <- newWriteEvent(commitMsg, fullPath, g.autoCommit)
//block here until write has been committed
g.waitForCommit()
return nil
}
func (g *gitdb) deleteLockFiles(files []string) error {
var err error
var failedDeletes []string
if len(files) > 0 {
for _, file := range files {
err = os.Remove(file)
if err != nil {
failedDeletes = append(failedDeletes, file)
}
}
}
if len(failedDeletes) > 0 {
return errors.New("Could not delete lock files: " + strings.Join(failedDeletes, ","))
}
return err
}