github.com/kubesphere/s2irun@v3.2.1+incompatible/pkg/scm/git/testhelpers.go (about)

     1  package git
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/kubesphere/s2irun/pkg/utils/cmd"
     9  	"github.com/kubesphere/s2irun/pkg/utils/cygpath"
    10  )
    11  
    12  // CreateLocalGitDirectory creates a git directory with a commit
    13  func CreateLocalGitDirectory() (string, error) {
    14  	cr := cmd.NewCommandRunner()
    15  
    16  	dir, err := CreateEmptyLocalGitDirectory()
    17  	if err != nil {
    18  		return "", err
    19  	}
    20  
    21  	f, err := os.Create(filepath.Join(dir, "testfile"))
    22  	if err != nil {
    23  		return "", err
    24  	}
    25  	f.Close()
    26  
    27  	err = cr.RunWithOptions(cmd.CommandOpts{Dir: dir}, "git", "add", ".")
    28  	if err != nil {
    29  		return "", err
    30  	}
    31  
    32  	err = cr.RunWithOptions(cmd.CommandOpts{Dir: dir, EnvAppend: []string{"GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@test", "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@test"}}, "git", "commit", "-m", "testcommit")
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  
    37  	return dir, nil
    38  }
    39  
    40  // CreateEmptyLocalGitDirectory creates a git directory with no checkin yet
    41  func CreateEmptyLocalGitDirectory() (string, error) {
    42  	cr := cmd.NewCommandRunner()
    43  
    44  	dir, err := ioutil.TempDir(os.TempDir(), "gitdir-s2i-test")
    45  	if err != nil {
    46  		return "", err
    47  	}
    48  
    49  	err = cr.RunWithOptions(cmd.CommandOpts{Dir: dir}, "git", "init")
    50  	if err != nil {
    51  		return "", err
    52  	}
    53  
    54  	return dir, nil
    55  }
    56  
    57  // CreateLocalGitDirectoryWithSubmodule creates a git directory with a submodule
    58  func CreateLocalGitDirectoryWithSubmodule() (string, error) {
    59  	cr := cmd.NewCommandRunner()
    60  
    61  	submodule, err := CreateLocalGitDirectory()
    62  	if err != nil {
    63  		return "", err
    64  	}
    65  	defer os.RemoveAll(submodule)
    66  
    67  	if cygpath.UsingCygwinGit {
    68  		var err error
    69  		submodule, err = cygpath.ToSlashCygwin(submodule)
    70  		if err != nil {
    71  			return "", err
    72  		}
    73  	}
    74  
    75  	dir, err := CreateEmptyLocalGitDirectory()
    76  	if err != nil {
    77  		return "", err
    78  	}
    79  
    80  	err = cr.RunWithOptions(cmd.CommandOpts{Dir: dir}, "git", "submodule", "add", submodule, "submodule")
    81  	if err != nil {
    82  		return "", err
    83  	}
    84  
    85  	return dir, nil
    86  }