Skip to content

Commit

Permalink
support auto-update (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
konoui authored Apr 3, 2021
1 parent 3cfd455 commit 06798a6
Show file tree
Hide file tree
Showing 13 changed files with 656 additions and 214 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
![Generic badge](https://github.com/konoui/alfred-tldr/workflows/test/badge.svg)
![Code Grade](https://www.code-inspector.com/project/20715/status/svg)

## alfred tldr

Expand Down
13 changes: 4 additions & 9 deletions assets/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -210,14 +210,7 @@
<key>escaping</key>
<integer>102</integer>
<key>script</key>
<string>./tldr ${nextCmd} --fuzzy 1&gt; /dev/null
ret=$?
if [ $ret -ne 0 ]; then
echo -n "failed to update tldr database"
exit 1
fi
echo -n "succeeded to update tldr database"</string>
<string>./tldr ${nextCmd} --fuzzy</string>
<key>scriptargtype</key>
<integer>1</integer>
<key>scriptfile</key>
Expand Down Expand Up @@ -331,7 +324,9 @@ echo -n "succeeded to update tldr database"</string>
</dict>
<key>variables</key>
<dict>
<key>ALFRED_TLDR_UPDATE_RECOMMEND</key>
<key>ALFRED_TLDR_WORKFLOW_UPDATE_RECOMMEND</key>
<string>true</string>
<key>ALFRED_TLDR_DB_UPDATE_RECOMMEND</key>
<string>true</string>
</dict>
<key>version</key>
Expand Down
225 changes: 41 additions & 184 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"errors"
"fmt"
"io"
"os"
Expand All @@ -26,22 +25,31 @@ var (
var defaultPlatform = tldr.PlatformOSX

const (
platformFlag = "platform"
updateFlag = "update"
confirmFlag = "confirm"
fuzzyFlag = "fuzzy"
versionFlag = "version"
languageFlag = "language"
longPlatformFlag = "platform"
longUpdateFlag = "update"
longVersionFlag = "version"
longLanguageFlag = "language"
confirmFlag = "confirm"
fuzzyFlag = "fuzzy"
updateWorkflowFlag = "update-workflow"
)

var (
platformFlag = string(longPlatformFlag[0])
updateFlag = string(longUpdateFlag[0])
versionFlag = string(longVersionFlag[0])
languageFlag = strings.ToUpper(string(longLanguageFlag[0]))
)

type config struct {
platform tldr.Platform
language string
update bool
confirm bool
fuzzy bool
version bool
tldrClient *tldr.Tldr
platform tldr.Platform
language string
update bool
updateWorkflow bool
confirm bool
fuzzy bool
version bool
tldrClient *tldr.Tldr
}

// NewRootCmd create a new cmd for root
Expand All @@ -62,27 +70,35 @@ func NewRootCmd() *cobra.Command {
if err := cfg.initTldr(); err != nil {
return err
}
if cfg.version {
return cfg.printVersion(version, revision)
if cfg.updateWorkflow {
return cfg.updateTLDRWorkflow()
}
if cfg.update {
return cfg.updateDB()
}
if cfg.version {
return cfg.printVersion(version, revision)
}
return cfg.printPage(args)
},
SilenceErrors: true,
SilenceUsage: true,
DisableSuggestions: true,
}
rootCmd.PersistentFlags().BoolVarP(&cfg.version, versionFlag, string(versionFlag[0]), false, "show the client version")
rootCmd.PersistentFlags().BoolVarP(&cfg.update, updateFlag, string(updateFlag[0]), false, "update tldr database")
rootCmd.PersistentFlags().StringVarP(&ptString, platformFlag, string(platformFlag[0]),
rootCmd.PersistentFlags().BoolVarP(&cfg.version, longVersionFlag, versionFlag,
false, "show the client version")
rootCmd.PersistentFlags().BoolVarP(&cfg.update, longUpdateFlag, updateFlag,
false, "update tldr database")
rootCmd.PersistentFlags().StringVarP(&ptString, longPlatformFlag, platformFlag,
defaultPlatform.String(), "select from linux/osx/sunos/windows")
rootCmd.PersistentFlags().StringVarP(&cfg.language, languageFlag, "L", "", "select language e.g.) en")
rootCmd.PersistentFlags().StringVarP(&cfg.language, longLanguageFlag, languageFlag, "", "select language e.g.) en")

// internal flag
rootCmd.PersistentFlags().BoolVarP(&cfg.confirm, confirmFlag, string(confirmFlag[0]), false, "confirmation for update")
rootCmd.PersistentFlags().BoolVar(&cfg.confirm, confirmFlag,
false, "confirmation for update")
rootCmd.PersistentFlags().BoolVar(&cfg.fuzzy, fuzzyFlag, false, "use fuzzy search")
rootCmd.PersistentFlags().BoolVar(&cfg.updateWorkflow, updateWorkflowFlag, false,
"update tldr workflow if possible")

rootCmd.SetUsageFunc(usageFunc)
rootCmd.SetHelpFunc(helpFunc)
Expand Down Expand Up @@ -110,10 +126,10 @@ func flagErrorFunc(cmd *cobra.Command, err error) error {

func showWorkflowUsage(cmd *cobra.Command) {
pflags := []*pflag.Flag{
cmd.Flag(platformFlag),
cmd.Flag(updateFlag),
cmd.Flag(versionFlag),
cmd.Flag(languageFlag),
cmd.Flag(longPlatformFlag),
cmd.Flag(longUpdateFlag),
cmd.Flag(longVersionFlag),
cmd.Flag(longLanguageFlag),
}

for _, p := range pflags {
Expand Down Expand Up @@ -167,165 +183,6 @@ func (cfg *config) initTldr() error {
return cfg.tldrClient.OnInitialize()
}

func (cfg *config) printPage(cmds []string) error {
// insert update recommendation first
if isUpdateRecommendEnabled() && cfg.tldrClient.Expired(twoWeeks) {
awf.Append(
alfred.NewItem().
Title("Please Enter! Tldr database is older than 2 weeks").
Arg(fmt.Sprintf("--%s --%s", updateFlag, confirmFlag)).
Icon(alfred.IconAlertNote),
).Variable(nextActionKey, nextActionShell)
}

// no input case
if len(cmds) == 0 {
awf.Append(
alfred.NewItem().
Title("Please input a command").
Subtitle("e.g.) tldr tar e.g.) tldr --help").
Valid(false),
).Output()
return nil
}

awf.SetEmptyWarning("No matching query", "Try a different query")
p, err := cfg.tldrClient.FindPage(cmds)
if err != nil {
if errors.Is(err, tldr.ErrNotFoundPage) {
if cfg.language != "" {
awf.Clear().SetEmptyWarning(
"Not found the command in selected language",
"Try not to specify language option",
).Output()
return nil
}
if cfg.fuzzy {
// list suggestions
return cfg.printFuzzyPages(cmds)
}
awf.Output()
return nil
}
return err
}

// TODO change icon for usage
// descriptions has one line at least
// see: https://github.com/tldr-pages/tldr/blob/master/contributing-guides/style-guide.md
title := p.CmdDescriptions[0]
subtitle := ""
if len(p.CmdDescriptions) >= 2 {
subtitle = p.CmdDescriptions[1]
}
awf.Append(
alfred.NewItem().
Title(title).
Subtitle(subtitle).
Valid(false).
Icon(
alfred.NewIcon().
Path("description.png"),
),
)
for _, cmd := range p.CmdExamples {
awf.Append(
alfred.NewItem().
Title(cmd.Cmd).
Subtitle(cmd.Description).
Arg(cmd.Cmd),
).Variable(nextActionKey, nextActionCopy)
}

awf.Output()
return nil
}

func (cfg *config) printFuzzyPages(cmds []string) error {
index, err := cfg.tldrClient.LoadIndexFile()
if err != nil {
return err
}

suggestions := index.Commands.Search(cmds)
for _, cmd := range suggestions {
complete := cmd.Name
pt := choicePlatform(cmd.Platforms, cfg.platform)
if pt != tldr.PlatformCommon && pt != defaultPlatform {
complete = fmt.Sprintf("-%s %s %s",
string(platformFlag[0]),
pt,
cmd.Name,
)
}
awf.Append(
alfred.NewItem().
Title(cmd.Name).
Subtitle(fmt.Sprintf("Platforms: %s", fmt.Sprintf("%s", cmd.Platforms))).
Valid(false).
Autocomplete(complete).
Icon(
alfred.NewIcon().
Path("candidate.png"),
),
)
}

awf.Output()
return nil
}

func (cfg *config) printVersion(v, r string) (_ error) {
title := fmt.Sprintf("alfred-tldr %v(%s)", v, r)
awf.Append(
alfred.NewItem().Title(title),
).Output()
return
}

func (cfg *config) updateDB() error {
if !cfg.update {
return errors.New("update is called even though update flag is not specified")
}

if cfg.confirm {
// update explicitly
awf.Logger().Infoln("updating tldr database...")
return cfg.tldrClient.Update()
}

awf.Append(
alfred.NewItem().
Title("Please Enter if update tldr database").
Arg(fmt.Sprintf("--%s --%s", updateFlag, confirmFlag)),
).
Variable(nextActionKey, nextActionShell).
Output()

return nil
}

func choicePlatform(pts []tldr.Platform, selected tldr.Platform) tldr.Platform {
if len(pts) >= 2 {
// if there are more than two platforms,
// priority are follow
// selected pt, common, others
for _, pt := range pts {
if pt == selected {
return selected
}
}

for _, pt := range pts {
if pt == tldr.PlatformCommon {
return tldr.PlatformCommon
}
}
}

return pts[0]
}

// Execute Execute root cmd
func Execute(rootCmd *cobra.Command) {
rootCmd.SetOut(outStream)
Expand Down
Loading

0 comments on commit 06798a6

Please sign in to comment.