Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.

Repository API for creating references #486

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package git

import (
"errors"
"strings"

"gopkg.in/src-d/go-git.v4/config"
"gopkg.in/src-d/go-git.v4/plumbing"
Expand Down Expand Up @@ -310,3 +311,39 @@ func (o *CommitOptions) Validate(r *Repository) error {

return nil
}

const (
refPrefix = "refs/"
refHeadPrefix = refPrefix + "heads/"
)

var (
ErrBranchNameNotProvided = errors.New("branch name should be provided")
)

// BranchOptions describes how a branch operation should be performed.
type BranchOptions struct {
// Name of the branch.
Name string
// Start point of the branch, by default is repository HEAD
StartPoint plumbing.Hash
}

// Validate validates the fields and sets the default values.
func (o *BranchOptions) Validate(r *Repository) error {
if o.Name == "" {
return ErrBranchNameNotProvided
}
if !strings.HasPrefix(o.Name, refHeadPrefix) {
o.Name = refHeadPrefix + o.Name
}

if o.StartPoint == plumbing.ZeroHash {
head, err := r.Reference(plumbing.HEAD, true)
if err != nil {
return err
}
o.StartPoint = head.Hash()
}
return nil
}
10 changes: 10 additions & 0 deletions repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,16 @@ func (r *Repository) Branches() (storer.ReferenceIter, error) {
}, refIter), nil
}

// CreateBranch creates a new branch.
func (r *Repository) CreateBranch(o *BranchOptions) (*plumbing.Reference, error) {
if err := o.Validate(r); err != nil {
return nil, err
}
n := plumbing.ReferenceName(o.Name)
b := plumbing.NewHashReference(n, o.StartPoint)
return b, r.Storer.SetReference(b)
}

// Notes returns all the References that are Branches.
func (r *Repository) Notes() (storer.ReferenceIter, error) {
refIter, err := r.Storer.IterReferences()
Expand Down