Skip to content

Commit

Permalink
feat: save and read tool config
Browse files Browse the repository at this point in the history
  • Loading branch information
wowu committed Jul 1, 2022
1 parent 76d29cc commit 861591e
Show file tree
Hide file tree
Showing 6 changed files with 118 additions and 40 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pro
69 changes: 69 additions & 0 deletions cfg/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package cfg

import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"

"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v2"
)

type Config struct {
GitHubToken string `yaml:"github_token"`
GitlabToken string `yaml:"gitlab_token"`
}

// Read config file and return config object
func Get() Config {
// check if file exists
_, err := os.Stat(configfile())
if err != nil {
if os.IsNotExist(err) {
return Config{}
}
}

data, err := ioutil.ReadFile(configfile())
if err != nil {
fmt.Println(err)
os.Exit(0)
}

var config Config
err = yaml.Unmarshal(data, &config)
if err != nil {
fmt.Println(err)
os.Exit(0)
}

return config
}

func Save(config Config) {
// Make sure the config directory exists
err := os.MkdirAll(path.Dir(configfile()), 0750)
if err != nil {
fmt.Println(err)
os.Exit(1)
}

data, err := yaml.Marshal(config)

ioutil.WriteFile(configfile(), data, 0600)
}

func configdir() string {
home, err := homedir.Dir()
if err != nil {
panic(err)
}

return filepath.Join(home, ".config")
}

func configfile() string {
return filepath.Join(configdir(), "pro", "config.yml")
}
55 changes: 27 additions & 28 deletions commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"runtime"
"strings"
"syscall"
"wowu/pro/cfg"
"wowu/pro/gitlab"

"github.com/fatih/color"
Expand All @@ -24,10 +25,7 @@ func auth(provider string) {
fmt.Print("Token: ")
byteToken, err := term.ReadPassword(int(syscall.Stdin))
fmt.Println()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
handleError(err)

token := strings.TrimSpace(string(byteToken))

Expand All @@ -49,39 +47,31 @@ func auth(provider string) {
}
}

config := cfg.Get()
config.GitlabToken = token
cfg.Save(config)

color.Green("Saved.")
}

func open(repoPath string, print bool) {
r, err := git.PlainOpen(repoPath)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
handleError(err)

remotes, err := r.Remotes()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
handleError(err)
if len(remotes) == 0 {
fmt.Println("No remotes found")
os.Exit(0)
}

// check if there is a remote named origin
origin, err := r.Remote("origin")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
handleError(err)

// get current head
head, err := r.Head()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
handleError(err)

if !head.Name().IsBranch() {
fmt.Println("Not on a branch")
Expand All @@ -95,10 +85,7 @@ func open(repoPath string, print bool) {
originURL := origin.Config().URLs[0]

gitURL, err := giturls.Parse(originURL)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
handleError(err)

if branch == "master" || branch == "main" || branch == "trunk" {
fmt.Println("Looks like you are on the main branch. Opening home page.")
Expand Down Expand Up @@ -144,12 +131,16 @@ func open(repoPath string, print bool) {
path = path[:len(path)-4]
}

mergeRequests, err := gitlab.MergeRequests(path, os.Getenv("GITLAB_TOKEN"))
if err != nil {
fmt.Println(err)
gitlabToken := cfg.Get().GitlabToken

if gitlabToken == "" {
color.Red("Gitlab token is not set. Run `pro auth gitlab` to set it.")
os.Exit(1)
}

mergeRequests, err := gitlab.MergeRequests(path, gitlabToken)
handleError(err)

// find merge request for current branch
currentMergeRequestIndex := slices.IndexFunc(mergeRequests, func(mr gitlab.MergeRequestResponse) bool {
return mr.SourceBranch == branch && mr.State == "opened"
Expand All @@ -158,7 +149,7 @@ func open(repoPath string, print bool) {
if currentMergeRequestIndex == -1 {
fmt.Println("No open merge request found for current branch")

fmt.Printf("Create pull request at https://gitlab.com/%s/merge_requests/new?merge_request%%5Bsource_branch%%5D=%s", path, branch)
fmt.Printf("Create pull request at https://gitlab.com/%s/merge_requests/new?merge_request%%5Bsource_branch%%5D=%s\n", path, branch)

os.Exit(0)
}
Expand Down Expand Up @@ -194,3 +185,11 @@ func openBrowser(url string) {
os.Exit(1)
}
}

// Print error and exit
func handleError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ go 1.18
require (
github.com/fatih/color v1.13.0
github.com/go-git/go-git/v5 v5.4.2
github.com/mitchellh/go-homedir v1.1.0
github.com/urfave/cli/v2 v2.10.3
github.com/whilp/git-urls v1.0.0
golang.org/x/exp v0.0.0-20220613132600-b0d781184e0d
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467
gopkg.in/yaml.v2 v2.4.0
)

require (
Expand All @@ -24,7 +26,6 @@ require (
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sergi/go-diff v1.2.0 // indirect
github.com/stretchr/testify v1.8.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRN
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
28 changes: 17 additions & 11 deletions pro.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@ import (
"github.com/urfave/cli/v2"
)

type Config struct {
GitHubToken string `yaml:"github_token"`
GitlabToken string `yaml:"gitlab_token"`
var openCommandFlags = []cli.Flag{
&cli.BoolFlag{
Name: "print",
Aliases: []string{"p"},
Usage: "print the PR URL instead of opening in browser",
},
}

func main() {
Expand All @@ -18,18 +21,12 @@ func main() {
app := &cli.App{
Name: "pro",
Usage: "Pull Request opener",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "print",
Aliases: []string{"p"},
Usage: "print the PR URL instead of opening in browser",
},
},
Flags: openCommandFlags,
Commands: []*cli.Command{
{
Name: "auth",
ArgsUsage: "[gitlab|github]",
Usage: "Login to GitLab or GitHub",
Usage: "Authorize GitLab or GitHub",
UsageText: fmt.Sprintf("pro auth gitlab\npro login github"),
Action: func(c *cli.Context) error {
if c.NArg() != 1 {
Expand All @@ -54,6 +51,15 @@ func main() {
return nil
},
},
{
Name: "open",
Usage: "Open PR page in browser (default action)",
Flags: openCommandFlags,
Action: func(c *cli.Context) error {
open(".", c.Bool("print"))
return nil
},
},
},
Action: func(c *cli.Context) error {
open(".", c.Bool("print"))
Expand Down

0 comments on commit 861591e

Please sign in to comment.