github.com/trevoraustin/hub@v2.2.0-preview1.0.20141105230840-96d8bfc654cc+incompatible/commands/compare.go (about) 1 package commands 2 3 import ( 4 "fmt" 5 "regexp" 6 7 "github.com/github/hub/github" 8 "github.com/github/hub/utils" 9 ) 10 11 var cmdCompare = &Command{ 12 Run: compare, 13 Usage: "compare [-u] [USER] [<START>...]<END>", 14 Short: "Open a compare page on GitHub", 15 Long: `Open a GitHub compare view page in the system's default web browser. 16 <START> to <END> are branch names, tag names, or commit SHA1s specifying 17 the range of history to compare. If a range with two dots ("a..b") is given, 18 it will be transformed into one with three dots. If <START> is omitted, 19 GitHub will compare against the base branch (the default is "master"). 20 If <END> is omitted, GitHub compare view is opened for the current branch. 21 With "-u", outputs the URL rather than opening the browser. 22 `, 23 } 24 25 var ( 26 flagCompareURLOnly bool 27 ) 28 29 func init() { 30 cmdCompare.Flag.BoolVarP(&flagCompareURLOnly, "url-only", "u", false, "URL only") 31 32 CmdRunner.Use(cmdCompare) 33 } 34 35 /* 36 $ gh compare refactor 37 > open https://github.com/CURRENT_REPO/compare/refactor 38 39 $ gh compare 1.0..1.1 40 > open https://github.com/CURRENT_REPO/compare/1.0...1.1 41 42 $ gh compare -u other-user patch 43 > open https://github.com/other-user/REPO/compare/patch 44 */ 45 func compare(command *Command, args *Args) { 46 localRepo, err := github.LocalRepo() 47 utils.Check(err) 48 49 var ( 50 branch *github.Branch 51 project *github.Project 52 r string 53 ) 54 55 branch, project, err = localRepo.RemoteBranchAndProject("", false) 56 utils.Check(err) 57 58 if args.IsParamsEmpty() { 59 if branch != nil && !branch.IsMaster() { 60 r = branch.ShortName() 61 } else { 62 err = fmt.Errorf("Usage: hub compare [USER] [<START>...]<END>") 63 utils.Check(err) 64 } 65 } else { 66 r = parseCompareRange(args.RemoveParam(args.ParamsSize() - 1)) 67 if args.IsParamsEmpty() { 68 project, err = localRepo.CurrentProject() 69 utils.Check(err) 70 } else { 71 project = github.NewProject(args.RemoveParam(args.ParamsSize()-1), "", "") 72 } 73 } 74 75 subpage := utils.ConcatPaths("compare", r) 76 url := project.WebURL("", "", subpage) 77 launcher, err := utils.BrowserLauncher() 78 utils.Check(err) 79 80 if flagCompareURLOnly { 81 args.Replace("echo", url) 82 } else { 83 args.Replace(launcher[0], "", launcher[1:]...) 84 args.AppendParams(url) 85 } 86 } 87 88 func parseCompareRange(r string) string { 89 shaOrTag := fmt.Sprintf("((?:%s:)?\\w[\\w.-]+\\w)", OwnerRe) 90 shaOrTagRange := fmt.Sprintf("^%s\\.\\.%s$", shaOrTag, shaOrTag) 91 shaOrTagRangeRegexp := regexp.MustCompile(shaOrTagRange) 92 return shaOrTagRangeRegexp.ReplaceAllString(r, "$1...$2") 93 }