repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/pipeline.go
git/pipeline.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "context" "fmt" "github.com/harness/gitness/git/api" "github.com/drone/go-generate/builder" ) type GeneratePipelineParams struct { ReadParams } type GeneratePipelinesOutput struct { PipelineYAML []byte } func (s *Service) GeneratePipeline(ctx context.Context, params *GeneratePipelineParams, ) (GeneratePipelinesOutput, error) { if err := params.Validate(); err != nil { return GeneratePipelinesOutput{}, err } repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID) sha, err := s.git.ResolveRev(ctx, repoPath, "HEAD") if err != nil { return GeneratePipelinesOutput{}, fmt.Errorf("failed to resolve HEAD revision: %w", err) } ctxFS, cancelFn := context.WithCancel(ctx) defer cancelFn() gitFS := api.NewFS(ctxFS, sha.String(), repoPath) // builds the pipeline configuration based on // the contents of the virtual filesystem. builder := builder.New() out, err := builder.Build(gitFS) if err != nil { return GeneratePipelinesOutput{}, fmt.Errorf("failed to build pipeline: %w", err) } return GeneratePipelinesOutput{ PipelineYAML: out, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/blob.go
git/blob.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "context" "fmt" "io" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/api" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" ) type GetBlobParams struct { ReadParams SHA string SizeLimit int64 } type GetBlobOutput struct { SHA sha.SHA // Size is the actual size of the blob. Size int64 // ContentSize is the total number of bytes returned by the Content Reader. ContentSize int64 // Content contains the (partial) content of the blob. Content io.ReadCloser } func (s *Service) GetBlob(ctx context.Context, params *GetBlobParams) (*GetBlobOutput, error) { if params == nil { return nil, ErrNoParamsProvided } repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID) // TODO: do we need to validate request for nil? reader, err := api.GetBlob( ctx, repoPath, params.AlternateObjectDirs, sha.Must(params.SHA), params.SizeLimit, ) if err != nil { return nil, err } return &GetBlobOutput{ SHA: reader.SHA, Size: reader.Size, ContentSize: reader.ContentSize, Content: reader.Content, }, nil } func (s *Service) FindLFSPointers( ctx context.Context, params *FindLFSPointersParams, ) (*FindLFSPointersOutput, error) { if params.RepoUID == "" { return nil, api.ErrRepositoryPathEmpty } repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID) var objects []parser.BatchCheckObject for _, gitObjDir := range params.AlternateObjectDirs { objs, err := s.listGitObjDir(ctx, repoPath, gitObjDir) if err != nil { return nil, err } objects = append(objects, objs...) } var candidateObjects []parser.BatchCheckObject for _, obj := range objects { if obj.Type == string(TreeNodeTypeBlob) && obj.Size <= parser.LfsPointerMaxSize { candidateObjects = append(candidateObjects, obj) } } var lfsInfos []LFSInfo if len(candidateObjects) == 0 { return &FindLFSPointersOutput{LFSInfos: lfsInfos}, nil } // check the short-listed objects for lfs-pointers content stdIn, stdOut, cancel := api.CatFileBatch(ctx, repoPath, params.AlternateObjectDirs) defer cancel() for _, obj := range candidateObjects { line := obj.SHA.String() + "\n" _, err := stdIn.Write([]byte(line)) if err != nil { return nil, fmt.Errorf("failed to write blob sha to git stdin: %w", err) } // first line is always the object type, sha, and size _, err = stdOut.ReadString('\n') if err != nil { return nil, fmt.Errorf("failed to read the git cat-file output: %w", err) } content, err := io.ReadAll(io.LimitReader(stdOut, obj.Size)) if err != nil { return nil, fmt.Errorf("failed to read the git cat-file output: %w", err) } oid, err := parser.GetLFSObjectID(content) if err != nil && !errors.Is(err, parser.ErrInvalidLFSPointer) { return nil, fmt.Errorf("failed to scan git cat-file output for %s: %w", obj.SHA, err) } if err == nil { lfsInfos = append(lfsInfos, LFSInfo{ObjID: oid, SHA: obj.SHA}) } // skip the trailing new line _, err = stdOut.ReadString('\n') if err != nil { return nil, fmt.Errorf("failed to read trailing newline after object: %w", err) } } return &FindLFSPointersOutput{LFSInfos: lfsInfos}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/service_pack.go
git/service_pack.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "context" "fmt" "io" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/api" "github.com/harness/gitness/types/enum" ) type InfoRefsParams struct { ReadParams Service string Options []string // (key, value) pair GitProtocol string } func (s *Service) GetInfoRefs(ctx context.Context, w io.Writer, params *InfoRefsParams) error { if err := params.Validate(); err != nil { return err } environ := []string{} if params.GitProtocol != "" { environ = append(environ, "GIT_PROTOCOL="+params.GitProtocol) } repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID) err := s.git.InfoRefs(ctx, repoPath, params.Service, w, environ...) if err != nil { return fmt.Errorf("failed to fetch info references: %w", err) } return nil } type ServicePackParams struct { *ReadParams *WriteParams api.ServicePackOptions } func (p *ServicePackParams) Validate() error { if p.Service == "" { return errors.InvalidArgument("service is mandatory field") } return nil } func (s *Service) ServicePack(ctx context.Context, params *ServicePackParams) error { if err := params.Validate(); err != nil { return err } var repoPath string switch params.Service { case enum.GitServiceTypeUploadPack: if err := params.ReadParams.Validate(); err != nil { return errors.InvalidArgument("upload-pack requires ReadParams") } repoPath = getFullPathForRepo(s.reposRoot, params.ReadParams.RepoUID) case enum.GitServiceTypeReceivePack: if err := params.WriteParams.Validate(); err != nil { return errors.InvalidArgument("receive-pack requires WriteParams") } params.Env = append(params.Env, CreateEnvironmentForPush(ctx, *params.WriteParams)...) repoPath = getFullPathForRepo(s.reposRoot, params.WriteParams.RepoUID) default: return errors.InvalidArgumentf("unsupported service provided: %s", params.Service) } err := s.git.ServicePack(ctx, repoPath, params.ServicePackOptions) if err != nil { return fmt.Errorf("failed to execute git %s: %w", params.Service, err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/submodule.go
git/submodule.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "context" "fmt" ) type GetSubmoduleParams struct { ReadParams // GitREF is a git reference (branch / tag / commit SHA) GitREF string Path string } type GetSubmoduleOutput struct { Submodule Submodule } type Submodule struct { Name string URL string } func (s *Service) GetSubmodule(ctx context.Context, params *GetSubmoduleParams) (*GetSubmoduleOutput, error) { if err := params.Validate(); err != nil { return nil, err } repoPath := getFullPathForRepo(s.reposRoot, params.RepoUID) // TODO: do we need to validate request for nil? gitSubmodule, err := s.git.GetSubmodule(ctx, repoPath, params.GitREF, params.Path) if err != nil { return nil, fmt.Errorf("GetSubmodule: failed to get submodule: %w", err) } return &GetSubmoduleOutput{ Submodule: Submodule{ Name: gitSubmodule.Name, URL: gitSubmodule.URL, }, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/common.go
git/common.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "github.com/harness/gitness/errors" ) // ReadParams contains the base parameters for read operations. type ReadParams struct { RepoUID string AlternateObjectDirs []string } func (p ReadParams) Validate() error { if p.RepoUID == "" { return errors.InvalidArgument("repository id cannot be empty") } return nil } // WriteParams contains the base parameters for write operations. type WriteParams struct { RepoUID string Actor Identity EnvVars map[string]string } func (p *WriteParams) Validate() error { if p.RepoUID == "" { return errors.InvalidArgument("RepoUID is mandatory field") } return p.Actor.Validate() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/kuberesolver.go
git/kuberesolver.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "github.com/sercand/kuberesolver/v5" ) func init() { kuberesolver.RegisterInCluster() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/repack.go
git/repack.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "context" "errors" "fmt" "path/filepath" "time" "github.com/harness/gitness/git/api" "github.com/rs/zerolog/log" ) type RepackStrategy string const ( RepackStrategyIncrementalWithUnreachable RepackStrategy = "incremental_with_unreachable" RepackStrategyFullWithCruft RepackStrategy = "full_with_cruft" RepackStrategyFullWithUnreachable RepackStrategy = "full_with_unreachable" RepackStrategyGeometric RepackStrategy = "geometric" ) type RepackParams struct { Strategy RepackStrategy WriteBitmap bool WriteMultiPackIndex bool CruftExpireBefore time.Time } func (p RepackParams) Validate() error { switch p.Strategy { case RepackStrategyIncrementalWithUnreachable: if p.WriteBitmap { return errors.New("cannot create bitmap with incremental repack strategy") } if p.WriteMultiPackIndex { return errors.New("cannot create multi-pack index with incremental repack strategy") } case RepackStrategyFullWithCruft: if p.CruftExpireBefore.IsZero() { return errors.New("cannot repack with cruft with empty expiration time") } case RepackStrategyFullWithUnreachable: case RepackStrategyGeometric: default: return fmt.Errorf("unknown strategy: %q", p.Strategy) } return nil } func (s *Service) repackObjects( ctx context.Context, repoPath string, params RepackParams, ) error { if err := params.Validate(); err != nil { return err } defer func() { err := api.SetLastFullRepackTime(repoPath, time.Now()) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to set last full repack time: %s", err.Error()) } }() switch params.Strategy { case RepackStrategyIncrementalWithUnreachable: // Pack all loose objects into a new pack file, regardless of their reachability. err := s.git.PackObjects(ctx, repoPath, api.PackObjectsParams{ PackLooseUnreachable: true, Local: true, Incremental: true, NonEmpty: true, Quiet: true, }, filepath.Join(repoPath, "objects", "pack", "pack")) if err != nil { return fmt.Errorf("incremental with unreachable repack objects error: %w", err) } // ensure that packed loose objects are deleted. err = s.git.PrunePacked(ctx, repoPath, api.PrunePackedParams{ Quiet: true, }) if err != nil { return fmt.Errorf("prune pack objects error: %w", err) } case RepackStrategyFullWithCruft: repackParams := api.RepackParams{ Cruft: true, PackKeptObjects: true, Local: true, RemoveRedundantObjects: true, WriteMidx: params.WriteMultiPackIndex, } if !params.CruftExpireBefore.IsZero() { repackParams.CruftExpireBefore = params.CruftExpireBefore } err := s.git.RepackObjects(ctx, repoPath, repackParams) if err != nil { return fmt.Errorf("full with cruft repack objects error: %w", err) } case RepackStrategyFullWithUnreachable: err := s.git.RepackObjects(ctx, repoPath, api.RepackParams{ SinglePack: true, Local: true, RemoveRedundantObjects: true, KeepUnreachable: true, WriteMidx: params.WriteMultiPackIndex, }) if err != nil { return fmt.Errorf("full with unreachable repack objects error: %w", err) } case RepackStrategyGeometric: err := s.git.RepackObjects(ctx, repoPath, api.RepackParams{ Geometric: 2, RemoveRedundantObjects: true, Local: true, WriteMidx: params.WriteMultiPackIndex, }) if err != nil { return fmt.Errorf("geometric repack objects error: %w", err) } } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hunk.go
git/hunk.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package git import ( "strconv" "strings" ) type Hunk struct { HunkHeader Lines []string } type HunkHeader struct { OldLine int OldSpan int NewLine int NewSpan int Text string } func (h *HunkHeader) IsZero() bool { return h.OldLine == 0 && h.OldSpan == 0 && h.NewLine == 0 && h.NewSpan == 0 } func (h *HunkHeader) IsValid() bool { oldOk := h.OldLine == 0 && h.OldSpan == 0 || h.OldLine > 0 && h.OldSpan > 0 newOk := h.NewLine == 0 && h.NewSpan == 0 || h.NewLine > 0 && h.NewSpan > 0 return !h.IsZero() && oldOk && newOk } func (h *HunkHeader) String() string { sb := strings.Builder{} sb.WriteString("@@ -") sb.WriteString(strconv.Itoa(h.OldLine)) if h.OldSpan != 1 { sb.WriteByte(',') sb.WriteString(strconv.Itoa(h.OldSpan)) } sb.WriteString(" +") sb.WriteString(strconv.Itoa(h.NewLine)) if h.NewSpan != 1 { sb.WriteByte(',') sb.WriteString(strconv.Itoa(h.NewSpan)) } sb.WriteString(" @@") if h.Text != "" { sb.WriteByte(' ') sb.WriteString(h.Text) } return sb.String() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/storage/storage.go
git/storage/storage.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package storage import "io" type Store interface { Save(filePath string, data io.Reader) (string, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/storage/local.go
git/storage/local.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package storage import ( "fmt" "io" "os" "path/filepath" ) type LocalStore struct{} func NewLocalStore() *LocalStore { return &LocalStore{} } func (store *LocalStore) Save(filePath string, data io.Reader) (string, error) { err := os.MkdirAll(filepath.Dir(filePath), 0o777) if err != nil { return "", err } file, err := os.Create(filePath) if err != nil { return "", fmt.Errorf("cannot create file: %w", err) } defer file.Close() _, err = io.Copy(file, data) if err != nil { return "", fmt.Errorf("cannot write to file: %w", err) } return filePath, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/storage/wire.go
git/storage/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package storage import "github.com/google/wire" var WireSet = wire.NewSet( ProvideLocalStore, ) func ProvideLocalStore() Store { return NewLocalStore() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hash/git.go
git/hash/git.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hash // SerializeReference serializes a reference to prepare it for hashing. func SerializeReference(ref string, sha string) []byte { return []byte(ref + ":" + sha) } // SerializeHead serializes the head to prepare it for hashing. func SerializeHead(value string) []byte { return []byte("HEAD:" + value) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hash/aggregate_xor_test.go
git/hash/aggregate_xor_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hash import ( "encoding/hex" "testing" "github.com/stretchr/testify/require" ) const ( value1 = "refs/heads/abcd:1234" value2 = "refs/heads/zyxw:9876" ) var ( hashValueEmpty, _ = hex.DecodeString("0000000000000000000000000000000000000000000000000000000000000000") hashValue1, _ = hex.DecodeString("3a00e4f6f30e7eef599350b1bc19e1469bf5c6b26c3d93839d53547f0a61060d") hashValue2, _ = hex.DecodeString("10111069c3abe9cec02f6bada1e1ab4233d04c7b1d4eb80f05ca2b851c3ba89d") hashValue1And2, _ = hex.DecodeString("2a11f49f30a5972199bc3b1c1df84a04a8258ac971732b8c98997ffa165aae90") ) func TestXORAggregator_Empty(t *testing.T) { xor, _ := New(TypeSHA256, AggregationTypeXOR) res, err := xor.Hash(SourceFromSlice([][]byte{})) require.NoError(t, err, "failed to hash value1") require.EqualValues(t, hashValueEmpty, res) } func TestXORAggregator_Single(t *testing.T) { xor, _ := New(TypeSHA256, AggregationTypeXOR) res, err := xor.Hash(SourceFromSlice([][]byte{[]byte(value1)})) require.NoError(t, err, "failed to hash value1") require.EqualValues(t, hashValue1, res) res, err = xor.Hash(SourceFromSlice([][]byte{[]byte(value2)})) require.NoError(t, err, "failed to hash value2") require.EqualValues(t, hashValue2, res) } func TestXORAggregator_Multi(t *testing.T) { xor, _ := New(TypeSHA256, AggregationTypeXOR) res, err := xor.Hash(SourceFromSlice([][]byte{[]byte(value1), []byte(value2)})) require.NoError(t, err, "failed to hash value1 and value2") require.EqualValues(t, hashValue1And2, res) } func TestXORAggregator_MultiSame(t *testing.T) { xor, _ := New(TypeSHA256, AggregationTypeXOR) res, err := xor.Hash(SourceFromSlice([][]byte{[]byte(value1), []byte(value1)})) require.NoError(t, err, "failed to hash value1 and value1") require.EqualValues(t, hashValueEmpty, res) res, err = xor.Hash(SourceFromSlice([][]byte{[]byte(value2), []byte(value2)})) require.NoError(t, err, "failed to hash value2 and value2") require.EqualValues(t, hashValueEmpty, res) res, err = xor.Hash(SourceFromSlice([][]byte{[]byte(value1), []byte(value2), []byte(value2)})) require.NoError(t, err, "failed to hash value1 and value2 and value2") require.EqualValues(t, hashValue1, res) res, err = xor.Hash(SourceFromSlice([][]byte{[]byte(value1), []byte(value1), []byte(value2)})) require.NoError(t, err, "failed to hash value1 and value1 and value2") require.EqualValues(t, hashValue2, res) res, err = xor.Hash(SourceFromSlice([][]byte{[]byte(value1), []byte(value2), []byte(value1)})) require.NoError(t, err, "failed to hash value1 and value2 and value1") require.EqualValues(t, hashValue2, res) } func TestAppendMulti(t *testing.T) { xor, _ := New(TypeSHA256, AggregationTypeXOR) res, err := xor.Append(hashValue1, SourceFromSlice([][]byte{[]byte(value2)})) require.NoError(t, err, "failed to append value2") require.EqualValues(t, hashValue1And2, res) res, err = xor.Append(hashValue2, SourceFromSlice([][]byte{[]byte(value1)})) require.NoError(t, err, "failed to append value1") require.EqualValues(t, hashValue1And2, res) res, err = xor.Append(hashValue2, SourceFromSlice([][]byte{[]byte(value1)})) require.NoError(t, err, "failed to append value1") require.EqualValues(t, hashValue1And2, res) } func TestAppendSame(t *testing.T) { xor, _ := New(TypeSHA256, AggregationTypeXOR) res, err := xor.Append(hashValue1, SourceFromSlice([][]byte{[]byte(value1)})) require.NoError(t, err, "failed to append value1") require.EqualValues(t, hashValueEmpty, res) res, err = xor.Append(hashValue2, SourceFromSlice([][]byte{[]byte(value2)})) require.NoError(t, err, "failed to append value2") require.EqualValues(t, hashValueEmpty, res) res, err = xor.Append(hashValue1, SourceFromSlice([][]byte{[]byte(value2), []byte(value2)})) require.NoError(t, err, "failed to append value2 and value2") require.EqualValues(t, hashValue1, res) res, err = xor.Append(hashValue1, SourceFromSlice([][]byte{[]byte(value1), []byte(value2)})) require.NoError(t, err, "failed to append value1 and value2") require.EqualValues(t, hashValue2, res) res, err = xor.Append(hashValue1, SourceFromSlice([][]byte{[]byte(value2), []byte(value1)})) require.NoError(t, err, "failed to append value2 and value1") require.EqualValues(t, hashValue2, res) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hash/source_test.go
git/hash/source_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hash import ( "context" "io" "testing" "time" "github.com/stretchr/testify/require" ) var ( byte1 = []byte{1} byte2 = []byte{2} ) func TestSourceFromChannel_blockingChannel(t *testing.T) { nextChan := make(chan SourceNext) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) go func() { defer close(nextChan) select { case nextChan <- SourceNext{Data: byte1}: case <-ctx.Done(): require.Fail(t, "writing data to source chan timed out") } }() next, err := source.Next() require.NoError(t, err, "no error expected on first call to next") require.Equal(t, byte1, next) _, err = source.Next() require.ErrorIs(t, err, io.EOF, "EOF expected after first element was read") } func TestSourceFromChannel_contextCanceled(t *testing.T) { nextChan := make(chan SourceNext) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) cncl() source := SourceFromChannel(ctx, nextChan) _, err := source.Next() require.ErrorIs(t, err, context.Canceled, "Canceled error expected") } func TestSourceFromChannel_sourceChannelDrainedOnClosing(t *testing.T) { nextChan := make(chan SourceNext, 1) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) nextChan <- SourceNext{Data: byte1} close(nextChan) next, err := source.Next() require.NoError(t, err, "no error expected on first call to next") require.Equal(t, byte1, next) _, err = source.Next() require.ErrorIs(t, err, io.EOF, "EOF expected after first element was read") } func TestSourceFromChannel_errorReturnedOnError(t *testing.T) { nextChan := make(chan SourceNext, 1) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) nextChan <- SourceNext{ Data: byte1, Err: io.ErrClosedPipe, } next, err := source.Next() require.ErrorIs(t, err, io.ErrClosedPipe, "ErrClosedPipe expected") require.Equal(t, byte1, next) } func TestSourceFromChannel_fullChannel(t *testing.T) { nextChan := make(chan SourceNext, 1) ctx, cncl := context.WithTimeout(context.Background(), 1*time.Second) defer cncl() source := SourceFromChannel(ctx, nextChan) nextChan <- SourceNext{Data: byte1} go func() { defer close(nextChan) select { case nextChan <- SourceNext{Data: byte2}: case <-ctx.Done(): require.Fail(t, "writing data to source chan timed out") } }() next, err := source.Next() require.NoError(t, err, "no error expected on first call to next") require.Equal(t, byte1, next) next, err = source.Next() require.NoError(t, err, "no error expected on second call to next") require.Equal(t, byte2, next) _, err = source.Next() require.ErrorIs(t, err, io.EOF, "EOF expected after two elements were read") }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hash/aggregate_xor.go
git/hash/aggregate_xor.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hash import ( "errors" "fmt" "io" ) // xorAggregator is an implementation of the Aggregator interface // that aggregates hashes by XORing them. type xorAggregator struct { hfm hashFactoryMethod hashSize int } func (a *xorAggregator) Empty() []byte { return make([]byte, a.hashSize) } func (a *xorAggregator) Hash(source Source) ([]byte, error) { return a.append(a.Empty(), source) } func (a *xorAggregator) Append(hash []byte, source Source) ([]byte, error) { // copy value to ensure we don't modify the original hash array hashCopy := make([]byte, len(hash)) copy(hashCopy, hash) return a.append(hashCopy, source) } func (a *xorAggregator) append(hash []byte, source Source) ([]byte, error) { if len(hash) != a.hashSize { return nil, fmt.Errorf( "hash is of invalid length %d, aggregator works with hashes of length %d", len(hash), a.hashSize, ) } // create new hasher to allow asynchronous usage hasher := a.hfm() v, err := source.Next() for err == nil { // calculate hash of the value hasher.Reset() hasher.Write(v) vHash := hasher.Sum(nil) // combine the hash with the current hash hash = xorInPlace(hash, vHash) v, err = source.Next() } if !errors.Is(err, io.EOF) { return nil, fmt.Errorf("failed getting the next element from source: %w", err) } return hash, nil } // xorInPlace XORs the provided byte arrays in place. // If one slice is shorter, 0s will be used as replacement elements. // WARNING: The method will taint the passed arrays! func xorInPlace(a, b []byte) []byte { // ensure len(a) >= len(b) if len(b) > len(a) { a, b = b, a } // xor all values from a with b (or 0) for i := 0; i < len(a); i++ { var bi byte if i < len(b) { bi = b[i] } a[i] ^= bi } return a }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hash/hash.go
git/hash/hash.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hash import ( "crypto/sha256" "fmt" "hash" ) // Type defines the different types of hashing that are supported. // NOTE: package doesn't take hash.Hash as input to allow external // callers to both calculate the hash themselves using this package, or call git to calculate the hash, // without the caller having to know internal details on what hash.Hash implementation is used. type Type string const ( // TypeSHA256 represents the sha256 hashing method. TypeSHA256 Type = "sha256" ) // AggregationType defines the different types of hash aggregation types available. type AggregationType string const ( // AggregationTypeXOR aggregates a list of hashes using XOR. // It provides commutative, self-inverse hashing, e.g.: // - order of elements doesn't matter // - two equal elements having the same hash cancel each other out. AggregationTypeXOR AggregationType = "xor" ) // Aggregator is an abstraction of a component that aggregates a list of values into a single hash. type Aggregator interface { // Empty returns the empty hash of an aggregator. It is returned when hashing an empty Source // or hashing a Source who's hash is equal to an empty source. Furthermore, the following is always true: // `Hash(s) == Append(Empty(), s)` FOR ALL sources s. Empty() []byte // Hash returns the hash aggregated over all elements of the provided source. Hash(source Source) ([]byte, error) // Append returns the hash that results when aggregating the existing hash // with the hashes of all elements of the provided source. // IMPORTANT: size of existing hash has to be compatible (Empty() can be used for reference). Append(hash []byte, source Source) ([]byte, error) } // New returns a new aggregator for the given aggregation and hashing type. func New(t Type, at AggregationType) (Aggregator, error) { // get hash factory method to ensure we fail on object creation in case of invalid Type. hfm, hashSize, err := getHashFactoryMethod(t) if err != nil { return nil, err } switch at { case AggregationTypeXOR: return &xorAggregator{ hfm: hfm, hashSize: hashSize, }, nil default: return nil, fmt.Errorf("unknown aggregation type '%s'", at) } } // hashFactoryMethod returns a hash.Hash implementation. type hashFactoryMethod func() hash.Hash // getHashFactoryMethod returns the hash factory method together with the length of its generated hashes. // NOTE: the length is needed to ensure hashes of an empty source are similar to hashes of `a <XOR> a`. func getHashFactoryMethod(t Type) (hashFactoryMethod, int, error) { switch t { case TypeSHA256: return sha256.New, sha256.Size, nil default: return nil, -1, fmt.Errorf("unknown hash type '%s'", t) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hash/source.go
git/hash/source.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hash import ( "context" "fmt" "io" ) // Source is an abstraction of a source of values that have to be hashed. type Source interface { Next() ([]byte, error) } // SourceFunc is an alias for a function that returns the content of a source call by call. type SourceFunc func() ([]byte, error) func (f SourceFunc) Next() ([]byte, error) { return f() } // SourceFromSlice returns a source that iterates over the slice. func SourceFromSlice(slice [][]byte) Source { return SourceFunc(func() ([]byte, error) { if len(slice) == 0 { return nil, io.EOF } // get next element and move slice forward next := slice[0] slice = slice[1:] return next, nil }) } // SourceNext encapsulates the data that is needed to serve a call to Source.Next(). // It is being used by SourceFromChannel to expose a channel as Source. type SourceNext struct { Data []byte Err error } // SourceFromChannel creates a source that returns all elements read from nextChan. // The .Data and .Err of a SourceNext object in the channel will be returned as is. // If the channel is closed, the source indicates the end of the data. func SourceFromChannel(ctx context.Context, nextChan <-chan SourceNext) Source { return SourceFunc(func() ([]byte, error) { select { case <-ctx.Done(): return nil, fmt.Errorf("source context failed with: %w", ctx.Err()) case next, ok := <-nextChan: // channel closed, end of operation if !ok { return nil, io.EOF } return next.Data, next.Err } }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/parser.go
git/command/parser.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "strings" ) // Parse os args to Command object. // This is very basic parser which doesn't care about // flags or positional args values it just injects into proper // slice of command struct. Every git command can contain // globals: // // git --help // // command: // // git version // git diff // // action: // // git remote set-url ... // // command or action flags: // // git diff --shortstat // // command or action args: // // git diff --shortstat main...dev // // post args: // // git diff main...dev -- file1 func Parse(args ...string) *Command { actions := map[string]uint{} c := &Command{ Envs: make(map[string]string), } globalPos := -1 namePos := -1 actionPos := -1 flagsPos := -1 argsPos := -1 postPos := -1 if len(args) == 0 { return c } if strings.ToLower(args[0]) == "git" { args = args[1:] } for i, arg := range args { isFlag := arg != "--" && strings.HasPrefix(arg, "-") b, isCommand := descriptions[arg] _, isAction := actions[arg] switch { case globalPos == -1 && namePos == -1 && isFlag: globalPos = i case namePos == -1 && isCommand: namePos = i actions = b.actions case actionPos == -1 && isAction && !isFlag: actionPos = i case flagsPos == -1 && (namePos >= 0 || actionPos > 0) && isFlag: flagsPos = i case argsPos == -1 && (namePos >= 0 || actionPos > 0) && !isFlag: argsPos = i case postPos == -1 && arg == "--": postPos = i } } end := len(args) if globalPos >= 0 { c.Globals = args[globalPos:cmpPos(namePos, end)] } if namePos >= 0 { c.Name = args[namePos] } if actionPos > 0 { c.Action = args[actionPos] } if flagsPos > 0 { c.Flags = args[flagsPos:cmpPos(argsPos, end)] } if argsPos > 0 { c.Args = args[argsPos:cmpPos(postPos, end)] } if postPos > 0 { c.PostSepArgs = args[postPos+1:] } return c } func cmpPos(check, or int) int { if check == -1 { return or } return check }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/command_test.go
git/command/command_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "bytes" "context" "io" "os" "strings" "testing" "time" "github.com/harness/gitness/errors" "github.com/rs/zerolog/log" ) func TestCreateBareRepository(t *testing.T) { cmd := New("init", WithFlag("--bare"), WithArg("samplerepo")) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() err := cmd.Run(ctx) defer os.RemoveAll("samplerepo") if err != nil { t.Errorf("expected: %v error, got: %v", nil, err) return } cmd = New("rev-parse", WithFlag("--is-bare-repository")) output := &bytes.Buffer{} err = cmd.Run(context.Background(), WithDir("samplerepo"), WithStdout(output)) if err != nil { t.Errorf("expected: %v error, got: %v", nil, err) return } got := strings.TrimSpace(output.String()) exp := "true" if got != exp { t.Errorf("expected value: %s, got: %s", exp, got) return } } func TestCommandContextTimeout(t *testing.T) { cmd := New("init", WithFlag("--bare"), WithArg("samplerepo")) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() err := cmd.Run(ctx) defer os.RemoveAll("samplerepo") if err != nil { t.Errorf("expected: %v error, got: %v", nil, err) } inbuff := &bytes.Buffer{} inbuff.WriteString("some content") outbuffer := &bytes.Buffer{} cmd = New("hash-object", WithFlag("--stdin")) err = cmd.Run(ctx, WithDir("./samplerepo"), WithStdin(inbuff), WithStdout(outbuffer), ) if err != nil { t.Errorf("hashing object failed: %v", err) return } log.Info().Msgf("outbuffer %s", outbuffer.String()) cmd = New("cat-file", WithFlag("--batch")) pr, pw := io.Pipe() defer pr.Close() outbuffer.Reset() go func() { defer pw.Close() for range 3 { _, _ = pw.Write(outbuffer.Bytes()) time.Sleep(1 * time.Second) } }() runCtx, runCancel := context.WithTimeout(context.Background(), 1*time.Second) defer runCancel() err = cmd.Run(runCtx, WithDir("./samplerepo"), WithStdin(pr), WithStdout(outbuffer), ) if !errors.Is(err, context.DeadlineExceeded) { t.Errorf("expected: %v error, got: %v", context.DeadlineExceeded, err) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/error.go
git/command/error.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "errors" "fmt" "os/exec" "strings" ) var ( // ErrInvalidArg represent family of errors to report about bad argument used to make a call. ErrInvalidArg = errors.New("invalid argument") ) // Error type with optional ExitCode and Stderr payload. type Error struct { Err error StdErr []byte } // NewError creates error with source err and stderr payload. func NewError(err error, stderr []byte) *Error { return &Error{ Err: err, StdErr: stderr, } } func (e *Error) ExitCode() int { var exitErr *exec.ExitError ok := errors.As(e.Err, &exitErr) if ok { return exitErr.ExitCode() } return 0 } func (e *Error) IsExitCode(code int) bool { return e.ExitCode() == code } func (e *Error) IsAmbiguousArgErr() bool { return strings.Contains(e.Error(), "ambiguous argument") } func (e *Error) IsBadObject() bool { return strings.Contains(e.Error(), "bad object") } func (e *Error) IsInvalidRefErr() bool { return strings.Contains(e.Error(), "not a valid ref") } func (e *Error) Error() string { if len(e.StdErr) != 0 { return fmt.Sprintf("%s: %s", e.Err.Error(), e.StdErr) } return e.Err.Error() } func (e *Error) Unwrap() error { return e.Err } // AsError unwraps Error otherwise return nil. func AsError(err error) (e *Error) { if errors.As(err, &e) { return } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/option.go
git/command/option.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "io" "strconv" "strings" "time" ) type CmdOptionFunc func(c *Command) // WithGlobal set the global optional flag of the Git command. func WithGlobal(flags ...string) CmdOptionFunc { return func(c *Command) { c.Globals = append(c.Globals, flags...) } } // WithAction set the action of the Git command, e.g. "set-url" in `git remote set-url`. func WithAction(action string) CmdOptionFunc { return func(c *Command) { c.Action = action } } // WithFlag set optional flags to pass before positional arguments. func WithFlag(flags ...string) CmdOptionFunc { return func(c *Command) { c.Flags = append(c.Flags, flags...) } } // WithArg add arguments that shall be passed after all flags. func WithArg(args ...string) CmdOptionFunc { return func(c *Command) { c.Args = append(c.Args, args...) } } // WithPostSepArg set arguments that shall be passed as positional arguments after the `--`. func WithPostSepArg(args ...string) CmdOptionFunc { return func(c *Command) { c.PostSepArgs = append(c.PostSepArgs, args...) } } // WithEnv sets environment variable using key value pair // for example: WithEnv("GIT_TRACE", "true"). func WithEnv(keyValPairs ...string) CmdOptionFunc { return func(c *Command) { for i := 0; i < len(keyValPairs); i += 2 { k, v := keyValPairs[i], keyValPairs[i+1] c.Envs[k] = v } } } // WithCommitter sets given committer to the command. func WithCommitter(name, email string) CmdOptionFunc { return func(c *Command) { c.Envs[GitCommitterName] = name c.Envs[GitCommitterEmail] = email } } // WithCommitterAndDate sets given committer and date to the command. func WithCommitterAndDate(name, email string, date time.Time) CmdOptionFunc { return func(c *Command) { c.Envs[GitCommitterName] = name c.Envs[GitCommitterEmail] = email c.Envs[GitCommitterDate] = date.Format(time.RFC3339) } } // WithAuthor sets given author to the command. func WithAuthor(name, email string) CmdOptionFunc { return func(c *Command) { c.Envs[GitAuthorName] = name c.Envs[GitAuthorEmail] = email } } // WithAuthorAndDate sets given author and date to the command. func WithAuthorAndDate(name, email string, date time.Time) CmdOptionFunc { return func(c *Command) { c.Envs[GitAuthorName] = name c.Envs[GitAuthorEmail] = email c.Envs[GitAuthorDate] = date.Format(time.RFC3339) } } // WithConfig function sets key and value for config command. func WithConfig(key, value string) CmdOptionFunc { return func(c *Command) { c.Envs["GIT_CONFIG_KEY_"+strconv.Itoa(c.configEnvCounter)] = key c.Envs["GIT_CONFIG_VALUE_"+strconv.Itoa(c.configEnvCounter)] = value c.configEnvCounter++ c.Envs["GIT_CONFIG_COUNT"] = strconv.Itoa(c.configEnvCounter) } } // WithAlternateObjectDirs function sets alternates directories for object access. func WithAlternateObjectDirs(dirs ...string) CmdOptionFunc { return func(c *Command) { if len(dirs) > 0 { c.Envs[GitAlternateObjectDirs] = strings.Join(dirs, ":") } } } // RunOption contains option for running a command. type RunOption struct { // Dir is location of repo. Dir string // Stdin is the input to the command. Stdin io.Reader // Stdout is the outputs from the command. Stdout io.Writer // Stderr is the error output from the command. Stderr io.Writer // Envs is environments slice containing (final) immutable // environment pair "ENV=value" Envs []string } type RunOptionFunc func(option *RunOption) // WithDir set directory RunOption.Dir, this is repository dir // where git command should be running. func WithDir(dir string) RunOptionFunc { return func(option *RunOption) { option.Dir = dir } } // WithStdin set RunOption.Stdin reader. func WithStdin(stdin io.Reader) RunOptionFunc { return func(option *RunOption) { option.Stdin = stdin } } // WithStdout set RunOption.Stdout writer. func WithStdout(stdout io.Writer) RunOptionFunc { return func(option *RunOption) { option.Stdout = stdout } } // WithStderr set RunOption.Stderr writer. func WithStderr(stderr io.Writer) RunOptionFunc { return func(option *RunOption) { option.Stderr = stderr } } // WithEnvs sets immutable values as slice, it is always added // et the end of env slice. func WithEnvs(envs ...string) RunOptionFunc { return func(option *RunOption) { option.Envs = append(option.Envs, envs...) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/env_test.go
git/command/env_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "reflect" "testing" ) func TestEnvs_Args(t *testing.T) { tests := []struct { name string e Envs want []string }{ { name: "test envs", e: Envs{ "GIT_TRACE": "true", }, want: []string{"GIT_TRACE=true"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := tt.e.Args(); !reflect.DeepEqual(got, tt.want) { t.Errorf("Args() = %v, want %v", got, tt.want) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/parser_test.go
git/command/parser_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "reflect" "testing" ) func TestParse(t *testing.T) { type args struct { args []string } tests := []struct { name string args args want *Command }{ { name: "git version test", args: args{ args: []string{ "git", "version", }, }, want: &Command{ Name: "version", Envs: make(map[string]string), }, }, { name: "git help test", args: args{ args: []string{ "git", "--help", }, }, want: &Command{ Envs: make(map[string]string), Globals: []string{"--help"}, }, }, { name: "diff basic test", args: args{ args: []string{ "git", "diff", "main...dev", }, }, want: &Command{ Name: "diff", Envs: make(map[string]string), Args: []string{"main...dev"}, }, }, { name: "diff path test", args: args{ args: []string{ "git", "diff", "--shortstat", "main...dev", "--", "file1", "file2", }, }, want: &Command{ Name: "diff", Flags: []string{"--shortstat"}, Args: []string{"main...dev"}, PostSepArgs: []string{ "file1", "file2", }, Envs: make(map[string]string), }, }, { name: "diff path test", args: args{ args: []string{ "git", "diff", "--shortstat", "main...dev", "--", }, }, want: &Command{ Name: "diff", Flags: []string{"--shortstat"}, Args: []string{"main...dev"}, PostSepArgs: []string{}, Envs: make(map[string]string), }, }, { name: "git remote basic test", args: args{ args: []string{ "git", "remote", "set-url", "origin", "http://reponame", }, }, want: &Command{ Name: "remote", Action: "set-url", Args: []string{"origin", "http://reponame"}, Envs: make(map[string]string), }, }, { name: "pack object test", args: args{ args: []string{ "git", "--shallow-file", "", "pack-objects", "--revs", "--thin", "--stdout", "--progress", "--delta-base-offset", }, }, want: &Command{ Globals: []string{"--shallow-file", ""}, Name: "pack-objects", Flags: []string{ "--revs", "--thin", "--stdout", "--progress", "--delta-base-offset", }, Envs: make(map[string]string), }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Parse(tt.args.args...); !reflect.DeepEqual(got, tt.want) { t.Errorf("Parse() = %v, want %v", got, tt.want) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/builder.go
git/command/builder.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "fmt" "math" "runtime" "strconv" "strings" ) const ( // NoRefUpdates denotes a command which will never update refs. NoRefUpdates = 1 << iota // NoEndOfOptions denotes a command which doesn't know --end-of-options. NoEndOfOptions ) type builder struct { flags uint options func() []CmdOptionFunc actions map[string]uint validatePositionalArgs func([]string) error } // supportsEndOfOptions indicates whether a command can handle the // `--end-of-options` option. func (b builder) supportsEndOfOptions() bool { return b.flags&NoEndOfOptions == 0 } // descriptions is a curated list of Git command descriptions. var descriptions = map[string]builder{ "am": {}, "add": {}, "apply": { flags: NoRefUpdates, }, "archive": { // git-archive(1) does not support disambiguating options from paths from revisions. flags: NoRefUpdates | NoEndOfOptions, validatePositionalArgs: func(args []string) error { for _, arg := range args { if strings.HasPrefix(arg, "-") { // check if the argument is a level of compression if _, err := strconv.Atoi(arg[1:]); err == nil { return nil } } if err := validatePositionalArg(arg); err != nil { return err } } return nil }, }, "blame": { // git-blame(1) does not support disambiguating options from paths from revisions. flags: NoRefUpdates | NoEndOfOptions, }, "branch": {}, "bundle": { flags: NoRefUpdates, }, "cat-file": { flags: NoRefUpdates, }, "check-attr": { flags: NoRefUpdates | NoEndOfOptions, }, "check-ref-format": { // git-check-ref-format(1) uses a hand-rolled option parser which doesn't support // `--end-of-options`. flags: NoRefUpdates | NoEndOfOptions, }, "checkout": { // git-checkout(1) does not support disambiguating options from paths from // revisions. flags: NoEndOfOptions, }, "clone": {}, "commit": { flags: 0, }, "commit-graph": { flags: NoRefUpdates, }, "commit-tree": { flags: NoRefUpdates, }, "config": { flags: NoRefUpdates, }, "count-objects": { flags: NoRefUpdates, }, "diff": { flags: NoRefUpdates, }, "diff-tree": { flags: NoRefUpdates, }, "fetch": { flags: 0, }, "for-each-ref": { flags: NoRefUpdates, }, "format-patch": { flags: NoRefUpdates, }, "fsck": { flags: NoRefUpdates, }, "gc": { flags: NoRefUpdates, }, "grep": { // git-grep(1) does not support disambiguating options from paths from // revisions. flags: NoRefUpdates | NoEndOfOptions, }, "hash-object": { flags: NoRefUpdates, }, "index-pack": { flags: NoRefUpdates | NoEndOfOptions, }, "init": { flags: NoRefUpdates, }, "log": { flags: NoRefUpdates, }, "ls-files": { flags: NoRefUpdates, }, "ls-remote": { flags: NoRefUpdates, }, "ls-tree": { flags: NoRefUpdates, }, "merge-base": { flags: NoRefUpdates, }, "merge-file": { flags: NoRefUpdates, }, "merge-tree": { flags: NoRefUpdates, }, "mktag": { flags: NoRefUpdates, }, "mktree": { flags: NoRefUpdates, }, "multi-pack-index": { flags: NoRefUpdates, }, "pack-refs": { flags: NoRefUpdates, }, "pack-objects": { flags: NoRefUpdates, options: configurePackOptions, }, "patch-id": { flags: NoRefUpdates | NoEndOfOptions, }, "prune": { flags: NoRefUpdates, }, "prune-packed": { flags: NoRefUpdates, }, "push": { flags: NoRefUpdates, }, "read-tree": { flags: NoRefUpdates, }, "receive-pack": { flags: 0, }, "remote": { // While git-remote(1)'s `add` subcommand does support `--end-of-options`, // `remove` doesn't. flags: NoEndOfOptions, actions: map[string]uint{ "add": 0, "rename": 0, "remove": 0, "set-head": 0, "set-branches": 0, "get-url": 0, "set-url": 0, "prune": 0, }, }, "repack": { flags: NoRefUpdates, }, "rev-list": { // We cannot use --end-of-options here because pseudo revisions like `--all` // and `--not` count as options. flags: NoRefUpdates | NoEndOfOptions, validatePositionalArgs: func(args []string) error { for _, arg := range args { // git-rev-list(1) supports pseudo-revision arguments which can be // intermingled with normal positional arguments. Given that these // pseudo-revisions have leading dashes, normal validation would // refuse them as positional arguments. We thus override validation // for two of these which we are using in our codebase. There are // more, but we can add them at a later point if they're ever // required. if arg == "--all" || arg == "--not" { continue } if err := validatePositionalArg(arg); err != nil { return fmt.Errorf("rev-list: %w", err) } } return nil }, }, "rev-parse": { // --end-of-options is echoed by git-rev-parse(1) if used without // `--verify`. flags: NoRefUpdates | NoEndOfOptions, }, "show": { flags: NoRefUpdates, }, "show-ref": { flags: NoRefUpdates, }, "symbolic-ref": { flags: 0, }, "tag": { flags: 0, }, "unpack-objects": { flags: NoRefUpdates | NoEndOfOptions, }, "update-ref": { flags: 0, }, "update-index": { flags: NoEndOfOptions, }, "upload-archive": { // git-upload-archive(1) has a handrolled parser which always interprets the // first argument as directory, so we cannot use `--end-of-options`. flags: NoRefUpdates | NoEndOfOptions, }, "upload-pack": { flags: NoRefUpdates, options: func() []CmdOptionFunc { return append([]CmdOptionFunc{ WithConfig("uploadpack.allowFilter", "true"), WithConfig("uploadpack.allowAnySHA1InWant", "true"), }, configurePackOptions()...) }, }, "version": { flags: NoRefUpdates, }, "worktree": { flags: 0, }, "write-tree": { flags: 0, }, } // args validates the given flags and arguments and, if valid, returns the complete command line. func (b builder) args( flags []string, args []string, postSepArgs []string, ) ([]string, error) { cmdArgs := make([]string, 0, len(flags)+len(args)+len(postSepArgs)) cmdArgs = append(cmdArgs, flags...) if b.supportsEndOfOptions() && len(flags) > 0 { cmdArgs = append(cmdArgs, "--end-of-options") } if b.validatePositionalArgs != nil { if err := b.validatePositionalArgs(args); err != nil { return nil, err } } else { for _, a := range args { if err := validatePositionalArg(a); err != nil { return nil, err } } } cmdArgs = append(cmdArgs, args...) if len(postSepArgs) > 0 && len(cmdArgs) > 0 && cmdArgs[len(cmdArgs)-1] != "--end-of-options" { cmdArgs = append(cmdArgs, "--") } // post separator args do not need any validation cmdArgs = append(cmdArgs, postSepArgs...) return cmdArgs, nil } func validatePositionalArg(arg string) error { if strings.HasPrefix(arg, "-") { return fmt.Errorf("positional arg %q cannot start with dash '-': %w", arg, ErrInvalidArg) } return nil } // threadsConfigValue limits the number of threads to prevent overwhelming the system and // exhausting all available CPU resources. func threadsConfigValue(numCPUs int) string { return fmt.Sprintf("%d", int(math.Max(1, math.Floor(math.Log2(float64(numCPUs)))))) } func configurePackOptions() []CmdOptionFunc { return []CmdOptionFunc{ // configuration variable that controls the maximum amount of memory a single thread can use // for the "delta search window" during the packing process. The packing process, performed // by git pack-objects, compresses Git objects (like commits, trees, blobs, and tags) // into a more efficient "packfile" format. WithConfig("pack.windowMemory", "100m"), // configuration variable which controls the number of threads used during packing operations, // specifically when resolving deltas and searching for optimal delta matches. This setting is // relevant for commands like git repack and git pack-objects. WithConfig("pack.threads", threadsConfigValue(runtime.NumCPU())), } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/env.go
git/command/env.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command const ( GitCommitterName = "GIT_COMMITTER_NAME" GitCommitterEmail = "GIT_COMMITTER_EMAIL" GitCommitterDate = "GIT_COMMITTER_DATE" GitAuthorName = "GIT_AUTHOR_NAME" GitAuthorEmail = "GIT_AUTHOR_EMAIL" GitAuthorDate = "GIT_AUTHOR_DATE" GitTrace = "GIT_TRACE" GitTracePack = "GIT_TRACE_PACK_ACCESS" GitTracePackAccess = "GIT_TRACE_PACKET" GitTracePerformance = "GIT_TRACE_PERFORMANCE" GitTraceSetup = "GIT_TRACE_SETUP" GitExecPath = "GIT_EXEC_PATH" // tells Git where to find its binaries. GitObjectDir = "GIT_OBJECT_DIRECTORY" GitAlternateObjectDirs = "GIT_ALTERNATE_OBJECT_DIRECTORIES" ) // Envs custom key value store for environment variables. type Envs map[string]string func (e Envs) Args() []string { slice := make([]string, 0, len(e)) for key, val := range e { slice = append(slice, key+"="+val) } return slice }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/command/command.go
git/command/command.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package command import ( "bytes" "context" "errors" "fmt" "io" "maps" "os/exec" "regexp" "sync" ) var ( GitExecutable = "git" actionRegex = regexp.MustCompile(`^[[:alnum:]]+[-[:alnum:]]*$`) ) // Command contains options for running a git command. type Command struct { // Globals is the number of optional flags to pass before command name. // example: git --shallow-file pack-objects ... Globals []string // Name is the name of the Git command to run, e.g. "log", "cat-file" or "worktree". Name string // Action is the action of the Git command, e.g. "set-url" in `git remote set-url` Action string // Flags is the number of optional flags to pass before positional arguments, e.g. // `--oneline` or `--format=fuller`. Flags []string // Args is the arguments that shall be passed after all flags. These arguments must not be // flags and thus cannot start with `-`. Note that it may be unsafe to use this field in the // case where arguments are directly user-controlled. In that case it is advisable to use // `PostSepArgs` instead. Args []string // PostSepArgs is the arguments that shall be passed as positional arguments after the `--` // separator. Git recognizes that separator as the point where it should stop expecting any // options and treat the remaining arguments as positionals. This should be used when // passing user-controlled input of arbitrary form like for example paths, which may start // with a `-`. PostSepArgs []string // Git environment variables Envs Envs // internal counter for GIT_CONFIG_COUNT environment variable. // more info: [link](https://git-scm.com/docs/git-config#Documentation/git-config.txt-GITCONFIGCOUNT) configEnvCounter int mux sync.RWMutex } // New creates new command for interacting with the git process. func New(name string, options ...CmdOptionFunc) *Command { c := &Command{ Name: name, Envs: make(Envs), } c.Add(options...) return c } // Clone clones the command object. func (c *Command) Clone() *Command { c.mux.RLock() defer c.mux.RUnlock() globals := make([]string, len(c.Globals)) copy(globals, c.Globals) flags := make([]string, len(c.Flags)) copy(flags, c.Flags) args := make([]string, len(c.Args)) copy(args, c.Args) postSepArgs := make([]string, len(c.PostSepArgs)) copy(postSepArgs, c.Flags) envs := make(Envs, len(c.Envs)) maps.Copy(envs, c.Envs) return &Command{ Name: c.Name, Action: c.Action, Flags: flags, Args: args, PostSepArgs: postSepArgs, Envs: envs, configEnvCounter: c.configEnvCounter, } } // Add appends given options to the command. func (c *Command) Add(options ...CmdOptionFunc) *Command { c.mux.Lock() defer c.mux.Unlock() for _, opt := range options { opt(c) } return c } // Run executes the git command with optional configuration using WithXxx functions. func (c *Command) Run(ctx context.Context, opts ...RunOptionFunc) (err error) { options := &RunOption{} for _, f := range opts { f(options) } if options.Stdout == nil { options.Stdout = io.Discard } errAsBuff := false if options.Stderr == nil { options.Stderr = new(bytes.Buffer) errAsBuff = true } args, err := c.makeArgs() if err != nil { return fmt.Errorf("failed to build argument list: %w", err) } cmd := exec.CommandContext(ctx, GitExecutable, args...) if len(c.Envs) > 0 { cmd.Env = c.Envs.Args() } cmd.Env = append(cmd.Env, options.Envs...) cmd.Dir = options.Dir cmd.Stdin = options.Stdin cmd.Stdout = options.Stdout cmd.Stderr = options.Stderr if err = cmd.Start(); err != nil { return err } result := make(chan error) go func() { result <- cmd.Wait() }() select { case <-ctx.Done(): <-result if cmd.Process != nil && cmd.ProcessState != nil && !cmd.ProcessState.Exited() { if err := cmd.Process.Kill(); err != nil && !errors.Is(ctx.Err(), context.DeadlineExceeded) { return fmt.Errorf("kill process: %w", err) } } return ctx.Err() case err = <-result: if err == nil { return nil } var stderr []byte if buff, ok := options.Stderr.(*bytes.Buffer); ok && errAsBuff { stderr = buff.Bytes() } return NewError(err, stderr) } } func (c *Command) makeArgs() ([]string, error) { c.mux.RLock() defer c.mux.RUnlock() var safeArgs []string commandDescription, ok := descriptions[c.Name] if !ok { return nil, fmt.Errorf("invalid sub command name %q: %w", c.Name, ErrInvalidArg) } if commandDescription.options != nil { options := commandDescription.options() for _, option := range options { option(c) } } // add globals if len(c.Globals) > 0 { safeArgs = append(safeArgs, c.Globals...) } safeArgs = append(safeArgs, c.Name) if c.Action != "" { if !actionRegex.MatchString(c.Action) { return nil, fmt.Errorf("invalid action %q: %w", c.Action, ErrInvalidArg) } safeArgs = append(safeArgs, c.Action) } commandArgs, err := commandDescription.args(c.Flags, c.Args, c.PostSepArgs) if err != nil { return nil, err } safeArgs = append(safeArgs, commandArgs...) return safeArgs, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hook/client.go
git/hook/client.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hook import ( "context" "fmt" "strings" ) var ( // ErrNotFound is returned in case resources related to a githook call aren't found. ErrNotFound = fmt.Errorf("not found") ) // Client is an abstraction of a githook client that can be used to trigger githook calls. type Client interface { PreReceive(ctx context.Context, in PreReceiveInput) (Output, error) Update(ctx context.Context, in UpdateInput) (Output, error) PostReceive(ctx context.Context, in PostReceiveInput) (Output, error) } // ClientFactory is an abstraction of a factory that creates a new client based on the provided environment variables. type ClientFactory interface { NewClient(envVars map[string]string) (Client, error) } // TODO: move to single representation once we have our custom Git CLI wrapper. func EnvVarsToMap(in []string) (map[string]string, error) { out := map[string]string{} for _, entry := range in { key, value, ok := strings.Cut(entry, "=") if !ok { return nil, fmt.Errorf("unexpected entry in input: %q", entry) } key = strings.TrimSpace(key) out[key] = value } return out, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hook/types.go
git/hook/types.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hook import "github.com/harness/gitness/git/sha" // Output represents the output of server hook api calls. type Output struct { // Messages contains standard user facing messages. Messages []string `json:"messages,omitempty"` // Error contains the user facing error (like "branch is protected", ...). Error *string `json:"error,omitempty"` } // ReferenceUpdate represents an update of a git reference. type ReferenceUpdate struct { // Ref is the full name of the reference that got updated. Ref string `json:"ref"` // Old is the old commmit hash (before the update). Old sha.SHA `json:"old"` // New is the new commit hash (after the update). New sha.SHA `json:"new"` } // Environment contains the information required to access a specific git environment. type Environment struct { // AlternateObjectDirs contains any alternate object dirs required to access all objects of an operation. AlternateObjectDirs []string `json:"alternate_object_dirs,omitempty"` } // PreReceiveInput represents the input of the pre-receive git hook. type PreReceiveInput struct { // Environment contains the information required to access the git environment. Environment Environment `json:"environment"` // RefUpdates contains all references that are being updated as part of the git operation. RefUpdates []ReferenceUpdate `json:"ref_updates"` } // UpdateInput represents the input of the update git hook. type UpdateInput struct { // Environment contains the information required to access the git environment. Environment Environment `json:"environment"` // RefUpdate contains information about the reference that is being updated. RefUpdate ReferenceUpdate `json:"ref_update"` } // PostReceiveInput represents the input of the post-receive git hook. type PostReceiveInput struct { // Environment contains the information required to access the git environment. Environment Environment `json:"environment"` // RefUpdates contains all references that got updated as part of the git operation. RefUpdates []ReferenceUpdate `json:"ref_updates"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hook/cli_core.go
git/hook/cli_core.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hook import ( "bufio" "context" "errors" "fmt" "io" "os" "strings" "time" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) // CLICore implements the core of a githook cli. It uses the client and execution timeout // to perform githook operations as part of a cli. type CLICore struct { client Client executionTimeout time.Duration } // NewCLICore returns a new CLICore using the provided client and execution timeout. func NewCLICore(client Client, executionTimeout time.Duration) *CLICore { return &CLICore{ client: client, executionTimeout: executionTimeout, } } // PreReceive executes the pre-receive git hook. func (c *CLICore) PreReceive(ctx context.Context) error { refUpdates, err := getUpdatedReferencesFromStdIn() if err != nil { return fmt.Errorf("failed to read updated references from std in: %w", err) } alternateObjDirs, err := getAlternateObjectDirsFromEnv(refUpdates) if err != nil { return fmt.Errorf("failed to read alternate object dirs from env: %w", err) } in := PreReceiveInput{ RefUpdates: refUpdates, Environment: Environment{ AlternateObjectDirs: alternateObjDirs, }, } out, err := c.client.PreReceive(ctx, in) return handleServerHookOutput(out, err) } // Update executes the update git hook. func (c *CLICore) Update(ctx context.Context, ref string, oldSHARaw string, newSHARaw string) error { newSHA := sha.Must(newSHARaw) oldSHA := sha.Must(oldSHARaw) alternateObjDirs, err := getAlternateObjectDirsFromEnv([]ReferenceUpdate{{Ref: ref, Old: oldSHA, New: newSHA}}) if err != nil { return fmt.Errorf("failed to read alternate object dirs from env: %w", err) } in := UpdateInput{ RefUpdate: ReferenceUpdate{ Ref: ref, Old: oldSHA, New: newSHA, }, Environment: Environment{ AlternateObjectDirs: alternateObjDirs, }, } out, err := c.client.Update(ctx, in) return handleServerHookOutput(out, err) } // PostReceive executes the post-receive git hook. func (c *CLICore) PostReceive(ctx context.Context) error { refUpdates, err := getUpdatedReferencesFromStdIn() if err != nil { return fmt.Errorf("failed to read updated references from std in: %w", err) } in := PostReceiveInput{ RefUpdates: refUpdates, Environment: Environment{ AlternateObjectDirs: nil, // all objects are in main objects folder at this point }, } out, err := c.client.PostReceive(ctx, in) return handleServerHookOutput(out, err) } //nolint:forbidigo // outputing to CMD as that's where git reads the data func handleServerHookOutput(out Output, err error) error { if err != nil { return fmt.Errorf("an error occurred when calling the server: %w", err) } // remove any preceding empty lines for len(out.Messages) > 0 && out.Messages[0] == "" { out.Messages = out.Messages[1:] } // remove any trailing empty lines for len(out.Messages) > 0 && out.Messages[len(out.Messages)-1] == "" { out.Messages = out.Messages[:len(out.Messages)-1] } // print messages before any error if len(out.Messages) > 0 { // add empty line before and after to make it easier readable fmt.Println() for _, msg := range out.Messages { fmt.Println(msg) } fmt.Println() } if out.Error != nil { return errors.New(*out.Error) } return nil } // getUpdatedReferencesFromStdIn reads the updated references provided by git from stdin. // The expected format is "<old-value> SP <new-value> SP <ref-name> LF" // For more details see https://git-scm.com/docs/githooks#pre-receive func getUpdatedReferencesFromStdIn() ([]ReferenceUpdate, error) { reader := bufio.NewReader(os.Stdin) updatedRefs := []ReferenceUpdate{} for { line, err := reader.ReadString('\n') // if end of file is reached, break the loop if err == io.EOF { break } if err != nil { fmt.Printf("Error when reading from standard input - %s\n", err) //nolint:forbidigo // executes as cli. return nil, err } if len(line) == 0 { return nil, errors.New("ref data from stdin contains empty line - not expected") } // splitting line of expected form "<old-value> SP <new-value> SP <ref-name> LF" splitGitHookData := strings.Split(line[:len(line)-1], " ") if len(splitGitHookData) != 3 { return nil, fmt.Errorf("received invalid data format or didn't receive enough parameters - %v", splitGitHookData) } updatedRefs = append(updatedRefs, ReferenceUpdate{ Old: sha.Must(splitGitHookData[0]), New: sha.Must(splitGitHookData[1]), Ref: splitGitHookData[2], }) } return updatedRefs, nil } // getAlternateObjectDirsFromEnv returns the alternate object directories that have to be used // to be able to preemptively access the quarantined objects created by a write operation. // NOTE: The temp dir of a write operation is it's main object dir, // which is the one that read operations have to use as alternate object dir. func getAlternateObjectDirsFromEnv(refUpdates []ReferenceUpdate) ([]string, error) { hasCreateOrUpdate := false for i := range refUpdates { if !refUpdates[i].New.IsNil() { hasCreateOrUpdate = true break } } // git doesn't create an alternate object dir if there's only delete operations if !hasCreateOrUpdate { return nil, nil } tmpDir, err := getRequiredEnvironmentVariable(command.GitObjectDir) if err != nil { return nil, err } return []string{tmpDir}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hook/client_ noop.go
git/hook/client_ noop.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hook import ( "context" ) // NoopClient directly returns success with the provided messages, without any other impact. type NoopClient struct { messages []string } func NewNoopClient(messages []string) Client { return &NoopClient{messages: messages} } func (c *NoopClient) PreReceive(_ context.Context, _ PreReceiveInput) (Output, error) { return Output{Messages: c.messages}, nil } func (c *NoopClient) Update(_ context.Context, _ UpdateInput) (Output, error) { return Output{Messages: c.messages}, nil } func (c *NoopClient) PostReceive(_ context.Context, _ PostReceiveInput) (Output, error) { return Output{Messages: c.messages}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hook/cli.go
git/hook/cli.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hook import ( "context" "errors" "os/signal" "syscall" "gopkg.in/alecthomas/kingpin.v2" ) const ( // ParamPreReceive is the parameter under which the pre-receive operation is registered. ParamPreReceive = "pre-receive" // ParamUpdate is the parameter under which the update operation is registered. ParamUpdate = "update" // ParamPostReceive is the parameter under which the post-receive operation is registered. ParamPostReceive = "post-receive" // CommandNamePreReceive is the command used by git for the pre-receive hook // (os.args[0] == "hooks/pre-receive"). CommandNamePreReceive = "hooks/pre-receive" // CommandNameUpdate is the command used by git for the update hook // (os.args[0] == "hooks/update"). CommandNameUpdate = "hooks/update" // CommandNamePostReceive is the command used by git for the post-receive hook // (os.args[0] == "hooks/post-receive"). CommandNamePostReceive = "hooks/post-receive" ) // SanitizeArgsForGit sanitizes the command line arguments (os.Args) if the command indicates they are coming from git. // Returns the santized args and true if the call comes from git, otherwise the original args are returned with false. func SanitizeArgsForGit(command string, args []string) ([]string, bool) { switch command { case CommandNamePreReceive: return append([]string{ParamPreReceive}, args...), true case CommandNameUpdate: return append([]string{ParamUpdate}, args...), true case CommandNamePostReceive: return append([]string{ParamPostReceive}, args...), true default: return args, false } } // KingpinRegister is an abstraction of an entity that allows to register commands. // This is required to allow registering hook commands both on application and sub command level. type KingpinRegister interface { Command(name, help string) *kingpin.CmdClause } var ( // ErrDisabled can be returned by the loading function to indicate the githook has been disabled. // Returning the error will cause the githook execution to be skipped (githook is noop and returns success). ErrDisabled = errors.New("githook disabled") ) // LoadCLICoreFunc is a function that creates a new CLI core that's used for githook cli execution. // This allows users to initialize their own CLI core with custom Client and configuration. type LoadCLICoreFunc func() (*CLICore, error) // RegisterAll registers all githook commands. func RegisterAll(cmd KingpinRegister, loadCoreFn LoadCLICoreFunc) { RegisterPreReceive(cmd, loadCoreFn) RegisterUpdate(cmd, loadCoreFn) RegisterPostReceive(cmd, loadCoreFn) } // RegisterPreReceive registers the pre-receive githook command. func RegisterPreReceive(cmd KingpinRegister, loadCoreFn LoadCLICoreFunc) { c := &preReceiveCommand{ loadCoreFn: loadCoreFn, } cmd.Command(ParamPreReceive, "hook that is executed before any reference of the push is updated"). Action(c.run) } // RegisterUpdate registers the update githook command. func RegisterUpdate(cmd KingpinRegister, loadCoreFn LoadCLICoreFunc) { c := &updateCommand{ loadCoreFn: loadCoreFn, } subCmd := cmd.Command(ParamUpdate, "hook that is executed before the specific reference gets updated"). Action(c.run) subCmd.Arg("ref", "reference for which the hook is executed"). Required(). StringVar(&c.ref) subCmd.Arg("old", "old commit sha"). Required(). StringVar(&c.oldSHA) subCmd.Arg("new", "new commit sha"). Required(). StringVar(&c.newSHA) } // RegisterPostReceive registers the post-receive githook command. func RegisterPostReceive(cmd KingpinRegister, loadCoreFn LoadCLICoreFunc) { c := &postReceiveCommand{ loadCoreFn: loadCoreFn, } cmd.Command(ParamPostReceive, "hook that is executed after all references of the push got updated"). Action(c.run) } type preReceiveCommand struct { loadCoreFn LoadCLICoreFunc } func (c *preReceiveCommand) run(*kingpin.ParseContext) error { return run(c.loadCoreFn, func(ctx context.Context, core *CLICore) error { return core.PreReceive(ctx) }) } type updateCommand struct { loadCoreFn LoadCLICoreFunc ref string oldSHA string newSHA string } func (c *updateCommand) run(*kingpin.ParseContext) error { return run(c.loadCoreFn, func(ctx context.Context, core *CLICore) error { return core.Update(ctx, c.ref, c.oldSHA, c.newSHA) }) } type postReceiveCommand struct { loadCoreFn LoadCLICoreFunc } func (c *postReceiveCommand) run(*kingpin.ParseContext) error { return run(c.loadCoreFn, func(ctx context.Context, core *CLICore) error { return core.PostReceive(ctx) }) } func run(loadCoreFn LoadCLICoreFunc, fn func(ctx context.Context, core *CLICore) error) error { core, err := loadCoreFn() if errors.Is(err, ErrDisabled) { // complete operation successfully without making any calls to the server. return nil } if err != nil { return err } // Create context that listens for the interrupt signal from the OS and has a timeout. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() ctx, cancel := context.WithTimeout(ctx, core.executionTimeout) defer cancel() return fn(ctx, core) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hook/env.go
git/hook/env.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hook import ( "bytes" "encoding/base64" "encoding/gob" "fmt" "os" ) const ( // envNamePayload defines the environment variable name used to send the payload to githook binary. envNamePayload = "GIT_HOOK_PAYLOAD" ) // GenerateEnvironmentVariables generates the environment variables that should be used when calling git // to ensure the payload will be available to the githook cli. func GenerateEnvironmentVariables(payload any) (map[string]string, error) { // serialize the payload payloadBuff := &bytes.Buffer{} encoder := gob.NewEncoder(payloadBuff) if err := encoder.Encode(payload); err != nil { return nil, fmt.Errorf("failed to encode payload: %w", err) } // send it as base64 to avoid issues with any problematic characters // NOTE: this will blow up the payload by ~33%, though it's not expected to be too big. // On the other hand, we save a lot of size by only needing one environment variable name. payloadBase64 := base64.StdEncoding.EncodeToString(payloadBuff.Bytes()) return map[string]string{ envNamePayload: payloadBase64, }, nil } // LoadPayloadFromMap loads the payload from a map containing environment variables in a map format. func LoadPayloadFromMap[T any](envVars map[string]string) (T, error) { var payload T // retrieve payload from environment variables payloadBase64, ok := envVars[envNamePayload] if !ok { return payload, fmt.Errorf("environment variable %q not found", envNamePayload) } return decodePayload[T](payloadBase64) } // LoadPayloadFromEnvironment loads the githook payload from the environment. func LoadPayloadFromEnvironment[T any]() (T, error) { var payload T // retrieve payload from environment variables payloadBase64, err := getRequiredEnvironmentVariable(envNamePayload) if err != nil { return payload, fmt.Errorf("failed to load payload from environment variables: %w", err) } return decodePayload[T](payloadBase64) } func decodePayload[T any](encodedPayload string) (T, error) { var payload T // decode base64 payloadBytes, err := base64.StdEncoding.DecodeString(encodedPayload) if err != nil { return payload, fmt.Errorf("failed to base64 decode payload: %w", err) } // deserialize the payload decoder := gob.NewDecoder(bytes.NewReader(payloadBytes)) err = decoder.Decode(&payload) if err != nil { return payload, fmt.Errorf("failed to deserialize payload: %w", err) } return payload, nil } func getRequiredEnvironmentVariable(name string) (string, error) { val, ok := os.LookupEnv(name) if !ok { return "", fmt.Errorf("environment variable %q not found", name) } if val == "" { return "", fmt.Errorf("environment variable %q found but it's empty", name) } return val, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/hook/refupdate.go
git/hook/refupdate.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hook import ( "bytes" "context" "fmt" "sort" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" "github.com/rs/zerolog/log" ) // CreateRefUpdater creates new RefUpdater object using the provided git hook ClientFactory. func CreateRefUpdater( hookClientFactory ClientFactory, envVars map[string]string, repoPath string, ) (*RefUpdater, error) { if repoPath == "" { return nil, errors.Internal(nil, "repo path can't be empty") } client, err := hookClientFactory.NewClient(envVars) if err != nil { return nil, fmt.Errorf("failed to create hook.Client: %w", err) } return &RefUpdater{ state: stateInit, hookClient: client, envVars: envVars, repoPath: repoPath, refs: nil, }, nil } // RefUpdater is an entity that is responsible for update of a reference. // It will call pre-receive hook prior to the update and post-receive hook after the update. // It has a state machine to guarantee that methods are called in the correct order (Init, Pre, Update, Post). type RefUpdater struct { state refUpdaterState hookClient Client envVars map[string]string repoPath string refs []ReferenceUpdate } // refUpdaterState represents state of the ref updater internal state machine. type refUpdaterState byte func (t refUpdaterState) String() string { switch t { case stateInit: return "INIT" case statePre: return "PRE" case stateUpdate: return "UPDATE" case statePost: return "POST" case stateDone: return "DONE" } return "INVALID" } const ( stateInit refUpdaterState = iota statePre stateUpdate statePost stateDone ) // Do runs full ref update by executing all methods in the correct order. func (u *RefUpdater) Do(ctx context.Context, refs []ReferenceUpdate) error { if err := u.Init(ctx, refs); err != nil { return fmt.Errorf("init failed: %w", err) } if err := u.Pre(ctx); err != nil { return fmt.Errorf("pre failed: %w", err) } if err := u.UpdateRef(ctx); err != nil { return fmt.Errorf("update failed: %w", err) } if err := u.Post(ctx); err != nil { return fmt.Errorf("post failed: %w", err) } return nil } // DoOne runs full ref update of only one reference. func (u *RefUpdater) DoOne(ctx context.Context, ref string, oldValue, newValue sha.SHA) error { return u.Do(ctx, []ReferenceUpdate{ { Ref: ref, Old: oldValue, New: newValue, }, }) } func (u *RefUpdater) Init(ctx context.Context, refs []ReferenceUpdate) error { if u.state != stateInit { return fmt.Errorf("invalid operation order: init old requires state=%s, current state=%s", stateInit, u.state) } u.refs = make([]ReferenceUpdate, 0, len(refs)) for _, ref := range refs { oldValue := ref.Old newValue := ref.New var oldValueKnown bool if oldValue.IsEmpty() { // if no old value was provided, use current value (as required for hooks) val, err := u.getRef(ctx, ref.Ref) if errors.IsNotFound(err) { //nolint:gocritic oldValue = sha.Nil } else if err != nil { return fmt.Errorf("failed to get current value of reference %q: %w", ref.Ref, err) } else { oldValue = val } oldValueKnown = true } if newValue.IsEmpty() { // don't break existing interface - user calls with empty value to delete the ref. newValue = sha.Nil } if oldValueKnown && oldValue == newValue { // skip the unchanged refs continue } u.refs = append(u.refs, ReferenceUpdate{ Ref: ref.Ref, Old: oldValue, New: newValue, }) } sort.Slice(u.refs, func(i, j int) bool { return u.refs[i].Ref < u.refs[j].Ref }) u.state = statePre return nil } // Pre runs the pre-receive git hook. func (u *RefUpdater) Pre(ctx context.Context, alternateDirs ...string) error { if u.state != statePre { return fmt.Errorf("invalid operation order: pre-receive hook requires state=%s, current state=%s", statePre, u.state) } if len(u.refs) == 0 { u.state = stateUpdate return nil } out, err := u.hookClient.PreReceive(ctx, PreReceiveInput{ RefUpdates: u.refs, Environment: Environment{ AlternateObjectDirs: alternateDirs, }, }) if err != nil { return fmt.Errorf("pre-receive call failed with: %w", err) } if out.Error != nil { log.Ctx(ctx).Debug(). Str("err", *out.Error). Msgf("Pre-receive blocked ref update\nMessages\n%v", out.Messages) return errors.PreconditionFailedf("pre-receive hook blocked reference update: %q", *out.Error) } u.state = stateUpdate return nil } // UpdateRef updates the git reference. func (u *RefUpdater) UpdateRef(ctx context.Context) error { if u.state != stateUpdate { return fmt.Errorf("invalid operation order: ref update requires state=%s, current state=%s", stateUpdate, u.state) } if len(u.refs) == 0 { u.state = statePost return nil } input := bytes.NewBuffer(nil) for _, ref := range u.refs { switch { case ref.New.IsNil(): _, _ = fmt.Fprintf(input, "delete %s\000%s\000", ref.Ref, ref.Old) case ref.Old.IsNil(): _, _ = fmt.Fprintf(input, "create %s\000%s\000", ref.Ref, ref.New) default: _, _ = fmt.Fprintf(input, "update %s\000%s\000%s\000", ref.Ref, ref.New, ref.Old) } } input.WriteString("commit\000") cmd := command.New("update-ref", command.WithFlag("--stdin"), command.WithFlag("-z")) if err := cmd.Run(ctx, command.WithStdin(input), command.WithDir(u.repoPath)); err != nil { msg := err.Error() if strings.Contains(msg, "reference already exists") { return errors.Conflict("reference already exists") } return fmt.Errorf("update of references %v failed: %w", u.refs, err) } u.state = statePost return nil } // Post runs the pre-receive git hook. func (u *RefUpdater) Post(ctx context.Context, alternateDirs ...string) error { if u.state != statePost { return fmt.Errorf("invalid operation order: post-receive hook requires state=%s, current state=%s", statePost, u.state) } if len(u.refs) == 0 { u.state = stateDone return nil } out, err := u.hookClient.PostReceive(ctx, PostReceiveInput{ RefUpdates: u.refs, Environment: Environment{ AlternateObjectDirs: alternateDirs, }, }) if err != nil { return fmt.Errorf("post-receive call failed with: %w", err) } if out.Error != nil { return fmt.Errorf("post-receive call returned error: %q", *out.Error) } u.state = stateDone return nil } func (u *RefUpdater) getRef(ctx context.Context, ref string) (sha.SHA, error) { cmd := command.New("show-ref", command.WithFlag("--verify"), command.WithFlag("-s"), command.WithArg(ref), ) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(u.repoPath), command.WithStdout(output)) if cErr := command.AsError(err); cErr != nil && cErr.IsExitCode(128) && cErr.IsInvalidRefErr() { return sha.None, errors.NotFoundf("reference %q not found", ref) } if err != nil { return sha.None, err } return sha.New(output.String()) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sharedrepo/remote.go
git/sharedrepo/remote.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sharedrepo import ( "context" "fmt" "regexp" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) var reNotOurRef = regexp.MustCompile("upload-pack: not our ref ([a-fA-f0-9]+)$") // FetchObjects pull git objects from a different repository. // It doesn't update any references. func (r *SharedRepo) FetchObjects( ctx context.Context, source string, objectSHAs []sha.SHA, ) error { cmd := command.New("fetch", command.WithConfig("advice.fetchShowForcedUpdates", "false"), command.WithConfig("credential.helper", ""), command.WithFlag( "--quiet", "--no-auto-gc", // because we're fetching objects that are not referenced "--no-tags", "--no-write-fetch-head", "--no-show-forced-updates", ), command.WithArg(source), ) for _, objectSHA := range objectSHAs { cmd.Add(command.WithArg(objectSHA.String())) } err := cmd.Run(ctx, command.WithDir(r.repoPath)) if err != nil { if parts := reNotOurRef.FindStringSubmatch(strings.TrimSpace(err.Error())); parts != nil { return errors.InvalidArgumentf("Unrecognized git object: %s", parts[1]) } return fmt.Errorf("failed to fetch objects: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sharedrepo/line_number_test.go
git/sharedrepo/line_number_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sharedrepo import ( "math" "testing" "github.com/stretchr/testify/assert" ) func Test_lineNumberIsEOF(t *testing.T) { assert.True(t, lineNumberEOF.IsEOF(), "lineNumberEOF should be EOF") assert.True(t, lineNumber(math.MaxInt64).IsEOF(), "lineNumberEOF should be EOF") assert.False(t, lineNumber(1).IsEOF(), "1 should not be EOF") } func Test_lineNumberString(t *testing.T) { assert.Equal(t, "eof", lineNumberEOF.String(), "lineNumberEOF should be 'eof'") assert.Equal(t, "eof", lineNumber(math.MaxInt64).String(), "math.MaxInt64 should be 'eof'") assert.Equal(t, "1", lineNumber(1).String(), "1 should be '1'") } func Test_parseLineNumber(t *testing.T) { tests := []struct { name string arg []byte wantErr string want lineNumber }{ { name: "test empty", arg: nil, wantErr: "line number can't be empty", }, { name: "test not a number", arg: []byte("test"), wantErr: "unable to parse", }, { name: "test maxInt64+1 fails", arg: []byte("9223372036854775808"), wantErr: "unable to parse", }, { name: "test smaller than 1", arg: []byte("0"), wantErr: "line numbering starts at 1", }, { name: "test maxInt64 not allowed", arg: []byte("9223372036854775807"), wantErr: "line numbering ends at 9223372036854775806", }, { name: "test smallest valid number (1)", arg: []byte("1"), want: 1, }, { name: "test biggest valid number (maxInt64-1)", arg: []byte("9223372036854775806"), want: 9223372036854775806, }, { name: "test eof", arg: []byte("eof"), want: lineNumberEOF, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseLineNumber(tt.arg) if tt.wantErr != "" { assert.ErrorContains(t, err, tt.wantErr, "error doesn't match expected.") } else { assert.Equal(t, tt.want, got, "parsed valued doesn't match expected") } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sharedrepo/sharedrepo_test.go
git/sharedrepo/sharedrepo_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sharedrepo import ( "bytes" "reflect" "testing" "github.com/harness/gitness/git/parser" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_parsePatchTextFilePayloads(t *testing.T) { tests := []struct { name string arg [][]byte wantErr string want []patchTextFileReplacement }{ { name: "test no payloads", arg: nil, want: []patchTextFileReplacement{}, }, { name: "test no zero byte splitter", arg: [][]byte{ []byte("0:1"), }, wantErr: "Payload format is missing the content separator", }, { name: "test line range wrong format", arg: [][]byte{ []byte("0\u0000"), }, wantErr: "Payload is missing the line number separator", }, { name: "test start line error returned", arg: [][]byte{ []byte("0:1\u0000"), }, wantErr: "Payload start line number is invalid", }, { name: "test end line error returned", arg: [][]byte{ []byte("1:a\u0000"), }, wantErr: "Payload end line number is invalid", }, { name: "test end smaller than start", arg: [][]byte{ []byte("2:1\u0000"), }, wantErr: "Payload end line has to be at least as big as start line", }, { name: "payload empty", arg: [][]byte{ []byte("1:2\u0000"), }, want: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 2, Content: []byte{}, }, }, }, { name: "payload non-empty with zero byte and line endings", arg: [][]byte{ []byte("1:eof\u0000a\nb\r\nc\u0000d"), }, want: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: lineNumberEOF, Content: []byte("a\nb\r\nc\u0000d"), }, }, }, { name: "multiple payloads", arg: [][]byte{ []byte("1:3\u0000a"), []byte("2:eof\u0000b"), }, want: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 3, Content: []byte("a"), }, { OmitFrom: 2, ContinueFrom: lineNumberEOF, Content: []byte("b"), }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parsePatchTextFilePayloads(tt.arg) if tt.wantErr != "" { assert.ErrorContains(t, err, tt.wantErr, "error doesn't match expected.") } else if !reflect.DeepEqual(got, tt.want) { t.Errorf("parsePatchTextFilePayloads() = %s, want %s", got, tt.want) } }) } } func Test_patchTextFileWritePatchedFile(t *testing.T) { type arg struct { file []byte replacements []patchTextFileReplacement } tests := []struct { name string arg arg wantErr string want []byte wantLE string }{ { name: "test no replacements (empty file)", arg: arg{ file: []byte(""), replacements: nil, }, wantLE: "\n", want: nil, }, { name: "test no replacements (single line no line ending)", arg: arg{ file: []byte("l1"), replacements: nil, }, wantLE: "\n", want: []byte("l1"), }, { name: "test no replacements keeps final line ending (LF)", arg: arg{ file: []byte("l1\n"), replacements: nil, }, wantLE: "\n", want: []byte("l1\n"), }, { name: "test no replacements keeps final line ending (CRLF)", arg: arg{ file: []byte("l1\r\n"), replacements: nil, }, wantLE: "\r\n", want: []byte("l1\r\n"), }, { name: "test no replacements multiple line endings", arg: arg{ file: []byte("l1\r\nl2\nl3"), replacements: nil, }, wantLE: "\r\n", want: []byte("l1\r\nl2\nl3"), }, { name: "test line ending correction with replacements (LF)", arg: arg{ file: []byte("l1\nl2\r\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: 2, Content: []byte("rl1\nrl2\r\nrl3"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1\nrl2\nrl3\nl2\r\nl3"), }, { name: "test line ending correction with replacements (CRLF)", arg: arg{ file: []byte("l1\r\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: 2, Content: []byte("rl1\nrl2\r\nrl3"), }, }, }, wantLE: "\r\n", want: []byte("l1\r\nrl1\r\nrl2\r\nrl3\r\nl2\nl3"), }, { name: "test line ending with replacements at eof (file none, replacement none)", arg: arg{ file: []byte("l1\nl2"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: lineNumberEOF, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1"), }, { name: "test line ending with replacements at eof (file none, replacement yes)", arg: arg{ file: []byte("l1\nl2"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: lineNumberEOF, Content: []byte("rl1\r\n"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1\n"), }, { name: "test line ending with replacements at eof (file yes, replacement none)", arg: arg{ file: []byte("l1\nl2\r\n"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: lineNumberEOF, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1"), }, { name: "test line ending with replacements at eof (file yes, replacement yes)", arg: arg{ file: []byte("l1\nl2\r\n"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: lineNumberEOF, Content: []byte("rl1\r\n"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1\n"), }, { name: "test final line ending doesn't increase line count", arg: arg{ file: []byte("l1\n"), replacements: []patchTextFileReplacement{ { OmitFrom: 3, ContinueFrom: 3, Content: []byte("rl1\r\n"), }, }, }, wantErr: "Patch action for [3,3) is exceeding end of file with 1 line(s)", }, { name: "test replacement out of bounds (start)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 3, ContinueFrom: lineNumberEOF, Content: []byte("rl1\r\n"), }, }, }, wantErr: "Patch action for [3,eof) is exceeding end of file with 1 line(s)", }, { name: "test replacement out of bounds (end)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 3, Content: []byte("rl1\r\n"), }, }, }, wantErr: "Patch action for [1,3) is exceeding end of file with 1 line(s)", }, { name: "test replacement out of bounds (after eof)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: lineNumberEOF, Content: []byte("rl1\r\n"), }, { OmitFrom: 2, ContinueFrom: 3, Content: []byte("rl1\r\n"), }, }, }, wantErr: "Patch action for [2,3) is exceeding end of file with 1 line(s)", }, { name: "test replacement out of bounds (after last line)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 2, Content: []byte("rl1\r\n"), }, { OmitFrom: 3, ContinueFrom: 4, Content: []byte("rl1\r\n"), }, }, }, wantErr: "Patch action for [3,4) is exceeding end of file with 1 line(s)", }, { name: "test overlap before eof (with empty)", arg: arg{ file: []byte(""), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 3, Content: []byte(""), }, { OmitFrom: 2, ContinueFrom: 2, Content: []byte(""), }, }, }, wantErr: "Patch actions have conflicting ranges [1,3)x[2,2)", }, { name: "test overlap before eof (non-empty + unordered)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: 3, Content: []byte(""), }, { OmitFrom: 1, ContinueFrom: 3, Content: []byte(""), }, }, }, wantErr: "Patch actions have conflicting ranges [1,3)x[2,3)", }, { name: "test overlap before eof (non-empty eof end)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 3, Content: []byte(""), }, { OmitFrom: 2, ContinueFrom: lineNumberEOF, Content: []byte(""), }, }, }, wantErr: "Patch actions have conflicting ranges [1,3)x[2,eof)", }, { name: "test overlap after eof (empty)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: lineNumberEOF, Content: []byte(""), }, { OmitFrom: 2, ContinueFrom: 2, Content: []byte(""), }, }, }, wantErr: "Patch actions have conflicting ranges [1,eof)x[2,2) for file with 3 line(s)", }, { name: "test overlap after eof (non-empty + unordered)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: 3, Content: []byte(""), }, { OmitFrom: 1, ContinueFrom: lineNumberEOF, Content: []byte(""), }, }, }, wantErr: "Patch actions have conflicting ranges [1,eof)x[2,3) for file with 3 line(s)", }, { name: "test overlap after eof (none-empty eof end)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: lineNumberEOF, Content: []byte(""), }, { OmitFrom: 1, ContinueFrom: lineNumberEOF, Content: []byte(""), }, }, }, wantErr: "Patch actions have conflicting ranges [1,eof)x[2,eof) for file with 3 line(s)", }, { name: "test insert (empty)", arg: arg{ file: nil, replacements: []patchTextFileReplacement{ { OmitFrom: lineNumberEOF, ContinueFrom: lineNumberEOF, Content: []byte("rl1\r\nrl2"), }, }, }, wantLE: "\n", want: []byte("rl1\nrl2"), }, { name: "test insert (start)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 1, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("rl1\nl1"), }, { name: "test insert (middle)", arg: arg{ file: []byte("l1\nl2"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: 2, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1\nl2"), }, { name: "test insert (end)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: 2, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1"), }, { name: "test insert (eof)", arg: arg{ file: []byte("l1"), replacements: []patchTextFileReplacement{ { OmitFrom: lineNumberEOF, ContinueFrom: lineNumberEOF, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1"), }, { name: "test inserts (multiple at start+middle+end(normal+eof))", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 1, Content: []byte("r1l1\nr1l2"), }, { OmitFrom: 1, ContinueFrom: 1, Content: []byte("r2l1\nr2l2"), }, { OmitFrom: 2, ContinueFrom: 2, Content: []byte("r3l1\nr3l2"), }, { OmitFrom: 2, ContinueFrom: 2, Content: []byte("r4l1\nr4l2"), }, { OmitFrom: 4, ContinueFrom: 4, Content: []byte("r5l1\nr5l2"), }, { OmitFrom: 4, ContinueFrom: 4, Content: []byte("r6l1\nr6l2"), }, { OmitFrom: lineNumberEOF, ContinueFrom: lineNumberEOF, Content: []byte("r7l1\nr7l2"), }, { OmitFrom: lineNumberEOF, ContinueFrom: lineNumberEOF, Content: []byte("r8l1\nr8l2"), }, }, }, wantLE: "\n", want: []byte( "r1l1\nr1l2\nr2l1\nr2l2\nl1\nr3l1\nr3l2\nr4l1\nr4l2\nl2\nl3\nr5l1\nr5l2\nr6l1\nr6l2\nr7l1\nr7l2\nr8l1\nr8l2"), }, { name: "test replace (head)", arg: arg{ file: []byte("l1\nl2"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 2, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("rl1\nl2"), }, { name: "test replace (middle)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 2, ContinueFrom: 3, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nrl1\nl3"), }, { name: "test replace (end)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 3, ContinueFrom: 4, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nl2\nrl1"), }, { name: "test replace (eof)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 3, ContinueFrom: lineNumberEOF, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("l1\nl2\nrl1"), }, { name: "test replace (1-end)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: 4, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("rl1"), }, { name: "test replace (1-eof)", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 1, ContinueFrom: lineNumberEOF, Content: []byte("rl1"), }, }, }, wantLE: "\n", want: []byte("rl1"), }, { name: "test sorting", arg: arg{ file: []byte("l1\nl2\nl3"), replacements: []patchTextFileReplacement{ { OmitFrom: 4, ContinueFrom: 4, Content: []byte("r5l1\nr5l2\r\n"), }, { OmitFrom: 4, ContinueFrom: lineNumberEOF, Content: []byte("r7l1\nr7l2\r\n"), }, { OmitFrom: 1, ContinueFrom: 1, Content: []byte("r0l1\nr0l2\r\n"), }, { OmitFrom: 2, ContinueFrom: 4, Content: []byte("r4l1\nr4l2\r\n"), }, { OmitFrom: 4, ContinueFrom: 4, Content: []byte("r6l1\nr6l2\r\n"), }, { OmitFrom: 1, ContinueFrom: 2, Content: []byte("r2l1\nr2l2\r\n"), }, { OmitFrom: 1, ContinueFrom: 1, Content: []byte("r1l1\nr1l2\r\n"), }, { OmitFrom: lineNumberEOF, ContinueFrom: lineNumberEOF, Content: []byte("r9l1\nr9l2\r\n"), }, { OmitFrom: 4, ContinueFrom: lineNumberEOF, Content: []byte("r8l1\nr8l2\r\n"), }, { OmitFrom: 2, ContinueFrom: 2, Content: []byte("r3l1\nr3l2\r\n"), }, { OmitFrom: lineNumberEOF, ContinueFrom: lineNumberEOF, Content: []byte("r10l1\nr10l2\r\n"), }, }, }, wantLE: "\n", want: []byte("r0l1\nr0l2\nr1l1\nr1l2\nr2l1\nr2l2\nr3l1\nr3l2\nr4l1\nr4l2\nr5l1\nr5l2\nr6l1\nr6l2\nr7l1\nr7l2" + "\nr8l1\nr8l2\nr9l1\nr9l2\nr10l1\nr10l2\n"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { scanner, le, err := parser.ReadTextFile(bytes.NewReader(tt.arg.file), nil) require.NoError(t, err, "failed to read input file") writer := bytes.Buffer{} err = patchTextFileWritePatchedFile(scanner, tt.arg.replacements, le, &writer) got := writer.Bytes() if tt.wantErr != "" { assert.ErrorContains(t, err, tt.wantErr, "error doesn't match expected.") } else { assert.Equal(t, tt.wantLE, le, "line ending doesn't match") if !reflect.DeepEqual(got, tt.want) { t.Errorf("patchTextFileWritePatchedFile() = %q, want %q", string(got), string(tt.want)) } } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sharedrepo/line_number.go
git/sharedrepo/line_number.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sharedrepo import ( "fmt" "math" "strconv" "strings" ) // lineNumberEOF indicates a line number pointing at the end of the file. // Setting it to max Int64 ensures that any valid lineNumber is smaller than a EOF line number. const lineNumberEOF = lineNumber(math.MaxInt64) type lineNumber int64 func (n lineNumber) IsEOF() bool { return n == lineNumberEOF } func (n lineNumber) String() string { if n == lineNumberEOF { return "eof" } return fmt.Sprint(int64(n)) } func parseLineNumber(raw []byte) (lineNumber, error) { if len(raw) == 0 { return 0, fmt.Errorf("line number can't be empty") } if strings.EqualFold(string(raw), "eof") { return lineNumberEOF, nil } val, err := strconv.ParseInt(string(raw), 10, 64) if err != nil { return 0, fmt.Errorf("unable to parse %q as line number", string(raw)) } if val < 1 { return 0, fmt.Errorf("line numbering starts at 1") } if val == int64(lineNumberEOF) { return 0, fmt.Errorf("line numbering ends at %d", lineNumberEOF-1) } return lineNumber(val), err }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sharedrepo/run.go
git/sharedrepo/run.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sharedrepo import ( "context" "fmt" "github.com/harness/gitness/git/hook" ) // Run is helper function used to run the provided function inside a shared repository. // If the provided hook.RefUpdater is not nil it will be used to update the reference. // Inside the provided inline function there should be a call to initialize the ref updater. // If the provided hook.RefUpdater is nil the entire operation is a read-only. func Run( ctx context.Context, refUpdater *hook.RefUpdater, tmpDir, repoPath string, fn func(s *SharedRepo) error, alternates ...string, ) error { s, err := NewSharedRepo(tmpDir, repoPath) if err != nil { return err } defer s.Close(ctx) if err := s.Init(ctx, alternates...); err != nil { return err } // The refUpdater.Init must be called within the fn (if refUpdater != nil), otherwise the refUpdater.Pre will fail. if err := fn(s); err != nil { return err } if refUpdater == nil { return nil } alternate := s.Directory() + "/objects" if err := refUpdater.Pre(ctx, alternate); err != nil { return fmt.Errorf("pre-receive hook failed: %w", err) } if err := s.MoveObjects(ctx); err != nil { return fmt.Errorf("failed to move objects: %w", err) } if err := refUpdater.UpdateRef(ctx); err != nil { return fmt.Errorf("failed to update reference: %w", err) } if err := refUpdater.Post(ctx, alternate); err != nil { return fmt.Errorf("post-receive hook failed: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sharedrepo/sharedrepo.go
git/sharedrepo/sharedrepo.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sharedrepo import ( "bufio" "bytes" "context" "crypto/rand" "encoding/base32" "fmt" "io" "io/fs" "os" "path" "path/filepath" "regexp" "sort" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/api" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/git/tempdir" "github.com/rs/zerolog/log" "golang.org/x/exp/slices" ) type SharedRepo struct { repoPath string sourceRepoPath string } // NewSharedRepo creates a new temporary bare repository. func NewSharedRepo( baseTmpDir string, sourceRepoPath string, ) (*SharedRepo, error) { if sourceRepoPath == "" { return nil, errors.New("repository path can't be empty") } var buf [5]byte _, _ = rand.Read(buf[:]) id := base32.StdEncoding.EncodeToString(buf[:]) repoPath, err := tempdir.CreateTemporaryPath(baseTmpDir, id) if err != nil { return nil, fmt.Errorf("failed to create shared repository directory: %w", err) } t := &SharedRepo{ repoPath: repoPath, sourceRepoPath: sourceRepoPath, } return t, nil } func (r *SharedRepo) Close(ctx context.Context) { if err := tempdir.RemoveTemporaryPath(r.repoPath); err != nil { log.Ctx(ctx).Err(err). Str("path", r.repoPath). Msg("Failed to remove temporary shared directory") } } func (r *SharedRepo) Init(ctx context.Context, alternates ...string) error { cmd := command.New("init", command.WithFlag("--bare")) if err := cmd.Run(ctx, command.WithDir(r.repoPath)); err != nil { return fmt.Errorf("failed to initialize bare git repository directory: %w", err) } if err := func() error { alternatesFilePath := filepath.Join(r.repoPath, "objects", "info", "alternates") f, err := os.OpenFile(alternatesFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err != nil { return fmt.Errorf("failed to create alternates file: %w", err) } defer func() { _ = f.Close() }() data := filepath.Join(r.sourceRepoPath, "objects") if _, err = fmt.Fprintln(f, data); err != nil { return fmt.Errorf("failed to write alternates file: %w", err) } for _, alternate := range alternates { if _, err = fmt.Fprintln(f, alternate); err != nil { return fmt.Errorf("failed to write alternates file: %w", err) } } return nil }(); err != nil { return fmt.Errorf("failed to make the alternates file in shared repository: %w", err) } return nil } func (r *SharedRepo) Directory() string { return r.repoPath } // SetDefaultIndex sets the git index to our HEAD. func (r *SharedRepo) SetDefaultIndex(ctx context.Context) error { cmd := command.New("read-tree", command.WithArg("HEAD")) if err := cmd.Run(ctx, command.WithDir(r.repoPath)); err != nil { return fmt.Errorf("failed to initialize shared repository index to HEAD: %w", err) } return nil } // SetIndex sets the git index to the provided treeish. func (r *SharedRepo) SetIndex(ctx context.Context, treeish sha.SHA) error { cmd := command.New("read-tree", command.WithArg(treeish.String())) if err := cmd.Run(ctx, command.WithDir(r.repoPath)); err != nil { return fmt.Errorf("failed to initialize shared repository index to %q: %w", treeish, err) } return nil } // ClearIndex clears the git index. func (r *SharedRepo) ClearIndex(ctx context.Context) error { cmd := command.New("read-tree", command.WithFlag("--empty")) if err := cmd.Run(ctx, command.WithDir(r.repoPath)); err != nil { return fmt.Errorf("failed to clear shared repository index: %w", err) } return nil } // LsFiles checks if the given filename arguments are in the index. func (r *SharedRepo) LsFiles( ctx context.Context, filenames ...string, ) ([]string, error) { cmd := command.New("ls-files", command.WithFlag("-z"), command.WithPostSepArg(filenames...), ) stdout := bytes.NewBuffer(nil) err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(stdout)) if err != nil { return nil, fmt.Errorf("failed to list files in shared repository's git index: %w", err) } files := make([]string, 0) for line := range bytes.SplitSeq(stdout.Bytes(), []byte{'\000'}) { files = append(files, string(line)) } return files, nil } // RemoveFilesFromIndex removes the given files from the index. func (r *SharedRepo) RemoveFilesFromIndex( ctx context.Context, filenames ...string, ) error { cmd := command.New("update-index", command.WithFlag("--remove"), command.WithFlag("-z"), command.WithFlag("--index-info")) stdin := bytes.NewBuffer(nil) for _, file := range filenames { if file != "" { stdin.WriteString("0 0000000000000000000000000000000000000000\t") stdin.WriteString(file) stdin.WriteByte('\000') } } if err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdin(stdin)); err != nil { return fmt.Errorf("failed to update-index in shared repo: %w", err) } return nil } // WriteGitObject writes the provided content to the object db and returns its hash. func (r *SharedRepo) WriteGitObject( ctx context.Context, content io.Reader, ) (sha.SHA, error) { cmd := command.New("hash-object", command.WithFlag("-w"), command.WithFlag("--stdin")) stdout := bytes.NewBuffer(nil) err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdin(content), command.WithStdout(stdout)) if err != nil { return sha.None, fmt.Errorf("failed to hash-object in shared repo: %w", err) } return sha.New(stdout.String()) } // GetTreeSHA returns the tree SHA of the rev. func (r *SharedRepo) GetTreeSHA( ctx context.Context, rev string, ) (sha.SHA, error) { cmd := command.New("show", command.WithFlag("--no-patch"), command.WithFlag("--format=%T"), command.WithArg(rev), ) stdout := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(stdout), ) if err != nil { if command.AsError(err).IsAmbiguousArgErr() { return sha.None, errors.NotFoundf("could not resolve git revision %q", rev) } return sha.None, fmt.Errorf("failed to get tree sha: %w", err) } return sha.New(stdout.String()) } // ShowFile dumps show file and write to io.Writer. func (r *SharedRepo) ShowFile( ctx context.Context, filePath string, rev string, writer io.Writer, ) error { file := strings.TrimSpace(rev) + ":" + strings.TrimSpace(filePath) cmd := command.New("show", command.WithArg(file)) if err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(writer)); err != nil { return fmt.Errorf("failed to show file in shared repo: %w", err) } return nil } // AddObjectToIndex adds the provided object hash to the index with the provided mode and path. func (r *SharedRepo) AddObjectToIndex( ctx context.Context, mode string, objectHash sha.SHA, objectPath string, ) error { cmd := command.New("update-index", command.WithFlag("--add"), command.WithFlag("--replace"), command.WithFlag("--cacheinfo", mode, objectHash.String(), objectPath)) if err := cmd.Run(ctx, command.WithDir(r.repoPath)); err != nil { if matched, _ := regexp.MatchString(".*Invalid path '.*", err.Error()); matched { return errors.InvalidArgumentf("invalid path '%s'", objectPath) } return fmt.Errorf("failed to add object to index in shared repo (path=%s): %w", objectPath, err) } return nil } // WriteTree writes the current index as a tree to the object db and returns its hash. func (r *SharedRepo) WriteTree(ctx context.Context) (sha.SHA, error) { cmd := command.New("write-tree") stdout := bytes.NewBuffer(nil) if err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(stdout)); err != nil { return sha.None, fmt.Errorf("failed to write-tree in shared repo: %w", err) } return sha.New(stdout.String()) } // MergeTree merges commits in git index. func (r *SharedRepo) MergeTree( ctx context.Context, commitMergeBase, commitTarget, commitSource sha.SHA, ) (sha.SHA, []string, error) { cmd := command.New("merge-tree", command.WithFlag("--write-tree"), command.WithFlag("--name-only"), command.WithFlag("--no-messages"), command.WithArg(commitTarget.String()), command.WithArg(commitSource.String())) if !commitMergeBase.IsEmpty() { cmd.Add(command.WithFlag("--merge-base=" + commitMergeBase.String())) } stdout := bytes.NewBuffer(nil) err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(stdout)) // no error: the output is just the tree object SHA if err == nil { return sha.Must(stdout.String()), nil, nil } // exit code=1: the output is the tree object SHA, and list of files in conflict. if cErr := command.AsError(err); cErr != nil && cErr.IsExitCode(1) { output := strings.TrimSpace(stdout.String()) lines := strings.Split(output, "\n") if len(lines) < 2 { log.Ctx(ctx).Err(err).Str("output", output).Msg("unexpected output of merge-tree in shared repo") return sha.None, nil, fmt.Errorf("unexpected output of merge-tree in shared repo: %w", err) } treeSHA := sha.Must(lines[0]) conflicts := CleanupMergeConflicts(lines[1:]) return treeSHA, conflicts, nil } return sha.None, nil, fmt.Errorf("failed to merge-tree in shared repo: %w", err) } func CleanupMergeConflicts(conflicts []string) []string { out := make([]string, 0, len(conflicts)) for _, conflict := range conflicts { conflict = strings.TrimSpace(conflict) if conflict != "" { out = append(out, conflict) } } return out } // CommitTree creates a commit from a given tree for the user with provided message. func (r *SharedRepo) CommitTree( ctx context.Context, author, committer *api.Signature, treeHash sha.SHA, message string, signoff bool, parentCommits ...sha.SHA, ) (sha.SHA, error) { cmd := command.New("commit-tree", command.WithArg(treeHash.String()), command.WithAuthorAndDate( author.Identity.Name, author.Identity.Email, author.When, ), command.WithCommitterAndDate( committer.Identity.Name, committer.Identity.Email, committer.When, ), ) for _, parentCommit := range parentCommits { cmd.Add(command.WithFlag("-p", parentCommit.String())) } // temporary no signing cmd.Add(command.WithFlag("--no-gpg-sign")) messageBytes := new(bytes.Buffer) _, _ = messageBytes.WriteString(message) if signoff { // Signed-off-by _, _ = messageBytes.WriteString("\n") _, _ = messageBytes.WriteString("Signed-off-by: ") _, _ = fmt.Fprintf(messageBytes, "%s <%s>\n", committer.Identity.Name, committer.Identity.Email) } stdout := bytes.NewBuffer(nil) err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(stdout), command.WithStdin(messageBytes)) if err != nil { return sha.None, fmt.Errorf("failed to commit-tree in shared repo: %w", err) } return sha.New(stdout.String()) } // CommitSHAsForRebase returns list of SHAs of the commits between the two git revisions // for a rebase operation - in the order they should be rebased in. func (r *SharedRepo) CommitSHAsForRebase( ctx context.Context, target, source sha.SHA, ) ([]sha.SHA, error) { // the command line arguments are mostly matching default `git rebase` behavior. // Only difference is we use `--date-order` (matches github behavior) whilst `git rebase` uses `--topo-order`. // Git Rebase's rev-list: https://github.com/git/git/blob/v2.41.0/sequencer.c#L5703-L5714 cmd := command.New("rev-list", command.WithFlag("--max-parents=1"), // exclude merge commits command.WithFlag("--cherry-pick"), // drop commits that already exist on target command.WithFlag("--reverse"), command.WithFlag("--right-only"), // only return commits from source command.WithFlag("--date-order"), // childs always before parents, otherwise by commit time stamp command.WithArg(target.String()+"..."+source.String())) stdout := bytes.NewBuffer(nil) if err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(stdout)); err != nil { return nil, fmt.Errorf("failed to rev-list in shared repo: %w", err) } var commitSHAs []sha.SHA scan := bufio.NewScanner(stdout) for scan.Scan() { commitSHA := sha.Must(scan.Text()) commitSHAs = append(commitSHAs, commitSHA) } if err := scan.Err(); err != nil { return nil, fmt.Errorf("failed to scan rev-list output in shared repo: %w", err) } return commitSHAs, nil } // MergeBase returns number of commits between the two git revisions. func (r *SharedRepo) MergeBase( ctx context.Context, rev1, rev2 string, ) (string, error) { cmd := command.New("merge-base", command.WithArg(rev1), command.WithArg(rev2)) stdout := bytes.NewBuffer(nil) if err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(stdout)); err != nil { return "", fmt.Errorf("failed to merge-base in shared repo: %w", err) } return strings.TrimSpace(stdout.String()), nil } // WriteDiff runs git diff between two revisions and stores the output to the provided writer. // The diff output would also include changes to binary files. func (r *SharedRepo) WriteDiff( ctx context.Context, revFrom, revTo string, wr io.Writer, ) error { cmd := command.New("diff", command.WithFlag("--binary"), command.WithArg(revFrom), command.WithArg(revTo)) if err := cmd.Run(ctx, command.WithDir(r.repoPath), command.WithStdout(wr)); err != nil { return fmt.Errorf("failed to diff in shared repo: %w", err) } return nil } // ApplyToIndex runs 'git apply --cached' which would update the current index with the provided diff patch. func (r *SharedRepo) ApplyToIndex( ctx context.Context, inputFileName string, ) error { cmd := command.New("apply", command.WithFlag("--cached"), command.WithArg(inputFileName)) if err := cmd.Run(ctx, command.WithDir(r.repoPath)); err != nil { return fmt.Errorf("failed to apply a patch in shared repo: %w", err) } return nil } func (r *SharedRepo) CreateFile( ctx context.Context, treeishSHA sha.SHA, filePath, mode string, payload []byte, ) (sha.SHA, error) { // only check path availability if a source commit is available (empty repo won't have such a commit) if !treeishSHA.IsEmpty() { if err := r.checkPathAvailability(ctx, treeishSHA, filePath, true); err != nil { return sha.None, err } } objectSHA, err := r.WriteGitObject(ctx, bytes.NewReader(payload)) if err != nil { return sha.None, fmt.Errorf("createFile: error hashing object: %w", err) } // Add the object to the index if err = r.AddObjectToIndex(ctx, mode, objectSHA, filePath); err != nil { return sha.None, fmt.Errorf("createFile: error creating object: %w", err) } return objectSHA, nil } func (r *SharedRepo) UpdateFile( ctx context.Context, treeishSHA sha.SHA, filePath string, objectSHA sha.SHA, mode string, payload []byte, ) (sha.SHA, error) { // get file mode from existing file (default unless executable) entry, err := r.getFileEntry(ctx, treeishSHA, objectSHA, filePath) if err != nil { return sha.None, err } if entry.IsExecutable() { mode = "100755" } objectSHA, err = r.WriteGitObject(ctx, bytes.NewReader(payload)) if err != nil { return sha.None, fmt.Errorf("updateFile: error hashing object: %w", err) } if err = r.AddObjectToIndex(ctx, mode, objectSHA, filePath); err != nil { return sha.None, fmt.Errorf("updateFile: error updating object: %w", err) } return objectSHA, nil } func (r *SharedRepo) MoveFile( ctx context.Context, treeishSHA sha.SHA, filePath string, objectSHA sha.SHA, mode string, payload []byte, ) (string, sha.SHA, error) { newPath, newContent, err := parseMovePayload(payload) if err != nil { return "", sha.None, err } // ensure file exists and matches SHA entry, err := r.getFileEntry(ctx, treeishSHA, objectSHA, filePath) if err != nil { return "", sha.None, err } // ensure new path is available if err = r.checkPathAvailability(ctx, treeishSHA, newPath, false); err != nil { return "", sha.None, err } var fileHash sha.SHA var fileMode string if newContent != nil { hash, err := r.WriteGitObject(ctx, bytes.NewReader(newContent)) if err != nil { return "", sha.None, fmt.Errorf("moveFile: error hashing object: %w", err) } fileHash = hash fileMode = mode if entry.IsExecutable() { const filePermissionExec = "100755" fileMode = filePermissionExec } } else { fileHash = entry.SHA fileMode = entry.Mode.String() } if err = r.AddObjectToIndex(ctx, fileMode, fileHash, newPath); err != nil { return "", sha.None, fmt.Errorf("moveFile: add object error: %w", err) } if err = r.RemoveFilesFromIndex(ctx, filePath); err != nil { return "", sha.None, fmt.Errorf("moveFile: remove object error: %w", err) } return newPath, fileHash, nil } func (r *SharedRepo) DeleteFile(ctx context.Context, filePath string) error { filesInIndex, err := r.LsFiles(ctx, filePath) if err != nil { return fmt.Errorf("deleteFile: listing files error: %w", err) } if !slices.Contains(filesInIndex, filePath) { return errors.NotFoundf("file path %s not found", filePath) } if err = r.RemoveFilesFromIndex(ctx, filePath); err != nil { return fmt.Errorf("deleteFile: remove object error: %w", err) } return nil } func (r *SharedRepo) PatchTextFile( ctx context.Context, treeishSHA sha.SHA, filePath string, objectSHA sha.SHA, payloadsRaw [][]byte, ) (sha.SHA, error) { payloads, err := parsePatchTextFilePayloads(payloadsRaw) if err != nil { return sha.None, err } entry, err := r.getFileEntry(ctx, treeishSHA, objectSHA, filePath) if err != nil { return sha.None, err } blob, err := api.GetBlob(ctx, r.repoPath, nil, entry.SHA, 0) if err != nil { return sha.None, fmt.Errorf("error reading blob: %w", err) } scanner, lineEnding, err := parser.ReadTextFile(blob.Content, nil) if err != nil { return sha.None, fmt.Errorf("error reading blob as text file: %w", err) } pipeReader, pipeWriter := io.Pipe() go func() { err := patchTextFileWritePatchedFile(scanner, payloads, lineEnding, pipeWriter) pipErr := pipeWriter.CloseWithError(err) if pipErr != nil { log.Ctx(ctx).Warn().Err(pipErr).Msgf("failed to close pipe writer with error: %s", err) } }() objectSHA, err = r.WriteGitObject(ctx, pipeReader) if err != nil { return sha.None, fmt.Errorf("error writing patched file to git store: %w", err) } if err = r.AddObjectToIndex(ctx, entry.Mode.String(), objectSHA, filePath); err != nil { return sha.None, fmt.Errorf("error updating object: %w", err) } return objectSHA, nil } // nolint: gocognit, gocyclo, cyclop func patchTextFileWritePatchedFile( fileScanner parser.Scanner, replacements []patchTextFileReplacement, lineEnding string, writer io.Writer, ) error { // sort replacements by `start ASC end ASC` to ensure proper processing (DO NOT CHANGE!) // Use stable sort to ensure ordering of `[1,1)[1,1)` is maintained sort.SliceStable(replacements, func(i, j int) bool { if replacements[i].OmitFrom == replacements[j].OmitFrom { return replacements[i].ContinueFrom < replacements[j].ContinueFrom } return replacements[i].OmitFrom < replacements[j].OmitFrom }) // ensure replacements aren't overlapping for i := 1; i < len(replacements); i++ { // Stop prevalidation at EOF as we don't know the line count of the file (NOTE: start=EOF => end=EOF). // Remaining overlaps are handled once EOF of the file is reached and we know the line number if replacements[i-1].ContinueFrom.IsEOF() { break } if replacements[i].OmitFrom < replacements[i-1].ContinueFrom { return errors.InvalidArgumentf( "Patch actions have conflicting ranges [%s,%s)x[%s,%s)", replacements[i-1].OmitFrom, replacements[i-1].ContinueFrom, replacements[i].OmitFrom, replacements[i].ContinueFrom, ) } } // helper function to write output (helps to ensure that we always have line endings between lines) previousWriteHadLineEndings := true write := func(line []byte) error { // skip lines without data - should never happen as an empty line still has line endings. if len(line) == 0 { return nil } // if the previous line didn't have line endings and there's another line coming, inject a line ending. // NOTE: this can for example happen when a suggestion doesn't have line endings if !previousWriteHadLineEndings { _, err := writer.Write([]byte(lineEnding)) if err != nil { return fmt.Errorf("failed to write forced injected line ending: %w", err) } } _, err := writer.Write(line) if err != nil { return fmt.Errorf("failed to write line: %w", err) } previousWriteHadLineEndings = parser.HasLineEnding(line) return nil } ri := 0 // replacement index var processReplacements func(ln lineNumber) (skipLine bool, err error) processReplacements = func(ln lineNumber) (bool, error) { // no replacements left if ri >= len(replacements) { return false, nil } // Assumption: replacements are sorted `start ASC end ASC` if ln < replacements[ri].OmitFrom { return false, nil } // write replacement immediately once we hit its range to ensure we maintain proper order. if ln == replacements[ri].OmitFrom { rScanner, _, err := parser.ReadTextFile(bytes.NewReader(replacements[ri].Content), &lineEnding) if err != nil { return false, fmt.Errorf("error to start reading replacement as text file: %w", err) } for rScanner.Scan() { if err := write(rScanner.Bytes()); err != nil { return false, fmt.Errorf("failed to inject replacement line: %w", err) } } if err := rScanner.Err(); err != nil { return false, fmt.Errorf("failed to read replacement line: %w", err) } } // if we reached the end of the replacement - move to next and reetrigger (to handle things like [1,2)+[2,2)+...) if ln >= replacements[ri].ContinueFrom { ri++ return processReplacements(ln) } // otherwise we are in the middle of the replacement - skip line return true, nil } var ln lineNumber for fileScanner.Scan() { ln++ skipLine, err := processReplacements(ln) if err != nil { return fmt.Errorf("failed processing replacements for line %d: %w", ln, err) } if skipLine { continue } line := fileScanner.Bytes() if err := write(line); err != nil { return fmt.Errorf("failed to copy line %d from original file: %w", ln, err) } } // move ln at end of file (e.g. after last line) ln++ // backfill EOF line numbers and finish overlap validation for remaining entries. // If any replacement entries are left, we know the current one has ContinueFrom >= ln or is EOF. for i := ri; i < len(replacements); i++ { // copy original input for error messages originalOmitFrom := replacements[i].OmitFrom originalContinueFrom := replacements[i].ContinueFrom // backfil EOF line numbers if replacements[i].OmitFrom.IsEOF() { replacements[i].OmitFrom = ln } if replacements[i].ContinueFrom.IsEOF() { replacements[i].ContinueFrom = ln } // ensure replacement range isn't out of bounds if replacements[i].OmitFrom > ln || replacements[i].ContinueFrom > ln { return errors.InvalidArgumentf( "Patch action for [%s,%s) is exceeding end of file with %d line(s).", originalOmitFrom, originalContinueFrom, ln-1, ) } // ensure no overlap with next element if i+1 < len(replacements) && replacements[i+1].OmitFrom < replacements[i].ContinueFrom { return errors.InvalidArgumentf( "Patch actions have conflicting ranges [%s,%s)x[%s,%s) for file with %d line(s).", originalOmitFrom, originalContinueFrom, replacements[i+1].OmitFrom, replacements[i+1].ContinueFrom, ln-1, ) } } skipLine, err := processReplacements(ln) if err != nil { return fmt.Errorf("failed processing replacements for EOF: %w", err) } // this should never happen! (as after full validation no remaining start/end is greater than line number at eof!) if skipLine || ri < len(replacements) { return fmt.Errorf( "unexpected status reached at end of file ri=%d (cnt=%d) and skipLine=%t", ri, len(replacements), skipLine, ) } return nil } func (r *SharedRepo) getFileEntry( ctx context.Context, treeishSHA sha.SHA, objectSHA sha.SHA, path string, ) (*api.TreeNode, error) { entry, err := api.GetTreeNode(ctx, r.repoPath, treeishSHA.String(), path, false) if errors.IsNotFound(err) { return nil, errors.NotFoundf("path %s not found", path) } if err != nil { return nil, fmt.Errorf("getFileEntry: failed to get tree for path %s: %w", path, err) } // If a SHA was given and the SHA given doesn't match the SHA of the fromTreePath, throw error if !objectSHA.IsEmpty() && !objectSHA.Equal(entry.SHA) { return nil, errors.InvalidArgumentf("sha does not match for path %s [given: %s, expected: %s]", path, objectSHA, entry.SHA) } return entry, nil } // checkPathAvailability ensures that the path is available for the requested operation. // For the path where this file will be created/updated, we need to make // sure no parts of the path are existing files or links except for the last // item in the path which is the file name, and that shouldn't exist IF it is // a new file OR is being moved to a new path. func (r *SharedRepo) checkPathAvailability( ctx context.Context, treeishSHA sha.SHA, filePath string, isNewFile bool, ) error { parts := strings.Split(filePath, "/") subTreePath := "" for index, part := range parts { subTreePath = path.Join(subTreePath, part) entry, err := api.GetTreeNode(ctx, r.repoPath, treeishSHA.String(), subTreePath, false) if err != nil { if errors.IsNotFound(err) { // Means there is no item with that name, so we're good break } return fmt.Errorf("checkPathAvailability: failed to get tree entry for path %s: %w", subTreePath, err) } switch { case index < len(parts)-1: if !entry.IsDir() { return errors.Conflictf("a file already exists where you're trying to create a subdirectory [path: %s]", subTreePath) } case entry.IsLink(): return errors.Conflictf("a symbolic link already exist where you're trying to create a subdirectory [path: %s]", subTreePath) case entry.IsDir(): return errors.Conflictf("a directory already exists where you're trying to create a subdirectory [path: %s]", subTreePath) case filePath != "" || isNewFile: return errors.Conflictf("file path %s already exists", filePath) } } return nil } // MoveObjects moves git object from the shared repository to the original repository. func (r *SharedRepo) MoveObjects(ctx context.Context) error { if r.sourceRepoPath == "" { return errors.New("shared repo not initialized with a repository") } srcDir := path.Join(r.repoPath, "objects") dstDir := path.Join(r.sourceRepoPath, "objects") var files []fileEntry err := filepath.WalkDir(srcDir, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } relPath, err := filepath.Rel(srcDir, path) if err != nil { return fmt.Errorf("failed to get relative path: %w", err) } // avoid coping anything in the info/ if strings.HasPrefix(relPath, "info/") { return nil } fileName := filepath.Base(relPath) files = append(files, fileEntry{ fileName: fileName, fullPath: path, relPath: relPath, priority: filePriority(fileName), }) return nil }) if err != nil { return fmt.Errorf("failed to list files of shared repository directory: %w", err) } sort.Slice(files, func(i, j int) bool { return files[i].priority < files[j].priority // 0 is top priority, 5 is lowest priority }) for _, f := range files { dstPath := filepath.Join(dstDir, f.relPath) err = os.MkdirAll(filepath.Dir(dstPath), os.ModePerm) if err != nil { return fmt.Errorf("failed to create directory for git object: %w", err) } // Try to move the file errRename := os.Rename(f.fullPath, dstPath) if errRename == nil { log.Ctx(ctx).Debug(). Str("object", f.relPath). Msg("moved git object") continue } // Try to copy the file errCopy := func() error { srcFile, err := os.Open(f.fullPath) if err != nil { return fmt.Errorf("failed to open source file: %w", err) } defer func() { _ = srcFile.Close() }() dstFile, err := os.Create(dstPath) if err != nil { return fmt.Errorf("failed to create target file: %w", err) } defer func() { _ = dstFile.Close() }() _, err = io.Copy(dstFile, srcFile) if err != nil { return fmt.Errorf("failed to copy file content: %w", err) } return nil }() if errCopy != nil { // Make sure that an invalid or incomplete file does not remain in the repository if copying fails. errRemove := os.Remove(dstPath) if os.IsNotExist(errRemove) { errRemove = nil } log.Ctx(ctx).Err(errCopy). Str("object", f.relPath). Str("errRename", errRename.Error()). Str("errRemove", errRemove.Error()). Msg("failed to move or copy git object") return fmt.Errorf("failed to move or copy git object: %w", errCopy) } log.Ctx(ctx).Warn(). Str("object", f.relPath). Str("errRename", errRename.Error()). Msg("copied git object") } return nil } // filePriority is based on https://github.com/git/git/blob/master/tmp-objdir.c#L168 func filePriority(name string) int { switch { case !strings.HasPrefix(name, "pack"): return 0 case strings.HasSuffix(name, ".keep"): return 1 case strings.HasSuffix(name, ".pack"): return 2 case strings.HasSuffix(name, ".rev"): return 3 case strings.HasSuffix(name, ".idx"): return 4 default: return 5 } } type fileEntry struct { fileName string fullPath string relPath string priority int } func parseMovePayload(payload []byte) (string, []byte, error) { var newContent []byte var newPath string filePathEnd := bytes.IndexByte(payload, 0) if filePathEnd < 0 { newPath = string(payload) newContent = nil } else { newPath = string(payload[:filePathEnd]) newContent = payload[filePathEnd+1:] } newPath = api.CleanUploadFileName(newPath) if newPath == "" { return "", nil, api.ErrInvalidPath } return newPath, newContent, nil } type patchTextFileReplacement struct { OmitFrom lineNumber ContinueFrom lineNumber Content []byte } func parsePatchTextFilePayloads(payloadsRaw [][]byte) ([]patchTextFileReplacement, error) { replacements := []patchTextFileReplacement{} for i := range payloadsRaw { replacement, err := parsePatchTextFilePayload(payloadsRaw[i]) if err != nil { return nil, err } replacements = append(replacements, replacement) } return replacements, nil } // parsePatchTextFilePayload parses the payload for a PATCH_TEXT_FILE action: // // <First Line to omit>:<First line to include again>\0<Replacement> // // Examples: // // `1:2\0some new line` // `1:eof\0some new line\n` // `1:1\0some new line\nsome other line` func parsePatchTextFilePayload(payloadRaw []byte) (patchTextFileReplacement, error) { lineInfo, replacement, ok := bytes.Cut(payloadRaw, []byte{0}) if !ok { return patchTextFileReplacement{}, errors.InvalidArgument("Payload format is missing the content separator.") } startBytes, endBytes, ok := bytes.Cut(lineInfo, []byte{':'}) if !ok { return patchTextFileReplacement{}, errors.InvalidArgument( "Payload is missing the line number separator.") } start, err := parseLineNumber(startBytes) if err != nil { return patchTextFileReplacement{}, errors.InvalidArgumentf("Payload start line number is invalid: %s", err) } end, err := parseLineNumber(endBytes) if err != nil { return patchTextFileReplacement{}, errors.InvalidArgumentf("Payload end line number is invalid: %s", err) } if end < start { return patchTextFileReplacement{}, errors.InvalidArgument("Payload end line has to be at least as big as start line.") } return patchTextFileReplacement{ OmitFrom: start, ContinueFrom: end, Content: replacement, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/diff/diff.go
git/diff/diff.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package diff import ( "bufio" "bytes" "fmt" "io" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/enum" ) // Predefine []byte variables to avoid runtime allocations. var ( escapedSlash = []byte(`\\`) regularSlash = []byte(`\`) escapedTab = []byte(`\t`) regularTab = []byte("\t") ) // LineType is the line type in diff. type LineType uint8 // A list of different line types. const ( DiffLinePlain LineType = iota + 1 DiffLineAdd DiffLineDelete DiffLineSection ) // FileType is the file status in diff. type FileType uint8 // A list of different file statuses. const ( FileAdd FileType = iota FileChange FileDelete FileRename ) // Line represents a line in diff. type Line struct { Type LineType // The type of the line Content string // The content of the line LeftLine int // The left line number RightLine int // The right line number } // Section represents a section in diff. type Section struct { Lines []*Line // lines in the section numAdditions int numDeletions int } // NumLines returns the number of lines in the section. func (s *Section) NumLines() int { return len(s.Lines) } // Line returns a specific line by given type and line number in a section. // nolint: gocognit func (s *Section) Line(lineType LineType, line int) *Line { var ( difference = 0 addCount = 0 delCount = 0 matchedDiffLine *Line ) loop: for _, diffLine := range s.Lines { switch diffLine.Type { case DiffLineAdd: addCount++ case DiffLineDelete: delCount++ case DiffLinePlain, DiffLineSection: if matchedDiffLine != nil { break loop } difference = diffLine.RightLine - diffLine.LeftLine addCount = 0 delCount = 0 } switch lineType { case DiffLineDelete: if diffLine.RightLine == 0 && diffLine.LeftLine == line-difference { matchedDiffLine = diffLine } case DiffLineAdd: if diffLine.LeftLine == 0 && diffLine.RightLine == line+difference { matchedDiffLine = diffLine } case DiffLinePlain, DiffLineSection: } } if addCount == delCount { return matchedDiffLine } return nil } // File represents a file in diff. type File struct { // The name and path of the file. Path string // The old name and path of the file. OldPath string // The type of the file. Type FileType // The index (SHA1 hash) of the file. For a changed/new file, it is the new SHA, // and for a deleted file it becomes "000000". SHA string // OldSHA is the old index (SHA1 hash) of the file. OldSHA string // The sections in the file. Sections []*Section numAdditions int numDeletions int mode enum.EntryMode oldMode enum.EntryMode IsBinary bool IsSubmodule bool Patch bytes.Buffer } func (f *File) Status() string { switch f.Type { case FileAdd: return "added" case FileDelete: return "deleted" case FileRename: return "renamed" case FileChange: return "changed" default: return "unchanged" } } // NumSections returns the number of sections in the file. func (f *File) NumSections() int { return len(f.Sections) } // NumAdditions returns the number of additions in the file. func (f *File) NumAdditions() int { return f.numAdditions } // NumChanges returns the number of additions and deletions in the file. func (f *File) NumChanges() int { return f.numAdditions + f.numDeletions } // NumDeletions returns the number of deletions in the file. func (f *File) NumDeletions() int { return f.numDeletions } // Mode returns the mode of the file. func (f *File) Mode() enum.EntryMode { return f.mode } // OldMode returns the old mode of the file if it's changed. func (f *File) OldMode() enum.EntryMode { return f.oldMode } func (f *File) IsEmpty() bool { return f.Path == "" && f.OldPath == "" } type Parser struct { *bufio.Reader // The next line that hasn't been processed. It is used to determine what kind // of process should go in. buffer []byte isEOF bool IncludePatch bool Patch bytes.Buffer } func (p *Parser) readLine() (newLine bool, err error) { if p.buffer != nil { return false, nil } p.buffer, err = p.ReadBytes('\n') if err != nil { if !errors.Is(err, io.EOF) { return false, fmt.Errorf("read string: %w", err) } p.isEOF = true } // Remove line break if len(p.buffer) > 0 && p.buffer[len(p.buffer)-1] == '\n' { newLine = true p.buffer = p.buffer[:len(p.buffer)-1] } return newLine, nil } var diffHead = []byte("diff --git ") //nolint:gocognit func (p *Parser) parseFileHeader() (*File, error) { p.Patch.Reset() submoduleMode := " 160000" if p.IncludePatch && len(p.buffer) > 0 { p.Patch.Write(p.buffer) p.Patch.Write([]byte{'\n'}) } line := string(p.buffer) p.buffer = nil // NOTE: In case file name is surrounded by double quotes (it happens only in // git-shell). e.g. diff --git "a/xxx" "b/xxx" aHasQuote := line[len(diffHead)] == '"' bHasQuote := line[len(line)-1] == '"' middle := strings.Index(line, ` b/`) if middle == -1 && bHasQuote { middle = strings.Index(line, ` "b/`) } if middle == -1 { return nil, errors.InvalidArgumentf("malformed header line: %s", line) } beg := len(diffHead) a := line[beg+2 : middle] if aHasQuote { a = string(UnescapeChars([]byte(a[1 : len(a)-1]))) } b := line[middle+3:] if bHasQuote { b = string(UnescapeChars([]byte(b[1 : len(b)-1]))) } file := &File{ Path: a, OldPath: b, Type: FileChange, } checkType: for !p.isEOF { newLine, err := p.readLine() if err != nil { return nil, err } if p.IncludePatch && len(p.buffer) > 0 { p.Patch.Write(p.buffer) if newLine { p.Patch.Write([]byte{'\n'}) } } subLine := string(p.buffer) p.buffer = nil if len(subLine) == 0 { continue } switch { case strings.HasPrefix(subLine, enum.DiffExtHeaderNewFileMode): file.Type = FileAdd file.IsSubmodule = strings.HasSuffix(subLine, submoduleMode) fields := strings.Fields(subLine) if len(fields) > 0 { mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64) file.mode = enum.EntryMode(mode) //nolint:gosec if file.oldMode == 0 { file.oldMode = file.mode } } case strings.HasPrefix(subLine, enum.DiffExtHeaderDeletedFileMode): file.Type = FileDelete file.IsSubmodule = strings.HasSuffix(subLine, submoduleMode) fields := strings.Fields(subLine) if len(fields) > 0 { mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64) file.mode = enum.EntryMode(mode) //nolint:gosec if file.oldMode == 0 { file.oldMode = file.mode } } case strings.HasPrefix(subLine, enum.DiffExtHeaderIndex): // e.g. index ee791be..9997571 100644 fields := strings.Fields(subLine[6:]) shas := strings.Split(fields[0], "..") if len(shas) != 2 { return nil, errors.New("malformed index: expect two SHAs in the form of <old>..<new>") } file.OldSHA = shas[0] file.SHA = shas[1] if len(fields) > 1 { mode, _ := strconv.ParseUint(fields[1], 8, 64) file.mode = enum.EntryMode(mode) //nolint:gosec file.oldMode = enum.EntryMode(mode) //nolint:gosec } break checkType case strings.HasPrefix(subLine, enum.DiffExtHeaderSimilarity): file.Type = FileRename file.OldPath = a file.Path = b // No need to look for index if it's a pure rename if strings.HasSuffix(subLine, "100%") { break checkType } case strings.HasPrefix(subLine, enum.DiffExtHeaderNewMode): fields := strings.Fields(subLine) if len(fields) > 0 { mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64) file.mode = enum.EntryMode(mode) //nolint:gosec } case strings.HasPrefix(subLine, enum.DiffExtHeaderOldMode): fields := strings.Fields(subLine) if len(fields) > 0 { mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64) file.oldMode = enum.EntryMode(mode) //nolint:gosec } } } return file, nil } //nolint:gocognit // refactor if needed func (p *Parser) parseSection() (*Section, error) { line := string(p.buffer) p.buffer = nil section := &Section{ Lines: []*Line{ { Type: DiffLineSection, Content: line, }, }, } // Parse line number, e.g. @@ -0,0 +1,3 @@ var leftLine, rightLine int ss := strings.Split(line, "@@") ranges := strings.Split(ss[1][1:], " ") leftLine, _ = strconv.Atoi(strings.Split(ranges[0], ",")[0][1:]) if len(ranges) > 1 { rightLine, _ = strconv.Atoi(strings.Split(ranges[1], ",")[0]) } else { rightLine = leftLine } for !p.isEOF { newLine, err := p.readLine() if err != nil { return nil, err } if len(p.buffer) == 0 { p.buffer = nil continue } // Make sure we're still in the section. If not, we're done with this section. if p.buffer[0] != ' ' && p.buffer[0] != '+' && p.buffer[0] != '-' { // No new line indicator if p.buffer[0] == '\\' && bytes.HasPrefix(p.buffer, []byte(`\ No newline at end of file`)) { p.buffer = nil continue } return section, nil } if p.IncludePatch && len(p.buffer) > 0 { p.Patch.Write(p.buffer) if newLine { p.Patch.Write([]byte{'\n'}) } } subLine := string(p.buffer) p.buffer = nil switch subLine[0] { case ' ': section.Lines = append(section.Lines, &Line{ Type: DiffLinePlain, Content: subLine, LeftLine: leftLine, RightLine: rightLine, }) leftLine++ rightLine++ case '+': section.Lines = append(section.Lines, &Line{ Type: DiffLineAdd, Content: subLine, RightLine: rightLine, }) section.numAdditions++ rightLine++ case '-': section.Lines = append(section.Lines, &Line{ Type: DiffLineDelete, Content: subLine, LeftLine: leftLine, }) section.numDeletions++ if leftLine > 0 { leftLine++ } } } return section, nil } //nolint:gocognit func (p *Parser) Parse(send func(f *File) error) error { file := new(File) currentFileLines := 0 additions := 0 deletions := 0 for !p.isEOF { newLine, err := p.readLine() if err != nil { return err } if len(p.buffer) == 0 { p.buffer = nil continue } // Found new file if bytes.HasPrefix(p.buffer, diffHead) { // stream previous file if !file.IsEmpty() && send != nil { _, _ = p.Patch.WriteTo(&file.Patch) err = send(file) if err != nil { return fmt.Errorf("failed to send out file: %w", err) } } file, err = p.parseFileHeader() if err != nil { return err } currentFileLines = 0 continue } if file == nil { p.buffer = nil continue } if p.IncludePatch && len(p.buffer) > 0 { p.Patch.Write(p.buffer) if newLine { p.Patch.Write([]byte{'\n'}) } } if bytes.HasPrefix(p.buffer, []byte("Binary")) { p.buffer = nil file.IsBinary = true continue } // Loop until we found section header if p.buffer[0] != '@' { p.buffer = nil continue } section, err := p.parseSection() if err != nil { return err } file.Sections = append(file.Sections, section) file.numAdditions += section.numAdditions file.numDeletions += section.numDeletions additions += section.numAdditions deletions += section.numDeletions currentFileLines += section.NumLines() } // stream last file if !file.IsEmpty() && send != nil { file.Patch.Write(p.Patch.Bytes()) err := send(file) if err != nil { return fmt.Errorf("failed to send last file: %w", err) } } return nil } // UnescapeChars reverses escaped characters. func UnescapeChars(in []byte) []byte { if bytes.ContainsAny(in, "\\\t") { return in } out := bytes.ReplaceAll(in, escapedSlash, regularSlash) out = bytes.ReplaceAll(out, escapedTab, regularTab) return out }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/diff/diff_test.go
git/diff/diff_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package diff import ( "bufio" "reflect" "strings" "testing" "github.com/harness/gitness/errors" ) func TestParseFileHeader(t *testing.T) { tests := []struct { name string input string includePatch bool expectedFile *File expectedError error }{ { name: "valid file header with no quoted paths", input: "diff --git a/example.txt b/example.txt", includePatch: false, expectedFile: &File{ Path: "example.txt", OldPath: "example.txt", Type: FileChange, }, expectedError: nil, }, { name: "valid file header with quoted paths", input: `diff --git "a/example space.txt" "b/example space.txt"`, includePatch: false, expectedFile: &File{ Path: "example space.txt", OldPath: "example space.txt", Type: FileChange, }, expectedError: nil, }, { name: "valid file header with a as quoted path", input: `diff --git "a/example space.txt" b/example space.txt`, includePatch: false, expectedFile: &File{ Path: "example space.txt", OldPath: "example space.txt", Type: FileChange, }, expectedError: nil, }, { name: "valid file header with b as quoted path", input: `diff --git a/example_space.txt "b/example_space.txt"`, includePatch: false, expectedFile: &File{ Path: "example_space.txt", OldPath: "example_space.txt", Type: FileChange, }, expectedError: nil, }, { name: "malformed file header", input: "diff --git a/example.txt example.txt", includePatch: false, expectedFile: nil, expectedError: &errors.Error{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { parser := &Parser{ Reader: bufio.NewReader(strings.NewReader(tt.input)), IncludePatch: tt.includePatch, } parser.buffer = []byte(tt.input) file, err := parser.parseFileHeader() if err != nil && tt.expectedError != nil && !errors.As(err, &tt.expectedError) { t.Errorf("expected error: %v, got: %v", tt.expectedError, err) } if !reflect.DeepEqual(file, tt.expectedFile) { t.Errorf("expected file: %+v, got: %+v", tt.expectedFile, file) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sha/sha.go
git/sha/sha.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sha import ( "bytes" "database/sql/driver" "encoding/gob" "encoding/json" "fmt" "regexp" "strings" "github.com/harness/gitness/errors" "github.com/swaggest/jsonschema-go" ) var ( Nil = Must("0000000000000000000000000000000000000000") None = SHA{} // regex defines the valid SHA format accepted by GIT (full form and short forms). // Note: as of now SHA is at most 40 characters long, but in the future it's moving to sha256 // which is 64 chars - keep this forward-compatible. regex = regexp.MustCompile("^[0-9a-f]{4,64}$") nilRegex = regexp.MustCompile("^0{4,64}$") // EmptyTree is the SHA of an empty tree. EmptyTree = Must("4b825dc642cb6eb9a060e54bf8d69288fbee4904") ) // SHA represents a git sha. type SHA struct { str string } // New creates and validates SHA from the value. func New(value string) (SHA, error) { value = strings.TrimSpace(value) value = strings.ToLower(value) if !regex.MatchString(value) { return SHA{}, errors.InvalidArgumentf("the provided commit sha '%s' is of invalid format.", value) } return SHA{ str: value, }, nil } // NewOrEmpty returns None if value is empty otherwise it will try to create // and validate new SHA object. func NewOrEmpty(value string) (SHA, error) { if value == "" { return None, nil } return New(value) } func (s SHA) GobEncode() ([]byte, error) { buffer := &bytes.Buffer{} err := gob.NewEncoder(buffer).Encode(s.str) if err != nil { return nil, fmt.Errorf("failed to pack sha value: %w", err) } return buffer.Bytes(), nil } func (s *SHA) GobDecode(v []byte) error { if err := gob.NewDecoder(bytes.NewReader(v)).Decode(&s.str); err != nil { return fmt.Errorf("failed to unpack sha value: %w", err) } return nil } func (s *SHA) UnmarshalJSON(content []byte) error { if s == nil { return nil } var str string err := json.Unmarshal(content, &str) if err != nil { return err } sha, err := NewOrEmpty(str) if err != nil { return err } s.str = sha.str return nil } func (s SHA) MarshalJSON() ([]byte, error) { return []byte("\"" + s.str + "\""), nil } // String returns string representation of the SHA. func (s SHA) String() string { return s.str } // IsNil returns whether this SHA is all zeroes. func (s SHA) IsNil() bool { return nilRegex.MatchString(s.str) } // IsEmpty returns whether this SHA is empty string. func (s SHA) IsEmpty() bool { return s.str == "" } // Equal returns true if val has the same SHA. func (s SHA) Equal(val SHA) bool { return s.str == val.str } // Must returns sha if there is an error it will panic. func Must(value string) SHA { sha, err := New(value) if err != nil { panic("invalid SHA" + err.Error()) } return sha } func (s SHA) JSONSchema() (jsonschema.Schema, error) { var schema jsonschema.Schema schema.AddType(jsonschema.String) schema.WithDescription("Git object hash") return schema, nil } func (s SHA) Value() (driver.Value, error) { return s.str, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/sha/sha_test.go
git/sha/sha_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sha import ( "bytes" "encoding/gob" "reflect" "testing" ) const emptyTreeSHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" func TestNew(t *testing.T) { tests := []struct { name string input string wantErr bool }{ { name: "valid sha", input: emptyTreeSHA, wantErr: false, }, { name: "valid short sha", input: "4b825dc6", wantErr: false, }, { name: "valid sha with spaces", input: " " + emptyTreeSHA + " ", wantErr: false, }, { name: "valid sha uppercase", input: "4B825DC642CB6EB9A060E54BF8D69288FBEE4904", wantErr: false, }, { name: "invalid sha - too short", input: "abc", wantErr: true, }, { name: "invalid sha - invalid characters", input: "gggggggggggggggggggggggggggggggggggggggg", wantErr: true, }, { name: "invalid sha - empty", input: "", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := New(tt.input) if (err != nil) != tt.wantErr { t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr && got.String() == "" { t.Error("expected non-empty SHA") } }) } } func TestNewOrEmpty(t *testing.T) { tests := []struct { name string input string wantErr bool isEmpty bool }{ { name: "valid sha", input: emptyTreeSHA, wantErr: false, isEmpty: false, }, { name: "empty string returns None", input: "", wantErr: false, isEmpty: true, }, { name: "invalid sha", input: "invalid", wantErr: true, isEmpty: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := NewOrEmpty(tt.input) if (err != nil) != tt.wantErr { t.Errorf("NewOrEmpty() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr && got.IsEmpty() != tt.isEmpty { t.Errorf("NewOrEmpty() isEmpty = %v, want %v", got.IsEmpty(), tt.isEmpty) } }) } } func TestSHA_IsNil(t *testing.T) { tests := []struct { name string sha SHA isNil bool }{ { name: "nil sha", sha: Nil, isNil: true, }, { name: "non-nil sha", sha: EmptyTree, isNil: false, }, { name: "empty sha", sha: None, isNil: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := tt.sha.IsNil(); got != tt.isNil { t.Errorf("IsNil() = %v, want %v", got, tt.isNil) } }) } } func TestSHA_IsEmpty(t *testing.T) { tests := []struct { name string sha SHA isEmpty bool }{ { name: "empty sha", sha: None, isEmpty: true, }, { name: "non-empty sha", sha: EmptyTree, isEmpty: false, }, { name: "nil sha", sha: Nil, isEmpty: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := tt.sha.IsEmpty(); got != tt.isEmpty { t.Errorf("IsEmpty() = %v, want %v", got, tt.isEmpty) } }) } } func TestSHA_Equal(t *testing.T) { sha1 := Must(emptyTreeSHA) sha2 := Must(emptyTreeSHA) sha3 := Must("1234567890abcdef1234567890abcdef12345678") tests := []struct { name string sha1 SHA sha2 SHA equal bool }{ { name: "equal shas", sha1: sha1, sha2: sha2, equal: true, }, { name: "different shas", sha1: sha1, sha2: sha3, equal: false, }, { name: "empty shas", sha1: None, sha2: None, equal: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := tt.sha1.Equal(tt.sha2); got != tt.equal { t.Errorf("Equal() = %v, want %v", got, tt.equal) } }) } } func TestSHA_String(t *testing.T) { sha := Must(emptyTreeSHA) if got := sha.String(); got != emptyTreeSHA { t.Errorf("String() = %v, want %v", got, emptyTreeSHA) } } func TestSHA_Value(t *testing.T) { sha := Must(emptyTreeSHA) val, err := sha.Value() if err != nil { t.Errorf("Value() error = %v", err) } if val != emptyTreeSHA { t.Errorf("Value() = %v, want %v", val, emptyTreeSHA) } } func TestSHA_GobEncodeDecode(t *testing.T) { original := Must(emptyTreeSHA) // Encode encoded, err := original.GobEncode() if err != nil { t.Fatalf("GobEncode() error = %v", err) } // Decode var decoded SHA err = decoded.GobDecode(encoded) if err != nil { t.Fatalf("GobDecode() error = %v", err) } if !original.Equal(decoded) { t.Errorf("GobEncode/Decode round trip failed: got %v, want %v", decoded, original) } } func TestSHA_GobEncodeDecodeWithGob(t *testing.T) { original := Must(emptyTreeSHA) // Encode using gob var buf bytes.Buffer enc := gob.NewEncoder(&buf) err := enc.Encode(original) if err != nil { t.Fatalf("gob.Encode() error = %v", err) } // Decode using gob var decoded SHA dec := gob.NewDecoder(&buf) err = dec.Decode(&decoded) if err != nil { t.Fatalf("gob.Decode() error = %v", err) } if !original.Equal(decoded) { t.Errorf("gob Encode/Decode round trip failed: got %v, want %v", decoded, original) } } func TestMust(t *testing.T) { t.Run("valid sha", func(t *testing.T) { sha := Must(emptyTreeSHA) if sha.String() != emptyTreeSHA { t.Errorf("Must() = %v, want %v", sha.String(), emptyTreeSHA) } }) t.Run("invalid sha panics", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("Must() did not panic on invalid SHA") } }() Must("invalid") }) } func TestSHA_MarshalJSON(t *testing.T) { tests := []struct { name string input SHA want []byte wantErr bool }{ { name: "happy path", input: EmptyTree, want: []byte("\"" + EmptyTree.String() + "\""), }, { name: "happy path - quotes", input: SHA{ str: "\"\"", }, want: []byte("\"\"\"\""), }, { name: "happy path - empty string", input: SHA{}, want: []byte("\"\""), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := tt.input.MarshalJSON() if (err != nil) != tt.wantErr { t.Errorf("MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("MarshalJSON() got = %v, want %v", got, tt.want) } }) } } func TestSHA_UnmarshalJSON(t *testing.T) { tests := []struct { name string input []byte expected SHA wantErr bool }{ { name: "happy path", input: []byte("\"" + EmptyTree.String() + "\""), expected: EmptyTree, wantErr: false, }, { name: "empty content returns empty", input: []byte("\"\""), expected: SHA{}, wantErr: false, }, { name: "invalid json", input: []byte("invalid"), expected: SHA{}, wantErr: true, }, { name: "invalid sha", input: []byte("\"invalid\""), expected: SHA{}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := SHA{} if err := s.UnmarshalJSON(tt.input); (err != nil) != tt.wantErr { t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) } if !tt.wantErr && !reflect.DeepEqual(s, tt.expected) { t.Errorf("bytes.Equal expected %s, got %s", tt.expected, s) } }) } } func TestSHA_JSONSchema(t *testing.T) { sha := Must(emptyTreeSHA) schema, err := sha.JSONSchema() if err != nil { t.Errorf("JSONSchema() error = %v", err) } if schema.Description == nil || *schema.Description != "Git object hash" { t.Errorf("JSONSchema() description = %v, want 'Git object hash'", schema.Description) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/merge.go
git/api/merge.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "context" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) const ( // RemotePrefix is the base directory of the remotes information of git. RemotePrefix = "refs/remotes/" ) // GetMergeBase checks and returns merge base of two branches and the reference used as base. func (g *Git) GetMergeBase( ctx context.Context, repoPath string, remote string, base string, head string, allowMultipleMergeBases bool, ) (sha.SHA, string, error) { if repoPath == "" { return sha.None, "", ErrRepositoryPathEmpty } if remote == "" { remote = "origin" } if remote != "origin" { tmpBaseName := RemotePrefix + remote + "/tmp_" + base // Fetch commit into a temporary branch in order to be able to handle commits and tags cmd := command.New("fetch", command.WithFlag("--no-tags"), command.WithArg(remote), command.WithPostSepArg(base+":"+tmpBaseName), ) err := cmd.Run(ctx, command.WithDir(repoPath)) if err == nil { base = tmpBaseName } } cmd := command.New("merge-base", command.WithArg(base, head), ) // If the two commits (base and head) have more than one merge-base (a very rare case): // * If allowMultipleMergeBases=true only the first merge base would be returned. // * If allowMultipleMergeBases=false an invalid argument error would be returned. if !allowMultipleMergeBases { cmd = cmd.Add(command.WithFlag("--all")) } stdout, stderr := new(bytes.Buffer), new(bytes.Buffer) err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout), command.WithStderr(stderr), ) if err != nil { // git merge-base rev1 rev2 // if there is unrelated history then stderr is empty with // exit code 1. This cannot be handled in processGitErrorf because stderr is empty. if command.AsError(err).IsExitCode(1) && stderr.Len() == 0 { return sha.None, "", &UnrelatedHistoriesError{ BaseRef: base, HeadRef: head, } } return sha.None, "", processGitErrorf(err, "failed to get merge-base [%s, %s]", base, head) } mergeBase := strings.TrimSpace(stdout.String()) if count := strings.Count(mergeBase, "\n") + 1; count > 1 { return sha.None, "", errors.InvalidArgumentf("The commits %s and %s have %d merge bases. This is not supported.", base, head, count) } result, err := sha.New(mergeBase) if err != nil { return sha.None, "", err } return result, base, nil } // IsAncestor returns if the provided commit SHA is ancestor of the other commit SHA. func (g *Git) IsAncestor( ctx context.Context, repoPath string, alternates []string, ancestorCommitSHA, descendantCommitSHA sha.SHA, ) (bool, error) { if repoPath == "" { return false, ErrRepositoryPathEmpty } cmd := command.New("merge-base", command.WithFlag("--is-ancestor"), command.WithArg(ancestorCommitSHA.String(), descendantCommitSHA.String()), command.WithAlternateObjectDirs(alternates...), ) err := cmd.Run(ctx, command.WithDir(repoPath)) if err != nil { cmdErr := command.AsError(err) if cmdErr != nil && cmdErr.IsExitCode(1) && len(cmdErr.StdErr) == 0 { return false, nil } return false, processGitErrorf(err, "failed to check commit ancestry [%s, %s]", ancestorCommitSHA, descendantCommitSHA) } return true, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/rev.go
git/api/rev.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "context" "fmt" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) func (g *Git) ResolveRev(ctx context.Context, repoPath string, rev string, ) (sha.SHA, error) { cmd := command.New("rev-parse", command.WithArg(rev)) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if err != nil { if command.AsError(err).IsAmbiguousArgErr() { return sha.None, errors.InvalidArgumentf("could not resolve git revision: %s", rev) } return sha.None, fmt.Errorf("failed to resolve git revision: %w", err) } return sha.New(output.String()) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/blame.go
git/api/blame.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "bytes" "context" "io" "regexp" "strconv" "strings" "time" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" "github.com/gotidy/ptr" ) var ( // blamePorcelainHeadRE is used to detect line header start in git blame porcelain output. // It is explained here: https://www.git-scm.com/docs/git-blame#_the_porcelain_format blamePorcelainHeadRE = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64}) (\d+) (\d+)( (\d+))?$`) blamePorcelainOutOfRangeErrorRE = regexp.MustCompile(`has only \d+ lines$`) ) type BlamePart struct { Commit *Commit `json:"commit"` Lines []string `json:"lines"` Previous *BlamePartPrevious `json:"previous,omitempty"` } type BlamePartPrevious struct { CommitSHA sha.SHA `json:"commit_sha"` FileName string `json:"file_name"` } type BlameNextReader interface { NextPart() (*BlamePart, error) } func (g *Git) Blame( ctx context.Context, repoPath string, rev string, file string, lineFrom int, lineTo int, ) BlameNextReader { // prepare the git command line arguments cmd := command.New( "blame", command.WithFlag("--porcelain"), command.WithFlag("--encoding", "UTF-8"), ) if lineFrom > 0 || lineTo > 0 { var lines string if lineFrom > 0 { lines = strconv.Itoa(lineFrom) } if lineTo > 0 { lines += "," + strconv.Itoa(lineTo) } cmd.Add(command.WithFlag("-L", lines)) } cmd.Add(command.WithArg(rev)) cmd.Add(command.WithPostSepArg(file)) pipeRead, pipeWrite := io.Pipe() stderr := &bytes.Buffer{} go func() { var err error defer func() { // If running of the command below fails, make the pipe reader also fail with the same error. _ = pipeWrite.CloseWithError(err) }() err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite), command.WithStderr(stderr), ) }() return &BlameReader{ scanner: bufio.NewScanner(pipeRead), cache: make(map[string]blameReaderCacheItem), errReader: stderr, // Any stderr output will cause the BlameReader to fail. } } type blameReaderCacheItem struct { commit *Commit previous *BlamePartPrevious } type BlameReader struct { scanner *bufio.Scanner lastLine string cache map[string]blameReaderCacheItem errReader io.Reader } func (r *BlameReader) nextLine() (string, error) { if line := r.lastLine; line != "" { r.lastLine = "" return line, nil } for r.scanner.Scan() { line := r.scanner.Text() if line != "" { return line, nil } } if err := r.scanner.Err(); err != nil { return "", err } return "", io.EOF } func (r *BlameReader) unreadLine(line string) { r.lastLine = line } //nolint:complexity,gocognit,nestif // it's ok func (r *BlameReader) NextPart() (*BlamePart, error) { var commit *Commit var previous *BlamePartPrevious var lines []string var err error for { var line string line, err = r.nextLine() if err != nil { break // This is the only place where we break the loop. Normally it will be the io.EOF. } if matches := blamePorcelainHeadRE.FindStringSubmatch(line); matches != nil { commitSHA := sha.Must(matches[1]) if commit == nil { if cacheItem, ok := r.cache[commitSHA.String()]; ok { commit = cacheItem.commit previous = cacheItem.previous } else { commit = &Commit{SHA: commitSHA} } if matches[5] != "" { // At index 5 there's number of lines in this section. However, the resulting // BlamePart might contain more than this because we join consecutive sections // if the commit SHA is the same. lineCount, _ := strconv.Atoi(matches[5]) lines = make([]string, 0, lineCount) } continue } if !commit.SHA.Equal(commitSHA) { r.unreadLine(line) r.cache[commit.SHA.String()] = blameReaderCacheItem{ commit: commit, previous: previous, } return &BlamePart{ Commit: commit, Lines: lines, Previous: previous, }, nil } continue } if commit == nil { // Continue reading the lines until a line header is reached. // This should not happen. Normal output always starts with a line header (with a commit SHA). continue } if line[0] == '\t' { // all output that contains actual file data is prefixed with tab, otherwise it's a header line lines = append(lines, line[1:]) continue } parseBlameHeaders(line, commit, &previous) } // Check if there's something in the error buffer... If yes, that's the error! // It should contain error string from the git. errRaw, _ := io.ReadAll(r.errReader) if len(errRaw) > 0 { line := string(errRaw) if idx := bytes.IndexByte(errRaw, '\n'); idx > 0 { line = line[:idx] // get only the first line of the output } line = strings.TrimPrefix(line, "fatal: ") // git errors start with the "fatal: " prefix switch { case strings.Contains(line, "no such path"): return nil, errors.NotFound(line) case strings.Contains(line, "bad revision"): return nil, errors.NotFound(line) case blamePorcelainOutOfRangeErrorRE.MatchString(line): return nil, errors.InvalidArgument(line) default: return nil, errors.Internalf(nil, "failed to get next part: %s", line) } } // This error can happen if the command git failed to start. Triggered by pipe writer's CloseWithError call. if !errors.Is(err, io.EOF) { return nil, errors.Internal(err, "failed to start git blame command") } var part *BlamePart if commit != nil && len(lines) > 0 { part = &BlamePart{ Commit: commit, Lines: lines, Previous: previous, } } return part, err } func parseBlameHeaders(line string, commit *Commit, previous **BlamePartPrevious) { // This is the list of git blame headers that we process. Other headers we ignore. const ( headerSummary = "summary " headerAuthorName = "author " headerAuthorMail = "author-mail " headerAuthorTime = "author-time " headerCommitterName = "committer " headerCommitterMail = "committer-mail " headerCommitterTime = "committer-time " headerPrevious = "previous " ) switch { case strings.HasPrefix(line, headerSummary): commit.Title = extractName(line[len(headerSummary):]) case strings.HasPrefix(line, headerAuthorName): commit.Author.Identity.Name = extractName(line[len(headerAuthorName):]) case strings.HasPrefix(line, headerAuthorMail): commit.Author.Identity.Email = extractEmail(line[len(headerAuthorMail):]) case strings.HasPrefix(line, headerAuthorTime): commit.Author.When = extractTime(line[len(headerAuthorTime):]) case strings.HasPrefix(line, headerCommitterName): commit.Committer.Identity.Name = extractName(line[len(headerCommitterName):]) case strings.HasPrefix(line, headerCommitterMail): commit.Committer.Identity.Email = extractEmail(line[len(headerCommitterMail):]) case strings.HasPrefix(line, headerCommitterTime): commit.Committer.When = extractTime(line[len(headerCommitterTime):]) case strings.HasPrefix(line, headerPrevious): *previous = ptr.Of(extractPrevious(line[len(headerPrevious):])) } } func extractName(s string) string { return s } // extractPrevious extracts the sha and filename of the previous commit. // example: previous 999d2ed306a916423d18e022abe258e92419ab9a README.md func extractPrevious(s string) BlamePartPrevious { rawSHA, fileName, _ := strings.Cut(s, " ") if len(fileName) > 0 && fileName[0] == '"' { fileName, _ = strconv.Unquote(fileName) } return BlamePartPrevious{ CommitSHA: sha.Must(rawSHA), FileName: fileName, } } // extractEmail extracts email from git blame output. // The email address is wrapped between "<" and ">" characters. // If "<" or ">" are not in place it returns the string as it. func extractEmail(s string) string { if len(s) >= 2 && s[0] == '<' && s[len(s)-1] == '>' { s = s[1 : len(s)-1] } return s } // extractTime extracts timestamp from git blame output. // The timestamp is UNIX time (in seconds). // In case of an error it simply returns zero UNIX time. func extractTime(s string) time.Time { milli, _ := strconv.ParseInt(s, 10, 64) return time.Unix(milli, 0) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/gc.go
git/api/gc.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "time" "github.com/harness/gitness/git/command" ) type GCParams struct { // Aggressive aggressively optimize the repository at the expense of cpu and time of execution. Aggressive bool // Auto option runs git gc checks whether any housekeeping is required, if not, // it exits without performing any work. Auto bool // Cruft option is when expiring unreachable objects pack them separately into a cruft pack // instead of storing them as loose objects. --cruft is on by default. Cruft *bool // MaxCruftSize limit the size of new cruft packs to be at most <n> bytes. MaxCruftSize uint64 // Prune prunes loose objects older than date (default is 2 weeks ago, // overridable by the config variable gc.pruneExpire). We should never use prune=now! Prune any // KeepLargestPack all packs except the largest non-cruft pack, any packs marked with a .keep file, // and any cruft pack(s) are consolidated into a single pack. // When this option is used, gc.bigPackThreshold is ignored. KeepLargestPack bool } // GC runs git gc command to collect garbage and optimize repository structure. func (g *Git) GC( ctx context.Context, repoPath string, params GCParams, ) error { cmd := command.New("gc") if params.Aggressive { cmd.Add(command.WithFlag("--aggressive")) } if params.Auto { cmd.Add(command.WithFlag("--auto")) } if params.Cruft != nil { if *params.Cruft { cmd.Add(command.WithFlag("--cruft")) } else { cmd.Add(command.WithFlag("--no-cruft")) } } if params.MaxCruftSize != 0 { cmd.Add(command.WithFlag(fmt.Sprintf("--max-cruft-size=%d", params.MaxCruftSize))) } // prune is by default on if params.Prune != nil { switch value := params.Prune.(type) { case bool: if !value { cmd.Add(command.WithFlag("--no-prune")) } case string: cmd.Add(command.WithFlag(fmt.Sprintf("--prune=%s", value))) case time.Time: if !value.IsZero() { cmd.Add(command.WithFlag(fmt.Sprintf("--prune=%s", value.Format(RFC2822DateFormat)))) } default: return fmt.Errorf("invalid prune value: %v", value) } } if params.KeepLargestPack { cmd.Add(command.WithFlag("--keep-largest-pack")) } if err := cmd.Run(ctx, command.WithDir(repoPath)); err != nil { return processGitErrorf(err, "failed to run gc command") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/wire.go
git/api/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "fmt" "time" "github.com/harness/gitness/cache" "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/types" "github.com/go-redis/redis/v8" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideLastCommitCache, ) func ProvideLastCommitCache( config types.Config, redisClient redis.UniversalClient, ) (cache.Cache[CommitEntryKey, *Commit], error) { cacheDuration := config.LastCommitCache.Duration // no need to cache if it's too short if cacheDuration < time.Second { return NoLastCommitCache(), nil } switch config.LastCommitCache.Mode { case enum.LastCommitCacheModeNone: return NoLastCommitCache(), nil case enum.LastCommitCacheModeInMemory: return NewInMemoryLastCommitCache(cacheDuration), nil case enum.LastCommitCacheModeRedis: return NewRedisLastCommitCache(redisClient, cacheDuration) default: return nil, fmt.Errorf("unknown last commit cache mode provided: %q", config.LastCommitCache.Mode) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/tree.go
git/api/tree.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "bytes" "context" "fmt" "io" "path" "regexp" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" "github.com/rs/zerolog/log" ) type TreeNodeWithCommit struct { TreeNode Commit *Commit } type TreeNode struct { NodeType TreeNodeType Mode TreeNodeMode SHA sha.SHA Name string Path string Size int64 } func (n *TreeNode) IsExecutable() bool { return n.Mode == TreeNodeModeExec } func (n *TreeNode) IsDir() bool { return n.Mode == TreeNodeModeTree } func (n *TreeNode) IsLink() bool { return n.Mode == TreeNodeModeSymlink } func (n *TreeNode) IsSubmodule() bool { return n.Mode == TreeNodeModeCommit } // TreeNodeType specifies the different types of nodes in a git tree. // IMPORTANT: has to be consistent with rpc.TreeNodeType (proto). type TreeNodeType int const ( TreeNodeTypeTree TreeNodeType = iota TreeNodeTypeBlob TreeNodeTypeCommit ) // TreeNodeMode specifies the different modes of a node in a git tree. // IMPORTANT: has to be consistent with rpc.TreeNodeMode (proto). type TreeNodeMode int const ( TreeNodeModeFile TreeNodeMode = iota TreeNodeModeSymlink TreeNodeModeExec TreeNodeModeTree TreeNodeModeCommit ) func (m TreeNodeMode) String() string { var result int switch m { case TreeNodeModeFile: result = 0o100644 case TreeNodeModeSymlink: result = 0o120000 case TreeNodeModeExec: result = 0o100755 case TreeNodeModeTree: result = 0o040000 case TreeNodeModeCommit: result = 0o160000 } return strconv.FormatInt(int64(result), 8) } func cleanTreePath(treePath string) string { return strings.Trim(path.Clean("/"+treePath), "/") } func parseTreeNodeMode(s string) (TreeNodeType, TreeNodeMode, error) { switch s { case "100644": return TreeNodeTypeBlob, TreeNodeModeFile, nil case "120000": return TreeNodeTypeBlob, TreeNodeModeSymlink, nil case "100755": return TreeNodeTypeBlob, TreeNodeModeExec, nil case "160000": return TreeNodeTypeCommit, TreeNodeModeCommit, nil case "040000": return TreeNodeTypeTree, TreeNodeModeTree, nil default: return TreeNodeTypeBlob, TreeNodeModeFile, fmt.Errorf("unknown git tree node mode: '%s'", s) } } // regexpLsTreeColumns is a regular expression that is used to parse a single line // of a "git ls-tree" output (which uses the NULL character as the line break). // The single line mode must be used because output might contain the EOL and other control characters. var regexpLsTreeColumns = regexp.MustCompile(`(?s)^(\d{6})\s+(\w+)\s+(\w+)(?:\s+(\d+|-))?\t(.+)`) func lsTree( ctx context.Context, repoPath string, rev string, treePath string, fetchSizes bool, recursive bool, ) ([]TreeNode, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } cmd := command.New("ls-tree", command.WithFlag("-z"), command.WithArg(rev), command.WithArg(treePath), ) if fetchSizes { cmd.Add(command.WithFlag("-l")) } if recursive { cmd.Add(command.WithFlag("-r")) } output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output), ) if err != nil { if strings.Contains(err.Error(), "fatal: not a tree object") { return nil, errors.InvalidArgumentf("revision %q does not point to a commit", rev) } if strings.Contains(err.Error(), "fatal: Not a valid object name") { return nil, errors.NotFoundf("revision %q not found", rev) } return nil, fmt.Errorf("failed to run git ls-tree: %w", err) } if output.Len() == 0 { return nil, errors.NotFoundf("path '%s' wasn't found in the repo", treePath) } n := bytes.Count(output.Bytes(), []byte{'\x00'}) list := make([]TreeNode, 0, n) scan := bufio.NewScanner(output) scan.Split(parser.ScanZeroSeparated) for scan.Scan() { line := scan.Text() columns := regexpLsTreeColumns.FindStringSubmatch(line) if columns == nil { log.Ctx(ctx).Error(). Str("ls-tree", output.String()). // logs the whole directory listing for the additional context Str("line", line). Msg("unrecognized format of git directory listing") return nil, fmt.Errorf("unrecognized format of git directory listing: %q", line) } nodeType, nodeMode, err := parseTreeNodeMode(columns[1]) if err != nil { log.Ctx(ctx).Err(err). Str("line", line). Msg("failed to parse git mode") return nil, fmt.Errorf("failed to parse git node type and file mode: %w", err) } nodeSha := sha.Must(columns[3]) var size int64 if columns[4] != "" && columns[4] != "-" { size, err = strconv.ParseInt(columns[4], 10, 64) if err != nil { log.Ctx(ctx).Error(). Str("line", line). Msg("failed to parse file size") return nil, fmt.Errorf("failed to parse file size in the git directory listing: %q", line) } } nodePath := columns[5] nodeName := path.Base(nodePath) list = append(list, TreeNode{ NodeType: nodeType, Mode: nodeMode, SHA: nodeSha, Name: nodeName, Path: nodePath, Size: size, }) } return list, nil } // lsFile returns all tree node entries in the requested directory. func lsDirectory( ctx context.Context, repoPath string, rev string, treePath string, fetchSizes bool, flattenDirectories bool, recursive bool, ) ([]TreeNode, error) { treePath = path.Clean(treePath) if treePath == "" { treePath = "." } else { treePath += "/" } nodes, err := lsTree(ctx, repoPath, rev, treePath, fetchSizes, recursive) if err != nil { return nil, err } if flattenDirectories { for i := range nodes { if nodes[i].NodeType != TreeNodeTypeTree { continue } if err := flattenDirectory(ctx, repoPath, rev, &nodes[i], fetchSizes); err != nil { return nil, fmt.Errorf("failed to flatten directory: %w", err) } } } return nodes, nil } // lsFile returns one tree node entry. func lsFile( ctx context.Context, repoPath string, rev string, treePath string, fetchSize bool, ) (TreeNode, error) { treePath = cleanTreePath(treePath) list, err := lsTree(ctx, repoPath, rev, treePath, fetchSize, false) if err != nil { return TreeNode{}, fmt.Errorf("failed to ls file: %w", err) } if len(list) != 1 { return TreeNode{}, fmt.Errorf("ls file list contains more than one element, len=%d", len(list)) } return list[0], nil } func flattenDirectory( ctx context.Context, repoPath string, rev string, node *TreeNode, fetchSizes bool, ) error { nodes := []TreeNode{*node} var pathPrefix string // Go in depth for as long as there are subdirectories with just one subdirectory. for len(nodes) == 1 && nodes[0].NodeType == TreeNodeTypeTree { nodesTemp, err := lsTree(ctx, repoPath, rev, nodes[0].Path+"/", fetchSizes, false) if err != nil { return fmt.Errorf("failed to peek dir entries for flattening: %w", err) } // Abort when the subdirectory contains more than one entry or contains an entry which is not a directory. // Git doesn't store empty directories. Every git tree must have at least one entry (except the sha.EmptyTree). if len(nodesTemp) != 1 || (len(nodesTemp) == 1 && nodesTemp[0].NodeType != TreeNodeTypeTree) { nodes[0].Name = path.Join(pathPrefix, nodes[0].Name) *node = nodes[0] break } pathPrefix = path.Join(pathPrefix, nodes[0].Name) nodes = nodesTemp } return nil } // GetTreeNode returns the tree node at the given path as found for the provided reference. func (g *Git) GetTreeNode(ctx context.Context, repoPath, rev, treePath string) (*TreeNode, error) { return GetTreeNode(ctx, repoPath, rev, treePath, false) } // GetTreeNode returns the tree node at the given path as found for the provided reference. func GetTreeNode(ctx context.Context, repoPath, rev, treePath string, fetchSize bool) (*TreeNode, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } // anything that's not the root path is a simple call if treePath != "" { treeNode, err := lsFile(ctx, repoPath, rev, treePath, fetchSize) if err != nil { return nil, fmt.Errorf("failed to get tree node: %w", err) } return &treeNode, nil } // root path (empty path) is a special case cmd := command.New("show", command.WithFlag("--no-patch"), command.WithFlag("--format="+fmtTreeHash), //nolint:goconst command.WithArg(rev+"^{commit}"), //nolint:goconst ) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if err != nil { if strings.Contains(err.Error(), "expected commit type") { return nil, errors.InvalidArgumentf("revision %q does not point to a commit", rev) } if strings.Contains(err.Error(), "unknown revision") { return nil, errors.NotFoundf("revision %q not found", rev) } return nil, fmt.Errorf("failed to get root tree node: %w", err) } return &TreeNode{ NodeType: TreeNodeTypeTree, Mode: TreeNodeModeTree, SHA: sha.Must(output.String()), Name: "", Path: "", }, err } // ListTreeNodes lists the child nodes of a tree reachable from ref via the specified path. func (g *Git) ListTreeNodes( ctx context.Context, repoPath, rev, treePath string, flattenDirectories bool, ) ([]TreeNode, error) { return ListTreeNodes(ctx, repoPath, rev, treePath, false, flattenDirectories) } // ListTreeNodes lists the child nodes of a tree reachable from ref via the specified path. func ListTreeNodes( ctx context.Context, repoPath, rev, treePath string, fetchSizes, flattenDirectories bool, ) ([]TreeNode, error) { list, err := lsDirectory( ctx, repoPath, rev, treePath, fetchSizes, flattenDirectories, false, ) if err != nil { return nil, fmt.Errorf("failed to list tree nodes: %w", err) } return list, nil } func ListTreeNodesRecursive( ctx context.Context, repoPath, rev, treePath string, fetchSizes, flattenDirectories bool, ) ([]TreeNode, error) { list, err := lsDirectory( ctx, repoPath, rev, treePath, fetchSizes, flattenDirectories, true, ) if err != nil { return nil, fmt.Errorf("failed to list tree nodes recursive: %w", err) } return list, nil } func (g *Git) ReadTree( ctx context.Context, repoPath string, ref string, w io.Writer, args ...string, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } cmd := command.New("read-tree", command.WithArg(ref), command.WithArg(args...), ) if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(w)); err != nil { return fmt.Errorf("unable to read %s in to the index: %w", ref, err) } return nil } // ListPaths lists all the paths in a repo recursively (similar-ish to `ls -lR`). // Note: Keep method simple for now to avoid unnecessary corner cases // by always listing whole repo content (and not relative to any directory). func (g *Git) ListPaths( ctx context.Context, repoPath string, rev string, includeDirs bool, ) (files []string, dirs []string, err error) { if repoPath == "" { return nil, nil, ErrRepositoryPathEmpty } // use custom ls-tree for speed up (file listing is ~10% faster, with dirs roughly the same) cmd := command.New("ls-tree", command.WithConfig("core.quotePath", "false"), // force printing of path in custom format without quoting command.WithFlag("-z"), command.WithFlag("-r"), command.WithFlag("--full-name"), command.WithArg(rev+"^{commit}"), //nolint:goconst enforce commit revs for now (keep it simple) ) format := fmtFieldPath if includeDirs { cmd.Add(command.WithFlag("-t")) format += fmtZero + fmtFieldObjectType } cmd.Add(command.WithFlag("--format=" + format)) //nolint:goconst output := &bytes.Buffer{} err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output), ) if err != nil { if strings.Contains(err.Error(), "expected commit type") { return nil, nil, errors.InvalidArgumentf("revision %q does not point to a commit", rev) } if strings.Contains(err.Error(), "fatal: Not a valid object name") { return nil, nil, errors.NotFoundf("revision %q not found", rev) } return nil, nil, fmt.Errorf("failed to run git ls-tree: %w", err) } scanner := bufio.NewScanner(output) scanner.Split(parser.ScanZeroSeparated) for scanner.Scan() { path := scanner.Text() isDir := false if includeDirs { // custom format guarantees the object type in the next scan if !scanner.Scan() { return nil, nil, fmt.Errorf("unexpected output from ls-tree when getting object type: %w", scanner.Err()) } objectType := scanner.Text() isDir = strings.EqualFold(objectType, string(GitObjectTypeTree)) } if isDir { dirs = append(dirs, path) continue } files = append(files, path) } if err := scanner.Err(); err != nil { return nil, nil, fmt.Errorf("error reading ls-tree output: %w", err) } return files, dirs, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/cat-file.go
git/api/cat-file.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "bytes" "context" "fmt" "io" "iter" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" "github.com/djherbis/buffer" "github.com/djherbis/nio/v3" ) // WriteCloserError wraps an io.WriteCloser with an additional CloseWithError function. type WriteCloserError interface { io.WriteCloser CloseWithError(err error) error } // CatFileBatch opens git cat-file --batch in the provided repo and returns a stdin pipe, // a stdout reader and cancel function. func CatFileBatch( ctx context.Context, repoPath string, alternateObjectDirs []string, flags ...command.CmdOptionFunc, ) (WriteCloserError, *bufio.Reader, func()) { const bufferSize = 32 * 1024 // We often want to feed the commits in order into cat-file --batch, // followed by their trees and sub trees as necessary. batchStdinReader, batchStdinWriter := io.Pipe() batchStdoutReader, batchStdoutWriter := nio.Pipe(buffer.New(bufferSize)) ctx, ctxCancel := context.WithCancel(ctx) closed := make(chan struct{}) cancel := func() { ctxCancel() _ = batchStdinWriter.Close() _ = batchStdoutReader.Close() <-closed } // Ensure cancel is called as soon as the provided context is cancelled go func() { <-ctx.Done() cancel() }() go func() { stderr := bytes.Buffer{} cmd := command.New("cat-file", command.WithFlag("--batch"), command.WithAlternateObjectDirs(alternateObjectDirs...), ) cmd.Add(flags...) err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdin(batchStdinReader), command.WithStdout(batchStdoutWriter), command.WithStderr(&stderr), ) if err != nil { _ = batchStdoutWriter.CloseWithError(command.NewError(err, stderr.Bytes())) _ = batchStdinReader.CloseWithError(command.NewError(err, stderr.Bytes())) } else { _ = batchStdoutWriter.Close() _ = batchStdinReader.Close() } close(closed) }() // For simplicities sake we'll us a buffered reader to read from the cat-file --batch batchReader := bufio.NewReaderSize(batchStdoutReader, bufferSize) return batchStdinWriter, batchReader, cancel } type BatchHeaderResponse struct { SHA sha.SHA Type GitObjectType Size int64 } // ReadBatchHeaderLine reads the header line from cat-file --batch // <sha> SP <type> SP <size> LF // sha is a 40byte not 20byte here. func ReadBatchHeaderLine(rd *bufio.Reader) (*BatchHeaderResponse, error) { line, err := rd.ReadString('\n') if err != nil { return nil, err } if len(line) == 1 { line, err = rd.ReadString('\n') if err != nil { return nil, err } } idx := strings.IndexByte(line, ' ') if idx < 0 { return nil, errors.NotFoundf("missing space char for: %s", line) } id := line[:idx] objType := line[idx+1:] if objType == "missing" { return nil, errors.NotFoundf("sha '%s' not found", id) } idx = strings.IndexByte(objType, ' ') if idx < 0 { return nil, errors.NotFoundf("sha '%s' not found", id) } sizeStr := objType[idx+1 : len(objType)-1] objType = objType[:idx] size, err := strconv.ParseInt(sizeStr, 10, 64) if err != nil { return nil, err } return &BatchHeaderResponse{ SHA: sha.Must(id), Type: GitObjectType(objType), Size: size, }, nil } func catFileObjects( ctx context.Context, repoPath string, alternateObjectDirs []string, iter iter.Seq[string], fn func(string, sha.SHA, GitObjectType, []byte) error, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } writer, reader, cancel := CatFileBatch(ctx, repoPath, alternateObjectDirs) defer func() { cancel() _ = writer.Close() }() buf := bytes.NewBuffer(nil) buf.Grow(512) for objectName := range iter { if _, err := writer.Write([]byte(objectName)); err != nil { return fmt.Errorf("failed to write object sha to cat-file stdin: %w", err) } if _, err := writer.Write([]byte{'\n'}); err != nil { return fmt.Errorf("failed to write EOL to cat-file stdin: %w", err) } output, err := ReadBatchHeaderLine(reader) if err != nil { if errors.Is(err, io.EOF) || errors.IsNotFound(err) { return fmt.Errorf("object %s does not exist", objectName) } return fmt.Errorf("failed to read cat-file object header line: %w", err) } buf.Reset() _, err = io.CopyN(buf, reader, output.Size) if err != nil { return fmt.Errorf("failed to read object raw data: %w", err) } _, err = reader.Discard(1) if err != nil { return fmt.Errorf("failed to discard EOL byte: %w", err) } err = fn(objectName, output.SHA, output.Type, buf.Bytes()) if err != nil { return fmt.Errorf("failed to parse %s with sha %s: %w", output.Type, output.SHA.String(), err) } } return nil } func CatFileCommits( ctx context.Context, repoPath string, alternateObjectDirs []string, commitSHAs []sha.SHA, ) ([]Commit, error) { commits := make([]Commit, 0, len(commitSHAs)) seq := func(yield func(string) bool) { for _, commitSHA := range commitSHAs { if !yield(commitSHA.String()) { return } } } err := catFileObjects(ctx, repoPath, alternateObjectDirs, seq, func( _ string, commitSHA sha.SHA, objectType GitObjectType, raw []byte, ) error { if objectType != GitObjectTypeCommit { return fmt.Errorf("for SHA %s expected commit, but received %q", commitSHA.String(), objectType) } rawObject, err := parser.Object(raw) if err != nil { return fmt.Errorf("failed to parse git object for SHA %s: %w", commitSHA.String(), err) } commit, err := asCommit(commitSHA, rawObject) if err != nil { return fmt.Errorf("failed to convert git object to commit SHA %s: %w", commitSHA.String(), err) } commits = append(commits, commit) return nil }) if err != nil { return nil, fmt.Errorf("failed to cat-file commits: %w", err) } return commits, nil } func CatFileAnnotatedTag( ctx context.Context, repoPath string, alternateObjectDirs []string, rev string, ) (*Tag, error) { var tags []Tag seq := func(yield func(string) bool) { yield(rev) } tags, err := catFileAnnotatedTags(ctx, repoPath, alternateObjectDirs, tags, seq) if err != nil { return nil, err } return &tags[0], nil } func CatFileAnnotatedTagFromSHAs( ctx context.Context, repoPath string, alternateObjectDirs []string, tagSHAs []sha.SHA, ) ([]Tag, error) { tags := make([]Tag, 0, len(tagSHAs)) seq := func(yield func(string) bool) { for _, tagSHA := range tagSHAs { if !yield(tagSHA.String()) { return } } } return catFileAnnotatedTags(ctx, repoPath, alternateObjectDirs, tags, seq) } func catFileAnnotatedTags( ctx context.Context, repoPath string, alternateObjectDirs []string, tags []Tag, seq iter.Seq[string], ) ([]Tag, error) { err := catFileObjects(ctx, repoPath, alternateObjectDirs, seq, func( objectName string, tagSHA sha.SHA, objectType GitObjectType, raw []byte, ) error { if objectType != GitObjectTypeTag { return fmt.Errorf("for %q (%s) expected tag, but received %q", objectName, tagSHA.String(), objectType) } rawObject, err := parser.Object(raw) if err != nil { return fmt.Errorf("failed to parse git object %s: %w", tagSHA.String(), err) } tag, err := asTag(tagSHA, rawObject) if err != nil { return fmt.Errorf("failed to convert git object %s to tag: %w", tagSHA.String(), err) } tags = append(tags, tag) return nil }) if err != nil { return nil, fmt.Errorf("failed to cat-file commits: %w", err) } return tags, nil } func asCommit( commitSHA sha.SHA, raw parser.ObjectRaw, ) (Commit, error) { var ( treeCount int authorCount int committerCount int treeSHA sha.SHA parentSHAs []sha.SHA author Signature committer Signature ) for _, header := range raw.Headers { value := strings.TrimRight(header.Value, "\n") switch header.Type { case "tree": entrySHA, err := sha.New(strings.TrimSpace(value)) if err != nil { return Commit{}, fmt.Errorf("failed to parse tree SHA %s: %w", value, err) } treeCount++ treeSHA = entrySHA case "parent": entrySHA, err := sha.New(value) if err != nil { return Commit{}, fmt.Errorf("failed to parse parent SHA %s: %w", value, err) } parentSHAs = append(parentSHAs, entrySHA) case "author": name, email, when, err := parser.ObjectHeaderIdentity(value) if err != nil { return Commit{}, fmt.Errorf("failed to parse author SHA %s: %w", value, err) } authorCount++ author = Signature{Identity: Identity{Name: name, Email: email}, When: when} case "committer": name, email, when, err := parser.ObjectHeaderIdentity(value) if err != nil { return Commit{}, fmt.Errorf("failed to parse committer SHA %s: %w", value, err) } committerCount++ committer = Signature{Identity: Identity{Name: name, Email: email}, When: when} case "encoding": // encoding is not currently processed - we assume UTF-8 case "mergetag": // encoding is not currently processed default: // custom headers not processed. } } if treeCount != 1 && authorCount != 1 && committerCount != 1 { return Commit{}, fmt.Errorf("incomplete commit info: trees=%d authors=%d committers=%d", treeCount, authorCount, committerCount) } title := parser.ExtractSubject(raw.Message) var signedData *SignedData if raw.SignatureType != "" { signedData = &SignedData{ Type: raw.SignatureType, Signature: raw.Signature, SignedContent: raw.SignedContent, } } return Commit{ SHA: commitSHA, TreeSHA: treeSHA, ParentSHAs: parentSHAs, Title: title, Message: raw.Message, Author: author, Committer: committer, SignedData: signedData, FileStats: nil, }, nil } func asTag(tagSHA sha.SHA, raw parser.ObjectRaw) (Tag, error) { var ( objectCount int tagTypeCount int tagNameCount int taggerCount int objectSHA sha.SHA tagType GitObjectType tagName string tagger Signature ) for _, header := range raw.Headers { value := strings.TrimRight(header.Value, "\n") switch header.Type { case "object": entrySHA, err := sha.New(value) if err != nil { return Tag{}, fmt.Errorf("failed to parse object SHA %s: %w", value, err) } objectCount++ objectSHA = entrySHA case "type": entryType, err := ParseGitObjectType(value) if err != nil { return Tag{}, err } tagTypeCount++ tagType = entryType case "tag": tagNameCount++ tagName = value case "tagger": name, email, when, err := parser.ObjectHeaderIdentity(value) if err != nil { return Tag{}, fmt.Errorf("failed to parse tagger %s: %w", value, err) } taggerCount++ tagger = Signature{Identity: Identity{Name: name, Email: email}, When: when} default: } } if objectCount != 1 && tagTypeCount != 1 && tagNameCount != 1 { return Tag{}, fmt.Errorf("incomplete tag info: objects=%d types=%d tags=%d", objectCount, tagTypeCount, tagNameCount) } title := parser.ExtractSubject(raw.Message) var signedData *SignedData if raw.SignatureType != "" { signedData = &SignedData{ Type: raw.SignatureType, Signature: raw.Signature, SignedContent: raw.SignedContent, } } return Tag{ Sha: tagSHA, Name: tagName, TargetSHA: objectSHA, TargetType: tagType, Title: title, Message: raw.Message, Tagger: tagger, SignedData: signedData, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/commit.go
git/api/commit.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "bytes" "context" "fmt" "regexp" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/enum" "github.com/harness/gitness/git/sha" "github.com/rs/zerolog/log" "golang.org/x/sync/errgroup" ) type CommitChangesOptions struct { Committer Signature Author Signature Message string } type CommitFileStats struct { ChangeType enum.FileDiffStatus Path string OldPath string // populated only in case of renames Insertions int64 Deletions int64 } type Commit struct { SHA sha.SHA TreeSHA sha.SHA ParentSHAs []sha.SHA Title string Message string Author Signature Committer Signature SignedData *SignedData FileStats []CommitFileStats } type CommitFilter struct { Path string AfterRef string Since int64 Until int64 Committer string Author string Regex bool } // CommitDivergenceRequest contains the refs for which the converging commits should be counted. type CommitDivergenceRequest struct { // From is the ref from which the counting of the diverging commits starts. From string // To is the ref at which the counting of the diverging commits ends. To string } // CommitDivergence contains the information of the count of converging commits between two refs. type CommitDivergence struct { // Ahead is the count of commits the 'From' ref is ahead of the 'To' ref. Ahead int32 // Behind is the count of commits the 'From' ref is behind the 'To' ref. Behind int32 } type PathRenameDetails struct { OldPath string Path string CommitSHABefore sha.SHA CommitSHAAfter sha.SHA } func (g *Git) listCommitSHAs( ctx context.Context, repoPath string, alternateObjectDirs []string, ref string, page int, limit int, filter CommitFilter, ) ([]sha.SHA, error) { cmd := command.New("rev-list") // return commits only up to a certain reference if requested if filter.AfterRef != "" { // ^REF tells the rev-list command to return only commits that aren't reachable by SHA cmd.Add(command.WithArg(fmt.Sprintf("^%s", filter.AfterRef))) } // add refCommitSHA as starting point cmd.Add(command.WithArg(ref)) cmd.Add(command.WithAlternateObjectDirs(alternateObjectDirs...)) if len(filter.Path) != 0 { cmd.Add(command.WithPostSepArg(filter.Path)) } // add pagination if requested // TODO: we should add absolut limits to protect git (return error) if limit > 0 { cmd.Add(command.WithFlag("--max-count", strconv.Itoa(limit))) if page > 1 { cmd.Add(command.WithFlag("--skip", strconv.Itoa((page-1)*limit))) } } if filter.Since > 0 || filter.Until > 0 { cmd.Add(command.WithFlag("--date", "unix")) } if filter.Since > 0 { cmd.Add(command.WithFlag("--since", strconv.FormatInt(filter.Since, 10))) } if filter.Until > 0 { cmd.Add(command.WithFlag("--until", strconv.FormatInt(filter.Until, 10))) } if filter.Regex { cmd.Add(command.WithFlag("-E")) } if filter.Committer != "" { cmd.Add(command.WithFlag("--committer", filter.Committer)) } if filter.Author != "" { cmd.Add(command.WithFlag("--author", filter.Author)) } output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if cErr := command.AsError(err); cErr != nil && cErr.IsExitCode(128) { if cErr.IsAmbiguousArgErr() || cErr.IsBadObject() { return []sha.SHA{}, nil // return an empty list if reference doesn't exist } } if err != nil { return nil, processGitErrorf(err, "failed to trigger rev-list command") } var objectSHAs []sha.SHA scanner := bufio.NewScanner(output) for scanner.Scan() { objectSHA, err := sha.New(scanner.Text()) if err != nil { return nil, fmt.Errorf("failed to parse commit sha: %w", err) } objectSHAs = append(objectSHAs, objectSHA) } if err := scanner.Err(); err != nil { return nil, fmt.Errorf("failed to scan commit sha list: %w", err) } return objectSHAs, nil } // ListCommitSHAs lists the commits reachable from ref. // Note: ref & afterRef can be Branch / Tag / CommitSHA. // Note: commits returned are [ref->...->afterRef). func (g *Git) ListCommitSHAs( ctx context.Context, repoPath string, alternateObjectDirs []string, ref string, page int, limit int, filter CommitFilter, ) ([]sha.SHA, error) { return g.listCommitSHAs(ctx, repoPath, alternateObjectDirs, ref, page, limit, filter) } // ListCommits lists the commits reachable from ref. // Note: ref & afterRef can be Branch / Tag / CommitSHA. // Note: commits returned are [ref->...->afterRef). func (g *Git) ListCommits( ctx context.Context, repoPath string, ref string, page int, limit int, includeStats bool, filter CommitFilter, ) ([]Commit, []PathRenameDetails, error) { if repoPath == "" { return nil, nil, ErrRepositoryPathEmpty } commitSHAs, err := g.listCommitSHAs(ctx, repoPath, nil, ref, page, limit, filter) if err != nil { return nil, nil, fmt.Errorf("failed to list commit SHAs: %w", err) } commits, err := CatFileCommits(ctx, repoPath, nil, commitSHAs) if err != nil { return nil, nil, fmt.Errorf("failed to list commits by SHAs: %w", err) } if includeStats { for i := range commits { fileStats, err := getCommitFileStats(ctx, repoPath, commits[i].SHA) if err != nil { return nil, nil, fmt.Errorf("encountered error getting commit file stats: %w", err) } commits[i].FileStats = fileStats } } if len(filter.Path) != 0 { renameDetailsList, err := getRenameDetails(ctx, repoPath, commits, filter.Path) if err != nil { return nil, nil, err } cleanedUpCommits := cleanupCommitsForRename(commits, renameDetailsList, filter.Path) return cleanedUpCommits, renameDetailsList, nil } return commits, nil, nil } func getCommitFileStats( ctx context.Context, repoPath string, sha sha.SHA, ) ([]CommitFileStats, error) { g, ctx := errgroup.WithContext(ctx) var changeInfoChanges map[string]changeInfoChange var changeInfoTypes map[string]changeInfoType g.Go(func() error { var err error changeInfoChanges, err = getChangeInfoChanges(ctx, repoPath, sha) return err }) g.Go(func() error { var err error changeInfoTypes, err = getChangeInfoTypes(ctx, repoPath, sha) return err }) if err := g.Wait(); err != nil { return nil, fmt.Errorf("failed to get change infos: %w", err) } if len(changeInfoTypes) == 0 { return []CommitFileStats{}, nil } fileStats := make([]CommitFileStats, len(changeInfoChanges)) i := 0 for path, info := range changeInfoChanges { fileStats[i] = CommitFileStats{ Path: changeInfoTypes[path].Path, OldPath: changeInfoTypes[path].OldPath, ChangeType: changeInfoTypes[path].Status, Insertions: info.Insertions, Deletions: info.Deletions, } i++ } return fileStats, nil } // In case of rename of a file, same commit will be listed twice - Once in old file and second time in new file. // Hence, we are making it a pattern to only list it as part of new file and not as part of old file. func cleanupCommitsForRename( commits []Commit, renameDetails []PathRenameDetails, path string, ) []Commit { if len(commits) == 0 { return commits } for _, renameDetail := range renameDetails { // Since rename details is present it implies that we have commits and hence don't need null check. if commits[0].SHA.Equal(renameDetail.CommitSHABefore) && path == renameDetail.OldPath { return commits[1:] } } return commits } func getRenameDetails( ctx context.Context, repoPath string, commits []Commit, path string, ) ([]PathRenameDetails, error) { if len(commits) == 0 { return []PathRenameDetails{}, nil } renameDetailsList := make([]PathRenameDetails, 0, 2) renameDetails, err := gitGetRenameDetails(ctx, repoPath, commits[0].SHA, path) if err != nil { return nil, err } if renameDetails.Path != "" || renameDetails.OldPath != "" { renameDetails.CommitSHABefore = commits[0].SHA renameDetailsList = append(renameDetailsList, *renameDetails) } if len(commits) == 1 { return renameDetailsList, nil } renameDetailsLast, err := gitGetRenameDetails(ctx, repoPath, commits[len(commits)-1].SHA, path) if err != nil { return nil, err } if renameDetailsLast.Path != "" || renameDetailsLast.OldPath != "" { renameDetailsLast.CommitSHAAfter = commits[len(commits)-1].SHA renameDetailsList = append(renameDetailsList, *renameDetailsLast) } return renameDetailsList, nil } func gitGetRenameDetails( ctx context.Context, repoPath string, sha sha.SHA, path string, ) (*PathRenameDetails, error) { changeInfos, err := getChangeInfoTypes(ctx, repoPath, sha) if err != nil { return &PathRenameDetails{}, fmt.Errorf("failed to get change infos %w", err) } for _, c := range changeInfos { if c.Status == enum.FileDiffStatusRenamed && (c.OldPath == path || c.Path == path) { return &PathRenameDetails{ OldPath: c.OldPath, Path: c.Path, }, nil } } return &PathRenameDetails{}, nil } func gitLogNameStatus(ctx context.Context, repoPath string, sha sha.SHA) ([]string, error) { cmd := command.New("log", command.WithFlag("--name-status"), command.WithFlag("--format="), //nolint:goconst command.WithFlag("--max-count=1"), command.WithArg(sha.String()), ) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if err != nil { return nil, fmt.Errorf("failed to trigger log command: %w", err) } return parseLinesToSlice(output.Bytes()), nil } func gitShowNumstat( ctx context.Context, repoPath string, sha sha.SHA, ) ([]string, error) { cmd := command.New("show", command.WithFlag("--numstat"), command.WithFlag("--format="), //nolint:goconst command.WithArg(sha.String()), ) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if err != nil { return nil, fmt.Errorf("failed to trigger show command: %w", err) } return parseLinesToSlice(output.Bytes()), nil } // Will match "R100\tREADME.md\tREADME_new.md". // Will extract README.md and README_new.md. var renameRegex = regexp.MustCompile(`\t(.+)\t(.+)`) func getChangeInfoTypes( ctx context.Context, repoPath string, sha sha.SHA, ) (map[string]changeInfoType, error) { lines, err := gitLogNameStatus(ctx, repoPath, sha) if err != nil { return nil, err } changeInfoTypes := make(map[string]changeInfoType, len(lines)) for _, line := range lines { c := changeInfoType{} matches := renameRegex.FindStringSubmatch(line) // renamed file if len(matches) > 0 { c.OldPath = matches[1] c.Path = matches[2] } else { lineParts := strings.Split(line, "\t") if len(lineParts) != 2 { return changeInfoTypes, fmt.Errorf("could not parse file change status string %q", line) } c.Path = lineParts[1] } c.Status = convertFileDiffStatus(ctx, line) changeInfoTypes[c.Path] = c } return changeInfoTypes, nil } // Will match "31\t0\t.harness/apidiff.yaml" and extract 31, 0 and .harness/apidiff.yaml. // Will match "-\t-\ttools/code-api/chart/charts/harness-common-1.0.27.tgz" and extract -, -, and a filename. var insertionsDeletionsRegex = regexp.MustCompile(`(\d+|-)\t(\d+|-)\t(.+)`) // Will match "0\t0\tREADME.md => README_new.md" and extract README_new.md. // Will match "-\t-\tfile_name.bin => file_name_new.bin" and extract file_name_new.bin. var renameRegexWithArrow = regexp.MustCompile(`(?:\d+|-)\t(?:\d+|-)\t.+\s=>\s(.+)`) func getChangeInfoChanges( ctx context.Context, repoPath string, sha sha.SHA, ) (map[string]changeInfoChange, error) { lines, err := gitShowNumstat(ctx, repoPath, sha) if err != nil { return nil, err } changeInfos := make(map[string]changeInfoChange, len(lines)) for _, line := range lines { matches := insertionsDeletionsRegex.FindStringSubmatch(line) if len(matches) != 4 { return map[string]changeInfoChange{}, fmt.Errorf("failed to regex match insertions and deletions for %q", line) } path := matches[3] if renMatches := renameRegexWithArrow.FindStringSubmatch(line); len(renMatches) == 2 { path = renMatches[1] } if matches[1] == "-" || matches[2] == "-" { changeInfos[path] = changeInfoChange{} continue } insertions, err := strconv.ParseInt(matches[1], 10, 64) if err != nil { return map[string]changeInfoChange{}, fmt.Errorf("failed to parse insertions for %q", line) } deletions, err := strconv.ParseInt(matches[2], 10, 64) if err != nil { return map[string]changeInfoChange{}, fmt.Errorf("failed to parse deletions for %q", line) } changeInfos[path] = changeInfoChange{ Insertions: insertions, Deletions: deletions, } } return changeInfos, nil } type changeInfoType struct { Status enum.FileDiffStatus OldPath string // populated only in case of renames Path string } type changeInfoChange struct { Insertions int64 Deletions int64 } func convertFileDiffStatus(ctx context.Context, c string) enum.FileDiffStatus { switch { case strings.HasPrefix(c, "A"): return enum.FileDiffStatusAdded case strings.HasPrefix(c, "C"): return enum.FileDiffStatusCopied case strings.HasPrefix(c, "D"): return enum.FileDiffStatusDeleted case strings.HasPrefix(c, "M"): return enum.FileDiffStatusModified case strings.HasPrefix(c, "R"): return enum.FileDiffStatusRenamed default: log.Ctx(ctx).Warn().Msgf("encountered unknown change type %s", c) return enum.FileDiffStatusUndefined } } // GetCommitFromRev returns the (latest) commit for a specific revision. func (g *Git) GetCommitFromRev( ctx context.Context, repoPath string, rev string, ) (*Commit, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } commitSHA, err := g.ResolveRev(ctx, repoPath, rev+"^{commit}") if errors.IsInvalidArgument(err) { return nil, errors.NotFoundf("revision %q not found", rev) } if err != nil { return nil, fmt.Errorf("failed to resolve revision %q: %w", rev, err) } return GetCommit(ctx, repoPath, commitSHA) } // GetCommits returns the commits for a specific list of SHAs. func (g *Git) GetCommits( ctx context.Context, repoPath string, commitSHAs []sha.SHA, ) ([]Commit, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } commits, err := CatFileCommits(ctx, repoPath, nil, commitSHAs) if err != nil { return nil, fmt.Errorf("failed to list commits by SHAs: %w", err) } return commits, nil } func GetCommit(ctx context.Context, repoPath string, commitSHA sha.SHA) (*Commit, error) { commits, err := CatFileCommits(ctx, repoPath, nil, []sha.SHA{commitSHA}) if err != nil { return nil, fmt.Errorf("failed to list commit by SHA: %w", err) } if len(commits) != 1 { return nil, fmt.Errorf("expected one commit, but got %d", len(commits)) } return &commits[0], nil } func GetLatestCommit( ctx context.Context, repoPath string, rev string, path string, ) (*Commit, error) { cmd := command.New("log", command.WithFlag("--max-count", "1"), command.WithFlag("--format="+fmtCommitHash), command.WithArg(rev), command.WithPostSepArg(path)) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if err != nil { if strings.Contains(err.Error(), "ambiguous argument") { return nil, errors.NotFoundf("revision %q not found", rev) } return nil, fmt.Errorf("failed to run git to get commit data: %w", err) } commitLine := strings.TrimSpace(output.String()) if commitLine == "" { return nil, errors.InvalidArgumentf("path %q not found in %s", path, rev) } commitSHA := sha.Must(commitLine) return GetCommit(ctx, repoPath, commitSHA) } // GetCommitDivergences returns the count of the diverging commits for all branch pairs. // IMPORTANT: If a maxCount is provided it limits the overal count of diverging commits // (maxCount 10 could lead to (0, 10) while it's actually (2, 12)). func (g *Git) GetCommitDivergences( ctx context.Context, repoPath string, requests []CommitDivergenceRequest, maxCount int32, ) ([]CommitDivergence, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } var err error res := make([]CommitDivergence, len(requests)) for i, req := range requests { res[i], err = g.getCommitDivergence(ctx, repoPath, req, maxCount) if errors.IsNotFound(err) { res[i] = CommitDivergence{Ahead: -1, Behind: -1} continue } if err != nil { return nil, err } } return res, nil } // getCommitDivergence returns the count of diverging commits for a pair of branches. // IMPORTANT: If a maxCount is provided it limits the overall count of diverging commits // (maxCount 10 could lead to (0, 10) while it's actually (2, 12)). func (g *Git) getCommitDivergence( ctx context.Context, repoPath string, req CommitDivergenceRequest, maxCount int32, ) (CommitDivergence, error) { cmd := command.New("rev-list", command.WithFlag("--count"), command.WithFlag("--left-right"), ) // limit count if requested. if maxCount > 0 { cmd.Add(command.WithFlag("--max-count", strconv.Itoa(int(maxCount)))) } // add query to get commits without shared base commits cmd.Add(command.WithArg(req.From + "..." + req.To)) stdout := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout)) if err != nil { return CommitDivergence{}, processGitErrorf(err, "git rev-list failed for '%s...%s'", req.From, req.To) } // parse output, e.g.: `1 2\n` output := stdout.String() rawLeft, rawRight, ok := strings.Cut(output, "\t") if !ok { return CommitDivergence{}, fmt.Errorf("git rev-list returned unexpected output '%s'", output) } // trim any unnecessary characters rawLeft = strings.TrimRight(rawLeft, " \t") rawRight = strings.TrimRight(rawRight, " \t\n") // parse numbers left, err := strconv.ParseInt(rawLeft, 10, 32) if err != nil { return CommitDivergence{}, fmt.Errorf("failed to parse git rev-list output for ahead '%s' (full: '%s')): %w", rawLeft, output, err) } right, err := strconv.ParseInt(rawRight, 10, 32) if err != nil { return CommitDivergence{}, fmt.Errorf("failed to parse git rev-list output for behind '%s' (full: '%s')): %w", rawRight, output, err) } return CommitDivergence{ Ahead: int32(left), Behind: int32(right), }, nil } func parseLinesToSlice(output []byte) []string { if len(output) == 0 { return nil } lines := bytes.Split(bytes.TrimSpace(output), []byte{'\n'}) slice := make([]string, len(lines)) for i, line := range lines { slice[i] = string(line) } return slice }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/api.go
git/api/api.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "github.com/harness/gitness/cache" "github.com/harness/gitness/git/hook" "github.com/harness/gitness/git/types" ) type Git struct { traceGit bool lastCommitCache cache.Cache[CommitEntryKey, *Commit] githookFactory hook.ClientFactory } func New( config types.Config, lastCommitCache cache.Cache[CommitEntryKey, *Commit], githookFactory hook.ClientFactory, ) (*Git, error) { return &Git{ traceGit: config.Trace, lastCommitCache: lastCommitCache, githookFactory: githookFactory, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/ref.go
git/api/ref.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "context" "fmt" "io" "math" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/api/foreachref" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) // GitReferenceField represents the different fields available When listing references. // For the full list, see https://git-scm.com/docs/git-for-each-ref#_field_names type GitReferenceField string const ( GitReferenceFieldRefName GitReferenceField = "refname" GitReferenceFieldObjectType GitReferenceField = "objecttype" GitReferenceFieldObjectName GitReferenceField = "objectname" GitReferenceFieldCreatorDate GitReferenceField = "creatordate" ) func ParseGitReferenceField(f string) (GitReferenceField, error) { switch f { case string(GitReferenceFieldCreatorDate): return GitReferenceFieldCreatorDate, nil case string(GitReferenceFieldRefName): return GitReferenceFieldRefName, nil case string(GitReferenceFieldObjectName): return GitReferenceFieldObjectName, nil case string(GitReferenceFieldObjectType): return GitReferenceFieldObjectType, nil default: return GitReferenceFieldRefName, fmt.Errorf("unknown git reference field '%s'", f) } } type WalkInstruction int const ( WalkInstructionStop WalkInstruction = iota WalkInstructionHandle WalkInstructionSkip ) type WalkReferencesEntry map[GitReferenceField]string // TODO: can be generic (so other walk methods can use the same) type WalkReferencesInstructor func(WalkReferencesEntry) (WalkInstruction, error) // TODO: can be generic (so other walk methods can use the same) type WalkReferencesHandler func(WalkReferencesEntry) error type WalkReferencesOptions struct { // Patterns are the patterns used to pre-filter the references of the repo. // OPTIONAL. By default all references are walked. Patterns []string // Fields indicates the fields that are passed to the instructor & handler // OPTIONAL. Default fields are: // - GitReferenceFieldRefName // - GitReferenceFieldObjectName Fields []GitReferenceField // Instructor indicates on how to handle the reference. // OPTIONAL. By default all references are handled. // NOTE: once walkInstructionStop is returned, the walking stops. Instructor WalkReferencesInstructor // Sort indicates the field by which the references should be sorted. // OPTIONAL. By default GitReferenceFieldRefName is used. Sort GitReferenceField // Order indicates the Order (asc or desc) of the sorted output Order SortOrder // MaxWalkDistance is the maximum number of nodes that are iterated over before the walking stops. // OPTIONAL. A value of <= 0 will walk all references. // WARNING: Skipped elements count towards the walking distance MaxWalkDistance int32 } func DefaultInstructor( _ WalkReferencesEntry, ) (WalkInstruction, error) { return WalkInstructionHandle, nil } // WalkReferences uses the provided options to filter the available references of the repo, // and calls the handle function for every matching node. // The instructor & handler are called with a map that contains the matching value for every field provided in fields. // TODO: walkReferences related code should be moved to separate file. func (g *Git) WalkReferences( ctx context.Context, repoPath string, handler WalkReferencesHandler, opts *WalkReferencesOptions, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } // backfil optional options if opts.Instructor == nil { opts.Instructor = DefaultInstructor } if len(opts.Fields) == 0 { opts.Fields = []GitReferenceField{GitReferenceFieldRefName, GitReferenceFieldObjectName} } if opts.MaxWalkDistance <= 0 { opts.MaxWalkDistance = math.MaxInt32 } if opts.Patterns == nil { opts.Patterns = []string{} } if string(opts.Sort) == "" { opts.Sort = GitReferenceFieldRefName } // prepare for-each-ref input sortArg := mapToReferenceSortingArgument(opts.Sort, opts.Order) rawFields := make([]string, len(opts.Fields)) for i := range opts.Fields { rawFields[i] = string(opts.Fields[i]) } format := foreachref.NewFormat(rawFields...) // initializer pipeline for output processing pipeOut, pipeIn := io.Pipe() defer pipeOut.Close() go func() { cmd := command.New("for-each-ref", command.WithFlag("--format", format.Flag()), command.WithFlag("--sort", sortArg), command.WithFlag("--count", strconv.Itoa(int(opts.MaxWalkDistance))), command.WithFlag("--ignore-case"), ) cmd.Add(command.WithArg(opts.Patterns...)) err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeIn), ) if err != nil { _ = pipeIn.CloseWithError(err) } else { _ = pipeIn.Close() } }() // TODO: return error from git command!!!! parser := format.Parser(pipeOut) return walkReferenceParser(parser, handler, opts) } func walkReferenceParser( parser *foreachref.Parser, handler WalkReferencesHandler, opts *WalkReferencesOptions, ) error { for i := int32(0); i < opts.MaxWalkDistance; i++ { // parse next line - nil if end of output reached or an error occurred. rawRef := parser.Next() if rawRef == nil { break } // convert to correct map. ref, err := mapRawRef(rawRef) if err != nil { return err } // check with the instructor on the next instruction. instruction, err := opts.Instructor(ref) if err != nil { return fmt.Errorf("error getting instruction: %w", err) } if instruction == WalkInstructionSkip { continue } if instruction == WalkInstructionStop { break } // otherwise handle the reference. err = handler(ref) if err != nil { return fmt.Errorf("error handling reference: %w", err) } } if err := parser.Err(); err != nil { return processGitErrorf(err, "failed to parse reference walk output") } return nil } // GetRef get's the target of a reference // IMPORTANT provide full reference name to limit risk of collisions across reference types // (e.g `refs/heads/main` instead of `main`). func (g *Git) GetRef( ctx context.Context, repoPath string, ref string, ) (sha.SHA, error) { if repoPath == "" { return sha.None, ErrRepositoryPathEmpty } cmd := command.New("show-ref", command.WithFlag("--verify"), command.WithFlag("-s"), command.WithArg(ref), ) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if cErr := command.AsError(err); cErr != nil { if cErr.IsExitCode(128) && cErr.IsInvalidRefErr() { return sha.None, errors.NotFoundf("reference %q not found", ref) } } if err != nil { return sha.None, err } return sha.New(output.String()) } // GetReferenceFromBranchName assumes the provided value is the branch name (not the ref!) // and first sanitizes the branch name (remove any spaces or 'refs/heads/' prefix) // It then returns the full form of the branch reference. func GetReferenceFromBranchName(branchName string) string { // remove spaces branchName = strings.TrimSpace(branchName) // remove `refs/heads/` prefix (shouldn't be there, but if it is remove it to try to avoid complications) // NOTE: This is used to reduce misconfigurations via api // TODO: block via CLI, too branchName = strings.TrimPrefix(branchName, gitReferenceNamePrefixBranch) // return reference return gitReferenceNamePrefixBranch + branchName } func GetReferenceFromTagName(tagName string) string { // remove spaces tagName = strings.TrimSpace(tagName) // remove `refs/heads/` prefix (shouldn't be there, but if it is remove it to try to avoid complications) // NOTE: This is used to reduce misconfigurations via api // TODO: block via CLI, too tagName = strings.TrimPrefix(tagName, gitReferenceNamePrefixTag) // return reference return gitReferenceNamePrefixTag + tagName }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/archive.go
git/api/archive.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "io" "strings" "time" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" ) type ArchiveFormat string const ( ArchiveFormatTar ArchiveFormat = "tar" ArchiveFormatZip ArchiveFormat = "zip" ArchiveFormatTarGz ArchiveFormat = "tar.gz" ArchiveFormatTgz ArchiveFormat = "tgz" ) var ArchiveFormats = []ArchiveFormat{ ArchiveFormatTar, ArchiveFormatZip, ArchiveFormatTarGz, ArchiveFormatTgz, } func ParseArchiveFormat(format string) (ArchiveFormat, error) { switch format { case "tar": return ArchiveFormatTar, nil case "zip": return ArchiveFormatZip, nil case "tar.gz": return ArchiveFormatTarGz, nil case "tgz": return ArchiveFormatTgz, nil default: return "", errors.InvalidArgumentf("failed to parse file format '%s' is invalid", format) } } func (f ArchiveFormat) Validate() error { switch f { case ArchiveFormatTar, ArchiveFormatZip, ArchiveFormatTarGz, ArchiveFormatTgz: return nil default: return errors.InvalidArgumentf("git archive flag format '%s' is invalid", f) } } type ArchiveAttribute string const ( ArchiveAttributeExportIgnore ArchiveAttribute = "export-ignore" ArchiveAttributeExportSubst ArchiveAttribute = "export-subst" ) func (f ArchiveAttribute) Validate() error { switch f { case ArchiveAttributeExportIgnore, ArchiveAttributeExportSubst: return nil default: return fmt.Errorf("git archive flag worktree-attributes '%s' is invalid", f) } } type ArchiveParams struct { // Format of the resulting archive. Possible values are tar, zip, tar.gz, tgz, // and any format defined using the configuration option tar.<format>.command // If --format is not given, and the output file is specified, the format is inferred // from the filename if possible (e.g. writing to foo.zip makes the output to be in the zip format), // Otherwise the output format is tar. Format ArchiveFormat // Prefix prepend <prefix>/ to paths in the archive. Can be repeated; its rightmost value is used // for all tracked files. Prefix string // Write the archive to <file> instead of stdout. File string // export-ignore // Files and directories with the attribute export-ignore won’t be added to archive files. // See gitattributes[5] for details. // // export-subst // If the attribute export-subst is set for a file then Git will expand several placeholders // when adding this file to an archive. See gitattributes[5] for details. Attributes ArchiveAttribute // Set modification time of archive entries. Without this option the committer time is // used if <tree-ish> is a commit or tag, and the current time if it is a tree. Time *time.Time // Compression is level used for tar.gz and zip packers. Compression *int // The tree or commit to produce an archive for. Treeish string // Paths is optional parameter, all files and subdirectories of the // current working directory are included in the archive, if one or more paths // are specified, only these are included. Paths []string } func (p *ArchiveParams) Validate() error { if p.Treeish == "" { return errors.InvalidArgument("treeish field cannot be empty") } //nolint:revive if err := p.Format.Validate(); err != nil { return err } return nil } func (g *Git) Archive(ctx context.Context, repoPath string, params ArchiveParams, w io.Writer) error { if err := params.Validate(); err != nil { return err } cmd := command.New("archive", command.WithArg(params.Treeish), ) format := ArchiveFormatTar if params.Format != "" { format = params.Format } cmd.Add(command.WithFlag("--format", string(format))) if params.Prefix != "" { prefix := params.Prefix if !strings.HasSuffix(params.Prefix, "/") { prefix += "/" } cmd.Add(command.WithFlag("--prefix", prefix)) } if params.File != "" { cmd.Add(command.WithFlag("--output", params.File)) } if params.Attributes != "" { if err := params.Attributes.Validate(); err != nil { return err } cmd.Add(command.WithFlag("--worktree-attributes", string(params.Attributes))) } if params.Time != nil { cmd.Add(command.WithFlag("--mtime", fmt.Sprintf("%q", params.Time.Format(time.DateTime)))) } if params.Compression != nil { switch params.Format { case ArchiveFormatZip: // zip accepts values digit 0-9 if *params.Compression < 0 || *params.Compression > 9 { return errors.InvalidArgumentf("compression level argument '%d' not supported for format 'zip'", *params.Compression) } cmd.Add(command.WithArg(fmt.Sprintf("-%d", *params.Compression))) case ArchiveFormatTarGz, ArchiveFormatTgz: // tar.gz accepts number cmd.Add(command.WithArg(fmt.Sprintf("-%d", *params.Compression))) case ArchiveFormatTar: // not usable for tar } } cmd.Add(command.WithArg(params.Paths...)) if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(w)); err != nil { return fmt.Errorf("failed to archive repository: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/pack-objects.go
git/api/pack-objects.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "github.com/harness/gitness/git/command" ) type PackObjectsParams struct { // Pack unreachable loose objects (and their loose counterparts removed). PackLooseUnreachable bool // This flag causes an object that is borrowed from an alternate object // store to be ignored even if it would have otherwise been packed. Local bool // This flag causes an object already in a pack to be ignored even if it // would have otherwise been packed. Incremental bool // Only create a packed archive if it would contain at least one object. NonEmpty bool // Should we show progress Quiet bool } func (g *Git) PackObjects( ctx context.Context, repoPath string, params PackObjectsParams, args ...string, ) error { cmd := command.New("pack-objects") if params.PackLooseUnreachable { cmd.Add(command.WithFlag("--pack-loose-unreachable")) } if params.Local { cmd.Add(command.WithFlag("--local")) } if params.Incremental { cmd.Add(command.WithFlag("--incremental")) } if params.NonEmpty { cmd.Add(command.WithFlag("--non-empty")) } if params.Quiet { cmd.Add(command.WithFlag("--quiet")) } if len(args) > 0 { cmd.Add(command.WithArg(args...)) } if err := cmd.Run(ctx, command.WithDir(repoPath)); err != nil { return processGitErrorf(err, "failed to pack objects") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/errors.go
git/api/errors.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "fmt" "strings" "github.com/harness/gitness/errors" "github.com/rs/zerolog/log" ) var ( ErrInvalidPath = errors.New("path is invalid") ErrRepositoryPathEmpty = errors.InvalidArgument("repository path cannot be empty") ErrBranchNameEmpty = errors.InvalidArgument("branch name cannot be empty") ErrParseDiffHunkHeader = errors.Internal(nil, "failed to parse diff hunk header") ErrNoDefaultBranch = errors.New("no default branch") ErrInvalidSignature = errors.New("invalid signature") ) // PushOutOfDateError represents an error if merging fails due to unrelated histories. type PushOutOfDateError struct { StdOut string StdErr string Err error } func (err *PushOutOfDateError) Error() string { return fmt.Sprintf("PushOutOfDate Error: %v: %s\n%s", err.Err, err.StdErr, err.StdOut) } // Unwrap unwraps the underlying error. func (err *PushOutOfDateError) Unwrap() error { return fmt.Errorf("%w - %s", err.Err, err.StdErr) } // PushRejectedError represents an error if merging fails due to rejection from a hook. type PushRejectedError struct { Message string StdOut string StdErr string Err error } // IsErrPushRejected checks if an error is a PushRejectedError. func IsErrPushRejected(err error) bool { var errPushRejected *PushRejectedError return errors.As(err, &errPushRejected) } func (err *PushRejectedError) Error() string { return fmt.Sprintf("PushRejected Error: %v: %s\n%s", err.Err, err.StdErr, err.StdOut) } // Unwrap unwraps the underlying error. func (err *PushRejectedError) Unwrap() error { return fmt.Errorf("%w - %s", err.Err, err.StdErr) } // GenerateMessage generates the remote message from the stderr. func (err *PushRejectedError) GenerateMessage() { messageBuilder := &strings.Builder{} i := strings.Index(err.StdErr, "remote: ") if i < 0 { err.Message = "" return } for len(err.StdErr) > i+8 { if err.StdErr[i:i+8] != "remote: " { break } i += 8 nl := strings.IndexByte(err.StdErr[i:], '\n') if nl >= 0 { messageBuilder.WriteString(err.StdErr[i : i+nl+1]) i = i + nl + 1 } else { messageBuilder.WriteString(err.StdErr[i:]) i = len(err.StdErr) } } err.Message = strings.TrimSpace(messageBuilder.String()) } // MoreThanOneError represents an error when there are more // than one sources (branch, tag) with the same name. type MoreThanOneError struct { StdOut string StdErr string Err error } // IsErrMoreThanOne checks if an error is a MoreThanOneError. func IsErrMoreThanOne(err error) bool { var errMoreThanOne *MoreThanOneError return errors.As(err, &errMoreThanOne) } func (err *MoreThanOneError) Error() string { return fmt.Sprintf("MoreThanOneError Error: %v: %s\n%s", err.Err, err.StdErr, err.StdOut) } // Logs the error and message, returns either the provided message or a git equivalent if possible. // Always logs the full message with error as warning. // Note: git errors should be processed in command package, this will probably be removed in the future. func processGitErrorf(err error, format string, args ...any) error { // create fallback error returned if we can't map it fallbackErr := errors.Internalf(err, format, args...) // always log internal error together with message. log.Warn().Msgf("%v: [GIT] %v", fallbackErr, err) switch { case strings.Contains(err.Error(), "no such file or directory"): return errors.NotFound("repository not found") case strings.Contains(err.Error(), "reference already exists"): return errors.Conflict("reference already exists") case strings.Contains(err.Error(), "no merge base"): if len(args) >= 2 { return &UnrelatedHistoriesError{ BaseRef: strings.TrimSpace(args[0].(string)), //nolint:errcheck HeadRef: strings.TrimSpace(args[1].(string)), //nolint:errcheck } } return &UnrelatedHistoriesError{} default: return fallbackErr } } type UnrelatedHistoriesError struct { BaseRef string HeadRef string } func (e *UnrelatedHistoriesError) Map() map[string]any { return map[string]any{ "base_ref": e.BaseRef, "head_ref": e.HeadRef, } } func (e *UnrelatedHistoriesError) Is(err error) bool { var target *UnrelatedHistoriesError ok := errors.As(err, &target) if !ok { return false } return target.BaseRef == e.BaseRef && target.HeadRef == e.HeadRef } func (e *UnrelatedHistoriesError) Error() string { if e.BaseRef == "" || e.HeadRef == "" { return "unrelated commit histories error" } // remove branch and tag prefixes, original remains in struct fields // we just need to remove first occurrence. baseRef := strings.TrimPrefix(e.BaseRef, BranchPrefix) baseRef = strings.TrimPrefix(baseRef, TagPrefix) headRef := strings.TrimPrefix(e.HeadRef, BranchPrefix) headRef = strings.TrimPrefix(headRef, TagPrefix) return fmt.Sprintf("%s and %s have entirely different commit histories.", baseRef, headRef) } // IsUnrelatedHistoriesError checks if an error is a UnrelatedHistoriesError. func IsUnrelatedHistoriesError(err error) bool { return AsUnrelatedHistoriesError(err) != nil } func AsUnrelatedHistoriesError(err error) *UnrelatedHistoriesError { var target *UnrelatedHistoriesError ok := errors.As(err, &target) if !ok { return nil } return target }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/config.go
git/api/config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" ) // Config set local git key and value configuration. func (g *Git) Config( ctx context.Context, repoPath string, key string, value string, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } if key == "" { return errors.InvalidArgument("key cannot be empty") } var outbuf, errbuf strings.Builder cmd := command.New("config", command.WithFlag("--local"), command.WithArg(key, value), ) err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(&outbuf), command.WithStderr(&errbuf), ) if err != nil { return fmt.Errorf("git config [%s -> <%s> ]: %w\n%s\n%s", key, value, err, outbuf.String(), errbuf.String()) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/ref_pack.go
git/api/ref_pack.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "github.com/harness/gitness/git/command" ) type PackRefsParams struct { // All option causes all refs to be packed as well, // with the exception of hidden refs, broken refs, and symbolic refs. // Useful for a repository with many branches of historical interests. All bool // NoPrune command usually removes loose refs under $GIT_DIR/refs // hierarchy after packing them. This option tells it not to. NoPrune bool // Auto pack refs as needed depending on the current state of the ref database. // The behavior depends on the ref format used by the repository and may change in the future. Auto bool // Include pack refs based on a glob(7) pattern. Repetitions of this option accumulate inclusion patterns. // If a ref is both included in --include and --exclude, --exclude takes precedence. Include string // Exclude doesn't pack refs matching the given glob(7) pattern. // Repetitions of this option accumulate exclusion patterns. Exclude string } func (g *Git) PackRefs( ctx context.Context, repoPath string, params PackRefsParams, ) error { cmd := command.New("pack-refs") if params.All { cmd.Add(command.WithFlag("--all")) } if params.NoPrune { cmd.Add(command.WithFlag("--no-prune")) } if params.Auto { cmd.Add(command.WithFlag("--auto")) } if params.Include != "" { cmd.Add(command.WithFlag("--include", params.Include)) } if params.Exclude != "" { cmd.Add(command.WithFlag("--exclude", params.Exclude)) } if err := cmd.Run(ctx, command.WithDir(repoPath)); err != nil { return processGitErrorf(err, "failed to pack refs") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/blame_test.go
git/api/blame_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "io" "strings" "testing" "testing/iotest" "time" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/sha" "github.com/google/go-cmp/cmp" ) func TestBlameReader_NextPart(t *testing.T) { // a sample of git blame porcelain output const blameOut = ` 16f267ad4f731af1b2e36f42e170ed8921377398 9 10 1 author Marko author-mail <marko.gacesa@harness.io> author-time 1669812989 author-tz +0100 committer Committer committer-mail <noreply@harness.io> committer-time 1669812989 committer-tz +0100 summary Pull request 1 previous ec84ae5018520efdead481c81a31950b82196ec6 "\"\\n\\123\342\210\206'ex' \\\\t.\\ttxt\"" filename file_name_before_rename.go Line 10 16f267ad4f731af1b2e36f42e170ed8921377398 12 11 1 Line 11 dcb4b6b63e86f06ed4e4c52fbc825545dc0b6200 12 12 1 author Marko author-mail <marko.gacesa@harness.io> author-time 1673952128 author-tz +0100 committer Committer committer-mail <noreply@harness.io> committer-time 1673952128 committer-tz +0100 summary Pull request 2 previous 6561a7b86e1a5e74ea0e4e73ccdfc18b486a2826 file_name.go filename file_name.go Line 12 16f267ad4f731af1b2e36f42e170ed8921377398 13 13 2 Line 13 16f267ad4f731af1b2e36f42e170ed8921377398 14 14 Line 14 ` author := Identity{ Name: "Marko", Email: "marko.gacesa@harness.io", } committer := Identity{ Name: "Committer", Email: "noreply@harness.io", } commit1 := &Commit{ SHA: sha.Must("16f267ad4f731af1b2e36f42e170ed8921377398"), Title: "Pull request 1", Message: "", Author: Signature{ Identity: author, When: time.Unix(1669812989, 0), }, Committer: Signature{ Identity: committer, When: time.Unix(1669812989, 0), }, } previous1 := &BlamePartPrevious{ CommitSHA: sha.Must("ec84ae5018520efdead481c81a31950b82196ec6"), FileName: `"\n\123∆'ex' \\t.\ttxt"`, } commit2 := &Commit{ SHA: sha.Must("dcb4b6b63e86f06ed4e4c52fbc825545dc0b6200"), Title: "Pull request 2", Message: "", Author: Signature{ Identity: author, When: time.Unix(1673952128, 0), }, Committer: Signature{ Identity: committer, When: time.Unix(1673952128, 0), }, } previous2 := &BlamePartPrevious{ CommitSHA: sha.Must("6561a7b86e1a5e74ea0e4e73ccdfc18b486a2826"), FileName: " file_name.go ", } want := []*BlamePart{ { Commit: commit1, Lines: []string{"Line 10", "Line 11"}, Previous: previous1, }, { Commit: commit2, Lines: []string{"Line 12"}, Previous: previous2, }, { Commit: commit1, Lines: []string{"Line 13", "Line 14"}, Previous: previous1, }, } reader := BlameReader{ scanner: bufio.NewScanner(strings.NewReader(blameOut)), cache: make(map[string]blameReaderCacheItem), errReader: strings.NewReader(""), } var got []*BlamePart for { part, err := reader.NextPart() if part != nil { got = append(got, part) } if err != nil { if !errors.Is(err, io.EOF) { t.Errorf("failed with the error: %v", err) } break } } if diff := cmp.Diff(got, want); diff != "" { t.Error(diff) } } func TestBlameReader_NextPart_UserError(t *testing.T) { reader := BlameReader{ scanner: bufio.NewScanner(strings.NewReader("")), cache: make(map[string]blameReaderCacheItem), errReader: strings.NewReader("fatal: no such path\n"), } _, err := reader.NextPart() if s := errors.AsStatus(err); s != errors.StatusNotFound { t.Errorf("expected NotFound error but got: %v", err) } } func TestBlameReader_NextPart_CmdError(t *testing.T) { reader := BlameReader{ scanner: bufio.NewScanner(iotest.ErrReader(errors.New("dummy error"))), cache: make(map[string]blameReaderCacheItem), errReader: strings.NewReader(""), } _, err := reader.NextPart() if s := errors.AsError(err); s.Status != errors.StatusInternal || s.Message != "failed to start git blame command" { t.Errorf("expected %v, but got: %v", s.Message, err) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/util.go
git/api/util.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "unicode" "github.com/yuin/goldmark/util" ) const ( userPlaceholder = "sanitized-credential" ) var schemeSep = []byte("://") // SanitizeCredentialURLs remove all credentials in URLs (starting with "scheme://") // for the input string: "https://user:pass@domain.com" => "https://sanitized-credential@domain.com" func SanitizeCredentialURLs(s string) string { bs := util.StringToReadOnlyBytes(s) schemeSepPos := bytes.Index(bs, schemeSep) if schemeSepPos == -1 || bytes.IndexByte(bs[schemeSepPos:], '@') == -1 { return s // fast return if there is no URL scheme or no userinfo } out := make([]byte, 0, len(bs)+len(userPlaceholder)) for schemeSepPos != -1 { schemeSepPos += 3 // skip the "://" sepAtPos := -1 // the possible '@' position: "https://foo@[^here]host" sepEndPos := schemeSepPos // the possible end position: "The https://host[^here] in log for test" sepLoop: for ; sepEndPos < len(bs); sepEndPos++ { c := bs[sepEndPos] if ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') { continue } switch c { case '@': sepAtPos = sepEndPos case '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '%': continue // due to RFC 3986, userinfo can contain - . _ ~ ! $ & ' ( ) * + , ; = : and any percent-encoded chars default: break sepLoop // if it is an invalid char for URL (eg: space, '/', and others), stop the loop } } // if there is '@', and the string is like "s://u@h", then hide the "u" part if sepAtPos != -1 && (schemeSepPos >= 4 && unicode.IsLetter(rune(bs[schemeSepPos-4]))) && sepAtPos-schemeSepPos > 0 && sepEndPos-sepAtPos > 0 { out = append(out, bs[:schemeSepPos]...) out = append(out, userPlaceholder...) out = append(out, bs[sepAtPos:sepEndPos]...) } else { out = append(out, bs[:sepEndPos]...) } bs = bs[sepEndPos:] schemeSepPos = bytes.Index(bs, schemeSep) } out = append(out, bs...) return util.BytesToReadOnlyString(out) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/commit_graph.go
git/api/commit_graph.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "github.com/harness/gitness/git/command" ) // documentation: https://git-scm.com/docs/git-commit-graph type CommitGraphAction string const ( // CommitGraphActionWrite writes a commit-graph file based on the commits found in packfiles. CommitGraphActionWrite CommitGraphAction = "write" // CommitGraphActionVerify reads the commit-graph file and verify its contents against the object database. // Used to check for corrupted data. CommitGraphActionVerify CommitGraphAction = "verify" ) func (a CommitGraphAction) Validate() error { switch a { case CommitGraphActionWrite, CommitGraphActionVerify: return nil default: return fmt.Errorf("unknown commit graph action: %s", a) } } func (a CommitGraphAction) String() (string, error) { switch a { case CommitGraphActionWrite: return "write", nil case CommitGraphActionVerify: return "verify", nil default: return "", fmt.Errorf("unknown commit graph action: %v", a) } } type CommitGraphSplitOption string const ( // CommitGraphSplitOptionEmpty doesn't exist in git, it is just value // to set --split without value. CommitGraphSplitOptionEmpty CommitGraphSplitOption = "" // CommitGraphSplitOptionReplace overwrites the existing chain with a new one. CommitGraphSplitOptionReplace CommitGraphSplitOption = "replace" ) func (o CommitGraphSplitOption) Validate() error { switch o { case CommitGraphSplitOptionEmpty, CommitGraphSplitOptionReplace: return nil default: return fmt.Errorf("unknown commit graph split option: %s", o) } } type CommitGraphParams struct { // Action represents command in git cli, can be write or verify. Action CommitGraphAction // Reachable option generates the new commit graph by walking commits starting at all refs. Reachable bool // ChangedPaths option computes and write information about the paths changed // between a commit and its first parent. This operation can take a while on large repositories. // It provides significant performance gains for getting history of a directory or // a file with git log -- <path>. ChangedPaths bool // SizeMultiple SizeMultiple int // Split option writes the commit-graph as a chain of multiple commit-graph files // stored in <dir>/info/commit-graphs. Split *CommitGraphSplitOption } func (p CommitGraphParams) Validate() error { if err := p.Action.Validate(); err != nil { return err } if p.Split != nil { if err := p.Split.Validate(); err != nil { return err } } return nil } func (g *Git) CommitGraph( ctx context.Context, repoPath string, params CommitGraphParams, ) error { if err := params.Validate(); err != nil { return err } cmd := command.New("commit-graph") action, err := params.Action.String() if err != nil { return err } cmd.Add(command.WithAction(action)) if params.Reachable { cmd.Add(command.WithFlag("--reachable")) } if params.ChangedPaths { cmd.Add(command.WithFlag("--changed-paths")) } if params.SizeMultiple > 0 { cmd.Add(command.WithFlag(fmt.Sprintf("--size-multiple=%d", params.SizeMultiple))) } if params.Split != nil { if *params.Split == "" { cmd.Add(command.WithFlag("--split")) } else { cmd.Add(command.WithFlag(fmt.Sprintf("--split=%s", *params.Split))) } } if err := cmd.Run(ctx, command.WithDir(repoPath)); err != nil { return processGitErrorf(err, "failed to write commit graph") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/format.go
git/api/format.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api const ( fmtZero = "%x00" fmtCommitHash = "%H" fmtTreeHash = "%T" fmtFieldObjectType = "%(objecttype)" fmtFieldPath = "%(path)" // RFC2822DateFormat is the date format that Git typically uses for dates. RFC2822DateFormat = "Mon Jan 02 2006 15:04:05 -0700" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/files.go
git/api/files.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "path" "strings" ) // CleanUploadFileName Trims a filename and returns empty string if it is a .git directory. func CleanUploadFileName(name string) string { // Rebase the filename name = strings.Trim(path.Clean("/"+name), "/") // Git disallows any filenames to have a .git directory in them. for part := range strings.SplitSeq(name, "/") { if strings.ToLower(part) == ".git" { return "" } } return name }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/repo.go
git/api/repo.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "context" "fmt" "os" "regexp" "strconv" "strings" "time" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" "github.com/rs/zerolog/log" ) type CloneRepoOptions struct { Timeout time.Duration Mirror bool Bare bool Quiet bool Branch string Shared bool NoCheckout bool Depth int Filter string SkipTLSVerify bool } type PushOptions struct { Remote string Branch string Force bool ForceWithLease string Env []string Timeout time.Duration Mirror bool } // ObjectCount represents the parsed information from the `git count-objects -v` command. // For field meanings, see https://git-scm.com/docs/git-count-objects#_options. type ObjectCount struct { Count int Size int64 InPack int Packs int SizePack int64 PrunePackable int Garbage int SizeGarbage int64 } const ( gitReferenceNamePrefixBranch = "refs/heads/" gitReferenceNamePrefixTag = "refs/tags/" ) var lsRemoteHeadRegexp = regexp.MustCompile(`ref: refs/heads/([^\s]+)\s+HEAD`) // InitRepository initializes a new Git repository. func (g *Git) InitRepository( ctx context.Context, repoPath string, bare bool, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } err := os.MkdirAll(repoPath, os.ModePerm) if err != nil { return fmt.Errorf("failed to create directory '%s', err: %w", repoPath, err) } cmd := command.New("init") if bare { cmd.Add(command.WithFlag("--bare")) } return cmd.Run(ctx, command.WithDir(repoPath)) } // SetDefaultBranch sets the default branch of a repo. func (g *Git) SetDefaultBranch( ctx context.Context, repoPath string, defaultBranch string, ignoreBranchExistance bool, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } if !ignoreBranchExistance { // best effort try to check for existence - technically someone else could delete it in the meanwhile. exist, err := g.IsBranchExist(ctx, repoPath, defaultBranch) if err != nil { return fmt.Errorf("failed to check if branch exists: %w", err) } if !exist { return errors.NotFoundf("branch %q does not exist", defaultBranch) } } // change default branch cmd := command.New("symbolic-ref", command.WithArg("HEAD", gitReferenceNamePrefixBranch+defaultBranch), ) err := cmd.Run(ctx, command.WithDir(repoPath)) if err != nil { return processGitErrorf(err, "failed to set new default branch") } return nil } // GetDefaultBranch gets the default branch of a repo. func (g *Git) GetDefaultBranch( ctx context.Context, repoPath string, ) (string, error) { rawBranchRef, err := g.GetSymbolicRefHeadRaw(ctx, repoPath) if err != nil { return "", fmt.Errorf("failed to get raw symbolic ref HEAD: %w", err) } branchName := strings.TrimPrefix( strings.TrimSpace( rawBranchRef, ), BranchPrefix, ) return branchName, nil } // GetSymbolicRefHeadRaw returns the raw output of the symolic-ref command for HEAD. func (g *Git) GetSymbolicRefHeadRaw( ctx context.Context, repoPath string, ) (string, error) { if repoPath == "" { return "", ErrRepositoryPathEmpty } // get default branch cmd := command.New("symbolic-ref", command.WithArg("HEAD"), ) output := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)) if err != nil { return "", processGitErrorf(err, "failed to get value of symbolic ref HEAD from git") } return output.String(), nil } // GetRemoteDefaultBranch retrieves the default branch of a remote repository. // If the repo doesn't have a default branch, types.ErrNoDefaultBranch is returned. func (g *Git) GetRemoteDefaultBranch( ctx context.Context, remoteURL string, ) (string, error) { cmd := command.New("ls-remote", command.WithConfig("credential.helper", ""), command.WithFlag("--symref"), command.WithFlag("-q"), command.WithArg(remoteURL), command.WithArg("HEAD"), ) output := &bytes.Buffer{} if err := cmd.Run(ctx, command.WithStdout(output)); err != nil { return "", processGitErrorf(err, "failed to ls remote repo") } // git output looks as follows, and we are looking for the ref that HEAD points to // ref: refs/heads/main HEAD // 46963bc7f0b5e8c5f039d50ac9e6e51933c78cdf HEAD match := lsRemoteHeadRegexp.FindStringSubmatch(strings.TrimSpace(output.String())) if match == nil { return "", ErrNoDefaultBranch } return match[1], nil } func (g *Git) Clone( ctx context.Context, from string, to string, opts CloneRepoOptions, ) error { if err := os.MkdirAll(to, os.ModePerm); err != nil { return err } cmd := command.New("clone") if opts.SkipTLSVerify { cmd.Add(command.WithConfig("http.sslVerify", "false")) } if opts.Mirror { cmd.Add(command.WithFlag("--mirror")) } if opts.Bare { cmd.Add(command.WithFlag("--bare")) } if opts.Quiet { cmd.Add(command.WithFlag("--quiet")) } if opts.Shared { cmd.Add(command.WithFlag("-s")) } if opts.NoCheckout { cmd.Add(command.WithFlag("--no-checkout")) } if opts.Depth > 0 { cmd.Add(command.WithFlag("--depth", strconv.Itoa(opts.Depth))) } if opts.Filter != "" { cmd.Add(command.WithFlag("--filter", opts.Filter)) } if len(opts.Branch) > 0 { cmd.Add(command.WithFlag("-b", opts.Branch)) } cmd.Add(command.WithPostSepArg(from, to)) if err := cmd.Run(ctx); err != nil { return fmt.Errorf("failed to clone repository: %w", err) } return nil } // Sync synchronizes the repository to match the provided source. // NOTE: This is a read operation and doesn't trigger any server side hooks. func (g *Git) Sync( ctx context.Context, repoPath string, source string, refSpecs []string, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } if len(refSpecs) == 0 { refSpecs = []string{"+refs/*:refs/*"} } cmd := command.New("fetch", command.WithConfig("advice.fetchShowForcedUpdates", "false"), command.WithConfig("credential.helper", ""), command.WithFlag( "--quiet", "--prune", "--atomic", "--force", "--no-write-fetch-head", "--no-show-forced-updates", ), command.WithArg(source), command.WithArg(refSpecs...), ) err := cmd.Run(ctx, command.WithDir(repoPath)) if err != nil { return processGitErrorf(err, "failed to sync repo") } return nil } // FetchObjects pull git objects from a different repository. // It doesn't update any references. func (g *Git) FetchObjects( ctx context.Context, repoPath string, source string, objectSHAs []sha.SHA, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } cmd := command.New("fetch", command.WithConfig("advice.fetchShowForcedUpdates", "false"), command.WithConfig("credential.helper", ""), command.WithFlag( "--quiet", "--no-auto-gc", // because we're fetching objects that are not referenced "--no-tags", "--no-write-fetch-head", "--no-show-forced-updates", ), command.WithArg(source), ) for _, objectSHA := range objectSHAs { cmd.Add(command.WithArg(objectSHA.String())) } err := cmd.Run(ctx, command.WithDir(repoPath)) if err != nil { if parts := reNotOurRef.FindStringSubmatch(strings.TrimSpace(err.Error())); parts != nil { return errors.InvalidArgumentf("Unrecognized git object: %s", parts[1]) } return processGitErrorf(err, "failed to fetch objects") } return nil } // ListRemoteReferences lists references from a remote repository. func (g *Git) ListRemoteReferences( ctx context.Context, repoPath string, remote string, refs ...string, ) (map[string]sha.SHA, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } cmd := command.New("ls-remote", command.WithFlag("--refs"), command.WithArg(remote), command.WithPostSepArg(refs...), ) stdout := bytes.NewBuffer(nil) if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout)); err != nil { return nil, fmt.Errorf("failed to list references from remote: %w", err) } result, err := parser.ReferenceList(stdout) if err != nil { return nil, fmt.Errorf("failed to parse references from remote: %w", err) } return result, nil } // ListLocalReferences lists references from the local repository. func (g *Git) ListLocalReferences( ctx context.Context, repoPath string, refs ...string, ) (map[string]sha.SHA, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } cmd := command.New("show-ref", command.WithPostSepArg(refs...), ) stdout := bytes.NewBuffer(nil) if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout)); err != nil { return nil, fmt.Errorf("failed to list references: %w", err) } result, err := parser.ReferenceList(stdout) if err != nil { return nil, fmt.Errorf("failed to parse references: %w", err) } return result, nil } var reNotOurRef = regexp.MustCompile("upload-pack: not our ref ([a-fA-f0-9]+)$") func (g *Git) AddFiles( ctx context.Context, repoPath string, all bool, files ...string, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } cmd := command.New("add") if all { cmd.Add(command.WithFlag("--all")) } cmd.Add(command.WithPostSepArg(files...)) err := cmd.Run(ctx, command.WithDir(repoPath)) if err != nil { return processGitErrorf(err, "failed to add changes") } return nil } // Commit commits the changes of the repository. func (g *Git) Commit( ctx context.Context, repoPath string, opts CommitChangesOptions, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } cmd := command.New("commit", command.WithFlag("-m", opts.Message), command.WithAuthorAndDate( opts.Author.Identity.Name, opts.Author.Identity.Email, opts.Author.When, ), command.WithCommitterAndDate( opts.Committer.Identity.Name, opts.Committer.Identity.Email, opts.Committer.When, ), ) err := cmd.Run(ctx, command.WithDir(repoPath)) // No stderr but exit status 1 means nothing to commit (see gitea CommitChanges) if err != nil && err.Error() != "exit status 1" { return processGitErrorf(err, "failed to commit changes") } return nil } // Push pushs local commits to given remote branch. // TODOD: return our own error types and move to above api.Push method. func (g *Git) Push( ctx context.Context, repoPath string, opts PushOptions, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } cmd := command.New("push", command.WithConfig("credential.helper", ""), ) if opts.Force { cmd.Add(command.WithFlag("-f")) } if opts.ForceWithLease != "" { cmd.Add(command.WithFlag("--force-with-lease=" + opts.ForceWithLease)) } if opts.Mirror { cmd.Add(command.WithFlag("--mirror")) } cmd.Add(command.WithPostSepArg(opts.Remote)) if len(opts.Branch) > 0 { cmd.Add(command.WithPostSepArg(opts.Branch)) } if g.traceGit { cmd.Add(command.WithEnv(command.GitTrace, "true")) } // remove credentials if there are any if strings.Contains(opts.Remote, "://") && strings.Contains(opts.Remote, "@") { opts.Remote = SanitizeCredentialURLs(opts.Remote) } var outbuf, errbuf strings.Builder err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(&outbuf), command.WithStderr(&errbuf), command.WithEnvs(opts.Env...), ) if g.traceGit { log.Ctx(ctx).Trace(). Str("git", "push"). Err(err). Msgf("IN:\n%#v\n\nSTDOUT:\n%s\n\nSTDERR:\n%s", opts, outbuf.String(), errbuf.String()) } if err != nil { switch { case strings.Contains(errbuf.String(), "non-fast-forward"): return &PushOutOfDateError{ StdOut: outbuf.String(), StdErr: errbuf.String(), Err: err, } case strings.Contains(errbuf.String(), "! [remote rejected]"): err := &PushRejectedError{ StdOut: outbuf.String(), StdErr: errbuf.String(), Err: err, } err.GenerateMessage() return err case strings.Contains(errbuf.String(), "matches more than one"): err := &MoreThanOneError{ StdOut: outbuf.String(), StdErr: errbuf.String(), Err: err, } return err default: // fall through to normal error handling } } if err != nil { // add commandline error output to error if errbuf.Len() > 0 { err = fmt.Errorf("%w\ncmd error output: %s", err, errbuf.String()) } return processGitErrorf(err, "failed to push changes") } return nil } func (g *Git) CountObjects(ctx context.Context, repoPath string) (ObjectCount, error) { var outbuf strings.Builder cmd := command.New("count-objects", command.WithFlag("-v")) err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(&outbuf), ) if err != nil { return ObjectCount{}, fmt.Errorf("error running git count-objects: %w", err) } objectCount := parseGitCountObjectsOutput(ctx, outbuf.String()) return objectCount, nil } //nolint:errcheck func parseGitCountObjectsOutput(ctx context.Context, output string) ObjectCount { info := ObjectCount{} output = strings.TrimSpace(output) lines := strings.SplitSeq(output, "\n") for line := range lines { fields := strings.Fields(line) switch fields[0] { case "count:": fmt.Sscanf(fields[1], "%d", &info.Count) //nolint:errcheck case "size:": fmt.Sscanf(fields[1], "%d", &info.Size) //nolint:errcheck case "in-pack:": fmt.Sscanf(fields[1], "%d", &info.InPack) //nolint:errcheck case "packs:": fmt.Sscanf(fields[1], "%d", &info.Packs) //nolint:errcheck case "size-pack:": fmt.Sscanf(fields[1], "%d", &info.SizePack) //nolint:errcheck case "prune-packable:": fmt.Sscanf(fields[1], "%d", &info.PrunePackable) //nolint:errcheck case "garbage:": fmt.Sscanf(fields[1], "%d", &info.Garbage) //nolint:errcheck case "size-garbage:": fmt.Sscanf(fields[1], "%d", &info.SizeGarbage) default: log.Ctx(ctx).Warn().Msgf("line '%s: %s' not processed", fields[0], fields[1]) } } return info }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/tag.go
git/api/tag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "io" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) type Tag struct { Sha sha.SHA Name string TargetSHA sha.SHA TargetType GitObjectType Title string Message string Tagger Signature SignedData *SignedData } type CreateTagOptions struct { // Message is the optional message the tag will be created with - if the message is empty // the tag will be lightweight, otherwise it'll be annotated. Message string // Tagger is the information used in case the tag is annotated (Message is provided). Tagger Signature } // TagPrefix tags prefix path on the repository. const TagPrefix = "refs/tags/" // GetAnnotatedTag returns the tag for a specific tag sha. func (g *Git) GetAnnotatedTag( ctx context.Context, repoPath string, rev string, ) (*Tag, error) { return CatFileAnnotatedTag(ctx, repoPath, nil, rev) } // GetAnnotatedTags returns the tags for a specific list of tag sha. func (g *Git) GetAnnotatedTags( ctx context.Context, repoPath string, tagSHAs []sha.SHA, ) ([]Tag, error) { return CatFileAnnotatedTagFromSHAs(ctx, repoPath, nil, tagSHAs) } // CreateTag creates the tag pointing at the provided SHA (could be any type, e.g. commit, tag, blob, ...) func (g *Git) CreateTag( ctx context.Context, repoPath string, name string, targetSHA sha.SHA, opts *CreateTagOptions, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } cmd := command.New("tag") if opts != nil && opts.Message != "" { cmd.Add(command.WithFlag("-m", opts.Message)) cmd.Add( command.WithCommitterAndDate( opts.Tagger.Identity.Name, opts.Tagger.Identity.Email, opts.Tagger.When, ), ) } cmd.Add(command.WithArg(name, targetSHA.String())) err := cmd.Run(ctx, command.WithDir(repoPath)) if err != nil { return processGitErrorf(err, "Service failed to create a tag") } return nil } func (g *Git) GetTagCount( ctx context.Context, repoPath string, ) (int, error) { if repoPath == "" { return 0, ErrRepositoryPathEmpty } pipeOut, pipeIn := io.Pipe() defer pipeOut.Close() cmd := command.New("tag") go func() { err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeIn)) if err != nil { _ = pipeIn.CloseWithError( processGitErrorf(err, "failed to trigger tag command"), ) return } _ = pipeIn.Close() }() return countLines(pipeOut) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/diff.go
git/api/diff.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "bytes" "context" "fmt" "io" "math" "regexp" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/parser" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" ) type FileDiffRequest struct { Path string `json:"path"` StartLine int `json:"start_line"` EndLine int `json:"-"` // warning: changes are possible and this field may not exist in the future } type FileDiffRequests []FileDiffRequest type DiffShortStat struct { Files int Additions int Deletions int } // modifyHeader needs to modify diff hunk header with the new start line // and end line with calculated span. // if diff hunk header is -100, 50 +100, 50 and startLine = 120, endLine=140 // then we need to modify header to -120,20 +120,20. // warning: changes are possible and param endLine may not exist in the future. func modifyHeader(hunk parser.HunkHeader, startLine, endLine int) []byte { oldStartLine := hunk.OldLine newStartLine := hunk.NewLine oldSpan := hunk.OldSpan newSpan := hunk.NewSpan oldEndLine := oldStartLine + oldSpan newEndLine := newStartLine + newSpan if startLine > 0 { if startLine < oldEndLine { oldStartLine = startLine } if startLine < newEndLine { newStartLine = startLine } } if endLine > 0 { if endLine < oldEndLine { oldSpan = endLine - startLine } else if oldEndLine > startLine { oldSpan = oldEndLine - startLine } if endLine < newEndLine { newSpan = endLine - startLine } else if newEndLine > startLine { newSpan = newEndLine - startLine } } return fmt.Appendf(nil, "@@ -%d,%d +%d,%d @@", oldStartLine, oldSpan, newStartLine, newSpan) } // cutLinesFromFullFileDiff reads from r and writes to w headers and between // startLine and endLine. if startLine and endLine is equal to 0 then it uses io.Copy // warning: changes are possible and param endLine may not exist in the future // //nolint:gocognit func cutLinesFromFullFileDiff(w io.Writer, r io.Reader, startLine, endLine int) error { if startLine < 0 { startLine = 0 } if endLine < 0 { endLine = 0 } if startLine == 0 && endLine > 0 { startLine = 1 } if endLine < startLine { endLine = 0 } // no need for processing lines just copy the data if startLine == 0 && endLine == 0 { _, err := io.Copy(w, r) return err } linePos := 0 start := false scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Bytes() if start { linePos++ } if endLine > 0 && linePos > endLine { break } if linePos > 0 && (startLine > 0 && linePos < startLine) { continue } if len(line) >= 2 && bytes.HasPrefix(line, []byte{'@', '@'}) { hunk, ok := parser.ParseDiffHunkHeader(string(line)) // TBD: maybe reader? if !ok { return fmt.Errorf("failed to extract lines from diff, range [%d,%d] : %w", startLine, endLine, ErrParseDiffHunkHeader) } line = modifyHeader(hunk, startLine, endLine) start = true } if _, err := w.Write(line); err != nil { return err } if _, err := w.Write([]byte{'\n'}); err != nil { return err } } return scanner.Err() } //nolint:gocognit func (g *Git) RawDiff( ctx context.Context, w io.Writer, repoPath string, baseRef string, headRef string, mergeBase bool, ignoreWhitespace bool, alternates []string, files ...FileDiffRequest, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } baseTag, err := g.GetAnnotatedTag(ctx, repoPath, baseRef) if err == nil { baseRef = baseTag.TargetSHA.String() } headTag, err := g.GetAnnotatedTag(ctx, repoPath, headRef) if err == nil { headRef = headTag.TargetSHA.String() } if mergeBase { mergeBaseSHA, _, err := g.GetMergeBase(ctx, repoPath, "", baseRef, headRef, true) if err != nil { return fmt.Errorf("failed to get merge base for %s and %s: %w", baseRef, headRef, err) } baseRef = mergeBaseSHA.String() } cmd := command.New("diff", command.WithFlag("-M"), command.WithFlag("--full-index"), command.WithAlternateObjectDirs(alternates...), ) if ignoreWhitespace { // Ignore whitespace when comparing lines. cmd.Add(command.WithFlag("-w")) } perFileDiffRequired := false paths := make([]string, 0, len(files)) if len(files) > 0 { for _, file := range files { paths = append(paths, file.Path) if file.StartLine > 0 || file.EndLine > 0 { perFileDiffRequired = true } } } processed := 0 again: startLine := 0 endLine := 0 newCmd := cmd.Clone() if len(files) > 0 { startLine = files[processed].StartLine endLine = files[processed].EndLine } if perFileDiffRequired { if startLine > 0 || endLine > 0 { newCmd.Add(command.WithFlag("-U" + strconv.Itoa(math.MaxInt32))) } paths = []string{files[processed].Path} } newCmd.Add(command.WithArg(baseRef, headRef)) if len(paths) > 0 { newCmd.Add(command.WithPostSepArg(paths...)) } pipeRead, pipeWrite := io.Pipe() go func() { var err error defer func() { // If running of the command below fails, make the pipe reader also fail with the same error. _ = pipeWrite.CloseWithError(err) }() err = newCmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite)) if err != nil { err = processGitErrorf(err, "git diff failed between %q and %q", baseRef, headRef) if cErr := command.AsError(err); cErr != nil { if cErr.IsExitCode(128) && cErr.IsBadObject() { err = errors.NotFound("commit not found") } } } }() if err = cutLinesFromFullFileDiff(w, pipeRead, startLine, endLine); err != nil { return err } if perFileDiffRequired { processed++ if processed < len(files) { goto again } } return nil } // CommitDiff will stream diff for provided ref. func (g *Git) CommitDiff( ctx context.Context, repoPath string, rev string, ignoreWhitespace bool, w io.Writer, ) error { if repoPath == "" { return ErrRepositoryPathEmpty } if rev == "" { return errors.InvalidArgument("git revision cannot be empty") } cmd := command.New("show", command.WithFlag("--full-index"), command.WithFlag("--pretty=format:%b"), command.WithArg(rev), ) if ignoreWhitespace { // Ignore whitespace when comparing lines. cmd.Add(command.WithFlag("-w")) } if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(w), ); err != nil { return processGitErrorf(err, "commit diff error") } return nil } func (g *Git) DiffShortStat( ctx context.Context, repoPath string, baseRef string, headRef string, useMergeBase bool, ignoreWhitespace bool, ) (DiffShortStat, error) { if repoPath == "" { return DiffShortStat{}, ErrRepositoryPathEmpty } separator := ".." if useMergeBase { separator = "..." } shortstatArgs := []string{baseRef + separator + headRef} if len(baseRef) == 0 || baseRef == types.NilSHA { shortstatArgs = []string{sha.EmptyTree.String(), headRef} } stat, err := GetDiffShortStat(ctx, repoPath, ignoreWhitespace, shortstatArgs...) if err != nil { return DiffShortStat{}, processGitErrorf(err, "failed to get diff short stat between %s and %s", baseRef, headRef) } return stat, nil } // GetDiffHunkHeaders for each file in diff output returns file name (old and new to detect renames), // and all hunk headers. The diffs are generated with unified=0 parameter to create minimum sized hunks. // Hunks' body is ignored. // The purpose of this function is to get data based on which code comments could be repositioned. func (g *Git) GetDiffHunkHeaders( ctx context.Context, repoPath string, targetRef string, sourceRef string, ) ([]*parser.DiffFileHunkHeaders, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } pipeRead, pipeWrite := io.Pipe() stderr := &bytes.Buffer{} go func() { var err error defer func() { // If running of the command below fails, make the pipe reader also fail with the same error. _ = pipeWrite.CloseWithError(err) }() cmd := command.New("diff", command.WithFlag("--patch"), command.WithFlag("--full-index"), command.WithFlag("--no-color"), command.WithFlag("--unified=0"), command.WithArg(sourceRef), command.WithArg(targetRef), ) err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite), command.WithStderr(stderr), // We capture stderr output in a buffer. ) }() fileHunkHeaders, err := parser.GetHunkHeaders(pipeRead) // First check if there's something in the stderr buffer, if yes that's the error if errStderr := parseDiffStderr(stderr); errStderr != nil { return nil, errStderr } // Next check if reading the git diff output caused an error if err != nil { return nil, err } return fileHunkHeaders, nil } // DiffCut parses full file git diff output and returns lines specified with the parameters. // The purpose of this function is to get diff data with which code comments could be generated. // //nolint:gocognit func (g *Git) DiffCut( ctx context.Context, repoPath string, targetRef string, sourceRef string, path string, ignoreWhitespace bool, params parser.DiffCutParams, ) (parser.HunkHeader, parser.Hunk, error) { if repoPath == "" { return parser.HunkHeader{}, parser.Hunk{}, ErrRepositoryPathEmpty } // first fetch the list of the changed files pipeRead, pipeWrite := io.Pipe() go func() { var err error defer func() { // If running of the command below fails, make the pipe reader also fail with the same error. _ = pipeWrite.CloseWithError(err) }() cmd := command.New("diff", command.WithFlag("--raw"), command.WithFlag("--merge-base"), command.WithFlag("-z"), command.WithFlag("--find-renames"), command.WithArg(targetRef), command.WithArg(sourceRef)) if ignoreWhitespace { // Ignore whitespace when comparing lines. cmd.Add(command.WithFlag("-w")) } err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite)) }() diffEntries, err := parser.DiffRaw(pipeRead) if err != nil { return parser.HunkHeader{}, parser.Hunk{}, fmt.Errorf("failed to find the list of changed files: %w", err) } var oldSHA, newSHA string for _, entry := range diffEntries { if entry.Status == parser.DiffStatusRenamed || entry.Status == parser.DiffStatusCopied { // Entries with the status 'R' and 'C' output two paths: the old path and the new path. // Using the params.LineStartNew flag to match the path with the entry's old or new path. if entry.Path != path && entry.OldPath != path { continue } if params.LineStartNew && path == entry.OldPath { msg := "for renamed files provide the new file name if commenting the changed lines" return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg) } if !params.LineStartNew && path == entry.Path { msg := "for renamed files provide the old file name if commenting the old lines" return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg) } } else if entry.Path != path { // All other statuses output just one path: If the path doesn't match it, proceed with the next entry. continue } rawFileMode := entry.OldFileMode if params.LineStartNew { rawFileMode = entry.NewFileMode } fileType, _, err := parseTreeNodeMode(rawFileMode) if err != nil { return parser.HunkHeader{}, parser.Hunk{}, fmt.Errorf("failed to parse file mode %s for path %s: %w", rawFileMode, path, err) } switch fileType { default: return parser.HunkHeader{}, parser.Hunk{}, errors.Internal(nil, "unrecognized object type") case TreeNodeTypeCommit: msg := "code comment is not allowed on a submodule" return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg) case TreeNodeTypeTree: msg := "code comment is not allowed on a directory" return parser.HunkHeader{}, parser.Hunk{}, errors.InvalidArgument(msg) case TreeNodeTypeBlob: // a blob is what we want } var hunkHeader parser.HunkHeader var hunk parser.Hunk switch entry.Status { case parser.DiffStatusRenamed, parser.DiffStatusCopied, parser.DiffStatusModified: // For modified and renamed compare file blob SHAs directly. oldSHA = entry.OldBlobSHA newSHA = entry.NewBlobSHA hunkHeader, hunk, err = g.diffCutFromHunk(ctx, repoPath, oldSHA, newSHA, ignoreWhitespace, params) case parser.DiffStatusAdded, parser.DiffStatusDeleted, parser.DiffStatusType: // for added and deleted files read the file content directly if params.LineStartNew { hunkHeader, hunk, err = g.diffCutFromBlob(ctx, repoPath, true, entry.NewBlobSHA, params) } else { hunkHeader, hunk, err = g.diffCutFromBlob(ctx, repoPath, false, entry.OldBlobSHA, params) } default: return parser.HunkHeader{}, parser.Hunk{}, fmt.Errorf("unrecognized git diff file status=%c for path=%s", entry.Status, path) } if err != nil { return parser.HunkHeader{}, parser.Hunk{}, fmt.Errorf("failed to extract hunk for git diff file status=%c path=%s: %w", entry.Status, path, err) } // The returned diff hunk will be stored in the DB and will only be used for display, as a reference. // Therefore, we trim too long lines to protect the system and the DB. const maxLineLen = 200 parser.LimitLineLen(&hunk.Lines, maxLineLen) return hunkHeader, hunk, nil } return parser.HunkHeader{}, parser.Hunk{}, errors.NotFound("path not found") } func (g *Git) diffCutFromHunk( ctx context.Context, repoPath string, oldSHA string, newSHA string, ignoreWhitespace bool, params parser.DiffCutParams, ) (parser.HunkHeader, parser.Hunk, error) { pipeRead, pipeWrite := io.Pipe() stderr := bytes.NewBuffer(nil) go func() { var err error defer func() { // If running of the command below fails, make the pipe reader also fail with the same error. _ = pipeWrite.CloseWithError(err) }() cmd := command.New("diff", command.WithFlag("--patch"), command.WithFlag("--full-index"), command.WithFlag("--no-color"), command.WithFlag("--unified=100000000"), command.WithArg(oldSHA), command.WithArg(newSHA)) if ignoreWhitespace { // Ignore whitespace when comparing lines. cmd.Add(command.WithFlag("-w")) } err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite), command.WithStderr(stderr)) }() diffCutHeader, linesHunk, err := parser.DiffCut(pipeRead, params) if errStderr := parseDiffStderr(stderr); errStderr != nil { // First check if there's something in the stderr buffer, if yes that's the error return parser.HunkHeader{}, parser.Hunk{}, errStderr } if err != nil { // Next check if reading the git diff output caused an error return parser.HunkHeader{}, parser.Hunk{}, err } return diffCutHeader, linesHunk, nil } func (g *Git) diffCutFromBlob( ctx context.Context, repoPath string, asAdded bool, sha string, params parser.DiffCutParams, ) (parser.HunkHeader, parser.Hunk, error) { pipeRead, pipeWrite := io.Pipe() go func() { var err error defer func() { // If running of the command below fails, make the pipe reader also fail with the same error. _ = pipeWrite.CloseWithError(err) }() cmd := command.New("cat-file", command.WithFlag("-p"), command.WithArg(sha)) err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeWrite)) }() cutHeader, cut, err := parser.BlobCut(pipeRead, params) if err != nil { // Next check if reading the git diff output caused an error return parser.HunkHeader{}, parser.Hunk{}, err } // Convert parser.CutHeader to parser.HunkHeader and parser.Cut to parser.Hunk. var hunkHeader parser.HunkHeader var hunk parser.Hunk if asAdded { for i := range cut.Lines { cut.Lines[i] = "+" + cut.Lines[i] } hunkHeader = parser.HunkHeader{ NewLine: cutHeader.Line, NewSpan: cutHeader.Span, } hunk = parser.Hunk{ HunkHeader: parser.HunkHeader{NewLine: cut.Line, NewSpan: cut.Span}, Lines: cut.Lines, } } else { for i := range cut.Lines { cut.Lines[i] = "-" + cut.Lines[i] } hunkHeader = parser.HunkHeader{ OldLine: cutHeader.Line, OldSpan: cutHeader.Span, } hunk = parser.Hunk{ HunkHeader: parser.HunkHeader{OldLine: cut.Line, OldSpan: cut.Span}, Lines: cut.Lines, } } return hunkHeader, hunk, nil } func (g *Git) DiffFileName(ctx context.Context, repoPath string, baseRef string, headRef string, mergeBase bool, ignoreWhitespace bool, ) ([]string, error) { cmd := command.New("diff", command.WithFlag("--name-only")) if mergeBase { cmd.Add(command.WithFlag("--merge-base")) } cmd.Add(command.WithArg(baseRef, headRef)) if ignoreWhitespace { // Ignore whitespace when comparing lines. cmd.Add(command.WithFlag("-w")) } stdout := &bytes.Buffer{} err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout), ) if err != nil { return nil, processGitErrorf(err, "failed to trigger diff command") } return parseLinesToSlice(stdout.Bytes()), nil } // GetDiffShortStat counts number of changed files, number of additions and deletions. func GetDiffShortStat( ctx context.Context, repoPath string, ignoreWhitespace bool, args ...string, ) (DiffShortStat, error) { // Now if we call: // $ git diff --shortstat 1ebb35b98889ff77299f24d82da426b434b0cca0...788b8b1440462d477f45b0088875 // we get: // " 9902 files changed, 2034198 insertions(+), 298800 deletions(-)\n" cmd := command.New("diff", command.WithFlag("--shortstat"), command.WithArg(args...), ) if ignoreWhitespace { // Ignore whitespace when comparing lines. cmd.Add(command.WithFlag("-w")) } stdout := &bytes.Buffer{} if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout), ); err != nil { return DiffShortStat{}, err } return parseDiffStat(stdout.String()) } var shortStatFormat = regexp.MustCompile( `\s*(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?`) func parseDiffStat(stdout string) (stat DiffShortStat, err error) { if len(stdout) == 0 || stdout == "\n" { return DiffShortStat{}, nil } groups := shortStatFormat.FindStringSubmatch(stdout) if len(groups) != 4 { return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s groups: %s", stdout, groups) } stat.Files, err = strconv.Atoi(groups[1]) if err != nil { return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s. Error parsing NumFiles %w", stdout, err) } if len(groups[2]) != 0 { stat.Additions, err = strconv.Atoi(groups[2]) if err != nil { return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s. Error parsing NumAdditions %w", stdout, err) } } if len(groups[3]) != 0 { stat.Deletions, err = strconv.Atoi(groups[3]) if err != nil { return DiffShortStat{}, fmt.Errorf("unable to parse shortstat: %s. Error parsing NumDeletions %w", stdout, err) } } return stat, nil } func parseDiffStderr(stderr *bytes.Buffer) error { errRaw := stderr.String() // assume there will never be a lot of output to stdout if len(errRaw) == 0 { return nil } if idx := strings.IndexByte(errRaw, '\n'); idx > 0 { errRaw = errRaw[:idx] // get only the first line of the output } errRaw = strings.TrimPrefix(errRaw, "fatal: ") // git errors start with the "fatal: " prefix if strings.Contains(errRaw, "bad revision") { return parser.ErrSHADoesNotMatch } return errors.New(errRaw) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/paths_details.go
git/api/paths_details.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" ) type PathDetails struct { Path string LastCommit *Commit } // PathsDetails returns additional details about provided the paths. func (g *Git) PathsDetails(ctx context.Context, repoPath string, rev string, paths []string, ) ([]PathDetails, error) { // resolve the git revision to the commit SHA - we need the commit SHA for the last commit hash entry key. commitSHA, err := g.ResolveRev(ctx, repoPath, rev) if err != nil { return nil, fmt.Errorf("failed to get path details: %w", err) } results := make([]PathDetails, len(paths)) for i, path := range paths { results[i].Path = path path = cleanTreePath(path) // use cleaned-up path for calculations to avoid not-founds. commitEntry, err := g.lastCommitCache.Get(ctx, makeCommitEntryKey(repoPath, commitSHA, path)) if err != nil { return nil, fmt.Errorf("failed to find last commit for path %s: %w", path, err) } results[i].LastCommit = commitEntry } return results, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/signed_data.go
git/api/signed_data.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api // SignedData represents a git signature part. type SignedData struct { Type string Signature []byte SignedContent []byte }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/match_files.go
git/api/match_files.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "io" "path" ) type FileContent struct { Path string Content []byte } //nolint:gocognit func (g *Git) MatchFiles( ctx context.Context, repoPath string, rev string, treePath string, pattern string, maxSize int, ) ([]FileContent, error) { nodes, err := lsDirectory(ctx, repoPath, rev, treePath, false, false, false) if err != nil { return nil, fmt.Errorf("failed to list files in match files: %w", err) } catFileWriter, catFileReader, catFileStop := CatFileBatch(ctx, repoPath, nil) defer catFileStop() var files []FileContent for i := range nodes { if nodes[i].NodeType != TreeNodeTypeBlob { continue } fileName := nodes[i].Name ok, err := path.Match(pattern, fileName) if err != nil { return nil, fmt.Errorf("failed to match file name against pattern: %w", err) } if !ok { continue } _, err = catFileWriter.Write([]byte(nodes[i].SHA.String() + "\n")) if err != nil { return nil, fmt.Errorf("failed to ask for file content from cat file batch: %w", err) } output, err := ReadBatchHeaderLine(catFileReader) if err != nil { return nil, fmt.Errorf("failed to read cat-file batch header: %w", err) } reader := io.LimitReader(catFileReader, output.Size+1) // plus eol if output.Size > int64(maxSize) { _, err = io.Copy(io.Discard, reader) if err != nil { return nil, fmt.Errorf("failed to discard a large file: %w", err) } } data, err := io.ReadAll(reader) if err != nil { return nil, fmt.Errorf("failed to read cat-file content: %w", err) } if len(data) > 0 { data = data[:len(data)-1] } if len(data) == 0 { continue } files = append(files, FileContent{ Path: nodes[i].Path, Content: data, }) } _ = catFileWriter.Close() return files, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/object.go
git/api/object.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "context" "fmt" "io" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) type GitObjectType string const ( GitObjectTypeCommit GitObjectType = "commit" GitObjectTypeTree GitObjectType = "tree" GitObjectTypeBlob GitObjectType = "blob" GitObjectTypeTag GitObjectType = "tag" ) func ParseGitObjectType(t string) (GitObjectType, error) { switch t { case string(GitObjectTypeCommit): return GitObjectTypeCommit, nil case string(GitObjectTypeBlob): return GitObjectTypeBlob, nil case string(GitObjectTypeTree): return GitObjectTypeTree, nil case string(GitObjectTypeTag): return GitObjectTypeTag, nil default: return GitObjectTypeBlob, fmt.Errorf("unknown git object type '%s'", t) } } type SortOrder int const ( SortOrderDefault SortOrder = iota SortOrderAsc SortOrderDesc ) func (g *Git) HashObject(ctx context.Context, repoPath string, reader io.Reader) (sha.SHA, error) { cmd := command.New("hash-object", command.WithFlag("-w"), command.WithFlag("--stdin"), ) stdout := new(bytes.Buffer) err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdin(reader), command.WithStdout(stdout), ) if err != nil { return sha.None, fmt.Errorf("failed to hash object: %w", err) } return sha.New(stdout.String()) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/branch.go
git/api/branch.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "bytes" "context" "fmt" "io" "strings" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" ) type Branch struct { Name string SHA sha.SHA Commit *Commit } type BranchFilter struct { Query string Page int32 PageSize int32 Sort GitReferenceField Order SortOrder IncludeCommit bool } // BranchPrefix base dir of the branch information file store on git. const BranchPrefix = "refs/heads/" // EnsureBranchPrefix ensures the ref always has "refs/heads/" as prefix. func EnsureBranchPrefix(ref string) string { if !strings.HasPrefix(ref, BranchPrefix) { return BranchPrefix + ref } return ref } // GetBranch gets an existing branch. func (g *Git) GetBranch( ctx context.Context, repoPath string, branchName string, ) (*Branch, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } if branchName == "" { return nil, ErrBranchNameEmpty } ref := GetReferenceFromBranchName(branchName) commit, err := g.GetCommitFromRev(ctx, repoPath, ref+"^{commit}") //nolint:goconst if err != nil { return nil, fmt.Errorf("failed to find the commit for the branch: %w", err) } return &Branch{ Name: branchName, SHA: commit.SHA, Commit: commit, }, nil } // HasBranches returns true iff there's at least one branch in the repo (any branch) // NOTE: This is different from repo.Empty(), // as it doesn't care whether the existing branch is the default branch or not. func (g *Git) HasBranches( ctx context.Context, repoPath string, ) (bool, error) { if repoPath == "" { return false, ErrRepositoryPathEmpty } // repo has branches IFF there's at least one commit that is reachable via a branch // (every existing branch points to a commit) cmd := command.New("rev-list", command.WithFlag("--max-count", "1"), command.WithFlag("--branches"), ) output := &bytes.Buffer{} if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(output)); err != nil { return false, processGitErrorf(err, "failed to trigger rev-list command") } return strings.TrimSpace(output.String()) == "", nil } func (g *Git) IsBranchExist(ctx context.Context, repoPath, name string) (bool, error) { cmd := command.New("show-ref", command.WithFlag("--exists", BranchPrefix+name), ) err := cmd.Run(ctx, command.WithDir(repoPath), ) if cmdERR := command.AsError(err); cmdERR != nil && cmdERR.IsExitCode(2) { // git returns exit code 2 in case the ref doesn't exist. // On success it would be 0 and no error would be returned in the first place. // Any other exit code we fall through to default error handling. // https://git-scm.com/docs/git-show-ref#Documentation/git-show-ref.txt---exists return false, nil } if err != nil { return false, processGitErrorf(err, "failed to check if branch %q exist", name) } return true, nil } func (g *Git) GetBranchCount( ctx context.Context, repoPath string, ) (int, error) { if repoPath == "" { return 0, ErrRepositoryPathEmpty } pipeOut, pipeIn := io.Pipe() defer pipeOut.Close() cmd := command.New("branch", command.WithFlag("--list"), command.WithFlag("--format=%(refname:short)"), ) go func() { err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(pipeIn)) if err != nil { _ = pipeIn.CloseWithError( processGitErrorf(err, "failed to trigger branch command"), ) return } _ = pipeIn.Close() }() return countLines(pipeOut) } func countLines(pipe io.Reader) (int, error) { scanner := bufio.NewScanner(pipe) count := 0 for scanner.Scan() { count++ } if err := scanner.Err(); err != nil { return 0, err } return count, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/last_commit_cache.go
git/api/last_commit_cache.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "crypto/sha256" "encoding/gob" "encoding/hex" "fmt" "strings" "time" "github.com/harness/gitness/cache" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/sha" "github.com/go-redis/redis/v8" "github.com/rs/zerolog/log" ) func NewInMemoryLastCommitCache( cacheDuration time.Duration, ) cache.Cache[CommitEntryKey, *Commit] { return cache.New[CommitEntryKey, *Commit]( commitEntryGetter{}, cacheDuration) } func logCacheErrFn(ctx context.Context, err error) { log.Ctx(ctx).Warn().Msgf("failed to use cache: %s", err.Error()) } func NewRedisLastCommitCache( redisClient redis.UniversalClient, cacheDuration time.Duration, ) (cache.Cache[CommitEntryKey, *Commit], error) { if redisClient == nil { return nil, errors.New("unable to create redis based LastCommitCache as redis client is nil") } return cache.NewRedis[CommitEntryKey, *Commit]( redisClient, commitEntryGetter{}, func(key CommitEntryKey) string { h := sha256.New() h.Write([]byte(key)) return "last_commit:" + hex.EncodeToString(h.Sum(nil)) }, commitValueCodec{}, cacheDuration, logCacheErrFn, ), nil } func NoLastCommitCache() cache.Cache[CommitEntryKey, *Commit] { return cache.NewNoCache[CommitEntryKey, *Commit](commitEntryGetter{}) } type CommitEntryKey string const separatorZero = "\x00" func makeCommitEntryKey( repoPath string, commitSHA sha.SHA, path string, ) CommitEntryKey { return CommitEntryKey(repoPath + separatorZero + commitSHA.String() + separatorZero + path) } func (c CommitEntryKey) Split() ( repoPath string, commitSHA string, path string, ) { parts := strings.Split(string(c), separatorZero) if len(parts) != 3 { return } repoPath = parts[0] commitSHA = parts[1] path = parts[2] return } type commitValueCodec struct{} func (c commitValueCodec) Encode(v *Commit) string { buffer := &strings.Builder{} _ = gob.NewEncoder(buffer).Encode(v) return buffer.String() } func (c commitValueCodec) Decode(s string) (*Commit, error) { commit := &Commit{} if err := gob.NewDecoder(strings.NewReader(s)).Decode(commit); err != nil { return nil, fmt.Errorf("failed to unpack commit entry value: %w", err) } return commit, nil } type commitEntryGetter struct{} // Find implements the cache.Getter interface. func (c commitEntryGetter) Find( ctx context.Context, key CommitEntryKey, ) (*Commit, error) { repoPath, commitSHA, path := key.Split() if path == "" { path = "." } return GetLatestCommit(ctx, repoPath, commitSHA, path) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/mapping.go
git/api/mapping.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api func mapRawRef( raw map[string]string, ) (map[GitReferenceField]string, error) { res := make(map[GitReferenceField]string, len(raw)) for k, v := range raw { gitRefField, err := ParseGitReferenceField(k) if err != nil { return nil, err } res[gitRefField] = v } return res, nil } func mapToReferenceSortingArgument( s GitReferenceField, o SortOrder, ) string { sortBy := string(GitReferenceFieldRefName) desc := o == SortOrderDesc if s == GitReferenceFieldCreatorDate { sortBy = string(GitReferenceFieldCreatorDate) if o == SortOrderDefault { desc = true } } if desc { return "-" + sortBy } return sortBy }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/fs.go
git/api/fs.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "context" "fmt" "io" "io/fs" "strings" "time" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sha" "github.com/bmatcuk/doublestar/v4" ) // FS represents a git filesystem. // It implements fs.FS interface. type FS struct { ctx context.Context rev string dir string } var ( // Make sure all targeted interfaces are implemented. _ fs.FS = (*FS)(nil) _ fs.ReadFileFS = (*FS)(nil) _ fs.ReadDirFS = (*FS)(nil) _ fs.GlobFS = (*FS)(nil) _ fs.StatFS = (*FS)(nil) ) // NewFS creates a new git file system for the provided revision. func NewFS(ctx context.Context, rev, dir string) *FS { return &FS{ ctx: ctx, rev: rev, dir: dir, } } // Open opens a file. // It is part of the fs.FS interface. func (f *FS) Open(path string) (fs.File, error) { if path != "" && !fs.ValidPath(path) { return nil, &fs.PathError{ Op: "open", Path: path, Err: fs.ErrInvalid, } } treeNode, err := GetTreeNode(f.ctx, f.dir, f.rev, path, true) if err != nil { if errors.IsNotFound(err) { return nil, &fs.PathError{ Op: "open", Path: path, Err: fs.ErrNotExist, } } return nil, &fs.PathError{ Op: "open", Path: path, Err: err, } } switch { case treeNode.IsDir(): return f.openTree(path, treeNode), nil case treeNode.IsSubmodule(): return f.openSubmodule(path, treeNode), nil default: return f.openBlob(path, treeNode), nil } } func (f *FS) openBlob(path string, treeNode *TreeNode) *fsFile { pipeRead, pipeWrite := io.Pipe() ctx, cancelFn := context.WithCancel(f.ctx) go func() { cmd := command.New("cat-file", command.WithFlag("-p"), command.WithArg(treeNode.SHA.String())) _ = pipeWrite.CloseWithError(cmd.Run(ctx, command.WithDir(f.dir), command.WithStdout(pipeWrite))) }() go func() { <-ctx.Done() _ = pipeWrite.CloseWithError(ctx.Err()) }() return &fsFile{ ctx: ctx, cancelFn: cancelFn, path: path, blobSHA: treeNode.SHA, mode: treeNode.Mode, size: treeNode.Size, reader: pipeRead, } } func (f *FS) openSubmodule(path string, treeNode *TreeNode) *fsFile { content := treeNode.SHA.String() + "\n" // content of a submodule is the commit SHA plus end-of-line character. return &fsFile{ ctx: context.Background(), cancelFn: func() {}, path: path, blobSHA: treeNode.SHA, mode: treeNode.Mode, size: int64(len(content)), reader: strings.NewReader(content), } } func (f *FS) openTree(path string, treeNode *TreeNode) *fsDir { return &fsDir{ ctx: context.Background(), path: path, treeSHA: treeNode.SHA, dir: f.dir, skip: 0, } } // ReadFile reads the whole file. // It is part of the fs.ReadFileFS interface. func (f *FS) ReadFile(path string) ([]byte, error) { file, err := f.Open(path) if err != nil { return nil, err } defer func() { _ = file.Close() }() buffer := bytes.NewBuffer(nil) _, err = io.Copy(buffer, file) if err != nil { return nil, err } return buffer.Bytes(), nil } // ReadDir returns all entries for a directory. // It is part of the fs.ReadDirFS interface. func (f *FS) ReadDir(name string) ([]fs.DirEntry, error) { treeNodes, err := ListTreeNodes(f.ctx, f.dir, f.rev, name, true, false) if err != nil { return nil, fmt.Errorf("failed to read git directory: %w", err) } result := make([]fs.DirEntry, len(treeNodes)) for i, treeNode := range treeNodes { result[i] = fsEntry{treeNode} } return result, nil } // Glob returns all file names that match the pattern. // It is part of the fs.GlobFS interface. func (f *FS) Glob(pattern string) ([]string, error) { return doublestar.Glob(f, pattern) } // Stat returns entry file info for a file path. // It is part of the fs.StatFS interface. func (f *FS) Stat(name string) (fs.FileInfo, error) { treeInfo, err := GetTreeNode(f.ctx, f.dir, f.rev, name, true) if err != nil { return nil, fmt.Errorf("failed to read git directory: %w", err) } return fsEntry{*treeInfo}, nil } type fsDir struct { ctx context.Context path string treeSHA sha.SHA dir string skip int } // Stat returns fs.FileInfo for the directory. // It is part of the fs.File interface. func (d *fsDir) Stat() (fs.FileInfo, error) { return d, nil } // Read always returns an error because it is not possible to read directory bytes. // It is part of the fs.File interface. func (d *fsDir) Read([]byte) (int, error) { return 0, &fs.PathError{ Op: "read", Path: d.path, Err: fs.ErrInvalid, } } // Close in a no-op for directories. // It is part of the fs.File interface. func (d *fsDir) Close() error { return nil } // ReadDir lists entries in the directory. The integer parameter can be used for pagination. // It is part of the fs.ReadDirFile interface. func (d *fsDir) ReadDir(n int) ([]fs.DirEntry, error) { treeNodes, err := ListTreeNodes(d.ctx, d.dir, d.treeSHA.String(), "", true, false) if err != nil { return nil, fmt.Errorf("failed to read git directory: %w", err) } if d.skip >= len(treeNodes) { treeNodes = treeNodes[len(treeNodes):] } else { treeNodes = treeNodes[d.skip:] } var result []fs.DirEntry for _, treeNode := range treeNodes { result = append(result, fsEntry{treeNode}) d.skip++ if n >= 1 && n == len(result) { break } } if len(result) == 0 { return nil, io.EOF } return result, nil } // Name returns the path. // It is part of the fs.FileInfo interface. func (d *fsDir) Name() string { return d.path } // Size implementation for directories returns zero. // It is part of the fs.FileInfo interface. func (d *fsDir) Size() int64 { return 0 } // Mode always returns fs.ModeDir because a git tree is a directory. // It is part of the fs.FileInfo interface. func (d *fsDir) Mode() fs.FileMode { return fs.ModeDir } // ModTime is unimplemented. // It is part of the fs.FileInfo interface. func (d *fsDir) ModTime() time.Time { return time.Time{} } // IsDir implementation always returns true. // It is part of the fs.FileInfo interface. func (d *fsDir) IsDir() bool { return true } // Sys is unimplemented. // It is part of the fs.FileInfo interface. func (d *fsDir) Sys() any { return nil } type fsFile struct { ctx context.Context cancelFn context.CancelFunc path string blobSHA sha.SHA mode TreeNodeMode size int64 reader io.Reader } // Stat returns fs.FileInfo for the file. // It is part of the fs.File interface. func (f *fsFile) Stat() (fs.FileInfo, error) { return f, nil } // Read bytes from the file. // It is part of the fs.File interface. func (f *fsFile) Read(bytes []byte) (int, error) { return f.reader.Read(bytes) } // Close closes the file. // It is part of the fs.File interface. func (f *fsFile) Close() error { f.cancelFn() return nil } // Name returns the name of the file. // It is part of the fs.FileInfo interface. func (f *fsFile) Name() string { return f.path } // Size returns file size - the size of the git blob object. // It is part of the fs.FileInfo interface. func (f *fsFile) Size() int64 { return f.size } // Mode returns file mode for the git blob. // It is part of the fs.FileInfo interface. func (f *fsFile) Mode() fs.FileMode { switch f.mode { //nolint:exhaustive case TreeNodeModeSymlink: return fs.ModeSymlink case TreeNodeModeCommit: return fs.ModeIrregular case TreeNodeModeExec: return 0o555 default: return 0o444 } } // ModTime is unimplemented. Git doesn't store file modification time directly. // It's possible to find the last commit (and thus the commit time) // that modified touched the file, but this is out of scope for this implementation. // It is part of the fs.FileInfo interface. func (f *fsFile) ModTime() time.Time { return time.Time{} } // IsDir implementation always returns false. // It is part of the fs.FileInfo interface. func (f *fsFile) IsDir() bool { return false } // Sys is unimplemented. // It is part of the fs.FileInfo interface. func (f *fsFile) Sys() any { return nil } type fsEntry struct { TreeNode } // Name returns name of a git tree entry. // It is part of the fs.DirEntry interface. func (e fsEntry) Name() string { return e.TreeNode.Name } // IsDir returns if a git tree entry is a directory. // It is part of the fs.FileInfo and fs.DirEntry interfaces. func (e fsEntry) IsDir() bool { return e.TreeNode.IsDir() } // Type returns the type of git tree entry. // It is part of the fs.DirEntry interface. func (e fsEntry) Type() fs.FileMode { return e.Mode() } // Info returns FileInfo for a git tree entry. // It is part of the fs.DirEntry interface. func (e fsEntry) Info() (fs.FileInfo, error) { return e, nil } // Size returns file size - the size of the git blob object. // It is part of the fs.FileInfo interface. func (e fsEntry) Size() int64 { return e.TreeNode.Size } // Mode always returns the filesystem entry mode. // It is part of the fs.FileInfo interface. func (e fsEntry) Mode() fs.FileMode { var mode fs.FileMode if e.TreeNode.Mode == TreeNodeModeExec { mode = 0o555 } else { mode = 0o444 } if e.TreeNode.IsDir() { mode |= fs.ModeDir } if e.TreeNode.IsLink() { mode |= fs.ModeSymlink } if e.TreeNode.IsSubmodule() { mode |= fs.ModeIrregular } return mode } // ModTime is unimplemented. Git doesn't store file modification time directly. // It's possible to find the last commit (and thus the commit time) // that modified touched the file, but this is out of scope for this implementation. // It is part of the fs.FileInfo interface. func (e fsEntry) ModTime() time.Time { return time.Time{} } // Sys is unimplemented. // It is part of the fs.FileInfo interface. func (e fsEntry) Sys() any { return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/prune.go
git/api/prune.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "time" "github.com/harness/gitness/git/command" ) type PrunePackedParams struct { DryRun bool Quiet bool } func (g *Git) PrunePacked( ctx context.Context, repoPath string, params PrunePackedParams, ) error { cmd := command.New("prune-packed") if params.DryRun { cmd.Add(command.WithFlag("--dry-run")) } if params.Quiet { cmd.Add(command.WithFlag("--quiet")) } if err := cmd.Run(ctx, command.WithDir(repoPath)); err != nil { return processGitErrorf(err, "failed to prune-packed objects") } return nil } type PruneObjectsParams struct { DryRun bool ExpireBefore time.Time } func (g *Git) PruneObjects( ctx context.Context, repoPath string, params PruneObjectsParams, ) error { cmd := command.New("prune") if params.DryRun { cmd.Add(command.WithFlag("--dry-run")) } if !params.ExpireBefore.IsZero() { cmd.Add(command.WithFlag(fmt.Sprintf("--expire=%s", params.ExpireBefore.Format(RFC2822DateFormat)))) } if err := cmd.Run(ctx, command.WithDir(repoPath)); err != nil { return processGitErrorf(err, "failed to prune objects") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/info.go
git/api/info.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "bytes" "encoding/binary" "errors" "fmt" "io" "io/fs" "os" "path" "path/filepath" "strings" "time" ) const ( // StaleObjectsGracePeriod is time delta that is used to indicate cutoff wherein an object // would be considered old. StaleObjectsGracePeriod = -7 * 24 * time.Hour // FullRepackTimestampFileName is the name of the file last full repack. FullRepackTimestampFileName = ".harness-full-repack-timestamp" ) // RepositoryInfo contains information about the repository. type RepositoryInfo struct { LooseObjects LooseObjectsInfo PackFiles PackFilesInfo References ReferencesInfo CommitGraph CommitGraphInfo } // LoadRepositoryInfo tracks all git files and returns the stats of repository. func LoadRepositoryInfo(repoPath string) (RepositoryInfo, error) { var result RepositoryInfo var err error result.LooseObjects, err = LoadLooseObjectsInfo(repoPath, time.Now().Add(StaleObjectsGracePeriod)) if err != nil { return RepositoryInfo{}, fmt.Errorf("loading loose objects info: %w", err) } result.PackFiles, err = LoadPackFilesInfo(repoPath) if err != nil { return RepositoryInfo{}, fmt.Errorf("loading pack files info: %w", err) } result.References, err = LoadReferencesInfo(repoPath) if err != nil { return RepositoryInfo{}, fmt.Errorf("loading references info: %w", err) } result.CommitGraph, err = LoadCommitGraphInfo(repoPath) if err != nil { return RepositoryInfo{}, fmt.Errorf("loading commit graph info: %w", err) } return result, nil } // LooseObjectsInfo contains information about loose objects. type LooseObjectsInfo struct { // Count is the number of loose objects. Count uint64 // Size is the total size of all loose objects in bytes. Size uint64 // StaleCount is the number of stale loose objects when taking into account the specified cutoff // date. StaleCount uint64 // StaleSize is the total size of stale loose objects when taking into account the specified // cutoff date. StaleSize uint64 // GarbageCount is the number of garbage files in the loose-objects shards. GarbageCount uint64 // GarbageSize is the total size of garbage in the loose-objects shards. GarbageSize uint64 } // LoadLooseObjectsInfo collects all loose objects information. // //nolint:gosec func LoadLooseObjectsInfo(repoPath string, cutoffDate time.Time) (LooseObjectsInfo, error) { objectsDir := filepath.Join(repoPath, "objects") var result LooseObjectsInfo subdirs, err := os.ReadDir(objectsDir) if err != nil { return LooseObjectsInfo{}, fmt.Errorf("reading objects dir: %w", err) } for _, subdir := range subdirs { if !subdir.IsDir() || len(subdir.Name()) != 2 { continue // skip invalid loose object dirs } subdirPath := filepath.Join(objectsDir, subdir.Name()) entries, err := os.ReadDir(subdirPath) if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return LooseObjectsInfo{}, fmt.Errorf("reading %s: %w", subdirPath, err) } for _, entry := range entries { info, err := entry.Info() if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return LooseObjectsInfo{}, fmt.Errorf("failed to read loose object entry %s: %w", entry.Name(), err) } if !isValidLooseObjectName(entry.Name()) { result.GarbageCount++ result.GarbageSize += uint64(info.Size()) continue } if info.ModTime().Before(cutoffDate) { result.StaleCount++ result.StaleSize += uint64(info.Size()) } result.Count++ result.Size += uint64(info.Size()) } } return result, nil } func isValidLooseObjectName(s string) bool { for _, c := range []byte(s) { if strings.IndexByte("0123456789abcdef", c) < 0 { return false } } return true } // PackFilesInfo contains information about git pack files. type PackFilesInfo struct { // Count is the number of pack files. Count uint64 // Size is the total size of all pack files in bytes. Size uint64 // ReverseIndexCount is the number of reverse indices. ReverseIndexCount uint64 // CruftCount is the number of cruft pack files which have a .mtimes file. CruftCount uint64 // CruftSize is the size of cruft pack files which have a .mtimes file. CruftSize uint64 // KeepCount is the number of .keep pack files. KeepCount uint64 // KeepSize is the size of .keep pack files. KeepSize uint64 // GarbageCount is the number of garbage files. GarbageCount uint64 // GarbageSize is the total size of all garbage files in bytes. GarbageSize uint64 // Bitmap contains information about the bitmap, if any exists. Bitmap BitmapInfo // MultiPackIndex contains information about the multi-pack-index, if any exists. MultiPackIndex MultiPackIndexInfo // MultiPackIndexBitmap contains information about the bitmap for the multi-pack-index, if // any exists. MultiPackIndexBitmap BitmapInfo // LastFullRepack indicates the last date at which a full repack has been performed. If the // date cannot be determined then this file is set to the zero time. LastFullRepack time.Time } // LoadPackFilesInfo loads information about git pack files. func LoadPackFilesInfo(repoPath string) (PackFilesInfo, error) { packsDir := path.Join(repoPath, "objects", "pack") entries, err := os.ReadDir(packsDir) if errors.Is(err, fs.ErrNotExist) { return PackFilesInfo{}, nil } if err != nil { return PackFilesInfo{}, fmt.Errorf("failed to read pack directory %s: %w", packsDir, err) } result := PackFilesInfo{} for _, entry := range entries { filename := entry.Name() info, err := entry.Info() if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return PackFilesInfo{}, fmt.Errorf("failed to read pack entry %s: %w", entry.Name(), err) } switch { case hasPrefixAndSuffix(filename, "pack-", ".pack"): result.Count++ result.Size += uint64(info.Size()) //nolint:gosec case hasPrefixAndSuffix(filename, "pack-", ".keep"): result.KeepCount++ result.KeepSize += uint64(info.Size()) //nolint:gosec case hasPrefixAndSuffix(filename, "pack-", ".mtimes"): result.CruftCount++ result.CruftSize += uint64(info.Size()) //nolint:gosec case hasPrefixAndSuffix(filename, "pack-", ".rev"): result.ReverseIndexCount++ case hasPrefixAndSuffix(filename, "pack-", ".bitmap"): result.Bitmap, err = LoadBitmapInfo(path.Join(packsDir, filename)) if err != nil { return PackFilesInfo{}, fmt.Errorf("failed to read pack bitmap %s: %w", entry.Name(), err) } case hasPrefixAndSuffix(filename, "multi-pack-index-", ".bitmap"): result.MultiPackIndexBitmap, err = LoadBitmapInfo(path.Join(packsDir, filename)) if err != nil { return PackFilesInfo{}, fmt.Errorf("failed to read multi-pack-index bitmap %s: %w", entry.Name(), err) } case filename == "multi-pack-index": result.MultiPackIndex, err = LoadMultiPackIndexInfo(path.Join(packsDir, filename)) if err != nil { return PackFilesInfo{}, fmt.Errorf("failed to read multi-pack-index: %w", err) } default: result.GarbageCount++ result.GarbageSize += uint64(info.Size()) //nolint:gosec } } lastFullRepack, err := GetLastFullRepackTime(repoPath) if err != nil { return PackFilesInfo{}, fmt.Errorf("failed to get last full repack time: %w", err) } result.LastFullRepack = lastFullRepack return result, nil } func SetLastFullRepackTime(repoPath string, t time.Time) error { fullpath := filepath.Join(repoPath, FullRepackTimestampFileName) err := os.Chtimes(fullpath, t, t) if err == nil { return nil } if !errors.Is(err, os.ErrNotExist) { return err } f, err := os.CreateTemp(repoPath, FullRepackTimestampFileName+"-*") if err != nil { return err } defer func() { _ = os.Remove(f.Name()) }() if err := os.Chtimes(f.Name(), t, t); err != nil { return err } if err := os.Rename(f.Name(), fullpath); err != nil { return err } return nil } // GetLastFullRepackTime returns the last date at which a full repack has been performed. func GetLastFullRepackTime(repoPath string) (time.Time, error) { info, err := os.Stat(path.Join(repoPath, FullRepackTimestampFileName)) if errors.Is(err, fs.ErrNotExist) { return time.Time{}, nil } if err != nil { return time.Time{}, err } return info.ModTime(), nil } func hasPrefixAndSuffix(s, prefix, suffix string) bool { return strings.HasPrefix(s, prefix) && strings.HasSuffix(s, suffix) } type BitmapInfo struct { // Version is the version of the bitmap. Expected always to be 1. Version uint16 // HasHashCache indicates whether the hash cache exists. // [GIT]: https://git-scm.com/docs/bitmap-format#_name_hash_cache HasHashCache bool // HasLookupTable indicates whether the lookup table exists. // [GIT]: https://git-scm.com/docs/bitmap-format#_commit_lookup_table HasLookupTable bool } // LoadBitmapInfo loads information about the git pack bitmap file. func LoadBitmapInfo(filename string) (BitmapInfo, error) { // The bitmap header is defined in // https://git-scm.com/docs/bitmap-format#_on_disk_format header := []byte{ 0, 0, 0, 0, // 4-byte signature 0, 0, // 2-byte version number (network byte order), Git only writes or recognizes version 1 0, 0, // 2-byte flags (network byte order) } f, err := os.Open(filename) if err != nil { return BitmapInfo{}, fmt.Errorf("failed to open bitmap file %s: %w", filename, err) } defer f.Close() _, err = io.ReadFull(f, header) if err != nil { return BitmapInfo{}, fmt.Errorf("failed to read bitmap file %s: %w", filename, err) } if !bytes.Equal(header[0:4], []byte{'B', 'I', 'T', 'M'}) { return BitmapInfo{}, fmt.Errorf("invalid bitmap file signature: %s", filename) } version := binary.BigEndian.Uint16(header[4:6]) if version != 1 { return BitmapInfo{}, fmt.Errorf("unsupported bitmap file version: %s", filename) } flags := binary.BigEndian.Uint16(header[6:8]) return BitmapInfo{ Version: version, // https://git-scm.com/docs/bitmap-format#Documentation/technical/bitmap-format.txt-BITMAPOPTHASHCACHE0x4 HasHashCache: flags&0x04 == 0x04, // BITMAP_OPT_HASH_CACHE (0x4) // https://git-scm.com/docs/bitmap-format#Documentation/technical/bitmap-format.txt-BITMAPOPTLOOKUPTABLE0x10 HasLookupTable: flags&0x10 == 0x10, // BITMAP_OPT_LOOKUP_TABLE (0x10) }, nil } type MultiPackIndexInfo struct { Exists bool Version uint8 PackFileCount uint64 } // LoadMultiPackIndexInfo loads information about the git multi-pack-index file. func LoadMultiPackIndexInfo(filename string) (MultiPackIndexInfo, error) { // The header is defined in // https://git-scm.com/docs/gitformat-pack#_multi_pack_index_midx_files_have_the_following_format header := []byte{ 0, 0, 0, 0, // 4-byte signature 0, // 1-byte version number, Git only writes or recognizes version 1 0, // 1-byte Object ID version 0, // 1-byte number of chunks 0, // 1-byte number of base multi-pack-index files 0, 0, 0, 0, // 4-byte number of pack files } f, err := os.Open(filename) if err != nil { return MultiPackIndexInfo{}, fmt.Errorf("failed to open multi-pack-index file %s: %w", filename, err) } defer f.Close() _, err = io.ReadFull(f, header) if err != nil { return MultiPackIndexInfo{}, fmt.Errorf("failed to read multi-pack-index file %s: %w", filename, err) } if !bytes.Equal(header[0:4], []byte{'M', 'I', 'D', 'X'}) { return MultiPackIndexInfo{}, fmt.Errorf("invalid multi-pack-index file signature: %s", filename) } version := header[4] if version != 1 { return MultiPackIndexInfo{}, fmt.Errorf("unsupported multi-pack-index file version: %s", filename) } // The number of base multi-pack-index files is always 0 in Git. baseFilesCount := header[7] if baseFilesCount != 0 { return MultiPackIndexInfo{}, fmt.Errorf("unsupported multi-pack-index file base files count: %d", baseFilesCount) } packFilesCount := binary.BigEndian.Uint32(header[8:12]) return MultiPackIndexInfo{ Exists: true, Version: version, PackFileCount: uint64(packFilesCount), }, nil } type ReferencesInfo struct { LooseReferenceCount uint64 PackedReferenceSize uint64 } func LoadReferencesInfo(repoPath string) (ReferencesInfo, error) { refsPath := path.Join(repoPath, "refs") result := ReferencesInfo{} if err := filepath.WalkDir(refsPath, func(_ string, d fs.DirEntry, err error) error { if errors.Is(err, fs.ErrNotExist) { // ignore if it doesn't exist return nil } if err != nil { return err } if !d.IsDir() { result.LooseReferenceCount++ } return nil }); err != nil { return ReferencesInfo{}, err } stats, err := os.Stat(path.Join(repoPath, "packed-refs")) if err != nil && !errors.Is(err, fs.ErrNotExist) { return ReferencesInfo{}, fmt.Errorf("failed to get packed refs size %s: %w", repoPath, err) } if stats != nil { result.PackedReferenceSize = uint64(stats.Size()) //nolint:gosec } return result, nil } // CommitGraphInfo returns information about the commit-graph of a repository. type CommitGraphInfo struct { // Exists tells whether the repository has a commit-graph. Exists bool // ChainLength is the length of the commit-graph chain, if it exists. If the // repository does not have a commit-graph chain but a monolithic commit-graph, then this // field will be set to 0. ChainLength uint64 // HasBloomFilters tells whether the commit-graph has bloom filters. Bloom filters are used // to answer whether a certain path has been changed in the commit the bloom // filter applies to. HasBloomFilters bool // HasGenerationData tells whether the commit-graph has generation data. Generation // data is stored as the corrected committer date, which is defined as the maximum // of the commit's own committer date or the corrected committer date of any of its // parents. This data can be used to determine whether a commit A comes after a // certain commit B. HasGenerationData bool // HasGenerationDataOverflow stores overflow data in case the corrected committer // date takes more than 31 bits to represent. HasGenerationDataOverflow bool } // LoadCommitGraphInfo returns information about the commit-graph of a repository. func LoadCommitGraphInfo(repoPath string) (CommitGraphInfo, error) { var info CommitGraphInfo commitGraphChainPath := filepath.Join( repoPath, "objects", "info", "commit-graphs", "commit-graph-chain", ) var commitGraphPaths []string chainData, err := os.ReadFile(commitGraphChainPath) //nolint:nestif if err != nil { if !errors.Is(err, os.ErrNotExist) { return CommitGraphInfo{}, fmt.Errorf("reading commit-graphs chain: %w", err) } // If we couldn't find it, we check whether the monolithic commit-graph file exists // and use that instead. commitGraphPath := filepath.Join( repoPath, "objects", "info", "commit-graph", ) if _, err := os.Stat(commitGraphPath); err != nil { if errors.Is(err, os.ErrNotExist) { return CommitGraphInfo{Exists: false}, nil } return CommitGraphInfo{}, fmt.Errorf("statting commit-graph: %w", err) } commitGraphPaths = []string{commitGraphPath} info.Exists = true } else { // Otherwise, if we have found the commit-graph-chain, we use the IDs it contains as // the set of commit-graphs to check further down below. ids := bytes.Split(bytes.TrimSpace(chainData), []byte{'\n'}) commitGraphPaths = make([]string, 0, len(ids)) for _, id := range ids { commitGraphPaths = append(commitGraphPaths, filepath.Join(repoPath, "objects", "info", "commit-graphs", fmt.Sprintf("graph-%s.graph", id)), ) } info.Exists = true info.ChainLength = uint64(len(commitGraphPaths)) } for _, graphFilePath := range commitGraphPaths { err := parseCommitGraphFile(graphFilePath, &info) if errors.Is(err, os.ErrNotExist) { // concurrently modified continue } if err != nil { return CommitGraphInfo{}, err } } return info, nil } func parseCommitGraphFile(filename string, info *CommitGraphInfo) error { f, err := os.Open(filename) if err != nil { return fmt.Errorf("read commit graph chain file: %w", err) } defer f.Close() reader := bufio.NewReader(f) // The header format is defined in gitformat-commit-graph(5). header := []byte{ 0, 0, 0, 0, // 4-byte signature: The signature is: {'C', 'G', 'P', 'H'} 0, // 1-byte version number: Currently, the only valid version is 1. 0, // 1-byte Hash Version 0, // 1-byte number of "chunks" 0, // 1-byte number of base commit-graphs } n, err := reader.Read(header) if err != nil { return fmt.Errorf("read commit graph file %q header: %w", filename, err) } if n != len(header) { return fmt.Errorf("commit graph file %q is too small, no header", filename) } if !bytes.Equal(header[:4], []byte("CGPH")) { return fmt.Errorf("commit graph file %q doesn't have signature", filename) } if header[4] != 1 { return fmt.Errorf( "commit graph file %q has unsupported version number: %v", filename, header[4]) } const chunkTableEntrySize = 12 numberOfChunks := header[6] table := make([]byte, (numberOfChunks+1)*chunkTableEntrySize) n, err = reader.Read(table) if err != nil { return fmt.Errorf( "read commit graph file %q table of contents for the chunks: %w", filename, err) } if n != len(table) { return fmt.Errorf( "commit graph file %q is too small, no table of contents", filename) } if !info.HasBloomFilters { info.HasBloomFilters = bytes.Contains(table, []byte("BIDX")) && bytes.Contains(table, []byte("BDAT")) } if !info.HasGenerationData { info.HasGenerationData = bytes.Contains(table, []byte("GDA2")) } if !info.HasGenerationDataOverflow { info.HasGenerationDataOverflow = bytes.Contains(table, []byte("GDO2")) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/blob.go
git/api/blob.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "io" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/sha" ) type BlobReader struct { SHA sha.SHA // Size is the actual size of the blob. Size int64 // ContentSize is the total number of bytes returned by the Content Reader. ContentSize int64 // Content contains the (partial) content of the blob. Content io.ReadCloser } // GetBlob returns the blob for the given object sha. func GetBlob( ctx context.Context, repoPath string, alternateObjectDirs []string, sha sha.SHA, sizeLimit int64, ) (*BlobReader, error) { stdIn, stdOut, cancel := CatFileBatch(ctx, repoPath, alternateObjectDirs) line := sha.String() + "\n" _, err := stdIn.Write([]byte(line)) if err != nil { cancel() return nil, fmt.Errorf("failed to write blob sha to git stdin: %w", err) } output, err := ReadBatchHeaderLine(stdOut) if err != nil { cancel() return nil, processGitErrorf(err, "failed to read cat-file batch line") } if !output.SHA.Equal(sha) { cancel() return nil, fmt.Errorf("cat-file returned object sha '%s' but expected '%s'", output.SHA, sha) } if output.Type != GitObjectTypeBlob { cancel() return nil, errors.InvalidArgumentf( "cat-file returned object type '%s' but expected '%s'", output.Type, GitObjectTypeBlob) } contentSize := output.Size if sizeLimit > 0 && sizeLimit < contentSize { contentSize = sizeLimit } return &BlobReader{ SHA: sha, Size: output.Size, ContentSize: contentSize, Content: newLimitReaderCloser(stdOut, contentSize, cancel), }, nil } func newLimitReaderCloser(reader io.Reader, limit int64, stop func()) limitReaderCloser { return limitReaderCloser{ reader: io.LimitReader(reader, limit), stop: stop, } } type limitReaderCloser struct { reader io.Reader stop func() } func (l limitReaderCloser) Read(p []byte) (n int, err error) { return l.reader.Read(p) } func (l limitReaderCloser) Close() error { l.stop() return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/diff_test.go
git/api/diff_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "io" "reflect" "strings" "testing" "github.com/harness/gitness/git/parser" "github.com/google/go-cmp/cmp" ) func Test_modifyHeader(t *testing.T) { type args struct { hunk parser.HunkHeader startLine int endLine int } tests := []struct { name string args args want []byte }{ { name: "test empty", args: args{ hunk: parser.HunkHeader{ OldLine: 0, OldSpan: 0, NewLine: 0, NewSpan: 0, }, startLine: 2, endLine: 10, }, want: []byte("@@ -0,0 +0,0 @@"), }, { name: "test empty 1", args: args{ hunk: parser.HunkHeader{ OldLine: 0, OldSpan: 0, NewLine: 0, NewSpan: 0, }, startLine: 0, endLine: 0, }, want: []byte("@@ -0,0 +0,0 @@"), }, { name: "test empty old", args: args{ hunk: parser.HunkHeader{ OldLine: 0, OldSpan: 0, NewLine: 1, NewSpan: 10, }, startLine: 2, endLine: 10, }, want: []byte("@@ -0,0 +2,8 @@"), }, { name: "test empty new", args: args{ hunk: parser.HunkHeader{ OldLine: 1, OldSpan: 10, NewLine: 0, NewSpan: 0, }, startLine: 2, endLine: 10, }, want: []byte("@@ -2,8 +0,0 @@"), }, { name: "test 1", args: args{ hunk: parser.HunkHeader{ OldLine: 2, OldSpan: 20, NewLine: 2, NewSpan: 20, }, startLine: 5, endLine: 10, }, want: []byte("@@ -5,5 +5,5 @@"), }, { name: "test 2", args: args{ hunk: parser.HunkHeader{ OldLine: 2, OldSpan: 20, NewLine: 2, NewSpan: 20, }, startLine: 15, endLine: 25, }, want: []byte("@@ -15,7 +15,7 @@"), }, { name: "test 4", args: args{ hunk: parser.HunkHeader{ OldLine: 1, OldSpan: 10, NewLine: 1, NewSpan: 10, }, startLine: 15, endLine: 20, }, want: []byte("@@ -1,10 +1,10 @@"), }, { name: "test 5", args: args{ hunk: parser.HunkHeader{ OldLine: 1, OldSpan: 108, NewLine: 1, NewSpan: 108, }, startLine: 5, endLine: 0, }, want: []byte("@@ -5,108 +5,108 @@"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := modifyHeader(tt.args.hunk, tt.args.startLine, tt.args.endLine); !reflect.DeepEqual(got, tt.want) { t.Errorf("modifyHeader() = %s, want %s", got, tt.want) } }) } } func Test_cutLinesFromFullDiff(t *testing.T) { type args struct { r io.Reader startLine int endLine int } tests := []struct { name string args args wantW string wantErr bool }{ { name: "test empty", args: args{ r: strings.NewReader(`diff --git a/file.txt b/file.txt index f0eec86f614944a81f87d879ebdc9a79aea0d7ea..47d2739ba2c34690248c8f91b84bb54e8936899a 100644 --- a/file.txt +++ b/file.txt @@ -0,0 +0,0 @@ `), startLine: 2, endLine: 10, }, wantW: `diff --git a/file.txt b/file.txt index f0eec86f614944a81f87d879ebdc9a79aea0d7ea..47d2739ba2c34690248c8f91b84bb54e8936899a 100644 --- a/file.txt +++ b/file.txt @@ -0,0 +0,0 @@ `, }, { name: "test 1", args: args{ r: strings.NewReader(`diff --git a/file.txt b/file.txt index f0eec86f614944a81f87d879ebdc9a79aea0d7ea..47d2739ba2c34690248c8f91b84bb54e8936899a 100644 --- a/file.txt +++ b/file.txt @@ -1,9 +1,9 @@ some content some content some content -some content +some content some content some content some content some content some content `), startLine: 2, endLine: 10, }, wantW: `diff --git a/file.txt b/file.txt index f0eec86f614944a81f87d879ebdc9a79aea0d7ea..47d2739ba2c34690248c8f91b84bb54e8936899a 100644 --- a/file.txt +++ b/file.txt @@ -2,8 +2,8 @@ some content some content -some content +some content some content some content some content some content some content `, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { w := &bytes.Buffer{} err := cutLinesFromFullFileDiff(w, tt.args.r, tt.args.startLine, tt.args.endLine) if (err != nil) != tt.wantErr { t.Errorf("cutLinesFromFullFileDiff() error = %v, wantErr %v", err, tt.wantErr) return } if gotW := w.String(); gotW != tt.wantW { t.Errorf("cutLinesFromFullFileDiff() gotW = %v, want %v, diff: %s", gotW, tt.wantW, cmp.Diff(gotW, tt.wantW)) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/service_pack.go
git/api/service_pack.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bytes" "context" "fmt" "io" "regexp" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) var safeGitProtocolHeader = regexp.MustCompile(`^[0-9a-zA-Z]+=[0-9a-zA-Z]+(:[0-9a-zA-Z]+=[0-9a-zA-Z]+)*$`) func (g *Git) InfoRefs( ctx context.Context, repoPath string, service string, w io.Writer, env ...string, ) error { stdout := &bytes.Buffer{} cmd := command.New(service, command.WithFlag("--stateless-rpc"), command.WithFlag("--advertise-refs"), command.WithArg("."), ) if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout), command.WithEnvs(env...), ); err != nil { return errors.Internalf(err, "InfoRefs service %s failed", service) } if _, err := w.Write(packetWrite("# service=git-" + service + "\n")); err != nil { return errors.Internalf(err, "failed to write pktLine in InfoRefs %s service", service) } if _, err := w.Write([]byte("0000")); err != nil { return errors.Internalf(err, "failed to flush data in InfoRefs %s service", service) } if _, err := io.Copy(w, stdout); err != nil { return errors.Internalf(err, "streaming InfoRefs %s service failed", service) } return nil } type ServicePackConfig struct { UploadPackHook string } type ServicePackOptions struct { Service enum.GitServiceType Timeout int // seconds StatelessRPC bool Stdout io.Writer Stdin io.Reader Stderr io.Writer Env []string Protocol string Config ServicePackConfig } func (g *Git) ServicePack( ctx context.Context, repoPath string, options ServicePackOptions, ) error { cmd := command.New(string(options.Service), command.WithArg(repoPath), command.WithEnv("SSH_ORIGINAL_COMMAND", string(options.Service)), ) if options.StatelessRPC { cmd.Add(command.WithFlag("--stateless-rpc")) } if options.Protocol != "" && safeGitProtocolHeader.MatchString(options.Protocol) { cmd.Add(command.WithEnv("GIT_PROTOCOL", options.Protocol)) } if options.Config.UploadPackHook != "" { cmd.Add(command.WithConfig("uploadpack.packObjectsHook", options.Config.UploadPackHook)) } err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(options.Stdout), command.WithStdin(options.Stdin), command.WithStderr(options.Stderr), command.WithEnvs(options.Env...), ) if err != nil && err.Error() != "signal: killed" { log.Ctx(ctx).Err(err).Msgf("Fail to serve RPC(%s) in %s: %v", options.Service, repoPath, err) } return err } func packetWrite(str string) []byte { s := strconv.FormatInt(int64(len(str)+4), 16) if len(s)%4 != 0 { s = strings.Repeat("0", 4-len(s)%4) + s } return []byte(s + str) } func PktError(w io.Writer, err error) { strErr := fmt.Sprintf("ERR %s\n", err.Error()) _, _ = w.Write(packetWrite(strErr)) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/signature.go
git/api/signature.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "fmt" "time" "github.com/harness/gitness/errors" ) // Signature represents the Author or Committer information. type Signature struct { Identity Identity // When is the timestamp of the Signature. When time.Time } func (s Signature) String() string { return fmt.Sprintf("%s <%s>", s.Identity.Name, s.Identity.Email) } type Identity struct { Name string Email string } func (i Identity) String() string { return fmt.Sprintf("%s <%s>", i.Name, i.Email) } func (i Identity) Validate() error { if i.Name == "" { return errors.InvalidArgument("identity name is mandatory") } if i.Email == "" { return errors.InvalidArgument("identity email is mandatory") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/submodule.go
git/api/submodule.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "bufio" "context" "strings" ) type Submodule struct { Name string URL string } // GetSubmodule returns the submodule at the given path reachable from ref. // Note: ref can be Branch / Tag / CommitSHA. func (g *Git) GetSubmodule( ctx context.Context, repoPath string, ref string, treePath string, ) (*Submodule, error) { if repoPath == "" { return nil, ErrRepositoryPathEmpty } treePath = cleanTreePath(treePath) // Get the commit object for the ref commitSHA, err := g.ResolveRev(ctx, repoPath, ref) if err != nil { return nil, processGitErrorf(err, "error getting commit for ref '%s'", ref) } node, err := g.GetTreeNode(ctx, repoPath, commitSHA.String(), ".gitmodules") if err != nil { return nil, processGitErrorf(err, "error reading tree node for ref '%s' with commit '%s'", ref, commitSHA) } reader, err := GetBlob(ctx, repoPath, nil, node.SHA, 0) if err != nil { return nil, processGitErrorf(err, "error reading commit for ref '%s'", ref) } defer reader.Content.Close() modules, err := GetSubModules(reader) if err != nil { return nil, processGitErrorf(err, "error getting submodule '%s' from commit", treePath) } return modules[treePath], nil } // GetSubModules get all the sub modules of current revision git tree. func GetSubModules(rd *BlobReader) (map[string]*Submodule, error) { var isModule bool var path string submodules := make(map[string]*Submodule, 4) scanner := bufio.NewScanner(rd.Content) for scanner.Scan() { if strings.HasPrefix(scanner.Text(), "[submodule") { isModule = true continue } if isModule { fields := strings.Split(scanner.Text(), "=") k := strings.TrimSpace(fields[0]) switch k { case "path": path = strings.TrimSpace(fields[1]) case "url": submodules[path] = &Submodule{path, strings.TrimSpace(fields[1])} isModule = false } } } return submodules, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/repack.go
git/api/repack.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" "fmt" "time" "github.com/harness/gitness/git/command" ) type RepackParams struct { // SinglePack packs everything referenced into a single pack. // git repack -a SinglePack bool // RemoveRedundantObjects after packing, if the newly created packs make some existing packs redundant, // remove the redundant packs. git repack -d RemoveRedundantObjects bool // This flag causes an object that is borrowed from an alternate object store to be // ignored even if it would have otherwise been packed. git repack -l pass --local to // git pack-objects --local. Local bool // Arrange resulting pack structure so that each successive pack contains at least // <factor> times the number of objects as the next-largest pack. Geometric int // When used with SinglePack and RemoveRedundantObjects, any unreachable objects from existing packs will be appended // to the end of the packfile instead of being removed. In addition, any unreachable // loose objects will be packed (and their loose counterparts removed). KeepUnreachable bool // Any unreachable objects are packed into a separate cruft pack Cruft bool // Expire unreachable objects older than <approxidate> immediately instead of waiting // for the next git gc invocation. Only useful with RemoveRedundantObjects CruftExpireBefore time.Time // Include objects in .keep files when repacking. Note that we still do not delete .keep packs // after pack-objects finishes. This means that we may duplicate objects, but this makes the // option safe to use when there are concurrent pushes or fetches. This option is generally // only useful if you are writing bitmaps with -b or repack.writeBitmaps, as it ensures that // the bitmapped packfile has the necessary objects. PackKeptObjects bool // Write a reachability bitmap index as part of the repack. // This only makes sense when used with SinglePack // as the bitmaps must be able to refer to all reachable objects WriteBitmap bool // Write a multi-pack index (see git-multi-pack-index[1]) containing the non-redundant packs // git repack --write-midx WriteMidx bool } func (g *Git) RepackObjects( ctx context.Context, repoPath string, params RepackParams, ) error { cmd := command.New("repack") if params.SinglePack { cmd.Add(command.WithFlag("-a")) } if params.RemoveRedundantObjects { cmd.Add(command.WithFlag("-d")) } if params.Local { cmd.Add(command.WithFlag("-l")) } if params.Geometric > 0 { cmd.Add(command.WithFlag(fmt.Sprintf("--geometric=%d", params.Geometric))) } if params.KeepUnreachable { cmd.Add(command.WithFlag("--keep-unreachable")) } if params.Cruft { cmd.Add(command.WithFlag("--cruft")) } if !params.CruftExpireBefore.IsZero() { cmd.Add(command.WithFlag(fmt.Sprintf("--cruft-expiration=%s", params.CruftExpireBefore.Format(RFC2822DateFormat)))) } if params.PackKeptObjects { cmd.Add(command.WithFlag("--pack-kept-objects")) } if params.WriteBitmap { cmd.Add(command.WithFlag("--write-bitmap-index")) } if params.WriteMidx { cmd.Add(command.WithFlag("--write-midx")) } if err := cmd.Run(ctx, command.WithDir(repoPath)); err != nil { return processGitErrorf(err, "failed to repack objects") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/foreachref/parser.go
git/api/foreachref/parser.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package foreachref import ( "bufio" "bytes" "errors" "fmt" "io" "strings" ) // Parser parses 'git for-each-ref' output according to a given output Format. type Parser struct { // tokenizes 'git for-each-ref' output into "reference paragraphs". scanner *bufio.Scanner // format represents the '--format' string that describes the expected // 'git for-each-ref' output structure. format Format // err holds the last encountered error during parsing. err error } // NewParser creates a 'git for-each-ref' output parser that will parse all // references in the provided Reader. The references in the output are assumed // to follow the specified Format. func NewParser(r io.Reader, format Format) *Parser { scanner := bufio.NewScanner(r) // in addition to the reference delimiter we specified in the --format, // `git for-each-ref` will always add a newline after every reference. refDelim := make([]byte, 0, len(format.refDelim)+1) refDelim = append(refDelim, format.refDelim...) refDelim = append(refDelim, '\n') // Split input into delimiter-separated "reference blocks". scanner.Split( func(data []byte, atEOF bool) (int, []byte, error) { // Scan until delimiter, marking end of reference. delimIdx := bytes.Index(data, refDelim) if delimIdx >= 0 { token := data[:delimIdx] advance := delimIdx + len(refDelim) return advance, token, nil } // If we're at EOF, we have a final, non-terminated reference. Return it. if atEOF { return len(data), data, nil } // Not yet a full field. Request more data. return 0, nil, nil }) return &Parser{ scanner: scanner, format: format, err: nil, } } // Next returns the next reference as a collection of key-value pairs. nil // denotes EOF but is also returned on errors. The Err method should always be // consulted after Next returning nil. // // It could, for example return something like: // // { "objecttype": "tag", "refname:short": "v1.16.4", "object": "f460b7543ed500e49c133c2cd85c8c55ee9dbe27" } func (p *Parser) Next() map[string]string { if !p.scanner.Scan() { return nil } fields, err := p.parseRef(p.scanner.Text()) if err != nil && !errors.Is(err, io.EOF) { p.err = err return nil } return fields } // Err returns the latest encountered parsing error. func (p *Parser) Err() error { return p.err } // parseRef parses out all key-value pairs from a single reference block, such as // // "type tag\0ref:short v1.16.4\0object f460b7543ed500e49c133c2cd85c8c55ee9dbe27" func (p *Parser) parseRef(refBlock string) (map[string]string, error) { if refBlock == "" { // must be at EOF return nil, io.EOF } fieldValues := make(map[string]string) fields := strings.Split(refBlock, p.format.fieldDelimStr) if len(fields) != len(p.format.fieldNames) { return nil, fmt.Errorf("unexpected number of reference fields: wanted %d, was %d", len(fields), len(p.format.fieldNames)) } for i, field := range fields { field = strings.TrimSpace(field) var fieldKey string var fieldVal string firstSpace := strings.Index(field, " ") if firstSpace > 0 { fieldKey = field[:firstSpace] fieldVal = field[firstSpace+1:] } else { // could be the case if the requested field had no value fieldKey = field } // enforce the format order of fields if p.format.fieldNames[i] != fieldKey { return nil, fmt.Errorf("unexpected field name at position %d: wanted: '%s', was: '%s'", i, p.format.fieldNames[i], fieldKey) } fieldValues[fieldKey] = fieldVal } return fieldValues, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/api/foreachref/format.go
git/api/foreachref/format.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package foreachref import ( "encoding/hex" "fmt" "io" "strings" ) var ( nullChar = []byte("\x00") dualNullChar = []byte("\x00\x00") ) // Format supports specifying and parsing an output format for 'git // for-each-ref'. See git-for-each-ref(1) for available fields. type Format struct { // fieldNames hold %(fieldname)s to be passed to the '--format' flag of // for-each-ref. See git-for-each-ref(1) for available fields. fieldNames []string // fieldDelim is the character sequence that is used to separate fields // for each reference. fieldDelim and refDelim should be selected to not // interfere with each other and to not be present in field values. fieldDelim []byte // fieldDelimStr is a string representation of fieldDelim. Used to save // us from repetitive reallocation whenever we need the delimiter as a // string. fieldDelimStr string // refDelim is the character sequence used to separate reference from // each other in the output. fieldDelim and refDelim should be selected // to not interfere with each other and to not be present in field // values. refDelim []byte } // NewFormat creates a forEachRefFormat using the specified fieldNames. See // git-for-each-ref(1) for available fields. func NewFormat(fieldNames ...string) Format { return Format{ fieldNames: fieldNames, fieldDelim: nullChar, fieldDelimStr: string(nullChar), refDelim: dualNullChar, } } // Flag returns a for-each-ref --format flag value that captures the fieldNames. func (f Format) Flag() string { var formatFlag strings.Builder for i, field := range f.fieldNames { // field key and field value formatFlag.WriteString(fmt.Sprintf("%s %%(%s)", field, field)) if i < len(f.fieldNames)-1 { // note: escape delimiters to allow control characters as // delimiters. For example, '%00' for null character or '%0a' // for newline. formatFlag.WriteString(f.hexEscaped(f.fieldDelim)) } } formatFlag.WriteString(f.hexEscaped(f.refDelim)) return formatFlag.String() } // Parser returns a Parser capable of parsing 'git for-each-ref' output produced // with this Format. func (f Format) Parser(r io.Reader) *Parser { return NewParser(r, f) } // hexEscaped produces hex-escpaed characters from a string. For example, "\n\0" // would turn into "%0a%00". func (f Format) hexEscaped(delim []byte) string { escaped := "" for i := range delim { escaped += "%" + hex.EncodeToString([]byte{delim[i]}) } return escaped }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/maintenance/stale_files.go
git/maintenance/stale_files.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package maintenance import ( "errors" "fmt" "io/fs" "path/filepath" "strings" "time" ) const ( deleteTempFilesOlderThanDuration = 24 * time.Hour ) func FindTempObjects(repoPath string) ([]string, error) { var files []string objectDir := filepath.Join(repoPath, "objects") if err := filepath.WalkDir(objectDir, func(path string, dirEntry fs.DirEntry, err error) error { if err != nil { if errors.Is(err, fs.ErrPermission) || errors.Is(err, fs.ErrNotExist) { return nil } return err } // Git creates only temp objects, packfiles and packfile indices. if dirEntry.IsDir() { return nil } isStale, err := isStaleTempObject(dirEntry) if err != nil { if errors.Is(err, fs.ErrNotExist) { return nil } return fmt.Errorf("checking for stale temporary object: %w", err) } if !isStale { return nil } files = append(files, path) return nil }); err != nil { return nil, fmt.Errorf("walking object directory: %w", err) } return files, nil } func isStaleTempObject(dirEntry fs.DirEntry) (bool, error) { if !strings.HasPrefix(dirEntry.Name(), "tmp_") { return false, nil } fi, err := dirEntry.Info() if err != nil { return false, err } if time.Since(fi.ModTime()) <= deleteTempFilesOlderThanDuration { return false, nil } return true, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/types/config.go
git/types/config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package types import ( "time" "github.com/harness/gitness/git/enum" ) // Config defines the configuration for the git package. type Config struct { // Trace specifies whether git operations' stdIn/stdOut/err are traced. // NOTE: Currently limited to 'push' operation until we move to internal command package. Trace bool // Root specifies the directory containing git related data (e.g. repos, ...) Root string // TmpDir (optional) specifies the directory for temporary data (e.g. repo clones, ...) TmpDir string // HookPath points to the binary used as git server hook. HookPath string // LastCommitCache holds configuration options for the last commit cache. LastCommitCache LastCommitCacheConfig } // LastCommitCacheConfig holds configuration options for the last commit cache. type LastCommitCacheConfig struct { // Mode determines where the cache will be. Mode enum.LastCommitCacheMode // Duration defines cache duration of last commit. Duration time.Duration }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/check/branch_test.go
git/check/branch_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package check import "testing" func TestBranchName(t *testing.T) { type args struct { branch string } tests := []struct { name string args args wantErr bool }{ { name: "happy path", args: args{ branch: "new-branch", }, wantErr: false, }, { name: "happy path, include slash", args: args{ branch: "eb/new-branch", }, wantErr: false, }, { name: "happy path, test utf-8 chars", args: args{ branch: "eb/new\u2318branch", }, wantErr: false, }, { name: "branch name empty should return error", args: args{ branch: "", }, wantErr: true, }, { name: "branch name starts with / should return error", args: args{ branch: "/new-branch", }, wantErr: true, }, { name: "branch name contains // should return error", args: args{ branch: "eb//new-branch", }, wantErr: true, }, { name: "branch name ends with / should return error", args: args{ branch: "eb/new-branch/", }, wantErr: true, }, { name: "branch name starts with . should return error", args: args{ branch: ".new-branch", }, wantErr: true, }, { name: "branch name contains .. should return error", args: args{ branch: "new..branch", }, wantErr: true, }, { name: "branch name ends with . should return error", args: args{ branch: "new-branch.", }, wantErr: true, }, { name: "branch name contains ~ should return error", args: args{ branch: "new~branch", }, wantErr: true, }, { name: "branch name contains ^ should return error", args: args{ branch: "^new-branch", }, wantErr: true, }, { name: "branch name contains : should return error", args: args{ branch: "new:branch", }, wantErr: true, }, { name: "branch name contains control char should return error", args: args{ branch: "new\x08branch", }, wantErr: true, }, { name: "branch name ends with .lock should return error", args: args{ branch: "new-branch.lock", }, wantErr: true, }, { name: "branch name starts with ? should return error", args: args{ branch: "?new-branch", }, wantErr: true, }, { name: "branch name contains ? should return error", args: args{ branch: "new?branch", }, wantErr: true, }, { name: "branch name ends with ? should return error", args: args{ branch: "new-branch?", }, wantErr: true, }, { name: "branch name starts with [ should return error", args: args{ branch: "[new-branch", }, wantErr: true, }, { name: "branch name contains [ should return error", args: args{ branch: "new[branch", }, wantErr: true, }, { name: "branch name ends with [ should return error", args: args{ branch: "new-branch[", }, wantErr: true, }, { name: "branch name starts with * should return error", args: args{ branch: "*new-branch", }, wantErr: true, }, { name: "branch name contains * should return error", args: args{ branch: "new*branch", }, wantErr: true, }, { name: "branch name ends with * should return error", args: args{ branch: "new-branch*", }, wantErr: true, }, { name: "branch name cannot contain a sequence @{ and should return error", args: args{ branch: "new-br@{anch", }, wantErr: true, }, { name: "branch name cannot be the single character @ and should return error", args: args{ branch: "@", }, wantErr: true, }, { name: "branch name cannot contain \\ and should return error", args: args{ branch: "new-br\\anch", }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := BranchName(tt.args.branch); (err != nil) != tt.wantErr { t.Errorf("validateBranchName() error = %v, wantErr %v", err, tt.wantErr) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/check/branch.go
git/check/branch.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package check import ( "errors" "fmt" "strings" ) /* https://git-scm.com/docs/git-check-ref-format * How to handle various characters in refnames: * 0: An acceptable character for refs * 1: End-of-component * 2: ., look for a preceding . to reject .. in refs * 3: {, look for a preceding @ to reject @{ in refs * 4: A bad character: ASCII control characters, and * ":", "?", "[", "\", "^", "~", SP, or TAB * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set. */ var refnameDisposition = [256]byte{ 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4, } //nolint:gocognit // refactor if needed func BranchName(branch string) error { const lock = ".lock" last := byte('\x00') for i := 0; i < len(branch); i++ { ch := branch[i] & 255 disp := refnameDisposition[ch] switch disp { case 1: if i == 0 { goto out } if last == '/' { // Refname contains "//" return fmt.Errorf("branch '%s' cannot have two consecutive slashes // ", branch) } case 2: if last == '.' { // Refname contains ".." return fmt.Errorf("branch '%s' cannot have two consecutive dots .. ", branch) } case 3: if last == '@' { // Refname contains "@{". return fmt.Errorf("branch '%s' cannot contain a sequence @{", branch) } case 4: return fmt.Errorf("branch '%s' cannot have ASCII control characters "+ "(i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere", branch) case 5: return fmt.Errorf("branch '%s' can't be a pattern", branch) } last = ch } out: if last == '\x00' { return errors.New("branch name is empty") } if last == '.' { return fmt.Errorf("branch '%s' cannot have . at the end", branch) } if last == '@' { return fmt.Errorf("branch '%s' cannot be the single character @", branch) } if last == '/' { return fmt.Errorf("branch '%s' cannot have / at the end", branch) } if branch[0] == '.' { return fmt.Errorf("branch '%s' cannot start with '.'", branch) } if strings.HasSuffix(branch, lock) { return fmt.Errorf("branch '%s' cannot end with '%s'", branch, lock) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/enum/merge.go
git/enum/merge.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package enum // MergeMethod represents the approach to merge commits into base branch. type MergeMethod string const ( // MergeMethodMerge create merge commit. MergeMethodMerge MergeMethod = "merge" // MergeMethodSquash squash commits into single commit before merging. MergeMethodSquash MergeMethod = "squash" // MergeMethodRebase rebase before merging. MergeMethodRebase MergeMethod = "rebase" // MergeMethodFastForward fast-forward merging. MergeMethodFastForward MergeMethod = "fast-forward" ) var MergeMethods = []MergeMethod{ MergeMethodMerge, MergeMethodSquash, MergeMethodRebase, MergeMethodFastForward, } func (m MergeMethod) Sanitize() (MergeMethod, bool) { switch m { case MergeMethodMerge, MergeMethodSquash, MergeMethodRebase, MergeMethodFastForward: return m, true default: return MergeMethodMerge, false } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/enum/hunk_headers.go
git/enum/hunk_headers.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package enum // Diff file header extensions. From: https://git-scm.com/docs/git-diff#generate_patch_text_with_p const ( DiffExtHeaderOldMode = "old mode" // old mode <mode> DiffExtHeaderNewMode = "new mode" // new mode <mode> DiffExtHeaderDeletedFileMode = "deleted file mode" // deleted file mode <mode> DiffExtHeaderNewFileMode = "new file mode" // new file mode <mode> DiffExtHeaderCopyFrom = "copy from" // copy from <path> DiffExtHeaderCopyTo = "copy to" // copy to <path> DiffExtHeaderRenameFrom = "rename from" // rename from <path> DiffExtHeaderRenameTo = "rename to" // rename to <path> DiffExtHeaderSimilarity = "similarity index" // similarity index <number> DiffExtHeaderDissimilarity = "dissimilarity index" // dissimilarity index <number> DiffExtHeaderIndex = "index" // index <hash>..<hash> <mode> )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/enum/entry.go
git/enum/entry.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package enum // EntryMode is the unix file mode of a tree entry. type EntryMode int // There are only a few file modes in Git. They look like unix file modes, but // they can only be one of these. const ( EntryTree EntryMode = 0040000 EntryBlob EntryMode = 0100644 EntryExec EntryMode = 0100755 EntrySymlink EntryMode = 0120000 EntryCommit EntryMode = 0160000 )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/enum/ref.go
git/enum/ref.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package enum type RefType int const ( RefTypeRaw RefType = iota RefTypeBranch RefTypeTag RefTypePullReqHead RefTypePullReqMerge ) func (t RefType) String() string { switch t { case RefTypeRaw: return "raw" case RefTypeBranch: return "branch" case RefTypeTag: return "tag" case RefTypePullReqHead: return "head" case RefTypePullReqMerge: return "merge" default: return "" } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/enum/cache.go
git/enum/cache.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package enum // LastCommitCacheMode specifies the type of the cache used for caching last commit information. type LastCommitCacheMode string const ( LastCommitCacheModeInMemory LastCommitCacheMode = "inmemory" LastCommitCacheModeRedis LastCommitCacheMode = "redis" LastCommitCacheModeNone LastCommitCacheMode = "none" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/enum/diff.go
git/enum/diff.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package enum type FileDiffStatus string const ( // NOTE: keeping values upper case for now to stay consistent with current API. // TODO: change drone/go-scm (and potentially new dependencies) to case insensitive. FileDiffStatusUndefined FileDiffStatus = "UNDEFINED" FileDiffStatusAdded FileDiffStatus = "ADDED" FileDiffStatusModified FileDiffStatus = "MODIFIED" FileDiffStatusDeleted FileDiffStatus = "DELETED" FileDiffStatusRenamed FileDiffStatus = "RENAMED" FileDiffStatusCopied FileDiffStatus = "COPIED" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/tempdir/file.go
git/tempdir/file.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tempdir import ( "errors" "fmt" "io/fs" "os" ) // CreateTemporaryPath creates a temporary path. func CreateTemporaryPath(reposTempPath, prefix string) (string, error) { if reposTempPath != "" { if err := os.MkdirAll(reposTempPath, os.ModePerm); err != nil { return "", fmt.Errorf("failed to create directory %s: %w", reposTempPath, err) } } basePath, err := os.MkdirTemp(reposTempPath, prefix+".git") if err != nil { return "", fmt.Errorf("failed to create dir %s-*.git: %w", prefix, err) } return basePath, nil } // RemoveTemporaryPath removes the temporary path. func RemoveTemporaryPath(basePath string) error { if _, err := os.Stat(basePath); !errors.Is(err, fs.ErrNotExist) { return os.RemoveAll(basePath) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/merge/merge.go
git/merge/merge.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package merge import ( "context" "fmt" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/api" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/git/sharedrepo" "github.com/rs/zerolog/log" ) type Params struct { Author, Committer *api.Signature Message string MergeBaseSHA, TargetSHA, SourceSHA sha.SHA } // Func represents a merge method function. The concrete merge implementation functions must have this signature. type Func func( ctx context.Context, s *sharedrepo.SharedRepo, params Params, ) (mergeSHA sha.SHA, conflicts []string, err error) // Merge merges two the commits (targetSHA and sourceSHA) using the Merge method. func Merge( ctx context.Context, s *sharedrepo.SharedRepo, params Params, ) (mergeSHA sha.SHA, conflicts []string, err error) { return mergeInternal(ctx, s, params, false) } // Squash merges two the commits (targetSHA and sourceSHA) using the Squash method. func Squash( ctx context.Context, s *sharedrepo.SharedRepo, params Params, ) (mergeSHA sha.SHA, conflicts []string, err error) { return mergeInternal(ctx, s, params, true) } // mergeInternal is internal implementation of merge used for Merge and Squash methods. func mergeInternal(ctx context.Context, s *sharedrepo.SharedRepo, params Params, squash bool, ) (mergeSHA sha.SHA, conflicts []string, err error) { mergeBaseSHA := params.MergeBaseSHA targetSHA := params.TargetSHA sourceSHA := params.SourceSHA var treeSHA sha.SHA treeSHA, conflicts, err = s.MergeTree(ctx, mergeBaseSHA, targetSHA, sourceSHA) if err != nil { return sha.None, nil, fmt.Errorf("merge tree failed: %w", err) } if len(conflicts) > 0 { return sha.None, conflicts, nil } parents := make([]sha.SHA, 0, 2) parents = append(parents, targetSHA) if !squash { parents = append(parents, sourceSHA) } mergeSHA, err = s.CommitTree(ctx, params.Author, params.Committer, treeSHA, params.Message, false, parents...) if err != nil { return sha.None, nil, fmt.Errorf("commit tree failed: %w", err) } return mergeSHA, conflicts, nil } // Rebase merges two the commits (targetSHA and sourceSHA) using the Rebase method. // Commit author isn't used here - it's copied from every commit. // Commit message isn't used here // //nolint:gocognit // refactor if needed. func Rebase( ctx context.Context, s *sharedrepo.SharedRepo, params Params, ) (mergeSHA sha.SHA, conflicts []string, err error) { mergeBaseSHA := params.MergeBaseSHA targetSHA := params.TargetSHA sourceSHA := params.SourceSHA sourceSHAs, err := s.CommitSHAsForRebase(ctx, mergeBaseSHA, sourceSHA) if err != nil { return sha.None, nil, fmt.Errorf("failed to find commit list in rebase merge: %w", err) } lastCommitSHA := targetSHA lastTreeSHA, err := s.GetTreeSHA(ctx, targetSHA.String()) if err != nil { return sha.None, nil, fmt.Errorf("failed to get tree sha for target: %w", err) } for _, commitSHA := range sourceSHAs { var treeSHA sha.SHA commitInfo, err := api.GetCommit(ctx, s.Directory(), commitSHA) if err != nil { return sha.None, nil, fmt.Errorf("failed to get commit data in rebase merge: %w", err) } // rebase merge preserves the commit author (and date) and the commit message, but changes the committer. author := &commitInfo.Author message := commitInfo.Title if commitInfo.Message != "" { message += "\n\n" + commitInfo.Message } var mergeTreeMergeBaseSHA sha.SHA if len(commitInfo.ParentSHAs) > 0 { // use parent of commit as merge base to only apply changes introduced by commit. // See example usage of when --merge-base was introduced: // https://github.com/git/git/commit/66265a693e8deb3ab86577eb7f69940410044081 // // NOTE: CommitSHAsForRebase only returns non-merge commits. mergeTreeMergeBaseSHA = commitInfo.ParentSHAs[0] } treeSHA, conflicts, err = s.MergeTree(ctx, mergeTreeMergeBaseSHA, lastCommitSHA, commitSHA) if err != nil { return sha.None, nil, fmt.Errorf("failed to merge tree in rebase merge: %w", err) } if len(conflicts) > 0 { return sha.None, conflicts, nil } // Drop any commit which after being rebased would be empty. // There's two cases in which that can happen: // 1. Empty commit. // Github is dropping empty commits, so we'll do the same. // 2. The changes of the commit already exist on the target branch. // Git's `git rebase` is dropping such commits on default (and so does Github) // https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---emptydropkeepask if treeSHA.Equal(lastTreeSHA) { log.Ctx(ctx).Debug().Msgf("skipping commit %s as it's empty after rebase", commitSHA) continue } lastCommitSHA, err = s.CommitTree(ctx, author, params.Committer, treeSHA, message, false, lastCommitSHA) if err != nil { return sha.None, nil, fmt.Errorf("failed to commit tree in rebase merge: %w", err) } lastTreeSHA = treeSHA } mergeSHA = lastCommitSHA return mergeSHA, nil, nil } // FastForward points the is internal implementation of merge used for Merge and Squash methods. // Commit author and committer aren't used here. Commit message isn't used here. func FastForward( _ context.Context, _ *sharedrepo.SharedRepo, params Params, ) (mergeSHA sha.SHA, conflicts []string, err error) { mergeBaseSHA := params.MergeBaseSHA targetSHA := params.TargetSHA sourceSHA := params.SourceSHA if targetSHA != mergeBaseSHA { return sha.None, nil, errors.Conflict("Target branch has diverged from the source branch. Fast-forward not possible.") } return sourceSHA, nil, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/merge/check.go
git/merge/check.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package merge import ( "bytes" "context" "strconv" "strings" "github.com/harness/gitness/errors" "github.com/harness/gitness/git/command" "github.com/harness/gitness/git/sharedrepo" "github.com/rs/zerolog/log" ) // FindConflicts checks if two git revisions are mergeable and returns list of conflict files if they are not. func FindConflicts( ctx context.Context, repoPath, base, head string, ) (mergeable bool, treeSHA string, conflicts []string, err error) { cmd := command.New("merge-tree", command.WithFlag("--write-tree"), command.WithFlag("--name-only"), command.WithFlag("--no-messages"), command.WithFlag("--stdin")) stdin := base + " " + head stdout := bytes.NewBuffer(nil) err = cmd.Run(ctx, command.WithDir(repoPath), command.WithStdin(strings.NewReader(stdin)), command.WithStdout(stdout)) if err != nil { return false, "", nil, errors.Internalf(err, "Failed to find conflicts between %s and %s", base, head) } output := strings.TrimSpace(stdout.String()) output = strings.TrimSuffix(output, "\000") lines := strings.Split(output, "\000") if len(lines) < 2 { log.Ctx(ctx).Error().Str("output", output).Msg("Unexpected merge-tree output") return false, "", nil, errors.Internalf(nil, "Failed to find conflicts between %s and %s: Unexpected git output", base, head) } status, err := strconv.Atoi(lines[0]) if err != nil { log.Ctx(ctx).Err(err).Str("output", output).Msg("Unexpected merge status") return false, "", nil, errors.Internalf(nil, "Failed to find conflicts between %s and %s: Unexpected merge status", base, head) } if status < 0 { return false, "", nil, errors.Internalf(nil, "Failed to find conflicts between %s and %s: Operation blocked. Status=%d", base, head, status) } treeSHA = lines[1] if status == 1 { return true, treeSHA, nil, nil // all good, merge possible, no conflicts found } conflicts = sharedrepo.CleanupMergeConflicts(lines[2:]) return false, treeSHA, conflicts, nil // conflict found, list of conflicted files returned } // CommitCount returns number of commits between the two git revisions. func CommitCount( ctx context.Context, repoPath string, start, end string, ) (int, error) { arg := command.WithArg(end) if len(start) > 0 { arg = command.WithArg(start + ".." + end) } cmd := command.New("rev-list", command.WithFlag("--count"), arg) stdout := bytes.NewBuffer(nil) if err := cmd.Run(ctx, command.WithDir(repoPath), command.WithStdout(stdout)); err != nil { return 0, errors.Internal(err, "failed to rev-list in shared repo") } commitCount, err := strconv.Atoi(strings.TrimSpace(stdout.String())) if err != nil { return 0, errors.Internal(err, "failed to parse commit count from rev-list output in shared repo") } return commitCount, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/parser/text.go
git/parser/text.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package parser import ( "bufio" "errors" "fmt" "io" "unicode/utf8" ) var ( ErrLineTooLong = errors.New("line too long") ) func newUTF8Scanner(inner Scanner, modifier func([]byte) []byte) *utf8Scanner { return &utf8Scanner{ scanner: inner, modifier: modifier, } } // utf8Scanner is wrapping the provided scanner with UTF-8 checks and a modifier function. type utf8Scanner struct { nextLine []byte nextErr error modifier func([]byte) []byte scanner Scanner } func (s *utf8Scanner) Scan() bool { scanOut := s.scanner.Scan() if !scanOut { s.nextLine = nil s.nextErr = s.scanner.Err() // to stay consistent with diff parser, treat bufio.ErrTooLong as binary file if errors.Is(s.nextErr, bufio.ErrTooLong) { s.nextErr = ErrBinaryFile } return false } // finalize next bytes original := s.scanner.Bytes() // Git is using first 8000 chars, but for now we stay consistent with diff parser // https://git.kernel.org/pub/scm/git/git.git/tree/xdiff-interface.c?h=v2.30.0#n187 if !utf8.Valid(original) { s.nextLine = nil s.nextErr = ErrBinaryFile return false } // copy bytes to ensure nothing happens during modification cpy := make([]byte, len(original)) copy(cpy, original) if s.modifier != nil { cpy = s.modifier(cpy) } s.nextLine = cpy s.nextErr = nil return true } func (s *utf8Scanner) Err() error { return s.nextErr } func (s *utf8Scanner) Bytes() []byte { return s.nextLine } func (s *utf8Scanner) Text() string { return string(s.nextLine) } // ReadTextFile returns a Scanner that reads the provided text file line by line. // // The returned Scanner fulfills the following: // - If any line is larger than 64kb, the scanning fails with ErrBinaryFile // - If the reader returns invalid UTF-8, the scanning fails with ErrBinaryFile // - Line endings are returned as-is, unless overwriteLE is provided func ReadTextFile(r io.Reader, overwriteLE *string) (Scanner, string, error) { scanner := NewScannerWithPeek(r, ScanLinesWithEOF) peekOut := scanner.Peek() if !peekOut && scanner.Err() != nil { return nil, "", fmt.Errorf("unknown error while peeking first line: %w", scanner.Err()) } // get raw bytes as we don't modify the slice firstLine := scanner.Bytes() // Heuristic - get line ending of file by first line, default to LF if there's no line endings in the file lineEnding := "\n" if HasLineEndingCRLF(firstLine) { lineEnding = "\r\n" } return newUTF8Scanner(scanner, func(line []byte) []byte { // overwrite line ending if requested (unless there's no line ending - e.g. last line) if overwriteLE != nil { if HasLineEndingCRLF(line) { return append(line[:len(line)-2], []byte(*overwriteLE)...) } else if HasLineEndingLF(line) { return append(line[:len(line)-1], []byte(*overwriteLE)...) } } return line }), lineEnding, nil } func HasLineEnding(line []byte) bool { // HasLineEndingLF is superset of HasLineEndingCRLF return HasLineEndingLF(line) } func HasLineEndingLF(line []byte) bool { return len(line) >= 1 && line[len(line)-1] == '\n' } func HasLineEndingCRLF(line []byte) bool { return len(line) >= 2 && line[len(line)-2] == '\r' && line[len(line)-1] == '\n' }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/parser/scanner_test.go
git/parser/scanner_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package parser import ( "bufio" "bytes" "testing" "github.com/stretchr/testify/require" ) func Test_scannerWithPeekSmoke(t *testing.T) { scanner := NewScannerWithPeek( bytes.NewReader([]byte("l1\nl2")), bufio.ScanLines, ) out := scanner.Peek() require.True(t, out) require.NoError(t, scanner.Err()) require.Equal(t, "l1", string(scanner.Bytes())) out = scanner.Scan() require.True(t, out) require.NoError(t, scanner.Err()) require.Equal(t, "l1", string(scanner.Bytes())) out = scanner.Scan() require.True(t, out) require.NoError(t, scanner.Err()) require.Equal(t, "l2", scanner.Text()) out = scanner.Scan() require.False(t, out) require.NoError(t, scanner.Err()) require.Nil(t, scanner.Bytes()) } func Test_scannerWithPeekDualPeek(t *testing.T) { scanner := NewScannerWithPeek( bytes.NewReader([]byte("l1\nl2")), bufio.ScanLines, ) out := scanner.Peek() require.True(t, out) require.NoError(t, scanner.Err()) require.Equal(t, "l1", string(scanner.Bytes())) out = scanner.Peek() require.False(t, out) require.ErrorIs(t, scanner.Err(), ErrPeekedMoreThanOnce) require.Nil(t, scanner.Bytes()) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/git/parser/diff_raw.go
git/parser/diff_raw.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package parser import ( "bufio" "fmt" "io" "regexp" "strconv" "github.com/harness/gitness/git/sha" ) type DiffStatus byte const ( DiffStatusModified DiffStatus = 'M' DiffStatusAdded DiffStatus = 'A' DiffStatusDeleted DiffStatus = 'D' DiffStatusRenamed DiffStatus = 'R' DiffStatusCopied DiffStatus = 'C' DiffStatusType DiffStatus = 'T' ) func (s DiffStatus) String() string { return fmt.Sprintf("%c", s) } type DiffRawFile struct { OldFileMode string NewFileMode string OldBlobSHA string NewBlobSHA string Status DiffStatus OldPath string Path string } var regexpDiffRaw = regexp.MustCompile(`:(\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) (\w)(\d*)`) // DiffRaw parses raw git diff output (git diff --raw). Each entry (a line) is a changed file. // The format is: // // :100644 100644 <old-hash> <new-hash> <status>NULL<file-name>NULL // // Old-hash and new-hash are the file object hashes. Status can be A added, D deleted, M modified, R renamed, C copied. // When the status is A then the old-hash is the zero hash, when the status is D the new-hash is the zero hash. // If the status is R or C then the output is: // // :100644 100644 <old-hash> <new-hash> R<similarity index>NULL<old-name>NULL<new-name>NULL func DiffRaw(r io.Reader) ([]DiffRawFile, error) { var result []DiffRawFile scan := bufio.NewScanner(r) scan.Split(ScanZeroSeparated) for scan.Scan() { s := scan.Text() groups := regexpDiffRaw.FindStringSubmatch(s) if groups == nil { continue } var oldPath, path string if !scan.Scan() { return nil, fmt.Errorf("failed to get path for the entry: %q; err=%w", s, scan.Err()) } path = scan.Text() status := DiffStatus(groups[5][0]) switch status { case DiffStatusRenamed, DiffStatusCopied: if !scan.Scan() { return nil, fmt.Errorf("failed to get new path for the entry: %q; err=%w", s, scan.Err()) } oldPath, path = path, scan.Text() case DiffStatusAdded, DiffStatusDeleted, DiffStatusModified, DiffStatusType: default: return nil, fmt.Errorf("got invalid raw diff status=%c for entry %s %s", status, s, path) } result = append(result, DiffRawFile{ OldFileMode: groups[1], NewFileMode: groups[2], OldBlobSHA: groups[3], NewBlobSHA: groups[4], Status: status, OldPath: oldPath, Path: path, }) } if err := scan.Err(); err != nil { return nil, fmt.Errorf("failed to scan raw diff: %w", scan.Err()) } return result, nil } type BatchCheckObject struct { SHA sha.SHA // TODO: Use proper TreeNodeType Type string Size int64 } var regexpBatchCheckObject = regexp.MustCompile(`^([0-9a-f]{40,64}) (\w+) (\d+)$`) func CatFileBatchCheckAllObjects(r io.Reader) ([]BatchCheckObject, error) { var result []BatchCheckObject scan := bufio.NewScanner(r) scan.Split(ScanZeroSeparated) for scan.Scan() { line := scan.Text() matches := regexpBatchCheckObject.FindStringSubmatch(line) if len(matches) != 4 { return nil, fmt.Errorf("failed to parse line: %q", line) } sha, err := sha.New(matches[1]) if err != nil { return nil, fmt.Errorf("failed to create sha.SHA for %q: %w", matches[1], err) } sizeStr := matches[3] size, err := strconv.ParseInt(sizeStr, 10, 64) if err != nil { return nil, fmt.Errorf("failed to convert size %q to int64: %w", sizeStr, err) } result = append(result, BatchCheckObject{ SHA: sha, Type: matches[2], Size: size, }) } if err := scan.Err(); err != nil { return nil, fmt.Errorf("failed to scan cat file batch check all objects: %w", scan.Err()) } return result, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false