github.com/grantbow/fit@v0.7.1-0.20220916164603-1f7c88ac81e6/scm/Detect.go (about)

     1  package scm
     2  
     3  import (
     4  	"errors"
     5  	bugs "github.com/grantbow/fit/issues"
     6  	"os"
     7  	"strings"
     8  )
     9  
    10  //var dops = bugs.Directory(os.PathSeparator)
    11  //var sops = string(os.PathSeparator)
    12  
    13  // SCMNotFound type returned by Error
    14  type SCMNotFound struct {
    15  	s string
    16  }
    17  
    18  func (e *SCMNotFound) Error() string {
    19  	return e.s
    20  }
    21  
    22  // SCMDirty type returned by Error
    23  type SCMDirty struct {
    24  	s string
    25  }
    26  
    27  func (e *SCMDirty) Error() string {
    28  	return e.s
    29  }
    30  
    31  func walkAndSearch(startpath string, dirnames []string) (fullpath, scmtype string) {
    32  	for _, scmtype := range dirnames {
    33  		if dirinfo, err := os.Stat(startpath + sops + scmtype); err == nil && dirinfo.IsDir() {
    34  			return startpath + sops + scmtype, scmtype
    35  		}
    36  	}
    37  
    38  	pieces := strings.Split(startpath, sops)
    39  
    40  	for i := len(pieces); i > 0; i -= 1 {
    41  		dir := strings.Join(pieces[0:i], sops)
    42  		for _, scmtype := range dirnames {
    43  			if dirinfo, err := os.Stat(dir + sops + scmtype); err == nil && dirinfo.IsDir() {
    44  				return dir + sops + scmtype, scmtype
    45  			}
    46  		}
    47  	}
    48  	return "", ""
    49  }
    50  
    51  // DetectSCM takes options and returns an SCMHandler and directory.
    52  func DetectSCM(options map[string]bool, config bugs.Config) (SCMHandler, bugs.Directory, error) {
    53  	// First look for an SCM directory
    54  	wd, _ := os.Getwd()
    55  
    56  	dirFound, scmtype := walkAndSearch(wd, []string{".git", ".hg"})
    57  	if dirFound != "" && scmtype == ".git" {
    58  		var gm GitManager
    59  		if val, ok := options["autoclose"]; ok {
    60  			gm.Autoclose = val
    61  		}
    62  		if val, ok := options["use_bug_prefix"]; ok {
    63  			gm.UseBugPrefix = val
    64  		}
    65  		return gm, bugs.Directory(dirFound), nil
    66  	}
    67  	if dirFound != "" && scmtype == ".hg" {
    68  		return HgManager{}, bugs.Directory(dirFound), nil
    69  	}
    70  
    71  	return nil, "", errors.New("No SCM found")
    72  }