Compare commits

...

6 Commits

23 changed files with 353 additions and 438 deletions

View File

@ -8,33 +8,33 @@ import (
)
// FetchSource fetches the source from remote.
func FetchSource(repo Repository) *types.Cmd {
func (r *Repository) FetchSource() *types.Cmd {
args := []string{
"fetch",
"origin",
fmt.Sprintf("+%s:", repo.Branch),
fmt.Sprintf("+%s:", r.Branch),
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}
// CheckoutHead handles branch checkout.
func CheckoutHead(repo Repository) *types.Cmd {
func (r *Repository) CheckoutHead() *types.Cmd {
args := []string{
"checkout",
"-qf",
repo.Branch,
r.Branch,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}

View File

@ -3,7 +3,7 @@ package git
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestFetchSource(t *testing.T) {
@ -32,9 +32,9 @@ func TestFetchSource(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := FetchSource(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.FetchSource()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -65,9 +65,9 @@ func TestCheckoutHead(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := CheckoutHead(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.CheckoutHead()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -1,96 +1,70 @@
package git
import (
"io"
"github.com/thegeeklab/wp-plugin-go/v2/types"
"golang.org/x/sys/execabs"
)
// ForceAdd forces the addition of all dirty files.
func ForceAdd(repo Repository) *types.Cmd {
cmd := execabs.Command(
gitBin,
"add",
"--all",
"--force",
)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
}
}
// Add updates the index to match the working tree.
func Add(repo Repository) *types.Cmd {
cmd := execabs.Command(
gitBin,
"add",
)
cmd.Dir = repo.WorkDir
if repo.Add != "" {
cmd.Args = append(cmd.Args, repo.Add)
} else {
cmd.Args = append(cmd.Args, "--all")
func (r *Repository) Add() *types.Cmd {
cmd := &types.Cmd{
Cmd: execabs.Command(
gitBin,
"add",
"--all",
),
}
cmd.Dir = r.WorkDir
return &types.Cmd{
Cmd: cmd,
}
return cmd
}
// TestCleanTree returns non-zero if diff between index and local repository.
func IsCleanTree(repo Repository) *types.Cmd {
cmd := execabs.Command(
gitBin,
"diff-index",
"--quiet",
"HEAD",
"--ignore-submodules",
)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
func (r *Repository) IsCleanTree() *types.Cmd {
cmd := &types.Cmd{
Cmd: execabs.Command(
gitBin,
"diff-index",
"--quiet",
"HEAD",
"--ignore-submodules",
),
}
cmd.Dir = r.WorkDir
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
cmd.SetTrace(false)
return cmd
}
// EmptyCommit simply create an empty commit.
func EmptyCommit(repo Repository) *types.Cmd {
args := []string{
"commit",
"--allow-empty",
"-m",
repo.CommitMsg,
// Commit creates a new commit with the specified commit message.
func (r *Repository) Commit() *types.Cmd {
if err := r.IsCleanTree().Run(); err == nil && !r.EmptyCommit {
return nil
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
if repo.NoVerify {
cmd.Args = append(cmd.Args, "--no-verify")
}
return &types.Cmd{
Cmd: cmd,
}
}
func Commit(repo Repository) *types.Cmd {
args := []string{
"commit",
"-m",
repo.CommitMsg,
r.CommitMsg,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
if repo.NoVerify {
cmd.Args = append(cmd.Args, "--no-verify")
if r.EmptyCommit {
args = append(args, "--allow-empty")
}
return &types.Cmd{
Cmd: cmd,
if r.NoVerify {
args = append(args, "--no-verify")
}
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}

View File

@ -3,7 +3,7 @@ package git
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestAdd(t *testing.T) {
@ -16,25 +16,16 @@ func TestAdd(t *testing.T) {
name: "add all files",
repo: Repository{
WorkDir: "/path/to/repo",
Add: "",
},
want: []string{gitBin, "add", "--all"},
},
{
name: "add specific file",
repo: Repository{
WorkDir: "/path/to/repo",
Add: "file.go",
},
want: []string{gitBin, "add", "file.go"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := Add(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.Add()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -63,43 +54,52 @@ func TestIsCleanTree(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := IsCleanTree(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.IsCleanTree()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestEmptyCommit(t *testing.T) {
func TestCommit(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "empty commit with default options",
name: "commit with message",
repo: Repository{
WorkDir: "/path/to/repo",
CommitMsg: "Empty commit",
CommitMsg: "Initial commit",
},
want: []string{gitBin, "commit", "--allow-empty", "-m", "Empty commit"},
want: []string{gitBin, "commit", "-m", "Initial commit"},
},
{
name: "empty commit with no-verify option",
name: "commit with empty commit",
repo: Repository{
WorkDir: "/path/to/repo",
CommitMsg: "Empty commit",
EmptyCommit: true,
},
want: []string{gitBin, "commit", "-m", "Empty commit", "--allow-empty"},
},
{
name: "commit with no verify",
repo: Repository{
WorkDir: "/path/to/repo",
CommitMsg: "Empty commit",
CommitMsg: "No verify commit",
NoVerify: true,
},
want: []string{gitBin, "commit", "--allow-empty", "-m", "Empty commit", "--no-verify"},
want: []string{gitBin, "commit", "-m", "No verify commit", "--no-verify"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := EmptyCommit(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.Commit()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -9,58 +9,58 @@ import (
// ConfigAutocorrect sets the local git autocorrect configuration for the given repository.
// The autocorrect setting determines how git handles minor typos in commands.
func ConfigAutocorrect(repo Repository) *types.Cmd {
func (r *Repository) ConfigAutocorrect() *types.Cmd {
args := []string{
"config",
"--local",
"help.autocorrect",
repo.Autocorrect,
r.Autocorrect,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}
// ConfigUserEmail sets the global git author email.
func ConfigUserEmail(repo Repository) *types.Cmd {
func (r *Repository) ConfigUserEmail() *types.Cmd {
args := []string{
"config",
"--local",
"user.email",
repo.Author.Email,
r.Author.Email,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}
// ConfigUserName configures the user.name git config setting for the given repository.
func ConfigUserName(repo Repository) *types.Cmd {
func (r *Repository) ConfigUserName() *types.Cmd {
args := []string{
"config",
"--local",
"user.name",
repo.Author.Name,
r.Author.Name,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}
// ConfigSSLVerify configures the http.sslVerify git config setting for the given repository.
func ConfigSSLVerify(repo Repository, skipVerify bool) *types.Cmd {
func (r *Repository) ConfigSSLVerify(skipVerify bool) *types.Cmd {
args := []string{
"config",
"--local",
@ -68,10 +68,27 @@ func ConfigSSLVerify(repo Repository, skipVerify bool) *types.Cmd {
strconv.FormatBool(!skipVerify),
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}
// ConfigSSHCommand sets custom SSH key.
func (r *Repository) ConfigSSHCommand(sshKey string) *types.Cmd {
args := []string{
"config",
"--local",
"core.sshCommand",
"ssh -i " + sshKey,
}
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.SetTrace(false)
return cmd
}

View File

@ -3,7 +3,7 @@ package git
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestConfigAutocorrect(t *testing.T) {
@ -32,9 +32,9 @@ func TestConfigAutocorrect(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := ConfigAutocorrect(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.ConfigAutocorrect()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -59,9 +59,9 @@ func TestConfigUserEmail(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := ConfigUserEmail(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.ConfigUserEmail()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -86,9 +86,9 @@ func TestConfigUserName(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := ConfigUserName(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.ConfigUserName()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -116,9 +116,32 @@ func TestConfigSSLVerify(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := ConfigSSLVerify(tt.repo, tt.skipVerify)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.ConfigSSLVerify(tt.skipVerify)
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestConfigSSHCommand(t *testing.T) {
tests := []struct {
name string
repo Repository
sshKey string
want []string
}{
{
name: "set SSH command with key",
repo: Repository{},
sshKey: "/path/to/ssh/key",
want: []string{gitBin, "config", "--local", "core.sshCommand", "ssh -i /path/to/ssh/key"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.ConfigSSHCommand(tt.sshKey)
assert.Equal(t, tt.want, cmd.Cmd.Args)
})
}
}

View File

@ -1,7 +1,5 @@
package git
const gitBin = "/usr/bin/git"
type Author struct {
Name string
Email string
@ -12,7 +10,6 @@ type Repository struct {
RemoteURL string
Branch string
Add string
CommitMsg string
Autocorrect string
@ -25,3 +22,5 @@ type Repository struct {
Author Author
}
const gitBin = "/usr/bin/git"

View File

@ -6,17 +6,17 @@ import (
)
// Init creates a new Git repository in the specified directory.
func Init(repo Repository) *types.Cmd {
func (r *Repository) Init() *types.Cmd {
args := []string{
"init",
"-b",
repo.Branch,
r.Branch,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}

View File

@ -3,7 +3,7 @@ package git
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestInit(t *testing.T) {
@ -24,9 +24,9 @@ func TestInit(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := Init(tt.repo)
require.Equal(t, tt.expected, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.Init()
assert.Equal(t, tt.expected, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -8,58 +8,58 @@ import (
)
// RemoteRemove drops the defined remote from a git repo.
func RemoteRemove(repo Repository) *types.Cmd {
func (r *Repository) RemoteRemove() *types.Cmd {
args := []string{
"remote",
"rm",
repo.RemoteName,
r.RemoteName,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}
// RemoteAdd adds an additional remote to a git repo.
func RemoteAdd(repo Repository) *types.Cmd {
func (r *Repository) RemoteAdd() *types.Cmd {
args := []string{
"remote",
"add",
repo.RemoteName,
repo.RemoteURL,
r.RemoteName,
r.RemoteURL,
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}
// RemotePush pushs the changes from the local head to a remote branch.
func RemotePush(repo Repository) *types.Cmd {
func (r *Repository) RemotePush() *types.Cmd {
args := []string{
"push",
repo.RemoteName,
fmt.Sprintf("HEAD:%s", repo.Branch),
r.RemoteName,
fmt.Sprintf("HEAD:%s", r.Branch),
}
cmd := execabs.Command(gitBin, args...)
cmd.Dir = repo.WorkDir
if repo.ForcePush {
cmd.Args = append(cmd.Args, "--force")
if r.ForcePush {
args = append(args, "--force")
}
if repo.PushFollowTags {
cmd.Args = append(cmd.Args, "--follow-tags")
if r.PushFollowTags {
args = append(args, "--follow-tags")
}
return &types.Cmd{
Cmd: cmd,
cmd := &types.Cmd{
Cmd: execabs.Command(gitBin, args...),
}
cmd.Dir = r.WorkDir
return cmd
}

View File

@ -3,7 +3,7 @@ package git
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestRemoteRemove(t *testing.T) {
@ -39,9 +39,9 @@ func TestRemoteRemove(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := RemoteRemove(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.RemoteRemove()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -73,9 +73,9 @@ func TestRemoteAdd(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := RemoteAdd(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.RemoteAdd()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -131,9 +131,9 @@ func TestRemotePush(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := RemotePush(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.RemotePush()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -7,26 +7,26 @@ import (
)
// Status returns a command that runs `git status --porcelain` for the given repository.
func Status(repo Repository) *types.Cmd {
cmd := execabs.Command(
gitBin,
"status",
"--porcelain",
)
cmd.Dir = repo.WorkDir
return &types.Cmd{
Cmd: cmd,
func (r *Repository) Status() *types.Cmd {
cmd := &types.Cmd{
Cmd: execabs.Command(
gitBin,
"status",
"--porcelain",
),
}
cmd.Dir = r.WorkDir
return cmd
}
// IsDirty checks if the given repository has any uncommitted changes.
// It runs `git status --porcelain` and returns true if the output is non-empty,
// indicating that there are uncommitted changes in the repository.
// If there is an error running the git command, it returns false.
func IsDirty(repo Repository) bool {
cmd := Status(repo)
cmd.Dir = repo.WorkDir
func (r *Repository) IsDirty() bool {
cmd := r.Status()
cmd.Dir = r.WorkDir
out, err := cmd.CombinedOutput()
if err != nil {

View File

@ -5,7 +5,7 @@ import (
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestStatus(t *testing.T) {
@ -37,9 +37,9 @@ func TestStatus(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := Status(tt.repo)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
cmd := tt.repo.Status()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
@ -70,17 +70,17 @@ func TestIsDirty(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := Init(tt.repo).Run(); err != nil {
require.NoError(t, err)
if err := tt.repo.Init().Run(); err != nil {
assert.NoError(t, err)
}
if tt.want {
_, err := os.Create(filepath.Join(tt.repo.WorkDir, "dummy"))
require.NoError(t, err)
assert.NoError(t, err)
}
isDirty := IsDirty(tt.repo)
require.Equal(t, tt.want, isDirty)
isDirty := tt.repo.IsDirty()
assert.Equal(t, tt.want, isDirty)
})
}
}

View File

@ -1,56 +0,0 @@
package git
import (
"fmt"
"os"
"path/filepath"
)
const (
netrcFile = `machine %s
login %s
password %s
`
configFile = `Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
`
)
const (
strictFilePerm = 0o600
strictDirPerm = 0o700
)
// WriteKey writes the SSH private key.
func WriteSSHKey(path, key string) error {
sshPath := filepath.Join(path, ".ssh")
confPath := filepath.Join(sshPath, "config")
keyPath := filepath.Join(sshPath, "id_rsa")
if err := os.MkdirAll(sshPath, strictDirPerm); err != nil {
return fmt.Errorf("failed to create .ssh directory: %w", err)
}
if err := os.WriteFile(confPath, []byte(configFile), strictFilePerm); err != nil {
return fmt.Errorf("failed to create .ssh/config file: %w", err)
}
if err := os.WriteFile(keyPath, []byte(key), strictFilePerm); err != nil {
return fmt.Errorf("failed to create .ssh/id_rsa file: %w", err)
}
return nil
}
// WriteNetrc writes the netrc file.
func WriteNetrc(path, machine, login, password string) error {
netrcPath := filepath.Join(path, ".netrc")
netrcContent := fmt.Sprintf(netrcFile, machine, login, password)
if err := os.WriteFile(netrcPath, []byte(netrcContent), strictFilePerm); err != nil {
return fmt.Errorf("failed to create .netrc file: %w", err)
}
return nil
}

View File

@ -1,96 +0,0 @@
package git
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestWriteSSHKey(t *testing.T) {
tests := []struct {
name string
privateKey string
dir string
wantErr bool
}{
{
name: "valid private key",
privateKey: "valid_private_key",
dir: t.TempDir(),
wantErr: false,
},
{
name: "empty private key",
privateKey: "",
dir: t.TempDir(),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := WriteSSHKey(tt.dir, tt.privateKey)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
privateKeyPath := filepath.Join(tt.dir, ".ssh", "id_rsa")
_, err = os.Stat(privateKeyPath)
require.NoError(t, err)
configPath := filepath.Join(tt.dir, ".ssh", "config")
_, err = os.Stat(configPath)
require.NoError(t, err)
})
}
}
func TestWriteNetrc(t *testing.T) {
tests := []struct {
name string
path string
machine string
login string
password string
wantErr bool
}{
{
name: "valid input",
path: t.TempDir(),
machine: "example.com",
login: "user",
password: "pass",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := WriteNetrc(tt.path, tt.machine, tt.login, tt.password)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
netrcPath := filepath.Join(tt.path, ".netrc")
_, err = os.Stat(netrcPath)
require.NoError(t, err)
content, err := os.ReadFile(netrcPath)
require.NoError(t, err)
expected := fmt.Sprintf("machine %s\nlogin %s\npassword %s\n", tt.machine, tt.login, tt.password)
require.Equal(t, expected, string(content))
})
}
}

6
go.mod
View File

@ -5,7 +5,7 @@ go 1.22
require (
github.com/rs/zerolog v1.32.0
github.com/stretchr/testify v1.9.0
github.com/thegeeklab/wp-plugin-go/v2 v2.2.0
github.com/thegeeklab/wp-plugin-go/v2 v2.3.1
github.com/urfave/cli/v2 v2.27.2
golang.org/x/sys v0.20.0
)
@ -29,7 +29,7 @@ require (
github.com/shopspring/decimal v1.2.0 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

12
go.sum
View File

@ -46,8 +46,8 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/thegeeklab/wp-plugin-go/v2 v2.2.0 h1:Z6UzL8N0v3J2uuk67DBnH19QNV1vXihaKC2OoH2TMAY=
github.com/thegeeklab/wp-plugin-go/v2 v2.2.0/go.mod h1:I/3M/4OPvr4FFS+s0aaImpX1llA/lS2KC6Bnp+qzsCs=
github.com/thegeeklab/wp-plugin-go/v2 v2.3.1 h1:ARwYgTPZ5iPsmOenmqcCf8TjiEe8wBOHKO7H/Xshe48=
github.com/thegeeklab/wp-plugin-go/v2 v2.3.1/go.mod h1:0t8M8txtEFiaB6RqLX8vLrxkqAo5FT5Hx7dztN592D4=
github.com/urfave/cli/v2 v2.27.2 h1:6e0H+AkS+zDckwPCUrZkKX38mRaau4nL2uipkJpbkcI=
github.com/urfave/cli/v2 v2.27.2/go.mod h1:g0+79LmHHATl7DAcHO99smiR/T7uGLw84w8Y42x+4eM=
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw=
@ -56,15 +56,15 @@ github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5t
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=

View File

@ -12,7 +12,7 @@ import (
"github.com/thegeeklab/wp-git-action/plugin"
"github.com/thegeeklab/wp-plugin-go/v2/docs"
wp_template "github.com/thegeeklab/wp-plugin-go/v2/template"
"github.com/thegeeklab/wp-plugin-go/v2/template"
)
func main() {
@ -23,7 +23,7 @@ func main() {
p := plugin.New(nil)
out, err := wp_template.Render(context.Background(), client, tmpl, docs.GetTemplateData(p.App))
out, err := template.Render(context.Background(), client, tmpl, docs.GetTemplateData(p.App))
if err != nil {
panic(err)
}

View File

@ -7,9 +7,9 @@ import (
"os"
"path/filepath"
"github.com/thegeeklab/wp-git-action/git"
"github.com/thegeeklab/wp-plugin-go/v2/file"
"github.com/thegeeklab/wp-plugin-go/v2/types"
"github.com/thegeeklab/wp-plugin-go/v2/util"
)
var (
@ -46,16 +46,14 @@ func (p *Plugin) run(ctx context.Context) error {
func (p *Plugin) Validate() error {
var err error
if p.Settings.Repo.WorkDir == "" {
p.Settings.Repo.WorkDir, err = os.Getwd()
}
p.Settings.Repo.Autocorrect = "never"
p.Settings.Repo.RemoteName = "origin"
p.Settings.Repo.Add = ""
if err != nil {
return fmt.Errorf("failed to get working directory: %w", err)
if p.Settings.Repo.WorkDir == "" {
p.Settings.Repo.WorkDir, err = os.Getwd()
if err != nil {
return fmt.Errorf("failed to get working directory: %w", err)
}
}
for _, actionStr := range p.Settings.Action.Value() {
@ -104,7 +102,7 @@ func (p *Plugin) Validate() error {
func (p *Plugin) Execute() error {
var err error
homeDir := getUserHomeDir()
homeDir := util.GetUserHomeDir()
batchCmd := make([]*types.Cmd, 0)
gitEnv := []string{
"GIT_AUTHOR_NAME",
@ -127,13 +125,11 @@ func (p *Plugin) Execute() error {
// Write SSH key and netrc file.
if p.Settings.SSHKey != "" {
if err := git.WriteSSHKey(homeDir, p.Settings.SSHKey); err != nil {
return err
}
batchCmd = append(batchCmd, p.Settings.Repo.ConfigSSHCommand(p.Settings.SSHKey))
}
netrc := p.Settings.Netrc
if err := git.WriteNetrc(homeDir, netrc.Machine, netrc.Login, netrc.Password); err != nil {
if err := WriteNetrc(homeDir, netrc.Machine, netrc.Login, netrc.Password); err != nil {
return err
}
@ -141,6 +137,7 @@ func (p *Plugin) Execute() error {
if err := os.MkdirAll(p.Settings.Repo.WorkDir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create working directory: %w", err)
}
defer os.RemoveAll(p.Settings.Repo.WorkDir)
p.Settings.Repo.IsEmpty, err = file.IsDirEmpty(p.Settings.Repo.WorkDir)
if err != nil {
@ -153,14 +150,14 @@ func (p *Plugin) Execute() error {
}
if !isDir {
batchCmd = append(batchCmd, git.Init(p.Settings.Repo))
batchCmd = append(batchCmd, p.Settings.Repo.Init())
}
// Handle repo configuration.
batchCmd = append(batchCmd, git.ConfigAutocorrect(p.Settings.Repo))
batchCmd = append(batchCmd, git.ConfigUserName(p.Settings.Repo))
batchCmd = append(batchCmd, git.ConfigUserEmail(p.Settings.Repo))
batchCmd = append(batchCmd, git.ConfigSSLVerify(p.Settings.Repo, p.Network.InsecureSkipVerify))
batchCmd = append(batchCmd, p.Settings.Repo.ConfigAutocorrect())
batchCmd = append(batchCmd, p.Settings.Repo.ConfigUserName())
batchCmd = append(batchCmd, p.Settings.Repo.ConfigUserEmail())
batchCmd = append(batchCmd, p.Settings.Repo.ConfigSSLVerify(p.Network.InsecureSkipVerify))
for _, actionStr := range p.Settings.Action.Value() {
action := Action(actionStr)
@ -205,11 +202,11 @@ func (p *Plugin) handleClone() ([]*types.Cmd, error) {
}
if p.Settings.Repo.RemoteURL != "" {
cmds = append(cmds, git.RemoteAdd(p.Settings.Repo))
cmds = append(cmds, p.Settings.Repo.RemoteAdd())
}
cmds = append(cmds, git.FetchSource(p.Settings.Repo))
cmds = append(cmds, git.CheckoutHead(p.Settings.Repo))
cmds = append(cmds, p.Settings.Repo.FetchSource())
cmds = append(cmds, p.Settings.Repo.CheckoutHead())
return cmds, nil
}
@ -218,30 +215,21 @@ func (p *Plugin) handleClone() ([]*types.Cmd, error) {
func (p *Plugin) handleCommit() []*types.Cmd {
var cmds []*types.Cmd
cmds = append(cmds, git.Add(p.Settings.Repo))
if err := git.IsCleanTree(p.Settings.Repo).Run(); err != nil {
cmds = append(cmds, git.Commit(p.Settings.Repo))
}
if p.Settings.Repo.EmptyCommit {
cmds = append(cmds, git.EmptyCommit(p.Settings.Repo))
}
cmds = append(cmds, p.Settings.Repo.Add())
cmds = append(cmds, p.Settings.Repo.Commit())
return cmds
}
// HandlePush pushs changes to remote.
func (p *Plugin) handlePush() []*types.Cmd {
return []*types.Cmd{git.RemotePush(p.Settings.Repo)}
return []*types.Cmd{p.Settings.Repo.RemotePush()}
}
// HandlePages syncs, commits and pushes the changes from the pages directory to the pages branch.
func (p *Plugin) handlePages() ([]*types.Cmd, error) {
var cmds []*types.Cmd
defer os.RemoveAll(p.Settings.Repo.WorkDir)
ccmd, err := p.handleClone()
if err != nil {
return cmds, err

View File

@ -34,10 +34,10 @@ func SyncDirectories(exclude []string, del bool, src, dest string) *types.Cmd {
dest,
)
cmd := execabs.Command("rsync", args...)
cmd := &types.Cmd{
Cmd: execabs.Command("rsync", args...),
}
cmd.Dir = src
return &types.Cmd{
Cmd: cmd,
}
return cmd
}

View File

@ -3,7 +3,7 @@ package plugin
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestSyncDirectories(t *testing.T) {
@ -39,8 +39,8 @@ func TestSyncDirectories(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := SyncDirectories(tt.exclude, tt.del, tt.src, tt.dest)
require.Equal(t, tt.want, cmd.Cmd.Args)
require.Equal(t, tt.src, cmd.Cmd.Dir)
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.src, cmd.Cmd.Dir)
})
}
}

View File

@ -1,15 +1,28 @@
package plugin
import (
"os/user"
"fmt"
"os"
"path/filepath"
)
func getUserHomeDir() string {
home := "/root"
const (
netrcFile = `machine %s
login %s
password %s
`
)
if currentUser, err := user.Current(); err == nil {
home = currentUser.HomeDir
const strictFilePerm = 0o600
// WriteNetrc writes the netrc file.
func WriteNetrc(path, machine, login, password string) error {
netrcPath := filepath.Join(path, ".netrc")
netrcContent := fmt.Sprintf(netrcFile, machine, login, password)
if err := os.WriteFile(netrcPath, []byte(netrcContent), strictFilePerm); err != nil {
return fmt.Errorf("failed to create .netrc file: %w", err)
}
return home
return nil
}

53
plugin/util_test.go Normal file
View File

@ -0,0 +1,53 @@
package plugin
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWriteNetrc(t *testing.T) {
tests := []struct {
name string
path string
machine string
login string
password string
wantErr bool
}{
{
name: "valid input",
path: t.TempDir(),
machine: "example.com",
login: "user",
password: "pass",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := WriteNetrc(tt.path, tt.machine, tt.login, tt.password)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
netrcPath := filepath.Join(tt.path, ".netrc")
_, err = os.Stat(netrcPath)
assert.NoError(t, err)
content, err := os.ReadFile(netrcPath)
assert.NoError(t, err)
expected := fmt.Sprintf("machine %s\nlogin %s\npassword %s\n", tt.machine, tt.login, tt.password)
assert.Equal(t, expected, string(content))
})
}
}