Skip to content

Commit

Permalink
add debug mode using zerolog closes #54, closes #55 (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
chriswalz committed Oct 19, 2020
1 parent fb92d75 commit c63fae8
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 71 deletions.
2 changes: 1 addition & 1 deletion .github/FUNDING.yml
@@ -1,3 +1,3 @@
# These are supported funding model platforms

github: [chriswalz]
github: [ chriswalz ]
3 changes: 1 addition & 2 deletions .goreleaser.yml
Expand Up @@ -32,8 +32,7 @@ changelog:
- '^test:'
# .goreleaser.yml
brews:
-
# Name template of the recipe
- # Name template of the recipe
# Default to project name
#name: myproject

Expand Down
74 changes: 40 additions & 34 deletions cmd/git.go
Expand Up @@ -2,123 +2,124 @@ package cmd

import (
"fmt"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"os/exec"
"strings"
)

func CloudBranchExists() bool {
msg, err := exec.Command("git", "pull").CombinedOutput()
msg, err := execCommand("git", "pull").CombinedOutput()
if err != nil {
fmt.Println(err)
log.Debug().Err(err)
}
//log.Println("msg:", string(msg))
//log.Println("err:", err)
return !strings.Contains(string(msg), "There is no tracking information for the current branch")
}

func CurrentBranch() string {
msg, err := exec.Command("git", "branch", "--show-current").CombinedOutput()
msg, err := execCommand("git", "branch", "--show-current").CombinedOutput()
if err != nil {
fmt.Println(err)
log.Debug().Err(err)
}
return strings.TrimSpace(string(msg))
}

func IsAheadOfCurrent() bool {
msg, err := exec.Command("git", "status", "-sb").CombinedOutput()
msg, err := execCommand("git", "status", "-sb").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Msg(err.Error())
}
return strings.Contains(string(msg), "ahead")
}

func IsGitRepo() bool {
_, err := exec.Command("git", "status").CombinedOutput()
_, err := execCommand("git", "status").CombinedOutput()
if err != nil {
return false
}
return true
}

func IsBehindCurrent() bool {
msg, err := exec.Command("git", "status", "-sb").CombinedOutput()
msg, err := execCommand("git", "status", "-sb").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
return strings.Contains(string(msg), "behind")
}

func NothingToCommit() bool {
msg, err := exec.Command("git", "status").CombinedOutput()
msg, err := execCommand("git", "status").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
return strings.Contains(string(msg), "nothing to commit")
}

func IsDiverged() bool {
msg, err := exec.Command("git", "status").CombinedOutput()
msg, err := execCommand("git", "status").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
return strings.Contains(string(msg), "have diverged")
}

func StashableChanges() bool {
msg, err := exec.Command("git", "status").CombinedOutput()
msg, err := execCommand("git", "status").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
return strings.Contains(string(msg), "Changes to be committed:") || strings.Contains(string(msg), "Changes not staged for commit:")
}

func MostRecentCommonAncestorCommit(branchA, branchB string) string {
msg, err := exec.Command("git", "merge-base", branchA, branchB).CombinedOutput()
msg, err := execCommand("git", "merge-base", branchA, branchB).CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
return string(msg)
}

func StashList() []string {
msg, err := exec.Command("git", "stash", "list").CombinedOutput()
msg, err := execCommand("git", "stash", "list").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
return strings.Split(string(msg), "\n")
}

func refreshBranch() error {
msg, err := exec.Command("git", "pull", "--ff-only").CombinedOutput()
msg, err := execCommand("git", "pull", "--ff-only").CombinedOutput()
if err != nil {
return err
}
if strings.TrimSpace(string(msg)) == "Already up to date." {
return nil
}
fmt.Println("Branch was fast-forwarded")
log.Debug().Msg("Branch was fast-forwarded")
return nil
}

func refreshOnBranch(branchName string) error {
_, err := exec.Command("git", "pull", "--ff-only", branchName).CombinedOutput()
_, err := execCommand("git", "pull", "--ff-only", branchName).CombinedOutput()
if err != nil {
return err
}
fmt.Println("Branch was fast-forwarded")
log.Debug().Msg("Branch was fast-forwarded")
return nil
}

func branchListRaw() (string, error) {
msg, err := exec.Command("git", "for-each-ref", "--sort=-committerdate", "refs/heads/", "refs/remotes", "--format='%(authordate); %(authorname); %(color:red)%(objectname:short); %(color:yellow)%(refname:short)%(color:reset); (%(color:green)%(committerdate:relative)%(color:reset))'").CombinedOutput()
msg, err := execCommand("git", "for-each-ref", "--sort=-committerdate", "refs/heads/", "refs/remotes", "--format='%(authordate); %(authorname); %(color:red)%(objectname:short); %(color:yellow)%(refname:short)%(color:reset); (%(color:green)%(committerdate:relative)%(color:reset))'").CombinedOutput()
return string(msg), err
}

func FileChangesList() []FileChange {
msg, err := exec.Command("git", "status", "--porcelain=v2").CombinedOutput()
msg, err := execCommand("git", "status", "--porcelain=v2").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
var changes []FileChange
// if user has an older version of git porcelain=v2 is not supported. don't show CL suggestions for now 2.7
Expand Down Expand Up @@ -148,9 +149,9 @@ func FileChangesList() []FileChange {
}

func AllGitAliases() (cc []*cobra.Command) {
msg, err := exec.Command("git", "config", "--get-regexp", "^alias").CombinedOutput()
msg, err := execCommand("git", "config", "--get-regexp", "^alias").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
return cc
}
aliases := strings.Split(strings.TrimSpace(string(msg)), "\n")
Expand All @@ -174,25 +175,30 @@ func AllGitAliases() (cc []*cobra.Command) {
}

func PrintGitVersion() {
msg, err := exec.Command("git", "--version").CombinedOutput()
msg, err := execCommand("git", "--version").CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
fmt.Println(string(msg))
log.Debug().Msg(string(msg))
}

func checkoutBranch(branch string) bool {
msg, err := exec.Command("git", "checkout", branch).CombinedOutput()
msg, err := execCommand("git", "checkout", branch).CombinedOutput()
if err != nil {
//fmt.Println(err)
log.Debug().Err(err)
}
return !strings.Contains(string(msg), "did not match any file")
}

func tagCurrentBranch(version string) error {
msg, err := exec.Command("git", "tag", version).CombinedOutput()
msg, err := execCommand("git", "tag", version).CombinedOutput()
if err != nil {
return fmt.Errorf("%v: %w", string(msg), err)
}
return err
}

func execCommand(name string, arg ...string) *exec.Cmd {
log.Debug().Msg(name + " " + strings.Join(arg, " "))
return exec.Command(name, arg...)
}
15 changes: 10 additions & 5 deletions cmd/rootShell.go
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"fmt"
"github.com/rs/zerolog/log"
"os"
"strings"

Expand All @@ -13,7 +14,7 @@ import (
var ShellCmd = &cobra.Command{
Use: "bit",
Short: "Bit is a Git CLI that predicts what you want to do",
Long: `v0.6.6`,
Long: `v0.6.11`,
Run: func(cmd *cobra.Command, args []string) {
completerSuggestionMap, bitCmdMap := CreateSuggestionMap(cmd)

Expand All @@ -27,7 +28,7 @@ var ShellCmd = &cobra.Command{
}
parsedArgs, err := parseCommandLine(resp)
if err != nil {
fmt.Println(err)
log.Debug().Err(err)
return
}
if bitCmdMap[subCommand] == nil {
Expand All @@ -44,6 +45,10 @@ var ShellCmd = &cobra.Command{
},
}

func init() {
ShellCmd.PersistentFlags().Bool("debug", false, "Print debugging information")
}

func CreateSuggestionMap(cmd *cobra.Command) (map[string][]prompt.Suggest, map[string]*cobra.Command) {
_, bitCmdMap := AllBitSubCommands(cmd)
allBitCmds := AllBitAndGitSubCommands(cmd)
Expand Down Expand Up @@ -74,7 +79,7 @@ func CreateSuggestionMap(cmd *cobra.Command) (map[string][]prompt.Suggest, map[s
// This is called by main.main(). It only needs to happen once to the ShellCmd.
func Execute() {
if err := ShellCmd.Execute(); err != nil {
fmt.Println(err)
log.Info().Err(err)
os.Exit(1)
}
}
Expand Down Expand Up @@ -123,7 +128,7 @@ func RunGitCommandWithArgs(args []string) {
var err error
err = RunInTerminalWithColor("git", args)
if err != nil {
//fixme fmt.Println("Command may not exist", err) use debug level logging
log.Debug().Msg("Command may not exist: " + err.Error())
}
return
}
Expand All @@ -136,7 +141,7 @@ func GitCommandsPromptUsed(args []string, suggestionMap map[string][]prompt.Sugg
// expected usage format
// bit (checkout|switch|co) [-b] branch-name
if args[len(args)-1] == "--version" {
fmt.Println("bit version v0.6.6")
log.Debug().Msg("bit version v0.6.11")
}
if isBranchCompletionCommand(sub) {
branchName := ""
Expand Down
35 changes: 13 additions & 22 deletions cmd/util.go
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/c-bata/go-prompt"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"os"
"os/exec"
Expand All @@ -22,6 +23,8 @@ func RunInTerminalWithColor(cmdName string, args []string) error {
}

func RunInTerminalWithColorInDir(cmdName string, dir string, args []string) error {
log.Debug().Msg(cmdName + " " + strings.Join(args, " "))

_, w, err := os.Pipe()
if err != nil {
panic(err)
Expand All @@ -37,6 +40,7 @@ func RunInTerminalWithColorInDir(cmdName string, dir string, args []string) erro
}

err = cmd.Run()
log.Debug().Err(err)
return err
}

Expand All @@ -60,7 +64,7 @@ func AskMultiLine(q string) string {
func BranchList() []Branch {
rawBranchData, err := branchListRaw()
if err != nil {
//log.Println(err) // fixme use debug log
log.Debug().Err(err)
}
return toStructuredBranchList(rawBranchData)
}
Expand Down Expand Up @@ -94,7 +98,7 @@ func toStructuredBranchList(rawBranchData string) []Branch {
func GenBumpedSemVersion() string {
msg, err := exec.Command("/bin/sh", "-c", `git describe --tags --abbrev=0 | awk -F. '{$NF+=1; OFS="."; print $0}'`).CombinedOutput()
if err != nil {
fmt.Println(err)
log.Debug().Err(err)
}
out := string(msg)
return strings.TrimSpace(out)
Expand All @@ -104,9 +108,9 @@ func AddCommandToShellHistory(cmd string, args []string) {
// not possible??
msg, err := exec.Command("/bin/bash", "-c", "history").CombinedOutput()
if err != nil {
fmt.Println(err)
log.Debug().Err(err)
}
fmt.Println(msg)
log.Debug().Msg(string(msg))
}

func BranchListSuggestions() []prompt.Suggest {
Expand Down Expand Up @@ -226,7 +230,7 @@ func HandleExit() {
fmt.Println(v)
fmt.Println(string(debug.Stack()))
fmt.Println("OS:", runtime.GOOS, runtime.GOARCH)
fmt.Println("bit version v0.6.6")
fmt.Println("bit version v0.6.11")
PrintGitVersion()

}
Expand Down Expand Up @@ -265,19 +269,6 @@ func concatCopyPreAllocate(slices [][]*cobra.Command) []*cobra.Command {
func FlagSuggestionsForCommand(gitSubCmd string, flagtype string) []prompt.Suggest {
str := ""

// git help pull | col -b > man.txt
//if gitSubCmd != "commit" && gitSubCmd != "push" && gitSubCmd != "status" {
// msg, err := exec.Command("/bin/sh", "-c", "git help " + gitSubCmd + " | col -bx").CombinedOutput()
// if err != nil {
// //fmt.Println(err)
// }
// out := string(msg)
// //out = stripCtlAndExtFromUTF8(out)
// split := strings.Split(out, "OPTIONS")
// fmt.Println(out, split)
// out=split[1]
// //return []prompt.Suggest{}
//}
flagMap := map[string]string{
"add": addFlagsStr,
"diff": diffFlagsStr,
Expand Down Expand Up @@ -325,8 +316,6 @@ func FlagSuggestionsForCommand(gitSubCmd string, flagtype string) []prompt.Sugge
})
}
}

//log.Println(list[i])
}
return suggestions
}
Expand Down Expand Up @@ -384,14 +373,14 @@ func RunScriptWithString(path string, script string, args ...string) {
var err error
err = RunInTerminalWithColor("bin/sh", args)
if err != nil {
fmt.Println(err)
log.Debug().Err(err)
}
}

func parseManPage(subCmd string) string {
msg, err := exec.Command("/bin/bash", "-c", "git help "+subCmd+" | col -b").CombinedOutput()
if err != nil {
fmt.Println(err)
log.Debug().Err(err)
}
splitA := strings.Split(string(msg), "\n\nOPTIONS")
splitB := regexp.MustCompile(`\.\n\n[A-Z]+`).Split(splitA[1], 2)
Expand All @@ -414,3 +403,5 @@ func isBranchCompletionCommand(command string) bool {

return command == "checkout" || command == "switch" || command == "co" || command == "merge"
}


0 comments on commit c63fae8

Please sign in to comment.