20
20
package book
21
21
22
22
import (
23
+ "encoding/json"
23
24
"fmt"
25
+ "net/http"
24
26
"os"
25
27
"os/exec"
28
+ "strings"
26
29
27
30
"github.com/pkg/errors"
28
31
"github.com/symfony-cli/terminal"
@@ -41,6 +44,25 @@ func (b *Book) Clone(version string) error {
41
44
}
42
45
43
46
ui .Section ("Cloning the Repository" )
47
+
48
+ // check that version exists on Github via the API
49
+ resp , err := http .Get (fmt .Sprintf ("https://api.github.com/repos/the-fast-track/book-%s" , version ))
50
+ if err != nil {
51
+ return errors .Wrap (err , "unable to get version on Github" )
52
+ }
53
+ defer resp .Body .Close ()
54
+ if resp .StatusCode != http .StatusOK {
55
+ versions , err := Versions ()
56
+ if err != nil {
57
+ return errors .Wrap (err , "unable to get book versions" )
58
+ }
59
+ terminal .Println ("The version you requested does not exist; available versions:" )
60
+ for _ , v := range versions {
61
+ terminal .Println (fmt .Sprintf (" - %s" , v ))
62
+ }
63
+ return errors .New ("please choose a valid version" )
64
+ }
65
+
44
66
cmd := exec .Command ("git" , "clone" , fmt .Sprintf ("https://github.com/the-fast-track/book-%s" , version ), b .Dir )
45
67
cmd .Env = os .Environ ()
46
68
cmd .Stdout = os .Stdout
@@ -63,3 +85,25 @@ func (b *Book) Clone(version string) error {
63
85
}
64
86
return nil
65
87
}
88
+
89
+ func Versions () ([]string , error ) {
90
+ resp , err := http .Get ("https://api.github.com/orgs/the-fast-track/repos" )
91
+ if err != nil {
92
+ return nil , errors .Wrap (err , "unable to get repositories from Github" )
93
+ }
94
+ defer resp .Body .Close ()
95
+ if resp .StatusCode != http .StatusOK {
96
+ return nil , errors .New ("failed to get repositories from Github" )
97
+ }
98
+ var repos []struct {
99
+ Name string `json:"name"`
100
+ }
101
+ if err := json .NewDecoder (resp .Body ).Decode (& repos ); err != nil {
102
+ return nil , errors .Wrap (err , "failed to decode response body" )
103
+ }
104
+ versions := []string {}
105
+ for _ , repo := range repos {
106
+ versions = append (versions , strings .Replace (repo .Name , "book-" , "" , 1 ))
107
+ }
108
+ return versions , nil
109
+ }
0 commit comments