-
Notifications
You must be signed in to change notification settings - Fork 0
/
restore.go
54 lines (44 loc) · 1.24 KB
/
restore.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
package git
import (
"fmt"
"strings"
)
// RestoreUsing will restore a given set of files back to their previous
// known state within the current repository (working directory). By
// inspecting each files [FileStatus], the correct decision can be made
// when restoring it
func (c *Client) RestoreUsing(statuses []FileStatus) error {
for _, status := range statuses {
var err error
if status.Untracked() {
err = c.removeUntrackedFile(status.Path)
} else if status.Modified() {
err = c.restoreFile(status)
} else if status.Renamed() {
err = c.undoRenamedFile(status.Path)
}
if err != nil {
return err
}
}
return nil
}
func (c *Client) removeUntrackedFile(pathspec string) error {
_, err := c.Exec("git clean --force -- " + pathspec)
return err
}
func (c *Client) restoreFile(status FileStatus) error {
var buf strings.Builder
buf.WriteString("git restore ")
if status.Indicators[0] == Modified {
buf.WriteString("--staged --worktree ")
}
buf.WriteString(status.Path)
_, err := c.Exec(buf.String())
return err
}
func (c *Client) undoRenamedFile(pathspec string) error {
original, renamed, _ := strings.Cut(pathspec, porcelainRenameSeparator)
_, err := c.Exec(fmt.Sprintf("git mv %s %s", renamed, original))
return err
}