-
Notifications
You must be signed in to change notification settings - Fork 10
/
alias.go
100 lines (83 loc) · 2.63 KB
/
alias.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package commands
import (
"fmt"
"sort"
"strings"
"github.com/AbGuthrie/goquery/v2/models"
"github.com/AbGuthrie/goquery/v2/config"
"github.com/AbGuthrie/goquery/v2/utils"
prompt "github.com/c-bata/go-prompt"
)
func printAliases(config *config.Config) {
aliases := config.Aliases
aliasNames := make([]string, 0)
for name := range aliases {
aliasNames = append(aliasNames, name)
}
sort.Strings(aliasNames)
aliasRows := make([]map[string]string, 0)
for _, aliasName := range aliasNames {
aliasRows = append(aliasRows, map[string]string{
"alias": aliasName,
"command": aliases[aliasName].Command,
"description": aliases[aliasName].Description,
})
}
utils.PrettyPrintQueryResults(aliasRows, config.PrintMode)
}
func alias(api models.GoQueryAPI, config *config.Config, cmdline string) error {
args := strings.Split(cmdline, " ")
// If no args provided, print current state of aliases
if len(args) == 1 {
printAliases(config)
return nil
}
// If '--add' argument provided, try remove alias from config
if args[1] == "--add" {
if len(args) < 4 {
return fmt.Errorf("--add flag requires an alias arguments: ALIAS_NAME ALIAS_COMMAND")
}
args = args[2:]
name := args[0]
command := ""
if len(args) > 1 {
command = strings.Join(args[1:], " ")
}
// Create the command and store in state
err := config.AddAlias(name, command)
if err != nil {
return fmt.Errorf(fmt.Sprintf("Error creating alias: %s\n", err))
}
fmt.Printf("Created new alias '%s' with command: %s\n", name, command)
return nil
}
// Handled --add by now, is input any other than '--remove' ?
if args[1] != "--remove" {
return fmt.Errorf(".alias must be called with either '--add' or '--remove' flags")
}
if len(args) == 2 {
return fmt.Errorf("--remove flag requires an alias name argument")
}
// Argument provided, try remove alias from config
if err := config.RemoveAlias(args[2]); err != nil {
return err
}
fmt.Printf("Successfully removed alias\n")
return nil
}
func aliasHelp() string {
return "Create a new alias or call with no arguments to list current aliases. " +
"The format for creating an alias is as follows: ALIAS_NAME .example arg1 $# arg3" +
"To remove an alias, use .alias --remove ALIAS_NAME"
}
func aliasSuggest(cmdline string) []prompt.Suggest {
// If just at .alias, suggest the flags
args := strings.Split(cmdline, " ")
if len(args) == 2 && args[1] == "" {
return []prompt.Suggest{
prompt.Suggest{Text: "--add", Description: "Use this flag to create a new alias"},
prompt.Suggest{Text: "--remove", Description: "Use this flag to remove an alias by name"},
}
}
return []prompt.Suggest{}
}