forked from MediaMath/grim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github_archive.go
86 lines (69 loc) · 2.15 KB
/
github_archive.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
package grim
// Copyright 2015 MediaMath <http://www.mediamath.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import (
"fmt"
"io/ioutil"
"mime"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func cloneRepo(token string, workspacePath string, clonePath string, owner string, repo string, ref string, timeOut time.Duration) (string, error) {
archive, err := downloadRepo(token, owner, repo, ref, workspacePath)
if err != nil {
return "", err
}
return unarchiveRepo(archive, workspacePath, clonePath, timeOut)
}
func unarchiveRepo(file, workspacePath, clonePath string, timeOut time.Duration) (string, error) {
tarPath, err := exec.LookPath("tar")
if err != nil {
return "", err
}
finalName := filepath.Join(workspacePath, clonePath)
if mkErr := os.MkdirAll(finalName, 0700); mkErr != nil {
return "", fmt.Errorf("Could not make path %s: %v", finalName, mkErr)
}
//extracts the folder into the finalName directory pulling off the top level folder
//will break if github starts returning a different tar format
result, err := execute(nil, workspacePath, tarPath, timeOut, "-xvf", file, "-C", finalName, "--strip-components=1")
if err != nil {
return "", err
}
if result.ExitCode != 0 {
return "", fmt.Errorf("extract archive failed: %v %v", result.ExitCode, strings.TrimSpace(result.Output))
}
return finalName, nil
}
func downloadRepo(token, owner, repo, ref string, location string) (string, error) {
client, err := getClientForToken(token)
if err != nil {
return "", err
}
u := fmt.Sprintf("repos/%s/%s/tarball/%s", owner, repo, ref)
req, err := client.NewRequest("GET", u, nil)
if err != nil {
return "", err
}
temp, err := ioutil.TempFile(location, "download")
if err != nil {
return "", err
}
resp, err := client.Do(req, temp)
temp.Close()
if err != nil {
return "", err
}
_, params, err := mime.ParseMediaType(resp.Response.Header["Content-Disposition"][0])
if err != nil {
return "", err
}
fileName := params["filename"]
downloaded := filepath.Join(location, fileName)
os.Rename(temp.Name(), downloaded)
return downloaded, nil
}