Compare commits

...

51 Commits

Author SHA1 Message Date
Felix Wiedmann
6211095c38 Merge pull request #27 from Nightapes/fix_commits
fix(commits):  don't break if commit is found and error happens on ol…
2019-10-08 21:09:43 +02:00
Nightapes
74e895b5ad fix(commits): don't break if commit is found and error happens on older commits and add better error message when git clone --depth is used 2019-10-08 20:46:57 +02:00
Sebastian
a69da92340 Merge pull request #26 from Nightapes/fix/build
build(workflow): fix call of binary
2019-09-25 10:42:44 +02:00
fwiedmann
ff87725801 build(workflow): fix call of binary 2019-09-25 00:20:41 +02:00
Felix Wiedmann
272a9b6e89 Merge pull request #25 from Nightapes/improvements
Improvements
2019-09-25 00:12:09 +02:00
Sebastian
07b606a21a Merge branch 'master' into improvements 2019-09-22 15:52:45 +02:00
Nightapes
44f95969bf feat(template): allow custom changelog template 2019-09-22 15:50:12 +02:00
Nightapes
399a3515f2 feat(docker): add docker image with go-semantic-release 2019-09-22 15:49:06 +02:00
Nightapes
2074877a3b build(pages): add jemoji plugin 2019-09-22 15:42:08 +02:00
Sebastian
b5551d8432 Set theme jekyll-theme-cayman 2019-09-22 15:34:33 +02:00
Sebastian
c92020d3ac Set theme jekyll-theme-slate 2019-09-22 15:33:05 +02:00
Felix Wiedmann
d9f2b163c7 Merge pull request #24 from Nightapes/fix/gitlab_request
fix(gitlab): fix broken request on release creation
2019-09-17 22:29:17 +02:00
Nightapes
4379551982 fix(gitlab): fix broken request on release creation 2019-09-17 21:01:05 +02:00
Felix Wiedmann
3eb13972ec Merge pull request #23 from Nightapes/fix_readme
docs(README): fix wrong confiig file
2019-09-16 22:36:39 +02:00
Sebastian
8659b40960 docs(README): fix wrong confiig file 2019-09-16 08:23:21 +02:00
Felix Wiedmann
7ead374039 Merge pull request #22 from Nightapes/gitlab_ci
fix(ci): add gitlab ci detection
2019-09-15 20:37:22 +02:00
Nightapes
ee1dc3d8db fix(ci): add gitlab ci detection 2019-09-15 20:13:17 +02:00
Felix Wiedmann
38e4c178ee Merge pull request #21 from Nightapes/golang_1_13
build(ci): update golang
2019-09-10 14:13:10 +02:00
Sebastian
e22d3d07f4 build(ci): update golang 2019-09-10 14:09:57 +02:00
Sebastian
46ae2da821 build(ci): update golangci-lint 2019-09-10 13:33:33 +02:00
Felix Wiedmann
e3265b1843 Merge pull request #19 from Nightapes/fix_release_version_calculation
Fix release version calculation
2019-09-03 23:43:02 +02:00
Nightapes
d03913e6d7 fix(pkg/semanticrelease): remove check for branch prefix for releases 2019-09-03 22:35:17 +02:00
Nightapes
e5ed8edb75 refactor(ci): add trace log 2019-09-03 22:18:13 +02:00
Nightapes
76ffeda95b fix(analyzer/angular): allow multi line commits 2019-09-03 21:44:38 +02:00
Nightapes
0994354089 fix(internal/calculator): fix relase version calculation 2019-09-03 21:34:00 +02:00
Felix Wiedmann
e8d7feeca3 Merge pull request #16 from Nightapes/improvements
Improvements
2019-09-03 09:54:22 +01:00
Sebastian
e0974e3140 Merge branch 'master' into improvements 2019-08-31 17:05:21 +02:00
Nightapes
8643656339 feat(changelog): add docker usage to changelog 2019-08-31 17:05:10 +02:00
Nightapes
829f2925ab fix(analyzer/angular): fix regex to regonize merge commits 2019-08-25 14:16:57 +02:00
Felix Wiedmann
7729ba5914 Merge pull request #14 from Nightapes/fix_first
fix(pkg/semantic-release): fix issue with first release in repository set first version to 1.0.0
2019-08-23 09:14:35 +02:00
Nightapes
72200582fd fix(pkg/semantic-release): fix issue with first release in repository, set first version to 1.0.0 2019-08-23 08:58:44 +02:00
Sebastian
2c26c8aa6d Merge pull request #11 from Nightapes/remove/draft
fix(github): remove 'draft' option because releases will always be pu…
2019-08-22 09:35:30 +02:00
Felix Wiedmann
4b72df07c8 Merge branch 'master' into remove/draft 2019-08-22 09:20:03 +02:00
Felix Wiedmann
df544f5be7 docs(releaser/util): remove unnecessary comment 2019-08-22 09:17:40 +02:00
Felix Wiedmann
812723e1f4 Merge pull request #13 from Nightapes/Nightapes-patch-1
feat(ci): add github actions
2019-08-22 09:12:47 +02:00
Sebastian
e91d9b0dac feat(ci): add github actions 2019-08-22 09:00:58 +02:00
fwiedmann
a2fc03c64d Merge branch 'master' of github.com:Nightapes/go-semantic-release into remove/draft 2019-08-22 00:12:24 +02:00
Felix Wiedmann
e419086dbe Merge pull request #12 from Nightapes/actions
build(ci): add github action
2019-08-22 00:07:31 +02:00
Nightapes
4c7cfd5e90 fix(ci): remove refs/heads/ from branch 2019-08-21 21:50:40 +02:00
Nightapes
89f4842a2b fear(ci): add github actions 2019-08-21 21:39:05 +02:00
Nightapes
7857b5f6f3 build(actions): add debug print 2019-08-21 21:23:07 +02:00
Nightapes
115964c9c1 fix(github): use env GITHUB_TOKEN for releaser 2019-08-21 21:06:57 +02:00
Nightapes
2f2f7e51fb build(ci): remove matrix, cache is missing 2019-08-21 20:52:53 +02:00
Nightapes
f1bb5470c0 test(internal): fix broken test after golang update 2019-08-21 20:39:58 +02:00
Nightapes
be1e483baa build(ci): fix action file 2019-08-21 20:06:30 +02:00
Nightapes
17f1890ca1 build(ci): update github action 2019-08-21 20:03:35 +02:00
Sebastian
6a53c3e587 build(ci): build needs test 2019-08-21 19:46:23 +02:00
Sebastian
a068e65369 build(ci): fix file 2019-08-21 19:41:51 +02:00
Sebastian
9e847c6af9 build(ci): add github action 2019-08-21 19:39:48 +02:00
fwiedmann
2eb64f153a test(util): add defer statement for testServer 2019-08-13 23:28:13 +02:00
fwiedmann
a6c651a97f fix(github): remove 'draft' option because releases will always be published public 2019-08-13 23:01:38 +02:00
35 changed files with 615 additions and 182 deletions

2
.dockerignore Normal file
View File

@@ -0,0 +1,2 @@
*
!build/

68
.github/workflows/main.yml vendored Normal file
View File

@@ -0,0 +1,68 @@
name: Go
on: [push, pull_request]
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v1
with:
go-version: 1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v1
- name: Lint
run: |
export PATH=$PATH:$(go env GOPATH)/bin
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.18.0
golangci-lint run ./...
- name: Run tests
run: go test ./...
- name: Build binary
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
go build -o build/go-semantic-release-temp ./cmd/go-semantic-release/
./build/go-semantic-release-temp next --no-cache --loglevel trace
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o build/go-semantic-release -ldflags "-w -s --X main.version=`./build/go-semantic-release-temp next`" ./cmd/go-semantic-release/
GOOS=windows GOARCH=386 CGO_ENABLED=0 go build -o build/go-semantic-release.exe -ldflags "-w -s -X main.version=`./build/go-semantic-release-temp next`" ./cmd/go-semantic-release/
- name: Build Docker image for master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
if: github.ref == 'refs/heads/master'
run: |
docker build -t nightapes/go-semantic-release:latest .
docker build -t nightapes/go-semantic-release:"$(./build/go-semantic-release next)" .
- name: Push Docker image for master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
if: github.ref == 'refs/heads/master'
run: |
docker login -u nightapes -p ${{ secrets.DOCKER_PASSWORD }}
docker push nightapes/go-semantic-release:latest
docker push nightapes/go-semantic-release:"$(./build/go-semantic-release next)"
- name: Build Docker image
if: github.ref != 'refs/heads/master'
run: |
docker build -t nightapes/go-semantic-release:development .
- name: Push Docker image
if: github.ref != 'refs/heads/master'
run: |
docker login -u nightapes -p ${{ secrets.DOCKER_PASSWORD }}
docker push nightapes/go-semantic-release:development
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: ./build/go-semantic-release-temp release --loglevel trace

2
.gitignore vendored
View File

@@ -16,3 +16,5 @@ go-semantic-release
.vscode/settings.json
CHANGELOG.md
cover.html
build/
.idea/

View File

@@ -1,21 +1,16 @@
commitFormat: angular
title: "go-semantic-release release"
branch:
master: beta
rc: rc
beta: beta
alpha: alpha
changelog:
printAll: false
template: ''
templatePath: ''
release: 'github'
github:
repo: "go-semantic-release"
user: "nightapes"
commitFormat: angular
branch:
master: release
assets:
- name: ./build/go-semantic-release
compress: false
- name: ./build/go-semantic-release.exe
compress: false
github:
repo: "go-semantic-release"
user: "nightapes"
customUrl: ""
changelog:
docker:
latest: true
repository: "nightapes/go-semantic-release"

9
Dockerfile Normal file
View File

@@ -0,0 +1,9 @@
FROM alpine:3.10.2
WORKDIR /code
COPY ./build/go-semantic-release .
USER 1000
ENTRYPOINT [ "./go-semantic-release" ]

196
README.md
View File

@@ -2,24 +2,194 @@
## Release Types
| Type | Git tag | Changelog | Release | Write access git | Api token |
|--- |:---: |:---: |:---: |:---: |:---: |
| `git` | :white_check_mark: | | | :white_check_mark:| |
| `github` | :white_check_mark: | :white_check_mark: | :white_check_mark:| | :white_check_mark: |
| `gitlab` | :white_check_mark: | :white_check_mark: | :white_check_mark:| | :white_check_mark: |
| Type | Implemendet | Git tag | Changelog | Release | Write access git | Api token |
| ---------- | :----------------: | :----------------: | :----------------: | :----------------: | :----------------: | :----------------: |
| `github` | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | | :white_check_mark: |
| `gitlab` | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | | :white_check_mark: |
| `git` | Comming soon | :white_check_mark: | | | :white_check_mark: | |
| `bitbuckt` | Comming soon | :white_check_mark: | | | :white_check_mark: | |
## Supported CI Pipelines
* Github Actions
* Gitlab CI
* Travis CI
* Custom CI, set enviroment `CI=true`
## How to use
`go-semantic-release` config file
Create a file with the name `.release.yml` or anything else, but you need to set to every command `-c <your config file>`
### Example config
```yml
commitFormat: angular
branch:
master: release
release: 'github'
github:
repo: "go-semantic-release"
user: "nightapes"
assets:
- name: ./build/go-semantic-release
compress: false
- name: ./build/go-semantic-release.exe
compress: false
```
#### CommitFormat
Set the commit format, at the moment we support ony [angular](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#commit-message-format), more coming soon.
```yml
commitFormat: angular
```
#### Branch
You can define which kind of release should be created for different branches.
Supported release kinds:
* `release` -> `v1.0.0`
* `rc` -> `v1.0.0-rc.0`
* `beta` -> `v1.0.0-beta.0`
* `alpha` -> `v1.0.0-alpha.0`
Add a branch config to your config
```yml
branch:
<branch-name>: <kind>
```
#### Relase
At the moment we support releases to gitlab and github.
##### Github
You need to set the env `GITHUB_TOKEN` with an access token.
```yml
release: 'github'
github:
user: "<user/group"
repo: "<repositroyname>"
## Optional, if your not using github.com
customUrl: <https://your.github>
```
##### Gitlab
You need to set the env `GITLAB_ACCESS_TOKEN` with an personal access token.
```yml
release: 'gitlab'
gitlab:
repo: "<repositroyname>" ## Example group/project
## Optional, if your not using gitlab.com
customUrl: <https://your.gitlab>
```
#### Assets
You can upload assets to a release
Support for gitlab and github.
If you want, you can let the file be compressed before uploading
```yml
assets:
- name: ./build/go-semantic-release
compress: false
```
#### Changelog
Following variables can be used for templates:
* `Commits` string
* `Version` string
* `Now` time.Time
* `Backtick` string
* `HasDocker` bool
* `HasDockerLatest` bool
* `DockerRepository` string
```yml
changelog:
printAll: false ## Print all valid commits to changelog
title: "v{{.Version}} ({{.Now.Format "2006-01-02"}})" ## Used for releases (go template)
templatePath: "./examples/changelog.tmpl" ## Path to a template file (go template)
```
##### Docker
You can print a help text for a docker image
```yml
changelog:
docker:
latest: false ## If you uploaded a latest image
repository: ## Your docker repository, which is used for docker run
```
### Version
`go-semantic-release` has two modes for calcualting the version: automatic or manual.
#### Automatic
Version will be calculated on the `next` or `release` command
#### Manual
If you don't want that `go-semantic-release` is calculating the version from the commits, you can set the version by hand with
following command:
```bash
./go-semantic-release set 1.1.1
```
### Print version
Print the next version, can be used to add version to your program
```bash
./go-semantic-release next
```
Example with go-lang
```bash
go build -ldflags "--X main.version=`./go-semantic-release next`"
```
### Create release
```bash
./go-semantic-release release
```
## Build
## Build from source
`go build ./cmd/go-semantic-release/`
```bash
go build ./cmd/go-semantic-release/
```
## Run
### Testing
Print the next version
```bash
go test ./...
```
`./go-semantic-release version next`
### Linting
Set a version
`./go-semantic-release version set v1.1.1`
```
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.16.0
golangci-lint run ./...
```

View File

@@ -1,2 +0,0 @@
go build ./cmd/main.go && ./main.exe version next --path /f/Repro/ambassador/
go build ./cmd/main.go && ./main.exe --loglevel debug version set v1.1.1 --path /f/Repro/ambassador/

3
_config.yml Normal file
View File

@@ -0,0 +1,3 @@
theme: jekyll-theme-cayman
plugins:
- jemoji

View File

@@ -11,7 +11,7 @@ func init() {
var zipCmd = &cobra.Command{
Use: "zip",
Short: "Zip configured artifact from release config",
Short: "Zip configured artifact from release config (internal)",
RunE: func(cmd *cobra.Command, args []string) error {
config, err := cmd.Flags().GetString("config")
if err != nil {

16
examples/changelog.tmpl Normal file
View File

@@ -0,0 +1,16 @@
# My custom release template v{{$.Version}} ({{.Now.Format "2006-01-02"}})
{{ .Commits -}}
{{ if .HasDocker}}
## Docker image
New docker image is released under {{$.Backtick}}{{.DockerRepository}}:{{.Version}}{{$.Backtick}}
### Usage
{{$.Backtick}}docker run {{.DockerRepository}}:{{.Version}}{{$.Backtick}}
{{ if .HasDockerLatest}}
or
{{$.Backtick}}docker run {{.DockerRepository}}:latest{{$.Backtick}}
{{ end -}}
{{ end -}}

3
go.mod
View File

@@ -1,6 +1,6 @@
module github.com/Nightapes/go-semantic-release
go 1.12
go 1.13
require (
github.com/Masterminds/semver v1.4.2
@@ -8,6 +8,7 @@ require (
github.com/google/go-cmp v0.3.0 // indirect
github.com/google/go-github/v25 v25.1.3
github.com/kevinburke/ssh_config v0.0.0-20190630040420-2e50c441276c // indirect
github.com/pkg/errors v0.8.1
github.com/sirupsen/logrus v1.4.2
github.com/spf13/cobra v0.0.5
github.com/stretchr/testify v1.3.0

View File

@@ -22,7 +22,7 @@ const ANGULAR = "angular"
func newAngular() *angular {
return &angular{
regex: `(TAG)(?:\((.*)\))?: (.*)`,
regex: `^(TAG)(?:\((.*)\))?: (.*)`,
log: log.WithField("analyzer", ANGULAR),
rules: []Rule{
{

View File

@@ -107,6 +107,11 @@ func TestAngular(t *testing.T) {
Author: "me",
Hash: "12345667",
},
shared.Commit{
Message: "Merge feat(internal/changelog): my first commit",
Author: "me",
Hash: "12345667",
},
},
},
{

View File

@@ -3,13 +3,14 @@ package cache_test
import (
"testing"
"io/ioutil"
"os"
"path"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/cache"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path"
)
func TestReadCacheNotFound(t *testing.T) {
@@ -54,7 +55,6 @@ func TestWriteAndReadCache(t *testing.T) {
VersionString: "1.1.0",
},
Branch: "master",
Draft: true,
Commits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
@@ -97,7 +97,6 @@ func TestWriteNotFound(t *testing.T) {
Version: createVersion("1.1.0"),
},
Branch: "master",
Draft: true,
})
assert.Errorf(t, err, "Write non exsiting file")

View File

@@ -40,29 +40,29 @@ func (c *Calculator) IncPrerelease(preReleaseType string, version *semver.Versio
}
//CalculateNewVersion from given commits and lastversion
func (c *Calculator) CalculateNewVersion(commits map[shared.Release][]shared.AnalyzedCommit, lastVersion *semver.Version, releaseType string, firstRelease bool) (semver.Version, bool) {
func (c *Calculator) CalculateNewVersion(commits map[shared.Release][]shared.AnalyzedCommit, lastVersion *semver.Version, releaseType string, firstRelease bool) semver.Version {
switch releaseType {
case "beta", "alpha":
case "beta", "alpha", "rc":
if len(commits["major"]) > 0 || len(commits["minor"]) > 0 || len(commits["patch"]) > 0 {
version, _ := c.IncPrerelease(releaseType, lastVersion)
return version, true
}
case "rc":
if len(commits["major"]) > 0 || len(commits["minor"]) > 0 || len(commits["patch"]) > 0 {
version, _ := c.IncPrerelease(releaseType, lastVersion)
return version, false
return version
}
case "release":
if !firstRelease {
if lastVersion.Prerelease() != "" {
newVersion, _ := lastVersion.SetPrerelease("")
return newVersion
}
if len(commits["major"]) > 0 {
return lastVersion.IncMajor(), false
return lastVersion.IncMajor()
} else if len(commits["minor"]) > 0 {
return lastVersion.IncMinor(), false
return lastVersion.IncMinor()
} else if len(commits["patch"]) > 0 {
return lastVersion.IncPatch(), false
return lastVersion.IncPatch()
}
}
}
return *lastVersion, false
return *lastVersion
}

View File

@@ -72,7 +72,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
releaseType string
lastVersion *semver.Version
nextVersion string
isDraft bool
isFirst bool
analyzedCommits map[shared.Release][]shared.AnalyzedCommit
}{
@@ -90,7 +89,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: true,
},
{
testCase: "version with preRelease beta",
@@ -106,7 +104,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: true,
},
{
testCase: "version without commits",
@@ -120,7 +117,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and first release",
@@ -134,7 +130,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: true,
isDraft: false,
},
{
testCase: "version with commits and rc release",
@@ -148,7 +143,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and rc release",
@@ -162,7 +156,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and major release",
@@ -176,7 +169,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and minor release",
@@ -190,7 +182,6 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and minor patch",
@@ -204,15 +195,13 @@ func TestCalculator_CalculateNewVersion(t *testing.T) {
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
}
c := calculator.New()
for _, test := range testConfigs {
next, draft := c.CalculateNewVersion(test.analyzedCommits, test.lastVersion, test.releaseType, test.isFirst)
assert.Equalf(t, test.isDraft, draft, "Should have draft %t for testcase %s", test.isDraft, test.testCase)
next := c.CalculateNewVersion(test.analyzedCommits, test.lastVersion, test.releaseType, test.isFirst)
assert.Equalf(t, test.nextVersion, next.String(), "Should have version %s for testcase %s", test.nextVersion, test.testCase)
}

View File

@@ -2,6 +2,7 @@ package changelog
import (
"bytes"
"io/ioutil"
"strings"
"text/template"
"time"
@@ -13,9 +14,7 @@ import (
log "github.com/sirupsen/logrus"
)
const defaultChangelogTitle string = `v{{.Version}} ({{.Now.Format "2006-01-02"}})`
const defaultChangelog string = `# v{{$.Version}} ({{.Now.Format "2006-01-02"}})
{{ range $index,$commit := .BreakingChanges -}}
const defaultCommitList string = `{{ range $index,$commit := .BreakingChanges -}}
{{ if eq $index 0 }}
## BREAKING CHANGES
{{ end}}
@@ -30,10 +29,37 @@ introduced by commit:
* **{{$.Backtick}}{{$commit.Scope}}{{$.Backtick}}** {{$commit.ParsedMessage}} {{if $.HasURL}} ([{{ printf "%.7s" $commit.Commit.Hash}}]({{ replace $.URL "{{hash}}" $commit.Commit.Hash}})) {{end}}
{{ end -}}
{{ end -}}
{{ end -}}`
const defaultChangelogTitle string = `v{{.Version}} ({{.Now.Format "2006-01-02"}})`
const defaultChangelog string = `# v{{$.Version}} ({{.Now.Format "2006-01-02"}})
{{ .Commits -}}
{{ if .HasDocker}}
## Docker image
New docker image is released under {{$.Backtick}}{{.DockerRepository}}:{{.Version}}{{$.Backtick}}
### Usage
{{$.Backtick}}docker run {{.DockerRepository}}:{{.Version}}{{$.Backtick}}
{{ if .HasDockerLatest}}
or
{{$.Backtick}}docker run {{.DockerRepository}}:latest{{$.Backtick}}
{{ end -}}
{{ end -}}
`
type changelogContent struct {
Commits string
Version string
Now time.Time
Backtick string
HasDocker bool
HasDockerLatest bool
DockerRepository string
}
type commitsContent struct {
Commits map[string][]shared.AnalyzedCommit
BreakingChanges []shared.AnalyzedCommit
Order []string
@@ -91,7 +117,7 @@ func (c *Changelog) GenerateChanglog(templateConfig shared.ChangelogTemplateConf
}
}
changelogContent := changelogContent{
commitsContent := commitsContent{
Version: templateConfig.Version,
Commits: commitsPerScope,
Now: c.releaseTime,
@@ -102,16 +128,50 @@ func (c *Changelog) GenerateChanglog(templateConfig shared.ChangelogTemplateConf
URL: templateConfig.CommitURL,
}
title, err := generateTemplate(defaultChangelogTitle, changelogContent)
changelogContent := changelogContent{
Version: templateConfig.Version,
Now: c.releaseTime,
Backtick: "`",
HasDocker: c.config.Changelog.Docker.Repository != "",
HasDockerLatest: c.config.Changelog.Docker.Latest,
DockerRepository: c.config.Changelog.Docker.Repository,
}
template := defaultChangelog
if c.config.Changelog.TemplatePath != "" {
content, err := ioutil.ReadFile(c.config.Changelog.TemplatePath)
if err != nil {
return nil, err
}
content, err := generateTemplate(defaultChangelog, changelogContent)
return &shared.GeneratedChangelog{Title: title, Content: content}, err
template = string(content)
}
func generateTemplate(text string, values changelogContent) (string, error) {
templateTitle := defaultChangelogTitle
if c.config.Changelog.TemplateTitle != "" {
templateTitle = c.config.Changelog.TemplateTitle
}
log.Debugf("Render title")
renderedTitle, err := generateTemplate(templateTitle, changelogContent)
if err != nil {
return nil, err
}
log.Debugf("Render commits")
renderedCommitList, err := generateTemplate(defaultCommitList, commitsContent)
if err != nil {
return nil, err
}
log.Tracef("Commits %s", renderedCommitList)
changelogContent.Commits = renderedCommitList
log.Debugf("Render changelog")
renderedContent, err := generateTemplate(template, changelogContent)
return &shared.GeneratedChangelog{Title: renderedTitle, Content: renderedContent}, err
}
func generateTemplate(text string, values interface{}) (string, error) {
funcMap := template.FuncMap{
"replace": replace,

View File

@@ -3,10 +3,11 @@ package ci
import (
"fmt"
"github.com/Nightapes/go-semantic-release/internal/gitutil"
log "github.com/sirupsen/logrus"
"os"
"strings"
"github.com/Nightapes/go-semantic-release/internal/gitutil"
log "github.com/sirupsen/logrus"
)
//ProviderConfig struct
@@ -42,6 +43,8 @@ func GetCIProvider(gitUtil *gitutil.GitUtil, envs map[string]string) (*ProviderC
services := []Service{
Travis{},
GithubActions{},
GitlabCI{},
Git{gitUtil: gitUtil}, // GIt must be the last option to check
}
@@ -49,6 +52,7 @@ func GetCIProvider(gitUtil *gitutil.GitUtil, envs map[string]string) (*ProviderC
config, err := service.detect(envs)
if err == nil {
log.Infof("Found CI: %s", config.Name)
log.Tracef("Found CI config: %+v", config)
return config, nil
}
log.Debugf("%s", err.Error())

View File

@@ -89,6 +89,41 @@ func TestCi(t *testing.T) {
result: &ci.ProviderConfig{IsPR: false, PR: "", PRBranch: "", Branch: "master", Tag: "TAG", Commit: "190bfd6aa60022afd0ef830342cfb07e33c45f37", BuildURL: "https://travis-ci.com/owner/repo/builds/1234", Service: "travis", Name: "Travis CI"},
hasError: false,
},
{
service: "Github Actions PR",
envs: map[string]string{
"GITHUB_EVENT_NAME": "pull_request",
"GITHUB_SHA": "190bfd6aa60022afd0ef830342cfb07e33c45f37",
"GITHUB_REF": "master",
"GITHUB_ACTION": "action",
},
result: &ci.ProviderConfig{IsPR: true, PR: "", PRBranch: "", Branch: "master", Tag: "", Commit: "190bfd6aa60022afd0ef830342cfb07e33c45f37", BuildURL: "", Service: "GithubActions", Name: "GithubActions CI"},
hasError: false,
},
{
service: "Github Actions Push",
envs: map[string]string{
"GITHUB_EVENT_NAME": "push",
"GITHUB_SHA": "190bfd6aa60022afd0ef830342cfb07e33c45f37",
"GITHUB_REF": "refs/heads/feature-branch-1",
"GITHUB_ACTION": "action",
},
result: &ci.ProviderConfig{IsPR: false, PR: "", PRBranch: "", Branch: "feature-branch-1", Tag: "", Commit: "190bfd6aa60022afd0ef830342cfb07e33c45f37", BuildURL: "", Service: "GithubActions", Name: "GithubActions CI"},
hasError: false,
},
{
service: "GitLab CI/CD PR",
envs: map[string]string{
"GITLAB_CI": "true",
"CI_COMMIT_SHA": "190bfd6aa60022afd0ef830342cfb07e33c45f37",
"CI_COMMIT_REF_NAME": "master",
"CI_COMMIT_TAG": "tag",
"CI_PROJECT_URL": "https://my.gitlab.com",
"CI_PIPELINE_ID": "1",
},
result: &ci.ProviderConfig{IsPR: false, PR: "", PRBranch: "", Branch: "master", Tag: "tag", Commit: "190bfd6aa60022afd0ef830342cfb07e33c45f37", BuildURL: "https://my.gitlab.com/pipelines/1", Service: "gitlab", Name: "GitLab CI/CD"},
hasError: false,
},
}
for _, config := range testConfigs {

View File

@@ -0,0 +1,43 @@
package ci
import (
"fmt"
"strings"
log "github.com/sirupsen/logrus"
)
//GithubActions struct
type GithubActions struct{}
//Detect if on GithubActions
func (t GithubActions) detect(envs map[string]string) (*ProviderConfig, error) {
if _, exists := envs["GITHUB_ACTION"]; !exists {
return nil, fmt.Errorf("not running on Github Actions")
}
isPR := false
value := envs["GITHUB_EVENT_NAME"]
if value == "pull_request" {
isPR = true
} else {
log.Debugf("GITHUB_EVENT_NAME=%s, not running on pr", value)
}
branch := envs["GITHUB_REF"]
if strings.HasPrefix(envs["GITHUB_REF"], "refs/heads/") {
branch = strings.Replace(branch, "refs/heads/", "", 1)
}
return &ProviderConfig{
Service: "GithubActions",
Name: "GithubActions CI",
Commit: envs["GITHUB_SHA"],
Branch: branch,
IsPR: isPR,
}, nil
}

26
internal/ci/gitlab_ci.go Normal file
View File

@@ -0,0 +1,26 @@
package ci
import (
"fmt"
)
//GitlabCI struct
type GitlabCI struct{}
//Detect if on GitlabCI
func (t GitlabCI) detect(envs map[string]string) (*ProviderConfig, error) {
if _, exists := envs["GITLAB_CI"]; !exists {
return nil, fmt.Errorf("not running on gitlab")
}
return &ProviderConfig{
Service: "gitlab",
Name: "GitLab CI/CD",
Commit: envs["CI_COMMIT_SHA"],
Tag: envs["CI_COMMIT_TAG"],
BuildURL: envs["CI_PROJECT_URL"] + "/pipelines/" + envs["CI_PIPELINE_ID"],
Branch: envs["CI_COMMIT_REF_NAME"],
IsPR: false,
}, nil
}

View File

@@ -5,12 +5,15 @@ import (
"fmt"
"sort"
"github.com/pkg/errors"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/shared"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"github.com/Nightapes/go-semantic-release/internal/shared"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
)
// GitUtil struct
@@ -87,7 +90,7 @@ func (g *GitUtil) GetLastVersion() (*semver.Version, string, error) {
err = gitTags.ForEach(func(p *plumbing.Reference) error {
v, err := semver.NewVersion(p.Name().Short())
log.Tracef("%+v with hash: %s", p.Target(), p.Hash())
log.Tracef("Tag %+v with hash: %s", p.Target(), p.Hash())
if err == nil {
tags = append(tags, v)
@@ -139,7 +142,7 @@ func (g *GitUtil) GetCommits(lastTagHash string) ([]shared.Commit, error) {
if c.Hash.String() == lastTagHash {
log.Debugf("Found commit with hash %s, will stop here", c.Hash.String())
foundEnd = true
return storer.ErrStop
}
if !foundEnd {
log.Tracef("Found commit with hash %s", c.Hash.String())
@@ -153,5 +156,9 @@ func (g *GitUtil) GetCommits(lastTagHash string) ([]shared.Commit, error) {
return nil
})
return commits, err
if err != nil {
return commits, errors.Wrap(err, "Could not read commits, check git clone depth in your ci")
}
return commits, nil
}

View File

@@ -32,7 +32,7 @@ type Client struct {
func New(c *config.GitHubProvider) (*Client, error) {
var err error
if c.AccessToken, err = util.GetAccessToken(GITHUB); err != nil {
if c.AccessToken, err = util.GetAccessToken("GITHUB_TOKEN"); err != nil {
return &Client{}, err
}
ctx := context.Background()
@@ -96,7 +96,6 @@ func (g *Client) CreateRelease(releaseVersion *shared.ReleaseVersion, generatedC
TargetCommitish: &releaseVersion.Branch,
Name: &generatedChangelog.Title,
Body: &generatedChangelog.Content,
Draft: &releaseVersion.Draft,
Prerelease: &prerelease,
})
if err != nil {

View File

@@ -90,7 +90,6 @@ var testReleases = []testReleaseStruct{
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
@@ -115,7 +114,6 @@ var testReleases = []testReleaseStruct{
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
@@ -145,19 +143,19 @@ func initHTTPServer(respCode int, body string) *httptest.Server {
func TestNew(t *testing.T) {
for _, testOject := range testNewClient {
if testOject.valid {
os.Setenv("GITHUB_ACCESS_TOKEN", "XXX")
os.Setenv("GITHUB_TOKEN", "XXX")
}
_, err := github.New(&testOject.config)
assert.Equal(t, testOject.valid, err == nil)
os.Unsetenv("GITHUB_ACCESS_TOKEN")
os.Unsetenv("GITHUB_TOKEN")
}
}
func TestGetCommitURL(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
os.Setenv("GITHUB_TOKEN", "XX")
for _, testOject := range testNewClient {
client, _ := github.New(&testOject.config)
actualURL := client.GetCommitURL()
@@ -170,12 +168,12 @@ func TestGetCommitURL(t *testing.T) {
assert.EqualValues(t, expectedURL, actualURL)
}
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
os.Unsetenv("GITHUB_TOKEN")
}
func TestGetCompareURL(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
os.Setenv("GITHUB_TOKEN", "XX")
for _, testOject := range testNewClient {
client, _ := github.New(&testOject.config)
actualURL := client.GetCompareURL("1", "2")
@@ -188,12 +186,12 @@ func TestGetCompareURL(t *testing.T) {
assert.EqualValues(t, expectedURL, actualURL)
}
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
os.Unsetenv("GITHUB_TOKEN")
}
func TestValidateConfig(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
os.Setenv("GITHUB_TOKEN", "XX")
for _, testOject := range testHelperMethod {
client, _ := github.New(&testOject.config)
err := client.ValidateConfig()
@@ -201,11 +199,11 @@ func TestValidateConfig(t *testing.T) {
assert.Equal(t, testOject.valid, err == nil)
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
os.Unsetenv("GITHUB_TOKEN")
}
func TestCreateRelease(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
os.Setenv("GITHUB_TOKEN", "XX")
for _, testObejct := range testReleases {
if testObejct.valid {
@@ -232,6 +230,6 @@ func TestCreateRelease(t *testing.T) {
assert.Error(t, err)
}
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
os.Unsetenv("GITHUB_TOKEN")
}

View File

@@ -2,7 +2,6 @@ package gitlab
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
@@ -26,7 +25,6 @@ const GITLAB = "gitlab"
// Client type struct
type Client struct {
config *config.GitLabProvider
context context.Context
client *http.Client
baseURL string
apiURL string
@@ -36,12 +34,17 @@ type Client struct {
}
// New initialize a new gitlabRelease
func New(config *config.GitLabProvider, accessToken string) (*Client, error) {
ctx := context.Background()
func New(config *config.GitLabProvider) (*Client, error) {
accessToken, err := util.GetAccessToken(fmt.Sprintf("%s_ACCESS_TOKEN", strings.ToUpper(GITLAB)))
if err != nil {
return nil, err
}
tokenHeader := util.NewAddHeaderTransport(nil, "PRIVATE-TOKEN", accessToken)
acceptHeader := util.NewAddHeaderTransport(tokenHeader, "Accept", "application/json")
contentHeader := util.NewAddHeaderTransport(acceptHeader, "Content-Type", "application/json")
httpClient := &http.Client{
Transport: acceptHeader,
Transport: contentHeader,
Timeout: time.Second * 60,
}
@@ -65,7 +68,6 @@ func New(config *config.GitLabProvider, accessToken string) (*Client, error) {
return &Client{
token: accessToken,
config: config,
context: ctx,
baseURL: config.CustomURL,
apiURL: config.CustomURL + "/api/v4",
client: httpClient,
@@ -108,6 +110,8 @@ func (g *Client) CreateRelease(releaseVersion *shared.ReleaseVersion, generatedC
return err
}
g.log.Tracef("Send release config %s", bodyBytes)
req, err := http.NewRequest("POST", url, bytes.NewReader(bodyBytes))
if err != nil {
return fmt.Errorf("could not create request: %s", err.Error())
@@ -123,7 +127,7 @@ func (g *Client) CreateRelease(releaseVersion *shared.ReleaseVersion, generatedC
return err
}
g.log.Infof("Crated release")
g.log.Infof("Created release")
return nil
}

View File

@@ -13,54 +13,61 @@ import (
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
//"github.com/Nightapes/go-semantic-release/internal/releaser/util"
"github.com/Nightapes/go-semantic-release/internal/releaser/gitlab"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/Nightapes/go-semantic-release/pkg/config"
)
func TestGetCommitURL(t *testing.T) {
os.Setenv("GITLAB_ACCESS_TOKEN", "XXX")
defer os.Unsetenv("GITLAB_ACCESS_TOKEN")
client, err := gitlab.New(&config.GitLabProvider{
CustomURL: "https://localhost/",
Repo: "test/test",
}, "aToken")
})
assert.NoError(t, err)
assert.Equal(t, "https://localhost/test/test/commit/{{hash}}", client.GetCommitURL())
}
func TestGetCompareURL(t *testing.T) {
os.Setenv("GITLAB_ACCESS_TOKEN", "XXX")
defer os.Unsetenv("GITLAB_ACCESS_TOKEN")
client, err := gitlab.New(&config.GitLabProvider{
CustomURL: "https://localhost/",
Repo: "test/test",
}, "aToken")
})
assert.NoError(t, err)
assert.Equal(t, "https://localhost/test/test/compare/1.0.0...1.0.1", client.GetCompareURL("1.0.0", "1.0.1"))
}
func TestValidateConfig_EmptyRepro(t *testing.T) {
os.Setenv("GITLAB_ACCESS_TOKEN", "XXX")
defer os.Unsetenv("GITLAB_ACCESS_TOKEN")
_, err := gitlab.New(&config.GitLabProvider{
CustomURL: "https://localhost/",
}, "aToken")
})
assert.Error(t, err)
}
func TestValidateConfig_DefaultURL(t *testing.T) {
os.Setenv("GITLAB_ACCESS_TOKEN", "XXX")
defer os.Unsetenv("GITLAB_ACCESS_TOKEN")
config := &config.GitLabProvider{
Repo: "localhost/test",
}
_, err := gitlab.New(config, "aToken")
_, err := gitlab.New(config)
assert.NoError(t, err)
assert.Equal(t, "https://gitlab.com", config.CustomURL)
}
func TestValidateConfig_CustomURL(t *testing.T) {
os.Setenv("GITLAB_ACCESS_TOKEN", "XXX")
defer os.Unsetenv("GITLAB_ACCESS_TOKEN")
config := &config.GitLabProvider{
Repo: "/localhost/test/",
CustomURL: "https://localhost/",
}
_, err := gitlab.New(config, "aToken")
_, err := gitlab.New(config)
assert.NoError(t, err)
assert.Equal(t, "https://localhost", config.CustomURL)
assert.Equal(t, "localhost/test", config.Repo)
@@ -94,7 +101,6 @@ func TestCreateRelease(t *testing.T) {
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
@@ -102,7 +108,7 @@ func TestCreateRelease(t *testing.T) {
},
responseBody: "{}",
responseCode: 200,
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content","assets":{"links":null}}`,
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content"}`,
valid: true,
},
{
@@ -119,7 +125,6 @@ func TestCreateRelease(t *testing.T) {
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
@@ -127,7 +132,7 @@ func TestCreateRelease(t *testing.T) {
},
responseBody: "{}",
responseCode: 500,
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content","assets":{"links":null}}`,
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content"}`,
valid: false,
},
{
@@ -145,7 +150,6 @@ func TestCreateRelease(t *testing.T) {
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
@@ -153,7 +157,7 @@ func TestCreateRelease(t *testing.T) {
},
responseCode: 400,
responseBody: "{}",
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content","assets":{"links":null}}`,
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content"}`,
valid: false,
},
}
@@ -184,8 +188,9 @@ func TestCreateRelease(t *testing.T) {
if testObject.config.CustomURL == "" {
testObject.config.CustomURL = testServer.URL
}
client, err := gitlab.New(&testObject.config, "aToken")
os.Setenv("GITLAB_ACCESS_TOKEN", "aToken")
defer os.Unsetenv("GITLAB_ACCESS_TOKEN")
client, err := gitlab.New(&testObject.config)
assert.NoError(t, err)
err = client.CreateRelease(testObject.releaseVersion, testObject.generatedChangelog)
@@ -310,8 +315,9 @@ func TestUploadAssets(t *testing.T) {
if testObject.config.CustomURL == "" {
testObject.config.CustomURL = testServer.URL
}
client, err := gitlab.New(&testObject.config, "aToken")
os.Setenv("GITLAB_ACCESS_TOKEN", "aToken")
defer os.Unsetenv("GITLAB_ACCESS_TOKEN")
client, err := gitlab.New(&testObject.config)
assert.NoError(t, err)
client.Release = "1.0.0"

View File

@@ -6,9 +6,6 @@ type Release struct {
Name string `json:"name"`
Ref string `json:"ref"`
Description string `json:"description,omitempty"`
Assets struct {
Links []*ReleaseLink `json:"links"`
} `json:"assets"`
}
// ReleaseLink struct

View File

@@ -5,7 +5,6 @@ import (
"github.com/Nightapes/go-semantic-release/internal/releaser/github"
"github.com/Nightapes/go-semantic-release/internal/releaser/gitlab"
"github.com/Nightapes/go-semantic-release/internal/releaser/util"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/Nightapes/go-semantic-release/pkg/config"
@@ -41,11 +40,7 @@ func (r *Releasers) GetReleaser() (Releaser, error) {
return github.New(&r.config.GitHubProvider)
case gitlab.GITLAB:
log.Debugf("initialize new %s-provider", gitlab.GITLAB)
accessToken, err := util.GetAccessToken(gitlab.GITLAB)
if err != nil {
return nil, err
}
return gitlab.New(&r.config.GitLabProvider, accessToken)
return gitlab.New(&r.config.GitLabProvider)
}
return nil, fmt.Errorf("could not initialize a releaser from this type: %s", r.config.Release)
}

View File

@@ -49,11 +49,9 @@ func NewAddHeaderTransport(T http.RoundTripper, key, value string) *AddHeaderTra
}
// GetAccessToken lookup for the providers accesstoken
func GetAccessToken(providerName string) (string, error) {
func GetAccessToken(envName string) (string, error) {
var token string
var exists bool
envName := fmt.Sprintf("%s_ACCESS_TOKEN", strings.ToUpper(providerName))
log.Debugf("check if %s environment variable is set", envName)
if token, exists = os.LookupEnv(envName); !exists {

View File

@@ -43,7 +43,7 @@ func TestGetAccessToken(t *testing.T) {
fmt.Println(err.Error())
}
_, err := util.GetAccessToken(testObject.providerName)
_, err := util.GetAccessToken(envName)
assert.Equal(t, testObject.valid, err == nil)
os.Unsetenv(envName)
@@ -193,7 +193,7 @@ func TestDoAndRoundTrip(t *testing.T) {
hasError: true,
responseBody: &example{},
responseBodyType: &example{},
path: "broken",
path: "4/broken",
},
}
@@ -214,6 +214,8 @@ func TestDoAndRoundTrip(t *testing.T) {
}))
defer testServer.Close()
req, err := http.NewRequest("POST", testServer.URL+testOject.path, nil)
assert.NoError(t, err)
@@ -225,6 +227,5 @@ func TestDoAndRoundTrip(t *testing.T) {
assert.Equal(t, testOject.statusCode, resp.StatusCode)
assert.Equal(t, testOject.responseBody, testOject.responseBodyType)
}
testServer.Close()
}
}

View File

@@ -9,7 +9,6 @@ type ReleaseVersion struct {
Last ReleaseVersionEntry `yaml:"last"`
Next ReleaseVersionEntry `yaml:"next"`
Branch string `yaml:"branch"`
Draft bool `yaml:"draft"`
Commits map[Release][]AnalyzedCommit `yaml:"commits"`
}

View File

@@ -11,8 +11,22 @@ import (
// ChangelogConfig struct
type ChangelogConfig struct {
PrintAll bool `yaml:"printAll,omitempty"`
Template string `yaml:"template,omitempty"`
TemplateTitle string `yaml:"title,omitempty"`
TemplatePath string `yaml:"templatePath,omitempty"`
Docker ChangelogDocker `yaml:"docker,omitempty"`
NPM ChangelogNPM `yaml:"npm,omitempty"`
}
//ChangelogDocker type struct
type ChangelogDocker struct {
Latest bool `yaml:"latest"`
Repository string `yaml:"repository"`
}
//ChangelogNPM type struct
type ChangelogNPM struct {
YARN bool `yaml:"latest"`
Repository string `yaml:"repository"`
}
//Asset type struct
@@ -46,7 +60,7 @@ type ReleaseConfig struct {
GitLabProvider GitLabProvider `yaml:"gitlab,omitempty"`
Assets []Asset `yaml:"assets"`
ReleaseTitle string `yaml:"title"`
IsPreRelease, IsDraft bool
IsPreRelease bool
}
// Read ReleaseConfig

View File

@@ -3,11 +3,12 @@ package config_test
import (
"testing"
"github.com/Nightapes/go-semantic-release/pkg/config"
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path"
"github.com/Nightapes/go-semantic-release/pkg/config"
"github.com/stretchr/testify/assert"
)
func TestReadCacheNotFound(t *testing.T) {
@@ -74,7 +75,7 @@ github:
Branch: map[string]string{"add_git_releases": "alpha", "alpha": "alpha", "beta": "beta", "master": "release", "rc": "rc"},
Changelog: config.ChangelogConfig{
PrintAll: false,
Template: "",
TemplateTitle: "",
TemplatePath: ""},
Release: "github",
GitHubProvider: config.GitHubProvider{
@@ -88,25 +89,6 @@ github:
Compress: false}},
ReleaseTitle: "go-semantic-release release",
IsPreRelease: false,
IsDraft: false,
}, result)
}
// func TestWriteNotFound(t *testing.T) {
// err := cache.Write("notfound/dir", shared.ReleaseVersion{
// Last: shared.ReleaseVersionEntry{
// Commit: "12345",
// Version: createVersion("1.0.0"),
// },
// Next: shared.ReleaseVersionEntry{
// Commit: "12346",
// Version: createVersion("1.1.0"),
// },
// Branch: "master",
// Draft: true,
// })
// assert.Errorf(t, err, "Write non exsiting file")
// }

View File

@@ -2,7 +2,6 @@ package semanticrelease
import (
"io/ioutil"
"strings"
"time"
"github.com/Masterminds/semver"
@@ -83,8 +82,8 @@ func (s *SemanticRelease) GetNextVersion(provider *ci.ProviderConfig, force bool
firstRelease := false
if lastVersion == nil {
defaultVersion, _ := semver.NewVersion("1.0.0")
lastVersion = defaultVersion
lastVersion, _ = semver.NewVersion("1.0.0")
log.Infof("This is the first release, will set version to %s", lastVersion.String())
firstRelease = true
}
@@ -97,16 +96,22 @@ func (s *SemanticRelease) GetNextVersion(provider *ci.ProviderConfig, force bool
analyzedCommits := s.analyzer.Analyze(commits)
isDraft := false
var newVersion semver.Version
foundBranchConfig := false
for branch, releaseType := range s.config.Branch {
if provider.Branch == branch || strings.HasPrefix(provider.Branch, branch) {
if provider.Branch == branch {
log.Debugf("Found branch config for branch %s with release type %s", provider.Branch, releaseType)
newVersion, isDraft = s.calculator.CalculateNewVersion(analyzedCommits, lastVersion, releaseType, firstRelease)
newVersion = s.calculator.CalculateNewVersion(analyzedCommits, lastVersion, releaseType, firstRelease)
foundBranchConfig = true
break
}
}
if !foundBranchConfig {
log.Warnf("No branch config found for branch %s, will return last known version", provider.Branch)
newVersion = *lastVersion
}
releaseVersion := shared.ReleaseVersion{
Next: shared.ReleaseVersionEntry{
Commit: provider.Commit,
@@ -117,10 +122,13 @@ func (s *SemanticRelease) GetNextVersion(provider *ci.ProviderConfig, force bool
Version: lastVersion,
},
Branch: provider.Branch,
Draft: isDraft,
Commits: analyzedCommits,
}
if firstRelease {
releaseVersion.Last.Version, _ = semver.NewVersion("0.0.0")
}
log.Infof("New version %s -> %s", lastVersion.String(), newVersion.String())
err = cache.Write(s.repository, releaseVersion)
if err != nil {
@@ -179,12 +187,12 @@ func (s *SemanticRelease) WriteChangeLog(changelogContent, file string) error {
func (s *SemanticRelease) Release(provider *ci.ProviderConfig, force bool) error {
if provider.IsPR {
log.Debugf("Will not perform a new release. This is a pull request")
log.Infof("Will not perform a new release. This is a pull request")
return nil
}
if _, ok := s.config.Branch[provider.Branch]; !ok {
log.Debugf("Will not perform a new release. Current %s branch is not configured in release config", provider.Branch)
log.Infof("Will not perform a new release. Current %s branch is not configured in release config", provider.Branch)
return nil
}