chore(deps): bump github.com/go-git/go-git/v5 from 5.11.0 to 5.12.0

Bumps [github.com/go-git/go-git/v5](https://github.com/go-git/go-git) from 5.11.0 to 5.12.0.
- [Release notes](https://github.com/go-git/go-git/releases)
- [Commits](https://github.com/go-git/go-git/compare/v5.11.0...v5.12.0)

---
updated-dependencies:
- dependency-name: github.com/go-git/go-git/v5
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot]
2024-04-01 22:13:25 +00:00
committed by GitHub
parent 7908a678df
commit 710eb46173
79 changed files with 1038 additions and 456 deletions

View File

@@ -27,14 +27,14 @@ compatibility status with go-git.
## Branching and merging
| Feature | Sub-feature | Status | Notes | Examples |
| ----------- | ----------- | ------ | --------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `branch` | | ✅ | | - [branch](_examples/branch/main.go) |
| `checkout` | | ✅ | Basic usages of checkout are supported. | - [checkout](_examples/checkout/main.go) |
| `merge` | | ❌ | | |
| `mergetool` | | ❌ | | |
| `stash` | | ❌ | | |
| `tag` | | ✅ | | - [tag](_examples/tag/main.go) <br/> - [tag create and push](_examples/tag-create-push/main.go) |
| Feature | Sub-feature | Status | Notes | Examples |
| ----------- | ----------- | ------------ | --------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `branch` | | ✅ | | - [branch](_examples/branch/main.go) |
| `checkout` | | ✅ | Basic usages of checkout are supported. | - [checkout](_examples/checkout/main.go) |
| `merge` | | ⚠️ (partial) | Fast-forward only | |
| `mergetool` | | ❌ | | |
| `stash` | | ❌ | | |
| `tag` | | ✅ | | - [tag](_examples/tag/main.go) <br/> - [tag create and push](_examples/tag-create-push/main.go) |
## Sharing and updating projects

View File

@@ -28,6 +28,7 @@ build-git:
test:
@echo "running against `git version`"; \
$(GOTEST) -race ./...
$(GOTEST) -v _examples/common_test.go _examples/common.go --examples
TEMP_REPO := $(shell mktemp)
test-sha256:

View File

@@ -89,6 +89,25 @@ type CloneOptions struct {
Shared bool
}
// MergeOptions describes how a merge should be performed.
type MergeOptions struct {
// Strategy defines the merge strategy to be used.
Strategy MergeStrategy
}
// MergeStrategy represents the different types of merge strategies.
type MergeStrategy int8
const (
// FastForwardMerge represents a Git merge strategy where the current
// branch can be simply updated to point to the HEAD of the branch being
// merged. This is only possible if the history of the branch being merged
// is a linear descendant of the current branch, with no conflicting commits.
//
// This is the default option.
FastForwardMerge MergeStrategy = iota
)
// Validate validates the fields and sets the default values.
func (o *CloneOptions) Validate() error {
if o.URL == "" {
@@ -166,7 +185,7 @@ const (
// AllTags fetch all tags from the remote (i.e., fetch remote tags
// refs/tags/* into local tags with the same name)
AllTags
//NoTags fetch no tags from the remote at all
// NoTags fetch no tags from the remote at all
NoTags
)
@@ -198,6 +217,9 @@ type FetchOptions struct {
CABundle []byte
// ProxyOptions provides info required for connecting to a proxy.
ProxyOptions transport.ProxyOptions
// Prune specify that local refs that match given RefSpecs and that do
// not exist remotely will be removed.
Prune bool
}
// Validate validates the fields and sets the default values.
@@ -324,9 +346,9 @@ var (
// CheckoutOptions describes how a checkout operation should be performed.
type CheckoutOptions struct {
// Hash is the hash of the commit to be checked out. If used, HEAD will be
// in detached mode. If Create is not used, Branch and Hash are mutually
// exclusive.
// Hash is the hash of a commit or tag to be checked out. If used, HEAD
// will be in detached mode. If Create is not used, Branch and Hash are
// mutually exclusive.
Hash plumbing.Hash
// Branch to be checked out, if Branch and Hash are empty is set to `master`.
Branch plumbing.ReferenceName
@@ -405,6 +427,11 @@ func (o *ResetOptions) Validate(r *Repository) error {
}
o.Commit = ref.Hash()
} else {
_, err := r.CommitObject(o.Commit)
if err != nil {
return fmt.Errorf("invalid reset option: %w", err)
}
}
return nil
@@ -474,6 +501,11 @@ type AddOptions struct {
// Glob adds all paths, matching pattern, to the index. If pattern matches a
// directory path, all directory contents are added to the index recursively.
Glob string
// SkipStatus adds the path with no status check. This option is relevant only
// when the `Path` option is specified and does not apply when the `All` option is used.
// Notice that when passing an ignored path it will be added anyway.
// When true it can speed up adding files to the worktree in very large repositories.
SkipStatus bool
}
// Validate validates the fields and sets the default values.
@@ -507,6 +539,10 @@ type CommitOptions struct {
// commit will not be signed. The private key must be present and already
// decrypted.
SignKey *openpgp.Entity
// Signer denotes a cryptographic signer to sign the commit with.
// A nil value here means the commit will not be signed.
// Takes precedence over SignKey.
Signer Signer
// Amend will create a new commit object and replace the commit that HEAD currently
// points to. Cannot be used with All nor Parents.
Amend bool

View File

@@ -116,7 +116,7 @@ func loadPatterns(fs billy.Filesystem, path string) (ps []Pattern, err error) {
return
}
// LoadGlobalPatterns loads gitignore patterns from from the gitignore file
// LoadGlobalPatterns loads gitignore patterns from the gitignore file
// declared in a user's ~/.gitconfig file. If the ~/.gitconfig file does not
// exist the function will return nil. If the core.excludesfile property
// is not declared, the function will return nil. If the file pointed to by
@@ -132,7 +132,7 @@ func LoadGlobalPatterns(fs billy.Filesystem) (ps []Pattern, err error) {
return loadPatterns(fs, fs.Join(home, gitconfigFile))
}
// LoadSystemPatterns loads gitignore patterns from from the gitignore file
// LoadSystemPatterns loads gitignore patterns from the gitignore file
// declared in a system's /etc/gitconfig file. If the /etc/gitconfig file does
// not exist the function will return nil. If the core.excludesfile property
// is not declared, the function will return nil. If the file pointed to by

View File

@@ -27,7 +27,7 @@ const (
// the commit with the "mergetag" header.
headermergetag string = "mergetag"
defaultUtf8CommitMesageEncoding MessageEncoding = "UTF-8"
defaultUtf8CommitMessageEncoding MessageEncoding = "UTF-8"
)
// Hash represents the hash of an object
@@ -189,7 +189,7 @@ func (c *Commit) Decode(o plumbing.EncodedObject) (err error) {
}
c.Hash = o.Hash()
c.Encoding = defaultUtf8CommitMesageEncoding
c.Encoding = defaultUtf8CommitMessageEncoding
reader, err := o.Reader()
if err != nil {
@@ -335,7 +335,7 @@ func (c *Commit) encode(o plumbing.EncodedObject, includeSig bool) (err error) {
}
}
if string(c.Encoding) != "" && c.Encoding != defaultUtf8CommitMesageEncoding {
if string(c.Encoding) != "" && c.Encoding != defaultUtf8CommitMessageEncoding {
if _, err = fmt.Fprintf(w, "\n%s %s", headerencoding, c.Encoding); err != nil {
return err
}

View File

@@ -57,6 +57,8 @@ func (c *commitPathIter) Next() (*Commit, error) {
}
func (c *commitPathIter) getNextFileCommit() (*Commit, error) {
var parentTree, currentTree *Tree
for {
// Parent-commit can be nil if the current-commit is the initial commit
parentCommit, parentCommitErr := c.sourceIter.Next()
@@ -68,13 +70,17 @@ func (c *commitPathIter) getNextFileCommit() (*Commit, error) {
parentCommit = nil
}
// Fetch the trees of the current and parent commits
currentTree, currTreeErr := c.currentCommit.Tree()
if currTreeErr != nil {
return nil, currTreeErr
if parentTree == nil {
var currTreeErr error
currentTree, currTreeErr = c.currentCommit.Tree()
if currTreeErr != nil {
return nil, currTreeErr
}
} else {
currentTree = parentTree
parentTree = nil
}
var parentTree *Tree
if parentCommit != nil {
var parentTreeErr error
parentTree, parentTreeErr = parentCommit.Tree()
@@ -115,7 +121,8 @@ func (c *commitPathIter) hasFileChange(changes Changes, parent *Commit) bool {
// filename matches, now check if source iterator contains all commits (from all refs)
if c.checkParent {
if parent != nil && isParentHash(parent.Hash, c.currentCommit) {
// Check if parent is beyond the initial commit
if parent == nil || isParentHash(parent.Hash, c.currentCommit) {
return true
}
continue

View File

@@ -6,7 +6,7 @@ import (
"errors"
"fmt"
"io"
"math"
"strconv"
"strings"
"github.com/go-git/go-git/v5/plumbing"
@@ -234,69 +234,56 @@ func (fileStats FileStats) String() string {
return printStat(fileStats)
}
// printStat prints the stats of changes in content of files.
// Original implementation: https://github.com/git/git/blob/1a87c842ece327d03d08096395969aca5e0a6996/diff.c#L2615
// Parts of the output:
// <pad><filename><pad>|<pad><changeNumber><pad><+++/---><newline>
// example: " main.go | 10 +++++++--- "
func printStat(fileStats []FileStat) string {
padLength := float64(len(" "))
newlineLength := float64(len("\n"))
separatorLength := float64(len("|"))
// Soft line length limit. The text length calculation below excludes
// length of the change number. Adding that would take it closer to 80,
// but probably not more than 80, until it's a huge number.
lineLength := 72.0
maxGraphWidth := uint(53)
maxNameLen := 0
maxChangeLen := 0
scaleLinear := func(it, width, max uint) uint {
if it == 0 || max == 0 {
return 0
}
return 1 + (it * (width - 1) / max)
}
// Get the longest filename and longest total change.
var longestLength float64
var longestTotalChange float64
for _, fs := range fileStats {
if int(longestLength) < len(fs.Name) {
longestLength = float64(len(fs.Name))
if len(fs.Name) > maxNameLen {
maxNameLen = len(fs.Name)
}
totalChange := fs.Addition + fs.Deletion
if int(longestTotalChange) < totalChange {
longestTotalChange = float64(totalChange)
changes := strconv.Itoa(fs.Addition + fs.Deletion)
if len(changes) > maxChangeLen {
maxChangeLen = len(changes)
}
}
// Parts of the output:
// <pad><filename><pad>|<pad><changeNumber><pad><+++/---><newline>
// example: " main.go | 10 +++++++--- "
// <pad><filename><pad>
leftTextLength := padLength + longestLength + padLength
// <pad><number><pad><+++++/-----><newline>
// Excluding number length here.
rightTextLength := padLength + padLength + newlineLength
totalTextArea := leftTextLength + separatorLength + rightTextLength
heightOfHistogram := lineLength - totalTextArea
// Scale the histogram.
var scaleFactor float64
if longestTotalChange > heightOfHistogram {
// Scale down to heightOfHistogram.
scaleFactor = longestTotalChange / heightOfHistogram
} else {
scaleFactor = 1.0
}
finalOutput := ""
result := ""
for _, fs := range fileStats {
addn := float64(fs.Addition)
deln := float64(fs.Deletion)
addc := int(math.Floor(addn/scaleFactor))
delc := int(math.Floor(deln/scaleFactor))
if addc < 0 {
addc = 0
}
if delc < 0 {
delc = 0
}
adds := strings.Repeat("+", addc)
dels := strings.Repeat("-", delc)
finalOutput += fmt.Sprintf(" %s | %d %s%s\n", fs.Name, (fs.Addition + fs.Deletion), adds, dels)
}
add := uint(fs.Addition)
del := uint(fs.Deletion)
np := maxNameLen - len(fs.Name)
cp := maxChangeLen - len(strconv.Itoa(fs.Addition+fs.Deletion))
return finalOutput
total := add + del
if total > maxGraphWidth {
add = scaleLinear(add, maxGraphWidth, total)
del = scaleLinear(del, maxGraphWidth, total)
}
adds := strings.Repeat("+", int(add))
dels := strings.Repeat("-", int(del))
namePad := strings.Repeat(" ", np)
changePad := strings.Repeat(" ", cp)
result += fmt.Sprintf(" %s%s | %s%d %s%s\n", fs.Name, namePad, changePad, total, adds, dels)
}
return result
}
func getFileStatsFromFilePatches(filePatches []fdiff.FilePatch) FileStats {

View File

@@ -7,6 +7,7 @@ import (
"io"
"path"
"path/filepath"
"sort"
"strings"
"github.com/go-git/go-git/v5/plumbing"
@@ -27,6 +28,7 @@ var (
ErrFileNotFound = errors.New("file not found")
ErrDirectoryNotFound = errors.New("directory not found")
ErrEntryNotFound = errors.New("entry not found")
ErrEntriesNotSorted = errors.New("entries in tree are not sorted")
)
// Tree is basically like a directory - it references a bunch of other trees
@@ -270,6 +272,28 @@ func (t *Tree) Decode(o plumbing.EncodedObject) (err error) {
return nil
}
type TreeEntrySorter []TreeEntry
func (s TreeEntrySorter) Len() int {
return len(s)
}
func (s TreeEntrySorter) Less(i, j int) bool {
name1 := s[i].Name
name2 := s[j].Name
if s[i].Mode == filemode.Dir {
name1 += "/"
}
if s[j].Mode == filemode.Dir {
name2 += "/"
}
return name1 < name2
}
func (s TreeEntrySorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Encode transforms a Tree into a plumbing.EncodedObject.
func (t *Tree) Encode(o plumbing.EncodedObject) (err error) {
o.SetType(plumbing.TreeObject)
@@ -279,7 +303,15 @@ func (t *Tree) Encode(o plumbing.EncodedObject) (err error) {
}
defer ioutil.CheckClose(w, &err)
if !sort.IsSorted(TreeEntrySorter(t.Entries)) {
return ErrEntriesNotSorted
}
for _, entry := range t.Entries {
if strings.IndexByte(entry.Name, 0) != -1 {
return fmt.Errorf("malformed filename %q", entry.Name)
}
if _, err = fmt.Fprintf(w, "%o %s", entry.Mode, entry.Name); err != nil {
return err
}

View File

@@ -88,7 +88,9 @@ func (t *treeNoder) Children() ([]noder.Noder, error) {
}
}
return transformChildren(parent)
var err error
t.children, err = transformChildren(parent)
return t.children, err
}
// Returns the children of a tree as treenoders.

View File

@@ -91,9 +91,9 @@ func advertisedReferences(ctx context.Context, s *session, serviceName string) (
}
type client struct {
c *http.Client
client *http.Client
transports *lru.Cache
m sync.RWMutex
mutex sync.RWMutex
}
// ClientOptions holds user configurable options for the client.
@@ -147,7 +147,7 @@ func NewClientWithOptions(c *http.Client, opts *ClientOptions) transport.Transpo
}
}
cl := &client{
c: c,
client: c,
}
if opts != nil {
@@ -234,10 +234,10 @@ func newSession(c *client, ep *transport.Endpoint, auth transport.AuthMethod) (*
// if the client wasn't configured to have a cache for transports then just configure
// the transport and use it directly, otherwise try to use the cache.
if c.transports == nil {
tr, ok := c.c.Transport.(*http.Transport)
tr, ok := c.client.Transport.(*http.Transport)
if !ok {
return nil, fmt.Errorf("expected underlying client transport to be of type: %s; got: %s",
reflect.TypeOf(transport), reflect.TypeOf(c.c.Transport))
reflect.TypeOf(transport), reflect.TypeOf(c.client.Transport))
}
transport = tr.Clone()
@@ -258,7 +258,7 @@ func newSession(c *client, ep *transport.Endpoint, auth transport.AuthMethod) (*
transport, found = c.fetchTransport(transportOpts)
if !found {
transport = c.c.Transport.(*http.Transport).Clone()
transport = c.client.Transport.(*http.Transport).Clone()
configureTransport(transport, ep)
c.addTransport(transportOpts, transport)
}
@@ -266,12 +266,12 @@ func newSession(c *client, ep *transport.Endpoint, auth transport.AuthMethod) (*
httpClient = &http.Client{
Transport: transport,
CheckRedirect: c.c.CheckRedirect,
Jar: c.c.Jar,
Timeout: c.c.Timeout,
CheckRedirect: c.client.CheckRedirect,
Jar: c.client.Jar,
Timeout: c.client.Timeout,
}
} else {
httpClient = c.c
httpClient = c.client
}
s := &session{

View File

@@ -14,21 +14,21 @@ type transportOptions struct {
}
func (c *client) addTransport(opts transportOptions, transport *http.Transport) {
c.m.Lock()
c.mutex.Lock()
c.transports.Add(opts, transport)
c.m.Unlock()
c.mutex.Unlock()
}
func (c *client) removeTransport(opts transportOptions) {
c.m.Lock()
c.mutex.Lock()
c.transports.Remove(opts)
c.m.Unlock()
c.mutex.Unlock()
}
func (c *client) fetchTransport(opts transportOptions) (*http.Transport, bool) {
c.m.RLock()
c.mutex.RLock()
t, ok := c.transports.Get(opts)
c.m.RUnlock()
c.mutex.RUnlock()
if !ok {
return nil, false
}

View File

@@ -49,7 +49,9 @@ type runner struct {
func (r *runner) Command(cmd string, ep *transport.Endpoint, auth transport.AuthMethod) (common.Command, error) {
c := &command{command: cmd, endpoint: ep, config: r.config}
if auth != nil {
c.setAuth(auth)
if err := c.setAuth(auth); err != nil {
return nil, err
}
}
if err := c.connect(); err != nil {

View File

@@ -470,6 +470,14 @@ func (r *Remote) fetch(ctx context.Context, o *FetchOptions) (sto storer.Referen
}
}
var updatedPrune bool
if o.Prune {
updatedPrune, err = r.pruneRemotes(o.RefSpecs, localRefs, remoteRefs)
if err != nil {
return nil, err
}
}
updated, err := r.updateLocalReferenceStorage(o.RefSpecs, refs, remoteRefs, specToRefs, o.Tags, o.Force)
if err != nil {
return nil, err
@@ -482,7 +490,7 @@ func (r *Remote) fetch(ctx context.Context, o *FetchOptions) (sto storer.Referen
}
}
if !updated {
if !updated && !updatedPrune {
return remoteRefs, NoErrAlreadyUpToDate
}
@@ -574,6 +582,27 @@ func (r *Remote) fetchPack(ctx context.Context, o *FetchOptions, s transport.Upl
return err
}
func (r *Remote) pruneRemotes(specs []config.RefSpec, localRefs []*plumbing.Reference, remoteRefs memory.ReferenceStorage) (bool, error) {
var updatedPrune bool
for _, spec := range specs {
rev := spec.Reverse()
for _, ref := range localRefs {
if !rev.Match(ref.Name()) {
continue
}
_, err := remoteRefs.Reference(rev.Dst(ref.Name()))
if errors.Is(err, plumbing.ErrReferenceNotFound) {
updatedPrune = true
err := r.s.RemoveReference(ref.Name())
if err != nil {
return false, err
}
}
}
}
return updatedPrune, nil
}
func (r *Remote) addReferencesToUpdate(
refspecs []config.RefSpec,
localRefs []*plumbing.Reference,
@@ -1099,7 +1128,7 @@ func isFastForward(s storer.EncodedObjectStorer, old, new plumbing.Hash, earlies
}
found := false
// stop iterating at the earlist shallow commit, ignoring its parents
// stop iterating at the earliest shallow commit, ignoring its parents
// note: when pull depth is smaller than the number of new changes on the remote, this fails due to missing parents.
// as far as i can tell, without the commits in-between the shallow pull and the earliest shallow, there's no
// real way of telling whether it will be a fast-forward merge.

View File

@@ -51,19 +51,21 @@ var (
// ErrFetching is returned when the packfile could not be downloaded
ErrFetching = errors.New("unable to fetch packfile")
ErrInvalidReference = errors.New("invalid reference, should be a tag or a branch")
ErrRepositoryNotExists = errors.New("repository does not exist")
ErrRepositoryIncomplete = errors.New("repository's commondir path does not exist")
ErrRepositoryAlreadyExists = errors.New("repository already exists")
ErrRemoteNotFound = errors.New("remote not found")
ErrRemoteExists = errors.New("remote already exists")
ErrAnonymousRemoteName = errors.New("anonymous remote name must be 'anonymous'")
ErrWorktreeNotProvided = errors.New("worktree should be provided")
ErrIsBareRepository = errors.New("worktree not available in a bare repository")
ErrUnableToResolveCommit = errors.New("unable to resolve commit")
ErrPackedObjectsNotSupported = errors.New("packed objects not supported")
ErrSHA256NotSupported = errors.New("go-git was not compiled with SHA256 support")
ErrAlternatePathNotSupported = errors.New("alternate path must use the file scheme")
ErrInvalidReference = errors.New("invalid reference, should be a tag or a branch")
ErrRepositoryNotExists = errors.New("repository does not exist")
ErrRepositoryIncomplete = errors.New("repository's commondir path does not exist")
ErrRepositoryAlreadyExists = errors.New("repository already exists")
ErrRemoteNotFound = errors.New("remote not found")
ErrRemoteExists = errors.New("remote already exists")
ErrAnonymousRemoteName = errors.New("anonymous remote name must be 'anonymous'")
ErrWorktreeNotProvided = errors.New("worktree should be provided")
ErrIsBareRepository = errors.New("worktree not available in a bare repository")
ErrUnableToResolveCommit = errors.New("unable to resolve commit")
ErrPackedObjectsNotSupported = errors.New("packed objects not supported")
ErrSHA256NotSupported = errors.New("go-git was not compiled with SHA256 support")
ErrAlternatePathNotSupported = errors.New("alternate path must use the file scheme")
ErrUnsupportedMergeStrategy = errors.New("unsupported merge strategy")
ErrFastForwardMergeNotPossible = errors.New("not possible to fast-forward merge changes")
)
// Repository represents a git repository
@@ -1769,8 +1771,43 @@ func (r *Repository) RepackObjects(cfg *RepackConfig) (err error) {
return nil
}
// Merge merges the reference branch into the current branch.
//
// If the merge is not possible (or supported) returns an error without changing
// the HEAD for the current branch. Possible errors include:
// - The merge strategy is not supported.
// - The specific strategy cannot be used (e.g. using FastForwardMerge when one is not possible).
func (r *Repository) Merge(ref plumbing.Reference, opts MergeOptions) error {
if opts.Strategy != FastForwardMerge {
return ErrUnsupportedMergeStrategy
}
// Ignore error as not having a shallow list is optional here.
shallowList, _ := r.Storer.Shallow()
var earliestShallow *plumbing.Hash
if len(shallowList) > 0 {
earliestShallow = &shallowList[0]
}
head, err := r.Head()
if err != nil {
return err
}
ff, err := isFastForward(r.Storer, head.Hash(), ref.Hash(), earliestShallow)
if err != nil {
return err
}
if !ff {
return ErrFastForwardMergeNotPossible
}
return r.Storer.SetReference(plumbing.NewHashReference(head.Name(), ref.Hash()))
}
// createNewObjectPack is a helper for RepackObjects taking care
// of creating a new pack. It is used so the the PackfileWriter
// of creating a new pack. It is used so the PackfileWriter
// deferred close has the right scope.
func (r *Repository) createNewObjectPack(cfg *RepackConfig) (h plumbing.Hash, err error) {
ow := newObjectWalker(r.Storer)

33
vendor/github.com/go-git/go-git/v5/signer.go generated vendored Normal file
View File

@@ -0,0 +1,33 @@
package git
import (
"io"
"github.com/go-git/go-git/v5/plumbing"
)
// signableObject is an object which can be signed.
type signableObject interface {
EncodeWithoutSignature(o plumbing.EncodedObject) error
}
// Signer is an interface for signing git objects.
// message is a reader containing the encoded object to be signed.
// Implementors should return the encoded signature and an error if any.
// See https://git-scm.com/docs/gitformat-signature for more information.
type Signer interface {
Sign(message io.Reader) ([]byte, error)
}
func signObject(signer Signer, obj signableObject) ([]byte, error) {
encoded := &plumbing.MemoryObject{}
if err := obj.EncodeWithoutSignature(encoded); err != nil {
return nil, err
}
r, err := encoded.Reader()
if err != nil {
return nil, err
}
return signer.Sign(r)
}

View File

@@ -29,6 +29,8 @@ type node struct {
hash []byte
children []noder.Noder
isDir bool
mode os.FileMode
size int64
}
// NewRootNode returns the root node based on a given billy.Filesystem.
@@ -48,8 +50,15 @@ func NewRootNode(
// difftree algorithm will detect changes in the contents of files and also in
// their mode.
//
// Please note that the hash is calculated on first invocation of Hash(),
// meaning that it will not update when the underlying file changes
// between invocations.
//
// The hash of a directory is always a 24-bytes slice of zero values
func (n *node) Hash() []byte {
if n.hash == nil {
n.calculateHash()
}
return n.hash
}
@@ -121,81 +130,74 @@ func (n *node) calculateChildren() error {
func (n *node) newChildNode(file os.FileInfo) (*node, error) {
path := path.Join(n.path, file.Name())
hash, err := n.calculateHash(path, file)
if err != nil {
return nil, err
}
node := &node{
fs: n.fs,
submodules: n.submodules,
path: path,
hash: hash,
isDir: file.IsDir(),
size: file.Size(),
mode: file.Mode(),
}
if hash, isSubmodule := n.submodules[path]; isSubmodule {
node.hash = append(hash[:], filemode.Submodule.Bytes()...)
if _, isSubmodule := n.submodules[path]; isSubmodule {
node.isDir = false
}
return node, nil
}
func (n *node) calculateHash(path string, file os.FileInfo) ([]byte, error) {
if file.IsDir() {
return make([]byte, 24), nil
func (n *node) calculateHash() {
if n.isDir {
n.hash = make([]byte, 24)
return
}
mode, err := filemode.NewFromOSFileMode(n.mode)
if err != nil {
n.hash = plumbing.ZeroHash[:]
return
}
if submoduleHash, isSubmodule := n.submodules[n.path]; isSubmodule {
n.hash = append(submoduleHash[:], filemode.Submodule.Bytes()...)
return
}
var hash plumbing.Hash
var err error
if file.Mode()&os.ModeSymlink != 0 {
hash, err = n.doCalculateHashForSymlink(path, file)
if n.mode&os.ModeSymlink != 0 {
hash = n.doCalculateHashForSymlink()
} else {
hash, err = n.doCalculateHashForRegular(path, file)
hash = n.doCalculateHashForRegular()
}
if err != nil {
return nil, err
}
mode, err := filemode.NewFromOSFileMode(file.Mode())
if err != nil {
return nil, err
}
return append(hash[:], mode.Bytes()...), nil
n.hash = append(hash[:], mode.Bytes()...)
}
func (n *node) doCalculateHashForRegular(path string, file os.FileInfo) (plumbing.Hash, error) {
f, err := n.fs.Open(path)
func (n *node) doCalculateHashForRegular() plumbing.Hash {
f, err := n.fs.Open(n.path)
if err != nil {
return plumbing.ZeroHash, err
return plumbing.ZeroHash
}
defer f.Close()
h := plumbing.NewHasher(plumbing.BlobObject, file.Size())
h := plumbing.NewHasher(plumbing.BlobObject, n.size)
if _, err := io.Copy(h, f); err != nil {
return plumbing.ZeroHash, err
return plumbing.ZeroHash
}
return h.Sum(), nil
return h.Sum()
}
func (n *node) doCalculateHashForSymlink(path string, file os.FileInfo) (plumbing.Hash, error) {
target, err := n.fs.Readlink(path)
func (n *node) doCalculateHashForSymlink() plumbing.Hash {
target, err := n.fs.Readlink(n.path)
if err != nil {
return plumbing.ZeroHash, err
return plumbing.ZeroHash
}
h := plumbing.NewHasher(plumbing.BlobObject, file.Size())
h := plumbing.NewHasher(plumbing.BlobObject, n.size)
if _, err := h.Write([]byte(target)); err != nil {
return plumbing.ZeroHash, err
return plumbing.ZeroHash
}
return h.Sum(), nil
return h.Sum()
}
func (n *node) String() string {

View File

@@ -227,20 +227,17 @@ func (w *Worktree) createBranch(opts *CheckoutOptions) error {
}
func (w *Worktree) getCommitFromCheckoutOptions(opts *CheckoutOptions) (plumbing.Hash, error) {
if !opts.Hash.IsZero() {
return opts.Hash, nil
hash := opts.Hash
if hash.IsZero() {
b, err := w.r.Reference(opts.Branch, true)
if err != nil {
return plumbing.ZeroHash, err
}
hash = b.Hash()
}
b, err := w.r.Reference(opts.Branch, true)
if err != nil {
return plumbing.ZeroHash, err
}
if !b.Name().IsTag() {
return b.Hash(), nil
}
o, err := w.r.Object(plumbing.AnyObject, b.Hash())
o, err := w.r.Object(plumbing.AnyObject, hash)
if err != nil {
return plumbing.ZeroHash, err
}
@@ -248,7 +245,7 @@ func (w *Worktree) getCommitFromCheckoutOptions(opts *CheckoutOptions) (plumbing
switch o := o.(type) {
case *object.Tag:
if o.TargetType != plumbing.CommitObject {
return plumbing.ZeroHash, fmt.Errorf("unsupported tag object target %q", o.TargetType)
return plumbing.ZeroHash, fmt.Errorf("%w: tag target %q", object.ErrUnsupportedObject, o.TargetType)
}
return o.Target, nil
@@ -256,7 +253,7 @@ func (w *Worktree) getCommitFromCheckoutOptions(opts *CheckoutOptions) (plumbing
return o.Hash, nil
}
return plumbing.ZeroHash, fmt.Errorf("unsupported tag target %q", o.Type())
return plumbing.ZeroHash, fmt.Errorf("%w: %q", object.ErrUnsupportedObject, o.Type())
}
func (w *Worktree) setHEADToCommit(commit plumbing.Hash) error {
@@ -431,6 +428,10 @@ var worktreeDeny = map[string]struct{}{
func validPath(paths ...string) error {
for _, p := range paths {
parts := strings.FieldsFunc(p, func(r rune) bool { return (r == '\\' || r == '/') })
if len(parts) == 0 {
return fmt.Errorf("invalid path: %q", p)
}
if _, denied := worktreeDeny[strings.ToLower(parts[0])]; denied {
return fmt.Errorf("invalid path prefix: %q", p)
}

View File

@@ -3,6 +3,7 @@ package git
import (
"bytes"
"errors"
"io"
"path"
"sort"
"strings"
@@ -14,6 +15,7 @@ import (
"github.com/go-git/go-git/v5/storage"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/go-git/go-billy/v5"
)
@@ -43,29 +45,30 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error
if err != nil {
return plumbing.ZeroHash, err
}
t, err := w.r.getTreeFromCommitHash(head.Hash())
headCommit, err := w.r.CommitObject(head.Hash())
if err != nil {
return plumbing.ZeroHash, err
}
treeHash = t.Hash
opts.Parents = []plumbing.Hash{head.Hash()}
} else {
idx, err := w.r.Storer.Index()
if err != nil {
return plumbing.ZeroHash, err
opts.Parents = nil
if len(headCommit.ParentHashes) != 0 {
opts.Parents = []plumbing.Hash{headCommit.ParentHashes[0]}
}
}
h := &buildTreeHelper{
fs: w.Filesystem,
s: w.r.Storer,
}
idx, err := w.r.Storer.Index()
if err != nil {
return plumbing.ZeroHash, err
}
treeHash, err = h.BuildTree(idx, opts)
if err != nil {
return plumbing.ZeroHash, err
}
h := &buildTreeHelper{
fs: w.Filesystem,
s: w.r.Storer,
}
treeHash, err = h.BuildTree(idx, opts)
if err != nil {
return plumbing.ZeroHash, err
}
commit, err := w.buildCommitObject(msg, opts, treeHash)
@@ -125,12 +128,17 @@ func (w *Worktree) buildCommitObject(msg string, opts *CommitOptions, tree plumb
ParentHashes: opts.Parents,
}
if opts.SignKey != nil {
sig, err := w.buildCommitSignature(commit, opts.SignKey)
// Convert SignKey into a Signer if set. Existing Signer should take priority.
signer := opts.Signer
if signer == nil && opts.SignKey != nil {
signer = &gpgSigner{key: opts.SignKey}
}
if signer != nil {
sig, err := signObject(signer, commit)
if err != nil {
return plumbing.ZeroHash, err
}
commit.PGPSignature = sig
commit.PGPSignature = string(sig)
}
obj := w.r.Storer.NewEncodedObject()
@@ -140,20 +148,17 @@ func (w *Worktree) buildCommitObject(msg string, opts *CommitOptions, tree plumb
return w.r.Storer.SetEncodedObject(obj)
}
func (w *Worktree) buildCommitSignature(commit *object.Commit, signKey *openpgp.Entity) (string, error) {
encoded := &plumbing.MemoryObject{}
if err := commit.Encode(encoded); err != nil {
return "", err
}
r, err := encoded.Reader()
if err != nil {
return "", err
}
type gpgSigner struct {
key *openpgp.Entity
cfg *packet.Config
}
func (s *gpgSigner) Sign(message io.Reader) ([]byte, error) {
var b bytes.Buffer
if err := openpgp.ArmoredDetachSign(&b, signKey, r, nil); err != nil {
return "", err
if err := openpgp.ArmoredDetachSign(&b, s.key, message, s.cfg); err != nil {
return nil, err
}
return b.String(), nil
return b.Bytes(), nil
}
// buildTreeHelper converts a given index.Index file into multiple git objects
@@ -263,4 +268,4 @@ func (h *buildTreeHelper) copyTreeToStorageRecursive(parent string, t *object.Tr
return hash, nil
}
return h.s.SetEncodedObject(o)
}
}

View File

@@ -271,7 +271,7 @@ func diffTreeIsEquals(a, b noder.Hasher) bool {
// no error is returned. When path is a file, the blob.Hash is returned.
func (w *Worktree) Add(path string) (plumbing.Hash, error) {
// TODO(mcuadros): deprecate in favor of AddWithOption in v6.
return w.doAdd(path, make([]gitignore.Pattern, 0))
return w.doAdd(path, make([]gitignore.Pattern, 0), false)
}
func (w *Worktree) doAddDirectory(idx *index.Index, s Status, directory string, ignorePattern []gitignore.Pattern) (added bool, err error) {
@@ -321,7 +321,7 @@ func (w *Worktree) AddWithOptions(opts *AddOptions) error {
}
if opts.All {
_, err := w.doAdd(".", w.Excludes)
_, err := w.doAdd(".", w.Excludes, false)
return err
}
@@ -329,16 +329,11 @@ func (w *Worktree) AddWithOptions(opts *AddOptions) error {
return w.AddGlob(opts.Glob)
}
_, err := w.Add(opts.Path)
_, err := w.doAdd(opts.Path, make([]gitignore.Pattern, 0), opts.SkipStatus)
return err
}
func (w *Worktree) doAdd(path string, ignorePattern []gitignore.Pattern) (plumbing.Hash, error) {
s, err := w.Status()
if err != nil {
return plumbing.ZeroHash, err
}
func (w *Worktree) doAdd(path string, ignorePattern []gitignore.Pattern, skipStatus bool) (plumbing.Hash, error) {
idx, err := w.r.Storer.Index()
if err != nil {
return plumbing.ZeroHash, err
@@ -348,6 +343,17 @@ func (w *Worktree) doAdd(path string, ignorePattern []gitignore.Pattern) (plumbi
var added bool
fi, err := w.Filesystem.Lstat(path)
// status is required for doAddDirectory
var s Status
var err2 error
if !skipStatus || fi == nil || fi.IsDir() {
s, err2 = w.Status()
if err2 != nil {
return plumbing.ZeroHash, err2
}
}
if err != nil || !fi.IsDir() {
added, h, err = w.doAddFile(idx, s, path, ignorePattern)
} else {
@@ -421,8 +427,9 @@ func (w *Worktree) AddGlob(pattern string) error {
// doAddFile create a new blob from path and update the index, added is true if
// the file added is different from the index.
// if s status is nil will skip the status check and update the index anyway
func (w *Worktree) doAddFile(idx *index.Index, s Status, path string, ignorePattern []gitignore.Pattern) (added bool, h plumbing.Hash, err error) {
if s.File(path).Worktree == Unmodified {
if s != nil && s.File(path).Worktree == Unmodified {
return false, h, nil
}
if len(ignorePattern) > 0 {