-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit-prep-directory.go
79 lines (66 loc) · 2.03 KB
/
git-prep-directory.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
package git
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// BuildDirectory holds the git rev and path to a cloned git repository. It also
// holds a cleanup function to safely remove this directory.
type BuildDirectory struct {
Name string
Dir string
Cleanup func()
}
// PrepBuildDirectory clones a given repository and checks out the given
// revision, setting the timestamp of all files to their commit time and putting
// all submodules into a submodule cache.
func PrepBuildDirectory(gitDir, remote, ref string, timeout time.Duration, messages io.Writer) (*BuildDirectory, error) {
start := time.Now()
defer func() {
fmt.Fprintf(messages, "Took %v to prep %v", time.Since(start), remote)
}()
if strings.HasPrefix(remote, "github.com/") {
remote = "https://" + remote
}
gitDir, err := filepath.Abs(gitDir)
if err != nil {
return nil, fmt.Errorf("unable to determine abspath: %v", err)
}
err = LocalMirror(remote, gitDir, ref, timeout, messages)
if err != nil {
return nil, fmt.Errorf("unable to LocalMirror: %v", err)
}
rev, err := RevParse(gitDir, ref)
if err != nil {
return nil, fmt.Errorf("unable to parse rev: %v", err)
}
tagName, err := Describe(gitDir, rev)
if err != nil {
return nil, fmt.Errorf("unable to describe %v: %v", rev, err)
}
shortRev := rev[:10]
checkoutPath := path.Join(gitDir, filepath.Join("c/", shortRev))
err = RecursiveCheckout(gitDir, checkoutPath, rev, timeout, messages)
if err != nil {
return nil, err
}
cleanup := func() {
err := SafeCleanup(checkoutPath)
if err != nil {
fmt.Fprintln(messages, "Error cleaning up path:", checkoutPath)
}
}
return &BuildDirectory{tagName, checkoutPath, cleanup}, nil
}
// SafeCleanup recursively removes all files from a given path, which has to be
// a subfolder of the current working directory.
func SafeCleanup(path string) error {
if path == "/" || path == "" || path == "." || strings.Contains(path, "..") {
return fmt.Errorf("invalid path specified for deletion %q", path)
}
return os.RemoveAll(path)
}