Beispiel #1
0
// Switch a repository to the empty branch, which will be created
// if it does not exist.
func switchToEmptyBranch(r *git.Repo) error {
	contents := bytes.NewBufferString("This branch intentionally left blank\n")
	readme := filepath.Join(r.WorkDir, "README.empty-branch")
	if ref, err := r.Ref("empty-branch"); err == nil {
		return ref.Checkout()
	}
	cmd, _, _ := r.Git("checkout", "--orphan", "empty-branch")
	if cmd.Run() != nil {
		return fmt.Errorf("Could not create empty-branch")
	}
	cmd, _, _ = r.Git("rm", "-r", "--cached", ".")
	if cmd.Run() != nil {
		return fmt.Errorf("Could not remove index from empty-branch")
	}
	cmd, _, _ = r.Git("clean", "-f", "-x", "-d")
	if cmd.Run() != nil {
		return fmt.Errorf("Could not clean working tree for empty-branch")
	}
	if ioutil.WriteFile(readme, contents.Bytes(), os.FileMode(0644)) != nil {
		return fmt.Errorf("Could not create README.empty-branch")
	}
	cmd, _, _ = r.Git("add", "README.empty-branch")
	if cmd.Run() != nil {
		return fmt.Errorf("Could not add README.empty-branch to empty-branch")
	}
	cmd, _, _ = r.Git("commit", "-m", "Created empty branch.")
	if cmd.Run() != nil {
		return fmt.Errorf("Could not create initial commit to empty-branch")
	}
	return nil
}
// Make commit and rollback functions for a specific repo where we will
// be messing with the branches.
func branchCheckpointer(r *git.Repo) (commit, rollback func(chan<- bool)) {
	// We only care about branch refernces, and we only want to save
	// the SHA references to the branches.
	refs := make(map[string]string)
	for _, ref := range r.Branches() {
		refs[ref.Name()] = ref.SHA
	}
	// There is no commit action.
	commit = noopCommit
	// On rollback, force all the branches back to where we were.
	rollback = func(c chan<- bool) {
		res := true
		for name, sha := range refs {
			cmd, _, _ := r.Git("branch", "-f", name, sha)
			res = res && (cmd.Run() == nil)
		}
		c <- res

	}
	return
}