Skip to content

Commit 400b337

Browse files
committed
refactor: internal/git
1 parent 6602359 commit 400b337

4 files changed

Lines changed: 64 additions & 128 deletions

File tree

internal/git/commit.go

Lines changed: 8 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,6 @@ import (
1313
"github.com/somaz94/go-git-commit-action/internal/gitcmd"
1414
)
1515

16-
// CommandDef defines a command to be executed
17-
type CommandDef struct {
18-
name string
19-
args []string
20-
desc string
21-
}
22-
2316
// FileBackup is a struct for file backups.
2417
type FileBackup struct {
2518
path string
@@ -161,37 +154,15 @@ func changeWorkingDirectory(config *config.GitConfig) error {
161154
// setupGitConfig configures Git with user information and safety settings.
162155
// It runs a series of git config commands to ensure the proper environment.
163156
func setupGitConfig(config *config.GitConfig) error {
164-
baseCommands := []CommandDef{
157+
baseCommands := []Command{
165158
{gitcmd.CmdGit, gitcmd.ConfigSafeDirArgs(gitcmd.PathApp), "Setting safe directory (/app)"},
166159
{gitcmd.CmdGit, gitcmd.ConfigSafeDirArgs(gitcmd.PathGitHubWorkspace), "Setting safe directory (/github/workspace)"},
167160
{gitcmd.CmdGit, gitcmd.ConfigUserEmailArgs(config.UserEmail), "Configuring user email"},
168161
{gitcmd.CmdGit, gitcmd.ConfigUserNameArgs(config.UserName), "Configuring user name"},
169162
{gitcmd.CmdGit, gitcmd.ConfigListArgs(), "Checking git configuration"},
170163
}
171164

172-
return executeCommandBatch(baseCommands, "\n⚙️ Executing Git Commands:")
173-
}
174-
175-
// executeCommandBatch runs a batch of commands, providing consistent output
176-
// formatting and error handling.
177-
func executeCommandBatch(commands []CommandDef, headerMessage string) error {
178-
if headerMessage != "" {
179-
fmt.Println(headerMessage)
180-
}
181-
182-
for _, cmd := range commands {
183-
fmt.Printf(" • %s... ", cmd.desc)
184-
command := exec.Command(cmd.name, cmd.args...)
185-
command.Stdout = os.Stdout
186-
command.Stderr = os.Stderr
187-
188-
if err := command.Run(); err != nil {
189-
fmt.Println("❌ Failed")
190-
return fmt.Errorf("failed to execute %s: %v", cmd.name, err)
191-
}
192-
fmt.Println("✅ Done")
193-
}
194-
return nil
165+
return ExecuteCommandBatch(baseCommands, "\n⚙️ Executing Git Commands:")
195166
}
196167

197168
// handleBranch manages branch-related operations, checking for local and remote
@@ -219,12 +190,12 @@ func handleBranch(config *config.GitConfig) error {
219190
// createNewBranch creates a new branch and pushes it to the remote repository.
220191
func createNewBranch(config *config.GitConfig) error {
221192
fmt.Printf("\n⚠️ Branch '%s' not found, creating it...\n", config.Branch)
222-
createCommands := []CommandDef{
193+
createCommands := []Command{
223194
{gitcmd.CmdGit, gitcmd.CheckoutNewBranchArgs(config.Branch), "Creating new branch"},
224195
{gitcmd.CmdGit, gitcmd.PushUpstreamArgs(gitcmd.RefOrigin, config.Branch), "Pushing new branch"},
225196
}
226197

227-
return executeCommandBatch(createCommands, "")
198+
return ExecuteCommandBatch(createCommands, "")
228199
}
229200

230201
// checkoutRemoteBranch checks out an existing remote branch while handling
@@ -329,13 +300,13 @@ func stashChanges() error {
329300

330301
// fetchAndCheckout fetches the remote branch and checks it out locally.
331302
func fetchAndCheckout(config *config.GitConfig) error {
332-
checkoutCommands := []CommandDef{
303+
checkoutCommands := []Command{
333304
{gitcmd.CmdGit, gitcmd.FetchArgs(gitcmd.RefOrigin, config.Branch), "Fetching remote branch"},
334305
{gitcmd.CmdGit, gitcmd.CheckoutArgs(config.Branch), "Checking out branch"},
335306
{gitcmd.CmdGit, gitcmd.ResetHardArgs(fmt.Sprintf("origin/%s", config.Branch)), "Resetting to remote state"},
336307
}
337308

338-
return executeCommandBatch(checkoutCommands, "")
309+
return ExecuteCommandBatch(checkoutCommands, "")
339310
}
340311

341312
// restoreChanges brings back the backed up files after branch switching.
@@ -480,30 +451,10 @@ func executeGitAdd(pattern string) error {
480451

481452
// performCommitAndPush commits the staged changes and pushes them to the remote.
482453
func performCommitAndPush(config *config.GitConfig) error {
483-
commitPushCommands := []CommandDef{
454+
commitPushCommands := []Command{
484455
{gitcmd.CmdGit, gitcmd.CommitArgs(config.CommitMessage), "Committing changes"},
485456
{gitcmd.CmdGit, gitcmd.PushArgs(gitcmd.RefOrigin, config.Branch), "Pushing to remote"},
486457
}
487458

488-
for _, cmd := range commitPushCommands {
489-
fmt.Printf(" • %s... ", cmd.desc)
490-
command := exec.Command(cmd.name, cmd.args...)
491-
command.Stdout = os.Stdout
492-
command.Stderr = os.Stderr
493-
494-
if err := command.Run(); err != nil {
495-
// Special handling for "nothing to commit" case
496-
if cmd.args[0] == "commit" && err.Error() == "exit status 1" {
497-
fmt.Println("⚠️ Nothing to commit, skipping...")
498-
continue
499-
}
500-
501-
fmt.Println("❌ Failed")
502-
return fmt.Errorf("failed to execute %s: %v", cmd.name, err)
503-
}
504-
505-
fmt.Println("✅ Done")
506-
}
507-
508-
return nil
459+
return ExecuteCommandBatch(commitPushCommands, "")
509460
}

internal/git/common.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package git
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"os/exec"
7+
)
8+
9+
// Command defines a command to be executed.
10+
// It encapsulates the command name, arguments, and a description
11+
// for consistent command execution across the git package.
12+
type Command struct {
13+
Name string // Command name (e.g., "git")
14+
Args []string // Command arguments
15+
Desc string // Human-readable description
16+
}
17+
18+
// ExecuteCommandBatch runs a batch of commands with consistent output
19+
// formatting and error handling. It provides visual feedback for each
20+
// command execution and handles errors gracefully.
21+
func ExecuteCommandBatch(commands []Command, headerMessage string) error {
22+
if headerMessage != "" {
23+
fmt.Println(headerMessage)
24+
}
25+
26+
for _, cmd := range commands {
27+
fmt.Printf(" • %s... ", cmd.Desc)
28+
command := exec.Command(cmd.Name, cmd.Args...)
29+
command.Stdout = os.Stdout
30+
command.Stderr = os.Stderr
31+
32+
if err := command.Run(); err != nil {
33+
// Special handling for "nothing to commit" case
34+
if len(cmd.Args) > 0 && cmd.Args[0] == "commit" && err.Error() == "exit status 1" {
35+
fmt.Println("⚠️ Nothing to commit, skipping...")
36+
continue
37+
}
38+
39+
fmt.Println("❌ Failed")
40+
return fmt.Errorf("failed to execute %s: %v", cmd.Name, err)
41+
}
42+
43+
fmt.Println("✅ Done")
44+
}
45+
46+
return nil
47+
}

internal/git/pr.go

Lines changed: 5 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,6 @@ import (
1313
"github.com/somaz94/go-git-commit-action/internal/gitcmd"
1414
)
1515

16-
// CommandDef defines a command to be executed
17-
type PRCommandDef struct {
18-
name string
19-
args []string
20-
desc string
21-
}
22-
2316
// GitHubClient handles GitHub API interactions.
2417
type GitHubClient struct {
2518
token string
@@ -185,41 +178,12 @@ func executePRGitAdd(pattern string) error {
185178

186179
// commitAndPushToBranch commits the staged changes and pushes them to the remote branch.
187180
func commitAndPushToBranch(config *config.GitConfig) error {
188-
commitPushCommands := []PRCommandDef{
181+
commitPushCommands := []Command{
189182
{gitcmd.CmdGit, gitcmd.CommitArgs(config.CommitMessage), "Committing changes"},
190183
{gitcmd.CmdGit, gitcmd.PushUpstreamArgs(gitcmd.RefOrigin, config.PRBranch), "Pushing changes"},
191184
}
192185

193-
return executePRCommandBatch(commitPushCommands, "")
194-
}
195-
196-
// executePRCommandBatch runs a batch of commands with consistent output formatting.
197-
func executePRCommandBatch(commands []PRCommandDef, headerMessage string) error {
198-
if headerMessage != "" {
199-
fmt.Println(headerMessage)
200-
}
201-
202-
for _, cmd := range commands {
203-
fmt.Printf(" • %s... ", cmd.desc)
204-
command := exec.Command(cmd.name, cmd.args...)
205-
command.Stdout = os.Stdout
206-
command.Stderr = os.Stderr
207-
208-
if err := command.Run(); err != nil {
209-
// Special handling for "nothing to commit" case
210-
if cmd.args[0] == "commit" && err.Error() == "exit status 1" {
211-
fmt.Println("⚠️ Nothing to commit, skipping...")
212-
continue
213-
}
214-
215-
fmt.Println("❌ Failed")
216-
return fmt.Errorf("failed to execute %s: %v", cmd.name, err)
217-
}
218-
219-
fmt.Println("✅ Done")
220-
}
221-
222-
return nil
186+
return ExecuteCommandBatch(commitPushCommands, "")
223187
}
224188

225189
// checkBranchDifferences checks the differences between the PR base branch and the source branch.
@@ -238,14 +202,14 @@ func checkBranchDifferences(config *config.GitConfig) error {
238202

239203
// fetchBranches fetches the latest from both the base and source branches.
240204
func fetchBranches(config *config.GitConfig) error {
241-
fetchCommands := []PRCommandDef{
205+
fetchCommands := []Command{
242206
{gitcmd.CmdGit, gitcmd.FetchArgs(gitcmd.RefOrigin, config.PRBase), "Fetching base branch"},
243207
{gitcmd.CmdGit, gitcmd.FetchArgs(gitcmd.RefOrigin, config.PRBranch), "Fetching source branch"},
244208
}
245209

246210
for _, cmd := range fetchCommands {
247-
if err := exec.Command(cmd.name, cmd.args...).Run(); err != nil {
248-
return fmt.Errorf("%s: %v", cmd.desc, err)
211+
if err := exec.Command(cmd.Name, cmd.Args...).Run(); err != nil {
212+
return fmt.Errorf("%s: %v", cmd.Desc, err)
249213
}
250214
}
251215

internal/git/tag.go

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,6 @@ import (
1111
"github.com/somaz94/go-git-commit-action/internal/gitcmd"
1212
)
1313

14-
// TagCommand defines a command to be executed for tag operations
15-
type TagCommand struct {
16-
name string
17-
args []string
18-
desc string
19-
}
20-
2114
// TagManager handles all operations related to Git tags.
2215
// It provides methods for creating, deleting, and managing Git tags.
2316
type TagManager struct {
@@ -73,12 +66,12 @@ func (tm *TagManager) fetchTags() error {
7366
func (tm *TagManager) deleteTag() error {
7467
fmt.Printf("\n • Deleting tag: %s\n", tm.config.TagName)
7568

76-
commands := []TagCommand{
69+
commands := []Command{
7770
{gitcmd.CmdGit, gitcmd.TagDeleteArgs(tm.config.TagName), "Deleting local tag"},
7871
{gitcmd.CmdGit, gitcmd.DeleteRemoteTagArgs(tm.config.TagName), "Deleting remote tag"},
7972
}
8073

81-
return tm.executeCommands(commands)
74+
return ExecuteCommandBatch(commands, "")
8275
}
8376

8477
// createTag creates a new Git tag and pushes it to the remote repository.
@@ -97,12 +90,12 @@ func (tm *TagManager) createTag() error {
9790
desc := tm.buildTagDescription(targetCommit)
9891

9992
// Execute the tag creation and push commands
100-
commands := []TagCommand{
93+
commands := []Command{
10194
{gitcmd.CmdGit, tagArgs, desc},
10295
{gitcmd.CmdGit, gitcmd.PushTagArgs(tm.config.TagName, true), "Pushing tag to remote"},
10396
}
10497

105-
return tm.executeCommands(commands)
98+
return ExecuteCommandBatch(commands, "")
10699
}
107100

108101
// resolveTargetCommit determines the exact commit that will be tagged.
@@ -195,22 +188,3 @@ func (tm *TagManager) buildTagDescription(targetCommit string) string {
195188

196189
return desc
197190
}
198-
199-
// executeCommands runs a sequence of commands and handles the output formatting.
200-
// It provides consistent error handling and status messages for each command.
201-
func (tm *TagManager) executeCommands(commands []TagCommand) error {
202-
for _, cmd := range commands {
203-
fmt.Printf(" • %s... ", cmd.desc)
204-
command := exec.Command(cmd.name, cmd.args...)
205-
command.Stdout = os.Stdout
206-
command.Stderr = os.Stderr
207-
208-
if err := command.Run(); err != nil {
209-
fmt.Println("❌ Failed")
210-
return fmt.Errorf("failed to execute %s: %v", cmd.name, err)
211-
}
212-
fmt.Println("✅ Done")
213-
}
214-
215-
return nil
216-
}

0 commit comments

Comments
 (0)