Skip to content

Commit

Permalink
Merge pull request #272 from zaquestion/drop_user_conf
Browse files Browse the repository at this point in the history
[#269] Simplify config setup
  • Loading branch information
zaquestion authored Dec 27, 2018
2 parents be24c68 + 3b1f5ae commit 78c18e0
Show file tree
Hide file tree
Showing 11 changed files with 146 additions and 65 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ before_script:
- ssh-add ~/.ssh/id_rsa

script:
- GO111MODULE=on make test
- make test

after_success:
- |
Expand Down
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ VERSION ?= $(shell git describe --long --tags)
GOURL ?= github.com/zaquestion/lab

build:
go build -ldflags "-X \"main.version=$(VERSION)\"" $(GOURL)
GO111MODULE=on go build -ldflags "-X \"main.version=$(VERSION)\"" $(GOURL)

install: build
go install $(GOURL)
GO111MODULE=on go install $(GOURL)

test:
bash -c "trap 'trap - SIGINT SIGTERM ERR; mv testdata/.git testdata/test.git; rm coverage-* 2>&1 > /dev/null; exit 1' SIGINT SIGTERM ERR; $(MAKE) internal-test"

internal-test:
rm coverage-* 2>&1 > /dev/null || true
mv testdata/test.git testdata/.git
go test -coverprofile=coverage-main.out -covermode=count -coverpkg ./... -run=$(run) $(GOURL)/cmd $(GOURL)/internal/...
GO111MODULE=on go test -coverprofile=coverage-main.out -covermode=count -coverpkg ./... -run=$(run) $(GOURL)/cmd $(GOURL)/internal/...
mv testdata/.git testdata/test.git
go get github.com/wadey/gocovmerge
gocovmerge coverage-*.out > coverage.txt && rm coverage-*.out
Expand Down
1 change: 0 additions & 1 deletion cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ func TestMain(m *testing.M) {
config := c.([]map[string]interface{})[0]
lab.Init(
config["host"].(string),
config["user"].(string),
config["token"].(string))

code := m.Run()
Expand Down
11 changes: 6 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ require (
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/avast/retry-go v0.0.0-20180319101611-5469272a8171
github.com/cpuguy83/go-md2man v1.0.8 // indirect
github.com/davecgh/go-spew v1.1.0 // indirect
github.com/derekparker/delve v1.1.0
github.com/gdamore/encoding v0.0.0-20151215212835-b23993cbb635 // indirect
github.com/gdamore/tcell v0.0.0-20180416163743-2f258105ca8c
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135 // indirect
Expand All @@ -20,21 +20,22 @@ require (
github.com/onsi/gomega v1.4.3 // indirect
github.com/pelletier/go-toml v1.1.0 // indirect
github.com/pkg/errors v0.8.0
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/tview v0.0.0-20180419193403-f855bee0205c
github.com/russross/blackfriday v1.5.1 // indirect
github.com/sirupsen/logrus v1.2.0 // indirect
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c // indirect
github.com/spf13/afero v1.1.0 // indirect
github.com/spf13/cast v1.2.0 // indirect
github.com/spf13/cobra v0.0.0-20180412120829-615425954c3b
github.com/spf13/jwalterweatherman v0.0.0-20180109140146-7c0cea34c8ec // indirect
github.com/spf13/pflag v1.0.1 // indirect
github.com/spf13/pflag v1.0.1
github.com/spf13/viper v0.0.0-20180507071007-15738813a09d
github.com/stretchr/testify v1.2.1
github.com/stretchr/testify v1.2.2
github.com/tcnksm/go-gitconfig v0.1.2
github.com/xanzy/go-gitlab v0.11.3
golang.org/x/crypto v0.0.0-20180420171155-e73bf333ef89
golang.org/x/arch v0.0.0-20181203225421-5a4828bb7045 // indirect
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793
golang.org/x/oauth2 v0.0.0-20180724155351-3d292e4d0cdc // indirect
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f // indirect
google.golang.org/appengine v1.1.0 // indirect
Expand Down
15 changes: 15 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ github.com/cpuguy83/go-md2man v1.0.8 h1:DwoNytLphI8hzS2Af4D0dfaEaiSq2bN05mEm4R6v
github.com/cpuguy83/go-md2man v1.0.8/go.mod h1:N6JayAiVKtlHSnuTCeuLSQVs75hb8q+dYQLjr7cDsKY=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/derekparker/delve v1.1.0 h1:icd65nMp7s2HiLz6y/6RCVXBdoED3xxYLwX09EMaRCc=
github.com/derekparker/delve v1.1.0/go.mod h1:pMSZMfp0Nhbm8qdZJkuE/yPGOkLpGXLS1I4poXQpuJU=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/gdamore/encoding v0.0.0-20151215212835-b23993cbb635 h1:hheUEMzaOie/wKeIc1WPa7CDVuIO5hqQxjS+dwTQEnI=
Expand All @@ -26,6 +30,7 @@ github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NH
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jtolds/gls v4.2.1+incompatible h1:fSuqC+Gmlu6l/ZYAoZzx2pyucC8Xza35fpRVWLVmUEE=
github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/lucasb-eyer/go-colorful v0.0.0-20170903184257-231272389856 h1:r+WvXmgROttp7pckv7TPN7OCUEPXmvhRklOOsL2iPPc=
github.com/lucasb-eyer/go-colorful v0.0.0-20170903184257-231272389856/go.mod h1:NXg0ArsFk0Y01623LgUqoqcouGDB+PwCCQlrwrG6xJ4=
github.com/lunixbochs/vtclean v0.0.0-20180621232353-2d01aacdc34a h1:weJVJJRzAJBFRlAiJQROKQs8oC9vOxvm4rZmBBk0ONw=
Expand All @@ -52,6 +57,8 @@ github.com/rsteube/cobra v0.0.1-zsh-completion-custom h1:Hqbid4kBOEu78syaZ8hCAIj
github.com/rsteube/cobra v0.0.1-zsh-completion-custom/go.mod h1:pAlNXnbm7kUeUgr/8AEn0Lv+VrT1T6obUvI1mC8KlvA=
github.com/russross/blackfriday v1.5.1 h1:B8ZN6pD4PVofmlDCDUdELeYrbsVIDM/bpjW3v3zgcRc=
github.com/russross/blackfriday v1.5.1/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c h1:Ho+uVpkel/udgjbwB5Lktg9BtvJSh2DT0Hi6LPSyI2w=
Expand All @@ -68,23 +75,31 @@ github.com/spf13/pflag v1.0.1 h1:aCvUg6QPl3ibpQUxyLkrEkCHtPqYJL4x9AuhqVqFis4=
github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v0.0.0-20180507071007-15738813a09d h1:pIz+bbPLk78K39d3u77IlNpJvpS/f0ao8n3sdy82eCs=
github.com/spf13/viper v0.0.0-20180507071007-15738813a09d/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7SrnBM=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.1 h1:52QO5WkIUcHGIR7EnGagH88x1bUzqGXTC5/1bDTUQ7U=
github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/tcnksm/go-gitconfig v0.1.2 h1:iiDhRitByXAEyjgBqsKi9QU4o2TNtv9kPP3RgPgXBPw=
github.com/tcnksm/go-gitconfig v0.1.2/go.mod h1:/8EhP4H7oJZdIPyT+/UIsG87kTzrzM4UsLGSItWYCpE=
github.com/xanzy/go-gitlab v0.0.0-20180921132519-8d21e61ce4a9 h1:gmCeo/bSUp/oLKpsZrICPRTgwsuI3m17l5c2X8y4/0g=
github.com/xanzy/go-gitlab v0.0.0-20180921132519-8d21e61ce4a9/go.mod h1:CRKHkvFWNU6C3AEfqLWjnCNnAs4nj8Zk95rX2S3X6Mw=
github.com/xanzy/go-gitlab v0.11.3 h1:gSYcSb+pCx3fco6/O3w784/omQVTcrgxRzyf14SBvUQ=
github.com/xanzy/go-gitlab v0.11.3/go.mod h1:CRKHkvFWNU6C3AEfqLWjnCNnAs4nj8Zk95rX2S3X6Mw=
golang.org/x/arch v0.0.0-20181203225421-5a4828bb7045 h1:Pn8fQdvx+z1avAi7fdM2kRYWQNxGlavNDSyzrQg2SsU=
golang.org/x/arch v0.0.0-20181203225421-5a4828bb7045/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8=
golang.org/x/crypto v0.0.0-20180420171155-e73bf333ef89 h1:YMKUzb2eHV8HdgAr0z9lbGN1Av2h4cgMMsvi+JV60MM=
golang.org/x/crypto v0.0.0-20180420171155-e73bf333ef89/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 h1:u+LnwYTOOW7Ukr/fppxEb1Nwz0AtPflrblfvUudpo+I=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20180724155351-3d292e4d0cdc h1:3ElrZeO6IBP+M8kgu5YFwRo92Gqr+zBg3aooYQ6ziqU=
golang.org/x/oauth2 v0.0.0-20180724155351-3d292e4d0cdc/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f h1:Bl/8QSvNqXvPGPGXa2z5xUTmV7VDcZyvRZ+QQXkXTZQ=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
Expand Down
55 changes: 24 additions & 31 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package config

import (
"bufio"
"errors"
"fmt"
"io"
"net/url"
Expand All @@ -20,28 +19,27 @@ const defaultGitLabHost = "https://gitlab.com"
// them to the provided confpath (default: ~/.config/lab.hcl)
func New(confpath string, r io.Reader) error {
var (
reader = bufio.NewReader(r)
host, user, token string
err error
reader = bufio.NewReader(r)
host, token string
err error
)
fmt.Printf("Enter default GitLab host (default: %s): ", defaultGitLabHost)
host, err = reader.ReadString('\n')
host = strings.TrimSpace(host)
if err != nil {
return err
}
if host == "" {
host = defaultGitLabHost
}

fmt.Print("Enter default GitLab user: ")
user, err = reader.ReadString('\n')
user = strings.TrimSpace(user)
if err != nil {
return err
}
if user == "" {
return errors.New("lab.hcl config core.user must be set")
// If core host is set in the environment (LAB_CORE_HOST) we only want
// to prompt for the token. We'll use the environments host and place
// it in the config. In the event both the host and token are in the
// env, this function shouldn't be called in the first place
if viper.GetString("core.host") == "" {
fmt.Printf("Enter GitLab host (default: %s): ", defaultGitLabHost)
host, err = reader.ReadString('\n')
host = strings.TrimSpace(host)
if err != nil {
return err
}
if host == "" {
host = defaultGitLabHost
}
} else {
// Required to correctly write config
host = viper.GetString("core.host")
}

tokenURL, err := url.Parse(host)
Expand All @@ -57,7 +55,6 @@ func New(confpath string, r io.Reader) error {
}

viper.Set("core.host", host)
viper.Set("core.user", user)
viper.Set("core.token", token)
if err := viper.WriteConfigAs(confpath); err != nil {
return err
Expand All @@ -76,18 +73,14 @@ var readPassword = func() (string, error) {

// CI returns credentials suitable for use within GitLab CI or empty strings if
// none found.
func CI() (string, string, string) {
func CI() (string, string) {
ciToken := os.Getenv("CI_JOB_TOKEN")
if ciToken == "" {
return "", "", ""
return "", ""
}
ciHost := strings.TrimSuffix(os.Getenv("CI_PROJECT_URL"), os.Getenv("CI_PROJECT_PATH"))
if ciHost == "" {
return "", "", ""
}
ciUser := os.Getenv("CI_REGISTRY_USER")
if ciUser == "" {
ciUser = "gitlab-ci-token"
return "", ""
}
return ciHost, ciUser, ciToken
return ciHost, ciToken
}
81 changes: 75 additions & 6 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@ import (
"os"
"path"
"strconv"
"strings"
"testing"
"time"

"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestNewConfig(t *testing.T) {
rand.Seed(time.Now().UnixNano())
testconf := "/tmp/testconf-" + strconv.Itoa(int(rand.Uint64()))
os.Mkdir(testconf, os.FileMode(0700))

Expand All @@ -25,7 +30,6 @@ func TestNewConfig(t *testing.T) {

var buf bytes.Buffer
fmt.Fprintln(&buf, "https://gitlab.zaquestion.io")
fmt.Fprintln(&buf, "zaq")

oldreadPassword := readPassword
readPassword = func() (string, error) {
Expand Down Expand Up @@ -53,8 +57,7 @@ func TestNewConfig(t *testing.T) {
os.Stdout = old // restoring the real stdout
out := <-outC

assert.Contains(t, out, "Enter default GitLab host (default: https://gitlab.com): ")
assert.Contains(t, out, "Enter default GitLab user:")
assert.Contains(t, out, "Enter GitLab host (default: https://gitlab.com): ")
assert.Contains(t, out, "Create a token here: https://gitlab.zaquestion.io/profile/personal_access_tokens\nEnter default GitLab token (scope: api):")

cfg, err := os.Open(path.Join(testconf, "lab.hcl"))
Expand All @@ -66,13 +69,79 @@ func TestNewConfig(t *testing.T) {
if err != nil {
t.Fatal(err)
}
assert.Equal(t, string(cfgData), `"core" = {
assert.Equal(t, `"core" = {
"host" = "https://gitlab.zaquestion.io"
"token" = "abcde12345"
}`, string(cfgData))
})
os.RemoveAll(testconf)
viper.Reset()
}

func TestNewConfigHostOverride(t *testing.T) {
rand.Seed(time.Now().UnixNano())
testconf := "/tmp/testconf-" + strconv.Itoa(int(rand.Uint64()))
os.Mkdir(testconf, os.FileMode(0700))

os.Setenv("LAB_CORE_HOST", "https://gitlab2.zaquestion.io")

t.Run("create config", func(t *testing.T) {
viper.SetEnvPrefix("LAB")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()

require.Equal(t, "https://gitlab2.zaquestion.io", viper.GetString("core.host"))

old := os.Stdout // keep backup of the real stdout
r, w, _ := os.Pipe()
os.Stdout = w

"user" = "zaq"
}`)
oldreadPassword := readPassword
readPassword = func() (string, error) {
return "abcde12345", nil
}
defer func() {
readPassword = oldreadPassword
}()

var buf bytes.Buffer
err := New(path.Join(testconf, "lab.hcl"), &buf)
if err != nil {
t.Fatal(err)
}

outC := make(chan string)
// copy the output in a separate goroutine so printing can't block indefinitely
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
outC <- buf.String()
}()

// back to normal state
w.Close()
os.Stdout = old // restoring the real stdout
out := <-outC

assert.NotContains(t, out, "Enter GitLab host")
assert.Contains(t, out, "Create a token here: https://gitlab2.zaquestion.io/profile/personal_access_tokens\nEnter default GitLab token (scope: api):")

cfg, err := os.Open(path.Join(testconf, "lab.hcl"))
if err != nil {
t.Fatal(err)
}

cfgData, err := ioutil.ReadAll(cfg)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, `"core" = {
"host" = "https://gitlab2.zaquestion.io"
"token" = "abcde12345"
}`, string(cfgData))
})
os.RemoveAll(testconf)
viper.Reset()
}
8 changes: 6 additions & 2 deletions internal/gitlab/gitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,19 @@ func User() string {
}

// Init initializes a gitlab client for use throughout lab.
func Init(_host, _user, _token string) {
func Init(_host, _token string) {
if len(_host) > 0 && _host[len(_host)-1 : len(_host)][0] == '/' {
_host = _host[0 : len(_host)-1]
}
host = _host
user = _user
token = _token
lab = gitlab.NewClient(nil, _token)
lab.SetBaseURL(host + "/api/v4")
u, _, err := lab.Users.CurrentUser()
if err != nil {
log.Fatal(err)
}
user = u.Username
}

// Defines filepath for default GitLab templates
Expand Down
10 changes: 7 additions & 3 deletions internal/gitlab/gitlab_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,23 @@ func TestMain(m *testing.M) {

Init(
config["host"].(string),
config["user"].(string),
config["token"].(string))
os.Exit(m.Run())
}

func TestUser(t *testing.T) {
// Should get set by Init() after TestMain()
require.Equal(t, "lab-testing", User())
}

func TestLoadGitLabTmplMR(t *testing.T) {
mrTmpl := LoadGitLabTmpl(TmplMR)
require.Equal(t, mrTmpl, "I am the default merge request template for lab")
require.Equal(t, "I am the default merge request template for lab", mrTmpl)
}

func TestLoadGitLabTmplIssue(t *testing.T) {
issueTmpl := LoadGitLabTmpl(TmplIssue)
require.Equal(t, issueTmpl, "This is the default issue template for lab")
require.Equal(t, "This is the default issue template for lab", issueTmpl)
}

func TestLint(t *testing.T) {
Expand Down
Loading

0 comments on commit 78c18e0

Please sign in to comment.