1package launchpad
2
3import (
4 "errors"
5 "fmt"
6 "net/http"
7 "regexp"
8
9 "github.com/MichaelMure/git-bug/bridge/core"
10 "github.com/MichaelMure/git-bug/cache"
11 "github.com/MichaelMure/git-bug/input"
12)
13
14var ErrBadProjectURL = errors.New("bad Launchpad project URL")
15
16func (Launchpad) ValidParams() map[string]interface{} {
17 return map[string]interface{}{
18 "URL": nil,
19 "Project": nil,
20 }
21}
22
23func (l *Launchpad) Configure(repo *cache.RepoCache, params core.BridgeParams) (core.Configuration, error) {
24 var err error
25 var project string
26
27 switch {
28 case params.Project != "":
29 project = params.Project
30 case params.URL != "":
31 // get project name from url
32 project, err = splitURL(params.URL)
33 default:
34 // get project name from terminal prompt
35 project, err = input.Prompt("Launchpad project name", "project name", input.Required)
36 }
37
38 if err != nil {
39 return nil, err
40 }
41
42 // verify project
43 ok, err := validateProject(project)
44 if err != nil {
45 return nil, err
46 }
47 if !ok {
48 return nil, fmt.Errorf("project doesn't exist")
49 }
50
51 conf := make(core.Configuration)
52 conf[core.ConfigKeyTarget] = target
53 conf[confKeyProject] = project
54
55 err = l.ValidateConfig(conf)
56 if err != nil {
57 return nil, err
58 }
59
60 return conf, nil
61}
62
63func (*Launchpad) ValidateConfig(conf core.Configuration) error {
64 if v, ok := conf[core.ConfigKeyTarget]; !ok {
65 return fmt.Errorf("missing %s key", core.ConfigKeyTarget)
66 } else if v != target {
67 return fmt.Errorf("unexpected target name: %v", v)
68 }
69 if _, ok := conf[confKeyProject]; !ok {
70 return fmt.Errorf("missing %s key", confKeyProject)
71 }
72
73 return nil
74}
75
76func validateProject(project string) (bool, error) {
77 url := fmt.Sprintf("%s/%s", apiRoot, project)
78
79 client := &http.Client{
80 Timeout: defaultTimeout,
81 }
82
83 resp, err := client.Get(url)
84 if err != nil {
85 return false, err
86 }
87
88 return resp.StatusCode == http.StatusOK, nil
89}
90
91// extract project name from url
92func splitURL(url string) (string, error) {
93 re, err := regexp.Compile(`launchpad\.net[\/:]([^\/]*[a-z]+)`)
94 if err != nil {
95 panic("regexp compile:" + err.Error())
96 }
97
98 res := re.FindStringSubmatch(url)
99 if res == nil {
100 return "", ErrBadProjectURL
101 }
102
103 return res[1], nil
104}