Adding a Helpers Package
In this lesson, we'll create another package that will contain some general utility function that is useful across the board and is not specific to multi-git. It is a good idea to separate this package and possibly share it so it can be imported by other projects.
We'll cover the following
The helpers package
In addition to the repo_manager
package, let’s add a little helpers package. This package will contain some general functions that can be used later by various tests. Multi-git deals with files and directories managed by git. Two useful functions are CreateDir()
and AddFiles()
.
The CreateDir()
function creates a directory and optionally initializes git in that directory:
func CreateDir(baseDir string, name string, initGit bool) (err error) {
dirName := path.Join(baseDir, name)
err = os.MkdirAll(dirName, os.ModePerm)
if err != nil {
return
}
if !initGit {
return
}
currDir, err := os.Getwd()
if err != nil {
return
}
defer os.Chdir(currDir)
os.Chdir(dirName)
err = exec.Command("git", "init").Run()
return
}
The AddFiles()
function just adds files with some canned content to populate a directory that can be used to test git operations later. Note the signature with the three dots for the filenames argument. This is the Go syntax for an arbitrary number of arguments:
func AddFiles(baseDir string,
dirName string,
commit bool,
filenames ... string) (err error) {
First, AddFiles()
iterates over all the filenames and writes the input data to each file in the target directory:
for _, f := range filenames {
data := []byte("data for" + f)
err = ioutil.WriteFile(path.Join(dir, f), data, 0777)
if err != nil {
return
}
}
If the commit
argument is false
, it just bails out.
if !commit {
return
}
if commit
is true
, then it adds all the files in the directory to git and commit them:
if err != nil {
return
}
defer os.Chdir(currDir)
os.Chdir(dir)
err = exec.Command("git", "add", "-A").Run()
if err != nil {
return
}
err = exec.Command("git", "commit", "-m", "added some files...").Run()
return
}
Verifying everything works
We don’t have automated tests yet, but, we still need to verify that multi-git works after the refactoring. We will do that by running manual acceptance tests. The shell script main.sh
below relies on pre.sh
to pull the code for multi-git v0.2, build it, create a couple of test repos, and set up the environment variables, MG_ROOT
and MG_REPOS
that multi-git
requires.
Then, main.sh
initializes the directories, adds a file to each directory, commits the files, and checks the log. All commands are performed on repositories.
Get hands-on with 1200+ tech skills courses.