Revamp config, Gofmt project, and clean up unneeded code
This commit is contained in:
113
main.go
113
main.go
@@ -19,36 +19,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/pelletier/go-toml"
|
||||
"io/ioutil"
|
||||
flag "github.com/spf13/pflag"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Put all arguments into a variable
|
||||
args := os.Args[1:]
|
||||
func main() {
|
||||
|
||||
// Check which currentUser is running command
|
||||
currentUser, err := user.Current()
|
||||
if err != nil { log.Fatal(err) }
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Create help flags
|
||||
var helpFlagGiven bool
|
||||
flag.BoolVar(&helpFlagGiven, "help", false, "Show help screen")
|
||||
flag.BoolVar(&helpFlagGiven, "h", false, "Show help screen (shorthand)")
|
||||
flag.BoolVarP(&helpFlagGiven, "help", "h", false, "Show help screen")
|
||||
|
||||
// Check to make sure root is not being used unless -r/--root specified
|
||||
var rootCheckBypass bool
|
||||
// Create --root and -r flags for root check bypass
|
||||
flag.BoolVar(&rootCheckBypass,"root", false, "Bypass root check")
|
||||
flag.BoolVar(&rootCheckBypass,"r", false, "Bypass root check (shorthand)")
|
||||
flag.BoolVarP(&rootCheckBypass, "root", "r", false, "Bypass root check")
|
||||
|
||||
var packageManagerOverride string
|
||||
flag.StringVarP(&packageManagerOverride, "package-manager", "p", os.Getenv("PAK_MGR_OVERRIDE"), "Override package manager wrapped by pak")
|
||||
// Parse arguments for flags
|
||||
flag.Parse()
|
||||
|
||||
@@ -63,108 +61,101 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Create regex to remove all flags using ";;;" as it is uncommon to use in command line
|
||||
flagRegex := regexp.MustCompile(`(?m)(;;;|^)-+[^;]*;;;`)
|
||||
// Join args into string
|
||||
argsStr := strings.Join(args, ";;;")
|
||||
// Remove all flags from join args
|
||||
argsStr = flagRegex.ReplaceAllString(argsStr, "$1")
|
||||
// Separate args back into slice
|
||||
args = strings.Split(argsStr, ";;;")
|
||||
// Get arguments without flags
|
||||
args := flag.Args()
|
||||
|
||||
// Define variables for config file location, and override state boolean
|
||||
var configFileLocation string
|
||||
var isOverridden bool
|
||||
// Get PAK_MGR_OVERRIDE environment variable
|
||||
override := os.Getenv("PAK_MGR_OVERRIDE")
|
||||
|
||||
// Read /etc/pak.toml into new Config{}
|
||||
config := NewConfig("/etc/pak.toml")
|
||||
|
||||
// If override is set
|
||||
if override != "" {
|
||||
// Set configFileLocation to /etc/pak.d/{override}.cfg
|
||||
configFileLocation = "/etc/pak.d/" + override + ".cfg"
|
||||
if packageManagerOverride != "" {
|
||||
// Set active package manager to override
|
||||
config.ActiveManager = packageManagerOverride
|
||||
// Set override state to true
|
||||
isOverridden = true
|
||||
} else {
|
||||
// Otherwise, set configFileLocation to default config
|
||||
configFileLocation = "/etc/pak.cfg"
|
||||
// Set override state to false
|
||||
isOverridden = false
|
||||
}
|
||||
|
||||
// Parse config file removing all comments and empty lines
|
||||
config, err := ioutil.ReadFile(configFileLocation)
|
||||
parsedConfig, _ := toml.Load(string(config))
|
||||
|
||||
// Set first line of config to variable
|
||||
packageManagerCommand := parsedConfig.Get("packageManager").(string)
|
||||
//fmt.Println(packageManagerCommand) //DEBUG
|
||||
|
||||
// Parse list of commands in config line 2 and set to variable as array
|
||||
commands := InterfaceToString(parsedConfig.Get("commands").([]interface{}))
|
||||
commands := config.Managers[config.ActiveManager].Commands
|
||||
//fmt.Println(commands) //DEBUG
|
||||
|
||||
// Set the root option in config line 3 to a variable
|
||||
useRoot := parsedConfig.Get("useRoot").(bool)
|
||||
useRoot := config.Managers[config.ActiveManager].UseRoot
|
||||
//fmt.Println(useRoot) //DEBUG
|
||||
|
||||
// Set command to use to invoke root at config line 4 to a variable
|
||||
rootCommand := parsedConfig.Get("rootCommand").(string)
|
||||
rootCommand := config.RootCommand
|
||||
//fmt.Println(rootCommand) //DEBUG
|
||||
|
||||
// Parse list of shortcuts in config and line 5 set to variable as an array
|
||||
shortcuts := InterfaceToString(parsedConfig.Get("shortcuts").([]interface{}))
|
||||
shortcuts := config.Managers[config.ActiveManager].Shortcuts
|
||||
//fmt.Println(shortcuts) //DEBUG
|
||||
|
||||
// Parse list of shortcuts in config line 6 and set to variable as array
|
||||
shortcutMappings := InterfaceToString(parsedConfig.Get("shortcutMappings").([]interface{}))
|
||||
//fmt.Println(shortcutMappings) //DEBUG
|
||||
|
||||
// Create similar to slice to put all matched commands into
|
||||
var similarTo []string
|
||||
|
||||
// Displays help message if no arguments provided or -h/--help is passed
|
||||
if len(args) == 0 || helpFlagGiven || Contains(args, "help") {
|
||||
printHelpMessage(packageManagerCommand, useRoot, rootCommand, commands, shortcuts, shortcutMappings, isOverridden)
|
||||
printHelpMessage(config.ActiveManager, useRoot, rootCommand, commands, shortcuts, isOverridden)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// Create distance slice to store JaroWinkler distance values
|
||||
var distance []float64
|
||||
distance := map[string]float64{}
|
||||
// Appends JaroWinkler distance between each available command and the first argument to an array
|
||||
for _,command := range commands {
|
||||
distance = append(distance, JaroWinkler(command, args[0], 1, 0))
|
||||
for command := range commands {
|
||||
distance[command] = JaroWinkler(command, args[0], 1, 0)
|
||||
}
|
||||
|
||||
// Deals with shortcuts
|
||||
for index, shortcut := range shortcuts {
|
||||
for shortcut, mapping := range shortcuts {
|
||||
// If the first argument is a shortcut and similarTo does not already contain its mapping, append it
|
||||
if args[0] == shortcut && !Contains(similarTo, shortcutMappings[index]) {
|
||||
similarTo = append(similarTo, shortcutMappings[index])
|
||||
if args[0] == shortcut && !Contains(similarTo, mapping) {
|
||||
similarTo = append(similarTo, mapping)
|
||||
}
|
||||
}
|
||||
|
||||
// Compares each distance to the max of the distance slice and appends the closest command to similarTo
|
||||
for index, element := range distance {
|
||||
for command, cmdDist := range distance {
|
||||
// If current element is the closest to the first argument
|
||||
if element == Max(distance) {
|
||||
if cmdDist == Max(GetValuesDist(distance)) {
|
||||
// Append command at same index as distance to similarTo
|
||||
similarTo = append(similarTo, commands[index])
|
||||
similarTo = append(similarTo, commands[command])
|
||||
}
|
||||
}
|
||||
|
||||
// If similarTo is still empty, log it fatally as something is wrong with the config or the code
|
||||
if len(similarTo) == 0 { log.Fatalln("This command does not match any known commands or shortcuts") }
|
||||
if len(similarTo) == 0 {
|
||||
log.Fatalln("This command does not match any known commands or shortcuts")
|
||||
}
|
||||
// Anonymous function to decide whether to print (overridden)
|
||||
printOverridden := func() string { if isOverridden { return "(overridden)" } else { return "" } }
|
||||
printOverridden := func() string {
|
||||
if isOverridden {
|
||||
return "(overridden)"
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
// Print text showing command being run and package manager being used
|
||||
fmt.Println("Running:", strings.Title(similarTo[0]), "using", strings.Title(packageManagerCommand), printOverridden())
|
||||
fmt.Println("Running:", strings.Title(GetKey(commands, similarTo[0])), "using", strings.Title(config.ActiveManager), printOverridden())
|
||||
// Run package manager with the proper arguments passed if more than one argument exists
|
||||
var cmdArr []string
|
||||
// If root is to be used, append it to cmdArr
|
||||
if useRoot { cmdArr = append(cmdArr, rootCommand) }
|
||||
if useRoot {
|
||||
cmdArr = append(cmdArr, rootCommand)
|
||||
}
|
||||
// Create slice with all commands and arguments for the package manager
|
||||
cmdArr = append(cmdArr, []string{packageManagerCommand, similarTo[0]}...)
|
||||
cmdArr = append(cmdArr, config.ActiveManager, similarTo[0])
|
||||
// If greater than 2 arguments, append them to cmdArr
|
||||
if len(args) >= 2 { cmdArr = append(cmdArr, strings.Join(args[1:], " ")) }
|
||||
if len(args) >= 2 {
|
||||
cmdArr = append(cmdArr, strings.Join(args[1:], " "))
|
||||
}
|
||||
// Create space separated string from cmdArr
|
||||
cmdStr := strings.Join(cmdArr, " ")
|
||||
// Instantiate exec.Command object with command sh, flag -c, and cmdStr
|
||||
@@ -180,4 +171,4 @@ func main() {
|
||||
fmt.Println("Error received from child process")
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user