Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestCliUsage(t *testing.T) {
t.Fatal(err)
}

gotUsage := stderr.Bytes()
gotUsage := stdout.Bytes()

expectedUsage, err := os.ReadFile(goldenFilepath)
if err != nil {
Expand Down
33 changes: 29 additions & 4 deletions config_file_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
package main

import (
"fmt"
"os"
"path/filepath"
"testing"

"github.com/urfave/cli/v2"
"gopkg.in/yaml.v3"
)

// buildTestConfig creates a minimal cli.App with appFlags(), runs it with the
// given args, and returns the appConfig produced by buildConfig.
func buildTestConfig(args []string) (*appConfig, error) {
var result *appConfig
var buildErr error

app := &cli.App{
Name: "gitbackup",
Flags: appFlags(),
Action: func(cCtx *cli.Context) error {
result, buildErr = buildConfig(cCtx)
return buildErr
},
}

// urfave/cli expects the program name as args[0]
fullArgs := append([]string{"gitbackup"}, args...)
if err := app.Run(fullArgs); err != nil {
return nil, fmt.Errorf("app.Run: %w", err)
}
return result, buildErr
}

func TestHandleInitConfig(t *testing.T) {
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, defaultConfigFile)
Expand Down Expand Up @@ -127,8 +152,8 @@ func TestInitConfigWithConfigFile(t *testing.T) {
os.Setenv("GITLAB_TOKEN", "testtoken")
defer os.Unsetenv("GITLAB_TOKEN")

// initConfig with --config flag should use config file values
c, err := initConfig([]string{"-config", configPath})
// buildTestConfig with --config flag should use config file values
c, err := buildTestConfig([]string{"-config", configPath})
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
Expand Down Expand Up @@ -160,7 +185,7 @@ func TestInitConfigCLIOverridesConfigFile(t *testing.T) {
defer os.Unsetenv("GITLAB_TOKEN")

// CLI flag overrides service to github
c, err := initConfig([]string{"-config", configPath, "-service", "github"})
c, err := buildTestConfig([]string{"-config", configPath, "-service", "github"})
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
Expand All @@ -177,7 +202,7 @@ func TestInitConfigCLIOverridesConfigFile(t *testing.T) {

func TestInitConfigNoConfigFile(t *testing.T) {
// No config file — should behave exactly as before
c, err := initConfig([]string{"-service", "github"})
c, err := buildTestConfig([]string{"-service", "github"})
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
Expand Down
10 changes: 8 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@ require (
golang.org/x/text v0.27.0 // indirect
)

require codeberg.org/mvdkleijn/forgejo-sdk/forgejo/v2 v2.2.0
require (
codeberg.org/mvdkleijn/forgejo-sdk/forgejo/v2 v2.2.0
github.com/urfave/cli/v2 v2.27.7
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/42wim/httpsig v1.2.3 // indirect
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
github.com/danieljoos/wincred v1.2.2 // indirect
github.com/davidmz/go-pageant v1.0.2 // indirect
github.com/dvsekhvalnov/jose2go v1.8.0 // indirect
Expand All @@ -35,10 +40,11 @@ require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/time v0.12.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ github.com/cli/browser v1.0.0/go.mod h1:IEWkHYbLjkhtjwwWlwTHW2lGxeS5gezEQBMLTwDH
github.com/cli/oauth v1.2.2 h1:/qG/wok8jzu66tx7q+duGOIp4DT5P/ACXrdc33UoNUQ=
github.com/cli/oauth v1.2.2/go.mod h1:qd/FX8ZBD6n1sVNQO3aIdRxeu5LGw9WhKnYhIIoC2A4=
github.com/cli/safeexec v1.0.0/go.mod h1:Z/D4tTN8Vs5gXYHDCbaM1S/anmEDnJb1iW0+EJ5zx3Q=
github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=
github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/danieljoos/wincred v1.2.2 h1:774zMFJrqaeYCK2W57BgAem/MLi6mtSE47MB6BOJ0i0=
github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7nd/ogr0Uh8=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand Down Expand Up @@ -74,14 +76,20 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU=
github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4=
github.com/xanzy/go-gitlab v0.115.0 h1:6DmtItNcVe+At/liXSgfE/DZNZrGfalQmBRmOcJjOn8=
github.com/xanzy/go-gitlab v0.115.0/go.mod h1:5XCDtM7AM6WMKmfDdOiEpyRWUqui2iS9ILfvCZ2gJ5M=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
Expand Down
109 changes: 57 additions & 52 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package main

import (
"flag"
"fmt"
"log"
"os"

"github.com/urfave/cli/v2"
)

// MaxConcurrentClones is the upper limit of the maximum number of
Expand All @@ -26,62 +27,66 @@ var knownServices = map[string]string{
"forgejo": "codeberg.org",
}

// parseSubcommandFlags parses --config and --help flags for a subcommand.
func parseSubcommandFlags(name, description string, args []string) string {
var configPath string
fs := flag.NewFlagSet("gitbackup "+name, flag.ExitOnError)
fs.StringVar(&configPath, "config", "", "Path to config file (default: OS config directory)")
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: gitbackup %s [--config path]\n\n", name)
fmt.Fprintf(os.Stderr, "%s\n\n", description)
fs.PrintDefaults()
}
fs.Parse(args)
return configPath
}

func main() {

// Handle subcommands before flag parsing
if len(os.Args) > 1 {
switch os.Args[1] {
case "init":
configPath := parseSubcommandFlags("init", "Create a default gitbackup.yml configuration file.", os.Args[2:])
if err := handleInitConfig(configPath); err != nil {
log.Fatal(err)
app := &cli.App{
Name: "gitbackup",
Usage: "Backup your Git repositories from GitHub, GitLab, Bitbucket, or Forgejo",
Flags: appFlags(),
Action: func(cCtx *cli.Context) error {
c, err := buildConfig(cCtx)
if err != nil {
return err
}
return
case "validate":
configPath := parseSubcommandFlags("validate", "Validate the gitbackup.yml configuration file.", os.Args[2:])
if err := handleValidateConfig(configPath); err != nil {
log.Fatal(err)
err = validateConfig(c)
if err != nil {
return err
}
return
}
}

c, err := initConfig(os.Args[1:])
if err != nil {
log.Fatal(err)
}
err = validateConfig(c)
if err != nil {
log.Fatal(err)
}

client := newClient(c.service, c.gitHostURL)
var executionErr error
client := newClient(c.service, c.gitHostURL)

// TODO implement validation of options so that we don't
// allow multiple operations at one go
if c.githubListUserMigrations {
handleGithubListUserMigrations(client, c)
} else if c.githubCreateUserMigration {
handleGithubCreateUserMigration(client, c)
} else {
executionErr = handleGitRepositoryClone(client, c)
if c.githubListUserMigrations {
handleGithubListUserMigrations(client, c)
} else if c.githubCreateUserMigration {
handleGithubCreateUserMigration(client, c)
} else {
if err := handleGitRepositoryClone(client, c); err != nil {
return err
}
}
return nil
},
Commands: []*cli.Command{
{
Name: "init",
Usage: "Create a default gitbackup.yml configuration file",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Usage: "Path to config file (default: OS config directory)",
},
},
Action: func(cCtx *cli.Context) error {
return handleInitConfig(cCtx.String("config"))
},
},
{
Name: "validate",
Usage: "Validate the gitbackup.yml configuration file",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Usage: "Path to config file (default: OS config directory)",
},
},
Action: func(cCtx *cli.Context) error {
return handleValidateConfig(cCtx.String("config"))
},
},
},
}
if executionErr != nil {
log.Fatal(executionErr)

if err := app.Run(os.Args); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
log.Fatal(err)
}
}
Loading
Loading