Skip to content

Commit 96a2020

Browse files
author
彭博
committed
修复 master 指向问题以及集成 glog 到 cobra
1 parent 11d8b2a commit 96a2020

File tree

9 files changed

+180
-45
lines changed

9 files changed

+180
-45
lines changed

.DS_Store

6 KB
Binary file not shown.

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.cookie
22
vendor
3-
.idea
3+
.idea
4+
dist

Gopkg.lock

Lines changed: 7 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Gopkg.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,7 @@
4848
[prune]
4949
go-tests = true
5050
unused-packages = true
51+
52+
[[constraint]]
53+
branch = "master"
54+
name = "github.com/golang/glog"

build.sh

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env bash
2+
3+
set -eo pipefail
4+
5+
APP_NAME=coding-cli
6+
MAIN=main.go
7+
ARCH=amd64
8+
OS=(
9+
darwin
10+
linux
11+
windows
12+
)
13+
DIST_DIR=dist
14+
15+
function GO_BUILD() {
16+
executable=${APP_NAME}-${GOOS}-${GOARCH}
17+
if [ $GOOS == "windows" ]; then
18+
executable=${APP_NAME}-${GOOS}-${GOARCH}.exe
19+
fi
20+
go build -ldflags="-s -w" -o $DIST_DIR/$executable $MAIN
21+
echo " $executable done."
22+
if hash upx 2>/dev/null; then
23+
echo " Compressing binary size using UPX for $executable"
24+
upx --ultra-brute $DIST_DIR/$executable
25+
echo " Compressed for $executable"
26+
else
27+
echo " No UPX installed, binary would not be comporessed"
28+
if [ `uname` == "Darwin" ]; then
29+
echo " Install UPX using brew: \`brew install upx\`"
30+
fi
31+
fi
32+
}
33+
34+
# Cleanup dist
35+
rm -rf $DIST_DIR
36+
37+
# Build exe
38+
echo "Building executables..."
39+
for os in "${OS[@]}"; do
40+
GOOS=$os GOARCH=$ARCH GO_BUILD
41+
done
42+
echo "All executables built."
43+
echo ""
44+
45+
# Package all exe
46+
echo "Packaging executables and configuration file..."
47+
zip -r $DIST_DIR/coding-cli.zip $DIST_DIR > /dev/null
48+
echo ""
49+
50+
echo "All done."

cmd/release.go

Lines changed: 82 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package cmd
1616

1717
import (
18+
"flag"
1819
"fmt"
1920
"io"
2021
"net/url"
@@ -29,6 +30,7 @@ import (
2930
"e.coding.net/codingcorp/coding-cli/pkg/model"
3031

3132
"e.coding.net/codingcorp/coding-cli/pkg/request"
33+
"github.com/golang/glog"
3234
"github.com/spf13/cobra"
3335
)
3436

@@ -38,6 +40,7 @@ const (
3840
diffURI = "/api/user/codingcorp/project/coding-dev/git/compare_v2?source=%s&target=%s&w=&prefix="
3941
mergeURI = "/api/user/codingcorp/project/coding-dev/git/merge/%d"
4042
gitBlobURI = "/api/user/codingcorp/project/coding-dev/git/blob/%s"
43+
referURI = "/api/user/codingcorp/project/coding-dev/resource_reference/%d"
4144
currentUserURI = "/api/current_user"
4245
diffTemplate = "/p/coding-dev/git/compare/%s...%s"
4346
)
@@ -110,26 +113,21 @@ var product string
110113

111114
// releaseCmd represents the release command
112115
var releaseCmd = &cobra.Command{
113-
Use: "release [分支、提交或标签]",
116+
Use: "release 目标分支 或 源分支 目标分支",
114117
Short: "创建版本发布",
115118
Long: `创建版本发布
116119
117120
为分支、提交或标签(简称 ref)创建版本发布,版本发布分为常规发布和紧急修复两类。`,
118121
Args: cobra.MinimumNArgs(1),
119122
Run: func(cmd *cobra.Command, args []string) {
120-
if len(args) == 0 {
121-
fmt.Fprintln(os.Stderr, "需提供分支名、提交或标签")
122-
return
123-
}
124-
target := args[0]
125-
source, err := defaultBranchCommitID()
123+
source, target, err := parseArgs(args)
126124
if err != nil {
127-
fmt.Fprintf(os.Stderr, "无法获取默认分支, %v\n", err)
125+
glog.Error("解析目标分支参数异常,%v", err)
128126
return
129127
}
130128
r, err := release(source, target)
131129
if err != nil {
132-
fmt.Fprintf(os.Stderr, "无法创建版本发布, %v\n", err)
130+
glog.Error("无法创建版本发布, %v", err)
133131
return
134132
}
135133
// 计算发布版本号
@@ -141,7 +139,7 @@ var releaseCmd = &cobra.Command{
141139
// 获取当前用户
142140
user, err := currentUser()
143141
if err != nil {
144-
fmt.Fprintf(os.Stderr, "获取负责人失败, %v\n", err)
142+
glog.Error("获取负责人失败, %v", err)
145143
return
146144
}
147145
r.Principal = user.Name
@@ -167,16 +165,35 @@ var releaseCmd = &cobra.Command{
167165
err = r.save(f)
168166
if err != nil {
169167
if shouldSave {
170-
fmt.Fprintf(os.Stderr, "文件保存失败, %v\n", err)
168+
glog.Error("文件保存失败, %v", err)
171169
} else {
172-
fmt.Fprintf(os.Stderr, "%v", err)
170+
glog.Error("%v", err)
173171
}
174172
} else if shouldSave {
175-
fmt.Printf("版本发布 %s 已保存到 %s\n", r.Release, output)
173+
glog.Error("版本发布 %s 已保存到 %s", r.Release, output)
176174
}
177175
},
178176
}
179177

178+
func parseArgs(args []string) (source string, target string, err error) {
179+
argsSize := len(args)
180+
if argsSize == 0 {
181+
return "", "", fmt.Errorf("需提供分支名、提交或标签")
182+
}
183+
if argsSize == 1 {
184+
target = args[0]
185+
source, err = defaultBranchCommitID()
186+
if err != nil {
187+
return "", "", fmt.Errorf("无法获取默认分支, %v", err)
188+
}
189+
}
190+
if argsSize == 2 {
191+
source = args[0]
192+
target = args[1]
193+
}
194+
return
195+
}
196+
180197
func contains(s interface{}, elem interface{}) bool {
181198
arrV := reflect.ValueOf(s)
182199
if arrV.Kind() == reflect.Slice {
@@ -190,15 +207,16 @@ func contains(s interface{}, elem interface{}) bool {
190207
}
191208

192209
type createRelease struct {
193-
Changes []changelog
194-
Diff string
195-
Hotfix bool
196-
Principal string
197-
Milestone string
198-
Services []string
199-
Release string
200-
Migration []migration
201-
Master string
210+
Changes []changelog
211+
Diff string
212+
Hotfix bool
213+
Principal string
214+
Milestone string
215+
Services []string
216+
Release string
217+
Migration []migration
218+
Master string
219+
PostMaster string
202220
}
203221

204222
var funcMap = template.FuncMap{
@@ -210,7 +228,7 @@ var funcMap = template.FuncMap{
210228
func (release *createRelease) save(o io.Writer) error {
211229
outputTpl, err := template.New("output").Funcs(funcMap).Parse(`## ChangeLog
212230
213-
{{range .Changes}}- {{.Title}} #{{.MergeID}}
231+
{{range .Changes}}- {{.Title}}{{range .TaskIDs}} #{{.}}{{end}} #{{.MergeID}}
214232
{{end}}
215233
216234
## Diff
@@ -249,7 +267,7 @@ func (release *createRelease) save(o io.Writer) error {
249267
### 发布后 master 指向
250268
251269
` + "`" + "`" + "`" + `
252-
{{.Master}}
270+
{{.PostMaster}}
253271
` + "`" + "`" + "`" + `
254272
`)
255273

@@ -289,17 +307,19 @@ func release(src string, target string) (r *createRelease, err error) {
289307
if len(src) != 40 {
290308
s, err = commitID(src)
291309
}
292-
r.Master = s
293-
294310
if err != nil {
295311
return nil, err
296312
}
313+
r.Master = s
297314
if len(target) != 40 {
298315
t, err = commitID(target)
299316
}
300317
if err != nil {
301318
return nil, err
302319
}
320+
r.PostMaster = t
321+
322+
glog.Infof("正在创建基于 %s(%s)...%s(%s) 的版本发布", s, src, t, target)
303323

304324
// 变更记录
305325
d, err := diff(s, t)
@@ -310,6 +330,7 @@ func release(src string, target string) (r *createRelease, err error) {
310330
if err != nil {
311331
return nil, err
312332
}
333+
glog.Infof("此版本包含 %d 个主要改动", len(r.Changes))
313334

314335
// 网页版本对比链接
315336
r.Diff, err = compareURL(s, t)
@@ -354,12 +375,7 @@ func file(c model.Commit, n string) (string, error) {
354375
func migrationScripts(c []changelog) ([]migration, error) {
355376
scripts := make([]migration, 0)
356377
for _, log := range c {
357-
req := request.NewGet(fmt.Sprintf(mergeURI, log.MergeID))
358-
merge := model.Merge{}
359-
err := req.SendAndUnmarshal(&merge)
360-
if err != nil {
361-
return nil, fmt.Errorf("获取合并请求失败, mergeID: %d, %v", log.MergeID, err)
362-
}
378+
merge := log.Merge
363379
paths := merge.MergeRequest.DiffStat.Paths
364380
for _, path := range paths {
365381
if path.Deletions == 0 && path.Insertions > 0 {
@@ -385,7 +401,7 @@ func findServices(names []string) []string {
385401
for _, name := range names {
386402
index, err := matchPattern(name, patterns)
387403
if err != nil {
388-
fmt.Println(err)
404+
glog.Infof("%v", err)
389405
continue
390406
}
391407
if index > servicesSize-1 {
@@ -415,13 +431,15 @@ func matchPattern(file string, patterns []string) (int, error) {
415431
return index, nil
416432
}
417433
}
418-
return -1, fmt.Errorf("无匹配结果, 文件不包含以下前缀\n\t文件:%s\n\t前缀:[%s]", file, strings.Join(patterns, ", "))
434+
return -1, fmt.Errorf("无匹配结果, 文件不包含以下前缀\t文件:%s\t前缀:[%s]", file, strings.Join(patterns, ", "))
419435
}
420436

421437
// changelog 包含 Merge Request 标题、Merge Request 完整信息以及任务完整信息
422438
type changelog struct {
423439
Title string
424440
MergeID int
441+
TaskIDs []int
442+
Merge model.Merge
425443
}
426444

427445
func changelogs(commits []model.Commit) ([]changelog, error) {
@@ -438,11 +456,40 @@ func changelogs(commits []model.Commit) ([]changelog, error) {
438456
if mergeID != 0 {
439457
c.MergeID = mergeID
440458
}
459+
req := request.NewGet(fmt.Sprintf(mergeURI, mergeID))
460+
merge := model.Merge{}
461+
err := req.SendAndUnmarshal(&merge)
462+
if err != nil {
463+
return nil, fmt.Errorf("获取合并请求失败, mergeID: %d, %v", mergeID, err)
464+
}
465+
c.Merge = merge
466+
glog.Infof("提取到合并请求 #%d - %s", mergeID, merge.MergeRequest.Title)
467+
ref, err := refer(mergeID)
468+
if err != nil {
469+
return nil, err
470+
}
471+
if ref.Task != nil {
472+
taskIDs := make([]int, 0)
473+
for _, t := range ref.Task {
474+
taskIDs = append(taskIDs, t.Code)
475+
}
476+
c.TaskIDs = taskIDs
477+
}
441478
changelogs = append(changelogs, c)
442479
}
443480
return changelogs, nil
444481
}
445482

483+
func refer(resourceID int) (*model.Refer, error) {
484+
req := request.NewGet(fmt.Sprintf(referURI, resourceID))
485+
refer := model.Refer{}
486+
err := req.SendAndUnmarshal(&refer)
487+
if err != nil {
488+
return nil, fmt.Errorf("获取资源引用请求失败, resourceID: %d, %v", resourceID, err)
489+
}
490+
return &refer, nil
491+
}
492+
446493
var mergeRequestIDReg = regexp.MustCompile(`merge/(\d+)`)
447494

448495
func mergeRequestID(msg string) int {
@@ -519,4 +566,5 @@ func init() {
519566
releaseCmd.Flags().StringVarP(&output, "output", "o", "", "保存到文件")
520567
releaseCmd.Flags().StringVarP(&rtype, "type", "t", "normal", "发布类型,hotfix - 紧急修复或者 normal - 常规更新")
521568
releaseCmd.Flags().StringVarP(&product, "product", "p", "enterprise-saas", "产品线,enterprise-saas 或者 professional")
569+
flag.Parse()
522570
}

cmd/root.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,14 @@ import (
1818
"fmt"
1919
"os"
2020

21+
goflag "flag"
22+
23+
"github.com/golang/glog"
2124
homedir "github.com/mitchellh/go-homedir"
2225
"github.com/spf13/cobra"
2326
"github.com/spf13/viper"
27+
28+
flag "github.com/spf13/pflag"
2429
)
2530

2631
var cfgFile string
@@ -41,13 +46,15 @@ var rootCmd = &cobra.Command{
4146
// This is called by main.main(). It only needs to happen once to the rootCmd.
4247
func Execute() {
4348
if err := rootCmd.Execute(); err != nil {
44-
fmt.Println(err)
49+
glog.Error(err)
4550
os.Exit(1)
4651
}
4752
}
4853

4954
func init() {
5055
cobra.OnInitialize(initConfig)
56+
// use glog in cobra see https://flowerinthenight.com/blog/2017/12/01/golang-cobra-glog
57+
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
5158
}
5259

5360
// initConfig reads in config file and ENV variables if set.

pkg/model/refer.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package model
2+
3+
type Refer struct {
4+
Task []struct {
5+
TargetProjectID int `json:"target_project_id"`
6+
TargetProjectName string `json:"target_project_name"`
7+
Code int `json:"code"`
8+
TargetType string `json:"target_type"`
9+
TargetID int `json:"target_id"`
10+
Title string `json:"title"`
11+
Link string `json:"link"`
12+
Status int `json:"status"`
13+
} `json:"Task"`
14+
}

0 commit comments

Comments
 (0)