Skip to content

Commit

Permalink
Add support read config from a config file (#180)
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen authored Oct 22, 2021
1 parent 46bca63 commit 4128c61
Show file tree
Hide file tree
Showing 7 changed files with 188 additions and 52 deletions.
24 changes: 12 additions & 12 deletions cmd/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,22 @@ func newFetchCmd(context.Context) (cmd *cobra.Command) {
}

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

_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, "gitee"))
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, ProviderGitee))
return
}

func (o *fetchOption) preRunE(_ *cobra.Command, _ []string) (err error) {
switch o.provider {
case "github":
o.provider = installer.ConfigGitHub
case "gitee":
o.provider = "https://gitee.com/LinuxSuRen/hd-home"
switch o.Provider {
case ProviderGitHub:
o.Provider = installer.ConfigGitHub
case ProviderGitee:
o.Provider = "https://gitee.com/LinuxSuRen/hd-home"
case "":
err = fmt.Errorf("--provider cannot be empty")
return
Expand All @@ -56,11 +55,12 @@ func (o *fetchOption) preRunE(_ *cobra.Command, _ []string) (err error) {
}

func (o *fetchOption) runE(cmd *cobra.Command, _ []string) (err error) {
return installer.FetchLatestRepo(o.provider, o.branch, cmd.OutOrStdout())
return installer.FetchLatestRepo(o.Provider, o.branch, cmd.OutOrStdout())
}

type fetchOption struct {
provider string
branch string
reset bool
searchOption

branch string
reset bool
}
30 changes: 13 additions & 17 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/linuxsuren/http-downloader/pkg"
"github.com/linuxsuren/http-downloader/pkg/installer"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
"net/http"
"net/url"
Expand All @@ -29,29 +30,23 @@ func newGetCmd(ctx context.Context) (cmd *cobra.Command) {

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

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

_ = cmd.RegisterFlagCompletionFunc("proxy-github", ArrayCompletion("gh.api.99988866.xyz",
"ghproxy.com", "mirror.ghproxy.com"))
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, "gitee"))
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, ProviderGitee))
return
}

type downloadOption struct {
URL string
Output string
ShowProgress bool
Fetch bool
searchOption

URL string
Output string
ShowProgress bool
Timeout int
MaxAttempts int
AcceptPreRelease bool
RoundTripper http.RoundTripper
ProxyGitHub string

ContinueAt int64

Provider string
Arch string
OS string
Arch string
OS string

Thread int
KeepPart bool
Expand All @@ -101,6 +95,8 @@ type downloadOption struct {
const (
// ProviderGitHub represents https://github.com
ProviderGitHub = "github"
// ProviderGitee represents https://gitee.com
ProviderGitee = "gitee"
)

func (o *downloadOption) preRunE(cmd *cobra.Command, args []string) (err error) {
Expand Down
17 changes: 6 additions & 11 deletions cmd/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/linuxsuren/http-downloader/pkg/installer"
"github.com/linuxsuren/http-downloader/pkg/os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
sysos "os"
"path"
"runtime"
Expand All @@ -24,16 +25,15 @@ func newInstallCmd(ctx context.Context) (cmd *cobra.Command) {
cmd = &cobra.Command{
Use: "install",
Short: "Install a package from https://github.com/LinuxSuRen/hd-home",
Example: "hd install jenkins-zh/jenkins-cli/jcli -t 6",
Example: "hd install goget",
Args: cobra.MinimumNArgs(1),
PreRunE: opt.preRunE,
RunE: opt.runE,
}

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

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

_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, "gitee"))
_ = cmd.RegisterFlagCompletionFunc("provider", ArrayCompletion(ProviderGitHub, ProviderGitee))
return
}

Expand Down
24 changes: 24 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
extpkg "github.com/linuxsuren/cobra-extension/pkg"
extver "github.com/linuxsuren/cobra-extension/version"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"runtime"
)

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

if err := loadConfig(); err != nil {
panic(err)
}

cmd.AddCommand(
newGetCmd(cxt), newInstallCmd(cxt), newFetchCmd(cxt), newSearchCmd(cxt), newTestCmd(),
extver.NewVersionCmd("linuxsuren", "http-downloader", "hd", nil),
extpkg.NewCompletionCmd(cmd))
return
}

func loadConfig() (err error) {
viper.SetConfigName("hd")
viper.SetConfigType("yaml")
viper.AddConfigPath("$HOME/.config")
viper.AddConfigPath(".")
if err = viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
err = nil
}
}
viper.SetDefault("provider", ProviderGitHub)
viper.SetDefault("fetch", true)
viper.SetDefault("thread", runtime.NumCPU()/2)
viper.SetDefault("goget", false)
return
}
31 changes: 27 additions & 4 deletions cmd/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,45 @@ import (
"fmt"
"github.com/linuxsuren/http-downloader/pkg/installer"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
sysos "os"
"path"
"path/filepath"
"strings"
)

func newSearchCmd(context.Context) (cmd *cobra.Command) {
opt := &searchOption{}

cmd = &cobra.Command{
Use: "search",
Short: "Search packages from the hd config repo",
Args: cobra.MinimumNArgs(1),
RunE: func(_ *cobra.Command, args []string) (err error) {
err = search(args[0])
return
},
RunE: opt.runE,
}
opt.addFlags(cmd.Flags())
return
}

type searchOption struct {
Fetch bool
Provider string
ProxyGitHub string
}

func (s *searchOption) addFlags(flags *pflag.FlagSet) {
flags.BoolVarP(&s.Fetch, "fetch", "", viper.GetBool("fetch"),
"If fetch the latest config from https://github.com/LinuxSuRen/hd-home")
flags.StringVarP(&s.Provider, "provider", "", viper.GetString("provider"), "The file provider")
flags.StringVarP(&s.ProxyGitHub, "proxy-github", "", viper.GetString("proxy-github"),
`The proxy address of github.com, the proxy address will be the prefix of the final address.
Available proxy: gh.api.99988866.xyz
Thanks to https://github.com/hunshcn/gh-proxy`)
}

func (s *searchOption) runE(_ *cobra.Command, args []string) (err error) {
err = search(args[0])
return
}

Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ require (
github.com/onsi/ginkgo v1.16.4
github.com/onsi/gomega v1.16.0
github.com/spf13/cobra v1.2.1
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.9.0
github.com/stretchr/testify v1.7.0
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8
gopkg.in/yaml.v2 v2.4.0
Expand Down
Loading

0 comments on commit 4128c61

Please sign in to comment.