Compare commits

...

34 Commits

Author SHA1 Message Date
Felix Wiedmann
e0a4725f06 Merge pull request #10 from Nightapes/fixes
Fixes
2019-08-11 23:02:12 +02:00
Nightapes
9cf4eab1d2 fix(cmd): don't print current dir in help text 2019-08-11 18:28:13 +02:00
Nightapes
6a514158ce fix(cache): save commits to cache to avoid empty changelog 2019-08-11 18:27:52 +02:00
Felix Wiedmann
f30c508f2a Merge pull request #9 from Nightapes/gitlab
Gitlab
2019-08-11 16:05:17 +02:00
Nightapes
7b16b164f2 test(gitlab): add missing tests 2019-08-11 15:03:55 +02:00
Sebastian
0fd39c72a0 Merge branch 'master' into gitlab 2019-08-08 21:35:39 +02:00
Nightapes
0e61bf7651 Merge branch 'gitlab' of github.com:Nightapes/go-semantic-release into gitlab 2019-08-08 21:33:42 +02:00
Nightapes
829fea1282 build(releaser): fix release config 2019-08-08 21:33:28 +02:00
Nightapes
467ae1f87e build(releaser): fix release config 2019-08-08 21:33:28 +02:00
Nightapes
5791d3b41c refactor(releaser): clean up code 2019-08-08 21:33:28 +02:00
Nightapes
92b42c8ffa feat(releaser): add gitlab as relase option 2019-08-08 21:33:28 +02:00
Nightapes
0bffe32a24 Merge branch 'gitlab' of github.com:Nightapes/go-semantic-release into gitlab 2019-08-08 21:32:42 +02:00
Nightapes
fab3fc030e build(releaser): fix release config 2019-08-08 21:32:29 +02:00
Nightapes
42a6a5fcf0 build(releaser): fix release config 2019-08-08 21:31:30 +02:00
Nightapes
2f20d8c31c refactor(releaser): clean up code 2019-08-08 21:30:29 +02:00
Sebastian
ec10557cb1 Merge pull request #8 from Nightapes/test/github-release
add tests for github releaser - UploadAssets method omitted because of future deprication
2019-08-08 21:12:48 +02:00
fwiedmann
c9d9420037 chore(gitlab/github/util): fix golangci-lint issues 2019-08-08 21:01:40 +02:00
fwiedmann
ff82ec7acd chore(util/github-release): fix golint issues 2019-08-08 20:44:33 +02:00
Nightapes
428514a1ef test(github): merge incoming changes 2019-08-08 20:22:49 +02:00
Nightapes
3bf84d5ad1 test(github): refactor unit test 2019-08-08 20:17:14 +02:00
fwiedmann
0037abfaf7 test(internal/releaser/github): add test for CreateRelease() 2019-08-08 20:07:22 +02:00
Nightapes
703d4b803c Merge branch 'test/github-release' of github.com:Nightapes/go-semantic-release into test/github-release 2019-08-07 23:27:05 +02:00
Nightapes
c086b12f01 feat(releaser): add gitlab as relase option 2019-08-07 23:24:13 +02:00
fwiedmann
3c500142aa temp(releaser/github): modify test 2019-08-07 23:11:04 +02:00
fwiedmann
bdc4fb1d74 tmp(releaser/github): add test for create release 2019-08-06 23:21:25 +02:00
fwiedmann
682fae3239 test(releaser/github): tests for GetCommitURL(), GetCompareURL(), ValisateConfig() 2019-07-29 23:11:07 +02:00
fwiedmann
e170ca9885 test(releaser/github): test New func 2019-07-28 23:00:08 +02:00
Felix Wiedmann
a15eaa597a Merge pull request #7 from Nightapes/add_git_releases
Add git releases
2019-07-28 21:56:06 +02:00
fwiedmann
6bdbc2173f chore(release.yaml): set master branch on beta release 2019-07-28 21:53:30 +02:00
Nightapes
1daff2bc8a refactor(pkg): clean up semantic release interface 2019-07-24 22:14:03 +02:00
Nightapes
e222734a1a test(internal/*): add more unit tests 2019-07-22 20:47:10 +02:00
Nightapes
6267e1cc81 refactor(pkg/semanticrelease): clean up code 2019-07-22 20:46:48 +02:00
fwiedmann
5986e2819a test(internal/releaser/util): add test for PrepareAssets 2019-07-22 18:13:11 +02:00
fwiedmann
581b62d324 ref(internal/releaser/util): check if asset name ist not empty, open file which should be zipped before create zip file 2019-07-22 18:11:48 +02:00
32 changed files with 1778 additions and 350 deletions

View File

@@ -1,11 +1,10 @@
commitFormat: angular
title: "go-semantic-release release"
branch:
master: release
master: beta
rc: rc
beta: beta
alpha: alpha
add_git_releases: alpha
changelog:
printAll: false
template: ''

View File

@@ -29,11 +29,11 @@ script:
- go test -v ./...
- go build -o build/go-semantic-release-temp ./cmd/go-semantic-release/
- echo "Building version `./build/go-semantic-release-temp next --loglevel debug --no-cache`"
- go build -o build/go-semantic-release -ldflags "-X main.version=`./build/go-semantic-release-temp next`" ./cmd/go-semantic-release/
- GOOS=windows GOARCH=386 go build -o build/go-semantic-release.exe -ldflags "-X main.version=`./build/go-semantic-release-temp next`" ./cmd/go-semantic-release/
- 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 go build -o build/go-semantic-release.exe -ldflags "-w -s -X main.version=`./build/go-semantic-release-temp next`" ./cmd/go-semantic-release/
after_success:
- ./build/go-semantic-release-temp release --loglevel debug
- ./build/go-semantic-release-temp release --loglevel trace
branches:
except:

View File

@@ -40,11 +40,17 @@ var changelogCmd = &cobra.Command{
return err
}
releaseVersion, err := s.GetNextVersion(force)
provider, err := s.GetCIProvider()
if err != nil {
return err
}
releaseVersion, err := s.GetNextVersion(provider, force)
if err != nil {
return err
}
log.Debugf("Found %d commits till last release", len(releaseVersion.Commits))
generatedChangelog, err := s.GetChangelog(releaseVersion)
if err != nil {
return err

View File

@@ -2,8 +2,8 @@ package commands
import (
"fmt"
"github.com/Nightapes/go-semantic-release/pkg/semanticrelease"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
@@ -35,7 +35,15 @@ var nextCmd = &cobra.Command{
return err
}
releaseVersion, err := s.GetNextVersion(force)
provider, err := s.GetCIProvider()
if err != nil {
log.Infof("Will not calculate version, set fake version. Could not find CI Provider, if running locally, set env CI=true")
fmt.Println("0.0.0-fake.0")
return nil
}
releaseVersion, err := s.GetNextVersion(provider, force)
if err != nil {
return err
}

View File

@@ -32,6 +32,12 @@ var releaseCmd = &cobra.Command{
if err != nil {
return err
}
return s.Release(force)
provider, err := s.GetCIProvider()
if err != nil {
return err
}
return s.Release(provider, force)
},
}

View File

@@ -31,11 +31,7 @@ func Execute(version string) {
}
func init() {
currentDir, err := os.Getwd()
if err != nil {
panic(err)
}
rootCmd.PersistentFlags().StringP("repository", "r", currentDir, "Path to repository")
rootCmd.PersistentFlags().StringP("repository", "r", "./", "Path to repository")
rootCmd.PersistentFlags().StringP("loglevel", "l", "error", "Set loglevel")
rootCmd.PersistentFlags().StringP("config", "c", ".release.yml", "Path to config file")
rootCmd.PersistentFlags().Bool("no-cache", false, "Ignore cache, don't use in ci build")

View File

@@ -31,6 +31,11 @@ var setCmd = &cobra.Command{
return err
}
return s.SetVersion(args[0])
provider, err := s.GetCIProvider()
if err != nil {
return err
}
return s.SetVersion(provider, args[0])
},
}

1
go.sum
View File

@@ -48,6 +48,7 @@ github.com/kevinburke/ssh_config v0.0.0-20180830205328-81db2a75821e h1:RgQk53JHp
github.com/kevinburke/ssh_config v0.0.0-20180830205328-81db2a75821e/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kevinburke/ssh_config v0.0.0-20190630040420-2e50c441276c h1:VAx3LRNjVNvjtgO7KFRuT/3aye/0zJvwn01rHSfoolo=
github.com/kevinburke/ssh_config v0.0.0-20190630040420-2e50c441276c/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=

View File

@@ -4,47 +4,30 @@ package analyzer
import (
"fmt"
"github.com/Nightapes/go-semantic-release/internal/gitutil"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/Nightapes/go-semantic-release/pkg/config"
log "github.com/sirupsen/logrus"
)
//Analyzer struct
type Analyzer struct {
analyzeCommit analyzeCommit
Config config.ChangelogConfig
analyzeCommits analyzeCommits
Config config.ChangelogConfig
}
//Release types, like major
type Release string
//Scope of the commit, like feat, fix,..
type Scope string
//Rule for commits
type Rule struct {
Tag string
TagString string
Release Release
Release shared.Release
Changelog bool
}
type analyzeCommit interface {
analyze(commit gitutil.Commit, tag Rule) (AnalyzedCommit, bool, error)
type analyzeCommits interface {
analyze(commit shared.Commit, tag Rule) (shared.AnalyzedCommit, bool, error)
getRules() []Rule
}
//AnalyzedCommit struct
type AnalyzedCommit struct {
Commit gitutil.Commit
ParsedMessage string
Scope Scope
ParsedBreakingChangeMessage string
Tag string
TagString string
Print bool
}
//New Analyzer struct for given commit format
func New(format string, config config.ChangelogConfig) (*Analyzer, error) {
analyzer := &Analyzer{
@@ -52,9 +35,9 @@ func New(format string, config config.ChangelogConfig) (*Analyzer, error) {
}
switch format {
case "angular":
log.Debugf("Commit format set to angular")
analyzer.analyzeCommit = newAngular()
case ANGULAR:
analyzer.analyzeCommits = newAngular()
log.Debugf("Commit format set to %s", ANGULAR)
default:
return nil, fmt.Errorf("invalid commit format: %s", format)
}
@@ -64,21 +47,21 @@ func New(format string, config config.ChangelogConfig) (*Analyzer, error) {
// GetRules from current mode
func (a *Analyzer) GetRules() []Rule {
return a.analyzeCommit.getRules()
return a.analyzeCommits.getRules()
}
// Analyze commits and return commits splitted by major,minor,patch
func (a *Analyzer) Analyze(commits []gitutil.Commit) map[Release][]AnalyzedCommit {
func (a *Analyzer) Analyze(commits []shared.Commit) map[shared.Release][]shared.AnalyzedCommit {
analyzedCommits := make(map[Release][]AnalyzedCommit)
analyzedCommits["major"] = make([]AnalyzedCommit, 0)
analyzedCommits["minor"] = make([]AnalyzedCommit, 0)
analyzedCommits["patch"] = make([]AnalyzedCommit, 0)
analyzedCommits["none"] = make([]AnalyzedCommit, 0)
analyzedCommits := make(map[shared.Release][]shared.AnalyzedCommit)
analyzedCommits["major"] = make([]shared.AnalyzedCommit, 0)
analyzedCommits["minor"] = make([]shared.AnalyzedCommit, 0)
analyzedCommits["patch"] = make([]shared.AnalyzedCommit, 0)
analyzedCommits["none"] = make([]shared.AnalyzedCommit, 0)
for _, commit := range commits {
for _, rule := range a.analyzeCommit.getRules() {
analyzedCommit, hasBreakingChange, err := a.analyzeCommit.analyze(commit, rule)
for _, rule := range a.analyzeCommits.getRules() {
analyzedCommit, hasBreakingChange, err := a.analyzeCommits.analyze(commit, rule)
if err == nil {
if a.Config.PrintAll {
analyzedCommit.Print = true

View File

@@ -8,17 +8,22 @@ import (
log "github.com/sirupsen/logrus"
"github.com/Nightapes/go-semantic-release/internal/gitutil"
"github.com/Nightapes/go-semantic-release/internal/shared"
)
type angular struct {
rules []Rule
regex string
log *log.Entry
}
// ANGULAR identifer
const ANGULAR = "angular"
func newAngular() *angular {
return &angular{
regex: `(TAG)(?:\((.*)\))?: (.*)`,
log: log.WithField("analyzer", ANGULAR),
rules: []Rule{
{
Tag: "feat",
@@ -76,9 +81,9 @@ func (a *angular) getRules() []Rule {
return a.rules
}
func (a *angular) analyze(commit gitutil.Commit, rule Rule) (AnalyzedCommit, bool, error) {
func (a *angular) analyze(commit shared.Commit, rule Rule) (shared.AnalyzedCommit, bool, error) {
analyzed := AnalyzedCommit{
analyzed := shared.AnalyzedCommit{
Commit: commit,
Tag: rule.Tag,
TagString: rule.TagString,
@@ -89,13 +94,13 @@ func (a *angular) analyze(commit gitutil.Commit, rule Rule) (AnalyzedCommit, boo
if len(matches) >= 1 {
if len(matches[0]) >= 3 {
analyzed.Scope = Scope(matches[0][2])
analyzed.Scope = shared.Scope(matches[0][2])
message := strings.Join(matches[0][3:], "")
if !strings.Contains(message, "BREAKING CHANGE:") {
analyzed.ParsedMessage = strings.Trim(message, " ")
log.Tracef("%s: found %s", commit.Message, rule.Tag)
a.log.Tracef("%s: found %s", commit.Message, rule.Tag)
return analyzed, false, nil
}
breakingChange := strings.SplitN(message, "BREAKING CHANGE:", 2)
@@ -103,11 +108,11 @@ func (a *angular) analyze(commit gitutil.Commit, rule Rule) (AnalyzedCommit, boo
analyzed.ParsedMessage = strings.Trim(breakingChange[0], " ")
analyzed.ParsedBreakingChangeMessage = strings.Trim(breakingChange[1], " ")
log.Tracef(" %s, BREAKING CHANGE found", commit.Message)
a.log.Tracef(" %s, BREAKING CHANGE found", commit.Message)
return analyzed, true, nil
}
}
log.Tracef("%s does not match %s, skip", commit.Message, rule.Tag)
a.log.Tracef("%s does not match %s, skip", commit.Message, rule.Tag)
return analyzed, false, fmt.Errorf("not found")
}

View File

@@ -4,7 +4,7 @@ import (
"testing"
"github.com/Nightapes/go-semantic-release/internal/analyzer"
"github.com/Nightapes/go-semantic-release/internal/gitutil"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/Nightapes/go-semantic-release/pkg/config"
"github.com/stretchr/testify/assert"
)
@@ -13,15 +13,15 @@ func TestAngular(t *testing.T) {
testConfigs := []struct {
testCase string
commits []gitutil.Commit
analyzedCommits map[analyzer.Release][]analyzer.AnalyzedCommit
commits []shared.Commit
analyzedCommits map[shared.Release][]shared.AnalyzedCommit
}{
{
testCase: "feat",
analyzedCommits: map[analyzer.Release][]analyzer.AnalyzedCommit{
"minor": []analyzer.AnalyzedCommit{
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"minor": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "feat(internal/changelog): my first commit",
Author: "me",
Hash: "12345667",
@@ -33,12 +33,12 @@ func TestAngular(t *testing.T) {
Print: true,
},
},
"major": []analyzer.AnalyzedCommit{},
"patch": []analyzer.AnalyzedCommit{},
"none": []analyzer.AnalyzedCommit{},
"major": []shared.AnalyzedCommit{},
"patch": []shared.AnalyzedCommit{},
"none": []shared.AnalyzedCommit{},
},
commits: []gitutil.Commit{
gitutil.Commit{
commits: []shared.Commit{
shared.Commit{
Message: "feat(internal/changelog): my first commit",
Author: "me",
Hash: "12345667",
@@ -47,10 +47,10 @@ func TestAngular(t *testing.T) {
},
{
testCase: "feat breaking change",
analyzedCommits: map[analyzer.Release][]analyzer.AnalyzedCommit{
"minor": []analyzer.AnalyzedCommit{
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"minor": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "feat(internal/changelog): my first commit",
Author: "me",
Hash: "12345667",
@@ -62,9 +62,9 @@ func TestAngular(t *testing.T) {
Print: true,
},
},
"major": []analyzer.AnalyzedCommit{
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
"major": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "feat(internal/changelog): my first break BREAKING CHANGE: change api to v2",
Author: "me",
Hash: "12345668",
@@ -77,16 +77,16 @@ func TestAngular(t *testing.T) {
ParsedBreakingChangeMessage: "change api to v2",
},
},
"patch": []analyzer.AnalyzedCommit{},
"none": []analyzer.AnalyzedCommit{},
"patch": []shared.AnalyzedCommit{},
"none": []shared.AnalyzedCommit{},
},
commits: []gitutil.Commit{
gitutil.Commit{
commits: []shared.Commit{
shared.Commit{
Message: "feat(internal/changelog): my first commit",
Author: "me",
Hash: "12345667",
},
gitutil.Commit{
shared.Commit{
Message: "feat(internal/changelog): my first break BREAKING CHANGE: change api to v2",
Author: "me",
Hash: "12345668",
@@ -95,14 +95,14 @@ func TestAngular(t *testing.T) {
},
{
testCase: "invalid",
analyzedCommits: map[analyzer.Release][]analyzer.AnalyzedCommit{
"minor": []analyzer.AnalyzedCommit{},
"major": []analyzer.AnalyzedCommit{},
"patch": []analyzer.AnalyzedCommit{},
"none": []analyzer.AnalyzedCommit{},
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"minor": []shared.AnalyzedCommit{},
"major": []shared.AnalyzedCommit{},
"patch": []shared.AnalyzedCommit{},
"none": []shared.AnalyzedCommit{},
},
commits: []gitutil.Commit{
gitutil.Commit{
commits: []shared.Commit{
shared.Commit{
Message: "internal/changelog: my first commit",
Author: "me",
Hash: "12345667",
@@ -111,10 +111,10 @@ func TestAngular(t *testing.T) {
},
{
testCase: "feat and build",
analyzedCommits: map[analyzer.Release][]analyzer.AnalyzedCommit{
"minor": []analyzer.AnalyzedCommit{
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"minor": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "feat(internal/changelog): my first commit",
Author: "me",
Hash: "12345667",
@@ -126,9 +126,9 @@ func TestAngular(t *testing.T) {
Print: true,
},
},
"none": []analyzer.AnalyzedCommit{
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
"none": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "build(internal/changelog): my first build",
Author: "me",
Hash: "12345668",
@@ -141,16 +141,16 @@ func TestAngular(t *testing.T) {
ParsedBreakingChangeMessage: "",
},
},
"patch": []analyzer.AnalyzedCommit{},
"major": []analyzer.AnalyzedCommit{},
"patch": []shared.AnalyzedCommit{},
"major": []shared.AnalyzedCommit{},
},
commits: []gitutil.Commit{
gitutil.Commit{
commits: []shared.Commit{
shared.Commit{
Message: "feat(internal/changelog): my first commit",
Author: "me",
Hash: "12345667",
},
gitutil.Commit{
shared.Commit{
Message: "build(internal/changelog): my first build",
Author: "me",
Hash: "12345668",

View File

@@ -5,49 +5,61 @@ import (
"io/ioutil"
"path"
log "github.com/sirupsen/logrus"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/shared"
"gopkg.in/yaml.v2"
)
// ReleaseVersion struct
type ReleaseVersion struct {
Last ReleaseVersionEntry `yaml:"last"`
Next ReleaseVersionEntry `yaml:"next"`
Branch string `yaml:"branch"`
Draft bool `yaml:"draft"`
}
//ReleaseVersionEntry struct
type ReleaseVersionEntry struct {
Commit string `yaml:"commit"`
Version string `yaml:"version"`
}
// Write version into .version
func Write(repository string, versionFileContent ReleaseVersion) error {
func Write(repository string, releaseVersion shared.ReleaseVersion) error {
completePath := path.Join(path.Dir(repository), ".version")
data, err := yaml.Marshal(&versionFileContent)
if releaseVersion.Last.Version != nil {
releaseVersion.Last.VersionString = releaseVersion.Last.Version.String()
}
if releaseVersion.Next.Version != nil {
releaseVersion.Next.VersionString = releaseVersion.Next.Version.String()
}
//toCache := &ReleaseVersion(releaseVersion)
data, err := yaml.Marshal(releaseVersion)
if err != nil {
return err
}
log.Infof("Save %s with hash %s to cache %s", releaseVersion.Next.Version.String(), releaseVersion.Next.Commit, completePath)
return ioutil.WriteFile(completePath, data, 0644)
}
// Read version into .version
func Read(repository string) (*ReleaseVersion, error) {
func Read(repository string) (*shared.ReleaseVersion, error) {
completePath := path.Join(path.Dir(repository), ".version")
content, err := ioutil.ReadFile(completePath)
if err != nil {
return &ReleaseVersion{}, err
log.Warnf("Could not read cache %s, will ignore cache", completePath)
return &shared.ReleaseVersion{}, nil
}
var versionFileContent ReleaseVersion
err = yaml.Unmarshal(content, &versionFileContent)
var parsedContent shared.ReleaseVersion
err = yaml.Unmarshal(content, &parsedContent)
if err != nil {
return &ReleaseVersion{}, err
return &shared.ReleaseVersion{}, err
}
return &versionFileContent, nil
parsedContent.Next.Version, err = semver.NewVersion(parsedContent.Next.VersionString)
if err != nil {
return nil, err
}
parsedContent.Last.Version, err = semver.NewVersion(parsedContent.Last.VersionString)
if err != nil {
return nil, err
}
log.Infof("Found cache, will return cached version %s", parsedContent.Next.Version)
return &parsedContent, nil
}

View File

@@ -3,7 +3,9 @@ package cache_test
import (
"testing"
"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"
@@ -12,8 +14,9 @@ import (
func TestReadCacheNotFound(t *testing.T) {
_, err := cache.Read("notfound/dir")
assert.Errorf(t, err, "Read non exsiting file")
resp, err := cache.Read("notfound/dir")
assert.NoErrorf(t, err, "Read non exsiting file")
assert.NotNil(t, resp)
}
@@ -39,17 +42,36 @@ func TestWriteAndReadCache(t *testing.T) {
assert.NoError(t, err)
content := cache.ReleaseVersion{
Last: cache.ReleaseVersionEntry{
Commit: "12345",
Version: "1.0.0",
content := shared.ReleaseVersion{
Last: shared.ReleaseVersionEntry{
Commit: "12345",
Version: createVersion("1.0.0"),
VersionString: "1.0.0",
},
Next: cache.ReleaseVersionEntry{
Commit: "12346",
Version: "1.1.0",
Next: shared.ReleaseVersionEntry{
Commit: "12346",
Version: createVersion("1.1.0"),
VersionString: "1.1.0",
},
Branch: "master",
Draft: true,
Commits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "Message",
Author: "Author",
Hash: "Hash",
},
ParsedMessage: "add gitlab as relase option",
Scope: "releaser",
ParsedBreakingChangeMessage: "",
Tag: "feat",
TagString: "Features",
Print: true,
},
},
},
}
defer os.RemoveAll(dir)
@@ -59,13 +81,29 @@ func TestWriteAndReadCache(t *testing.T) {
result, readError := cache.Read(dir)
assert.NoErrorf(t, readError, "Should read file")
assert.Equal(t, &content, result)
assert.EqualValues(t, &content, result)
}
func TestWriteNotFound(t *testing.T) {
err := cache.Write("notfound/dir", cache.ReleaseVersion{})
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")
}
func createVersion(version string) *semver.Version {
ver, _ := semver.NewVersion(version)
return ver
}

View File

@@ -0,0 +1,68 @@
package calculator
import (
"strconv"
"strings"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/shared"
log "github.com/sirupsen/logrus"
)
// Calculator struct
type Calculator struct{}
// New Calculator struct
func New() *Calculator {
return &Calculator{}
}
//IncPrerelease increase prerelease by one
func (c *Calculator) IncPrerelease(preReleaseType string, version *semver.Version) (semver.Version, error) {
defaultPrerelease := preReleaseType + ".0"
if version.Prerelease() == "" || !strings.HasPrefix(version.Prerelease(), preReleaseType) {
return version.SetPrerelease(defaultPrerelease)
}
parts := strings.Split(version.Prerelease(), ".")
if len(parts) == 2 {
i, err := strconv.Atoi(parts[1])
if err != nil {
log.Warnf("Could not parse release tag %s, use version %s", version.Prerelease(), version.String())
return version.SetPrerelease(defaultPrerelease)
}
return version.SetPrerelease(preReleaseType + "." + strconv.Itoa((i + 1)))
}
log.Warnf("Could not parse release tag %s, use version %s", version.Prerelease(), version.String())
return version.SetPrerelease(defaultPrerelease)
}
//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) {
switch releaseType {
case "beta", "alpha":
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
}
case "release":
if !firstRelease {
if len(commits["major"]) > 0 {
return lastVersion.IncMajor(), false
} else if len(commits["minor"]) > 0 {
return lastVersion.IncMinor(), false
} else if len(commits["patch"]) > 0 {
return lastVersion.IncPatch(), false
}
}
}
return *lastVersion, false
}

View File

@@ -0,0 +1,219 @@
package calculator_test
import (
"testing"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/calculator"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/stretchr/testify/assert"
)
func createVersion(version string) *semver.Version {
ver, _ := semver.NewVersion(version)
return ver
}
func TestCalculator_IncPrerelease(t *testing.T) {
testConfigs := []struct {
testCase string
preReleaseType string
lastVersion *semver.Version
nextVersion string
hasError bool
}{
{
testCase: "version without preRelease",
preReleaseType: "alpha",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.0.0-alpha.0",
},
{
testCase: "version with preRelease",
preReleaseType: "alpha",
lastVersion: createVersion("1.0.0-alpha.0"),
nextVersion: "1.0.0-alpha.1",
},
{
testCase: "version with preRelease, change type",
preReleaseType: "beta",
lastVersion: createVersion("1.0.0-alpha.0"),
nextVersion: "1.0.0-beta.0",
},
{
testCase: "version with preRelease but broken",
preReleaseType: "alpha",
lastVersion: createVersion("1.0.0-alpha.br0ken"),
nextVersion: "1.0.0-alpha.0",
},
{
testCase: "version with preRelease but broken 2",
preReleaseType: "alpha",
lastVersion: createVersion("1.0.0-alphabr0ken"),
nextVersion: "1.0.0-alpha.0",
},
}
c := calculator.New()
for _, test := range testConfigs {
next, err := c.IncPrerelease(test.preReleaseType, test.lastVersion)
assert.Equalf(t, test.hasError, err != nil, "Testcase %s should have error: %t -> %s", test.testCase, test.hasError, err)
assert.Equal(t, test.nextVersion, next.String())
}
}
func TestCalculator_CalculateNewVersion(t *testing.T) {
testConfigs := []struct {
testCase string
releaseType string
lastVersion *semver.Version
nextVersion string
isDraft bool
isFirst bool
analyzedCommits map[shared.Release][]shared.AnalyzedCommit
}{
{
testCase: "version with preRelease alpha",
releaseType: "alpha",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.0.0-alpha.0",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{},
"minor": []shared.AnalyzedCommit{
shared.AnalyzedCommit{},
},
"patch": []shared.AnalyzedCommit{},
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: true,
},
{
testCase: "version with preRelease beta",
releaseType: "beta",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.0.0-beta.0",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{},
"minor": []shared.AnalyzedCommit{
shared.AnalyzedCommit{},
},
"patch": []shared.AnalyzedCommit{},
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: true,
},
{
testCase: "version without commits",
releaseType: "alpha",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.0.0",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{},
"minor": []shared.AnalyzedCommit{},
"patch": []shared.AnalyzedCommit{},
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and first release",
releaseType: "release",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.0.0",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"minor": []shared.AnalyzedCommit{},
"patch": []shared.AnalyzedCommit{},
"none": []shared.AnalyzedCommit{},
},
isFirst: true,
isDraft: false,
},
{
testCase: "version with commits and rc release",
releaseType: "rc",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.0.0-rc.0",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"minor": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"patch": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and rc release",
releaseType: "rc",
lastVersion: createVersion("1.0.0-rc.0"),
nextVersion: "1.0.0-rc.1",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{},
"minor": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"patch": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and major release",
releaseType: "release",
lastVersion: createVersion("1.0.0"),
nextVersion: "2.0.0",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"minor": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"patch": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and minor release",
releaseType: "release",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.1.0",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{},
"minor": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"patch": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"none": []shared.AnalyzedCommit{},
},
isFirst: false,
isDraft: false,
},
{
testCase: "version with commits and minor patch",
releaseType: "release",
lastVersion: createVersion("1.0.0"),
nextVersion: "1.0.1",
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"major": []shared.AnalyzedCommit{},
"minor": []shared.AnalyzedCommit{},
"patch": []shared.AnalyzedCommit{shared.AnalyzedCommit{}},
"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)
assert.Equalf(t, test.nextVersion, next.String(), "Should have version %s for testcase %s", test.nextVersion, test.testCase)
}
}

View File

@@ -34,8 +34,8 @@ introduced by commit:
`
type changelogContent struct {
Commits map[string][]analyzer.AnalyzedCommit
BreakingChanges []analyzer.AnalyzedCommit
Commits map[string][]shared.AnalyzedCommit
BreakingChanges []shared.AnalyzedCommit
Order []string
Version string
Now time.Time
@@ -49,6 +49,7 @@ type Changelog struct {
config *config.ReleaseConfig
rules []analyzer.Rule
releaseTime time.Time
log *log.Entry
}
//New Changelog struct for generating changelog from commits
@@ -57,18 +58,19 @@ func New(config *config.ReleaseConfig, rules []analyzer.Rule, releaseTime time.T
config: config,
rules: rules,
releaseTime: releaseTime,
log: log.WithField("changelog", config.CommitFormat),
}
}
// GenerateChanglog from given commits
func (c *Changelog) GenerateChanglog(templateConfig shared.ChangelogTemplateConfig, analyzedCommits map[analyzer.Release][]analyzer.AnalyzedCommit) (*shared.GeneratedChangelog, error) {
func (c *Changelog) GenerateChanglog(templateConfig shared.ChangelogTemplateConfig, analyzedCommits map[shared.Release][]shared.AnalyzedCommit) (*shared.GeneratedChangelog, error) {
commitsPerScope := map[string][]analyzer.AnalyzedCommit{}
commitsBreakingChange := []analyzer.AnalyzedCommit{}
commitsPerScope := map[string][]shared.AnalyzedCommit{}
commitsBreakingChange := []shared.AnalyzedCommit{}
order := make([]string, 0)
for _, rule := range c.rules {
log.Debugf("Add %s to list", rule.TagString)
c.log.Tracef("Add %s to list", rule.TagString)
if rule.Changelog || c.config.Changelog.PrintAll {
order = append(order, rule.TagString)
}
@@ -82,7 +84,7 @@ func (c *Changelog) GenerateChanglog(templateConfig shared.ChangelogTemplateConf
continue
}
if _, ok := commitsPerScope[commit.TagString]; !ok {
commitsPerScope[commit.TagString] = make([]analyzer.AnalyzedCommit, 0)
commitsPerScope[commit.TagString] = make([]shared.AnalyzedCommit, 0)
}
commitsPerScope[commit.TagString] = append(commitsPerScope[commit.TagString], commit)
}

View File

@@ -5,7 +5,6 @@ import (
"github.com/Nightapes/go-semantic-release/internal/analyzer"
"github.com/Nightapes/go-semantic-release/internal/changelog"
"github.com/Nightapes/go-semantic-release/internal/gitutil"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/Nightapes/go-semantic-release/pkg/config"
"github.com/stretchr/testify/assert"
@@ -23,16 +22,16 @@ func TestChangelog(t *testing.T) {
testConfigs := []struct {
testCase string
analyzedCommits map[analyzer.Release][]analyzer.AnalyzedCommit
analyzedCommits map[shared.Release][]shared.AnalyzedCommit
result *shared.GeneratedChangelog
hasError bool
}{
{
testCase: "feat",
analyzedCommits: map[analyzer.Release][]analyzer.AnalyzedCommit{
"minor": []analyzer.AnalyzedCommit{
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"minor": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "feat(test): my first commit",
Author: "me",
Hash: "12345667",
@@ -53,10 +52,10 @@ func TestChangelog(t *testing.T) {
},
{
testCase: "feat breaking change",
analyzedCommits: map[analyzer.Release][]analyzer.AnalyzedCommit{
"minor": []analyzer.AnalyzedCommit{
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
analyzedCommits: map[shared.Release][]shared.AnalyzedCommit{
"minor": []shared.AnalyzedCommit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "feat(test): my first commit",
Author: "me",
Hash: "12345667",
@@ -67,8 +66,8 @@ func TestChangelog(t *testing.T) {
TagString: "Features",
Print: true,
},
analyzer.AnalyzedCommit{
Commit: gitutil.Commit{
shared.AnalyzedCommit{
Commit: shared.Commit{
Message: "feat(test): my first break: BREAKING CHANGE: change api to v2",
Author: "me",
Hash: "12345668",

View File

@@ -51,7 +51,7 @@ func GetCIProvider(gitUtil *gitutil.GitUtil, envs map[string]string) (*ProviderC
log.Infof("Found CI: %s", config.Name)
return config, nil
}
log.Infof("%s", err.Error())
log.Debugf("%s", err.Error())
}
return nil, fmt.Errorf("could not find any CI, if running locally set env CI=true")
}

View File

@@ -10,15 +10,9 @@ import (
"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"
)
// Commit struct
type Commit struct {
Message string
Author string
Hash string
}
// GitUtil struct
type GitUtil struct {
Repository *git.Repository
@@ -126,7 +120,7 @@ func (g *GitUtil) GetLastVersion() (*semver.Version, string, error) {
}
// GetCommits from git hash to HEAD
func (g *GitUtil) GetCommits(lastTagHash string) ([]Commit, error) {
func (g *GitUtil) GetCommits(lastTagHash string) ([]shared.Commit, error) {
ref, err := g.Repository.Head()
if err != nil {
@@ -138,7 +132,7 @@ func (g *GitUtil) GetCommits(lastTagHash string) ([]Commit, error) {
return nil, err
}
var commits []Commit
var commits []shared.Commit
var foundEnd bool
err = cIter.ForEach(func(c *object.Commit) error {
@@ -149,7 +143,7 @@ func (g *GitUtil) GetCommits(lastTagHash string) ([]Commit, error) {
}
if !foundEnd {
log.Tracef("Found commit with hash %s", c.Hash.String())
commit := Commit{
commit := shared.Commit{
Message: c.Message,
Author: c.Committer.Name,
Hash: c.Hash.String(),

View File

@@ -25,6 +25,7 @@ type Client struct {
context context.Context
release *github.RepositoryRelease
baseURL string
log *log.Entry
}
// New initialize a new GitHubRelease
@@ -52,6 +53,7 @@ func New(c *config.GitHubProvider) (*Client, error) {
client: client,
context: ctx,
baseURL: baseURL,
log: log.WithField("releaser", GITHUB),
}, err
}
@@ -67,7 +69,7 @@ func (g *Client) GetCompareURL(oldVersion, newVersion string) string {
//ValidateConfig for github
func (g *Client) ValidateConfig() error {
log.Debugf("validate GitHub provider config")
g.log.Debugf("validate GitHub provider config")
if g.config.Repo == "" {
return fmt.Errorf("github Repro is not set")
@@ -85,11 +87,11 @@ func (g *Client) ValidateConfig() error {
func (g *Client) CreateRelease(releaseVersion *shared.ReleaseVersion, generatedChangelog *shared.GeneratedChangelog) error {
tag := releaseVersion.Next.Version.String()
log.Debugf("create release with version %s", tag)
g.log.Debugf("create release with version %s", tag)
prerelease := releaseVersion.Next.Version.Prerelease() != ""
release, resp, err := g.client.Repositories.CreateRelease(g.context, g.config.User, g.config.Repo, &github.RepositoryRelease{
release, _, err := g.client.Repositories.CreateRelease(g.context, g.config.User, g.config.Repo, &github.RepositoryRelease{
TagName: &tag,
TargetCommitish: &releaseVersion.Branch,
Name: &generatedChangelog.Title,
@@ -97,19 +99,18 @@ func (g *Client) CreateRelease(releaseVersion *shared.ReleaseVersion, generatedC
Draft: &releaseVersion.Draft,
Prerelease: &prerelease,
})
if err != nil {
if !strings.Contains(err.Error(), "already_exists") && resp.StatusCode >= http.StatusUnprocessableEntity {
return fmt.Errorf("could not create release: %v", err)
if strings.Contains(err.Error(), "already_exists") {
g.log.Infof("A release with tag %s already exits, will not perform a release or update", tag)
return nil
}
log.Infof("A release with tag %s already exits, will not perform a release or update", tag)
} else {
g.release = release
log.Debugf("Release repsone: %+v", *release)
log.Infof("Crated release")
return fmt.Errorf("could not create release: %s", err.Error())
}
g.release = release
g.log.Debugf("Release repsone: %+v", *release)
g.log.Infof("Crated release")
return nil
}
// UploadAssets uploads specified assets
@@ -133,7 +134,7 @@ func (g *Client) UploadAssets(repoDir string, assets []config.Asset) error {
}
if resp.StatusCode >= http.StatusBadRequest {
return fmt.Errorf("releaser: github: Could not upload asset %s: %s", file.Name(), resp.Status)
return fmt.Errorf("could not upload asset %s: %s", file.Name(), resp.Status)
}
}
}

View File

@@ -0,0 +1,237 @@
package github_test
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
log "github.com/sirupsen/logrus"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/releaser/github"
"github.com/Nightapes/go-semantic-release/internal/shared"
"github.com/Nightapes/go-semantic-release/pkg/config"
"github.com/stretchr/testify/assert"
)
type testHelperMethodStruct struct {
config config.GitHubProvider
valid bool
}
type testReleaseStruct struct {
config config.GitHubProvider
releaseVersion *shared.ReleaseVersion
generatedChangelog *shared.GeneratedChangelog
requestResponseBody string
requestResponseCode int
valid bool
}
var testNewClient = []testHelperMethodStruct{
testHelperMethodStruct{config: config.GitHubProvider{
Repo: "foo",
User: "bar",
},
valid: true,
},
testHelperMethodStruct{config: config.GitHubProvider{
Repo: "foo",
User: "bar",
CustomURL: "https://test.com",
},
valid: false,
},
}
var testHelperMethod = []testHelperMethodStruct{
testHelperMethodStruct{config: config.GitHubProvider{
Repo: "foo",
User: "bar",
},
valid: true,
},
testHelperMethodStruct{config: config.GitHubProvider{
Repo: "",
User: "bar",
},
valid: false,
},
testHelperMethodStruct{config: config.GitHubProvider{
Repo: "foo",
User: "",
},
valid: false,
},
}
var lastVersion, _ = semver.NewVersion("1.0.0")
var newVersion, _ = semver.NewVersion("2.0.0")
var testReleases = []testReleaseStruct{
testReleaseStruct{
config: config.GitHubProvider{
Repo: "foo",
User: "bar",
},
releaseVersion: &shared.ReleaseVersion{
Last: shared.ReleaseVersionEntry{
Version: lastVersion,
Commit: "foo",
},
Next: shared.ReleaseVersionEntry{
Version: newVersion,
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
Content: "content",
},
requestResponseBody: "{ \"url\": \"https://api.github.com/repos/octocat/Hello-World/releases/1\", \"html_url\": \"https://github.com/octocat/Hello-World/releases/v1.0.0\", \"assets_url\": \"https://api.github.com/repos/octocat/Hello-World/releases/1/assets\", \"upload_url\": \"https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}\", \"tarball_url\": \"https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0\", \"zipball_url\": \"https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0\", \"id\": 1, \"node_id\": \"MDc6UmVsZWFzZTE=\", \"tag_name\": \"v1.0.0\", \"target_commitish\": \"master\", \"name\": \"v1.0.0\", \"body\": \"Description of the release\", \"draft\": false, \"prerelease\": false, \"created_at\": \"2013-02-27T19:35:32Z\", \"published_at\": \"2013-02-27T19:35:32Z\", \"author\": { \"login\": \"octocat\", \"id\": 1, \"node_id\": \"MDQ6VXNlcjE=\", \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\", \"gravatar_id\": \"\", \"url\": \"https://api.github.com/users/octocat\", \"html_url\": \"https://github.com/octocat\", \"followers_url\": \"https://api.github.com/users/octocat/followers\", \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\", \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\", \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\", \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\", \"organizations_url\": \"https://api.github.com/users/octocat/orgs\", \"repos_url\": \"https://api.github.com/users/octocat/repos\", \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\", \"received_events_url\": \"https://api.github.com/users/octocat/received_events\", \"type\": \"User\", \"site_admin\": false }, \"assets\": [ ]}",
requestResponseCode: 200,
valid: true,
},
testReleaseStruct{
config: config.GitHubProvider{
Repo: "foo",
User: "bar",
},
releaseVersion: &shared.ReleaseVersion{
Last: shared.ReleaseVersionEntry{
Version: lastVersion,
Commit: "foo",
},
Next: shared.ReleaseVersionEntry{
Version: newVersion,
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
Content: "content",
},
requestResponseCode: 400,
valid: false,
},
}
func initHTTPServer(respCode int, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
log.Infof("Got call from %s %s", req.Method, req.URL.String())
rw.WriteHeader(respCode)
rw.Header().Set("Content-Type", "application/json")
if _, err := rw.Write([]byte(body)); err != nil {
log.Info(err)
}
}))
}
func TestNew(t *testing.T) {
for _, testOject := range testNewClient {
if testOject.valid {
os.Setenv("GITHUB_ACCESS_TOKEN", "XXX")
}
_, err := github.New(&testOject.config)
assert.Equal(t, testOject.valid, err == nil)
os.Unsetenv("GITHUB_ACCESS_TOKEN")
}
}
func TestGetCommitURL(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
for _, testOject := range testNewClient {
client, _ := github.New(&testOject.config)
actualURL := client.GetCommitURL()
if testOject.config.CustomURL != "" {
expectedURL := fmt.Sprintf("%s/%s/%s/commit/{{hash}}", testOject.config.CustomURL, testOject.config.User, testOject.config.Repo)
assert.EqualValues(t, expectedURL, actualURL)
} else {
expectedURL := fmt.Sprintf("%s/%s/%s/commit/{{hash}}", "https://github.com", testOject.config.User, testOject.config.Repo)
assert.EqualValues(t, expectedURL, actualURL)
}
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
}
func TestGetCompareURL(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
for _, testOject := range testNewClient {
client, _ := github.New(&testOject.config)
actualURL := client.GetCompareURL("1", "2")
if testOject.config.CustomURL != "" {
expectedURL := fmt.Sprintf("%s/%s/%s/compare/%s...%s", testOject.config.CustomURL, testOject.config.User, testOject.config.Repo, "1", "2")
assert.EqualValues(t, expectedURL, actualURL)
} else {
expectedURL := fmt.Sprintf("%s/%s/%s/compare/%s...%s", "https://github.com", testOject.config.User, testOject.config.Repo, "1", "2")
assert.EqualValues(t, expectedURL, actualURL)
}
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
}
func TestValidateConfig(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
for _, testOject := range testHelperMethod {
client, _ := github.New(&testOject.config)
err := client.ValidateConfig()
assert.Equal(t, testOject.valid, err == nil)
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
}
func TestCreateRelease(t *testing.T) {
os.Setenv("GITHUB_ACCESS_TOKEN", "XX")
for _, testObejct := range testReleases {
if testObejct.valid {
server := initHTTPServer(testObejct.requestResponseCode, testObejct.requestResponseBody)
testObejct.config.CustomURL = server.URL
client, _ := github.New(&testObejct.config)
err := client.CreateRelease(testObejct.releaseVersion, testObejct.generatedChangelog)
if err != nil {
t.Log(err)
}
assert.Equal(t, testObejct.valid, err == nil)
server.Close()
} else {
testObejct.config.CustomURL = "http://foo"
client, _ := github.New(&testObejct.config)
err := client.CreateRelease(testObejct.releaseVersion, testObejct.generatedChangelog)
if err != nil {
t.Log(err)
}
assert.Error(t, err)
}
}
os.Unsetenv("GITHUB_ACCESS_TOKEN")
}

View File

@@ -0,0 +1,217 @@
package gitlab
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
"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"
log "github.com/sirupsen/logrus"
)
// GITLAB identifer for gitlab interface
const GITLAB = "gitlab"
// Client type struct
type Client struct {
config *config.GitLabProvider
context context.Context
client *http.Client
baseURL string
apiURL string
token string
Release string
log *log.Entry
}
// New initialize a new gitlabRelease
func New(config *config.GitLabProvider, accessToken string) (*Client, error) {
ctx := context.Background()
tokenHeader := util.NewAddHeaderTransport(nil, "PRIVATE-TOKEN", accessToken)
acceptHeader := util.NewAddHeaderTransport(tokenHeader, "Accept", "application/json")
httpClient := &http.Client{
Transport: acceptHeader,
Timeout: time.Second * 60,
}
logger := log.WithField("releaser", GITLAB)
logger.Debugf("validate gitlab provider config")
if config.Repo == "" {
return nil, fmt.Errorf("gitlab Repro is not set")
}
config.Repo = strings.Trim(config.Repo, "/")
if config.CustomURL == "" {
config.CustomURL = "https://gitlab.com"
}
config.CustomURL = strings.Trim(config.CustomURL, "/")
logger.Debugf("Use gitlab url %s", config.CustomURL)
return &Client{
token: accessToken,
config: config,
context: ctx,
baseURL: config.CustomURL,
apiURL: config.CustomURL + "/api/v4",
client: httpClient,
log: logger,
}, nil
}
//GetCommitURL for gitlab
func (g *Client) GetCommitURL() string {
return fmt.Sprintf("%s/%s/commit/{{hash}}", g.baseURL, g.config.Repo)
}
//GetCompareURL for gitlab
func (g *Client) GetCompareURL(oldVersion, newVersion string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", g.baseURL, g.config.Repo, oldVersion, newVersion)
}
//ValidateConfig for gitlab
func (g *Client) ValidateConfig() error {
return nil
}
// CreateRelease creates release on remote
func (g *Client) CreateRelease(releaseVersion *shared.ReleaseVersion, generatedChangelog *shared.GeneratedChangelog) error {
tag := releaseVersion.Next.Version.String()
g.Release = tag
g.log.Infof("create release with version %s", tag)
url := fmt.Sprintf("%s/projects/%s/releases", g.apiURL, util.PathEscape(g.config.Repo))
g.log.Infof("Send release to %s", url)
bodyBytes, err := json.Marshal(Release{
TagName: tag,
Name: generatedChangelog.Title,
Description: generatedChangelog.Content,
Ref: releaseVersion.Branch,
})
if err != nil {
return err
}
req, err := http.NewRequest("POST", url, bytes.NewReader(bodyBytes))
if err != nil {
return fmt.Errorf("could not create request: %s", err.Error())
}
resp, err := util.Do(g.client, req, nil)
if err != nil {
return fmt.Errorf("could not create release: %s", err.Error())
}
if err := util.IsValidResult(resp); err != nil {
return err
}
g.log.Infof("Crated release")
return nil
}
// UploadAssets uploads specified assets
func (g *Client) UploadAssets(repoDir string, assets []config.Asset) error {
filesToUpload, err := util.PrepareAssets(repoDir, assets)
if err != nil {
return err
}
for _, f := range filesToUpload {
file, err := os.Open(*f)
if err != nil {
return err
}
defer file.Close()
fileInfo, _ := file.Stat()
result, err := g.uploadFile(fileInfo.Name(), file)
if err != nil {
return fmt.Errorf("could not upload asset %s: %s", file.Name(), err.Error())
}
downloadURL := fmt.Sprintf("%s/%s%s", g.baseURL, g.config.Repo, result.URL)
g.log.Infof("Uploaded file %s to gitlab can be downloaded under %s", file.Name(), downloadURL)
path := fmt.Sprintf("%s/projects/%s/releases/%s/assets/links?name=%s&url=%s", g.apiURL, util.PathEscape(g.config.Repo), g.Release, util.PathEscape(fileInfo.Name()), downloadURL)
req, err := http.NewRequest("POST", path, nil)
if err != nil {
return err
}
g.log.Infof("Link file %s with release %s", file.Name(), g.Release)
resp, err := util.Do(g.client, req, nil)
if err != nil {
return err
}
if err = util.IsValidResult(resp); err != nil {
return err
}
g.log.Infof("Link file with release %s is done", g.Release)
}
return nil
}
func (g *Client) uploadFile(fileName string, file *os.File) (*ProjectFile, error) {
b := &bytes.Buffer{}
w := multipart.NewWriter(b)
fw, err := w.CreateFormFile("file", fileName)
if err != nil {
return nil, err
}
_, err = io.Copy(fw, file)
if err != nil {
return nil, err
}
w.Close()
url := fmt.Sprintf("%s/projects/%s/uploads", g.apiURL, util.PathEscape(g.config.Repo))
req, err := http.NewRequest("POST", url, nil)
if err != nil {
return nil, err
}
req.Body = ioutil.NopCloser(b)
req.ContentLength = int64(b.Len())
req.Header.Set("Content-Type", w.FormDataContentType())
uf := &ProjectFile{}
resp, err := util.Do(g.client, req, uf)
if err != nil {
return nil, err
}
if err = util.IsValidResult(resp); err != nil {
return nil, err
}
return uf, nil
}

View File

@@ -0,0 +1,327 @@
package gitlab_test
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Masterminds/semver"
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) {
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) {
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) {
_, err := gitlab.New(&config.GitLabProvider{
CustomURL: "https://localhost/",
}, "aToken")
assert.Error(t, err)
}
func TestValidateConfig_DefaultURL(t *testing.T) {
config := &config.GitLabProvider{
Repo: "localhost/test",
}
_, err := gitlab.New(config, "aToken")
assert.NoError(t, err)
assert.Equal(t, "https://gitlab.com", config.CustomURL)
}
func TestValidateConfig_CustomURL(t *testing.T) {
config := &config.GitLabProvider{
Repo: "/localhost/test/",
CustomURL: "https://localhost/",
}
_, err := gitlab.New(config, "aToken")
assert.NoError(t, err)
assert.Equal(t, "https://localhost", config.CustomURL)
assert.Equal(t, "localhost/test", config.Repo)
}
func TestCreateRelease(t *testing.T) {
lastVersion, _ := semver.NewVersion("1.0.0")
newVersion, _ := semver.NewVersion("2.0.0")
testReleases := []struct {
config config.GitLabProvider
releaseVersion *shared.ReleaseVersion
generatedChangelog *shared.GeneratedChangelog
responseBody string
responseCode int
requestBody string
valid bool
}{
{
config: config.GitLabProvider{
Repo: "foo/bar",
},
releaseVersion: &shared.ReleaseVersion{
Last: shared.ReleaseVersionEntry{
Version: lastVersion,
Commit: "foo",
},
Next: shared.ReleaseVersionEntry{
Version: newVersion,
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
Content: "content",
},
responseBody: "{}",
responseCode: 200,
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content","assets":{"links":null}}`,
valid: true,
},
{
config: config.GitLabProvider{
Repo: "foo/bar",
},
releaseVersion: &shared.ReleaseVersion{
Last: shared.ReleaseVersionEntry{
Version: lastVersion,
Commit: "foo",
},
Next: shared.ReleaseVersionEntry{
Version: newVersion,
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
Content: "content",
},
responseBody: "{}",
responseCode: 500,
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content","assets":{"links":null}}`,
valid: false,
},
{
config: config.GitLabProvider{
Repo: "foo/bar",
CustomURL: "broken",
},
releaseVersion: &shared.ReleaseVersion{
Last: shared.ReleaseVersionEntry{
Version: lastVersion,
Commit: "foo",
},
Next: shared.ReleaseVersionEntry{
Version: newVersion,
Commit: "bar",
},
Branch: "master",
Draft: false,
},
generatedChangelog: &shared.GeneratedChangelog{
Title: "title",
Content: "content",
},
responseCode: 400,
responseBody: "{}",
requestBody: `{"tag_name":"2.0.0","name":"title","ref":"master","description":"content","assets":{"links":null}}`,
valid: false,
},
}
for _, testObject := range testReleases {
testServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
log.Infof("Got call from %s %s", req.Method, req.URL.String())
assert.Equal(t, req.Header.Get("PRIVATE-TOKEN"), "aToken")
assert.Equal(t, req.Header.Get("Accept"), "application/json")
bodyBytes, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Fatal(err)
}
assert.Equal(t, testObject.requestBody, string(bodyBytes))
rw.WriteHeader(testObject.responseCode)
rw.Header().Set("Content-Type", "application/json")
if _, err := rw.Write([]byte(testObject.responseBody)); err != nil {
log.Info(err)
}
}))
if testObject.config.CustomURL == "" {
testObject.config.CustomURL = testServer.URL
}
client, err := gitlab.New(&testObject.config, "aToken")
assert.NoError(t, err)
err = client.CreateRelease(testObject.releaseVersion, testObject.generatedChangelog)
if err != nil {
t.Log(err)
}
assert.Equal(t, testObject.valid, err == nil)
testServer.Close()
}
}
func TestUploadAssets(t *testing.T) {
file, err := ioutil.TempFile("", "prefix")
if err != nil {
log.Fatal(err)
}
defer os.Remove(file.Name())
_, err = file.WriteString("testFile")
assert.NoError(t, err)
testReleases := []struct {
config config.GitLabProvider
responseBody []string
responseCode []int
assets []config.Asset
requestBody []string
testDir string
url []string
method []string
valid bool
}{
{
config: config.GitLabProvider{
Repo: "foo/bar",
},
responseBody: []string{`{"alt" : "dk", "url": "/uploads/66dbcd21ec5d24ed6ea225176098d52b/dk.png", "markdown" :"![dk](/uploads/66dbcd21ec5d24ed6ea225176098d52b/dk.png)"}`, ""},
responseCode: []int{200, 200},
requestBody: []string{
filepath.Base(file.Name()), ""},
url: []string{`/api/v4/projects/foo%2Fbar/uploads`, "/api/v4/projects/foo%2Fbar/releases/1.0.0/assets/links?name=" + filepath.Base(file.Name()) + "&url=<SERVER>/foo/bar/uploads/"},
method: []string{"POST", "POST"},
valid: true,
testDir: os.TempDir(),
assets: []config.Asset{
config.Asset{
Name: filepath.Base(file.Name()),
Compress: false,
},
},
},
{
config: config.GitLabProvider{
Repo: "foo/bar",
},
responseBody: []string{`{"alt" : "dk", "url": "/uploads/66dbcd21ec5d24ed6ea225176098d52b/dk.png", "markdown" :"![dk](/uploads/66dbcd21ec5d24ed6ea225176098d52b/dk.png)"}`, ""},
responseCode: []int{400, 200},
requestBody: []string{
filepath.Base(file.Name()), ""},
url: []string{`/api/v4/projects/foo%2Fbar/uploads`, "/api/v4/projects/foo%2Fbar/releases/1.0.0/assets/links?name=" + filepath.Base(file.Name()) + "&url=<SERVER>/foo/bar/uploads/"},
method: []string{"POST", "POST"},
valid: false,
testDir: os.TempDir(),
assets: []config.Asset{
config.Asset{
Name: filepath.Base(file.Name()),
Compress: false,
},
},
},
{
config: config.GitLabProvider{
Repo: "foo/bar",
},
responseBody: []string{`broken`, ""},
responseCode: []int{200, 200},
requestBody: []string{
filepath.Base(file.Name()), ""},
url: []string{`/api/v4/projects/foo%2Fbar/uploads`, "/api/v4/projects/foo%2Fbar/releases/1.0.0/assets/links?name=" + filepath.Base(file.Name()) + "&url=<SERVER>/foo/bar/uploads/"},
method: []string{"POST", "POST"},
valid: false,
testDir: os.TempDir(),
assets: []config.Asset{
config.Asset{
Name: filepath.Base(file.Name()),
Compress: false,
},
},
},
}
for _, testObject := range testReleases {
calls := 0
testServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
log.Infof("Got call from %s %s", req.Method, req.URL.String())
assert.Contains(t, req.URL.String(), strings.ReplaceAll(testObject.url[calls], "<SERVER>", testObject.config.CustomURL))
assert.Equal(t, req.Method, testObject.method[calls])
assert.Equal(t, req.Header.Get("PRIVATE-TOKEN"), "aToken")
assert.Equal(t, req.Header.Get("Accept"), "application/json")
bodyBytes, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Fatal(err)
}
assert.Contains(t, string(bodyBytes), testObject.requestBody[calls])
rw.WriteHeader(testObject.responseCode[calls])
rw.Header().Set("Content-Type", "application/json")
if _, err := rw.Write([]byte(testObject.responseBody[calls])); err != nil {
log.Info(err)
}
calls++
}))
if testObject.config.CustomURL == "" {
testObject.config.CustomURL = testServer.URL
}
client, err := gitlab.New(&testObject.config, "aToken")
assert.NoError(t, err)
client.Release = "1.0.0"
err = client.UploadAssets(testObject.testDir, testObject.assets)
if err != nil {
t.Log(err)
}
assert.Equal(t, testObject.valid, err == nil)
testServer.Close()
}
}

View File

@@ -0,0 +1,25 @@
package gitlab
// Release struct
type Release struct {
TagName string `json:"tag_name"`
Name string `json:"name"`
Ref string `json:"ref"`
Description string `json:"description,omitempty"`
Assets struct {
Links []*ReleaseLink `json:"links"`
} `json:"assets"`
}
// ReleaseLink struct
type ReleaseLink struct {
Name string `json:"name"`
URL string `json:"url"`
}
// ProjectFile struct
type ProjectFile struct {
Alt string `json:"alt"`
URL string `json:"url"`
Markdown string `json:"markdown"`
}

View File

@@ -4,6 +4,8 @@ import (
"fmt"
"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"
@@ -37,6 +39,13 @@ func (r *Releasers) GetReleaser() (Releaser, error) {
case github.GITHUB:
log.Debugf("initialize new %s-provider", github.GITHUB)
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 nil, fmt.Errorf("could not initialize a releaser from this type: %s", r.config.Release)
}

View File

@@ -3,9 +3,11 @@ package util
import (
"archive/zip"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
@@ -25,6 +27,27 @@ func CreateBearerHTTPClient(ctx context.Context, token string) *http.Client {
return client
}
// AddHeaderTransport struct
type AddHeaderTransport struct {
T http.RoundTripper
key string
value string
}
// RoundTrip add header
func (adt *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Add(adt.key, adt.value)
return adt.T.RoundTrip(req)
}
//NewAddHeaderTransport to add default header
func NewAddHeaderTransport(T http.RoundTripper, key, value string) *AddHeaderTransport {
if T == nil {
T = http.DefaultTransport
}
return &AddHeaderTransport{T, key, value}
}
// GetAccessToken lookup for the providers accesstoken
func GetAccessToken(providerName string) (string, error) {
var token string
@@ -45,7 +68,9 @@ func GetAccessToken(providerName string) (string, error) {
func PrepareAssets(repository string, assets []config.Asset) ([]*string, error) {
filesToUpload := []*string{}
for _, asset := range assets {
if asset.Compress {
if asset.Name == "" {
return nil, fmt.Errorf("asset name declaration is empty, please check your configuration file")
} else if asset.Compress {
log.Debugf("Asset %s will now be compressed", asset.Name)
log.Debugf("Repo url %s", repository)
zipNameWithPath, err := zipFile(repository, asset.Name)
@@ -65,6 +90,12 @@ func PrepareAssets(repository string, assets []config.Asset) ([]*string, error)
// ZipFile compress given file in zip format
func zipFile(repository string, file string) (string, error) {
fileToZip, err := os.Open(repository + "/" + file)
if err != nil {
return "", err
}
defer fileToZip.Close()
zipFileName := fmt.Sprintf("%s/%s.zip", strings.TrimSuffix(repository, "/"), file)
zipFile, err := os.Create(zipFileName)
@@ -75,12 +106,6 @@ func zipFile(repository string, file string) (string, error) {
defer zipFile.Close()
fileToZip, err := os.Open(repository + "/" + file)
if err != nil {
return "", err
}
defer fileToZip.Close()
fileToZipInfo, err := fileToZip.Stat()
if err != nil {
return "", err
@@ -107,3 +132,45 @@ func zipFile(repository string, file string) (string, error) {
return zipFileName, nil
}
//PathEscape to be url save
func PathEscape(s string) string {
return strings.Replace(url.PathEscape(s), ".", "%2E", -1)
}
// Do request for client
func Do(client *http.Client, req *http.Request, v interface{}) (*http.Response, error) {
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case 200, 201, 202, 204:
if v != nil {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
}
}
}
return resp, err
}
// IsValidResult validates response code
func IsValidResult(resp *http.Response) error {
switch resp.StatusCode {
case 200, 201, 202, 204:
return nil
default:
return fmt.Errorf("%s %s: %d", resp.Request.Method, resp.Request.URL, resp.StatusCode)
}
}
// ShouldRetry request
func ShouldRetry(resp *http.Response) bool {
return resp.StatusCode == http.StatusTooManyRequests
}

View File

@@ -3,9 +3,17 @@ package util_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
log "github.com/sirupsen/logrus"
"github.com/Nightapes/go-semantic-release/pkg/config"
"github.com/stretchr/testify/assert"
@@ -41,3 +49,182 @@ func TestGetAccessToken(t *testing.T) {
os.Unsetenv(envName)
}
}
type testDoubleFiles struct {
testFiles []config.Asset
valid bool
}
var files = []testDoubleFiles{
testDoubleFiles{
testFiles: []config.Asset{
config.Asset{
Name: "file0",
Compress: true,
},
config.Asset{
Name: "file1",
Compress: true,
},
},
valid: true,
},
testDoubleFiles{
testFiles: []config.Asset{
config.Asset{
Name: "",
Compress: true,
},
config.Asset{
Name: "",
Compress: false,
},
},
valid: false,
},
}
func TestPrepareAssets(t *testing.T) {
for _, testObject := range files {
workDir, _ := os.Getwd()
filesToDelete := []string{}
for _, testFile := range testObject.testFiles {
if testFile.Name != "" {
filesToDelete = append(filesToDelete, testFile.Name)
file, err := os.Create(testFile.Name)
if err != nil {
fmt.Print(err.Error())
}
defer file.Close()
if testFile.Compress {
filesToDelete = append(filesToDelete, testFile.Name+".zip")
}
}
}
preparedFiles, err := util.PrepareAssets(workDir, testObject.testFiles)
if err == nil {
assert.Equal(t, 2, len(preparedFiles))
}
assert.Equal(t, testObject.valid, err == nil)
for _, file := range filesToDelete {
if err := os.Remove(file); err != nil {
fmt.Println(err.Error())
}
}
}
}
func TestShouldRetry(t *testing.T) {
assert.True(t, util.ShouldRetry(&http.Response{StatusCode: 429}))
assert.False(t, util.ShouldRetry(&http.Response{StatusCode: 200}))
}
func TestIsValidResult(t *testing.T) {
assert.NoError(t, util.IsValidResult(&http.Response{StatusCode: 200}))
assert.NoError(t, util.IsValidResult(&http.Response{StatusCode: 201}))
assert.NoError(t, util.IsValidResult(&http.Response{StatusCode: 202}))
assert.NoError(t, util.IsValidResult(&http.Response{StatusCode: 204}))
u, err := url.Parse("https://localhost")
assert.NoError(t, err)
assert.Error(t, util.IsValidResult(&http.Response{StatusCode: 500, Request: &http.Request{
Method: "POST",
URL: u,
}}))
}
func TestPathEscape(t *testing.T) {
assert.Equal(t, "test%2Ftest", util.PathEscape("test/test"))
assert.Equal(t, "test", util.PathEscape("test"))
assert.Equal(t, "test%2Etest", util.PathEscape("test.test"))
}
type example struct {
Test string `json:"test"`
}
func TestDoAndRoundTrip(t *testing.T) {
tokenHeader := util.NewAddHeaderTransport(nil, "PRIVATE-TOKEN", "aToken")
acceptHeader := util.NewAddHeaderTransport(tokenHeader, "Accept", "application/json")
httpClient := &http.Client{
Transport: acceptHeader,
Timeout: time.Second * 60,
}
testsDoMethod := []struct {
statusCode int
body string
responseBody interface{}
responseBodyType interface{}
hasError bool
path string
}{
{
statusCode: 200,
body: `{"test" : "hallo"}`,
responseBody: &example{
Test: "hallo",
},
responseBodyType: &example{},
hasError: false,
path: "",
},
{
statusCode: 400,
body: `{"test" : "hallo"}`,
responseBody: &example{},
responseBodyType: &example{},
hasError: false,
path: "",
},
{
statusCode: 200,
body: `{"test" : "hallo"}`,
hasError: true,
responseBody: &example{},
responseBodyType: &example{},
path: "broken",
},
}
for _, testOject := range testsDoMethod {
testServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
log.Infof("Got call from %s %s", req.Method, req.URL.String())
assert.Equal(t, req.Header.Get("PRIVATE-TOKEN"), "aToken")
assert.Equal(t, req.Header.Get("Accept"), "application/json")
rw.WriteHeader(testOject.statusCode)
rw.Header().Set("Content-Type", "application/json")
if _, err := rw.Write([]byte(testOject.body)); err != nil {
log.Info(err)
}
}))
req, err := http.NewRequest("POST", testServer.URL+testOject.path, nil)
assert.NoError(t, err)
resp, err := util.Do(httpClient, req, testOject.responseBodyType)
assert.Equal(t, testOject.hasError, err != nil)
if !testOject.hasError {
assert.Equal(t, testOject.statusCode, resp.StatusCode)
assert.Equal(t, testOject.responseBody, testOject.responseBodyType)
}
testServer.Close()
}
}

View File

@@ -6,16 +6,18 @@ import (
//ReleaseVersion struct
type ReleaseVersion struct {
Last ReleaseVersionEntry
Next ReleaseVersionEntry
Branch string
Draft bool
Last ReleaseVersionEntry `yaml:"last"`
Next ReleaseVersionEntry `yaml:"next"`
Branch string `yaml:"branch"`
Draft bool `yaml:"draft"`
Commits map[Release][]AnalyzedCommit `yaml:"commits"`
}
//ReleaseVersionEntry struct
type ReleaseVersionEntry struct {
Commit string
Version *semver.Version
Commit string `yaml:"commit"`
VersionString string `yaml:"version"`
Version *semver.Version `yaml:"-"`
}
//GeneratedChangelog struct
@@ -31,3 +33,27 @@ type ChangelogTemplateConfig struct {
Hash string
Version string
}
//AnalyzedCommit struct
type AnalyzedCommit struct {
Commit Commit `yaml:"commit"`
ParsedMessage string `yaml:"parsedMessage"`
Scope Scope `yaml:"scope"`
ParsedBreakingChangeMessage string `yaml:"parsedBreakingChangeMessage"`
Tag string `yaml:"tag"`
TagString string `yaml:"tagString"`
Print bool `yaml:"print"`
}
//Scope of the commit, like feat, fix,..
type Scope string
//Release types, like major
type Release string
// Commit struct
type Commit struct {
Message string `yaml:"message"`
Author string `yaml:"author"`
Hash string `yaml:"hash"`
}

View File

@@ -29,6 +29,13 @@ type GitHubProvider struct {
AccessToken string
}
// GitLabProvider struct
type GitLabProvider struct {
Repo string `yaml:"repo"`
CustomURL string `yaml:"customUrl,omitempty"`
AccessToken string
}
// ReleaseConfig struct
type ReleaseConfig struct {
CommitFormat string `yaml:"commitFormat"`
@@ -36,6 +43,7 @@ type ReleaseConfig struct {
Changelog ChangelogConfig `yaml:"changelog,omitempty"`
Release string `yaml:"release,omitempty"`
GitHubProvider GitHubProvider `yaml:"github,omitempty"`
GitLabProvider GitLabProvider `yaml:"gitlab,omitempty"`
Assets []Asset `yaml:"assets"`
ReleaseTitle string `yaml:"title"`
IsPreRelease, IsDraft bool
@@ -55,7 +63,7 @@ func Read(configPath string) (*ReleaseConfig, error) {
return &ReleaseConfig{}, err
}
log.Debugf("Found config %+v", releaseConfig)
log.Tracef("Found config %+v", releaseConfig)
return &releaseConfig, nil
}

112
pkg/config/config_test.go Normal file
View File

@@ -0,0 +1,112 @@
package config_test
import (
"testing"
"github.com/Nightapes/go-semantic-release/pkg/config"
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path"
)
func TestReadCacheNotFound(t *testing.T) {
_, err := config.Read("notfound/dir")
assert.Errorf(t, err, "Read non exsiting file")
}
func TestReadCacheInvalidContent(t *testing.T) {
dir, err := ioutil.TempDir("", "prefix")
assert.NoError(t, err)
defer os.RemoveAll(dir)
completePath := path.Join(path.Dir(dir), ".release.yml")
brokenContent := []byte("hello broken\ngo: lang\n")
err = ioutil.WriteFile(completePath, brokenContent, 0644)
assert.NoError(t, err)
_, readError := config.Read(completePath)
assert.Errorf(t, readError, "Should give error, when broken content")
}
func TestWriteAndReadCache(t *testing.T) {
dir, err := ioutil.TempDir("", "prefix")
assert.NoError(t, err)
defer os.RemoveAll(dir)
completePath := path.Join(path.Dir(dir), ".release.yml")
content := []byte(`
commitFormat: angular
title: "go-semantic-release release"
branch:
master: release
rc: rc
beta: beta
alpha: alpha
add_git_releases: alpha
changelog:
printAll: false
template: ''
templatePath: ''
release: 'github'
assets:
- name: ./build/go-semantic-release
compress: false
github:
repo: "go-semantic-release"
user: "nightapes"
customUrl: ""
`)
err = ioutil.WriteFile(completePath, content, 0644)
assert.NoError(t, err)
result, readError := config.Read(completePath)
assert.NoErrorf(t, readError, "Should read file")
assert.EqualValues(t, &config.ReleaseConfig{
CommitFormat: "angular",
Branch: map[string]string{"add_git_releases": "alpha", "alpha": "alpha", "beta": "beta", "master": "release", "rc": "rc"},
Changelog: config.ChangelogConfig{
PrintAll: false,
Template: "",
TemplatePath: ""},
Release: "github",
GitHubProvider: config.GitHubProvider{
Repo: "go-semantic-release",
User: "nightapes",
CustomURL: "",
AccessToken: ""},
Assets: []config.Asset{
config.Asset{
Name: "./build/go-semantic-release",
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

@@ -1,87 +0,0 @@
package semanticrelease
import (
"strconv"
"strings"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/cache"
"github.com/Nightapes/go-semantic-release/internal/shared"
log "github.com/sirupsen/logrus"
)
func (s *SemanticRelease) incPrerelease(preReleaseType string, version semver.Version) semver.Version {
defaultPrerelease := preReleaseType + ".0"
if version.Prerelease() == "" || !strings.HasPrefix(version.Prerelease(), preReleaseType) {
version, _ = version.SetPrerelease(defaultPrerelease)
} else {
parts := strings.Split(version.Prerelease(), ".")
if len(parts) == 2 {
i, err := strconv.Atoi(parts[1])
if err != nil {
version, _ = version.SetPrerelease(defaultPrerelease)
log.Warnf("Could not parse release tag %s, use version %s", version.Prerelease(), version.String())
} else {
version, _ = version.SetPrerelease(preReleaseType + "." + strconv.Itoa((i + 1)))
}
} else {
version, _ = version.SetPrerelease(defaultPrerelease)
log.Warnf("Could not parse release tag %s, use version %s", version.Prerelease(), version.String())
}
}
return version
}
func (s *SemanticRelease) saveToCache(releaseVersion shared.ReleaseVersion) error {
toCache := cache.ReleaseVersion{
Next: cache.ReleaseVersionEntry{
Commit: releaseVersion.Next.Commit,
Version: releaseVersion.Next.Version.String(),
},
Last: cache.ReleaseVersionEntry{
Commit: releaseVersion.Last.Commit,
Version: releaseVersion.Last.Version.String(),
},
Branch: releaseVersion.Branch,
}
log.Debugf("Save %s with hash %s to cache", releaseVersion.Next.Version.String(), releaseVersion.Next.Commit)
return cache.Write(s.repository, toCache)
}
func (s *SemanticRelease) readFromCache(currentHash string) (*shared.ReleaseVersion, error) {
content, err := cache.Read(s.repository)
if err == nil && content.Next.Commit == currentHash {
nextVersion, err := semver.NewVersion(content.Next.Version)
if err != nil {
return nil, err
}
lastVersion, err := semver.NewVersion(content.Last.Version)
if err != nil {
return nil, err
}
releaseVersion := &shared.ReleaseVersion{
Next: shared.ReleaseVersionEntry{
Commit: content.Next.Commit,
Version: nextVersion,
},
Last: shared.ReleaseVersionEntry{
Commit: content.Last.Commit,
Version: lastVersion,
},
Branch: content.Branch,
}
log.Infof("Found cache, will return cached version %s", content.Next.Version)
return releaseVersion, nil
}
log.Debugf("Mismatch git and version file %s - %s", content.Next.Commit, currentHash)
return nil, nil
}

View File

@@ -1,13 +1,14 @@
package semanticrelease
import (
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/Masterminds/semver"
"github.com/Nightapes/go-semantic-release/internal/analyzer"
"github.com/Nightapes/go-semantic-release/internal/cache"
"github.com/Nightapes/go-semantic-release/internal/calculator"
"github.com/Nightapes/go-semantic-release/internal/changelog"
"github.com/Nightapes/go-semantic-release/internal/ci"
"github.com/Nightapes/go-semantic-release/internal/gitutil"
@@ -23,6 +24,7 @@ type SemanticRelease struct {
config *config.ReleaseConfig
gitutil *gitutil.GitUtil
analyzer *analyzer.Analyzer
calculator *calculator.Calculator
releaser releaser.Releaser
repository string
}
@@ -50,32 +52,25 @@ func New(c *config.ReleaseConfig, repository string) (*SemanticRelease, error) {
releaser: releaser,
analyzer: analyzer,
repository: repository,
calculator: calculator.New(),
}, nil
}
//GetCIProvider result with ci config
func (s *SemanticRelease) GetCIProvider() (*ci.ProviderConfig, error) {
return ci.GetCIProvider(s.gitutil, ci.ReadAllEnvs())
}
// GetNextVersion from .version or calculate new from commits
func (s *SemanticRelease) GetNextVersion(force bool) (*shared.ReleaseVersion, error) {
provider, err := ci.GetCIProvider(s.gitutil, ci.ReadAllEnvs())
if err != nil {
fakeVersion, _ := semver.NewVersion("0.0.0-fake.0")
log.Warnf("Will not calculate version, set fake version. Could not find CI Provider, if running locally, set env CI=true")
return &shared.ReleaseVersion{
Next: shared.ReleaseVersionEntry{
Commit: "",
Version: fakeVersion,
},
}, nil
}
func (s *SemanticRelease) GetNextVersion(provider *ci.ProviderConfig, force bool) (*shared.ReleaseVersion, error) {
log.Debugf("Ignore .version file if exits, %t", force)
if !force {
releaseVersion, err := s.readFromCache(provider.Commit)
releaseVersion, err := cache.Read(s.repository)
if err != nil {
return nil, err
}
if releaseVersion != nil {
if releaseVersion.Next.Commit == provider.Commit && releaseVersion != nil {
return releaseVersion, nil
}
}
@@ -85,16 +80,12 @@ func (s *SemanticRelease) GetNextVersion(force bool) (*shared.ReleaseVersion, er
return nil, err
}
var newVersion semver.Version
firstRelease := false
if lastVersion == nil {
defaultVersion, _ := semver.NewVersion("1.0.0")
newVersion = *defaultVersion
lastVersion = defaultVersion
firstRelease = true
} else {
newVersion = *lastVersion
}
commits, err := s.gitutil.GetCommits(lastVersionHash)
@@ -104,32 +95,15 @@ func (s *SemanticRelease) GetNextVersion(force bool) (*shared.ReleaseVersion, er
log.Debugf("Found %d commits till last release", len(commits))
a, err := analyzer.New(s.config.CommitFormat, s.config.Changelog)
if err != nil {
return nil, err
}
result := a.Analyze(commits)
analyzedCommits := s.analyzer.Analyze(commits)
isDraft := false
var newVersion semver.Version
for branch, releaseType := range s.config.Branch {
if provider.Branch == branch || strings.HasPrefix(provider.Branch, branch) {
log.Debugf("Found branch config for branch %s with release type %s", provider.Branch, releaseType)
switch releaseType {
case "beta", "alpha":
isDraft = true
newVersion = s.incPrerelease(releaseType, newVersion)
case "rc":
newVersion = s.incPrerelease(releaseType, newVersion)
case "release":
if !firstRelease {
if len(result["major"]) > 0 {
newVersion = newVersion.IncMajor()
} else if len(result["minor"]) > 0 {
newVersion = newVersion.IncMinor()
} else if len(result["patch"]) > 0 {
newVersion = newVersion.IncPatch()
}
}
}
newVersion, isDraft = s.calculator.CalculateNewVersion(analyzedCommits, lastVersion, releaseType, firstRelease)
break
}
}
@@ -142,12 +116,13 @@ func (s *SemanticRelease) GetNextVersion(force bool) (*shared.ReleaseVersion, er
Commit: lastVersionHash,
Version: lastVersion,
},
Branch: provider.Branch,
Draft: isDraft,
Branch: provider.Branch,
Draft: isDraft,
Commits: analyzedCommits,
}
log.Infof("New version %s -> %s", lastVersion.String(), newVersion.String())
err = s.saveToCache(releaseVersion)
err = cache.Write(s.repository, releaseVersion)
if err != nil {
return nil, err
}
@@ -155,19 +130,13 @@ func (s *SemanticRelease) GetNextVersion(force bool) (*shared.ReleaseVersion, er
}
//SetVersion for git repository
func (s *SemanticRelease) SetVersion(version string) error {
func (s *SemanticRelease) SetVersion(provider *ci.ProviderConfig, version string) error {
newVersion, err := semver.NewVersion(version)
if err != nil {
return err
}
provider, err := ci.GetCIProvider(s.gitutil, ci.ReadAllEnvs())
if err != nil {
return fmt.Errorf("will not set version. Could not find CI Provider, if running locally, set env CI=true")
}
lastVersion, lastVersionHash, err := s.gitutil.GetLastVersion()
if err != nil {
return err
@@ -176,7 +145,7 @@ func (s *SemanticRelease) SetVersion(version string) error {
lastVersion, _ = semver.NewVersion("1.0.0")
}
return s.saveToCache(shared.ReleaseVersion{
return cache.Write(s.repository, shared.ReleaseVersion{
Next: shared.ReleaseVersionEntry{
Commit: provider.Commit,
Version: newVersion,
@@ -191,22 +160,13 @@ func (s *SemanticRelease) SetVersion(version string) error {
// GetChangelog from last version till now
func (s *SemanticRelease) GetChangelog(releaseVersion *shared.ReleaseVersion) (*shared.GeneratedChangelog, error) {
commits, err := s.gitutil.GetCommits(releaseVersion.Last.Commit)
if err != nil {
return nil, err
}
result := s.analyzer.Analyze(commits)
log.Debugf("Found %d commits till last release", len(commits))
c := changelog.New(s.config, s.analyzer.GetRules(), time.Now())
return c.GenerateChanglog(shared.ChangelogTemplateConfig{
Version: releaseVersion.Next.Version.String(),
Hash: releaseVersion.Last.Commit,
CommitURL: s.releaser.GetCommitURL(),
CompareURL: s.releaser.GetCompareURL(releaseVersion.Last.Version.String(), releaseVersion.Next.Version.String()),
}, result)
}, releaseVersion.Commits)
}
@@ -216,14 +176,7 @@ func (s *SemanticRelease) WriteChangeLog(changelogContent, file string) error {
}
// Release pusblish release to provider
func (s *SemanticRelease) Release(force bool) error {
provider, err := ci.GetCIProvider(s.gitutil, ci.ReadAllEnvs())
if err != nil {
log.Debugf("Will not perform a new release. Could not find CI Provider")
return nil
}
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")
@@ -235,12 +188,17 @@ func (s *SemanticRelease) Release(force bool) error {
return nil
}
releaseVersion, err := s.GetNextVersion(force)
releaseVersion, err := s.GetNextVersion(provider, force)
if err != nil {
log.Debugf("Could not get next version")
return err
}
if releaseVersion.Next.Version.Equal(releaseVersion.Last.Version) {
log.Infof("No new version, no release needed %s <> %s", releaseVersion.Next.Version.String(), releaseVersion.Last.Version.String())
return nil
}
generatedChanglog, err := s.GetChangelog(releaseVersion)
if err != nil {
log.Debugf("Could not get changelog")