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