diff --git a/.gitignore b/.gitignore index 13ea6d3..5999076 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -semver \ No newline at end of file +semver-gen \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile index cf952fe..fce7efd 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,10 @@ all: build build: - @go build -o semver *.go + @go build -o semver-gen *.go run: build - @./semver + @./semver-gen test: @go test ./... -v -race -cover \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..d06a117 --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +## Semantic version generator + +Project created overnight, to prove that management of semantic versioning is NOT painful and do not require arguments and debates within the team. Simple, clean and only thing the project team should need to agree to are the keywords. + +- [Semantic version generator](#semantic-version-generator) + - [How does it work](#how-does-it-work) + - [Usage](#usage) + - [Calculations example](#calculations-example) + - [Example configuration](#example-configuration) + - [Good to know](#good-to-know) + +### How does it work + +* Binary clones the github repository +* Iterates through the list of commits looking for the keywords specified in config file for additional bumps of versions +* Returns the semantic version which can be included in the release + +### Usage + +```bash + bash$ ./semver-gen -g +SEMVER 5.1.1 +``` + +Available flags: + +```yaml +Flags: + -c, --config string Path to config file (default "config.yaml") + -g, --generate Generate semantic version + -h, --help help for this command + -r, --repository string Repository URL. If not specified local dir will be used. (default "https://github.com/lukaszraczylo/simple-gql-client") +``` + +#### Calculations example + +* 0.0.1 - PATCH - starting commit +* 0.0.2 - PATCH - another commit +* 0.1.0 - MINOR - after commit with word 'Change' => increment MINOR, reset PATCH +* 0.1.1 - PATCH - additional commit +* 1.0.1 - MAJOR - commit with word 'BREAKING' = > INCREMENT MAJOR, reset MINOR +* 1.0.2 - PATCH - another commit + +#### Example configuration + +```yaml +version: 1 +force: + major: 1 + minor: 0 + patch: 1 +wording: + patch: + - update + - initial + minor: + - add + - change + - improve + major: + - breaking + - the # For testing purposes +``` + +* version: is not respected at the moment, introduced for potential backwards compatibility in future +* force: sets the "starting" version, you don't need to specify this section as the default is always `0` +* wording: words the program should look for in the git commits to increment (patch|minor|major) + +### Good to know + +* Word matching uses fuzzy search AND is case INSENSITIVE +* I do not recommend using common words ( like "the" from the example configuration ) \ No newline at end of file diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..2c5f8dc --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,187 @@ +/* +Copyright © 2021 LUKASZ RACZYLO + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cmd + +import ( + "fmt" + "net/url" + "os" + "sort" + "strings" + "time" + + git "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing/object" + "github.com/lithammer/fuzzysearch/fuzzy" + "github.com/lukaszraczylo/zero" + "github.com/spf13/viper" +) + +var ( + err error + repo *Setup +) + +type Wording struct { + Patch []string + Minor []string + Major []string +} + +type Force struct { + Patch int + Minor int + Major int +} + +type SemVer struct { + Patch int + Minor int + Major int +} + +type Setup struct { + RepositoryName string + RepositoryLocalPath string + RepositoryHandler *git.Repository + Commits []CommitDetails + Semver SemVer + Wording Wording + Force Force + Generate bool + LocalConfigFile string +} + +type CommitDetails struct { + Hash string + Author string + Message string + Timestamp time.Time +} + +func checkMatches(content []string, targets []string) bool { + var r []string + for _, tgt := range targets { + r = fuzzy.FindFold(tgt, content) + } + return (len(r) > 0) +} + +func (s *Setup) CalculateSemver() SemVer { + for _, commit := range s.Commits { + s.Semver.Patch++ + commitSlice := strings.Split(commit.Message, " ") + matchPatch := checkMatches(commitSlice, s.Wording.Patch) + matchMinor := checkMatches(commitSlice, s.Wording.Minor) + matchMajor := checkMatches(commitSlice, s.Wording.Major) + if matchPatch { + s.Semver.Patch++ + // fmt.Println("Patch version bumped:", commit.Message) + } + if matchMinor { + s.Semver.Minor++ + s.Semver.Patch = 1 + // fmt.Println("Minor version bumped:", commit.Message) + } + if matchMajor { + s.Semver.Major++ + s.Semver.Minor = 0 + s.Semver.Patch = 1 + // fmt.Println("Major version bumped:", commit.Message) + } + } + return s.Semver +} + +func (s *Setup) ListCommits() ([]CommitDetails, error) { + ref, err := s.RepositoryHandler.Head() + if err != nil { + return []CommitDetails{}, err + } + commitsList, err := s.RepositoryHandler.Log(&git.LogOptions{From: ref.Hash(), Order: git.LogOrderBSF}) + if err != nil { + return []CommitDetails{}, err + } + commitsList.ForEach(func(c *object.Commit) error { + s.Commits = append(s.Commits, CommitDetails{Hash: c.Hash.String(), Author: c.Author.String(), Message: c.Message, Timestamp: c.Author.When}) + sort.Slice(s.Commits, func(i, j int) bool { return s.Commits[i].Timestamp.Unix() < s.Commits[j].Timestamp.Unix() }) + return nil + }) + return s.Commits, err +} + +func (s *Setup) Prepare() error { + u, _ := url.Parse(s.RepositoryName) + s.RepositoryLocalPath = fmt.Sprintf("/tmp/foo/%s", u.Path) + os.RemoveAll(s.RepositoryLocalPath) + s.RepositoryHandler, err = git.PlainClone(s.RepositoryLocalPath, false, &git.CloneOptions{ + URL: s.RepositoryName, + }) + if err != nil { + fmt.Println("Unable to reach repository", err.Error()) + } + return err +} + +func (s *Setup) ForcedVersioning() { + if !zero.IsZero(s.Force.Major) { + s.Semver.Major = s.Force.Major + } + if !zero.IsZero(s.Force.Minor) { + s.Semver.Minor = s.Force.Minor + } + if !zero.IsZero(s.Force.Patch) { + s.Semver.Patch = s.Force.Patch + } +} + +func (s *Setup) ReadConfig(file string) error { + viper.SetConfigFile(file) + err := viper.ReadInConfig() + if err != nil { + err = fmt.Errorf("Fatal error config file: %s \n", err) + return err + } + viper.UnmarshalKey("wording", &s.Wording) + viper.UnmarshalKey("force", &s.Force) + return err +} + +func (s *Setup) getSemver() string { + return fmt.Sprintf("%d.%d.%d", s.Semver.Major, s.Semver.Minor, s.Semver.Patch) +} + +func (s *Setup) parseFlags() { + +} + +func main() { + if repo.Generate { + err := repo.ReadConfig(repo.LocalConfigFile) + if err != nil { + panic(err) + } + err = repo.Prepare() + if err != nil { + panic(err) + } + repo.ListCommits() + repo.ForcedVersioning() + repo.CalculateSemver() + fmt.Println("SEMVER", repo.getSemver()) + } +} diff --git a/cmd/main_test.go b/cmd/main_test.go new file mode 100644 index 0000000..4ef9aa3 --- /dev/null +++ b/cmd/main_test.go @@ -0,0 +1,358 @@ +/* +Copyright © 2021 LUKASZ RACZYLO + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "os" + "strings" + "testing" + + git "github.com/go-git/go-git/v5" + "github.com/lukaszraczylo/zero" + assertions "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" +) + +type Tests struct { + suite.Suite +} + +var ( + assert *assertions.Assertions +) + +func (suite *Tests) SetupTest() { + assert = assertions.New(suite.T()) +} + +func TestSuite(t *testing.T) { + suite.Run(t, new(Tests)) +} + +func (suite *Tests) TestSetup_getSemver() { + type fields struct { + Semver SemVer + } + tests := []struct { + name string + fields fields + want string + }{ + { + name: "Return 1.3.7", + fields: fields{ + Semver: SemVer{ + Major: 1, + Minor: 3, + Patch: 7, + }, + }, + want: "1.3.7", + }, + } + for _, tt := range tests { + suite.T().Run(tt.name, func(t *testing.T) { + s := &Setup{ + Semver: tt.fields.Semver, + } + got := s.getSemver() + assert.Equal(tt.want, got, "Unexpected result in "+tt.name) + }) + } +} + +func (suite *Tests) TestSetup_ForcedVersioning() { + type fields struct { + Semver SemVer + Force Force + } + tests := []struct { + name string + fields fields + want string + }{ + { + name: "No versioning", + want: "0.0.0", + }, + { + name: "Major version set", + fields: fields{ + Force: Force{ + Major: 2, + }, + }, + want: "2.0.0", + }, + { + name: "Minor version set", + fields: fields{ + Force: Force{ + Minor: 3, + }, + }, + want: "0.3.0", + }, + { + name: "Patch version set", + fields: fields{ + Force: Force{ + Patch: 7, + }, + }, + want: "0.0.7", + }, + } + for _, tt := range tests { + suite.T().Run(tt.name, func(t *testing.T) { + s := &Setup{ + Semver: tt.fields.Semver, + Force: tt.fields.Force, + } + s.ForcedVersioning() + got := s.getSemver() + assert.Equal(tt.want, got, "Unexpected result in "+tt.name) + }) + } +} + +func (suite *Tests) TestSetup_Prepare() { + type fields struct { + RepositoryName string + RepositoryLocalPath string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + { + name: "Test repository lukaszraczylo/simple-gql-client", + fields: fields{ + RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client", + }, + wantErr: true, + }, + { + name: "Test non-existing repository", + fields: fields{ + RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client-dead", + }, + wantErr: true, + }, + } + for _, tt := range tests { + suite.T().Run(tt.name, func(t *testing.T) { + s := &Setup{ + RepositoryName: tt.fields.RepositoryName, + } + s.Prepare() + if _, err := os.Stat(s.RepositoryLocalPath); os.IsNotExist(err) { + if !tt.wantErr { + assert.NoError(err, "Error should not be present in "+tt.name) + } else { + assert.Error(err, "Error should be present in "+tt.name) + } + } + }) + } +} + +func (suite *Tests) TestSetup_ReadConfig() { + type fields struct { + Wording Wording + Force Force + } + type args struct { + file string + } + tests := []struct { + name string + fields fields + args args + wordingEmpty bool + wantErr bool + }{ + { + name: "Test non-existent config file", + args: args{ + file: "random-file-name.yaml", + }, + wordingEmpty: true, + wantErr: true, + }, + { + name: "Test existing config file", + args: args{ + file: "../config.yaml", + }, + wordingEmpty: false, + wantErr: false, + }, + } + for _, tt := range tests { + suite.T().Run(tt.name, func(t *testing.T) { + s := &Setup{} + err := s.ReadConfig(tt.args.file) + if !tt.wantErr { + assert.NoError(err, "Error should not be present in "+tt.name) + } else { + assert.Error(err, "Error should be present in "+tt.name) + } + assert.Equal(tt.wordingEmpty, zero.IsZero(s.Wording), "Unexpected wording count "+tt.name+":", s.Wording) + }) + } +} + +func (suite *Tests) Test_checkMatches() { + type args struct { + content []string + targets []string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "No match", + args: args{ + content: strings.Fields("Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space"), + targets: []string{"github", "repository", "test"}, + }, + want: false, + }, + { + name: "Match", + args: args{ + content: strings.Fields("Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space"), + targets: []string{"github", "repository", "instance"}, + }, + want: true, + }, + } + for _, tt := range tests { + suite.T().Run(tt.name, func(t *testing.T) { + got := checkMatches(tt.args.content, tt.args.targets) + assert.Equal(tt.want, got, "Unexpected result in "+tt.name) + }) + } +} + +func (suite *Tests) TestSetup_ListCommits() { + type fields struct { + RepositoryName string + RepositoryLocalPath string + RepositoryHandler *git.Repository + Commits []CommitDetails + Semver SemVer + Wording Wording + Force Force + } + + tests := []struct { + name string + fields fields + noCommits bool + wantErr bool + }{ + { + name: "List commits from existing repository", + fields: fields{ + RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client", + }, + noCommits: false, + wantErr: false, + }, + { + name: "List commits from non-existing repository", + fields: fields{ + RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client-dead", + }, + noCommits: true, + wantErr: true, + }, + } + for _, tt := range tests { + suite.T().Run(tt.name, func(t *testing.T) { + s := &Setup{ + RepositoryName: tt.fields.RepositoryName, + } + s.Prepare() + listOfCommits, err := s.ListCommits() + if !tt.wantErr { + assert.NoError(err, "Error should not be present in "+tt.name) + } else { + assert.Error(err, "Error should be present in "+tt.name) + } + assert.Equal(tt.noCommits, zero.IsZero(listOfCommits), "Unexpected commits count"+tt.name) + }) + } +} + +func (suite *Tests) TestSetup_CalculateSemver() { + type fields struct { + RepositoryName string + } + type wantSemver struct { + Major int + Minor int + Patch int + } + tests := []struct { + name string + fields fields + wantSemver wantSemver + }{ + { + name: "Test on existing repository", + fields: fields{ + RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client", + }, + wantSemver: wantSemver{ + Major: 5, + Minor: 1, + Patch: 1, + }, + }, + { + name: "Test on non-existing repository", + fields: fields{ + RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client-dead", + }, + wantSemver: wantSemver{ + Major: 1, // 1 because config file enforces MAJOR version + Minor: 0, + Patch: 0, + }, + }, + } + for _, tt := range tests { + suite.T().Run(tt.name, func(t *testing.T) { + s := &Setup{ + RepositoryName: tt.fields.RepositoryName, + } + s.ReadConfig("../config.yaml") + s.Prepare() + s.ListCommits() + s.ForcedVersioning() + semver := s.CalculateSemver() + assert.Equal(tt.wantSemver.Major, semver.Major, "Unexpected MAJOR semver result in "+tt.name) + assert.Equal(tt.wantSemver.Minor, semver.Minor, "Unexpected MINOR semver result in "+tt.name) + assert.Equal(tt.wantSemver.Patch, semver.Patch, "Unexpected PATCH semver result in "+tt.name) + }) + } +} diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..efacf86 --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,50 @@ +/* +Copyright © 2021 LUKASZ RACZYLO + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "os" + "strings" + + "github.com/spf13/cobra" +) + +var cfgFile string + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "semver-gen", + Short: "An effortless semantic version generator", + Long: `semver-gen // Lukasz Raczylo, raczylo.com + +Effortless semantic version generator with git commit keywords matching, allowing you to focus on the development. +Visit https://github.com/lukaszraczylo/semver-generator for more information, documentation and examples.`, + Run: func(cmd *cobra.Command, args []string) {}, +} + +func Execute() { + cobra.CheckErr(rootCmd.Execute()) +} + +func init() { + repo = &Setup{} + if !strings.HasSuffix(os.Args[0], ".test") { + rootCmd.PersistentFlags().StringVarP(&repo.RepositoryName, "repository", "r", "https://github.com/lukaszraczylo/simple-gql-client", "Repository URL. If not specified local dir will be used.") + rootCmd.PersistentFlags().StringVarP(&repo.LocalConfigFile, "config", "c", "config.yaml", "Path to config file") + rootCmd.PersistentFlags().BoolVarP(&repo.Generate, "generate", "g", true, "Generate semantic version") + main() + } +} diff --git a/config.yaml b/config.yaml index cd648ba..c785f3a 100644 --- a/config.yaml +++ b/config.yaml @@ -10,4 +10,5 @@ wording: - change - improve major: - - breaking \ No newline at end of file + - breaking + - the # For testing purposes \ No newline at end of file diff --git a/go.mod b/go.mod index fc56254..387d041 100644 --- a/go.mod +++ b/go.mod @@ -14,14 +14,17 @@ require ( github.com/lithammer/fuzzysearch v1.1.1 github.com/lukaszraczylo/zero v0.0.0-20160322155811-4a4535dd56e7 // indirect github.com/magiconair/properties v1.8.5 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/mapstructure v1.4.1 // indirect github.com/pelletier/go-toml v1.9.0 // indirect github.com/sergi/go-diff v1.2.0 // indirect github.com/spf13/afero v1.6.0 // indirect github.com/spf13/cast v1.3.1 // indirect + github.com/spf13/cobra v1.1.3 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/viper v1.7.1 + github.com/stretchr/testify v1.7.0 // indirect github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77 // indirect golang.org/x/crypto v0.0.0-20210506145944-38f3c27a63bf // indirect golang.org/x/net v0.0.0-20210508051633-16afe75a6701 // indirect diff --git a/go.sum b/go.sum index f52081a..1c3c082 100644 --- a/go.sum +++ b/go.sum @@ -39,9 +39,11 @@ github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= @@ -121,6 +123,8 @@ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2p github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= @@ -190,6 +194,7 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= @@ -203,6 +208,7 @@ github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7z github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= @@ -210,6 +216,7 @@ github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= @@ -225,6 +232,8 @@ github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M= +github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= @@ -233,6 +242,7 @@ github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/src-d/gcfg v1.4.0/go.mod h1:p/UMsR43ujA89BJY9duynAwIpvqEujIH/jFlfL7jWoI= @@ -242,6 +252,8 @@ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoH github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -418,6 +430,8 @@ gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/main.go b/main.go index 5619f38..dc04915 100644 --- a/main.go +++ b/main.go @@ -1,154 +1,22 @@ +/* +Copyright © 2021 LUKASZ RACZYLO + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ package main -import ( - "fmt" - "net/url" - "os" - "sort" - "strings" - "time" - - git "github.com/go-git/go-git/v5" - "github.com/go-git/go-git/v5/plumbing/object" - "github.com/lithammer/fuzzysearch/fuzzy" - "github.com/lukaszraczylo/zero" - "github.com/spf13/viper" -) - -var ( - err error -) - -type Wording struct { - Patch []string - Minor []string - Major []string -} - -type Force struct { - Patch int - Minor int - Major int -} - -type SemVer struct { - Patch int - Minor int - Major int -} - -type Setup struct { - RepositoryName string - RepositoryLocalPath string - RepositoryHandler *git.Repository - Commits []CommitDetails - Semver SemVer - Wording Wording - Force Force -} - -type CommitDetails struct { - Hash string - Author string - Message string - Timestamp time.Time -} - -func checkMatches(content []string, targets []string) bool { - var r []string - for _, tgt := range targets { - r = fuzzy.FindFold(tgt, content) - } - return (len(r) > 0) -} - -func (s *Setup) CalculateSemver() { - for _, commit := range s.Commits { - s.Semver.Patch++ - commitSlice := strings.Split(commit.Message, " ") - matchPatch := checkMatches(commitSlice, s.Wording.Patch) - matchMinor := checkMatches(commitSlice, s.Wording.Minor) - matchMajor := checkMatches(commitSlice, s.Wording.Major) - // fmt.Println(matchPatch, matchMinor, matchMajor, commit.Message, s.Wording.Patch, s.Wording.Minor, s.Wording.Major) - if matchPatch { - s.Semver.Patch++ - fmt.Println("Patch version bumped:", commit.Message) - } - if matchMinor { - s.Semver.Minor++ - s.Semver.Patch = 1 - fmt.Println("Minor version bumped:", commit.Message) - } - if matchMajor { - s.Semver.Major++ - s.Semver.Minor = 0 - s.Semver.Patch = 1 - fmt.Println("Major version bumped:", commit.Message) - } - } -} - -func (s *Setup) ListCommits() { - ref, _ := s.RepositoryHandler.Head() - commitsList, err := s.RepositoryHandler.Log(&git.LogOptions{From: ref.Hash(), Order: git.LogOrderBSF}) - if err != nil { - panic(err) - } - commitsList.ForEach(func(c *object.Commit) error { - s.Commits = append(s.Commits, CommitDetails{Hash: c.Hash.String(), Author: c.Author.String(), Message: c.Message, Timestamp: c.Author.When}) - sort.Slice(s.Commits, func(i, j int) bool { return s.Commits[i].Timestamp.Unix() < s.Commits[j].Timestamp.Unix() }) - return nil - }) -} - -func (s *Setup) Prepare() { - u, _ := url.Parse(s.RepositoryName) - s.RepositoryLocalPath = fmt.Sprintf("/tmp/foo/%s", u.Path) - os.RemoveAll(s.RepositoryLocalPath) - s.RepositoryHandler, err = git.PlainClone(s.RepositoryLocalPath, false, &git.CloneOptions{ - URL: s.RepositoryName, - }) - if err != nil { - panic(err) - } -} - -func (s *Setup) ForcedVersioning() { - if !zero.IsZero(s.Force.Major) { - s.Semver.Major = s.Force.Major - } - if !zero.IsZero(s.Force.Minor) { - s.Semver.Minor = s.Force.Minor - } - if !zero.IsZero(s.Force.Patch) { - s.Semver.Patch = s.Force.Patch - } -} - -func (s *Setup) ReadConfig(file string) { - viper.SetConfigFile(file) - viper.AddConfigPath(".") - err := viper.ReadInConfig() - if err != nil { - panic(fmt.Errorf("Fatal error config file: %s \n", err)) - } - viper.UnmarshalKey("wording", &s.Wording) - viper.UnmarshalKey("force", &s.Force) -} - -func (s *Setup) getSemver() string { - return fmt.Sprintf("%d.%d.%d", s.Semver.Major, s.Semver.Minor, s.Semver.Patch) -} +import "github.com/lukaszraczylo/semver-generator/cmd" func main() { - repo := &Setup{ - RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client", - } - repo.ReadConfig("config.yaml") - repo.Prepare() - fmt.Println("Repo local path:", repo.RepositoryLocalPath) - repo.ListCommits() - repo.ForcedVersioning() - repo.CalculateSemver() - fmt.Println("Calculated semver:", repo.getSemver()) + cmd.Execute() } diff --git a/main_test.go b/main_test.go deleted file mode 100644 index fd4e1e2..0000000 --- a/main_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "testing" - - git "github.com/go-git/go-git/v5" -) - -func TestSetup_getSemver(t *testing.T) { - type fields struct { - RepositoryName string - RepositoryLocalPath string - RepositoryHandler *git.Repository - Commits []CommitDetails - Semver SemVer - Wording Wording - } - tests := []struct { - name string - fields fields - want string - }{ - { - name: "Return 1.3.7", - fields: fields{ - Semver: SemVer{ - Major: 1, - Minor: 3, - Patch: 7, - }, - }, - want: "1.3.7", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - s := &Setup{ - RepositoryName: tt.fields.RepositoryName, - RepositoryLocalPath: tt.fields.RepositoryLocalPath, - RepositoryHandler: tt.fields.RepositoryHandler, - Commits: tt.fields.Commits, - Semver: tt.fields.Semver, - Wording: tt.fields.Wording, - } - if got := s.getSemver(); got != tt.want { - t.Errorf("Setup.getSemver() = %v, want %v", got, tt.want) - } - }) - } -}