|
1 | | -// +build !norwfs |
2 | | - |
3 | 1 | package dotgit |
4 | 2 |
|
5 | 3 | import ( |
| 4 | + "fmt" |
6 | 5 | "os" |
7 | 6 |
|
8 | 7 | "gopkg.in/src-d/go-git.v4/plumbing" |
9 | 8 | "gopkg.in/src-d/go-git.v4/utils/ioutil" |
| 9 | + |
| 10 | + "gopkg.in/src-d/go-billy.v4" |
10 | 11 | ) |
11 | 12 |
|
12 | 13 | func (d *DotGit) setRef(fileName, content string, old *plumbing.Reference) (err error) { |
| 14 | + if billy.CapabilityCheck(d.fs, billy.ReadAndWriteCapability) { |
| 15 | + return d.setRefRwfs(fileName, content, old) |
| 16 | + } |
| 17 | + |
| 18 | + return d.setRefNorwfs(fileName, content, old) |
| 19 | +} |
| 20 | + |
| 21 | +func (d *DotGit) setRefRwfs(fileName, content string, old *plumbing.Reference) (err error) { |
13 | 22 | // If we are not checking an old ref, just truncate the file. |
14 | 23 | mode := os.O_RDWR | os.O_CREATE |
15 | 24 | if old == nil { |
@@ -41,3 +50,41 @@ func (d *DotGit) setRef(fileName, content string, old *plumbing.Reference) (err |
41 | 50 | _, err = f.Write([]byte(content)) |
42 | 51 | return err |
43 | 52 | } |
| 53 | + |
| 54 | +// There are some filesystems that don't support opening files in RDWD mode. |
| 55 | +// In these filesystems the standard SetRef function can not be used as it |
| 56 | +// reads the reference file to check that it's not modified before updating it. |
| 57 | +// |
| 58 | +// This version of the function writes the reference without extra checks |
| 59 | +// making it compatible with these simple filesystems. This is usually not |
| 60 | +// a problem as they should be accessed by only one process at a time. |
| 61 | +func (d *DotGit) setRefNorwfs(fileName, content string, old *plumbing.Reference) error { |
| 62 | + _, err := d.fs.Stat(fileName) |
| 63 | + if err == nil && old != nil { |
| 64 | + fRead, err := d.fs.Open(fileName) |
| 65 | + if err != nil { |
| 66 | + return err |
| 67 | + } |
| 68 | + |
| 69 | + ref, err := d.readReferenceFrom(fRead, old.Name().String()) |
| 70 | + fRead.Close() |
| 71 | + |
| 72 | + if err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + |
| 76 | + if ref.Hash() != old.Hash() { |
| 77 | + return fmt.Errorf("reference has changed concurrently") |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + f, err := d.fs.Create(fileName) |
| 82 | + if err != nil { |
| 83 | + return err |
| 84 | + } |
| 85 | + |
| 86 | + defer f.Close() |
| 87 | + |
| 88 | + _, err = f.Write([]byte(content)) |
| 89 | + return err |
| 90 | +} |
0 commit comments