├── .github ├── dependabot.yml └── workflows │ ├── build.yml │ └── create-release.yml ├── .gitignore ├── .golangci.yaml ├── .gommit.toml ├── .goreleaser.yaml ├── LICENSE ├── README.md ├── cmd ├── check.go ├── check_commit.go ├── check_commit_test.go ├── check_message.go ├── check_message_test.go ├── check_range.go ├── check_range_test.go ├── check_test.go ├── exit.go ├── root.go ├── ui.go ├── version.go └── version_test.go ├── features ├── .gommit-no-examples.toml ├── .gommit-no-matchers.toml ├── .gommit-wrong-regexp.toml ├── .gommit.toml ├── bad-commit.sh ├── bad-summary-message-commit.sh ├── repo-teardown.sh └── repo.sh ├── go.mod ├── go.sum ├── gommit ├── gommit.go ├── gommit_test.go ├── version.go └── version_test.go ├── main.go └── reference ├── reference_history.go └── reference_history_test.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gomod 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | pull-request-branch-name: 8 | separator: "-" 9 | open-pull-requests-limit: 10 10 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | tags: 6 | - v* 7 | branches: 8 | - master 9 | - main 10 | pull_request: 11 | permissions: 12 | contents: read 13 | 14 | jobs: 15 | call-workflow: 16 | uses: antham/go-workflow-github-action/.github/workflows/build.yml@master 17 | secrets: 18 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 19 | -------------------------------------------------------------------------------- /.github/workflows/create-release.yml: -------------------------------------------------------------------------------- 1 | name: Create the release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | permissions: 9 | contents: write 10 | 11 | jobs: 12 | call-workflow: 13 | uses: antham/go-workflow-github-action/.github/workflows/create-release.yml@master 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor/* 2 | /gommit/test/ 3 | /reference/test/ 4 | /coverage.txt 5 | /cmd/test/ 6 | /build/* 7 | /reference/shallow-repository-test/ 8 | /reference/testing-repository/ 9 | /cmd/testing-repository/ 10 | /gommit/testing-repository/ 11 | /cmd/test-repository/ 12 | /gommit/test-repository/ 13 | /reference/test-repository/ 14 | -------------------------------------------------------------------------------- /.golangci.yaml: -------------------------------------------------------------------------------- 1 | linters: 2 | enable: 3 | - gofumpt 4 | -------------------------------------------------------------------------------- /.gommit.toml: -------------------------------------------------------------------------------- 1 | [config] 2 | exclude-merge-commits=true 3 | check-summary-length=true 4 | summary-length=72 5 | 6 | [matchers] 7 | simple=".+? : [a-z0-9].+(?:\n)?" 8 | extended=".+? : [a-z0-9].+?\n(?:\n?.+)+(?:\n)?" 9 | dependabot="Bump.+?\n(?:\n?.+)+(?:\n)?" 10 | 11 | [examples] 12 | a_simple_commit=""" 13 | module : a commit message 14 | """ 15 | an_extended_commit=""" 16 | module : a commit message 17 | 18 | * first line 19 | * second line 20 | * and so on... 21 | """ 22 | -------------------------------------------------------------------------------- /.goreleaser.yaml: -------------------------------------------------------------------------------- 1 | before: 2 | hooks: 3 | - go mod tidy 4 | builds: 5 | - env: 6 | - CGO_ENABLED=0 7 | goos: 8 | - linux 9 | - windows 10 | - darwin 11 | goarch: 12 | - amd64 13 | ldflags: 14 | - -X 'github.com/antham/gommit/gommit.appVersion={{.Version}}' 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gommit [![codecov](https://codecov.io/gh/antham/gommit/branch/master/graph/badge.svg)](https://codecov.io/gh/antham/gommit) [![Go Report Card](https://goreportcard.com/badge/github.com/antham/gommit)](https://goreportcard.com/report/github.com/antham/gommit) [![GitHub tag](https://img.shields.io/github/tag/antham/gommit.svg)]() 2 | 3 | Gommit analyze commits messages to ensure they follow defined pattern. 4 | 5 | [![asciicast](https://asciinema.org/a/0j12qm7yay1kku7o3vrs67pv2.png)](https://asciinema.org/a/0j12qm7yay1kku7o3vrs67pv2) 6 | 7 | ## Summary 8 | 9 | - [Setup](#setup) 10 | - [Usage](#usage) 11 | - [Practical Usage](#practical-usage) 12 | - [Third Part Libraries](#third-part-libraries) 13 | 14 | ## Setup 15 | 16 | Download from release page according to your architecture gommit binary : https://github.com/antham/gommit/releases 17 | 18 | ### Define a file .gommit.toml 19 | 20 | Create a file `.gommit.toml` at the root of your project, for instance : 21 | 22 | ```toml 23 | [config] 24 | exclude-merge-commits=true 25 | check-summary-length=true 26 | summary-length=50 27 | 28 | [matchers] 29 | all="(?:ref|feat|test|fix|style)\\(.*?\\) : .*?\n(?:\n?(?:\\* | ).*?\n)*" 30 | 31 | [examples] 32 | a_simple_commit=""" 33 | [feat|test|ref|fix|style](module) : A commit message 34 | """ 35 | an_extended_commit=""" 36 | [feat|test|ref|fix|style](module) : A commit message 37 | 38 | * first line 39 | * second line 40 | * and so on... 41 | """ 42 | ``` 43 | 44 | #### Config 45 | 46 | - `exclude-merge-commits` : if set to true, will not check commit message for merge commit 47 | - `check-summary-length` : if set to true, check commit summary length, default is 50 characters 48 | - `summary-length` : you can override the default value summary length, which is 50 characters, this config is used only if check-summary-length is true 49 | 50 | #### Matchers 51 | 52 | You can define as many matchers you want using regexp, naming is up to you, they will all be compared against a commit message till one match. Regexps used support comments, possessive match, positive lookahead, negative lookahead, positive lookbehind, negative lookbehind, back reference, named back referenc and conditionals. 53 | 54 | #### Examples 55 | 56 | Provided to help user to understand where is the problem, like matchers you can define as many examples as you want, they all will be displayed to the user if an error occured. 57 | 58 | If you defined for instance : 59 | 60 | ``` 61 | a_simple_commit=""" 62 | [feat|test|ref|fix|style](module) : A commit message 63 | """ 64 | ``` 65 | 66 | this example will be displayed to the user like that : 67 | 68 | ``` 69 | A simple commit : 70 | 71 | [feat|test|ref|fix|style](module) : A commit message 72 | ``` 73 | 74 | key is used as a title, underscore are replaced with withespaces. 75 | 76 | ## Usage 77 | 78 | ```bash 79 | Ensure your commit messages are consistent 80 | 81 | Usage: 82 | gommit [command] 83 | 84 | Available Commands: 85 | check Check ensure a message follows defined patterns 86 | version App version 87 | 88 | Flags: 89 | --config string (default ".gommit.toml") 90 | -h, --help help for gommit 91 | 92 | Use "gommit [command] --help" for more information about a command. 93 | ``` 94 | 95 | ### check 96 | 97 | ```bash 98 | Check ensure a message follows defined patterns 99 | 100 | Usage: 101 | gommit check [flags] 102 | gommit check [command] 103 | 104 | Available Commands: 105 | commit Check commit message 106 | message Check message 107 | range Check messages in commit range 108 | 109 | Flags: 110 | -h, --help help for check 111 | 112 | Global Flags: 113 | --config string (default ".gommit.toml") 114 | 115 | Use "gommit check [command] --help" for more information about a command. 116 | 117 | 118 | You need to provide two commit references to run matching for instance : 119 | ``` 120 | 121 | #### check commit 122 | 123 | ```bash 124 | Check commit message 125 | 126 | Usage: 127 | gommit check commit [id] [&path] [flags] 128 | 129 | Flags: 130 | -h, --help help for commit 131 | 132 | Global Flags: 133 | --config string (default ".gommit.toml") 134 | ``` 135 | 136 | Check one comit from its commit ID, doesn't support short ID currently : 137 | 138 | `gommit check commit aeb603ba83614fae682337bdce9ee1bad1da6d6e` 139 | 140 | #### check message 141 | 142 | ```bash 143 | Check message 144 | 145 | Usage: 146 | gommit check message [message] [flags] 147 | 148 | Flags: 149 | -h, --help help for message 150 | 151 | Global Flags: 152 | --config string (default ".gommit.toml") 153 | ``` 154 | 155 | Check a message, useful for script for instance when you want to use it with git hooks : 156 | 157 | `gommit check message "Hello"` 158 | 159 | #### check range 160 | 161 | ```bash 162 | Check messages in range 163 | 164 | Usage: 165 | gommit check range [revisionfrom] [revisionTo] [&path] [flags] 166 | 167 | Flags: 168 | -h, --help help for range 169 | 170 | Global Flags: 171 | --config string (default ".gommit.toml") 172 | ``` 173 | 174 | Check a commit range, useful if you want to use it with a CI to ensure all commits in branch are following your conventions : 175 | 176 | - with relative references : `gommit check range master~2^ master` 177 | - with absolute references : `gommit check range dev test` 178 | - with commit ids (doesn't support short ID currently) : `gommit check range 7bbb37ade3ff36e362d7e20bf34a1325a15b 09f25db7971c100a8c0cfc2b22ab7f872ff0c18d` 179 | 180 | ## Practical usage 181 | 182 | If your system isn't described here and you find a way to have gommit working on it, please improve this documentation by doing a PR for the next who would like to do the same. 183 | 184 | ### Git hook 185 | 186 | It's possible to use gommit to validate each commit when you are creating them. To do so, you need to use the `commit-msg` hook, you can replace default script with this one : 187 | 188 | ``` 189 | #!/bin/sh 190 | 191 | gommit check message "$(cat "$1")"; 192 | ``` 193 | 194 | ### Travis 195 | 196 | In travis, all history isn't cloned, default depth is 50 commits, you can change it : https://docs.travis-ci.com/user/customizing-the-build#Git-Clone-Depth. 197 | 198 | First, we download the binary from the release page according to the version we want and we add in `.travis.yml` : 199 | 200 | ```yaml 201 | before_install: 202 | - wget -O /tmp/gommit https://github.com/antham/gommit/releases/download/v2.0.0/gommit_linux_386 && chmod 777 /tmp/gommit 203 | ``` 204 | 205 | We can add a perl script in our repository to analyze the commit range against master for instance (master reference needs to be part of cloned history): 206 | 207 | ```perl 208 | #!/bin/perl 209 | 210 | `git ls-remote origin master` =~ /([a-f0-9]{40})/; 211 | 212 | my $refHead = `git rev-parse HEAD`; 213 | my $refTail = $1; 214 | 215 | chomp($refHead); 216 | chomp($refTail); 217 | 218 | if ($refHead eq $refTail) { 219 | exit 0; 220 | } 221 | 222 | system "gommit check range $refTail $refHead"; 223 | 224 | if ($? > 0) { 225 | exit 1; 226 | } 227 | ``` 228 | 229 | And finally in `.travis.yml`, make it crashs when an error occured : 230 | 231 | ```yaml 232 | script: perl test-branch-commit-messages-in-travis.pl 233 | ``` 234 | 235 | ### CircleCI 236 | 237 | In CircleCI (2.0), there is an environment variable that describe current branch : `CIRCLE_BRANCH` (https://circleci.com/docs/2.0/env-vars/#circleci-environment-variable-descriptions). 238 | 239 | First, we download the binary from the release page according to the version we want and we add in `.circleci/config.yml` : 240 | 241 | ```yaml 242 | - run: 243 | name: Get gommit binary 244 | command: | 245 | mkdir /home/circleci/bin 246 | wget -O ~/bin/gommit https://github.com/antham/gommit/releases/download/v2.0.0/gommit_linux_386 && chmod 777 ~/bin/gommit 247 | ``` 248 | 249 | And we can run gommit against master for instance : 250 | 251 | ```yaml 252 | - run: 253 | name: Run gommit 254 | command: | 255 | if [ $CIRCLE_BRANCH != 'master' ]; then ~/bin/gommit check range $(git rev-parse origin/master) $CIRCLE_BRANCH ; fi 256 | ``` 257 | 258 | ## Third Part Libraries 259 | 260 | ### Nodejs 261 | 262 | - [gommitjs](https://github.com/dschnare/gommitjs) : A Nodejs wrapper for gommit 263 | -------------------------------------------------------------------------------- /cmd/check.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/dlclark/regexp2" 8 | 9 | "github.com/antham/gommit/gommit" 10 | "github.com/spf13/cobra" 11 | "github.com/spf13/viper" 12 | ) 13 | 14 | // checkCmd represents the check command 15 | var checkCmd = &cobra.Command{ 16 | Use: "check", 17 | Short: "Check ensure a message follows defined patterns", 18 | Run: func(cmd *cobra.Command, args []string) { 19 | if err := cmd.Help(); err != nil { 20 | failure(err) 21 | 22 | exitError() 23 | } 24 | }, 25 | } 26 | 27 | func parseDirectory(path string) (string, error) { 28 | var err error 29 | 30 | if path == "" { 31 | if path, err = os.Getwd(); err != nil { 32 | return "", err 33 | } 34 | } else { 35 | f, err := os.Stat(path) 36 | if err != nil { 37 | return "", fmt.Errorf(`Ensure "%s" directory exists`, path) 38 | } 39 | 40 | if !f.IsDir() { 41 | return "", fmt.Errorf(`"%s" must be a directory`, path) 42 | } 43 | } 44 | 45 | return path, nil 46 | } 47 | 48 | func validateFileConfig() error { 49 | if len(viper.GetStringMapString("matchers")) == 0 { 50 | return fmt.Errorf("At least one matcher must be defined") 51 | } 52 | 53 | if len(viper.GetStringMapString("examples")) == 0 { 54 | return fmt.Errorf("At least one example must be defined") 55 | } 56 | 57 | for name, matcher := range viper.GetStringMapString("matchers") { 58 | _, err := regexp2.Compile(matcher, 0) 59 | if err != nil { 60 | return fmt.Errorf(`Regexp "%s" identified by "%s" is not a valid regexp, please check the syntax`, matcher, name) 61 | } 62 | } 63 | 64 | return nil 65 | } 66 | 67 | func processMatchResult(matchings *[]*gommit.Matching, err error, examples map[string]string) { 68 | if err != nil { 69 | failure(err) 70 | 71 | exitError() 72 | } 73 | 74 | if len(*matchings) != 0 { 75 | renderMatchings(matchings) 76 | renderExamples(examples) 77 | 78 | exitError() 79 | } 80 | 81 | success("Everything is ok") 82 | 83 | exitSuccess() 84 | } 85 | 86 | func buildOptions() gommit.Options { 87 | viper.SetDefault("config.summary-length", 50) 88 | 89 | return gommit.Options{ 90 | CheckSummaryLength: viper.GetBool("config.check-summary-length"), 91 | ExcludeMergeCommits: viper.GetBool("config.exclude-merge-commits"), 92 | SummaryLength: viper.GetInt("config.summary-length"), 93 | } 94 | } 95 | 96 | func init() { 97 | RootCmd.AddCommand(checkCmd) 98 | } 99 | -------------------------------------------------------------------------------- /cmd/check_commit.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | 7 | "github.com/spf13/cobra" 8 | "github.com/spf13/viper" 9 | 10 | "github.com/antham/gommit/gommit" 11 | ) 12 | 13 | // checkCommitCmd represents the command that check a commit message 14 | var checkCommitCmd = &cobra.Command{ 15 | Use: "commit [id] [&path]", 16 | Short: "Check commit message", 17 | Run: func(cmd *cobra.Command, args []string) { 18 | err := validateFileConfig() 19 | if err != nil { 20 | failure(err) 21 | 22 | exitError() 23 | } 24 | 25 | ID, path, err := extractCheckCommitArgs(args) 26 | if err != nil { 27 | failure(err) 28 | 29 | exitError() 30 | } 31 | 32 | q := gommit.CommitQuery{ 33 | ID: ID, 34 | Path: path, 35 | Matchers: viper.GetStringMapString("matchers"), 36 | Options: buildOptions(), 37 | } 38 | 39 | matching, err := gommit.MatchCommitQuery(q) 40 | 41 | matchings := &[]*gommit.Matching{} 42 | 43 | if !gommit.IsZeroMatching(matching) { 44 | *matchings = append(*matchings, matching) 45 | } 46 | 47 | processMatchResult(matchings, err, viper.GetStringMapString("examples")) 48 | }, 49 | } 50 | 51 | func extractCheckCommitArgs(args []string) (string, string, error) { 52 | if len(args) < 1 { 53 | return "", "", fmt.Errorf("One argument required : commit id") 54 | } 55 | 56 | ok, err := regexp.Match("[a-fA-F0-9]{40}", []byte(args[0])) 57 | 58 | if err != nil || !ok { 59 | return "", "", fmt.Errorf("Argument must be a valid commit id") 60 | } 61 | 62 | if len(args) > 2 { 63 | return "", "", fmt.Errorf("2 arguments must be provided at most") 64 | } 65 | 66 | var path string 67 | 68 | if len(args) == 2 { 69 | path = args[1] 70 | } 71 | 72 | path, err = parseDirectory(path) 73 | if err != nil { 74 | return "", "", err 75 | } 76 | 77 | return args[0], path, nil 78 | } 79 | 80 | func init() { 81 | checkCmd.AddCommand(checkCommitCmd) 82 | } 83 | -------------------------------------------------------------------------------- /cmd/check_commit_test.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "os/exec" 7 | "sync" 8 | "testing" 9 | 10 | "github.com/sirupsen/logrus" 11 | "github.com/stretchr/testify/assert" 12 | 13 | "github.com/antham/gommit/gommit" 14 | ) 15 | 16 | func TestCheckCommitWithErrors(t *testing.T) { 17 | err := exec.Command("../features/repo.sh").Run() 18 | if err != nil { 19 | logrus.Fatal(err) 20 | } 21 | 22 | path, err := os.Getwd() 23 | if err != nil { 24 | logrus.Fatal(err) 25 | } 26 | 27 | exitError = func() { 28 | panic(1) 29 | } 30 | 31 | exitSuccess = func() { 32 | panic(0) 33 | } 34 | 35 | var errc error 36 | 37 | failure = func(err error) { 38 | errc = err 39 | } 40 | 41 | arguments := [][]string{ 42 | { 43 | "check", 44 | "commit", 45 | }, 46 | { 47 | "check", 48 | "commit", 49 | "whatever", 50 | }, 51 | { 52 | "check", 53 | "commit", 54 | "whatever", 55 | "whatever", 56 | }, 57 | { 58 | "check", 59 | "commit", 60 | "826f193edd4ba9d6d1799b66fa64f9a84f1db3bf", 61 | "whatever", 62 | "whatever", 63 | }, 64 | { 65 | "check", 66 | "commit", 67 | "826f193edd4ba9d6d1799b66fa64f9a84f1db3bf", 68 | "whatever", 69 | }, 70 | { 71 | "check", 72 | "commit", 73 | "826f193edd4ba9d6d1799b66fa64f9a84f1db3bf", 74 | "testing-repository", 75 | }, 76 | { 77 | "check", 78 | "commit", 79 | "826f193edd4ba9d6d1799b66fa64f9a84f1db3bf", 80 | "testing-repository", 81 | }, 82 | { 83 | "check", 84 | "commit", 85 | "826f193edd4ba9d6d1799b66fa64f9a84f1db3bf", 86 | "testing-repository", 87 | }, 88 | { 89 | "check", 90 | "commit", 91 | "826f193edd4ba9d6d1799b66fa64f9a84f1db3bf", 92 | "testing-repository", 93 | }, 94 | } 95 | 96 | errors := []error{ 97 | fmt.Errorf("One argument required : commit id"), 98 | fmt.Errorf(`Argument must be a valid commit id`), 99 | fmt.Errorf(`Argument must be a valid commit id`), 100 | fmt.Errorf(`2 arguments must be provided at most`), 101 | fmt.Errorf(`Ensure "whatever" directory exists`), 102 | fmt.Errorf(`object not found`), 103 | fmt.Errorf(`At least one matcher must be defined`), 104 | fmt.Errorf(`At least one example must be defined`), 105 | fmt.Errorf(`Regexp "**" identified by "all" is not a valid regexp, please check the syntax`), 106 | } 107 | 108 | configs := []string{ 109 | path + "/../features/.gommit.toml", 110 | path + "/../features/.gommit.toml", 111 | path + "/../features/.gommit.toml", 112 | path + "/../features/.gommit.toml", 113 | path + "/../features/.gommit.toml", 114 | path + "/../features/.gommit.toml", 115 | path + "/../features/.gommit-no-matchers.toml", 116 | path + "/../features/.gommit-no-examples.toml", 117 | path + "/../features/.gommit-wrong-regexp.toml", 118 | } 119 | 120 | for i, a := range arguments { 121 | var w sync.WaitGroup 122 | 123 | w.Add(1) 124 | 125 | go func() { 126 | defer func() { 127 | if r := recover(); r != nil && r.(int) == 0 { 128 | errc = nil 129 | } 130 | 131 | w.Done() 132 | }() 133 | 134 | os.Args = []string{"", "--config", configs[i]} 135 | os.Args = append(os.Args, a...) 136 | 137 | _ = RootCmd.Execute() 138 | }() 139 | 140 | w.Wait() 141 | 142 | assert.Error(t, errc, "Must return an error") 143 | assert.EqualError(t, errc, errors[i].Error(), "Must return an error : "+errors[i].Error()) 144 | } 145 | } 146 | 147 | func TestCheckCommit(t *testing.T) { 148 | path, err := os.Getwd() 149 | if err != nil { 150 | logrus.Fatal(err) 151 | } 152 | 153 | for _, filename := range []string{"../features/repo.sh"} { 154 | err = exec.Command(filename).Run() 155 | if err != nil { 156 | logrus.Fatal(err) 157 | } 158 | } 159 | 160 | var code int 161 | var message string 162 | var w sync.WaitGroup 163 | 164 | success = func(msg string) { 165 | message = msg 166 | } 167 | 168 | exitError = func() { 169 | panic(1) 170 | } 171 | 172 | exitSuccess = func() { 173 | panic(0) 174 | } 175 | 176 | cmd := exec.Command("git", "rev-parse", "HEAD") 177 | cmd.Dir = "testing-repository" 178 | 179 | ID, err := cmd.Output() 180 | if err != nil { 181 | logrus.Fatal(err) 182 | } 183 | 184 | w.Add(1) 185 | 186 | go func() { 187 | defer func() { 188 | if r := recover(); r != nil { 189 | code = r.(int) 190 | } 191 | 192 | w.Done() 193 | }() 194 | 195 | os.Args = []string{"", "--config", path + "/../features/.gommit.toml", "check", "commit", string(ID[:len(ID)-1]), path + "/testing-repository"} 196 | 197 | Execute() 198 | }() 199 | 200 | w.Wait() 201 | 202 | assert.EqualValues(t, 0, code, "Must exit with no errors (exit 0)") 203 | assert.EqualValues(t, "Everything is ok", message, "Must return a message to inform everything is ok") 204 | } 205 | 206 | func TestCheckCommitWithBadMessage(t *testing.T) { 207 | path, err := os.Getwd() 208 | if err != nil { 209 | logrus.Fatal(err) 210 | } 211 | 212 | for _, filename := range []string{"../features/repo.sh", "../features/bad-commit.sh"} { 213 | err = exec.Command(filename).Run() 214 | if err != nil { 215 | logrus.Fatal(err) 216 | } 217 | } 218 | 219 | var code int 220 | var message string 221 | var w sync.WaitGroup 222 | 223 | success = func(msg string) { 224 | message = msg 225 | } 226 | 227 | exitError = func() { 228 | panic(1) 229 | } 230 | 231 | exitSuccess = func() { 232 | panic(0) 233 | } 234 | 235 | cmd := exec.Command("git", "rev-parse", "HEAD") 236 | cmd.Dir = "testing-repository" 237 | 238 | ID, err := cmd.Output() 239 | if err != nil { 240 | logrus.Fatal(err) 241 | } 242 | 243 | var matchings *[]*gommit.Matching 244 | var examples map[string]string 245 | 246 | renderMatchings = func(m *[]*gommit.Matching) { 247 | matchings = m 248 | } 249 | 250 | renderExamples = func(e map[string]string) { 251 | examples = e 252 | } 253 | 254 | w.Add(1) 255 | 256 | go func() { 257 | defer func() { 258 | if r := recover(); r != nil { 259 | code = r.(int) 260 | } 261 | 262 | w.Done() 263 | }() 264 | 265 | os.Args = []string{"", "--config", path + "/../features/.gommit.toml", "check", "commit", string(ID[:len(ID)-1]), path + "/testing-repository"} 266 | 267 | Execute() 268 | }() 269 | 270 | w.Wait() 271 | 272 | assert.EqualValues(t, 1, code, "Must exit with errors (exit 1)") 273 | assert.Empty(t, message, "Must return no success message") 274 | assert.Len(t, *matchings, 1, "Must return 1 commits") 275 | assert.Len(t, examples, 3, "Must return 3 examples") 276 | } 277 | -------------------------------------------------------------------------------- /cmd/check_message.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/spf13/cobra" 7 | "github.com/spf13/viper" 8 | 9 | "github.com/antham/gommit/gommit" 10 | ) 11 | 12 | // checkMessageCmd represents the command that check a message 13 | var checkMessageCmd = &cobra.Command{ 14 | Use: "message [message]", 15 | Short: "Check message", 16 | Run: func(cmd *cobra.Command, args []string) { 17 | err := validateFileConfig() 18 | if err != nil { 19 | failure(err) 20 | 21 | exitError() 22 | } 23 | 24 | message, err := extractCheckMessageArgs(args) 25 | if err != nil { 26 | failure(err) 27 | 28 | exitError() 29 | } 30 | 31 | q := gommit.MessageQuery{ 32 | Message: message, 33 | Matchers: viper.GetStringMapString("matchers"), 34 | Options: buildOptions(), 35 | } 36 | 37 | matching, err := gommit.MatchMessageQuery(q) 38 | 39 | matchings := &[]*gommit.Matching{} 40 | 41 | if !gommit.IsZeroMatching(matching) { 42 | *matchings = append(*matchings, matching) 43 | } 44 | 45 | processMatchResult(matchings, err, viper.GetStringMapString("examples")) 46 | }, 47 | } 48 | 49 | func extractCheckMessageArgs(args []string) (string, error) { 50 | if len(args) != 1 { 51 | return "", fmt.Errorf("One argument required : message") 52 | } 53 | 54 | return args[0], nil 55 | } 56 | 57 | func init() { 58 | checkCmd.AddCommand(checkMessageCmd) 59 | } 60 | -------------------------------------------------------------------------------- /cmd/check_message_test.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | "os/exec" 6 | "sync" 7 | "testing" 8 | 9 | "github.com/sirupsen/logrus" 10 | "github.com/stretchr/testify/assert" 11 | 12 | "github.com/antham/gommit/gommit" 13 | ) 14 | 15 | func TestCheckMessageWithErrors(t *testing.T) { 16 | path, err := os.Getwd() 17 | if err != nil { 18 | logrus.Fatal(err) 19 | } 20 | 21 | exitError = func() { 22 | panic(1) 23 | } 24 | 25 | exitSuccess = func() { 26 | panic(0) 27 | } 28 | 29 | var errc error 30 | 31 | failure = func(err error) { 32 | errc = err 33 | } 34 | 35 | arguments := [][]string{ 36 | { 37 | "check", 38 | "message", 39 | }, 40 | { 41 | "check", 42 | "message", 43 | }, 44 | { 45 | "check", 46 | "message", 47 | "test", 48 | }, 49 | { 50 | "check", 51 | "message", 52 | "test", 53 | }, 54 | } 55 | 56 | errorStrings := []string{ 57 | "open .*: no such file or directory", 58 | "One argument required : message", 59 | `At least one matcher must be defined`, 60 | `At least one example must be defined`, 61 | } 62 | 63 | configs := []string{ 64 | path + "/test.toml", 65 | path + "/../features/.gommit.toml", 66 | path + "/../features/.gommit-no-matchers.toml", 67 | path + "/../features/.gommit-no-examples.toml", 68 | } 69 | 70 | for i, a := range arguments { 71 | var w sync.WaitGroup 72 | 73 | w.Add(1) 74 | 75 | go func() { 76 | defer func() { 77 | if r := recover(); r != nil && r.(int) == 0 { 78 | errc = nil 79 | } 80 | 81 | w.Done() 82 | }() 83 | 84 | os.Args = []string{"", "--config", configs[i]} 85 | os.Args = append(os.Args, a...) 86 | 87 | _ = RootCmd.Execute() 88 | }() 89 | 90 | w.Wait() 91 | 92 | assert.Error(t, errc, "Must return an error") 93 | assert.Regexp(t, errorStrings[i], errc.Error()) 94 | } 95 | } 96 | 97 | func TestCheckMessage(t *testing.T) { 98 | path, err := os.Getwd() 99 | if err != nil { 100 | logrus.Fatal(err) 101 | } 102 | 103 | for _, filename := range []string{"../features/repo.sh"} { 104 | 105 | err := exec.Command(filename).Run() 106 | if err != nil { 107 | logrus.Fatal(err) 108 | } 109 | } 110 | 111 | var code int 112 | var message string 113 | var w sync.WaitGroup 114 | 115 | success = func(msg string) { 116 | message = msg 117 | } 118 | 119 | exitError = func() { 120 | panic(1) 121 | } 122 | 123 | exitSuccess = func() { 124 | panic(0) 125 | } 126 | 127 | w.Add(1) 128 | 129 | go func() { 130 | defer func() { 131 | if r := recover(); r != nil { 132 | code = r.(int) 133 | } 134 | 135 | w.Done() 136 | }() 137 | 138 | os.Args = []string{"", "--config", path + "/../features/.gommit.toml", "check", "message", "feat(cmd) : everything is fine\n"} 139 | 140 | Execute() 141 | }() 142 | 143 | w.Wait() 144 | 145 | assert.EqualValues(t, 0, code, "Must exit without errors (exit 0)") 146 | assert.EqualValues(t, "Everything is ok", message, "Must return a message to inform everything is ok") 147 | } 148 | 149 | func TestCheckMessageWithBadMessage(t *testing.T) { 150 | path, err := os.Getwd() 151 | if err != nil { 152 | logrus.Fatal(err) 153 | } 154 | 155 | for _, filename := range []string{"../features/repo.sh"} { 156 | 157 | err := exec.Command(filename).Run() 158 | if err != nil { 159 | logrus.Fatal(err) 160 | } 161 | } 162 | 163 | var code int 164 | var message string 165 | var w sync.WaitGroup 166 | 167 | success = func(msg string) { 168 | message = msg 169 | } 170 | 171 | exitError = func() { 172 | panic(1) 173 | } 174 | 175 | exitSuccess = func() { 176 | panic(0) 177 | } 178 | 179 | var matchings *[]*gommit.Matching 180 | var examples map[string]string 181 | 182 | renderMatchings = func(m *[]*gommit.Matching) { 183 | matchings = m 184 | } 185 | 186 | renderExamples = func(e map[string]string) { 187 | examples = e 188 | } 189 | 190 | w.Add(1) 191 | 192 | go func() { 193 | defer func() { 194 | if r := recover(); r != nil { 195 | code = r.(int) 196 | } 197 | 198 | w.Done() 199 | }() 200 | 201 | os.Args = []string{"", "--config", path + "/../features/.gommit.toml", "check", "message", "everything is fine\n"} 202 | 203 | Execute() 204 | }() 205 | 206 | w.Wait() 207 | 208 | assert.EqualValues(t, 1, code, "Must exit with errors (exit 1)") 209 | assert.Empty(t, message, "Must return no success message") 210 | assert.Len(t, *matchings, 1, "Must return 1 commits") 211 | assert.Len(t, examples, 3, "Must return 3 examples") 212 | } 213 | -------------------------------------------------------------------------------- /cmd/check_range.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/spf13/cobra" 7 | "github.com/spf13/viper" 8 | 9 | "github.com/antham/gommit/gommit" 10 | ) 11 | 12 | // checkRangeCmd represents the check command 13 | var checkRangeCmd = &cobra.Command{ 14 | Use: "range [revisionfrom] [revisionTo] [&path]", 15 | Short: "Check messages in range", 16 | Run: func(cmd *cobra.Command, args []string) { 17 | err := validateFileConfig() 18 | if err != nil { 19 | failure(err) 20 | 21 | exitError() 22 | } 23 | 24 | from, to, path, err := extractCheckRangeArgs(args) 25 | if err != nil { 26 | failure(err) 27 | 28 | exitError() 29 | } 30 | 31 | q := gommit.RangeQuery{ 32 | Path: path, 33 | From: from, 34 | To: to, 35 | Matchers: viper.GetStringMapString("matchers"), 36 | Options: buildOptions(), 37 | } 38 | 39 | matchings, err := gommit.MatchRangeQuery(q) 40 | 41 | processMatchResult(matchings, err, viper.GetStringMapString("examples")) 42 | }, 43 | } 44 | 45 | func extractCheckRangeArgs(args []string) (string, string, string, error) { 46 | if len(args) < 2 { 47 | return "", "", "", fmt.Errorf("Two arguments required : origin commit and end commit") 48 | } 49 | 50 | if len(args) > 3 { 51 | return "", "", "", fmt.Errorf("3 arguments must be provided at most") 52 | } 53 | 54 | var path string 55 | var err error 56 | 57 | if len(args) == 3 { 58 | path = args[2] 59 | } 60 | 61 | path, err = parseDirectory(path) 62 | if err != nil { 63 | return "", "", "", err 64 | } 65 | 66 | return args[0], args[1], path, nil 67 | } 68 | 69 | func init() { 70 | checkCmd.AddCommand(checkRangeCmd) 71 | } 72 | -------------------------------------------------------------------------------- /cmd/check_range_test.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "os/exec" 7 | "sync" 8 | "testing" 9 | 10 | "github.com/sirupsen/logrus" 11 | "github.com/stretchr/testify/assert" 12 | 13 | "github.com/antham/gommit/gommit" 14 | ) 15 | 16 | func TestCheckRangeWithErrors(t *testing.T) { 17 | err := exec.Command("../features/repo.sh").Run() 18 | if err != nil { 19 | logrus.Fatal(err) 20 | } 21 | 22 | path, err := os.Getwd() 23 | if err != nil { 24 | logrus.Fatal(err) 25 | } 26 | 27 | exitError = func() { 28 | panic(1) 29 | } 30 | 31 | exitSuccess = func() { 32 | panic(0) 33 | } 34 | 35 | var errc error 36 | 37 | failure = func(err error) { 38 | errc = err 39 | } 40 | 41 | arguments := [][]string{ 42 | { 43 | "check", 44 | "range", 45 | }, 46 | { 47 | "check", 48 | "range", 49 | "master~2", 50 | }, 51 | { 52 | "check", 53 | "range", 54 | "master~1", 55 | "master~2", 56 | "test", 57 | "whatever", 58 | }, 59 | { 60 | "check", 61 | "range", 62 | "master~1", 63 | "master~2", 64 | "whatever", 65 | }, 66 | { 67 | "check", 68 | "range", 69 | "master~1", 70 | "master~2", 71 | "check.go", 72 | }, 73 | { 74 | "check", 75 | "range", 76 | "whatever", 77 | "master", 78 | "testing-repository/", 79 | }, 80 | { 81 | "check", 82 | "range", 83 | "master~2", 84 | "master~1", 85 | "testing-repository/", 86 | }, 87 | { 88 | "check", 89 | "range", 90 | "master~2", 91 | "master~1", 92 | "testing-repository/", 93 | }, 94 | } 95 | 96 | errors := []error{ 97 | fmt.Errorf("Two arguments required : origin commit and end commit"), 98 | fmt.Errorf("Two arguments required : origin commit and end commit"), 99 | fmt.Errorf("3 arguments must be provided at most"), 100 | fmt.Errorf(`Ensure "whatever" directory exists`), 101 | fmt.Errorf(`"check.go" must be a directory`), 102 | fmt.Errorf(`Reference "whatever" can't be found in git repository`), 103 | fmt.Errorf(`At least one matcher must be defined`), 104 | fmt.Errorf(`At least one example must be defined`), 105 | } 106 | 107 | configs := []string{ 108 | path + "/../features/.gommit.toml", 109 | path + "/../features/.gommit.toml", 110 | path + "/../features/.gommit.toml", 111 | path + "/../features/.gommit.toml", 112 | path + "/../features/.gommit.toml", 113 | path + "/../features/.gommit.toml", 114 | path + "/../features/.gommit-no-matchers.toml", 115 | path + "/../features/.gommit-no-examples.toml", 116 | } 117 | 118 | for i, a := range arguments { 119 | var w sync.WaitGroup 120 | 121 | w.Add(1) 122 | 123 | go func() { 124 | defer func() { 125 | if r := recover(); r != nil && r.(int) == 0 { 126 | errc = nil 127 | } 128 | 129 | w.Done() 130 | }() 131 | 132 | os.Args = []string{"", "--config", configs[i]} 133 | os.Args = append(os.Args, a...) 134 | 135 | _ = RootCmd.Execute() 136 | }() 137 | 138 | w.Wait() 139 | 140 | assert.Error(t, errc, "Must return an error") 141 | assert.EqualError(t, errc, errors[i].Error(), "Must return an error : "+errors[i].Error()) 142 | } 143 | } 144 | 145 | func TestCheckRangeWithBadCommitMessage(t *testing.T) { 146 | path, err := os.Getwd() 147 | if err != nil { 148 | logrus.Fatal(err) 149 | } 150 | 151 | for _, filename := range []string{"../features/repo.sh", "../features/bad-commit.sh"} { 152 | 153 | err := exec.Command(filename).Run() 154 | if err != nil { 155 | logrus.Fatal(err) 156 | } 157 | } 158 | 159 | exitError = func() { 160 | panic(1) 161 | } 162 | 163 | exitSuccess = func() { 164 | panic(0) 165 | } 166 | 167 | var w sync.WaitGroup 168 | 169 | var matchings *[]*gommit.Matching 170 | var examples map[string]string 171 | 172 | renderMatchings = func(m *[]*gommit.Matching) { 173 | matchings = m 174 | } 175 | 176 | renderExamples = func(e map[string]string) { 177 | examples = e 178 | } 179 | 180 | w.Add(1) 181 | 182 | go func() { 183 | defer func() { 184 | if r := recover(); r != nil && r.(int) == 0 { 185 | matchings = &[]*gommit.Matching{} 186 | examples = map[string]string{} 187 | } 188 | 189 | w.Done() 190 | }() 191 | 192 | os.Args = []string{"", "--config", path + "/../features/.gommit.toml", "check", "range", "test~3", "test", path + "/testing-repository"} 193 | 194 | Execute() 195 | }() 196 | 197 | w.Wait() 198 | 199 | assert.Len(t, *matchings, 1, "Must return 1 commits") 200 | assert.Len(t, examples, 3, "Must return 3 examples") 201 | } 202 | 203 | func TestCheckRangeWithNoErrors(t *testing.T) { 204 | path, err := os.Getwd() 205 | if err != nil { 206 | logrus.Fatal(err) 207 | } 208 | 209 | for _, filename := range []string{"../features/repo.sh"} { 210 | 211 | err := exec.Command(filename).Run() 212 | if err != nil { 213 | logrus.Fatal(err) 214 | } 215 | } 216 | 217 | var code int 218 | var message string 219 | var w sync.WaitGroup 220 | 221 | success = func(msg string) { 222 | message = msg 223 | } 224 | 225 | exitError = func() { 226 | panic(1) 227 | } 228 | 229 | exitSuccess = func() { 230 | panic(0) 231 | } 232 | 233 | w.Add(1) 234 | 235 | go func() { 236 | defer func() { 237 | if r := recover(); r != nil { 238 | code = r.(int) 239 | } 240 | 241 | w.Done() 242 | }() 243 | 244 | os.Args = []string{"", "--config", path + "/../features/.gommit.toml", "check", "range", "test~2", "test", path + "/testing-repository"} 245 | 246 | Execute() 247 | }() 248 | 249 | w.Wait() 250 | 251 | assert.EqualValues(t, 0, code, "Must exit without errors (exit 0)") 252 | assert.EqualValues(t, "Everything is ok", message, "Must return a message to inform everything is ok") 253 | } 254 | -------------------------------------------------------------------------------- /cmd/check_test.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | 9 | "github.com/antham/gommit/gommit" 10 | ) 11 | 12 | func TestBuildOptionsWithDefaultValues(t *testing.T) { 13 | opts := buildOptions() 14 | 15 | assert.Equal(t, gommit.Options{SummaryLength: 50, CheckSummaryLength: false, ExcludeMergeCommits: false}, opts) 16 | } 17 | 18 | func TestParseDirectoryWithErrors(t *testing.T) { 19 | _, err := parseDirectory("/test") 20 | 21 | assert.EqualError(t, err, `Ensure "/test" directory exists`) 22 | 23 | _, err = os.Create("/tmp/file") 24 | 25 | assert.NoError(t, err) 26 | 27 | _, err = parseDirectory("/tmp/file") 28 | 29 | assert.EqualError(t, err, `"/tmp/file" must be a directory`) 30 | } 31 | -------------------------------------------------------------------------------- /cmd/exit.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | ) 6 | 7 | var exitError = func() { 8 | os.Exit(1) 9 | } 10 | 11 | var exitSuccess = func() { 12 | os.Exit(0) 13 | } 14 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "github.com/spf13/viper" 6 | ) 7 | 8 | var cfgFile string 9 | 10 | // RootCmd represents the base command when called without any subcommands 11 | var RootCmd = &cobra.Command{ 12 | Use: "gommit", 13 | Short: "Ensure your commit messages are consistent", 14 | } 15 | 16 | // Execute adds all child commands to the root command sets flags appropriately. 17 | // This is called by main.main(). It only needs to happen once to the rootCmd. 18 | func Execute() { 19 | if err := RootCmd.Execute(); err != nil { 20 | failure(err) 21 | exitError() 22 | } 23 | } 24 | 25 | func init() { 26 | cobra.OnInitialize(initConfig) 27 | 28 | RootCmd.PersistentFlags().StringVar(&cfgFile, "config", ".gommit.toml", "") 29 | } 30 | 31 | // initConfig reads in config file and ENV variables if set. 32 | func initConfig() { 33 | if cfgFile != "" { 34 | viper.SetConfigFile(cfgFile) 35 | } 36 | 37 | viper.AddConfigPath(".") 38 | 39 | if err := viper.ReadInConfig(); err != nil { 40 | failure(err) 41 | exitError() 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /cmd/ui.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/fatih/color" 8 | "golang.org/x/text/cases" 9 | "golang.org/x/text/language" 10 | 11 | "github.com/antham/gommit/gommit" 12 | ) 13 | 14 | var failure = func(err error) { 15 | color.Red(err.Error()) 16 | } 17 | 18 | var success = func(message string) { 19 | color.Green(message) 20 | } 21 | 22 | var info = func(message string) { 23 | color.Cyan(message) 24 | } 25 | 26 | var renderMatchings = func(matchings *[]*gommit.Matching) { 27 | for _, m := range *matchings { 28 | color.White("----") 29 | fmt.Println() 30 | 31 | if ID, ok := m.Context["ID"]; ok { 32 | fmt.Printf("%s%s\n", color.YellowString("Id : "), color.WhiteString("%s", ID)) 33 | } 34 | 35 | if message, ok := m.Context["message"]; ok { 36 | color.Yellow("Message : ") 37 | 38 | for _, field := range strings.Split(message, "\n") { 39 | fmt.Printf("%s%s\n", color.YellowString(" "), color.WhiteString("%s", field)) 40 | } 41 | } 42 | 43 | fmt.Println() 44 | 45 | errs := []error{} 46 | 47 | if m.MessageError != nil { 48 | errs = append(errs, m.MessageError) 49 | } 50 | 51 | if m.SummaryError != nil { 52 | errs = append(errs, m.SummaryError) 53 | } 54 | 55 | for i, e := range errs { 56 | if i == 0 { 57 | fmt.Printf("%s", color.YellowString("Error(s) : ")) 58 | fmt.Printf("- %s\n", color.RedString("%s", e.Error())) 59 | } else { 60 | fmt.Printf(" - %s\n", color.RedString("%s", e.Error())) 61 | } 62 | } 63 | 64 | fmt.Println() 65 | } 66 | } 67 | 68 | var renderExamples = func(examples map[string]string) { 69 | color.White("=======") 70 | fmt.Println() 71 | 72 | color.White("Your message must match one of those following patterns :") 73 | 74 | fmt.Println() 75 | 76 | for key, example := range examples { 77 | color.White("----") 78 | fmt.Println() 79 | 80 | color.Yellow("%s : ", strings.Replace(cases.Title(language.English).String(key), "_", " ", -1)) 81 | fmt.Println() 82 | 83 | color.Cyan("%s", example) 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /cmd/version.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/antham/gommit/gommit" 5 | "github.com/spf13/cobra" 6 | ) 7 | 8 | // versionCmd represents the version command 9 | var versionCmd = &cobra.Command{ 10 | Use: "version", 11 | Short: "App version", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | info(gommit.GetVersion()) 14 | }, 15 | } 16 | 17 | func init() { 18 | RootCmd.AddCommand(versionCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/version_test.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | "sync" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | 10 | "github.com/antham/gommit/gommit" 11 | ) 12 | 13 | func TestVersion(t *testing.T) { 14 | var code int 15 | var message string 16 | var w sync.WaitGroup 17 | 18 | info = func(msg string) { 19 | message = msg 20 | } 21 | 22 | exitError = func() { 23 | panic(1) 24 | } 25 | 26 | exitSuccess = func() { 27 | panic(0) 28 | } 29 | 30 | w.Add(1) 31 | 32 | go func() { 33 | defer func() { 34 | if r := recover(); r != nil { 35 | code = r.(int) 36 | } 37 | 38 | w.Done() 39 | }() 40 | 41 | os.Args = []string{"", "version"} 42 | 43 | Execute() 44 | }() 45 | 46 | w.Wait() 47 | 48 | assert.EqualValues(t, 0, code, "Must exit without errors (exit 0)") 49 | assert.EqualValues(t, gommit.GetVersion(), message, "Must return app version") 50 | } 51 | -------------------------------------------------------------------------------- /features/.gommit-no-examples.toml: -------------------------------------------------------------------------------- 1 | [config] 2 | exclude-merge-commit=false 3 | check-summary-length=false 4 | 5 | [matchers] 6 | simple="(?:ref|feat|update)\\(.*?\\) : .*?\n(?:\n?.*?\n)*" 7 | -------------------------------------------------------------------------------- /features/.gommit-no-matchers.toml: -------------------------------------------------------------------------------- 1 | [config] 2 | exclude-merge-commit=false 3 | check-summary-length=false 4 | 5 | [examples] 6 | a_new_feature=""" 7 | feat(module) : An added feature 8 | 9 | New feature 10 | """ 11 | a_refactor=""" 12 | ref(module) : Refactor module 13 | 14 | Refactor a module 15 | """ 16 | 17 | an_update=""" 18 | update(module) : Update a file 19 | 20 | Update file 21 | """ 22 | -------------------------------------------------------------------------------- /features/.gommit-wrong-regexp.toml: -------------------------------------------------------------------------------- 1 | [config] 2 | exclude-merge-commit=false 3 | check-summary-length=false 4 | 5 | [matchers] 6 | all="**" 7 | 8 | [examples] 9 | a_new_feature=""" 10 | feat(module) : An added feature 11 | 12 | New feature 13 | """ 14 | a_refactor=""" 15 | ref(module) : Refactor module 16 | 17 | Refactor a module 18 | """ 19 | 20 | an_update=""" 21 | update(module) : Update a file 22 | 23 | Update file 24 | """ 25 | -------------------------------------------------------------------------------- /features/.gommit.toml: -------------------------------------------------------------------------------- 1 | [config] 2 | exclude-merge-commit=false 3 | check-summary-length=false 4 | 5 | [matchers] 6 | simple="(?:ref|feat|update)\\(.*?\\) : .*?\n(?:\n?.*?\n)*" 7 | [examples] 8 | a_new_feature=""" 9 | feat(module) : An added feature 10 | 11 | New feature 12 | """ 13 | a_refactor=""" 14 | ref(module) : Refactor module 15 | 16 | Refactor a module 17 | """ 18 | 19 | an_update=""" 20 | update(module) : Update a file 21 | 22 | Update file 23 | """ 24 | -------------------------------------------------------------------------------- /features/bad-commit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd testing-repository || exit 1 4 | 5 | # Update file 2 with a bad commit message 6 | echo "test 2 test 2" > file2 7 | git add file2 8 | git commit -F- < /dev/null 15 | git init $gitRepositoryPath 16 | cd $gitRepositoryPath || exit 1 17 | 18 | # Create branch test 19 | git checkout --quiet -b test 20 | 21 | # Create several commits on test branch 22 | touch file1 23 | git add file1 24 | git commit --quiet -F- < 0 { 130 | current := queue[0] 131 | queue = append([]*object.Commit{}, queue[1:]...) 132 | 133 | err := current.Parents().ForEach( 134 | func(c *object.Commit) error { 135 | if _, ok := seen[c.ID().String()]; !ok { 136 | seen[c.ID().String()] = true 137 | queue = append(queue, c) 138 | } 139 | 140 | return nil 141 | }) 142 | 143 | if err != nil && err.Error() != plumbing.ErrObjectNotFound.Error() { 144 | return seen, errBrowsingTree 145 | } 146 | } 147 | 148 | return seen, nil 149 | } 150 | 151 | // findDiffCommits extracts commits that are no part of a given commit list 152 | // using kind of depth first search algorithm to keep commits ordered 153 | func findDiffCommits(commit *object.Commit, exclusionList *map[string]bool) (*[]*object.Commit, error) { 154 | commits := []*object.Commit{} 155 | queue := append([]*node{}, &node{value: commit}) 156 | seen := map[string]bool{commit.ID().String(): true} 157 | var current *node 158 | 159 | for len(queue) > 0 { 160 | current = queue[0] 161 | queue = append([]*node{}, queue[1:]...) 162 | 163 | if _, ok := (*exclusionList)[current.value.ID().String()]; !ok { 164 | commits = append(commits, current.value) 165 | } 166 | 167 | err := current.value.Parents().ForEach( 168 | func(c *object.Commit) error { 169 | if _, ok := seen[c.ID().String()]; !ok { 170 | seen[c.ID().String()] = true 171 | n := &node{value: c, parent: current} 172 | queue = append([]*node{n}, queue...) 173 | } 174 | 175 | return nil 176 | }) 177 | 178 | if err != nil && err.Error() != plumbing.ErrObjectNotFound.Error() { 179 | return &commits, errBrowsingTree 180 | } 181 | } 182 | 183 | return &commits, nil 184 | } 185 | -------------------------------------------------------------------------------- /reference/reference_history_test.go: -------------------------------------------------------------------------------- 1 | package reference 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "os/exec" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | 11 | "github.com/go-git/go-git/v5" 12 | "github.com/go-git/go-git/v5/plumbing" 13 | "github.com/go-git/go-git/v5/plumbing/object" 14 | "github.com/sirupsen/logrus" 15 | ) 16 | 17 | var ( 18 | repo *git.Repository 19 | gitRepositoryPath = "testing-repository" 20 | ) 21 | 22 | func setup() { 23 | err := exec.Command("../features/repo.sh").Run() 24 | if err != nil { 25 | logrus.Fatal(err) 26 | } 27 | 28 | path, err := os.Getwd() 29 | if err != nil { 30 | fmt.Println(err) 31 | os.Exit(1) 32 | } 33 | 34 | repo, err = git.PlainOpen(path + "/" + gitRepositoryPath) 35 | if err != nil { 36 | fmt.Println(err) 37 | os.Exit(1) 38 | } 39 | } 40 | 41 | func getCommitFromRef(ref string) *object.Commit { 42 | cmd := exec.Command("git", "rev-parse", ref) 43 | cmd.Dir = gitRepositoryPath 44 | 45 | ID, err := cmd.Output() 46 | ID = ID[:len(ID)-1] 47 | 48 | if err != nil { 49 | logrus.WithField("ID", string(ID)).Fatal(err) 50 | } 51 | 52 | c, err := repo.CommitObject(plumbing.NewHash(string(ID))) 53 | if err != nil { 54 | logrus.WithField("ID", ID).Fatal(err) 55 | } 56 | 57 | return c 58 | } 59 | 60 | func TestMain(m *testing.M) { 61 | setup() 62 | code := m.Run() 63 | os.Exit(code) 64 | } 65 | 66 | func TestResolveRef(t *testing.T) { 67 | type g struct { 68 | ref string 69 | f func(*object.Commit, error) 70 | } 71 | 72 | tests := []g{ 73 | { 74 | "HEAD", 75 | func(o *object.Commit, err error) { 76 | assert.NoError(t, err) 77 | assert.True(t, o.ID().String() == getCommitFromRef("HEAD").ID().String(), "Must resolve HEAD reference") 78 | }, 79 | }, 80 | { 81 | "test1", 82 | func(o *object.Commit, err error) { 83 | assert.NoError(t, err) 84 | assert.True(t, o.ID().String() == getCommitFromRef("test1").ID().String(), "Must resolve branch reference") 85 | }, 86 | }, 87 | { 88 | "test1", 89 | func(o *object.Commit, err error) { 90 | assert.NoError(t, err) 91 | assert.True(t, o.ID().String() == getCommitFromRef("test1").ID().String(), "Must resolve commit id") 92 | }, 93 | }, 94 | { 95 | "whatever", 96 | func(o *object.Commit, err error) { 97 | assert.Error(t, err) 98 | assert.EqualError(t, err, `Reference "whatever" can't be found in git repository`) 99 | }, 100 | }, 101 | } 102 | 103 | for _, test := range tests { 104 | test.f(resolveRef(test.ref, repo)) 105 | } 106 | } 107 | 108 | func TestResolveRefWithErrors(t *testing.T) { 109 | type g struct { 110 | ref string 111 | repo *git.Repository 112 | f func(*object.Commit, error) 113 | } 114 | 115 | tests := []g{ 116 | { 117 | "whatever", 118 | repo, 119 | func(o *object.Commit, err error) { 120 | assert.Error(t, err) 121 | assert.EqualError(t, err, `Reference "whatever" can't be found in git repository`) 122 | }, 123 | }, 124 | } 125 | 126 | for _, test := range tests { 127 | test.f(resolveRef(test.ref, test.repo)) 128 | } 129 | } 130 | 131 | func TestFetchCommitInterval(t *testing.T) { 132 | type g struct { 133 | toRef string 134 | fromRef string 135 | f func(*[]*object.Commit, error) 136 | } 137 | tests := []g{ 138 | { 139 | "HEAD", 140 | "test", 141 | func(cs *[]*object.Commit, err error) { 142 | assert.Error(t, err) 143 | assert.Regexp(t, `Can't produce a diff between .*? and .*?, check your range is correct by running "git log .*?\.\..*?" command`, err.Error()) 144 | }, 145 | }, 146 | { 147 | "HEAD~1", 148 | "HEAD~3", 149 | func(cs *[]*object.Commit, err error) { 150 | assert.Error(t, err) 151 | assert.Regexp(t, `Can't produce a diff between .*? and .*?, check your range is correct by running "git log .*?\.\..*?" command`, err.Error()) 152 | }, 153 | }, 154 | { 155 | "HEAD~3", 156 | "test~2^2", 157 | func(cs *[]*object.Commit, err error) { 158 | assert.NoError(t, err) 159 | assert.Len(t, *cs, 5) 160 | 161 | commitTests := []string{ 162 | "Merge branch 'test2' into test1\n", 163 | "feat(file6) : new file 6\n\ncreate a new file 6\n", 164 | "feat(file5) : new file 5\n\ncreate a new file 5\n", 165 | "feat(file4) : new file 4\n\ncreate a new file 4\n", 166 | "feat(file3) : new file 3\n\ncreate a new file 3\n", 167 | } 168 | 169 | for i, c := range *cs { 170 | assert.Equal(t, commitTests[i], c.Message) 171 | } 172 | }, 173 | }, 174 | { 175 | "HEAD~4", 176 | "test~2^2^2", 177 | func(cs *[]*object.Commit, err error) { 178 | assert.NoError(t, err) 179 | assert.Len(t, *cs, 5) 180 | 181 | commitTests := []string{ 182 | "feat(file6) : new file 6\n\ncreate a new file 6\n", 183 | "feat(file5) : new file 5\n\ncreate a new file 5\n", 184 | "feat(file4) : new file 4\n\ncreate a new file 4\n", 185 | "feat(file3) : new file 3\n\ncreate a new file 3\n", 186 | "feat(file2) : new file 2\n\ncreate a new file 2\n", 187 | } 188 | 189 | for i, c := range *cs { 190 | assert.Equal(t, commitTests[i], c.Message) 191 | } 192 | }, 193 | }, 194 | { 195 | getCommitFromRef("HEAD~4").ID().String(), 196 | getCommitFromRef("test~2^2^2").ID().String(), 197 | func(cs *[]*object.Commit, err error) { 198 | assert.NoError(t, err) 199 | assert.Len(t, *cs, 5) 200 | 201 | commitTests := []string{ 202 | "feat(file6) : new file 6\n\ncreate a new file 6\n", 203 | "feat(file5) : new file 5\n\ncreate a new file 5\n", 204 | "feat(file4) : new file 4\n\ncreate a new file 4\n", 205 | "feat(file3) : new file 3\n\ncreate a new file 3\n", 206 | "feat(file2) : new file 2\n\ncreate a new file 2\n", 207 | } 208 | 209 | for i, c := range *cs { 210 | assert.Equal(t, commitTests[i], c.Message) 211 | } 212 | }, 213 | }, 214 | { 215 | "whatever", 216 | "HEAD~1", 217 | func(cs *[]*object.Commit, err error) { 218 | assert.EqualError(t, err, `Reference "whatever" can't be found in git repository`) 219 | }, 220 | }, 221 | { 222 | "HEAD~1", 223 | "whatever", 224 | func(cs *[]*object.Commit, err error) { 225 | assert.EqualError(t, err, `Reference "whatever" can't be found in git repository`) 226 | }, 227 | }, 228 | { 229 | "HEAD", 230 | "HEAD", 231 | func(cs *[]*object.Commit, err error) { 232 | assert.EqualError(t, err, `Can't produce a diff between HEAD and HEAD, check your range is correct by running "git log HEAD..HEAD" command`) 233 | }, 234 | }, 235 | } 236 | for _, test := range tests { 237 | test.f(FetchCommitInterval(repo, test.toRef, test.fromRef)) 238 | } 239 | } 240 | 241 | func TestShallowCloneProducesNoErrors(t *testing.T) { 242 | repositoryPath := "shallow-repository-test" 243 | cmd := exec.Command("rm", "-rf", repositoryPath) 244 | _, err := cmd.Output() 245 | assert.NoError(t, err) 246 | 247 | cmd = exec.Command("git", "clone", "--depth", "2", "https://github.com/octocat/Spoon-Knife.git", repositoryPath) 248 | _, err = cmd.Output() 249 | assert.NoError(t, err) 250 | 251 | path, err := os.Getwd() 252 | if err != nil { 253 | fmt.Println(err) 254 | os.Exit(1) 255 | } 256 | 257 | repo, err := git.PlainOpen(path + "/" + repositoryPath) 258 | if err != nil { 259 | logrus.Fatal(err) 260 | } 261 | 262 | commits, err := FetchCommitInterval(repo, "HEAD~1", "HEAD") 263 | assert.NoError(t, err) 264 | assert.Len(t, *commits, 1, "Must fetch commits in shallow clone") 265 | } 266 | 267 | func TestFetchCommitByID(t *testing.T) { 268 | cmd := exec.Command("git", "rev-parse", "HEAD") 269 | cmd.Dir = gitRepositoryPath 270 | 271 | ID, err := cmd.Output() 272 | if err != nil { 273 | logrus.Fatal(err) 274 | } 275 | 276 | commit, err := FetchCommitByID(repo, string(ID[:len(ID)-1])) 277 | 278 | assert.NoError(t, err, "Must return no errors") 279 | assert.Equal(t, "feat(file8) : new file 8\n\ncreate a new file 8\n", commit.Message, "Must return commit linked to this id") 280 | } 281 | 282 | func TestFetchCommitByIDWithAWrongCommitID(t *testing.T) { 283 | _, err := FetchCommitByID(repo, "whatever") 284 | 285 | assert.Error(t, err, "Must return an error") 286 | } 287 | --------------------------------------------------------------------------------