Provisioning: Use Nanogit for basic git operations in Github repository type (#107889)
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// basicGitBranchNameRegex is a regular expression to validate a git branch name
|
||||
// it does not cover all cases as positive lookaheads are not supported in Go's regexp
|
||||
var basicGitBranchNameRegex = regexp.MustCompile(`^[a-zA-Z0-9\-\_\/\.]+$`)
|
||||
|
||||
// IsValidGitBranchName checks if a branch name is valid.
|
||||
// It uses the following regexp `^[a-zA-Z0-9\-\_\/\.]+$` to validate the branch name with some additional checks that must satisfy the following rules:
|
||||
// 1. The branch name must have at least one character and must not be empty.
|
||||
// 2. The branch name cannot start with `/` or end with `/`, `.`, or whitespace.
|
||||
// 3. The branch name cannot contain consecutive slashes (`//`).
|
||||
// 4. The branch name cannot contain consecutive dots (`..`).
|
||||
// 5. The branch name cannot contain `@{`.
|
||||
// 6. The branch name cannot include the following characters: `~`, `^`, `:`, `?`, `*`, `[`, `\`, or `]`.
|
||||
func IsValidGitBranchName(branch string) bool {
|
||||
if !basicGitBranchNameRegex.MatchString(branch) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Additional checks for invalid patterns
|
||||
if strings.HasPrefix(branch, "/") || strings.HasSuffix(branch, "/") ||
|
||||
strings.HasSuffix(branch, ".") || strings.Contains(branch, "..") ||
|
||||
strings.Contains(branch, "//") || strings.HasSuffix(branch, ".lock") {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestIsValidGitBranchName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
branch string
|
||||
expected bool
|
||||
}{
|
||||
{"Valid branch name", "feature/add-tests", true},
|
||||
{"Valid branch name with numbers", "feature/123-add-tests", true},
|
||||
{"Valid branch name with dots", "feature.add.tests", true},
|
||||
{"Valid branch name with hyphens", "feature-add-tests", true},
|
||||
{"Valid branch name with underscores", "feature_add_tests", true},
|
||||
{"Valid branch name with mixed characters", "feature/add_tests-123", true},
|
||||
{"Starts with /", "/feature", false},
|
||||
{"Ends with /", "feature/", false},
|
||||
{"Ends with .", "feature.", false},
|
||||
{"Ends with space", "feature ", false},
|
||||
{"Contains consecutive slashes", "feature//branch", false},
|
||||
{"Contains consecutive dots", "feature..branch", false},
|
||||
{"Contains @{", "feature@{branch", false},
|
||||
{"Contains invalid character ~", "feature~branch", false},
|
||||
{"Contains invalid character ^", "feature^branch", false},
|
||||
{"Contains invalid character :", "feature:branch", false},
|
||||
{"Contains invalid character ?", "feature?branch", false},
|
||||
{"Contains invalid character *", "feature*branch", false},
|
||||
{"Contains invalid character [", "feature[branch", false},
|
||||
{"Contains invalid character ]", "feature]branch", false},
|
||||
{"Contains invalid character \\", "feature\\branch", false},
|
||||
{"Empty branch name", "", false},
|
||||
{"Only whitespace", " ", false},
|
||||
{"Single valid character", "a", true},
|
||||
{"Ends with .lock", "feature.lock", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.expected, IsValidGitBranchName(tt.branch))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package git
|
||||
|
||||
import "github.com/grafana/grafana/pkg/registry/apis/provisioning/repository"
|
||||
|
||||
// GitRepository is an interface that combines all repository capabilities
|
||||
// needed for Git repositories.
|
||||
//
|
||||
//go:generate mockery --name GitRepository --structname MockGitRepository --inpackage --filename git_repository_mock.go --with-expecter
|
||||
type GitRepository interface {
|
||||
repository.Repository
|
||||
repository.Versioned
|
||||
repository.Writer
|
||||
repository.Reader
|
||||
repository.StageableRepository
|
||||
URL() string
|
||||
Branch() string
|
||||
}
|
||||
@@ -0,0 +1,836 @@
|
||||
// Code generated by mockery v2.52.4. DO NOT EDIT.
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
context "context"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
field "k8s.io/apimachinery/pkg/util/validation/field"
|
||||
|
||||
repository "github.com/grafana/grafana/pkg/registry/apis/provisioning/repository"
|
||||
|
||||
v0alpha1 "github.com/grafana/grafana/pkg/apis/provisioning/v0alpha1"
|
||||
)
|
||||
|
||||
// MockGitRepository is an autogenerated mock type for the GitRepository type
|
||||
type MockGitRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockGitRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockGitRepository) EXPECT() *MockGitRepository_Expecter {
|
||||
return &MockGitRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Branch provides a mock function with no fields
|
||||
func (_m *MockGitRepository) Branch() string {
|
||||
ret := _m.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Branch")
|
||||
}
|
||||
|
||||
var r0 string
|
||||
if rf, ok := ret.Get(0).(func() string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_Branch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Branch'
|
||||
type MockGitRepository_Branch_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Branch is a helper method to define mock.On call
|
||||
func (_e *MockGitRepository_Expecter) Branch() *MockGitRepository_Branch_Call {
|
||||
return &MockGitRepository_Branch_Call{Call: _e.mock.On("Branch")}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Branch_Call) Run(run func()) *MockGitRepository_Branch_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Branch_Call) Return(_a0 string) *MockGitRepository_Branch_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Branch_Call) RunAndReturn(run func() string) *MockGitRepository_Branch_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// CompareFiles provides a mock function with given fields: ctx, base, ref
|
||||
func (_m *MockGitRepository) CompareFiles(ctx context.Context, base string, ref string) ([]repository.VersionedFileChange, error) {
|
||||
ret := _m.Called(ctx, base, ref)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for CompareFiles")
|
||||
}
|
||||
|
||||
var r0 []repository.VersionedFileChange
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string) ([]repository.VersionedFileChange, error)); ok {
|
||||
return rf(ctx, base, ref)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string) []repository.VersionedFileChange); ok {
|
||||
r0 = rf(ctx, base, ref)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]repository.VersionedFileChange)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
|
||||
r1 = rf(ctx, base, ref)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockGitRepository_CompareFiles_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CompareFiles'
|
||||
type MockGitRepository_CompareFiles_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// CompareFiles is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - base string
|
||||
// - ref string
|
||||
func (_e *MockGitRepository_Expecter) CompareFiles(ctx interface{}, base interface{}, ref interface{}) *MockGitRepository_CompareFiles_Call {
|
||||
return &MockGitRepository_CompareFiles_Call{Call: _e.mock.On("CompareFiles", ctx, base, ref)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_CompareFiles_Call) Run(run func(ctx context.Context, base string, ref string)) *MockGitRepository_CompareFiles_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string), args[2].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_CompareFiles_Call) Return(_a0 []repository.VersionedFileChange, _a1 error) *MockGitRepository_CompareFiles_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_CompareFiles_Call) RunAndReturn(run func(context.Context, string, string) ([]repository.VersionedFileChange, error)) *MockGitRepository_CompareFiles_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Config provides a mock function with no fields
|
||||
func (_m *MockGitRepository) Config() *v0alpha1.Repository {
|
||||
ret := _m.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Config")
|
||||
}
|
||||
|
||||
var r0 *v0alpha1.Repository
|
||||
if rf, ok := ret.Get(0).(func() *v0alpha1.Repository); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*v0alpha1.Repository)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_Config_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Config'
|
||||
type MockGitRepository_Config_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Config is a helper method to define mock.On call
|
||||
func (_e *MockGitRepository_Expecter) Config() *MockGitRepository_Config_Call {
|
||||
return &MockGitRepository_Config_Call{Call: _e.mock.On("Config")}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Config_Call) Run(run func()) *MockGitRepository_Config_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Config_Call) Return(_a0 *v0alpha1.Repository) *MockGitRepository_Config_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Config_Call) RunAndReturn(run func() *v0alpha1.Repository) *MockGitRepository_Config_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Create provides a mock function with given fields: ctx, path, ref, data, message
|
||||
func (_m *MockGitRepository) Create(ctx context.Context, path string, ref string, data []byte, message string) error {
|
||||
ret := _m.Called(ctx, path, ref, data, message)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, []byte, string) error); ok {
|
||||
r0 = rf(ctx, path, ref, data, message)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockGitRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - path string
|
||||
// - ref string
|
||||
// - data []byte
|
||||
// - message string
|
||||
func (_e *MockGitRepository_Expecter) Create(ctx interface{}, path interface{}, ref interface{}, data interface{}, message interface{}) *MockGitRepository_Create_Call {
|
||||
return &MockGitRepository_Create_Call{Call: _e.mock.On("Create", ctx, path, ref, data, message)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Create_Call) Run(run func(ctx context.Context, path string, ref string, data []byte, message string)) *MockGitRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].([]byte), args[4].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Create_Call) Return(_a0 error) *MockGitRepository_Create_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Create_Call) RunAndReturn(run func(context.Context, string, string, []byte, string) error) *MockGitRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Delete provides a mock function with given fields: ctx, path, ref, message
|
||||
func (_m *MockGitRepository) Delete(ctx context.Context, path string, ref string, message string) error {
|
||||
ret := _m.Called(ctx, path, ref, message)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Delete")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, string) error); ok {
|
||||
r0 = rf(ctx, path, ref, message)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'
|
||||
type MockGitRepository_Delete_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Delete is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - path string
|
||||
// - ref string
|
||||
// - message string
|
||||
func (_e *MockGitRepository_Expecter) Delete(ctx interface{}, path interface{}, ref interface{}, message interface{}) *MockGitRepository_Delete_Call {
|
||||
return &MockGitRepository_Delete_Call{Call: _e.mock.On("Delete", ctx, path, ref, message)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Delete_Call) Run(run func(ctx context.Context, path string, ref string, message string)) *MockGitRepository_Delete_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Delete_Call) Return(_a0 error) *MockGitRepository_Delete_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Delete_Call) RunAndReturn(run func(context.Context, string, string, string) error) *MockGitRepository_Delete_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// History provides a mock function with given fields: ctx, path, ref
|
||||
func (_m *MockGitRepository) History(ctx context.Context, path string, ref string) ([]v0alpha1.HistoryItem, error) {
|
||||
ret := _m.Called(ctx, path, ref)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for History")
|
||||
}
|
||||
|
||||
var r0 []v0alpha1.HistoryItem
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string) ([]v0alpha1.HistoryItem, error)); ok {
|
||||
return rf(ctx, path, ref)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string) []v0alpha1.HistoryItem); ok {
|
||||
r0 = rf(ctx, path, ref)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]v0alpha1.HistoryItem)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
|
||||
r1 = rf(ctx, path, ref)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockGitRepository_History_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'History'
|
||||
type MockGitRepository_History_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// History is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - path string
|
||||
// - ref string
|
||||
func (_e *MockGitRepository_Expecter) History(ctx interface{}, path interface{}, ref interface{}) *MockGitRepository_History_Call {
|
||||
return &MockGitRepository_History_Call{Call: _e.mock.On("History", ctx, path, ref)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_History_Call) Run(run func(ctx context.Context, path string, ref string)) *MockGitRepository_History_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string), args[2].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_History_Call) Return(_a0 []v0alpha1.HistoryItem, _a1 error) *MockGitRepository_History_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_History_Call) RunAndReturn(run func(context.Context, string, string) ([]v0alpha1.HistoryItem, error)) *MockGitRepository_History_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// LatestRef provides a mock function with given fields: ctx
|
||||
func (_m *MockGitRepository) LatestRef(ctx context.Context) (string, error) {
|
||||
ret := _m.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for LatestRef")
|
||||
}
|
||||
|
||||
var r0 string
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context) (string, error)); ok {
|
||||
return rf(ctx)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context) string); ok {
|
||||
r0 = rf(ctx)
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context) error); ok {
|
||||
r1 = rf(ctx)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockGitRepository_LatestRef_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LatestRef'
|
||||
type MockGitRepository_LatestRef_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// LatestRef is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockGitRepository_Expecter) LatestRef(ctx interface{}) *MockGitRepository_LatestRef_Call {
|
||||
return &MockGitRepository_LatestRef_Call{Call: _e.mock.On("LatestRef", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_LatestRef_Call) Run(run func(ctx context.Context)) *MockGitRepository_LatestRef_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_LatestRef_Call) Return(_a0 string, _a1 error) *MockGitRepository_LatestRef_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_LatestRef_Call) RunAndReturn(run func(context.Context) (string, error)) *MockGitRepository_LatestRef_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Read provides a mock function with given fields: ctx, path, ref
|
||||
func (_m *MockGitRepository) Read(ctx context.Context, path string, ref string) (*repository.FileInfo, error) {
|
||||
ret := _m.Called(ctx, path, ref)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Read")
|
||||
}
|
||||
|
||||
var r0 *repository.FileInfo
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string) (*repository.FileInfo, error)); ok {
|
||||
return rf(ctx, path, ref)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string) *repository.FileInfo); ok {
|
||||
r0 = rf(ctx, path, ref)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*repository.FileInfo)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
|
||||
r1 = rf(ctx, path, ref)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockGitRepository_Read_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Read'
|
||||
type MockGitRepository_Read_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Read is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - path string
|
||||
// - ref string
|
||||
func (_e *MockGitRepository_Expecter) Read(ctx interface{}, path interface{}, ref interface{}) *MockGitRepository_Read_Call {
|
||||
return &MockGitRepository_Read_Call{Call: _e.mock.On("Read", ctx, path, ref)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Read_Call) Run(run func(ctx context.Context, path string, ref string)) *MockGitRepository_Read_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string), args[2].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Read_Call) Return(_a0 *repository.FileInfo, _a1 error) *MockGitRepository_Read_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Read_Call) RunAndReturn(run func(context.Context, string, string) (*repository.FileInfo, error)) *MockGitRepository_Read_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ReadTree provides a mock function with given fields: ctx, ref
|
||||
func (_m *MockGitRepository) ReadTree(ctx context.Context, ref string) ([]repository.FileTreeEntry, error) {
|
||||
ret := _m.Called(ctx, ref)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ReadTree")
|
||||
}
|
||||
|
||||
var r0 []repository.FileTreeEntry
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string) ([]repository.FileTreeEntry, error)); ok {
|
||||
return rf(ctx, ref)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string) []repository.FileTreeEntry); ok {
|
||||
r0 = rf(ctx, ref)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]repository.FileTreeEntry)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = rf(ctx, ref)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockGitRepository_ReadTree_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadTree'
|
||||
type MockGitRepository_ReadTree_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ReadTree is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ref string
|
||||
func (_e *MockGitRepository_Expecter) ReadTree(ctx interface{}, ref interface{}) *MockGitRepository_ReadTree_Call {
|
||||
return &MockGitRepository_ReadTree_Call{Call: _e.mock.On("ReadTree", ctx, ref)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_ReadTree_Call) Run(run func(ctx context.Context, ref string)) *MockGitRepository_ReadTree_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_ReadTree_Call) Return(_a0 []repository.FileTreeEntry, _a1 error) *MockGitRepository_ReadTree_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_ReadTree_Call) RunAndReturn(run func(context.Context, string) ([]repository.FileTreeEntry, error)) *MockGitRepository_ReadTree_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Stage provides a mock function with given fields: ctx, opts
|
||||
func (_m *MockGitRepository) Stage(ctx context.Context, opts repository.StageOptions) (repository.StagedRepository, error) {
|
||||
ret := _m.Called(ctx, opts)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Stage")
|
||||
}
|
||||
|
||||
var r0 repository.StagedRepository
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, repository.StageOptions) (repository.StagedRepository, error)); ok {
|
||||
return rf(ctx, opts)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context, repository.StageOptions) repository.StagedRepository); ok {
|
||||
r0 = rf(ctx, opts)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(repository.StagedRepository)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context, repository.StageOptions) error); ok {
|
||||
r1 = rf(ctx, opts)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockGitRepository_Stage_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Stage'
|
||||
type MockGitRepository_Stage_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Stage is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - opts repository.StageOptions
|
||||
func (_e *MockGitRepository_Expecter) Stage(ctx interface{}, opts interface{}) *MockGitRepository_Stage_Call {
|
||||
return &MockGitRepository_Stage_Call{Call: _e.mock.On("Stage", ctx, opts)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Stage_Call) Run(run func(ctx context.Context, opts repository.StageOptions)) *MockGitRepository_Stage_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(repository.StageOptions))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Stage_Call) Return(_a0 repository.StagedRepository, _a1 error) *MockGitRepository_Stage_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Stage_Call) RunAndReturn(run func(context.Context, repository.StageOptions) (repository.StagedRepository, error)) *MockGitRepository_Stage_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Test provides a mock function with given fields: ctx
|
||||
func (_m *MockGitRepository) Test(ctx context.Context) (*v0alpha1.TestResults, error) {
|
||||
ret := _m.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Test")
|
||||
}
|
||||
|
||||
var r0 *v0alpha1.TestResults
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context) (*v0alpha1.TestResults, error)); ok {
|
||||
return rf(ctx)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context) *v0alpha1.TestResults); ok {
|
||||
r0 = rf(ctx)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*v0alpha1.TestResults)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context) error); ok {
|
||||
r1 = rf(ctx)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockGitRepository_Test_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Test'
|
||||
type MockGitRepository_Test_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Test is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockGitRepository_Expecter) Test(ctx interface{}) *MockGitRepository_Test_Call {
|
||||
return &MockGitRepository_Test_Call{Call: _e.mock.On("Test", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Test_Call) Run(run func(ctx context.Context)) *MockGitRepository_Test_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Test_Call) Return(_a0 *v0alpha1.TestResults, _a1 error) *MockGitRepository_Test_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Test_Call) RunAndReturn(run func(context.Context) (*v0alpha1.TestResults, error)) *MockGitRepository_Test_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// URL provides a mock function with no fields
|
||||
func (_m *MockGitRepository) URL() string {
|
||||
ret := _m.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for URL")
|
||||
}
|
||||
|
||||
var r0 string
|
||||
if rf, ok := ret.Get(0).(func() string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_URL_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'URL'
|
||||
type MockGitRepository_URL_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// URL is a helper method to define mock.On call
|
||||
func (_e *MockGitRepository_Expecter) URL() *MockGitRepository_URL_Call {
|
||||
return &MockGitRepository_URL_Call{Call: _e.mock.On("URL")}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_URL_Call) Run(run func()) *MockGitRepository_URL_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_URL_Call) Return(_a0 string) *MockGitRepository_URL_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_URL_Call) RunAndReturn(run func() string) *MockGitRepository_URL_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Update provides a mock function with given fields: ctx, path, ref, data, message
|
||||
func (_m *MockGitRepository) Update(ctx context.Context, path string, ref string, data []byte, message string) error {
|
||||
ret := _m.Called(ctx, path, ref, data, message)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Update")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, []byte, string) error); ok {
|
||||
r0 = rf(ctx, path, ref, data, message)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_Update_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Update'
|
||||
type MockGitRepository_Update_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Update is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - path string
|
||||
// - ref string
|
||||
// - data []byte
|
||||
// - message string
|
||||
func (_e *MockGitRepository_Expecter) Update(ctx interface{}, path interface{}, ref interface{}, data interface{}, message interface{}) *MockGitRepository_Update_Call {
|
||||
return &MockGitRepository_Update_Call{Call: _e.mock.On("Update", ctx, path, ref, data, message)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Update_Call) Run(run func(ctx context.Context, path string, ref string, data []byte, message string)) *MockGitRepository_Update_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].([]byte), args[4].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Update_Call) Return(_a0 error) *MockGitRepository_Update_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Update_Call) RunAndReturn(run func(context.Context, string, string, []byte, string) error) *MockGitRepository_Update_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Validate provides a mock function with no fields
|
||||
func (_m *MockGitRepository) Validate() field.ErrorList {
|
||||
ret := _m.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Validate")
|
||||
}
|
||||
|
||||
var r0 field.ErrorList
|
||||
if rf, ok := ret.Get(0).(func() field.ErrorList); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(field.ErrorList)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_Validate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Validate'
|
||||
type MockGitRepository_Validate_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Validate is a helper method to define mock.On call
|
||||
func (_e *MockGitRepository_Expecter) Validate() *MockGitRepository_Validate_Call {
|
||||
return &MockGitRepository_Validate_Call{Call: _e.mock.On("Validate")}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Validate_Call) Run(run func()) *MockGitRepository_Validate_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Validate_Call) Return(_a0 field.ErrorList) *MockGitRepository_Validate_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Validate_Call) RunAndReturn(run func() field.ErrorList) *MockGitRepository_Validate_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Write provides a mock function with given fields: ctx, path, ref, data, message
|
||||
func (_m *MockGitRepository) Write(ctx context.Context, path string, ref string, data []byte, message string) error {
|
||||
ret := _m.Called(ctx, path, ref, data, message)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Write")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string, string, []byte, string) error); ok {
|
||||
r0 = rf(ctx, path, ref, data, message)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockGitRepository_Write_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Write'
|
||||
type MockGitRepository_Write_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Write is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - path string
|
||||
// - ref string
|
||||
// - data []byte
|
||||
// - message string
|
||||
func (_e *MockGitRepository_Expecter) Write(ctx interface{}, path interface{}, ref interface{}, data interface{}, message interface{}) *MockGitRepository_Write_Call {
|
||||
return &MockGitRepository_Write_Call{Call: _e.mock.On("Write", ctx, path, ref, data, message)}
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Write_Call) Run(run func(ctx context.Context, path string, ref string, data []byte, message string)) *MockGitRepository_Write_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].([]byte), args[4].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Write_Call) Return(_a0 error) *MockGitRepository_Write_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockGitRepository_Write_Call) RunAndReturn(run func(context.Context, string, string, []byte, string) error) *MockGitRepository_Write_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// NewMockGitRepository creates a new instance of MockGitRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockGitRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockGitRepository {
|
||||
mock := &MockGitRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() { mock.AssertExpectations(t) })
|
||||
|
||||
return mock
|
||||
}
|
||||
@@ -0,0 +1,734 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
|
||||
"github.com/grafana/grafana-app-sdk/logging"
|
||||
provisioning "github.com/grafana/grafana/pkg/apis/provisioning/v0alpha1"
|
||||
"github.com/grafana/grafana/pkg/registry/apis/provisioning/repository"
|
||||
"github.com/grafana/grafana/pkg/registry/apis/provisioning/safepath"
|
||||
"github.com/grafana/nanogit"
|
||||
"github.com/grafana/nanogit/log"
|
||||
"github.com/grafana/nanogit/options"
|
||||
"github.com/grafana/nanogit/protocol"
|
||||
"github.com/grafana/nanogit/protocol/hash"
|
||||
)
|
||||
|
||||
type RepositoryConfig struct {
|
||||
URL string
|
||||
Branch string
|
||||
Token string
|
||||
EncryptedToken []byte
|
||||
Path string
|
||||
}
|
||||
|
||||
// Make sure all public functions of this struct call the (*gitRepository).logger function, to ensure the Git repo details are included.
|
||||
type gitRepository struct {
|
||||
config *provisioning.Repository
|
||||
gitConfig RepositoryConfig
|
||||
client nanogit.Client
|
||||
}
|
||||
|
||||
func NewGitRepository(
|
||||
ctx context.Context,
|
||||
config *provisioning.Repository,
|
||||
gitConfig RepositoryConfig,
|
||||
) (GitRepository, error) {
|
||||
var opts []options.Option
|
||||
if len(gitConfig.Token) > 0 {
|
||||
opts = append(opts, options.WithBasicAuth("git", gitConfig.Token))
|
||||
}
|
||||
|
||||
client, err := nanogit.NewHTTPClient(gitConfig.URL, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create nanogit client: %w", err)
|
||||
}
|
||||
|
||||
return &gitRepository{
|
||||
config: config,
|
||||
gitConfig: gitConfig,
|
||||
client: client,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) URL() string {
|
||||
return r.gitConfig.URL
|
||||
}
|
||||
|
||||
func (r *gitRepository) Branch() string {
|
||||
return r.gitConfig.Branch
|
||||
}
|
||||
|
||||
func (r *gitRepository) Config() *provisioning.Repository {
|
||||
return r.config
|
||||
}
|
||||
|
||||
// Validate implements provisioning.Repository.
|
||||
func (r *gitRepository) Validate() (list field.ErrorList) {
|
||||
cfg := r.gitConfig
|
||||
|
||||
t := string(r.config.Spec.Type)
|
||||
if cfg.URL == "" {
|
||||
list = append(list, field.Required(field.NewPath("spec", t, "url"), "a git url is required"))
|
||||
} else {
|
||||
if !isValidGitURL(cfg.URL) {
|
||||
list = append(list, field.Invalid(field.NewPath("spec", t, "url"), cfg.URL, "invalid git URL format"))
|
||||
}
|
||||
}
|
||||
if cfg.Branch == "" {
|
||||
list = append(list, field.Required(field.NewPath("spec", t, "branch"), "a git branch is required"))
|
||||
} else if !IsValidGitBranchName(cfg.Branch) {
|
||||
list = append(list, field.Invalid(field.NewPath("spec", t, "branch"), cfg.Branch, "invalid branch name"))
|
||||
}
|
||||
|
||||
// If the repository has workflows, we require a token or encrypted token
|
||||
if len(r.config.Spec.Workflows) > 0 {
|
||||
if cfg.Token == "" && len(cfg.EncryptedToken) == 0 {
|
||||
list = append(list, field.Required(field.NewPath("spec", t, "token"), "a git access token is required"))
|
||||
}
|
||||
}
|
||||
|
||||
if err := safepath.IsSafe(cfg.Path); err != nil {
|
||||
list = append(list, field.Invalid(field.NewPath("spec", t, "path"), cfg.Path, err.Error()))
|
||||
}
|
||||
|
||||
if safepath.IsAbs(cfg.Path) {
|
||||
list = append(list, field.Invalid(field.NewPath("spec", t, "path"), cfg.Path, "path must be relative"))
|
||||
}
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
func isValidGitURL(gitURL string) bool {
|
||||
// Parse URL
|
||||
parsed, err := url.Parse(gitURL)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Must be HTTPS
|
||||
if parsed.Scheme != "https" {
|
||||
return false
|
||||
}
|
||||
|
||||
// Must have a host
|
||||
if parsed.Host == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// Must have a path
|
||||
if parsed.Path == "" || parsed.Path == "/" {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Test implements provisioning.Repository.
|
||||
func (r *gitRepository) Test(ctx context.Context) (*provisioning.TestResults, error) {
|
||||
ctx, _ = r.logger(ctx, "")
|
||||
|
||||
t := string(r.config.Spec.Type)
|
||||
|
||||
if ok, err := r.client.IsAuthorized(ctx); err != nil || !ok {
|
||||
detail := "not authorized"
|
||||
if err != nil {
|
||||
detail = fmt.Sprintf("failed check if authorized: %v", err)
|
||||
}
|
||||
|
||||
return &provisioning.TestResults{
|
||||
Code: http.StatusBadRequest,
|
||||
Success: false,
|
||||
Errors: []provisioning.ErrorDetails{{
|
||||
Type: metav1.CauseTypeFieldValueInvalid,
|
||||
Field: field.NewPath("spec", t, "token").String(),
|
||||
Detail: detail,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ok, err := r.client.RepoExists(ctx); err != nil || !ok {
|
||||
detail := "repository not found"
|
||||
if err != nil {
|
||||
detail = fmt.Sprintf("failed check if repository exists: %v", err)
|
||||
}
|
||||
|
||||
return &provisioning.TestResults{
|
||||
Code: http.StatusBadRequest,
|
||||
Success: false,
|
||||
Errors: []provisioning.ErrorDetails{{
|
||||
Type: metav1.CauseTypeFieldValueInvalid,
|
||||
Field: field.NewPath("spec", t, "url").String(),
|
||||
Detail: detail,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Test basic connectivity by getting the branch reference
|
||||
_, err := r.client.GetRef(ctx, fmt.Sprintf("refs/heads/%s", r.gitConfig.Branch))
|
||||
if err != nil {
|
||||
detail := "branch not found"
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return &provisioning.TestResults{
|
||||
Code: http.StatusBadRequest,
|
||||
Success: false,
|
||||
Errors: []provisioning.ErrorDetails{{
|
||||
Type: metav1.CauseTypeFieldValueInvalid,
|
||||
Field: field.NewPath("spec", t, "branch").String(),
|
||||
Detail: detail,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
detail = fmt.Sprintf("failed to check if branch exists: %v", err)
|
||||
|
||||
return &provisioning.TestResults{
|
||||
Code: http.StatusBadRequest,
|
||||
Success: false,
|
||||
Errors: []provisioning.ErrorDetails{{
|
||||
Type: metav1.CauseTypeFieldValueInvalid,
|
||||
Field: field.NewPath("spec", t, "branch").String(),
|
||||
Detail: detail,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &provisioning.TestResults{
|
||||
Code: http.StatusOK,
|
||||
Success: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Read implements provisioning.Repository.
|
||||
func (r *gitRepository) Read(ctx context.Context, filePath, ref string) (*repository.FileInfo, error) {
|
||||
ctx, _ = r.logger(ctx, ref)
|
||||
finalPath := safepath.Join(r.gitConfig.Path, filePath)
|
||||
|
||||
// Resolve ref to commit hash
|
||||
refHash, err := r.resolveRefToHash(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// get root hash
|
||||
// TODO: Fix GetTree in nanogit as it does not work commit hash
|
||||
commit, err := r.client.GetCommit(ctx, refHash)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get commit: %w", err)
|
||||
}
|
||||
|
||||
// Check if the path represents a directory
|
||||
if safepath.IsDir(filePath) {
|
||||
tree, err := r.client.GetTreeByPath(ctx, commit.Tree, finalPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return nil, repository.ErrFileNotFound
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("get tree by path: %w", err)
|
||||
}
|
||||
|
||||
return &repository.FileInfo{
|
||||
Path: filePath,
|
||||
Ref: refHash.String(),
|
||||
Hash: tree.Hash.String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
blob, err := r.client.GetBlobByPath(ctx, commit.Tree, finalPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return nil, repository.ErrFileNotFound
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("read blob: %w", err)
|
||||
}
|
||||
|
||||
return &repository.FileInfo{
|
||||
Path: filePath,
|
||||
Ref: ref,
|
||||
Data: blob.Content,
|
||||
Hash: blob.Hash.String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) ReadTree(ctx context.Context, ref string) ([]repository.FileTreeEntry, error) {
|
||||
ctx, _ = r.logger(ctx, ref)
|
||||
|
||||
// Resolve ref to commit hash
|
||||
refHash, err := r.resolveRefToHash(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get flat tree using nanogit's GetFlatTree
|
||||
tree, err := r.client.GetFlatTree(ctx, refHash)
|
||||
if err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return nil, repository.ErrRefNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get flat tree: %w", err)
|
||||
}
|
||||
|
||||
entries := make([]repository.FileTreeEntry, 0, len(tree.Entries))
|
||||
for _, entry := range tree.Entries {
|
||||
isBlob := entry.Type == protocol.ObjectTypeBlob
|
||||
// Apply path prefix filtering
|
||||
relativePath, err := safepath.RelativeTo(entry.Path, r.gitConfig.Path)
|
||||
if err != nil {
|
||||
// File is outside configured path, skip it
|
||||
continue
|
||||
}
|
||||
|
||||
filePath := relativePath
|
||||
if !isBlob && !safepath.IsDir(filePath) {
|
||||
filePath = filePath + "/"
|
||||
}
|
||||
|
||||
converted := repository.FileTreeEntry{
|
||||
Path: filePath,
|
||||
// TODO: Remove size from repository.FileTreeEntry. We don't need it per se.
|
||||
Size: 0, // FlatTreeEntry doesn't have size, set to 0
|
||||
Hash: entry.Hash.String(),
|
||||
Blob: isBlob,
|
||||
}
|
||||
entries = append(entries, converted)
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) Create(ctx context.Context, path, ref string, data []byte, comment string) error {
|
||||
if ref == "" {
|
||||
ref = r.gitConfig.Branch
|
||||
}
|
||||
ctx, _ = r.logger(ctx, ref)
|
||||
branchRef, err := r.ensureBranchExists(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
writer, err := r.client.NewStagedWriter(ctx, branchRef)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create staged writer: %w", err)
|
||||
}
|
||||
|
||||
if err := r.create(ctx, path, data, writer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.commitAndPush(ctx, writer, comment)
|
||||
}
|
||||
|
||||
func (r *gitRepository) create(ctx context.Context, path string, data []byte, writer nanogit.StagedWriter) error {
|
||||
finalPath := safepath.Join(r.gitConfig.Path, path)
|
||||
// Create .keep file if it is a directory
|
||||
if safepath.IsDir(finalPath) {
|
||||
if data != nil {
|
||||
return apierrors.NewBadRequest("data cannot be provided for a directory")
|
||||
}
|
||||
|
||||
finalPath = safepath.Join(finalPath, ".keep")
|
||||
data = []byte{}
|
||||
}
|
||||
|
||||
if _, err := writer.CreateBlob(ctx, finalPath, data); err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectAlreadyExists) {
|
||||
return repository.ErrFileAlreadyExists
|
||||
}
|
||||
|
||||
return fmt.Errorf("create blob: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) Update(ctx context.Context, path, ref string, data []byte, comment string) error {
|
||||
if ref == "" {
|
||||
ref = r.gitConfig.Branch
|
||||
}
|
||||
ctx, _ = r.logger(ctx, ref)
|
||||
|
||||
// Check if trying to update a directory
|
||||
if safepath.IsDir(path) {
|
||||
return apierrors.NewBadRequest("cannot update a directory")
|
||||
}
|
||||
|
||||
branchRef, err := r.ensureBranchExists(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Create a staged writer
|
||||
writer, err := r.client.NewStagedWriter(ctx, branchRef)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create staged writer: %w", err)
|
||||
}
|
||||
|
||||
if err := r.update(ctx, path, data, writer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.commitAndPush(ctx, writer, comment)
|
||||
}
|
||||
|
||||
func (r *gitRepository) update(ctx context.Context, path string, data []byte, writer nanogit.StagedWriter) error {
|
||||
// Check if trying to update a directory
|
||||
if safepath.IsDir(path) {
|
||||
return apierrors.NewBadRequest("cannot update a directory")
|
||||
}
|
||||
|
||||
finalPath := safepath.Join(r.gitConfig.Path, path)
|
||||
if _, err := writer.UpdateBlob(ctx, finalPath, data); err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return repository.ErrFileNotFound
|
||||
}
|
||||
|
||||
return fmt.Errorf("update blob: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) Write(ctx context.Context, path string, ref string, data []byte, message string) error {
|
||||
if ref == "" {
|
||||
ref = r.gitConfig.Branch
|
||||
}
|
||||
|
||||
ctx, _ = r.logger(ctx, ref)
|
||||
info, err := r.Read(ctx, path, ref)
|
||||
if err != nil && !(errors.Is(err, repository.ErrFileNotFound)) {
|
||||
return fmt.Errorf("check if file exists before writing: %w", err)
|
||||
}
|
||||
if err == nil {
|
||||
// If the value already exists and is the same, we don't need to do anything
|
||||
if bytes.Equal(info.Data, data) {
|
||||
return nil
|
||||
}
|
||||
return r.Update(ctx, path, ref, data, message)
|
||||
}
|
||||
|
||||
return r.Create(ctx, path, ref, data, message)
|
||||
}
|
||||
|
||||
func (r *gitRepository) Delete(ctx context.Context, path, ref, comment string) error {
|
||||
if ref == "" {
|
||||
ref = r.gitConfig.Branch
|
||||
}
|
||||
ctx, _ = r.logger(ctx, ref)
|
||||
|
||||
branchRef, err := r.ensureBranchExists(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Create a staged writer
|
||||
writer, err := r.client.NewStagedWriter(ctx, branchRef)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create staged writer: %w", err)
|
||||
}
|
||||
|
||||
if err := r.delete(ctx, path, writer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.commitAndPush(ctx, writer, comment)
|
||||
}
|
||||
|
||||
func (r *gitRepository) delete(ctx context.Context, path string, writer nanogit.StagedWriter) error {
|
||||
finalPath := safepath.Join(r.gitConfig.Path, path)
|
||||
// Check if it's a directory - use DeleteTree for directories, DeleteBlob for files
|
||||
if safepath.IsDir(path) {
|
||||
trimmed := strings.TrimSuffix(finalPath, "/")
|
||||
if _, err := writer.DeleteTree(ctx, trimmed); err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return repository.ErrFileNotFound
|
||||
}
|
||||
return fmt.Errorf("delete tree: %w", err)
|
||||
}
|
||||
} else {
|
||||
if _, err := writer.DeleteBlob(ctx, finalPath); err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return repository.ErrFileNotFound
|
||||
}
|
||||
return fmt.Errorf("delete blob: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) History(_ context.Context, _ string, _ string) ([]provisioning.HistoryItem, error) {
|
||||
return nil, &apierrors.StatusError{ErrStatus: metav1.Status{
|
||||
Status: metav1.StatusFailure,
|
||||
Code: http.StatusNotImplemented,
|
||||
Reason: metav1.StatusReasonMethodNotAllowed,
|
||||
Message: "history is not supported for pure git repositories",
|
||||
}}
|
||||
}
|
||||
|
||||
func (r *gitRepository) LatestRef(ctx context.Context) (string, error) {
|
||||
ctx, _ = r.logger(ctx, "")
|
||||
branchRef, err := r.client.GetRef(ctx, fmt.Sprintf("refs/heads/%s", r.gitConfig.Branch))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("get branch ref: %w", err)
|
||||
}
|
||||
|
||||
return branchRef.Hash.String(), nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) CompareFiles(ctx context.Context, base, ref string) ([]repository.VersionedFileChange, error) {
|
||||
if base == "" && ref == "" {
|
||||
return nil, fmt.Errorf("base and ref cannot be empty")
|
||||
}
|
||||
if ref == "" {
|
||||
return nil, fmt.Errorf("ref cannot be empty")
|
||||
}
|
||||
|
||||
ctx, logger := r.logger(ctx, ref)
|
||||
|
||||
// Resolve base ref to hash
|
||||
var baseHash hash.Hash
|
||||
if base != "" {
|
||||
var err error
|
||||
baseHash, err = r.resolveRefToHash(ctx, base)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve base ref: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve ref to hash
|
||||
refHash, err := r.resolveRefToHash(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve ref: %w", err)
|
||||
}
|
||||
|
||||
// Get commit hashes for base and ref
|
||||
// Compare commits using nanogit
|
||||
files, err := r.client.CompareCommits(ctx, baseHash, refHash)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("compare commits: %w", err)
|
||||
}
|
||||
|
||||
changes := make([]repository.VersionedFileChange, 0)
|
||||
for _, f := range files {
|
||||
switch f.Status {
|
||||
case protocol.FileStatusAdded:
|
||||
currentPath, err := safepath.RelativeTo(f.Path, r.gitConfig.Path)
|
||||
if err != nil {
|
||||
// do nothing as it's outside of configured path
|
||||
continue
|
||||
}
|
||||
|
||||
changes = append(changes, repository.VersionedFileChange{
|
||||
Path: currentPath,
|
||||
Ref: ref,
|
||||
Action: repository.FileActionCreated,
|
||||
})
|
||||
case protocol.FileStatusModified:
|
||||
currentPath, err := safepath.RelativeTo(f.Path, r.gitConfig.Path)
|
||||
if err != nil {
|
||||
// do nothing as it's outside of configured path
|
||||
continue
|
||||
}
|
||||
|
||||
changes = append(changes, repository.VersionedFileChange{
|
||||
Path: currentPath,
|
||||
Ref: ref,
|
||||
Action: repository.FileActionUpdated,
|
||||
})
|
||||
case protocol.FileStatusDeleted:
|
||||
currentPath, err := safepath.RelativeTo(f.Path, r.gitConfig.Path)
|
||||
if err != nil {
|
||||
// do nothing as it's outside of configured path
|
||||
continue
|
||||
}
|
||||
|
||||
changes = append(changes, repository.VersionedFileChange{
|
||||
Ref: ref,
|
||||
PreviousRef: base,
|
||||
Path: currentPath,
|
||||
PreviousPath: currentPath,
|
||||
Action: repository.FileActionDeleted,
|
||||
})
|
||||
case protocol.FileStatusTypeChanged:
|
||||
// Handle type changes as modifications
|
||||
currentPath, err := safepath.RelativeTo(f.Path, r.gitConfig.Path)
|
||||
if err != nil {
|
||||
// do nothing as it's outside of configured path
|
||||
continue
|
||||
}
|
||||
|
||||
changes = append(changes, repository.VersionedFileChange{
|
||||
Path: currentPath,
|
||||
Ref: ref,
|
||||
Action: repository.FileActionUpdated,
|
||||
})
|
||||
default:
|
||||
logger.Error("ignore unhandled file", "file", f.Path, "status", string(f.Status))
|
||||
}
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) Stage(ctx context.Context, opts repository.StageOptions) (repository.StagedRepository, error) {
|
||||
return NewStagedGitRepository(ctx, r, opts)
|
||||
}
|
||||
|
||||
// resolveRefToHash resolves a ref (branch name or commit hash) to a commit hash
|
||||
func (r *gitRepository) resolveRefToHash(ctx context.Context, ref string) (hash.Hash, error) {
|
||||
// Use default branch if ref is empty
|
||||
if ref == "" {
|
||||
ref = r.gitConfig.Branch
|
||||
}
|
||||
|
||||
// Try to parse ref as a hash first
|
||||
refHash, err := hash.FromHex(ref)
|
||||
if err == nil && refHash != hash.Zero {
|
||||
// Valid hash, return it
|
||||
return refHash, nil
|
||||
}
|
||||
|
||||
// Prefix ref with refs/heads/
|
||||
ref = fmt.Sprintf("refs/heads/%s", ref)
|
||||
|
||||
// Not a valid hash, try to resolve as a branch reference
|
||||
branchRef, err := r.client.GetRef(ctx, ref)
|
||||
if err != nil {
|
||||
if errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return hash.Zero, fmt.Errorf("ref not found: %s: %w", ref, repository.ErrRefNotFound)
|
||||
}
|
||||
return hash.Zero, fmt.Errorf("get ref %s: %w", ref, err)
|
||||
}
|
||||
|
||||
return branchRef.Hash, nil
|
||||
}
|
||||
|
||||
// ensureBranchExists checks if a branch exists and creates it if it doesn't,
|
||||
// returning the branch reference to avoid duplicate GetRef calls
|
||||
func (r *gitRepository) ensureBranchExists(ctx context.Context, branchName string) (nanogit.Ref, error) {
|
||||
if !IsValidGitBranchName(branchName) {
|
||||
return nanogit.Ref{}, &apierrors.StatusError{
|
||||
ErrStatus: metav1.Status{
|
||||
Code: http.StatusBadRequest,
|
||||
Message: "invalid branch name",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Check if branch exists by trying to get the branch reference
|
||||
branchRef, err := r.client.GetRef(ctx, fmt.Sprintf("refs/heads/%s", branchName))
|
||||
if err == nil {
|
||||
// Branch exists, return it
|
||||
logging.FromContext(ctx).Info("branch already exists", "branch", branchName)
|
||||
return branchRef, nil
|
||||
}
|
||||
|
||||
// If error is not "ref not found", return the error
|
||||
if !errors.Is(err, nanogit.ErrObjectNotFound) {
|
||||
return nanogit.Ref{}, fmt.Errorf("check branch exists: %w", err)
|
||||
}
|
||||
|
||||
// Branch doesn't exist, create it based on the configured branch
|
||||
srcBranch := r.gitConfig.Branch
|
||||
srcRef, err := r.client.GetRef(ctx, fmt.Sprintf("refs/heads/%s", srcBranch))
|
||||
if err != nil {
|
||||
return nanogit.Ref{}, fmt.Errorf("get source branch ref: %w", err)
|
||||
}
|
||||
|
||||
// Create the new branch reference
|
||||
newRef := nanogit.Ref{
|
||||
Name: fmt.Sprintf("refs/heads/%s", branchName),
|
||||
Hash: srcRef.Hash,
|
||||
}
|
||||
|
||||
if err := r.client.CreateRef(ctx, newRef); err != nil {
|
||||
return nanogit.Ref{}, fmt.Errorf("create branch: %w", err)
|
||||
}
|
||||
|
||||
return newRef, nil
|
||||
}
|
||||
|
||||
// createSignature creates author and committer signatures using the context signature if available,
|
||||
// falling back to default Grafana signature
|
||||
func (r *gitRepository) createSignature(ctx context.Context) (nanogit.Author, nanogit.Committer) {
|
||||
author := nanogit.Author{
|
||||
Name: "Grafana",
|
||||
Email: "noreply@grafana.com",
|
||||
Time: time.Now(),
|
||||
}
|
||||
committer := nanogit.Committer{
|
||||
Name: "Grafana",
|
||||
Email: "noreply@grafana.com",
|
||||
Time: time.Now(),
|
||||
}
|
||||
|
||||
// Use signature from context if available
|
||||
if sig := repository.GetAuthorSignature(ctx); sig != nil && sig.Name != "" {
|
||||
author.Name = sig.Name
|
||||
author.Email = sig.Email
|
||||
author.Time = sig.When
|
||||
committer.Name = sig.Name
|
||||
committer.Email = sig.Email
|
||||
committer.Time = sig.When
|
||||
}
|
||||
|
||||
if author.Time.IsZero() {
|
||||
author.Time = time.Now()
|
||||
committer.Time = time.Now()
|
||||
}
|
||||
|
||||
return author, committer
|
||||
}
|
||||
|
||||
func (r *gitRepository) commit(ctx context.Context, writer nanogit.StagedWriter, comment string) error {
|
||||
author, committer := r.createSignature(ctx)
|
||||
if _, err := writer.Commit(ctx, comment, author, committer); err != nil {
|
||||
return fmt.Errorf("commit changes: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) commitAndPush(ctx context.Context, writer nanogit.StagedWriter, comment string) error {
|
||||
if err := r.commit(ctx, writer, comment); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := writer.Push(ctx); err != nil {
|
||||
return fmt.Errorf("push changes: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *gitRepository) logger(ctx context.Context, ref string) (context.Context, logging.Logger) {
|
||||
logger := logging.FromContext(ctx)
|
||||
|
||||
type containsGit int
|
||||
var containsGitKey containsGit
|
||||
if ctx.Value(containsGitKey) != nil {
|
||||
return ctx, logging.FromContext(ctx)
|
||||
}
|
||||
|
||||
if ref == "" {
|
||||
ref = r.gitConfig.Branch
|
||||
}
|
||||
logger = logger.With(slog.Group("git_repository", "url", r.gitConfig.URL, "ref", ref, "nanogit", true))
|
||||
ctx = logging.Context(ctx, logger)
|
||||
// We want to ensure we don't add multiple git_repository keys. With doesn't deduplicate the keys...
|
||||
ctx = context.WithValue(ctx, containsGitKey, true)
|
||||
|
||||
ctx = log.ToContext(ctx, logger)
|
||||
|
||||
return ctx, logger
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,186 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/grafana/grafana/pkg/registry/apis/provisioning/repository"
|
||||
"github.com/grafana/grafana/pkg/registry/apis/provisioning/safepath"
|
||||
"github.com/grafana/nanogit"
|
||||
)
|
||||
|
||||
// stagedGitRepository implements repository.ClonedRepository by wrapping a gitRepository
|
||||
// FIXME: this is a hack until we can delete the go-git cloned implementation
|
||||
// once that happens we could do more magic here.
|
||||
type stagedGitRepository struct {
|
||||
*gitRepository
|
||||
opts repository.StageOptions
|
||||
writer nanogit.StagedWriter
|
||||
}
|
||||
|
||||
func NewStagedGitRepository(ctx context.Context, repo *gitRepository, opts repository.StageOptions) (repository.StagedRepository, error) {
|
||||
if opts.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, opts.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
ref, err := repo.client.GetRef(ctx, "refs/heads/"+repo.gitConfig.Branch)
|
||||
if err != nil {
|
||||
// TODO: opts.CreateIfNotExists doesn't make sense in the context of the staged repository
|
||||
// because we only support the branch that is passed in.
|
||||
// we should probably add branch to the repository.CloneOptions which should be repurposed
|
||||
// as some kind of branch creation options.
|
||||
return nil, err
|
||||
}
|
||||
|
||||
writer, err := repo.client.NewStagedWriter(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build staged writer: %w", err)
|
||||
}
|
||||
|
||||
return &stagedGitRepository{
|
||||
gitRepository: repo,
|
||||
opts: opts,
|
||||
writer: writer,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) Read(ctx context.Context, path, ref string) (*repository.FileInfo, error) {
|
||||
if ref != "" && ref != r.gitConfig.Branch {
|
||||
return nil, errors.New("ref is not supported for staged repository")
|
||||
}
|
||||
|
||||
// TODO: the read in the cloned is simplied used to check if a folder exists,
|
||||
// We should fix the usage and the interface so that it's not needed to load the entire blob
|
||||
return r.gitRepository.Read(ctx, path, ref)
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) ReadTree(ctx context.Context, ref string) ([]repository.FileTreeEntry, error) {
|
||||
if ref != "" && ref != r.gitConfig.Branch {
|
||||
return nil, errors.New("ref is not supported for staged repository")
|
||||
}
|
||||
|
||||
ref = ""
|
||||
// TODO: I think we don't need this for cloned repository currently.
|
||||
// we should probably remove it from the interface or construct this tree from the writer itself
|
||||
|
||||
return r.gitRepository.ReadTree(ctx, ref)
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) Create(ctx context.Context, path, ref string, data []byte, message string) error {
|
||||
if ref != "" && ref != r.gitConfig.Branch {
|
||||
return errors.New("ref is not supported for staged repository")
|
||||
}
|
||||
|
||||
if err := r.create(ctx, path, data, r.writer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := r.commit(ctx, r.writer, message); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if r.opts.PushOnWrites {
|
||||
return r.Push(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) blobExists(ctx context.Context, path string) (bool, error) {
|
||||
if r.gitConfig.Path != "" {
|
||||
path = safepath.Join(r.gitConfig.Path, path)
|
||||
}
|
||||
return r.writer.BlobExists(ctx, path)
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) Write(ctx context.Context, path, ref string, data []byte, message string) error {
|
||||
if ref != "" && ref != r.gitConfig.Branch {
|
||||
return errors.New("ref is not supported for staged repository")
|
||||
}
|
||||
|
||||
exists, err := r.blobExists(ctx, path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check if file exists: %w", err)
|
||||
}
|
||||
|
||||
if exists {
|
||||
if err := r.update(ctx, path, data, r.writer); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := r.create(ctx, path, data, r.writer); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := r.commit(ctx, r.writer, message); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if r.opts.PushOnWrites {
|
||||
return r.Push(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) Update(ctx context.Context, path, ref string, data []byte, message string) error {
|
||||
if ref != "" && ref != r.gitConfig.Branch {
|
||||
return errors.New("ref is not supported for staged repository")
|
||||
}
|
||||
|
||||
if safepath.IsDir(path) {
|
||||
return errors.New("cannot update a directory in a staged repository")
|
||||
}
|
||||
|
||||
if err := r.update(ctx, path, data, r.writer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := r.commit(ctx, r.writer, message); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if r.opts.PushOnWrites {
|
||||
return r.Push(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) Delete(ctx context.Context, path, ref, message string) error {
|
||||
if ref != "" && ref != r.gitConfig.Branch {
|
||||
return errors.New("ref is not supported for staged repository")
|
||||
}
|
||||
|
||||
if err := r.delete(ctx, path, r.writer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := r.commit(ctx, r.writer, message); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if r.opts.PushOnWrites {
|
||||
return r.Push(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) Push(ctx context.Context) error {
|
||||
if r.opts.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, r.opts.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
return r.writer.Push(ctx)
|
||||
}
|
||||
|
||||
func (r *stagedGitRepository) Remove(ctx context.Context) error {
|
||||
return r.writer.Cleanup(ctx)
|
||||
}
|
||||
@@ -0,0 +1,891 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
provisioning "github.com/grafana/grafana/pkg/apis/provisioning/v0alpha1"
|
||||
"github.com/grafana/grafana/pkg/registry/apis/provisioning/repository"
|
||||
"github.com/grafana/nanogit"
|
||||
"github.com/grafana/nanogit/mocks"
|
||||
"github.com/grafana/nanogit/protocol/hash"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewStagedGitRepository(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeClient)
|
||||
opts repository.StageOptions
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
name: "succeeds with default options",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{
|
||||
Name: "refs/heads/main",
|
||||
Hash: hash.Hash{1, 2, 3},
|
||||
}, nil)
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
mockClient.NewStagedWriterReturns(mockWriter, nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
wantError: nil,
|
||||
},
|
||||
{
|
||||
name: "succeeds with BeforeFn",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{
|
||||
Name: "refs/heads/main",
|
||||
Hash: hash.Hash{1, 2, 3},
|
||||
}, nil)
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
mockClient.NewStagedWriterReturns(mockWriter, nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
wantError: nil,
|
||||
},
|
||||
{
|
||||
name: "succeeds with timeout",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{
|
||||
Name: "refs/heads/main",
|
||||
Hash: hash.Hash{1, 2, 3},
|
||||
}, nil)
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
mockClient.NewStagedWriterReturns(mockWriter, nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
Timeout: time.Second * 5,
|
||||
},
|
||||
wantError: nil,
|
||||
},
|
||||
{
|
||||
name: "fails with GetRef error",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{}, errors.New("ref not found"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
wantError: errors.New("ref not found"),
|
||||
},
|
||||
{
|
||||
name: "fails with NewStagedWriter error",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{
|
||||
Name: "refs/heads/main",
|
||||
Hash: hash.Hash{1, 2, 3},
|
||||
}, nil)
|
||||
mockClient.NewStagedWriterReturns(nil, errors.New("failed to create writer"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
wantError: errors.New("build staged writer: failed to create writer"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockClient := &mocks.FakeClient{}
|
||||
tt.setupMock(mockClient)
|
||||
|
||||
gitRepo := &gitRepository{
|
||||
client: mockClient,
|
||||
gitConfig: RepositoryConfig{
|
||||
Branch: "main",
|
||||
URL: "https://git.example.com/repo.git",
|
||||
Token: "token123",
|
||||
},
|
||||
config: &provisioning.Repository{
|
||||
Spec: provisioning.RepositorySpec{
|
||||
Type: "test_type",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
stagedRepo, err := NewStagedGitRepository(context.Background(), gitRepo, tt.opts)
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, stagedRepo)
|
||||
|
||||
// Compare opts fields individually since function pointers can't be compared directly
|
||||
actualOpts := stagedRepo.(*stagedGitRepository).opts
|
||||
require.Equal(t, tt.opts.PushOnWrites, actualOpts.PushOnWrites)
|
||||
require.Equal(t, tt.opts.Timeout, actualOpts.Timeout)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_Read(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeClient)
|
||||
path string
|
||||
ref string
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
name: "succeeds with empty ref",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{
|
||||
Name: "refs/heads/main",
|
||||
Hash: hash.Hash{1, 2, 3},
|
||||
}, nil)
|
||||
mockClient.GetCommitReturns(&nanogit.Commit{
|
||||
Tree: hash.Hash{4, 5, 6},
|
||||
}, nil)
|
||||
mockClient.GetBlobByPathReturns(&nanogit.Blob{
|
||||
Content: []byte("file content"),
|
||||
Hash: hash.Hash{7, 8, 9},
|
||||
}, nil)
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
wantError: nil,
|
||||
},
|
||||
{
|
||||
name: "succeeds with matching ref",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{
|
||||
Name: "refs/heads/main",
|
||||
Hash: hash.Hash{1, 2, 3},
|
||||
}, nil)
|
||||
mockClient.GetCommitReturns(&nanogit.Commit{
|
||||
Tree: hash.Hash{4, 5, 6},
|
||||
}, nil)
|
||||
mockClient.GetBlobByPathReturns(&nanogit.Blob{
|
||||
Content: []byte("file content"),
|
||||
Hash: hash.Hash{7, 8, 9},
|
||||
}, nil)
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "main",
|
||||
wantError: nil,
|
||||
},
|
||||
{
|
||||
name: "fails with unsupported ref",
|
||||
setupMock: func(_ *mocks.FakeClient) {
|
||||
// No setup needed as error occurs before client calls
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "feature-branch",
|
||||
wantError: errors.New("ref is not supported for staged repository"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockClient := &mocks.FakeClient{}
|
||||
tt.setupMock(mockClient)
|
||||
|
||||
stagedRepo := createTestStagedRepository(mockClient)
|
||||
fileInfo, err := stagedRepo.Read(context.Background(), tt.path, tt.ref)
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, fileInfo)
|
||||
require.Equal(t, tt.path, fileInfo.Path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_ReadTree(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeClient)
|
||||
ref string
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
name: "succeeds with empty ref",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
mockClient.GetRefReturns(nanogit.Ref{
|
||||
Name: "refs/heads/main",
|
||||
Hash: hash.Hash{1, 2, 3},
|
||||
}, nil)
|
||||
mockClient.GetFlatTreeReturns(&nanogit.FlatTree{
|
||||
Entries: []nanogit.FlatTreeEntry{
|
||||
{
|
||||
Path: "configs/test.yaml",
|
||||
Hash: hash.Hash{4, 5, 6},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
},
|
||||
ref: "",
|
||||
wantError: nil,
|
||||
},
|
||||
{
|
||||
name: "fails with unsupported ref",
|
||||
setupMock: func(mockClient *mocks.FakeClient) {
|
||||
// No setup needed as error occurs before client calls
|
||||
},
|
||||
ref: "feature-branch",
|
||||
wantError: errors.New("ref is not supported for staged repository"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockClient := &mocks.FakeClient{}
|
||||
tt.setupMock(mockClient)
|
||||
|
||||
stagedRepo := createTestStagedRepository(mockClient)
|
||||
|
||||
entries, err := stagedRepo.ReadTree(context.Background(), tt.ref)
|
||||
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_Create(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeStagedWriter)
|
||||
opts repository.StageOptions
|
||||
path string
|
||||
ref string
|
||||
data []byte
|
||||
message string
|
||||
wantError error
|
||||
expectPush bool
|
||||
}{
|
||||
{
|
||||
name: "succeeds with empty ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.CreateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Create test file",
|
||||
wantError: nil,
|
||||
expectPush: false,
|
||||
},
|
||||
{
|
||||
name: "succeeds with matching ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.CreateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
mockWriter.PushReturns(nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: true,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "main",
|
||||
data: []byte("content"),
|
||||
message: "Create test file",
|
||||
wantError: nil,
|
||||
expectPush: true,
|
||||
},
|
||||
{
|
||||
name: "fails with unsupported ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
// No setup needed as error occurs before writer calls
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "feature-branch",
|
||||
data: []byte("content"),
|
||||
message: "Create test file",
|
||||
wantError: errors.New("ref is not supported for staged repository"),
|
||||
},
|
||||
{
|
||||
name: "fails with create blob error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.CreateBlobReturns(hash.Hash{}, errors.New("create blob failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Create test file",
|
||||
wantError: errors.New("create blob: create blob failed"),
|
||||
},
|
||||
{
|
||||
name: "fails with commit error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.CreateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, errors.New("commit failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Create test file",
|
||||
wantError: errors.New("commit changes: commit failed"),
|
||||
},
|
||||
{
|
||||
name: "fails with push error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.CreateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
mockWriter.PushReturns(errors.New("push failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: true,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Create test file",
|
||||
wantError: errors.New("push failed"),
|
||||
expectPush: true, // Push is still called even though it fails
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
tt.setupMock(mockWriter)
|
||||
|
||||
stagedRepo := createTestStagedRepositoryWithWriter(mockWriter, tt.opts)
|
||||
|
||||
err := stagedRepo.Create(context.Background(), tt.path, tt.ref, tt.data, tt.message)
|
||||
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Verify push behavior
|
||||
if tt.expectPush {
|
||||
require.Equal(t, 1, mockWriter.PushCallCount())
|
||||
} else if tt.wantError == nil {
|
||||
require.Equal(t, 0, mockWriter.PushCallCount())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_Write(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeStagedWriter)
|
||||
opts repository.StageOptions
|
||||
path string
|
||||
ref string
|
||||
data []byte
|
||||
message string
|
||||
fileExists bool
|
||||
wantError error
|
||||
expectPush bool
|
||||
}{
|
||||
{
|
||||
name: "succeeds with empty ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.BlobExistsReturns(false, nil)
|
||||
mockWriter.CreateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Write test file",
|
||||
fileExists: false,
|
||||
wantError: nil,
|
||||
expectPush: false,
|
||||
},
|
||||
{
|
||||
name: "succeeds with matching ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.BlobExistsReturns(true, nil)
|
||||
mockWriter.UpdateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
mockWriter.PushReturns(nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: true,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "main",
|
||||
data: []byte("updated content"),
|
||||
message: "Update test file",
|
||||
fileExists: true,
|
||||
wantError: nil,
|
||||
expectPush: true,
|
||||
},
|
||||
{
|
||||
name: "fails with unsupported ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
// No setup needed as error occurs before writer calls
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "feature-branch",
|
||||
data: []byte("content"),
|
||||
message: "Write test file",
|
||||
wantError: errors.New("ref is not supported for staged repository"),
|
||||
},
|
||||
{
|
||||
name: "fails with blob exists check error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.BlobExistsReturns(false, errors.New("blob exists check failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Write test file",
|
||||
wantError: errors.New("check if file exists: blob exists check failed"),
|
||||
},
|
||||
{
|
||||
name: "fails with create error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.BlobExistsReturns(false, nil)
|
||||
mockWriter.CreateBlobReturns(hash.Hash{}, errors.New("create failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Write test file",
|
||||
wantError: errors.New("create blob: create failed"),
|
||||
},
|
||||
{
|
||||
name: "fails with update error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.BlobExistsReturns(true, nil)
|
||||
mockWriter.UpdateBlobReturns(hash.Hash{}, errors.New("update failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Write test file",
|
||||
wantError: errors.New("update blob: update failed"),
|
||||
},
|
||||
{
|
||||
name: "fails with commit error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.BlobExistsReturns(false, nil)
|
||||
mockWriter.CreateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, errors.New("commit failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Write test file",
|
||||
wantError: errors.New("commit changes: commit failed"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
tt.setupMock(mockWriter)
|
||||
|
||||
stagedRepo := createTestStagedRepositoryWithWriter(mockWriter, tt.opts)
|
||||
|
||||
err := stagedRepo.Write(context.Background(), tt.path, tt.ref, tt.data, tt.message)
|
||||
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Verify push behavior
|
||||
if tt.expectPush {
|
||||
require.Equal(t, 1, mockWriter.PushCallCount())
|
||||
} else if tt.wantError == nil {
|
||||
require.Equal(t, 0, mockWriter.PushCallCount())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_Update(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeStagedWriter)
|
||||
opts repository.StageOptions
|
||||
path string
|
||||
ref string
|
||||
data []byte
|
||||
message string
|
||||
wantError error
|
||||
expectPush bool
|
||||
}{
|
||||
{
|
||||
name: "succeeds with empty ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.UpdateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("updated content"),
|
||||
message: "Update test file",
|
||||
wantError: nil,
|
||||
expectPush: false,
|
||||
},
|
||||
{
|
||||
name: "succeeds with matching ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.UpdateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
mockWriter.PushReturns(nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: true,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "main",
|
||||
data: []byte("updated content"),
|
||||
message: "Update test file",
|
||||
wantError: nil,
|
||||
expectPush: true,
|
||||
},
|
||||
{
|
||||
name: "fails with unsupported ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
// No setup needed as error occurs before writer calls
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "feature-branch",
|
||||
data: []byte("content"),
|
||||
message: "Update test file",
|
||||
wantError: errors.New("ref is not supported for staged repository"),
|
||||
},
|
||||
{
|
||||
name: "fails with directory update",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
// No setup needed as error occurs before writer calls
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "directory/",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Update directory",
|
||||
wantError: errors.New("cannot update a directory in a staged repository"),
|
||||
},
|
||||
{
|
||||
name: "fails with update blob error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.UpdateBlobReturns(hash.Hash{}, errors.New("update blob failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Update test file",
|
||||
wantError: errors.New("update blob: update blob failed"),
|
||||
},
|
||||
{
|
||||
name: "fails with commit error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.UpdateBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, errors.New("commit failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
data: []byte("content"),
|
||||
message: "Update test file",
|
||||
wantError: errors.New("commit changes: commit failed"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
tt.setupMock(mockWriter)
|
||||
|
||||
stagedRepo := createTestStagedRepositoryWithWriter(mockWriter, tt.opts)
|
||||
|
||||
err := stagedRepo.Update(context.Background(), tt.path, tt.ref, tt.data, tt.message)
|
||||
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Verify push behavior
|
||||
if tt.expectPush {
|
||||
require.Equal(t, 1, mockWriter.PushCallCount())
|
||||
} else if tt.wantError == nil {
|
||||
require.Equal(t, 0, mockWriter.PushCallCount())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_Delete(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeStagedWriter)
|
||||
opts repository.StageOptions
|
||||
path string
|
||||
ref string
|
||||
message string
|
||||
wantError error
|
||||
expectPush bool
|
||||
}{
|
||||
{
|
||||
name: "succeeds with empty ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.DeleteBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
message: "Delete test file",
|
||||
wantError: nil,
|
||||
expectPush: false,
|
||||
},
|
||||
{
|
||||
name: "succeeds with matching ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.DeleteTreeReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, nil)
|
||||
mockWriter.PushReturns(nil)
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: true,
|
||||
},
|
||||
path: "testdir/",
|
||||
ref: "main",
|
||||
message: "Delete test directory",
|
||||
wantError: nil,
|
||||
expectPush: true,
|
||||
},
|
||||
{
|
||||
name: "fails with unsupported ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
// No setup needed as error occurs before writer calls
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "feature-branch",
|
||||
message: "Delete test file",
|
||||
wantError: errors.New("ref is not supported for staged repository"),
|
||||
},
|
||||
{
|
||||
name: "fails with delete blob error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.DeleteBlobReturns(hash.Hash{}, errors.New("delete blob failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
message: "Delete test file",
|
||||
wantError: errors.New("delete blob: delete blob failed"),
|
||||
},
|
||||
{
|
||||
name: "fails with commit error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.DeleteBlobReturns(hash.Hash{1, 2, 3}, nil)
|
||||
mockWriter.CommitReturns(&nanogit.Commit{}, errors.New("commit failed"))
|
||||
},
|
||||
opts: repository.StageOptions{
|
||||
PushOnWrites: false,
|
||||
},
|
||||
path: "test.yaml",
|
||||
ref: "",
|
||||
message: "Delete test file",
|
||||
wantError: errors.New("commit changes: commit failed"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
tt.setupMock(mockWriter)
|
||||
|
||||
stagedRepo := createTestStagedRepositoryWithWriter(mockWriter, tt.opts)
|
||||
|
||||
err := stagedRepo.Delete(context.Background(), tt.path, tt.ref, tt.message)
|
||||
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Verify push behavior
|
||||
if tt.expectPush {
|
||||
require.Equal(t, 1, mockWriter.PushCallCount())
|
||||
} else if tt.wantError == nil {
|
||||
require.Equal(t, 0, mockWriter.PushCallCount())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_Push(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setupMock func(*mocks.FakeStagedWriter)
|
||||
wantError error
|
||||
expectCalls int
|
||||
}{
|
||||
{
|
||||
name: "succeeds with empty ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.PushReturns(nil)
|
||||
},
|
||||
wantError: nil,
|
||||
expectCalls: 1,
|
||||
},
|
||||
{
|
||||
name: "succeeds with matching ref",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.PushReturns(nil)
|
||||
},
|
||||
wantError: nil,
|
||||
expectCalls: 1,
|
||||
},
|
||||
{
|
||||
name: "succeeds with timeout",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.PushReturns(nil)
|
||||
},
|
||||
wantError: nil,
|
||||
expectCalls: 1,
|
||||
},
|
||||
{
|
||||
name: "fails with push error",
|
||||
setupMock: func(mockWriter *mocks.FakeStagedWriter) {
|
||||
mockWriter.PushReturns(errors.New("push failed"))
|
||||
},
|
||||
wantError: errors.New("push failed"),
|
||||
expectCalls: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
tt.setupMock(mockWriter)
|
||||
|
||||
stagedRepo := createTestStagedRepositoryWithWriter(mockWriter, repository.StageOptions{})
|
||||
|
||||
err := stagedRepo.Push(context.Background())
|
||||
|
||||
if tt.wantError != nil {
|
||||
require.EqualError(t, err, tt.wantError.Error())
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
require.Equal(t, tt.expectCalls, mockWriter.PushCallCount())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStagedGitRepository_Remove(t *testing.T) {
|
||||
t.Run("succeeds with remove", func(t *testing.T) {
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
stagedRepo := createTestStagedRepositoryWithWriter(mockWriter, repository.StageOptions{})
|
||||
|
||||
err := stagedRepo.Remove(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, mockWriter.CleanupCallCount())
|
||||
})
|
||||
}
|
||||
|
||||
// Helper functions for creating test instances
|
||||
|
||||
func createTestStagedRepository(mockClient *mocks.FakeClient) *stagedGitRepository {
|
||||
mockWriter := &mocks.FakeStagedWriter{}
|
||||
return createTestStagedRepositoryWithWriter(mockWriter, repository.StageOptions{}, mockClient)
|
||||
}
|
||||
|
||||
func createTestStagedRepositoryWithWriter(mockWriter *mocks.FakeStagedWriter, opts repository.StageOptions, mockClient ...*mocks.FakeClient) *stagedGitRepository {
|
||||
var client nanogit.Client
|
||||
if len(mockClient) > 0 {
|
||||
client = mockClient[0]
|
||||
} else {
|
||||
// Create a default mock client for tests that don't need specific behavior
|
||||
defaultClient := &mocks.FakeClient{}
|
||||
client = defaultClient
|
||||
}
|
||||
|
||||
gitRepo := &gitRepository{
|
||||
client: client,
|
||||
gitConfig: RepositoryConfig{
|
||||
Branch: "main",
|
||||
URL: "https://git.example.com/repo.git",
|
||||
Token: "token123",
|
||||
Path: "configs",
|
||||
},
|
||||
config: &provisioning.Repository{
|
||||
Spec: provisioning.RepositorySpec{
|
||||
Type: "test_type",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return &stagedGitRepository{
|
||||
gitRepository: gitRepo,
|
||||
opts: opts,
|
||||
writer: mockWriter,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user