github.com/Rookout/GoSDK@v0.1.48/pkg/information/git.go (about)

     1  package information
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  	"regexp"
     8  	"strings"
     9  
    10  	"github.com/Rookout/GoSDK/pkg/logger"
    11  )
    12  
    13  const (
    14  	_GIT_FOLDER = ".git"
    15  	_GIT_HEAD   = "HEAD"
    16  	_GIT_CONFIG = "config"
    17  )
    18  
    19  var r = regexp.MustCompile("\\[remote \"origin\"]\\s*url\\s*=\\s(?P<url>\\S*)")
    20  
    21  func isGit(path string) bool {
    22  	return isDir(filepath.Join(path, _GIT_FOLDER))
    23  }
    24  
    25  func isDir(path string) bool {
    26  	if pathAbs, err := filepath.Abs(path); err == nil {
    27  		if fileInfo, err := os.Stat(pathAbs); !os.IsNotExist(err) && fileInfo.IsDir() {
    28  			return true
    29  		}
    30  	}
    31  	return false
    32  }
    33  
    34  func FindRoot(strPath string) string {
    35  	if isGit(strPath) {
    36  		return strPath
    37  	} else {
    38  		parentPath := filepath.Dir(strPath)
    39  		if parentPath == strPath {
    40  			return ""
    41  		}
    42  		return FindRoot(parentPath)
    43  	}
    44  }
    45  
    46  func followSymLinks(root string, link string) string {
    47  	content := ""
    48  	fileContent, err := ioutil.ReadFile(filepath.Join(root, link))
    49  	content = string(fileContent)
    50  	if err != nil {
    51  		logger.Logger().WithError(err).Debugln("Error reading git information from file system")
    52  	}
    53  	if strings.HasPrefix(content, "ref:") {
    54  		splitContent := strings.Split(content, " ")
    55  		if len(splitContent) > 1 {
    56  			nextLink := strings.TrimSpace(splitContent[1])
    57  			return followSymLinks(root, nextLink)
    58  		}
    59  	}
    60  	return strings.TrimSpace(content)
    61  }
    62  
    63  func GetRevision(path string) string {
    64  	return followSymLinks(filepath.Join(path, _GIT_FOLDER), _GIT_HEAD)
    65  }
    66  
    67  func GetRemoteOrigin(path string) string {
    68  	content := ""
    69  	fileContent, err := ioutil.ReadFile(filepath.Join(path, _GIT_FOLDER, _GIT_CONFIG))
    70  	content = string(fileContent)
    71  	if err != nil {
    72  		logger.Logger().Debugf("Error reading git config from file system: %s", err)
    73  		return ""
    74  	}
    75  
    76  	matches := r.FindStringSubmatch(content)
    77  	urlIndex := r.SubexpIndex("url")
    78  	if urlIndex < len(matches) {
    79  		return matches[urlIndex]
    80  	} else {
    81  		return ""
    82  	}
    83  }