github.com/pengwynn/gh@v1.0.1-0.20140118055701-14327ca3942e/commands/ci_status.go (about) 1 package commands 2 3 import ( 4 "fmt" 5 "github.com/jingweno/gh/git" 6 "github.com/jingweno/gh/github" 7 "github.com/jingweno/gh/utils" 8 "os" 9 ) 10 11 var cmdCiStatus = &Command{ 12 Run: ciStatus, 13 Usage: "ci-status [-v] [COMMIT]", 14 Short: "Show CI status of a commit", 15 Long: `Looks up the SHA for <COMMIT> in GitHub Status API and displays the latest 16 status. Exits with one of: 17 success (0), error (1), failure (1), pending (2), no status (3) 18 19 If "-v" is given, additionally print the URL to CI build results. 20 `, 21 } 22 23 var flagCiStatusVerbose bool 24 25 func init() { 26 cmdCiStatus.Flag.BoolVarP(&flagCiStatusVerbose, "verbose", "v", false, "VERBOSE") 27 28 CmdRunner.Use(cmdCiStatus) 29 } 30 31 /* 32 $ gh ci-status 33 > (prints CI state of HEAD and exits with appropriate code) 34 > One of: success (0), error (1), failure (1), pending (2), no status (3) 35 36 $ gh ci-status -v 37 > (prints CI state of HEAD, the URL to the CI build results and exits with appropriate code) 38 > One of: success (0), error (1), failure (1), pending (2), no status (3) 39 40 $ gh ci-status BRANCH 41 > (prints CI state of BRANCH and exits with appropriate code) 42 > One of: success (0), error (1), failure (1), pending (2), no status (3) 43 44 $ gh ci-status SHA 45 > (prints CI state of SHA and exits with appropriate code) 46 > One of: success (0), error (1), failure (1), pending (2), no status (3) 47 */ 48 func ciStatus(cmd *Command, args *Args) { 49 ref := "HEAD" 50 if !args.IsParamsEmpty() { 51 ref = args.RemoveParam(0) 52 } 53 54 localRepo := github.LocalRepo() 55 project, err := localRepo.MainProject() 56 utils.Check(err) 57 58 sha, err := git.Ref(ref) 59 if err != nil { 60 err = fmt.Errorf("Aborted: no revision could be determined from '%s'", ref) 61 } 62 utils.Check(err) 63 64 if args.Noop { 65 fmt.Printf("Would request CI status for %s\n", sha) 66 } else { 67 state, targetURL, exitCode, err := fetchCiStatus(project, sha) 68 utils.Check(err) 69 if flagCiStatusVerbose && targetURL != "" { 70 fmt.Printf("%s: %s\n", state, targetURL) 71 } else { 72 fmt.Println(state) 73 } 74 75 os.Exit(exitCode) 76 } 77 } 78 79 func fetchCiStatus(p *github.Project, sha string) (state, targetURL string, exitCode int, err error) { 80 gh := github.NewClient(p.Host) 81 status, err := gh.CIStatus(p, sha) 82 if err != nil { 83 return 84 } 85 86 if status == nil { 87 state = "no status" 88 } else { 89 state = status.State 90 targetURL = status.TargetURL 91 } 92 93 switch state { 94 case "success": 95 exitCode = 0 96 case "failure", "error": 97 exitCode = 1 98 case "pending": 99 exitCode = 2 100 default: 101 exitCode = 3 102 } 103 104 return 105 }