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