Skip to content

Commit

Permalink
feat: add verbose flag (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
doron-cohen committed Nov 9, 2020
1 parent aa488a8 commit 74792b4
Show file tree
Hide file tree
Showing 12 changed files with 67 additions and 58 deletions.
24 changes: 9 additions & 15 deletions cmd/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"fmt"
"log"
"os"

"github.com/spf13/cobra"
Expand All @@ -21,28 +20,24 @@ var cleanCmd = &cobra.Command{
Use: "clean",
Short: "Clean up dotfiles from your $HOME",
Run: func(cmd *cobra.Command, args []string) {
log.Println("Cleaning up!")
tui.Debug("Cleaning up!")

_, err := rules.LoadRulesConfig(rulesFilePath)
if err != nil {
if _, rulesMissing := err.(*rules.MissingRulesFile); rulesMissing {
log.Println("Couldn't find rules file. Please run `antidot update`.")
tui.Print("Couldn't find rules file. Please run `antidot update`.")
os.Exit(2)
}
log.Fatalln("Failed to read rules file: ", err)
tui.FatalIfError("Failed to read rules file", err)
}

userHomeDir, err := utils.GetHomeDir()
if err != nil {
log.Fatalln("Unable to detect user home dir: ", err)
}
tui.FatalIfError("Unable to detect user home dir", err)

dotfiles, err := dotfile.Detect(userHomeDir)
if err != nil {
log.Fatalln("Failed to detect dotfiles in home dir: ", err)
}
tui.FatalIfError("Failed to detect dotfiles in home dir", err)

log.Printf("Found %d dotfiles in %s\n", len(dotfiles), userHomeDir)
tui.Debug("Found %d dotfiles in %s", len(dotfiles), userHomeDir)

for _, dotfile := range dotfiles {
rule := rules.MatchRule(&dotfile)
Expand All @@ -52,12 +47,11 @@ var cleanCmd = &cobra.Command{

rule.Pprint()
confirmed := tui.Confirm(fmt.Sprintf("Apply rule %s?", rule.Name))
if !confirmed {
log.Println("Not applying rule")
continue
if confirmed {
rule.Apply()
}

rule.Apply()
tui.Print("") // one line space
}
},
}
14 changes: 4 additions & 10 deletions cmd/init.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package cmd

import (
"fmt"
"log"

"github.com/spf13/cobra"

"github.com/doron-cohen/antidot/internal/tui"
"github.com/doron-cohen/antidot/internal/utils"
)

Expand All @@ -19,16 +17,12 @@ var initCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
// TODO: detect shell and generate appropriate script
envFilePath, err := utils.GetEnvFile()
if err != nil {
log.Fatalf("Failed to get env file path: %v", err)
}
tui.FatalIfError("Failed to get env file path", err)

aliasFilePath, err := utils.GetAliasFile()
if err != nil {
log.Fatalf("Failed to get alias file path: %v", err)
}
tui.FatalIfError("Failed to get alias file path", err)

fmt.Printf(`if [[ "$ANTIDOT_INIT" != "1" ]]; then
tui.Print(`if [[ "$ANTIDOT_INIT" != "1" ]]; then
%s
source %s
source %s
Expand Down
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/spf13/cobra"

"github.com/doron-cohen/antidot/internal/tui"
"github.com/doron-cohen/antidot/internal/utils"
)

Expand All @@ -19,6 +20,7 @@ var rootCmd = &cobra.Command{
}

func init() {
rootCmd.PersistentFlags().BoolVarP(&tui.Verbose, "verbose", "v", false, "Output verbosity")
rootCmd.PersistentFlags().StringVarP(&rulesFilePath, "rules", "r", utils.GetRulesFilePath(), "Rules file path")
}

Expand Down
11 changes: 4 additions & 7 deletions cmd/update.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package cmd

import (
"log"

"github.com/doron-cohen/antidot/internal/tui"
"github.com/doron-cohen/antidot/internal/utils"
"github.com/spf13/cobra"
)
Expand All @@ -17,12 +16,10 @@ var updateCmd = &cobra.Command{
Use: "update",
Short: "Update rules file",
Run: func(cmd *cobra.Command, args []string) {
log.Printf("Updating rules...")
tui.Debug("Updating rules...")
err := utils.Download(rulesSource, rulesFilePath)
if err != nil {
log.Fatalf("Failed to update rules: %v", err)
}
tui.FatalIfError("Failed to update rules", err)

log.Printf("Rules updated")
tui.Print("Rules updated successfully")
},
}
7 changes: 3 additions & 4 deletions internal/rules/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package rules
import (
"errors"
"fmt"
"log"
"os"

"github.com/doron-cohen/antidot/internal/tui"
Expand Down Expand Up @@ -35,7 +34,7 @@ func (a Alias) Apply() error {

existingAlias, isAliasContained := aliasMap[a.Alias]
if isAliasContained {
log.Printf("Alias %s already exists in alias file %s", a.Alias, aliasMap)
tui.Debug("Alias %s already exists in alias file %s", a.Alias, aliasMap)
if existingAlias != a.Command {
errMessage := fmt.Sprintf(
"Current command for alias '%s' (%s) is different than the requested (%s)",
Expand All @@ -49,7 +48,7 @@ func (a Alias) Apply() error {
aliasMap[a.Alias] = a.Command
}

log.Printf("Writing to %s", aliasFilePath)
tui.Debug("Writing to %s", aliasFilePath)
if err = utils.WriteKeyValuesToFile(aliasMap, aliasFilePath); err != nil {
return err
}
Expand All @@ -58,7 +57,7 @@ func (a Alias) Apply() error {
}

func (a Alias) Pprint() {
log.Printf(
tui.Print(
" %s %s%s\"%s\"",
tui.ApplyStyle(tui.Magenta, "ALIAS"),
a.Alias,
Expand Down
6 changes: 3 additions & 3 deletions internal/rules/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package rules

import (
"io/ioutil"
"log"
"os"

"github.com/doron-cohen/antidot/internal/tui"
"github.com/mitchellh/mapstructure"
"gopkg.in/yaml.v2"
)
Expand All @@ -23,7 +23,7 @@ type RulesConfig struct {
var rulesConfig RulesConfig

func LoadRulesConfig(filepath string) (RulesConfig, error) {
log.Printf("Loading rules config file %s", filepath)
tui.Debug("Loading rules config file %s", filepath)
rulesBytes, err := ioutil.ReadFile(filepath)
if err != nil {
if os.IsNotExist(err) {
Expand Down Expand Up @@ -55,6 +55,6 @@ func LoadRulesConfig(filepath string) (RulesConfig, error) {
return RulesConfig{}, err
}

log.Printf("Loaded %d rules", len(rulesConfig.Rules))
tui.Debug("Loaded %d rules", len(rulesConfig.Rules))
return rulesConfig, nil
}
3 changes: 1 addition & 2 deletions internal/rules/delete.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package rules

import (
"log"
"os"

"github.com/doron-cohen/antidot/internal/tui"
Expand All @@ -27,7 +26,7 @@ func (d Delete) Apply() error {
}

func (d Delete) Pprint() {
log.Printf(" %s %s", tui.ApplyStyle(tui.Red, "DELETE"), utils.ExpandEnv(d.Path))
tui.Print(" %s %s", tui.ApplyStyle(tui.Red, "DELETE"), utils.ExpandEnv(d.Path))
}

func init() {
Expand Down
7 changes: 3 additions & 4 deletions internal/rules/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package rules
import (
"errors"
"fmt"
"log"
"os"

"github.com/doron-cohen/antidot/internal/tui"
Expand Down Expand Up @@ -34,7 +33,7 @@ func (e Export) Apply() error {

existingValue, isKeyContained := envMap[e.Key]
if isKeyContained {
log.Printf("Key %s already exists in env file %s", e.Key, envFile)
tui.Debug("Key %s already exists in env file %s", e.Key, envFile)
if existingValue != e.Value {
errMessage := fmt.Sprintf(
"Current value for key '%s' (%s) is different than the requested (%s)",
Expand All @@ -48,7 +47,7 @@ func (e Export) Apply() error {
envMap[e.Key] = e.Value
}

log.Printf("Writing to %s", envFile)
tui.Debug("Writing to %s", envFile)
if err = utils.WriteKeyValuesToFile(envMap, envFile); err != nil {
return err
}
Expand All @@ -57,7 +56,7 @@ func (e Export) Apply() error {
}

func (e Export) Pprint() {
log.Printf(
tui.Print(
" %s %s%s\"%s\"",
tui.ApplyStyle(tui.Blue, "EXPORT"),
e.Key,
Expand Down
5 changes: 2 additions & 3 deletions internal/rules/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package rules
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"

Expand All @@ -21,7 +20,7 @@ func (m Migrate) Apply() error {
source := utils.ExpandEnv(m.Source)
_, err := os.Stat(source)
if os.IsNotExist(err) {
log.Printf("File %s doesn't exist. Skipping action", source)
tui.Print("File %s doesn't exist. Skipping action", source)
return nil
} else if err != nil {
return err
Expand Down Expand Up @@ -60,7 +59,7 @@ func (m Migrate) Pprint() {
}

// TODO: move the indentation logic elsewhere
log.Printf(
tui.Print(
" %s %s %s %s%s",
tui.ApplyStyle(tui.Green, "MOVE "),
utils.ExpandEnv(m.Source),
Expand Down
10 changes: 4 additions & 6 deletions internal/rules/rule.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package rules

import (
"log"

"github.com/google/go-cmp/cmp"

"github.com/doron-cohen/antidot/internal/dotfile"
Expand All @@ -18,13 +16,13 @@ type Rule struct {
}

func (r Rule) Pprint() {
log.Println(tui.ApplyStylef(tui.Cyan, "Rule %s:", r.Name))
tui.Print(tui.ApplyStylef(tui.Cyan, "Rule %s:", r.Name))
for _, action := range r.Actions {
action.Pprint()
}

if r.Ignore {
log.Println(tui.ApplyStyle(tui.Gray, " IGNORED"))
tui.Print(tui.ApplyStyle(tui.Gray, " IGNORED"))
}
}

Expand All @@ -34,7 +32,7 @@ func (r Rule) Apply() {
for _, action := range r.Actions {
err := action.Apply()
if err != nil {
log.Printf("Failed to run rule %s: %v", r.Name, err)
tui.Print("Failed to run rule %s: %v", r.Name, err)
break
}
}
Expand All @@ -44,7 +42,7 @@ func (r Rule) Apply() {
func MatchRule(dotfile *dotfile.Dotfile) *Rule {
for _, rule := range rulesConfig.Rules {
if cmp.Equal(dotfile, rule.Dotfile) {
log.Printf("Matched rule %s with dotfile %s", rule.Name, dotfile.Name)
tui.Debug("Matched rule %s with dotfile %s", rule.Name, dotfile.Name)
return &rule
}
}
Expand Down
29 changes: 29 additions & 0 deletions internal/tui/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package tui

import (
"fmt"
"os"
)

var Verbose bool

func Debug(format string, a ...interface{}) {
if Verbose {
format = fmt.Sprintf("DEBUG: %s\n", format)
fmt.Fprintf(os.Stderr, ApplyStylef(Gray, format, a...))
}
}

func Print(format string, a ...interface{}) {
fmt.Printf(format+"\n", a...)
}

func FatalIfError(message string, err error) {
if err != nil {
if message != "" {
fmt.Fprintln(os.Stderr, message)
}
fmt.Fprintf(os.Stderr, ApplyStylef(Red, "Error: %v\n", err))
os.Exit(255)
}
}
7 changes: 3 additions & 4 deletions internal/utils/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"

"github.com/doron-cohen/antidot/internal/tui"
)

func Download(src, dest string) error {
Expand All @@ -20,9 +21,7 @@ func Download(src, dest string) error {
defer resp.Body.Close()

tempFile, err := ioutil.TempFile("", "rules.*.yaml")
if err != nil {
log.Fatal(err)
}
tui.FatalIfError("Failed to create rules file", err)
defer os.Remove(tempFile.Name())

_, err = io.Copy(tempFile, resp.Body)
Expand Down

0 comments on commit 74792b4

Please sign in to comment.