Skip to content

Commit 2380a5c

Browse files
committed
remove lock timeout, add test for lock
1 parent a531bd6 commit 2380a5c

File tree

2 files changed

+55
-3
lines changed

2 files changed

+55
-3
lines changed

sicher.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import (
1616
"path/filepath"
1717
"reflect"
1818
"regexp"
19-
"time"
2019

2120
"github.com/juju/fslock"
2221
)
@@ -194,12 +193,14 @@ func (s *sicher) Edit(editor ...string) error {
194193

195194
// lock file to enable only one edit at a time
196195
credFileLock := fslock.New(credFile.Name()) //newFileLock(credFile)
197-
err = credFileLock.LockWithTimeout(time.Second * 10)
196+
err = credFileLock.TryLock()
198197
if err != nil {
198+
if err == fslock.ErrLocked {
199+
return fmt.Errorf("%s: File is in use in another terminal", err)
200+
}
199201
return fmt.Errorf("error locking file: %s", err)
200202
}
201203
defer credFileLock.Unlock()
202-
203204
var buf bytes.Buffer
204205
_, err = io.Copy(&buf, credFile)
205206
if err != nil {

sicher_test.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"os/exec"
88
"path/filepath"
99
"strings"
10+
"sync"
1011
"testing"
1112
)
1213

@@ -95,6 +96,56 @@ func TestEditSuccess(t *testing.T) {
9596
os.Remove(gitPath)
9697
})
9798
}
99+
func TestEditFileLock(t *testing.T) {
100+
oldExecCmd := execCmd
101+
defer func() { execCmd = oldExecCmd }()
102+
s, encPath, keyPath := setupTest()
103+
104+
s.Initialize(os.Stdin)
105+
buf := bytes.Buffer{}
106+
107+
execCmd = func(cmd string, args ...string) *exec.Cmd {
108+
stdIn, stdOut, stdErr = &buf, &buf, &buf
109+
110+
if cmd != "vim" {
111+
t.Errorf("Expected command to be vim, got %s", cmd)
112+
}
113+
return exec.Command("cat", args...)
114+
}
115+
116+
var wg sync.WaitGroup
117+
chErr := make(chan error, 1)
118+
for i := 0; i < 2; i++ {
119+
wg.Add(1)
120+
go func() {
121+
err := s.Edit("vim")
122+
if err != nil {
123+
chErr <- err
124+
}
125+
wg.Done()
126+
}()
127+
}
128+
129+
wg.Wait()
130+
131+
select {
132+
case err := <-chErr:
133+
if err == nil {
134+
t.Errorf("Expected file to be locked and exit error, got nil error")
135+
}
136+
default:
137+
t.Errorf("Expected file to be locked and exit error, received no error")
138+
}
139+
140+
// get path to the gitignore file and cleanup
141+
gitPath := strings.Replace(encPath, fmt.Sprintf("%s.enc", s.Environment), ".gitignore", 1)
142+
143+
t.Cleanup(func() {
144+
os.Remove(encPath)
145+
os.Remove(keyPath)
146+
os.Remove(gitPath)
147+
})
148+
}
98149

99150
func TestEditFail(t *testing.T) {
100151
oldExecCmd := execCmd

0 commit comments

Comments
 (0)