github.com/vchain-us/vcn@v0.9.11-0.20210921212052-a2484d23c0b3/pkg/extractor/git/git.go (about) 1 /* 2 * Copyright (c) 2018-2020 vChain, Inc. All Rights Reserved. 3 * This software is released under GPL3. 4 * The full license information can be found under: 5 * https://www.gnu.org/licenses/gpl-3.0.en.html 6 * 7 */ 8 9 package git 10 11 import ( 12 "path/filepath" 13 "strings" 14 15 git "gopkg.in/src-d/go-git.v4" 16 17 "github.com/vchain-us/vcn/pkg/api" 18 "github.com/vchain-us/vcn/pkg/extractor" 19 "github.com/vchain-us/vcn/pkg/uri" 20 ) 21 22 // Scheme for git 23 const Scheme = "git" 24 25 // Artifact returns a git *api.Artifact from a given u 26 func Artifact(u *uri.URI, options ...extractor.Option) ([]*api.Artifact, error) { 27 28 if u.Scheme != Scheme { 29 return nil, nil 30 } 31 32 path := strings.TrimPrefix(u.Opaque, "//") 33 path, err := filepath.Abs(path) 34 if err != nil { 35 return nil, err 36 } 37 38 repo, err := git.PlainOpen(path) 39 if err != nil { 40 return nil, err 41 } 42 43 commit, err := lastCommit(repo) 44 if err != nil { 45 return nil, err 46 } 47 48 hash, size, err := digestCommit(*commit) 49 if err != nil { 50 return nil, err 51 } 52 53 // Metadata container 54 m := api.Metadata{ 55 Scheme: map[string]interface{}{ 56 "Commit": commit.Hash.String(), 57 "Tree": commit.TreeHash.String(), 58 "Parents": func() []string { 59 res := make([]string, len(commit.ParentHashes)) 60 for i, h := range commit.ParentHashes { 61 res[i] = h.String() 62 } 63 return res 64 }(), 65 "Author": commit.Author, 66 "Committer": commit.Committer, 67 "Message": commit.Message, 68 "PGPSignature": commit.PGPSignature, 69 }, 70 } 71 72 name := filepath.Base(path) 73 if remotes, err := repo.Remotes(); err == nil && len(remotes) > 0 { 74 urls := remotes[0].Config().URLs 75 if len(urls) > 0 { 76 name = urls[0] 77 } 78 } 79 name += "@" + commit.Hash.String()[:7] 80 81 return []*api.Artifact{{ 82 Kind: Scheme, 83 Hash: hash, 84 Size: size, 85 Name: name, 86 Metadata: m, 87 }}, nil 88 }