github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/cmd/chore/e2e/trigger/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "flag" 7 "fmt" 8 "io" 9 "net/http" 10 "os" 11 "os/exec" 12 "strconv" 13 "strings" 14 ) 15 16 func main() { 17 18 var ( 19 token, org, repository, branch string 20 from int 21 cleanup bool 22 ) 23 24 flag.StringVar(&token, "access-token", "", "Personal access token with repo scope") 25 flag.StringVar(&org, "organization", "", "Github organization") 26 flag.StringVar(&repository, "repository", "", "Github project") 27 flag.StringVar(&branch, "branch", "", "Branch to test. Default is current") 28 flag.IntVar(&from, "from", 1, "From e2e test stage") 29 flag.BoolVar(&cleanup, "cleanup", true, "Cleanup after tests are done") 30 31 flag.Parse() 32 33 if branch == "" { 34 ref, err := exec.Command("git", "branch", "--show-current").Output() 35 if err != nil { 36 panic(err) 37 } 38 branch = strings.TrimPrefix(strings.TrimSpace(string(ref)), "heads/") 39 } 40 41 fmt.Printf("organization=%s\n", org) 42 fmt.Printf("repository=%s\n", repository) 43 fmt.Printf("branch=%s\n", branch) 44 fmt.Printf("from=%d\n", from) 45 fmt.Printf("cleanup=%t\n", cleanup) 46 47 if err := emit(event{ 48 EventType: "webhook-trigger", 49 ClientPayload: map[string]string{ 50 "branch": branch, 51 "from": strconv.Itoa(from), 52 "cleanup": strconv.FormatBool(cleanup), 53 }, 54 }, token, org, repository); err != nil { 55 panic(err) 56 } 57 } 58 59 type event struct { 60 EventType string `json:"event_type,omitempty"` 61 ClientPayload map[string]string `json:"client_payload,omitempty"` 62 Branch string `json:"branch,omitempty"` 63 } 64 65 func emit(event event, accessToken, organisation, repository string) error { 66 67 data, err := json.Marshal(event) 68 if err != nil { 69 return err 70 } 71 72 url := fmt.Sprintf("https://api.github.com/repos/%s/%s/dispatches", organisation, repository) 73 req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data)) 74 if err != nil { 75 return err 76 } 77 78 req.Header.Set("Accept", "application/vnd.github.everest-preview+json") 79 req.Header.Set("Authorization", fmt.Sprintf("token %s", accessToken)) 80 81 resp, err := http.DefaultClient.Do(req) 82 if err != nil { 83 return err 84 } 85 defer resp.Body.Close() 86 87 _, err = io.Copy(os.Stdout, resp.Body) 88 if err != nil { 89 return err 90 } 91 fmt.Println(resp.Status) 92 if resp.StatusCode >= 400 { 93 return fmt.Errorf("emitting github repository dispatch event at %s failed", url) 94 } 95 return nil 96 }