Skip to content

Commit 4128c61

Browse files
authored
Add support read config from a config file (#180)
1 parent 46bca63 commit 4128c61

File tree

7 files changed

+188
-52
lines changed

7 files changed

+188
-52
lines changed

cmd/fetch.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,22 @@ func newFetchCmd(context.Context) (cmd *cobra.Command) {
1818
}
1919

2020
flags := cmd.Flags()
21-
flags.StringVarP(&opt.provider, "provider", "p", "github",
22-
"The provider of hd-home repository")
21+
opt.addFlags(flags)
2322
flags.StringVarP(&opt.branch, "branch", "b", installer.ConfigBranch,
2423
"The branch of git repository (not support currently)")
2524
flags.BoolVarP(&opt.reset, "reset", "", false,
2625
"If you want to reset the hd-config which means delete and clone it again")
2726

28-
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, "gitee"))
27+
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, ProviderGitee))
2928
return
3029
}
3130

3231
func (o *fetchOption) preRunE(_ *cobra.Command, _ []string) (err error) {
33-
switch o.provider {
34-
case "github":
35-
o.provider = installer.ConfigGitHub
36-
case "gitee":
37-
o.provider = "https://gitee.com/LinuxSuRen/hd-home"
32+
switch o.Provider {
33+
case ProviderGitHub:
34+
o.Provider = installer.ConfigGitHub
35+
case ProviderGitee:
36+
o.Provider = "https://gitee.com/LinuxSuRen/hd-home"
3837
case "":
3938
err = fmt.Errorf("--provider cannot be empty")
4039
return
@@ -56,11 +55,12 @@ func (o *fetchOption) preRunE(_ *cobra.Command, _ []string) (err error) {
5655
}
5756

5857
func (o *fetchOption) runE(cmd *cobra.Command, _ []string) (err error) {
59-
return installer.FetchLatestRepo(o.provider, o.branch, cmd.OutOrStdout())
58+
return installer.FetchLatestRepo(o.Provider, o.branch, cmd.OutOrStdout())
6059
}
6160

6261
type fetchOption struct {
63-
provider string
64-
branch string
65-
reset bool
62+
searchOption
63+
64+
branch string
65+
reset bool
6666
}

cmd/get.go

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"github.com/linuxsuren/http-downloader/pkg"
77
"github.com/linuxsuren/http-downloader/pkg/installer"
88
"github.com/spf13/cobra"
9+
"github.com/spf13/viper"
910
"gopkg.in/yaml.v2"
1011
"net/http"
1112
"net/url"
@@ -29,29 +30,23 @@ func newGetCmd(ctx context.Context) (cmd *cobra.Command) {
2930

3031
// set flags
3132
flags := cmd.Flags()
33+
opt.addFlags(flags)
3234
flags.StringVarP(&opt.Output, "output", "o", "", "Write output to <file> instead of stdout.")
33-
flags.BoolVarP(&opt.Fetch, "fetch", "", true,
34-
"If fetch the latest config from https://github.com/LinuxSuRen/hd-home")
3535
flags.BoolVarP(&opt.AcceptPreRelease, "accept-preRelease", "", false,
3636
"If you accept preRelease as the binary asset from GitHub")
3737
flags.BoolVarP(&opt.AcceptPreRelease, "pre", "", false,
3838
"Same with option --accept-preRelease")
39-
flags.StringVarP(&opt.ProxyGitHub, "proxy-github", "", "",
40-
`The proxy address of github.com, the proxy address will be the prefix of the final address.
41-
Available proxy: gh.api.99988866.xyz
42-
Thanks to https://github.com/hunshcn/gh-proxy`)
4339

4440
flags.IntVarP(&opt.Timeout, "time", "", 10,
4541
`The default timeout in seconds with the HTTP request`)
4642
flags.IntVarP(&opt.MaxAttempts, "max-attempts", "", 10,
4743
`Max times to attempt to download, zero means there's no retry action'`)
4844
flags.BoolVarP(&opt.ShowProgress, "show-progress", "", true, "If show the progress of download")
4945
flags.Int64VarP(&opt.ContinueAt, "continue-at", "", -1, "ContinueAt")
50-
flags.IntVarP(&opt.Thread, "thread", "t", 0,
46+
flags.IntVarP(&opt.Thread, "thread", "t", viper.GetInt("thread"),
5147
`Download file with multi-threads. It only works when its value is bigger than 1`)
5248
flags.BoolVarP(&opt.KeepPart, "keep-part", "", false,
5349
"If you want to keep the part files instead of deleting them")
54-
flags.StringVarP(&opt.Provider, "provider", "", ProviderGitHub, "The file provider")
5550
flags.StringVarP(&opt.OS, "os", "", runtime.GOOS, "The OS of target binary file")
5651
flags.StringVarP(&opt.Arch, "arch", "", runtime.GOARCH, "The arch of target binary file")
5752
flags.BoolVarP(&opt.PrintSchema, "print-schema", "", false,
@@ -63,26 +58,25 @@ Thanks to https://github.com/hunshcn/gh-proxy`)
6358

6459
_ = cmd.RegisterFlagCompletionFunc("proxy-github", ArrayCompletion("gh.api.99988866.xyz",
6560
"ghproxy.com", "mirror.ghproxy.com"))
66-
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, "gitee"))
61+
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, ProviderGitee))
6762
return
6863
}
6964

7065
type downloadOption struct {
71-
URL string
72-
Output string
73-
ShowProgress bool
74-
Fetch bool
66+
searchOption
67+
68+
URL string
69+
Output string
70+
ShowProgress bool
7571
Timeout int
7672
MaxAttempts int
7773
AcceptPreRelease bool
7874
RoundTripper http.RoundTripper
79-
ProxyGitHub string
8075

8176
ContinueAt int64
8277

83-
Provider string
84-
Arch string
85-
OS string
78+
Arch string
79+
OS string
8680

8781
Thread int
8882
KeepPart bool
@@ -101,6 +95,8 @@ type downloadOption struct {
10195
const (
10296
// ProviderGitHub represents https://github.com
10397
ProviderGitHub = "github"
98+
// ProviderGitee represents https://gitee.com
99+
ProviderGitee = "gitee"
104100
)
105101

106102
func (o *downloadOption) preRunE(cmd *cobra.Command, args []string) (err error) {

cmd/install.go

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"github.com/linuxsuren/http-downloader/pkg/installer"
99
"github.com/linuxsuren/http-downloader/pkg/os"
1010
"github.com/spf13/cobra"
11+
"github.com/spf13/viper"
1112
sysos "os"
1213
"path"
1314
"runtime"
@@ -24,16 +25,15 @@ func newInstallCmd(ctx context.Context) (cmd *cobra.Command) {
2425
cmd = &cobra.Command{
2526
Use: "install",
2627
Short: "Install a package from https://github.com/LinuxSuRen/hd-home",
27-
Example: "hd install jenkins-zh/jenkins-cli/jcli -t 6",
28+
Example: "hd install goget",
2829
Args: cobra.MinimumNArgs(1),
2930
PreRunE: opt.preRunE,
3031
RunE: opt.runE,
3132
}
3233

3334
flags := cmd.Flags()
35+
opt.addFlags(flags)
3436
flags.BoolVarP(&opt.ShowProgress, "show-progress", "", true, "If show the progress of download")
35-
flags.BoolVarP(&opt.Fetch, "fetch", "", true,
36-
"If fetch the latest config from https://github.com/LinuxSuRen/hd-home")
3737
flags.BoolVarP(&opt.AcceptPreRelease, "accept-preRelease", "", false,
3838
"If you accept preRelease as the binary asset from GitHub")
3939
flags.BoolVarP(&opt.AcceptPreRelease, "pre", "", false,
@@ -42,28 +42,23 @@ func newInstallCmd(ctx context.Context) (cmd *cobra.Command) {
4242
"Indicate if install it via go install github.com/xxx/xxx")
4343
flags.StringVarP(&opt.fromBranch, "from-branch", "", "master",
4444
"Only works if the flag --from-source is true")
45-
flags.BoolVarP(&opt.goget, "goget", "", false,
45+
flags.BoolVarP(&opt.goget, "goget", "", viper.GetBool("fetch"),
4646
"Use command goget to download the binary, only works if the flag --from-source is true")
47-
flags.StringVarP(&opt.ProxyGitHub, "proxy-github", "", "",
48-
`The proxy address of github.com, the proxy address will be the prefix of the final address.
49-
Available proxy: gh.api.99988866.xyz
50-
Thanks to https://github.com/hunshcn/gh-proxy`)
5147

5248
flags.BoolVarP(&opt.Download, "download", "", true,
5349
"If download the package")
5450
flags.BoolVarP(&opt.force, "force", "f", false,
5551
"Indicate if force to download the package even it is exist")
5652
flags.BoolVarP(&opt.CleanPackage, "clean-package", "", true,
5753
"Clean the package if the installation is success")
58-
flags.IntVarP(&opt.Thread, "thread", "t", 4,
54+
flags.IntVarP(&opt.Thread, "thread", "t", viper.GetInt("thread"),
5955
`Download file with multi-threads. It only works when its value is bigger than 1`)
6056
flags.BoolVarP(&opt.KeepPart, "keep-part", "", false,
6157
"If you want to keep the part files instead of deleting them")
62-
flags.StringVarP(&opt.Provider, "provider", "", ProviderGitHub, "The file provider")
6358
flags.StringVarP(&opt.OS, "os", "", runtime.GOOS, "The OS of target binary file")
6459
flags.StringVarP(&opt.Arch, "arch", "", runtime.GOARCH, "The arch of target binary file")
6560

66-
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, "gitee"))
61+
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, ProviderGitee))
6762
return
6863
}
6964

cmd/root.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
extpkg "github.com/linuxsuren/cobra-extension/pkg"
66
extver "github.com/linuxsuren/cobra-extension/version"
77
"github.com/spf13/cobra"
8+
"github.com/spf13/viper"
9+
"runtime"
810
)
911

1012
// NewRoot returns the root command
@@ -14,9 +16,31 @@ func NewRoot(cxt context.Context) (cmd *cobra.Command) {
1416
Short: "HTTP download tool",
1517
}
1618

19+
if err := loadConfig(); err != nil {
20+
panic(err)
21+
}
22+
1723
cmd.AddCommand(
1824
newGetCmd(cxt), newInstallCmd(cxt), newFetchCmd(cxt), newSearchCmd(cxt), newTestCmd(),
1925
extver.NewVersionCmd("linuxsuren", "http-downloader", "hd", nil),
2026
extpkg.NewCompletionCmd(cmd))
2127
return
2228
}
29+
30+
func loadConfig() (err error) {
31+
viper.SetConfigName("hd")
32+
viper.SetConfigType("yaml")
33+
viper.AddConfigPath("$HOME/.config")
34+
viper.AddConfigPath(".")
35+
if err = viper.ReadInConfig(); err != nil {
36+
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
37+
// Config file not found; ignore error if desired
38+
err = nil
39+
}
40+
}
41+
viper.SetDefault("provider", ProviderGitHub)
42+
viper.SetDefault("fetch", true)
43+
viper.SetDefault("thread", runtime.NumCPU()/2)
44+
viper.SetDefault("goget", false)
45+
return
46+
}

cmd/search.go

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,45 @@ import (
55
"fmt"
66
"github.com/linuxsuren/http-downloader/pkg/installer"
77
"github.com/spf13/cobra"
8+
"github.com/spf13/pflag"
9+
"github.com/spf13/viper"
810
sysos "os"
911
"path"
1012
"path/filepath"
1113
"strings"
1214
)
1315

1416
func newSearchCmd(context.Context) (cmd *cobra.Command) {
17+
opt := &searchOption{}
18+
1519
cmd = &cobra.Command{
1620
Use: "search",
1721
Short: "Search packages from the hd config repo",
1822
Args: cobra.MinimumNArgs(1),
19-
RunE: func(_ *cobra.Command, args []string) (err error) {
20-
err = search(args[0])
21-
return
22-
},
23+
RunE: opt.runE,
2324
}
25+
opt.addFlags(cmd.Flags())
26+
return
27+
}
28+
29+
type searchOption struct {
30+
Fetch bool
31+
Provider string
32+
ProxyGitHub string
33+
}
34+
35+
func (s *searchOption) addFlags(flags *pflag.FlagSet) {
36+
flags.BoolVarP(&s.Fetch, "fetch", "", viper.GetBool("fetch"),
37+
"If fetch the latest config from https://github.com/LinuxSuRen/hd-home")
38+
flags.StringVarP(&s.Provider, "provider", "", viper.GetString("provider"), "The file provider")
39+
flags.StringVarP(&s.ProxyGitHub, "proxy-github", "", viper.GetString("proxy-github"),
40+
`The proxy address of github.com, the proxy address will be the prefix of the final address.
41+
Available proxy: gh.api.99988866.xyz
42+
Thanks to https://github.com/hunshcn/gh-proxy`)
43+
}
44+
45+
func (s *searchOption) runE(_ *cobra.Command, args []string) (err error) {
46+
err = search(args[0])
2447
return
2548
}
2649

go.mod

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ require (
1414
github.com/onsi/ginkgo v1.16.4
1515
github.com/onsi/gomega v1.16.0
1616
github.com/spf13/cobra v1.2.1
17+
github.com/spf13/pflag v1.0.5
18+
github.com/spf13/viper v1.9.0
1719
github.com/stretchr/testify v1.7.0
1820
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8
1921
gopkg.in/yaml.v2 v2.4.0

0 commit comments

Comments
 (0)