forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
step_changelog.go
404 lines (369 loc) · 11 KB
/
step_changelog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package cmd
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"time"
"github.com/ghodss/yaml"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/src-d/go-git.v4/plumbing/object"
chgit "github.com/jenkins-x/chyle/chyle/git"
cmdutil "github.com/jenkins-x/jx/pkg/jx/cmd/util"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"strconv"
"strings"
)
// StepChangelogOptions contains the command line flags
type StepChangelogOptions struct {
StepOptions
PreviousRevision string
CurrentRevision string
TemplatesDir string
ReleaseYamlFile string
CrdYamlFile string
Dir string
Version string
OverwriteCRD bool
GenerateCRD bool
UpdateRelease bool
State StepChangelogState
}
type StepChangelogState struct {
GitInfo *gits.GitRepositoryInfo
GitProvider gits.GitProvider
FoundIssueNames map[string]bool
}
const (
ReleaseName = `{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}`
SpecName = `{{ .Chart.Name }}`
SpecVersion = `{{ .Chart.Version }}`
ReleaseCrdYaml = `apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
creationTimestamp: 2018-02-24T14:56:33Z
name: releases.jenkins.io
resourceVersion: "557150"
selfLink: /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions/releases.jenkins.io
uid: e77f4e08-1972-11e8-988e-42010a8401df
spec:
group: jenkins.io
names:
kind: Release
listKind: ReleaseList
plural: releases
shortNames:
- rel
singular: release
scope: Namespaced
version: v1`
)
var (
StepChangelogLong = templates.LongDesc(`
Generates a Changelog for the last tag
`)
StepChangelogExample = templates.Examples(`
jx step changelog
`)
GitHubIssueRegex = regexp.MustCompile(`(\#\d+)`)
)
func NewCmdStepChangelog(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := StepChangelogOptions{
StepOptions: StepOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "changelog",
Short: "Creates a changelog for a git tag",
Aliases: []string{"changes"},
Long: StepChangelogLong,
Example: StepChangelogExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
cmdutil.CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.PreviousRevision, "previous-rev", "p", "", "the previous tag revision")
cmd.Flags().StringVarP(&options.CurrentRevision, "rev", "r", "", "the current tag revision")
cmd.Flags().StringVarP(&options.TemplatesDir, "templates-dir", "t", "", "the directory containing the helm chart templates to generate the resources")
cmd.Flags().StringVarP(&options.ReleaseYamlFile, "release-yaml-file", "", "release.yaml", "the name of the file to generate the Release YAML")
cmd.Flags().StringVarP(&options.CrdYamlFile, "crd-yaml-file", "", "release-crd.yaml", "the name of the file to generate the Release CustomResourceDefinition YAML")
cmd.Flags().StringVarP(&options.Version, "version", "v", "", "The version to release")
cmd.Flags().StringVarP(&options.Dir, "dir", "", "", "The directory of the git repository. Defaults to the current working directory")
cmd.Flags().BoolVarP(&options.OverwriteCRD, "overwrite", "o", false, "overwrites the Release CRD YAML file if it exists")
cmd.Flags().BoolVarP(&options.GenerateCRD, "crd", "c", false, "Generate the CRD in the chart")
cmd.Flags().BoolVarP(&options.UpdateRelease, "update-release", "", true, "Should we update the release on the git repository with the changelog")
return cmd
}
func (o *StepChangelogOptions) Run() error {
apisClient, err := o.Factory.CreateApiExtensionsClient()
if err != nil {
return err
}
err = kube.RegisterPipelineActivityCRD(apisClient)
if err != nil {
return err
}
err = kube.RegisterReleaseCRD(apisClient)
if err != nil {
return err
}
dir := o.Dir
if dir == "" {
dir, err = os.Getwd()
if err != nil {
return err
}
}
previousRev := o.PreviousRevision
if previousRev == "" {
previousRev, err = gits.GetPreviousGitTagSHA(dir)
if err != nil {
return err
}
}
currentRev := o.CurrentRevision
if currentRev == "" {
currentRev, err = gits.GetCurrentGitTagSHA(dir)
if err != nil {
return err
}
}
templatesDir := o.TemplatesDir
if templatesDir == "" {
chartFile, err := o.FindHelmChart()
if err != nil {
return fmt.Errorf("Could not find helm chart %s", err)
}
path, _ := filepath.Split(chartFile)
templatesDir = filepath.Join(path, "templates")
}
err = os.MkdirAll(templatesDir, DefaultWritePermissions)
if err != nil {
return fmt.Errorf("Failed to create the templates directory %s due to %s", templatesDir, err)
}
o.Printf("Generating change log from git ref %s => %s\n", util.ColorInfo(previousRev), util.ColorInfo(currentRev))
gitDir, gitConfDir, err := gits.FindGitConfigDir(dir)
if err != nil {
return err
}
if gitDir == "" || gitConfDir == "" {
o.warnf("No git directory could be found from dir %s\n", dir)
return nil
}
gitUrl, err := gits.DiscoverUpstreamGitURL(gitConfDir)
if err != nil {
return err
}
gitInfo, err := gits.ParseGitURL(gitUrl)
if err != nil {
return err
}
o.State.GitInfo = gitInfo
authConfigSvc, err := o.Factory.CreateGitAuthConfigService()
if err != nil {
return err
}
gitProvider, err := o.State.GitInfo.CreateProvider(authConfigSvc)
if err != nil {
return err
}
o.State.GitProvider = gitProvider
o.State.FoundIssueNames = map[string]bool{}
commits, err := chgit.FetchCommits(gitDir, previousRev, currentRev)
if err != nil {
return err
}
release := &v1.Release{
TypeMeta: metav1.TypeMeta{
Kind: "Release",
APIVersion: jenkinsio.GroupAndVersion,
},
ObjectMeta: metav1.ObjectMeta{
Name: ReleaseName,
CreationTimestamp: metav1.Time{
Time: time.Now(),
},
ResourceVersion: "1",
DeletionTimestamp: &metav1.Time{},
},
Spec: v1.ReleaseSpec{
Name: SpecName,
Version: SpecVersion,
GitHttpURL: gitInfo.HttpURL(),
GitCloneURL: gitInfo.HttpCloneURL(),
Commits: []v1.CommitSummary{},
Issues: []v1.IssueSummary{},
PullRequests: []v1.IssueSummary{},
},
}
if commits != nil {
for _, commit := range *commits {
o.addCommit(&release.Spec, &commit)
}
}
data, err := yaml.Marshal(release)
if err != nil {
return err
}
if data == nil {
return fmt.Errorf("Could not marshal release to yaml")
}
releaseFile := filepath.Join(templatesDir, o.ReleaseYamlFile)
crdFile := filepath.Join(templatesDir, o.CrdYamlFile)
err = ioutil.WriteFile(releaseFile, data, DefaultWritePermissions)
if err != nil {
return fmt.Errorf("Failed to save Release YAML file %s: %s", releaseFile, err)
}
exists, err := util.FileExists(crdFile)
if err != nil {
return fmt.Errorf("Failed to check for CRD YAML file %s: %s", crdFile, err)
}
o.Printf("generated: %s\n", util.ColorInfo(releaseFile))
if o.GenerateCRD && (o.OverwriteCRD || !exists) {
err = ioutil.WriteFile(crdFile, []byte(ReleaseCrdYaml), DefaultWritePermissions)
if err != nil {
return fmt.Errorf("Failed to save Release CRD YAML file %s: %s", crdFile, err)
}
o.Printf("generated: %s\n", util.ColorInfo(crdFile))
}
// lets try to update the release
markdown, err := gits.GenerateMarkdown(&release.Spec, gitInfo)
if err != nil {
return err
}
version := o.Version
if version != "" && o.UpdateRelease {
releaseInfo := &gits.GitRelease{
Name: version,
TagName: version,
Body: markdown,
}
err = gitProvider.UpdateRelease(gitInfo.Organisation, gitInfo.Name, version, releaseInfo)
url := util.UrlJoin(gitInfo.HttpURL(), "releases/tag", version)
if err != nil {
return fmt.Errorf("Failed to update the release at %s: %s", url, err)
}
o.Printf("Updated the release information at %s\n", util.ColorInfo(url))
} else {
o.Printf("\nGenerated Changelog:\n")
o.Printf("%s\n\n", markdown)
}
return nil
}
func (o *StepChangelogOptions) addCommit(spec *v1.ReleaseSpec, commit *object.Commit) {
// TODO
url := ""
branch := "master"
sha := commit.Hash.String()
commitSummary := v1.CommitSummary{
Message: commit.Message,
URL: url,
SHA: sha,
Author: o.toUserDetails(commit.Author),
Branch: branch,
Committer: o.toUserDetails(commit.Committer),
}
spec.Commits = append(spec.Commits, commitSummary)
err := o.addIssuesAndPullRequests(spec, &commitSummary)
if err != nil {
o.warnf("Failed to enrich commits with issues: %s\n", err)
}
}
func (o *StepChangelogOptions) addIssuesAndPullRequests(spec *v1.ReleaseSpec, commit *v1.CommitSummary) error {
// TODO for now assume github but allow a JIRA server & project name to be specified...
gitProvider := o.State.GitProvider
if !gitProvider.HasIssues() {
return nil
}
gitInfo := o.State.GitInfo
results := GitHubIssueRegex.FindStringSubmatch(commit.Message)
for _, result := range results {
numberText := strings.TrimPrefix(result, "#")
if _, ok := o.State.FoundIssueNames[result]; !ok {
o.State.FoundIssueNames[result] = true
number, err := strconv.Atoi(numberText)
if err != nil {
o.warnf("Failed to convert issue reference %s into a number %s\n", numberText, err)
continue
}
owner := gitInfo.Organisation
repo := gitInfo.Name
issue, err := gitProvider.GetIssue(owner, repo, number)
if err != nil {
o.warnf("Failed to lookup issue %s in repository\n", result, err)
continue
}
if issue == nil {
o.warnf("Failed to find issue %d for repository %s/%s\n", number, owner, repo)
}
issueSummary := v1.IssueSummary{
ID: numberText,
URL: issue.URL,
Title: issue.Title,
Body: issue.Body,
User: o.gitUserToUserDetails(issue.User),
ClosedBy: o.gitUserToUserDetails(issue.ClosedBy),
Assignees: o.gitUserToUserDetailSlice(issue.Assignees),
}
state := issue.State
if state != nil {
issueSummary.State = *state
}
if issue.IsPullRequest {
spec.PullRequests = append(spec.PullRequests, issueSummary)
} else {
spec.Issues = append(spec.Issues, issueSummary)
}
}
}
return nil
}
func (o *StepChangelogOptions) gitUserToUserDetailSlice(users []gits.GitUser) []v1.UserDetails {
answer := []v1.UserDetails{}
for _, user := range users {
answer = append(answer, *o.gitUserToUserDetails(&user))
}
return answer
}
func (o *StepChangelogOptions) gitUserToUserDetails(user *gits.GitUser) *v1.UserDetails {
return &v1.UserDetails{
Login: user.Login,
Name: user.Name,
Email: user.Email,
URL: user.URL,
AvatarURL: user.AvatarURL,
/*
CreationTimestamp: &metav1.Time{
Time: user.When,
},
*/
}
}
func (o *StepChangelogOptions) toUserDetails(signature object.Signature) *v1.UserDetails {
// TODO
login := ""
return &v1.UserDetails{
Login: login,
Name: signature.Name,
Email: signature.Email,
CreationTimestamp: &metav1.Time{
Time: signature.When,
},
}
}