-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathsourceref.go
71 lines (61 loc) · 1.92 KB
/
sourceref.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
package app
import (
"fmt"
"net/url"
"github.com/openshift/origin/pkg/generate/git"
)
// SourceRefGenerator generates new SourceRefs either from a URL or a Directory
//
// Generators for SourceRef
// - Git URL -> SourceRef
// - Directory -> SourceRef
type SourceRefGenerator struct {
repository git.Repository
}
// NewSourceRefGenerator creates a new SourceRefGenerator
func NewSourceRefGenerator() *SourceRefGenerator {
return &SourceRefGenerator{
repository: git.NewRepository(),
}
}
// FromGitURL creates a SourceRef from a Git URL.
// If the URL includes a hash, it is used for the SourceRef's branch
// reference. Otherwise, 'master' is assumed
func (g *SourceRefGenerator) FromGitURL(location, contextDir string) (*SourceRef, error) {
url, err := url.Parse(location)
if err != nil {
return nil, err
}
ref := url.Fragment
url.Fragment = ""
if len(ref) == 0 {
ref = "master"
}
return &SourceRef{URL: url, Ref: ref, ContextDir: contextDir}, nil
}
// FromDirectory creates a SourceRef from a directory that contains
// a git repository. The URL is obtained from the origin remote branch, and
// the reference is taken from the currently checked out branch.
func (g *SourceRefGenerator) FromDirectory(directory string) (*SourceRef, error) {
// Make sure that this is a git directory
gitRoot, err := g.repository.GetRootDir(directory)
if err != nil {
return nil, fmt.Errorf("could not obtain git repository root for %s, the directory may not be part of a valid source repository", directory)
}
// Get URL
location, ok, err := g.repository.GetOriginURL(gitRoot)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("no origin remote defined for the provided Git repository")
}
// Get Branch Ref
ref := g.repository.GetRef(gitRoot)
srcRef, err := g.FromGitURL(fmt.Sprintf("%s#%s", location, ref), directory)
if err != nil {
return nil, err
}
srcRef.Dir = gitRoot
return srcRef, nil
}