Skip to content

Commit

Permalink
Merge pull request #26 from MrLYC/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
MrLYC authored May 14, 2023
2 parents bddd88c + 4fa6ed9 commit c00a0e0
Show file tree
Hide file tree
Showing 11 changed files with 139 additions and 79 deletions.
77 changes: 44 additions & 33 deletions cmd/command/list.go
Original file line number Diff line number Diff line change
@@ -1,67 +1,76 @@
package command

import (
"fmt"
"os"
"strings"

"github.com/mgutz/ansi"
"github.com/spf13/cobra"

"github.com/mrlyc/cmdr/core"
"github.com/mrlyc/cmdr/core/utils"
"github.com/tomlazar/table"
)

// listCmd represents the list command
var listCmd = &cobra.Command{
Use: "list",
Short: "List commands",
Run: runCommand(func(cfg core.Configuration, manager core.CommandManager) error {
name := cfg.GetString(core.CfgKeyXCommandListName)
version := cfg.GetString(core.CfgKeyXCommandListVersion)
location := cfg.GetString(core.CfgKeyXCommandListLocation)
activate := cfg.GetBool(core.CfgKeyXCommandListActivate)

query, err := manager.Query()
commands, err := queryCommands(
manager,
cfg.GetBool(core.CfgKeyXCommandListActivate),
cfg.GetString(core.CfgKeyXCommandListName),
cfg.GetString(core.CfgKeyXCommandListVersion),
cfg.GetString(core.CfgKeyXCommandListLocation),
)
if err != nil {
return err
}

if name != "" {
query.WithName(name)
}

if version != "" {
query.WithVersion(version)
}
fields := cfg.GetStringSlice(core.CfgKeyXCommandListFields)
rowMaker := func(activateFlag string, name string, version string, location string) []string {
mappings := map[string]string{
"activated": activateFlag,
"name": name,
"version": version,
"location": location,
}

if location != "" {
query.WithLocation(location)
}
results := make([]string, 0, len(fields))
for _, field := range fields {
result, ok := mappings[strings.ToLower(field)]
if ok {
results = append(results, result)
}
}

if activate {
query.WithActivated(activate)
return results
}

commands, err := query.All()
if err != nil {
return err
tab := table.Table{
Headers: rowMaker("Activated", "Name", "Version", "Location"),
}

utils.SortCommands(commands)
for _, command := range commands {
var parts []string
if command.GetActivated() {
parts = append(parts, "*")
} else {
parts = append(parts, " ")
for _, cmd := range commands {
activated := ""
if cmd.GetActivated() {
activated = "*"
}

parts = append(parts, command.GetName(), command.GetVersion())

_, _ = fmt.Fprintf(os.Stdout, "%s\n", strings.Join(parts, " "))
tab.Rows = append(tab.Rows, rowMaker(
activated,
cmd.GetName(),
cmd.GetVersion(),
cmd.GetLocation(),
))
}

return nil
return tab.WriteTable(os.Stdout, &table.Config{
Color: true,
AlternateColors: true,
TitleColorCode: ansi.ColorCode("white+buf"),
})
}),
}

Expand All @@ -72,6 +81,7 @@ func init() {
flags.StringP("version", "v", "", "command version")
flags.StringP("location", "l", "", "command location")
flags.BoolP("activate", "a", false, "activate command")
flags.StringSliceP("fields", "f", []string{"Activated", "Name", "Version", "Location"}, "fields to display")

cfg := core.GetConfiguration()

Expand All @@ -80,6 +90,7 @@ func init() {
cfg.BindPFlag(core.CfgKeyXCommandListVersion, flags.Lookup("version")),
cfg.BindPFlag(core.CfgKeyXCommandListLocation, flags.Lookup("location")),
cfg.BindPFlag(core.CfgKeyXCommandListActivate, flags.Lookup("activate")),
cfg.BindPFlag(core.CfgKeyXCommandListFields, flags.Lookup("fields")),

utils.NewDefaultCobraCommandCompleteHelper(listCmd).RegisterAll(),
)
Expand Down
31 changes: 31 additions & 0 deletions cmd/command/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,34 @@ import (
func runCommand(fn func(cfg core.Configuration, manager core.CommandManager) error) func(cmd *cobra.Command, args []string) {
return utils.RunCobraCommandWith(core.CommandProviderDefault, fn)
}

func queryCommands(manager core.CommandManager, activate bool, name, version, location string) ([]core.Command, error) {
query, err := manager.Query()
if err != nil {
return nil, err
}

if activate {
query.WithActivated(activate)
}

if name != "" {
query.WithName(name)
}

if version != "" {
query.WithVersion(version)
}

if location != "" {
query.WithLocation(location)
}

commands, err := query.All()
if err != nil {
return nil, err
}

utils.SortCommands(commands)
return commands, nil
}
14 changes: 14 additions & 0 deletions cmd/command/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,18 @@ var _ = Describe("Utils", func() {

fn(&cmd, []string{})
})

It("should query commands", func() {
query := mock.NewMockCommandQuery(ctrl)
query.EXPECT().WithActivated(true).Return(query)
query.EXPECT().WithName("name").Return(query)
query.EXPECT().WithVersion("version").Return(query)
query.EXPECT().WithLocation("location").Return(query)
query.EXPECT().All().Return(nil, nil)

manager.EXPECT().Query().Return(query, nil)

_, err := queryCommands(manager, true, "name", "version", "location")
Expect(err).To(BeNil())
})
})
1 change: 1 addition & 0 deletions core/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ const (
CfgKeyXCommandListVersion = "_.command.list.version"
CfgKeyXCommandListLocation = "_.command.list.location"
CfgKeyXCommandListActivate = "_.command.list.activate"
CfgKeyXCommandListFields = "_.command.list.fields"
// cmd.command.remove
CfgKeyXCommandRemoveName = "_.command.remove.name"
CfgKeyXCommandRemoveVersion = "_.command.remove.version"
Expand Down
5 changes: 4 additions & 1 deletion core/fetcher/go.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,14 @@ func (g *GoInstaller) Fetch(name, version, uri, dst string) error {
}

var err error
logger.Warn("version suffix not set, retry by version")
for _, detected := range []string{
fmt.Sprintf("%s@%s", location, version),
fmt.Sprintf("%s@v%s", location, version),
fmt.Sprintf("%s@latest", location),
} {
logger.Warn("version suffix not set, detecting", map[string]interface{}{
"suffix": detected,
})
err := g.install(detected, dst)
if err == nil {
break
Expand Down
46 changes: 9 additions & 37 deletions core/initializer/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"os"

"github.com/hashicorp/go-multierror"
ver "github.com/hashicorp/go-version"
"github.com/pkg/errors"

"github.com/mrlyc/cmdr/core"
Expand All @@ -16,26 +17,9 @@ type CmdrUpdater struct {
manager core.CommandManager
}

func (c *CmdrUpdater) getActivatedCmdrVersion() string {
query, err := c.manager.Query()
if err != nil {
return ""
}

command, err := query.
WithName(c.name).
WithActivated(true).
One()

if err != nil {
return ""
}

return command.GetVersion()
}

func (c *CmdrUpdater) removeLegacies(safeVersions []string) error {
func (c *CmdrUpdater) removeLegacies() error {
logger := core.GetLogger()
currentVersion := ver.Must(ver.NewVersion(c.version))

query, err := c.manager.Query()
if err != nil {
Expand All @@ -52,31 +36,25 @@ func (c *CmdrUpdater) removeLegacies(safeVersions []string) error {

var errs error
for _, command := range commands {
logger.Debug("checking legacy command", map[string]interface{}{
logger.Debug("checking command", map[string]interface{}{
"command": command,
})

if command.GetActivated() {
continue
}

version := command.GetVersion()
isSafe := false
for _, safeVersion := range safeVersions {
if safeVersion == version {
isSafe = true
break
}
}
definedVersion := command.GetVersion()
semver := ver.Must(ver.NewVersion(definedVersion))

if isSafe {
if currentVersion.Compare(semver) <= 0 {
continue
}

logger.Info("removing legacy cmdr", map[string]interface{}{
"command": command,
})
err = c.manager.Undefine(c.name, version)
err = c.manager.Undefine(c.name, definedVersion)
if err != nil {
errs = multierror.Append(errs, err)
}
Expand All @@ -87,12 +65,6 @@ func (c *CmdrUpdater) removeLegacies(safeVersions []string) error {

func (c *CmdrUpdater) Init(isUpgrade bool) error {
logger := core.GetLogger()
safeVersion := []string{c.version}
version := c.getActivatedCmdrVersion()
if version != "" {
safeVersion = append(safeVersion, version)
}

logger.Debug("update command", map[string]interface{}{
"name": c.name,
"version": c.version,
Expand All @@ -110,7 +82,7 @@ func (c *CmdrUpdater) Init(isUpgrade bool) error {
return errors.Wrapf(err, "failed to activate command %s", c.name)
}

return c.removeLegacies(safeVersion)
return c.removeLegacies()
}

func NewCmdrUpdater(manager core.CommandManager, name, version, localtion string) *CmdrUpdater {
Expand Down
2 changes: 1 addition & 1 deletion core/manager/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func (m *DownloadManager) fetch(fetcher core.Fetcher, name, version, location, o
if err == nil {
break
} else {
logger.Warn("failed to download %s, retrying...", map[string]interface{}{
logger.Warn("download failed, retrying...", map[string]interface{}{
"uri": location,
})
}
Expand Down
8 changes: 4 additions & 4 deletions core/mock/initializer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ require (
github.com/klauspost/compress v1.15.11 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mattn/go-runewidth v0.0.13 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
Expand All @@ -73,6 +75,7 @@ require (
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.8.2 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/tomlazar/table v0.1.2 // indirect
github.com/ulikunitz/xz v0.5.10 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
Expand Down
11 changes: 11 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -431,14 +431,22 @@ github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i
github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls=
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
Expand Down Expand Up @@ -538,6 +546,8 @@ github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tomlazar/table v0.1.2 h1:DP8f62FzZAZk8oavepm1v/oyf4ni3/LMHWNlOinmleg=
github.com/tomlazar/table v0.1.2/go.mod h1:IecZnpep9f/BatHacfh+++ftE+lFONN8BVPi9nx5U1w=
github.com/ulikunitz/xz v0.5.10 h1:t92gobL9l3HE202wg3rlk19F6X+JOxl9BBrCCMYEYd8=
github.com/ulikunitz/xz v0.5.10/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/urfave/cli v1.22.3/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
Expand Down Expand Up @@ -788,6 +798,7 @@ golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
Expand Down
Loading

0 comments on commit c00a0e0

Please sign in to comment.