config.go

  1package launchpad
  2
  3import (
  4	"bufio"
  5	"fmt"
  6	"net/http"
  7	"os"
  8	"regexp"
  9	"strings"
 10
 11	"github.com/MichaelMure/git-bug/bridge/core"
 12	"github.com/MichaelMure/git-bug/repository"
 13)
 14
 15const keyProject = "project"
 16
 17var (
 18	rxLaunchpadURL = regexp.MustCompile(`launchpad\.net[\/:]([^\/]*[a-z]+)`)
 19)
 20
 21func (*Launchpad) Configure(repo repository.RepoCommon, params core.BridgeParams) (core.Configuration, error) {
 22	if params.Token != "" {
 23		fmt.Println("warning: --token is ineffective for a Launchpad bridge")
 24	}
 25	if params.Owner != "" {
 26		fmt.Println("warning: --owner is ineffective for a Launchpad bridge")
 27	}
 28
 29	conf := make(core.Configuration)
 30	var err error
 31	var project string
 32
 33	if params.Project != "" {
 34		project = params.Project
 35
 36	} else if params.URL != "" {
 37		// get project name from url
 38		_, project, err = splitURL(params.URL)
 39		if err != nil {
 40			return nil, err
 41		}
 42
 43	} else {
 44		// get project name from terminal prompt
 45		project, err = promptProjectName()
 46		if err != nil {
 47			return nil, err
 48		}
 49	}
 50
 51	// verify project
 52	ok, err := validateProject(project)
 53	if err != nil {
 54		return nil, err
 55	}
 56	if !ok {
 57		return nil, fmt.Errorf("project doesn't exist")
 58	}
 59
 60	conf[keyProject] = project
 61	return conf, nil
 62}
 63
 64func (*Launchpad) ValidateConfig(conf core.Configuration) error {
 65	if _, ok := conf[keyProject]; !ok {
 66		return fmt.Errorf("missing %s key", keyProject)
 67	}
 68
 69	return nil
 70}
 71
 72func promptProjectName() (string, error) {
 73	for {
 74		fmt.Print("Launchpad project name: ")
 75
 76		line, err := bufio.NewReader(os.Stdin).ReadString('\n')
 77		if err != nil {
 78			return "", err
 79		}
 80
 81		line = strings.TrimRight(line, "\n")
 82
 83		if line == "" {
 84			fmt.Println("Project name is empty")
 85			continue
 86		}
 87
 88		return line, nil
 89	}
 90}
 91
 92func validateProject(project string) (bool, error) {
 93	url := fmt.Sprintf("%s/%s", apiRoot, project)
 94
 95	resp, err := http.Get(url)
 96	if err != nil {
 97		return false, err
 98	}
 99
100	return resp.StatusCode == http.StatusOK, nil
101}
102
103func splitURL(url string) (string, string, error) {
104	res := rxLaunchpadURL.FindStringSubmatch(url)
105	if res == nil {
106		return "", "", fmt.Errorf("bad Launchpad project url")
107	}
108
109	return res[0], res[1], nil
110}