├── .gitignore ├── .typos.toml ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── question.yml │ ├── suggestion.yml │ └── bug.yml ├── PULL_REQUEST_TEMPLATE.md ├── dependabot.yml ├── CONTRIBUTING.md ├── workflows │ ├── codeql.yml │ └── ci.yml ├── images │ ├── license.svg │ ├── card.svg │ └── usage.svg └── CODE_OF_CONDUCT.md ├── go.mod ├── gomakegen.go ├── go.sum ├── SECURITY.md ├── README.md ├── Makefile ├── LICENSE └── cli └── cli.go /.gitignore: -------------------------------------------------------------------------------- 1 | gomakegen 2 | -------------------------------------------------------------------------------- /.typos.toml: -------------------------------------------------------------------------------- 1 | [files] 2 | extend-exclude = ["go.sum"] 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/essentialkaos/gomakegen/v3 2 | 3 | go 1.23.6 4 | 5 | require github.com/essentialkaos/ek/v13 v13.27.1 6 | 7 | require ( 8 | github.com/essentialkaos/depsy v1.3.1 // indirect 9 | golang.org/x/sys v0.33.0 // indirect 10 | ) 11 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### What did you implement: 2 | 3 | Closes #XXXXX 4 | 5 | ### How did you implement it: 6 | 7 | ... 8 | 9 | ### How can we verify it: 10 | 11 | ... 12 | 13 | ### TODO's: 14 | 15 | - [ ] Write documentation 16 | - [ ] Check that there aren't other open pull requests for the same issue/feature 17 | - [ ] Format your source code by `make fmt` 18 | - [ ] Pass the test by `make test` 19 | - [ ] Provide verification config / commands 20 | - [ ] Enable "Allow edits from maintainers" for this PR 21 | - [ ] Update the messages below 22 | 23 | **Is this ready for review?:** No 24 | **Is it a breaking change?:** No 25 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: "gomod" 5 | directory: "/" 6 | target-branch: "develop" 7 | schedule: 8 | interval: "daily" 9 | timezone: "Etc/UTC" 10 | time: "03:00" 11 | labels: 12 | - "PR • MAINTENANCE" 13 | assignees: 14 | - "andyone" 15 | groups: 16 | all: 17 | applies-to: version-updates 18 | update-types: 19 | - "minor" 20 | - "patch" 21 | 22 | - package-ecosystem: "github-actions" 23 | directory: "/" 24 | target-branch: "develop" 25 | schedule: 26 | interval: "daily" 27 | timezone: "Etc/UTC" 28 | time: "03:00" 29 | labels: 30 | - "PR • MAINTENANCE" 31 | assignees: 32 | - "andyone" 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.yml: -------------------------------------------------------------------------------- 1 | name: ❓ Question 2 | description: Question about application, configuration or code 3 | title: "[Question]: " 4 | labels: ["issue • question"] 5 | assignees: 6 | - andyone 7 | 8 | body: 9 | - type: markdown 10 | attributes: 11 | value: | 12 | > [!IMPORTANT] 13 | > Before you open an issue, search GitHub Issues for a similar question. If so, please add a 👍 reaction to the existing issue. 14 | 15 | - type: textarea 16 | attributes: 17 | label: Question 18 | description: Detailed question 19 | validations: 20 | required: true 21 | 22 | - type: textarea 23 | attributes: 24 | label: Related version application info 25 | description: Output of `gomakegen -vv` command 26 | render: shell 27 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | **IMPORTANT! Contribute your code only if you have an excellent understanding of project idea and all existing code base. Otherwise, a nicely formatted issue will be more helpful to us.** 4 | 5 | ### Issues 6 | 7 | 1. Provide product version where the problem was found; 8 | 2. Provide info about your environment; 9 | 3. Provide detailed info about your problem; 10 | 4. Provide steps to reproduce the problem; 11 | 5. Provide actual and expected results. 12 | 13 | ### Code 14 | 15 | 1. Check your code **before** creating pull request; 16 | 2. If tests are present in a project, add tests for your code; 17 | 3. Add inline documentation for your code; 18 | 4. Apply code style used throughout the project; 19 | 5. Create your pull request to `develop` branch (_pull requests to other branches are not allowed_). 20 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [master, develop] 6 | pull_request: 7 | branches: [master] 8 | schedule: 9 | - cron: '0 3 * * */2' 10 | workflow_dispatch: 11 | inputs: 12 | force_run: 13 | description: 'Force workflow run' 14 | required: true 15 | type: choice 16 | options: [yes, no] 17 | 18 | permissions: 19 | security-events: write 20 | actions: read 21 | contents: read 22 | 23 | jobs: 24 | analyse: 25 | name: Analyse 26 | runs-on: ubuntu-latest 27 | 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v4 31 | with: 32 | fetch-depth: 2 33 | 34 | - name: Initialize CodeQL 35 | uses: github/codeql-action/init@v3 36 | with: 37 | languages: go 38 | 39 | - name: Perform CodeQL Analysis 40 | uses: github/codeql-action/analyze@v3 41 | -------------------------------------------------------------------------------- /gomakegen.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // ////////////////////////////////////////////////////////////////////////////////// // 4 | // // 5 | // Copyright (c) 2025 ESSENTIAL KAOS // 6 | // Apache License, Version 2.0 // 7 | // // 8 | // ////////////////////////////////////////////////////////////////////////////////// // 9 | 10 | import ( 11 | _ "embed" 12 | 13 | CLI "github.com/essentialkaos/gomakegen/v3/cli" 14 | ) 15 | 16 | // ////////////////////////////////////////////////////////////////////////////////// // 17 | 18 | //go:embed go.mod 19 | var gomod []byte 20 | 21 | // gitrev is short hash of the latest git commit 22 | var gitrev string 23 | 24 | // ////////////////////////////////////////////////////////////////////////////////// // 25 | 26 | func main() { 27 | CLI.Init(gitrev, gomod) 28 | } 29 | -------------------------------------------------------------------------------- /.github/images/license.svg: -------------------------------------------------------------------------------- 1 | license: Apache-2.0licenseApache-2.0 -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/essentialkaos/check v1.4.1 h1:SuxXzrbokPGTPWxGRnzy0hXvtb44mtVrdNxgPa1s4c8= 2 | github.com/essentialkaos/check v1.4.1/go.mod h1:xQOYwFvnxfVZyt5Qvjoa1SxcRqu5VyP77pgALr3iu+M= 3 | github.com/essentialkaos/depsy v1.3.1 h1:00k9QcMsdPM4IzDaEFHsTHBD/zoM0oxtB5+dMUwbQa8= 4 | github.com/essentialkaos/depsy v1.3.1/go.mod h1:B5+7Jhv2a2RacOAxIKU2OeJp9QfZjwIpEEPI5X7auWM= 5 | github.com/essentialkaos/ek/v13 v13.27.1 h1:qblB9u6dqWPm2xfv95n0bUzW9zKEpZI/GlUnrxRskck= 6 | github.com/essentialkaos/ek/v13 v13.27.1/go.mod h1:8/TJJ/5C5F1MC1iCMyepkRHoKGjPt4U6OzQvmgFN+9U= 7 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 8 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 9 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 10 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 11 | github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= 12 | github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= 13 | golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= 14 | golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/suggestion.yml: -------------------------------------------------------------------------------- 1 | name: ➕ Suggestion 2 | description: Suggest new feature or improvement 3 | title: "[Suggestion]: " 4 | labels: ["issue • suggestion"] 5 | assignees: 6 | - andyone 7 | 8 | body: 9 | - type: markdown 10 | attributes: 11 | value: | 12 | > [!IMPORTANT] 13 | > Before you open an issue, search GitHub Issues for a similar feature requests. If so, please add a 👍 reaction to the existing issue. 14 | > 15 | > Opening a feature request kicks off a discussion. Requests may be closed if we're not actively planning to work on them. 16 | 17 | - type: textarea 18 | attributes: 19 | label: Proposal 20 | description: Description of the feature 21 | validations: 22 | required: true 23 | 24 | - type: textarea 25 | attributes: 26 | label: Current behavior 27 | description: What currently happens 28 | validations: 29 | required: true 30 | 31 | - type: textarea 32 | attributes: 33 | label: Desired behavior 34 | description: What you would like to happen 35 | validations: 36 | required: true 37 | 38 | - type: textarea 39 | attributes: 40 | label: Use case 41 | description: Why is this important (helps with prioritizing requests) 42 | validations: 43 | required: true 44 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [master, develop] 6 | pull_request: 7 | branches: [master] 8 | workflow_dispatch: 9 | inputs: 10 | force_run: 11 | description: 'Force workflow run' 12 | required: true 13 | type: choice 14 | options: [yes, no] 15 | 16 | permissions: 17 | actions: read 18 | contents: read 19 | statuses: write 20 | 21 | concurrency: 22 | group: ${{ github.workflow }}-${{ github.ref }} 23 | cancel-in-progress: true 24 | 25 | jobs: 26 | Go: 27 | name: Go 28 | runs-on: ubuntu-latest 29 | 30 | strategy: 31 | matrix: 32 | go: [ 'oldstable', 'stable' ] 33 | 34 | steps: 35 | - name: Checkout 36 | uses: actions/checkout@v4 37 | 38 | - name: Set up Go 39 | uses: actions/setup-go@v5 40 | with: 41 | go-version: ${{ matrix.go }} 42 | 43 | - name: Download dependencies 44 | run: make deps 45 | 46 | - name: Build binary 47 | run: make all 48 | 49 | Typos: 50 | name: Typos 51 | runs-on: ubuntu-latest 52 | 53 | needs: Go 54 | 55 | steps: 56 | - name: Checkout 57 | uses: actions/checkout@v4 58 | 59 | - name: Check spelling 60 | uses: crate-ci/typos@master 61 | continue-on-error: true 62 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policies and Procedures 2 | 3 | This document outlines security procedures and general policies for all 4 | ESSENTIAL KAOS projects. 5 | 6 | * [Reporting a Bug](#reporting-a-bug) 7 | * [Disclosure Policy](#disclosure-policy) 8 | 9 | ## Reporting a Bug 10 | 11 | The ESSENTIAL KAOS team and community take all security bugs in our projects 12 | very seriously. Thank you for improving the security of our project. We 13 | appreciate your efforts and responsible disclosure and will make every effort 14 | to acknowledge your contributions. 15 | 16 | Report security bugs by emailing our security team at security@essentialkaos.com. 17 | 18 | The security team will acknowledge your email within 48 hours and will send a 19 | more detailed response within 48 hours, indicating the next steps in handling 20 | your report. After the initial reply to your report, the security team will 21 | endeavor to keep you informed of the progress towards a fix and full 22 | announcement, and may ask for additional information or guidance. 23 | 24 | Report security bugs in third-party dependencies to the person or team 25 | maintaining the dependencies. 26 | 27 | ## Disclosure Policy 28 | 29 | When the security team receives a security bug report, they will assign it to a 30 | primary handler. This person will coordinate the fix and release process, 31 | involving the following steps: 32 | 33 | * Confirm the problem and determine the affected versions; 34 | * Audit code to find any similar potential problems; 35 | * Prepare fixes for all releases still under maintenance. These fixes will be 36 | released as fast as possible. 37 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug.yml: -------------------------------------------------------------------------------- 1 | name: ❗ Bug Report 2 | description: File a bug report 3 | title: "[Bug]: " 4 | labels: ["issue • bug"] 5 | assignees: 6 | - andyone 7 | 8 | body: 9 | - type: markdown 10 | attributes: 11 | value: | 12 | > [!IMPORTANT] 13 | > Before you open an issue, search GitHub Issues for a similar bug reports. If so, please add a 👍 reaction to the existing issue. 14 | 15 | - type: textarea 16 | attributes: 17 | label: Verbose application info 18 | description: Output of `gomakegen -vv` command 19 | render: shell 20 | validations: 21 | required: true 22 | 23 | - type: dropdown 24 | id: version 25 | attributes: 26 | label: Install tools 27 | description: How did you install this application 28 | options: 29 | - From Sources 30 | - RPM Package 31 | - Prebuilt Binary 32 | default: 0 33 | validations: 34 | required: true 35 | 36 | - type: textarea 37 | attributes: 38 | label: Steps to reproduce 39 | description: Short guide on how to reproduce this problem on our site 40 | placeholder: | 41 | 1. [First Step] 42 | 2. [Second Step] 43 | 3. [and so on...] 44 | validations: 45 | required: true 46 | 47 | - type: textarea 48 | attributes: 49 | label: Expected behavior 50 | description: What you expected to happen 51 | validations: 52 | required: true 53 | 54 | - type: textarea 55 | attributes: 56 | label: Actual behavior 57 | description: What actually happened 58 | validations: 59 | required: true 60 | 61 | - type: textarea 62 | attributes: 63 | label: Additional info 64 | description: Include gist of relevant config, logs, etc. 65 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of 4 | fostering an open and welcoming community, we pledge to respect all people who 5 | contribute through reporting issues, posting feature requests, updating 6 | documentation, submitting pull requests or patches, and other activities. 7 | 8 | We are committed to making participation in this project a harassment-free 9 | experience for everyone, regardless of level of experience, gender, gender 10 | identity and expression, sexual orientation, disability, personal appearance, 11 | body size, race, ethnicity, age, religion, or nationality. 12 | 13 | Examples of unacceptable behavior by participants include: 14 | 15 | * The use of sexualized language or imagery 16 | * Personal attacks 17 | * Trolling or insulting/derogatory comments 18 | * Public or private harassment 19 | * Publishing other's private information, such as physical or electronic 20 | addresses, without explicit permission 21 | * Other unethical or unprofessional conduct 22 | 23 | Project maintainers have the right and responsibility to remove, edit, or 24 | reject comments, commits, code, wiki edits, issues, and other contributions 25 | that are not aligned to this Code of Conduct, or to ban temporarily or 26 | permanently any contributor for other behaviors that they deem inappropriate, 27 | threatening, offensive, or harmful. 28 | 29 | By adopting this Code of Conduct, project maintainers commit themselves to 30 | fairly and consistently applying these principles to every aspect of managing 31 | this project. Project maintainers who do not follow or enforce the Code of 32 | Conduct may be permanently removed from the project team. 33 | 34 | This Code of Conduct applies both within project spaces and in public spaces 35 | when an individual is representing the project or its community. 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 38 | reported by contacting a project maintainer at [INSERT EMAIL ADDRESS]. All 39 | complaints will be reviewed and investigated and will result in a response that 40 | is deemed necessary and appropriate to the circumstances. Maintainers are 41 | obligated to maintain confidentiality with regard to the reporter of an 42 | incident. 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | GoReportCard 5 | Codacy badge 6 | GitHub Actions CI Status 7 | GitHub Actions CodeQL Status 8 | 9 |

10 | 11 |

InstallationUsageBuild StatusContributingLicense

12 | 13 |
14 | 15 | `gomakegen` is simple utility for generating makefiles for Golang applications. 16 | 17 | ### Installation 18 | 19 | To build the `gomakegen` from scratch, make sure you have a working Go 1.23+ workspace (_[instructions](https://go.dev/doc/install)_), then: 20 | 21 | ``` 22 | go install github.com/essentialkaos/gomakegen/v3@latest 23 | ``` 24 | 25 | #### Prebuilt binaries 26 | 27 | You can download prebuilt binaries for Linux and macOS from [EK Apps Repository](https://apps.kaos.st/gomakegen/latest): 28 | 29 | ```bash 30 | bash <(curl -fsSL https://apps.kaos.st/get) gomakegen 31 | ``` 32 | 33 | ### Command-line completion 34 | 35 | You can generate completion for `bash`, `zsh` or `fish` shell. 36 | 37 | Bash: 38 | ```bash 39 | sudo gomakegen --completion=bash 1> /etc/bash_completion.d/gomakegen 40 | ``` 41 | 42 | ZSH: 43 | ```bash 44 | sudo gomakegen --completion=zsh 1> /usr/share/zsh/site-functions/gomakegen 45 | ``` 46 | 47 | Fish: 48 | ```bash 49 | sudo gomakegen --completion=fish 1> /usr/share/fish/vendor_completions.d/gomakegen.fish 50 | ``` 51 | 52 | ### Man documentation 53 | 54 | You can generate man page using next command: 55 | 56 | ```bash 57 | gomakegen --generate-man | sudo gzip > /usr/share/man/man1/gomakegen.1.gz 58 | ``` 59 | 60 | ### Usage 61 | 62 | 63 | 64 | ### CI Status 65 | 66 | | Branch | Status | 67 | |--------|--------| 68 | | `master` | [![CI](https://kaos.sh/w/gomakegen/ci.svg?branch=master)](https://kaos.sh/w/gomakegen/ci?query=branch:master) | 69 | | `develop` | [![CI](https://kaos.sh/w/gomakegen/ci.svg?branch=master)](https://kaos.sh/w/gomakegen/ci?query=branch:develop) | 70 | 71 | ### Contributing 72 | 73 | Before contributing to this project please read our [Contributing Guidelines](https://github.com/essentialkaos/.github/blob/master/CONTRIBUTING.md). 74 | 75 | ### License 76 | 77 | [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) 78 | 79 |

80 | -------------------------------------------------------------------------------- /.github/images/card.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | 3 | # This Makefile generated by GoMakeGen 3.3.3 using next command: 4 | # gomakegen --mod --strip . 5 | # 6 | # More info: https://kaos.sh/gomakegen 7 | 8 | ################################################################################ 9 | 10 | ifdef VERBOSE ## Print verbose information (Flag) 11 | VERBOSE_FLAG = -v 12 | endif 13 | 14 | ifdef PROXY ## Force proxy usage for downloading dependencies (Flag) 15 | export GOPROXY=https://proxy.golang.org/cached-only,direct 16 | endif 17 | 18 | ifdef CGO ## Enable CGO usage (Flag) 19 | export CGO_ENABLED=1 20 | else 21 | export CGO_ENABLED=0 22 | endif 23 | 24 | MAKEDIR = $(dir $(realpath $(firstword $(MAKEFILE_LIST)))) 25 | GITREV ?= $(shell test -s $(MAKEDIR)/.git && git rev-parse --short HEAD) 26 | 27 | ################################################################################ 28 | 29 | .DEFAULT_GOAL := help 30 | .PHONY = fmt vet all install uninstall clean deps update init vendor tidy mod-init mod-update mod-download mod-vendor help 31 | 32 | ################################################################################ 33 | 34 | all: gomakegen ## Build all binaries 35 | 36 | gomakegen: 37 | @echo "Building gomakegen…" 38 | @go build $(VERBOSE_FLAG) -ldflags="-s -w -X main.gitrev=$(GITREV)" gomakegen.go 39 | 40 | install: ## Install all binaries 41 | @echo "Installing binaries…" 42 | @cp gomakegen /usr/bin/gomakegen 43 | 44 | uninstall: ## Uninstall all binaries 45 | @echo "Removing installed binaries…" 46 | @rm -f /usr/bin/gomakegen 47 | 48 | init: mod-init ## Initialize new module 49 | 50 | deps: mod-download ## Download dependencies 51 | 52 | update: mod-update ## Update dependencies to the latest versions 53 | 54 | vendor: mod-vendor ## Make vendored copy of dependencies 55 | 56 | tidy: ## Cleanup dependencies 57 | @echo "•• Tidying up dependencies…" 58 | ifdef COMPAT ## Compatible Go version (String) 59 | @go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT) -go=$(COMPAT) 60 | else 61 | @go mod tidy $(VERBOSE_FLAG) 62 | endif 63 | @echo "•• Updating vendored dependencies…" 64 | @test -d vendor && rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || : 65 | 66 | mod-init: 67 | @echo "••• Modules initialization…" 68 | @rm -f go.mod go.sum 69 | ifdef MODULE_PATH ## Module path for initialization (String) 70 | @go mod init $(MODULE_PATH) 71 | else 72 | @go mod init 73 | endif 74 | 75 | @echo "••• Dependencies cleanup…" 76 | ifdef COMPAT ## Compatible Go version (String) 77 | @go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT) -go=$(COMPAT) 78 | else 79 | @go mod tidy $(VERBOSE_FLAG) 80 | endif 81 | @echo "••• Stripping toolchain info…" 82 | @grep -q 'toolchain ' go.mod && go mod edit -toolchain=none || : 83 | 84 | mod-update: 85 | @echo "•••• Updating dependencies…" 86 | ifdef UPDATE_ALL ## Update all dependencies (Flag) 87 | @go get -u $(VERBOSE_FLAG) all 88 | else 89 | @go get -u $(VERBOSE_FLAG) ./... 90 | endif 91 | 92 | @echo "•••• Stripping toolchain info…" 93 | @grep -q 'toolchain ' go.mod && go mod edit -toolchain=none || : 94 | 95 | @echo "•••• Dependencies cleanup…" 96 | ifdef COMPAT 97 | @go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT) 98 | else 99 | @go mod tidy $(VERBOSE_FLAG) 100 | endif 101 | 102 | @echo "•••• Updating vendored dependencies…" 103 | @test -d vendor && rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || : 104 | 105 | mod-download: 106 | @echo "Downloading dependencies…" 107 | @go mod download 108 | 109 | mod-vendor: 110 | @echo "Vendoring dependencies…" 111 | @rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || : 112 | 113 | fmt: ## Format source code with gofmt 114 | @echo "Formatting sources…" 115 | @find . -name "*.go" -exec gofmt -s -w {} \; 116 | 117 | vet: ## Runs 'go vet' over sources 118 | @echo "Running 'go vet' over sources…" 119 | @go vet -composites=false -printfuncs=LPrintf,TLPrintf,TPrintf,log.Debug,log.Info,log.Warn,log.Error,log.Critical,log.Print ./... 120 | 121 | clean: ## Remove generated files 122 | @echo "Removing built binaries…" 123 | @rm -f gomakegen 124 | 125 | help: ## Show this info 126 | @printf '\n\033[1mTargets:\033[0m\n\n' 127 | @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \ 128 | | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[33m%-9s\033[0m %s\n", $$1, $$2}' 129 | @printf '\n\033[1mVariables:\033[0m\n\n' 130 | @grep -E '^ifdef [A-Z_]+ .*?## .*$$' $(abspath $(lastword $(MAKEFILE_LIST))) \ 131 | | sed 's/ifdef //' \ 132 | | sort -h \ 133 | | awk 'BEGIN {FS = " .*?## "}; {printf " \033[32m%-11s\033[0m %s\n", $$1, $$2}' 134 | @echo '' 135 | @printf '\033[90mGenerated by GoMakeGen 3.3.3\033[0m\n\n' 136 | 137 | ################################################################################ 138 | -------------------------------------------------------------------------------- /.github/images/usage.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GoMakeGen Usage 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | Terminal 57 | 58 | Usage: gomakegen {options} source-dir 59 | Options 60 | --glide, -g ........ Add target to fetching dependencies with glide 61 | --dep, -d .......... Add target to fetching dependencies with dep 62 | --mod, -m .......... Add target to fetching dependencies with go mod (default for 63 | Go ≥ 1.18) 64 | --strip, -S ........ Strip binaries 65 | --benchmark, -B .... Add target to run benchmarks 66 | --race, -R ......... Add target to test race conditions 67 | --cgo, -C .......... Enable CGO usage 68 | --output, -o file .. Output file (Makefile by default) 69 | --no-color, -nc .... Disable colors in output 70 | --help, -h ......... Show this help message 71 | --version, -v ...... Show version 72 | Examples 73 | gomakegen . 74 | Generate makefile for project in current directory and save as Makefile 75 | gomakegen $GOPATH/src/github.com/profile/project 76 | Generate makefile for github.com/profile/project and save as Makefile 77 | gomakegen $GOPATH/src/github.com/profile/project -o project.make 78 | Generate makefile for github.com/profile/project and save as project.make 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 ESSENTIAL KAOS 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /cli/cli.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | // ////////////////////////////////////////////////////////////////////////////////// // 4 | // // 5 | // Copyright (c) 2025 ESSENTIAL KAOS // 6 | // Apache License, Version 2.0 // 7 | // // 8 | // ////////////////////////////////////////////////////////////////////////////////// // 9 | 10 | import ( 11 | "bufio" 12 | "bytes" 13 | "fmt" 14 | "os" 15 | "os/exec" 16 | "path/filepath" 17 | "runtime" 18 | "slices" 19 | "sort" 20 | "strconv" 21 | "strings" 22 | 23 | "go/parser" 24 | "go/token" 25 | 26 | "github.com/essentialkaos/ek/v13/fmtc" 27 | "github.com/essentialkaos/ek/v13/fsutil" 28 | "github.com/essentialkaos/ek/v13/mathutil" 29 | "github.com/essentialkaos/ek/v13/options" 30 | "github.com/essentialkaos/ek/v13/path" 31 | "github.com/essentialkaos/ek/v13/strutil" 32 | "github.com/essentialkaos/ek/v13/support" 33 | "github.com/essentialkaos/ek/v13/support/apps" 34 | "github.com/essentialkaos/ek/v13/support/deps" 35 | "github.com/essentialkaos/ek/v13/terminal" 36 | "github.com/essentialkaos/ek/v13/terminal/tty" 37 | "github.com/essentialkaos/ek/v13/usage" 38 | "github.com/essentialkaos/ek/v13/usage/completion/bash" 39 | "github.com/essentialkaos/ek/v13/usage/completion/fish" 40 | "github.com/essentialkaos/ek/v13/usage/completion/zsh" 41 | "github.com/essentialkaos/ek/v13/usage/man" 42 | "github.com/essentialkaos/ek/v13/usage/update" 43 | "github.com/essentialkaos/ek/v13/version" 44 | ) 45 | 46 | // ////////////////////////////////////////////////////////////////////////////////// // 47 | 48 | // App info 49 | const ( 50 | APP = "GoMakeGen" 51 | VER = "3.3.3" 52 | DESC = "Utility for generating makefiles for Go applications" 53 | ) 54 | 55 | // Constants with options names 56 | const ( 57 | OPT_OUTPUT = "o:output" 58 | OPT_GLIDE = "g:glide" 59 | OPT_DEP = "d:dep" 60 | OPT_MOD = "m:mod" 61 | OPT_STRIP = "S:strip" 62 | OPT_BENCHMARK = "B:benchmark" 63 | OPT_RACE = "R:race" 64 | OPT_CGO = "C:cgo" 65 | OPT_NO_COLOR = "nc:no-color" 66 | OPT_HELP = "h:help" 67 | OPT_VER = "v:version" 68 | 69 | OPT_VERB_VER = "vv:verbose-version" 70 | OPT_COMPLETION = "completion" 71 | OPT_GENERATE_MAN = "generate-man" 72 | ) 73 | 74 | // SEPARATOR_SIZE is default separator size 75 | const SEPARATOR_SIZE = 80 76 | 77 | // ////////////////////////////////////////////////////////////////////////////////// // 78 | 79 | // Makefile contains full info for makefile generation 80 | type Makefile struct { 81 | BaseImports []string 82 | TestImports []string 83 | Binaries []string 84 | 85 | FuzzPaths []string 86 | TestPaths []string 87 | 88 | PkgBase string 89 | 90 | MaxTargetNameSize int 91 | MaxOptionNameSize int 92 | 93 | HasTests bool 94 | Benchmark bool 95 | Race bool 96 | Strip bool 97 | CGO bool 98 | HasSubpackages bool 99 | HasStableImports bool 100 | 101 | GlideUsed bool 102 | DepUsed bool 103 | ModUsed bool 104 | } 105 | 106 | // ////////////////////////////////////////////////////////////////////////////////// // 107 | 108 | // Options map 109 | var optMap = options.Map{ 110 | OPT_OUTPUT: {Value: "Makefile"}, 111 | OPT_GLIDE: {Type: options.BOOL}, 112 | OPT_DEP: {Type: options.BOOL}, 113 | OPT_MOD: {Type: options.BOOL}, 114 | OPT_STRIP: {Type: options.BOOL}, 115 | OPT_BENCHMARK: {Type: options.BOOL}, 116 | OPT_RACE: {Type: options.BOOL}, 117 | OPT_CGO: {Type: options.BOOL}, 118 | OPT_NO_COLOR: {Type: options.BOOL}, 119 | OPT_HELP: {Type: options.BOOL}, 120 | OPT_VER: {Type: options.MIXED}, 121 | 122 | OPT_VERB_VER: {Type: options.BOOL}, 123 | OPT_COMPLETION: {}, 124 | OPT_GENERATE_MAN: {Type: options.BOOL}, 125 | } 126 | 127 | // Paths for check package 128 | var checkPackageImports = []string{ 129 | "github.com/go-check/check", 130 | "github.com/essentialkaos/check", 131 | "gopkg.in/check.v1", 132 | } 133 | 134 | var colorTagApp, colorTagVer string 135 | 136 | // ////////////////////////////////////////////////////////////////////////////////// // 137 | 138 | func Init(gitRev string, gomod []byte) { 139 | runtime.GOMAXPROCS(2) 140 | 141 | preConfigureUI() 142 | 143 | args, errs := options.Parse(optMap) 144 | 145 | if !errs.IsEmpty() { 146 | terminal.Error("Options parsing errors:") 147 | terminal.Error(errs.Error("- ")) 148 | os.Exit(1) 149 | } 150 | 151 | configureUI() 152 | 153 | switch { 154 | case options.Has(OPT_COMPLETION): 155 | os.Exit(genCompletion()) 156 | case options.Has(OPT_GENERATE_MAN): 157 | printMan() 158 | os.Exit(0) 159 | case options.GetB(OPT_VER): 160 | genAbout(gitRev).Print(options.GetS(OPT_VER)) 161 | os.Exit(0) 162 | case options.GetB(OPT_VERB_VER): 163 | support.Collect(APP, VER). 164 | WithRevision(gitRev). 165 | WithDeps(deps.Extract(gomod)). 166 | WithApps(apps.Golang()). 167 | Print() 168 | os.Exit(0) 169 | case options.GetB(OPT_HELP) || len(args) == 0: 170 | genUsage().Print() 171 | os.Exit(0) 172 | } 173 | 174 | dir := args.Get(0).Clean().String() 175 | 176 | checkDir(dir) 177 | process(dir) 178 | } 179 | 180 | func preConfigureUI() { 181 | if !tty.IsTTY() { 182 | fmtc.DisableColors = true 183 | } 184 | 185 | switch { 186 | case fmtc.IsTrueColorSupported(): 187 | colorTagApp, colorTagVer = "{*}{#00ADD8}", "{#5DC9E2}" 188 | case fmtc.Is256ColorsSupported(): 189 | colorTagApp, colorTagVer = "{*}{#38}", "{#74}" 190 | default: 191 | colorTagApp, colorTagVer = "{*}{c}", "{c}" 192 | } 193 | } 194 | 195 | // configureUI configures user interface 196 | func configureUI() { 197 | if options.GetB(OPT_NO_COLOR) { 198 | fmtc.DisableColors = true 199 | } 200 | } 201 | 202 | // checkDir checks directory with sources 203 | func checkDir(dir string) { 204 | err := fsutil.ValidatePerms("DRX", dir) 205 | 206 | if err != nil { 207 | terminal.Warn(err) 208 | os.Exit(1) 209 | } 210 | } 211 | 212 | // process starts sources processing 213 | func process(dir string) { 214 | sources := fsutil.ListAllFiles( 215 | dir, true, 216 | fsutil.ListingFilter{ 217 | MatchPatterns: []string{"*.go"}, 218 | SizeGreater: 1, // Ignore empty files 219 | }, 220 | ) 221 | 222 | sources = filterSources(sources) 223 | makefile := generateMakefile(sources, dir) 224 | 225 | exportMakefile(makefile) 226 | } 227 | 228 | // filterSources removes sources from vendor directory from sources list 229 | func filterSources(sources []string) []string { 230 | var result []string 231 | 232 | for _, source := range sources { 233 | if strings.HasPrefix(source, "vendor/") { 234 | continue 235 | } 236 | 237 | result = append(result, source) 238 | } 239 | 240 | return result 241 | } 242 | 243 | // exportMakefile renders makefile and write data to file 244 | func exportMakefile(makefile *Makefile) { 245 | switch { 246 | case makefile.DepUsed: 247 | fmtc.Println("{r}▲ Warning! Dep is deprecated and should not be used for new projects.{!}\n") 248 | case makefile.GlideUsed: 249 | fmtc.Println("{r}▲ Warning! Glide is deprecated and should not be used for new projects.{!}\n") 250 | } 251 | 252 | err := os.WriteFile(options.GetS(OPT_OUTPUT), makefile.Render(), 0644) 253 | 254 | if err != nil { 255 | terminal.Error(err) 256 | os.Exit(1) 257 | } 258 | 259 | fmtc.Printfn("{g}Makefile successfully created as {g*}%s{!}", options.GetS(OPT_OUTPUT)) 260 | } 261 | 262 | // generateMakefile collects imports, process options and generate makefile struct 263 | func generateMakefile(sources []string, dir string) *Makefile { 264 | makefile := collectImports(sources, dir) 265 | goVersion := getGoVersion() 266 | 267 | applyOptionsFromMakefile(dir+"/"+options.GetS(OPT_OUTPUT), makefile) 268 | 269 | makefile.Benchmark = makefile.Benchmark || options.GetB(OPT_BENCHMARK) 270 | makefile.Race = makefile.Race || options.GetB(OPT_RACE) 271 | makefile.CGO = makefile.CGO || options.GetB(OPT_CGO) 272 | makefile.Strip = makefile.Strip || options.GetB(OPT_STRIP) 273 | makefile.GlideUsed = makefile.GlideUsed || options.GetB(OPT_GLIDE) || fsutil.IsExist(dir+"/glide.yaml") 274 | makefile.DepUsed = makefile.DepUsed || options.GetB(OPT_DEP) || fsutil.IsExist(dir+"/Gopkg.toml") 275 | makefile.ModUsed = makefile.ModUsed || options.GetB(OPT_MOD) || fsutil.IsExist(dir+"/go.mod") 276 | 277 | if !goVersion.IsZero() && (goVersion.Major() > 1 || goVersion.Minor() > 17) { 278 | makefile.ModUsed = true 279 | } 280 | 281 | makefile.HasStableImports = containsStableImports(makefile.BaseImports) 282 | makefile.HasStableImports = makefile.HasStableImports || containsStableImports(makefile.TestImports) 283 | 284 | makefile.Cleanup(dir) 285 | 286 | return makefile 287 | } 288 | 289 | // collectImports collects import from source files and returns imports for 290 | // base sources, test sources and slice with binaries 291 | func collectImports(sources []string, dir string) *Makefile { 292 | baseSources, testSources := splitSources(sources) 293 | 294 | baseImports, binaries, hasSubPkgs := extractBaseImports(baseSources, dir) 295 | testImports, testPaths := extractTestImports(testSources, dir) 296 | fuzzPaths := collectFuzzPaths(baseSources, dir) 297 | 298 | return &Makefile{ 299 | BaseImports: baseImports, 300 | TestImports: testImports, 301 | FuzzPaths: fuzzPaths, 302 | TestPaths: testPaths, 303 | PkgBase: getBasePkgPath(dir), 304 | Binaries: binaries, 305 | HasTests: hasTests(sources), 306 | HasSubpackages: hasSubPkgs, 307 | } 308 | } 309 | 310 | // splitSources splits sources to two slices - with base sources and test sources 311 | func splitSources(sources []string) ([]string, []string) { 312 | if !hasTests(sources) { 313 | return sources, nil 314 | } 315 | 316 | var bSources, tSources []string 317 | 318 | for _, source := range sources { 319 | if isTestSource(source) { 320 | tSources = append(tSources, source) 321 | } else { 322 | bSources = append(bSources, source) 323 | } 324 | } 325 | 326 | return bSources, tSources 327 | } 328 | 329 | // extractBaseImports extracts base imports from given source files 330 | func extractBaseImports(sources []string, dir string) ([]string, []string, bool) { 331 | importsMap := make(map[string]bool) 332 | binaries := make([]string, 0) 333 | hasSubPkgs := false 334 | 335 | for _, source := range sources { 336 | imports, isBinary := extractImports(source, dir) 337 | 338 | for _, path := range imports { 339 | importsMap[path] = true 340 | } 341 | 342 | // Append to slice only binaries in root directory 343 | if isBinary && !strings.Contains(source, "/") { 344 | binaries = append(binaries, source) 345 | } 346 | 347 | if !hasSubPkgs && strings.Contains(source, "/") { 348 | hasSubPkgs = true 349 | } 350 | } 351 | 352 | return importMapToSlice(importsMap), binaries, hasSubPkgs 353 | } 354 | 355 | // extractTestImports extracts test imports from given source files 356 | func extractTestImports(sources []string, dir string) ([]string, []string) { 357 | if len(sources) == 0 { 358 | return nil, nil 359 | } 360 | 361 | importsMap := make(map[string]bool) 362 | testPaths := make(map[string]bool) 363 | 364 | for _, source := range sources { 365 | imports, _ := extractImports(source, dir) 366 | basePath := path.Dir(source) 367 | 368 | for _, path := range imports { 369 | importsMap[path] = true 370 | } 371 | 372 | testPaths["./"+basePath] = true 373 | } 374 | 375 | return importMapToSlice(importsMap), importMapToSlice(testPaths) 376 | } 377 | 378 | // collectFuzzPaths collects paths with fuzz tests 379 | func collectFuzzPaths(sources []string, dir string) []string { 380 | var result []string 381 | 382 | for _, source := range sources { 383 | if hasFuzzTests(source, dir) { 384 | result = append(result, path.Dir(source)) 385 | } 386 | } 387 | 388 | return result 389 | } 390 | 391 | // cleanupImports removes internal packages and local imports 392 | func cleanupImports(imports []string, dir string) []string { 393 | if len(imports) == 0 { 394 | return nil 395 | } 396 | 397 | result := make(map[string]bool) 398 | gopath := os.Getenv("GOPATH") 399 | basePath := getBasePkgPath(dir) 400 | 401 | for _, imp := range imports { 402 | if !isExternalPackage(imp) { 403 | continue 404 | } 405 | 406 | if strings.HasPrefix(imp, basePath) { 407 | continue 408 | } 409 | 410 | result[getPackageRoot(imp, gopath)] = true 411 | } 412 | 413 | return importMapToSlice(result) 414 | } 415 | 416 | // cleanupBinaries removes .go suffix from names of binaries 417 | func cleanupBinaries(binaries []string) []string { 418 | var result []string 419 | 420 | for _, bin := range binaries { 421 | result = append(result, strings.TrimSuffix(bin, ".go")) 422 | } 423 | 424 | return result 425 | } 426 | 427 | // extractImports returns slice with all imports in source file 428 | func extractImports(source, dir string) ([]string, bool) { 429 | fset := token.NewFileSet() 430 | file := path.Join(dir, source) 431 | f, err := parser.ParseFile(fset, file, nil, parser.ImportsOnly) 432 | 433 | if err != nil { 434 | terminal.Error(err) 435 | os.Exit(1) 436 | } 437 | 438 | var result []string 439 | var isBinary bool 440 | 441 | for _, imp := range f.Imports { 442 | if f.Name.String() == "main" { 443 | isBinary = true 444 | } 445 | 446 | result = append(result, strings.Trim(imp.Path.Value, "\"")) 447 | } 448 | 449 | return result, isBinary 450 | } 451 | 452 | // hasFuzzTest returns true if given source package 453 | func hasFuzzTests(source, dir string) bool { 454 | fset := token.NewFileSet() 455 | file := path.Join(dir, source) 456 | f, err := parser.ParseFile(fset, file, nil, parser.ParseComments) 457 | 458 | if err != nil { 459 | terminal.Error(err) 460 | os.Exit(1) 461 | } 462 | 463 | if len(f.Comments) == 0 { 464 | return false 465 | } 466 | 467 | return strings.Contains(f.Comments[0].Text(), "+build gofuzz") 468 | } 469 | 470 | // hasTests returns true if project has tests 471 | func hasTests(sources []string) bool { 472 | for _, source := range sources { 473 | if isTestSource(source) { 474 | return true 475 | } 476 | } 477 | 478 | return false 479 | } 480 | 481 | // isTestSource returns true if given file is tests 482 | func isTestSource(source string) bool { 483 | return strings.HasSuffix(source, "_test.go") 484 | } 485 | 486 | // getPackageRoot returns root for package 487 | func getPackageRoot(pkg, gopath string) string { 488 | if isPackageRoot(gopath + "/src/" + pkg) { 489 | return pkg 490 | } 491 | 492 | pkgSlice := strings.Split(pkg, "/") 493 | 494 | for i := 2; i < len(pkgSlice); i++ { 495 | path := strings.Join(pkgSlice[:i], "/") 496 | 497 | if isPackageRoot(gopath + "/src/" + path) { 498 | return path 499 | } 500 | } 501 | 502 | return pkg 503 | } 504 | 505 | // isPackageRoot returns true if given path is root for package 506 | func isPackageRoot(path string) bool { 507 | if !fsutil.IsExist(path + "/.git") { 508 | return false 509 | } 510 | 511 | files := fsutil.List(path, true, fsutil.ListingFilter{MatchPatterns: []string{"*.go"}}) 512 | 513 | return len(files) != 0 514 | } 515 | 516 | // isExternalPackage returns true if given package is external 517 | func isExternalPackage(pkg string) bool { 518 | pkgSlice := strings.Split(pkg, "/") 519 | 520 | if len(pkgSlice) == 0 || !strings.Contains(pkgSlice[0], ".") { 521 | return false 522 | } 523 | return true 524 | } 525 | 526 | // importMapToSlice converts map with package names to string slice 527 | func importMapToSlice(imports map[string]bool) []string { 528 | if len(imports) == 0 { 529 | return nil 530 | } 531 | 532 | var result []string 533 | 534 | for path := range imports { 535 | result = append(result, path) 536 | } 537 | 538 | sort.Strings(result) 539 | 540 | return result 541 | } 542 | 543 | // containsPackage returns true if imports contains given packages 544 | func containsPackage(imports []string, pkgs []string) bool { 545 | for _, pkg := range pkgs { 546 | if slices.Contains(imports, pkg) { 547 | return true 548 | } 549 | } 550 | 551 | return false 552 | } 553 | 554 | // getBasePkgPath returns base package path 555 | func getBasePkgPath(dir string) string { 556 | gopath, _ := filepath.EvalSymlinks(os.Getenv("GOPATH")) 557 | absDir, _ := filepath.Abs(dir) 558 | absDir, _ = filepath.EvalSymlinks(absDir) 559 | 560 | return strutil.Exclude(absDir, gopath+"/src/") 561 | } 562 | 563 | // containsStableImports returns true if imports contains stable import services path 564 | func containsStableImports(imports []string) bool { 565 | if len(imports) == 0 { 566 | return false 567 | } 568 | 569 | for _, pkg := range imports { 570 | if strings.HasPrefix(pkg, "gopkg.in") { 571 | return true 572 | } 573 | } 574 | 575 | return false 576 | } 577 | 578 | // applyOptionsFromFile reads used options from previously generated Makefile 579 | // and applies it to makefile struct 580 | func applyOptionsFromMakefile(file string, m *Makefile) { 581 | if !fsutil.IsExist(file) { 582 | return 583 | } 584 | 585 | opts := extractOptionsFromMakefile(file) 586 | 587 | if opts == "" { 588 | return 589 | } 590 | 591 | for _, opt := range strutil.Fields(opts) { 592 | switch strings.TrimLeft(opt, "-") { 593 | case getOptionName(OPT_GLIDE): 594 | m.GlideUsed = true 595 | case getOptionName(OPT_DEP): 596 | m.DepUsed = true 597 | case getOptionName(OPT_STRIP): 598 | m.Strip = true 599 | case getOptionName(OPT_BENCHMARK): 600 | m.Benchmark = true 601 | case getOptionName(OPT_RACE): 602 | m.Race = true 603 | case getOptionName(OPT_CGO): 604 | m.CGO = true 605 | } 606 | } 607 | } 608 | 609 | // extractOptionsFromMakefile extracts options from previously generated Makefile 610 | func extractOptionsFromMakefile(file string) string { 611 | fd, err := os.OpenFile(file, os.O_RDONLY, 0) 612 | 613 | if err != nil { 614 | return "" 615 | } 616 | 617 | defer fd.Close() 618 | 619 | r := bufio.NewReader(fd) 620 | s := bufio.NewScanner(r) 621 | 622 | for s.Scan() { 623 | text := s.Text() 624 | 625 | if !strings.HasPrefix(text, "# gomakegen ") { 626 | continue 627 | } 628 | 629 | return strutil.Exclude(text, "# gomakegen ") 630 | } 631 | 632 | return "" 633 | } 634 | 635 | // ////////////////////////////////////////////////////////////////////////////////// // 636 | 637 | // Cleanup cleans imports and binaries 638 | func (m *Makefile) Cleanup(dir string) { 639 | m.BaseImports = cleanupImports(m.BaseImports, dir) 640 | m.TestImports = cleanupImports(m.TestImports, dir) 641 | 642 | m.Binaries = cleanupBinaries(m.Binaries) 643 | 644 | sort.Strings(m.Binaries) 645 | } 646 | 647 | // Render returns makefile data 648 | func (m *Makefile) Render() []byte { 649 | var result string 650 | 651 | result += m.getHeader() 652 | result += m.getTargets() 653 | 654 | return []byte(result) 655 | } 656 | 657 | // ////////////////////////////////////////////////////////////////////////////////// // 658 | 659 | // getHeader returns header data 660 | func (m *Makefile) getHeader() string { 661 | var result string 662 | 663 | result += getSeparator() + "\n\n" 664 | result += m.getGenerationComment() 665 | result += getSeparator() + "\n\n" 666 | result += m.getDefaultVariables() 667 | result += getSeparator() + "\n\n" 668 | result += m.getDefaultGoal() + "\n" 669 | result += m.getPhony() + "\n" 670 | result += getSeparator() + "\n\n" 671 | 672 | return result 673 | } 674 | 675 | // getTargets returns targets data 676 | func (m *Makefile) getTargets() string { 677 | var result string 678 | 679 | result += m.getBinTarget() 680 | result += m.getInstallTarget() 681 | result += m.getUninstallTarget() 682 | result += m.getInitTarget() 683 | result += m.getDepsTarget() 684 | result += m.getTestDepsTarget() 685 | result += m.getUpdateTarget() 686 | result += m.getVendorTarget() 687 | result += m.getTestTarget() 688 | result += m.getFuzzTarget() 689 | result += m.getBenchTarget() 690 | result += m.getGlideTarget() 691 | result += m.getDepTarget() 692 | result += m.getModTarget() 693 | result += m.getFmtTarget() 694 | result += m.getVetTarget() 695 | result += m.getCleanTarget() 696 | result += m.getHelpTarget() 697 | 698 | result += getSeparator() + "\n" 699 | 700 | return result 701 | } 702 | 703 | // codebeat:disable[ABC] 704 | 705 | // getPhony returns PHONY part of makefile 706 | func (m *Makefile) getPhony() string { 707 | phony := []string{"fmt", "vet"} 708 | 709 | if len(m.Binaries) != 0 { 710 | phony = append(phony, "all", "install", "uninstall", "clean") 711 | } 712 | 713 | if len(m.BaseImports) != 0 || m.ModUsed { 714 | phony = append(phony, "deps", "update") 715 | } 716 | 717 | if len(m.TestImports) != 0 { 718 | phony = append(phony, "test") 719 | } 720 | 721 | if !m.GlideUsed && !m.DepUsed && !m.ModUsed { 722 | if len(m.TestImports) != 0 { 723 | phony = append(phony, "deps-test") 724 | } 725 | } else { 726 | phony = append(phony, "init", "vendor") 727 | } 728 | 729 | if len(m.FuzzPaths) != 0 { 730 | phony = append(phony, "gen-fuzz") 731 | } 732 | 733 | if m.Benchmark { 734 | phony = append(phony, "benchmark") 735 | } 736 | 737 | for _, target := range phony { 738 | m.MaxTargetNameSize = mathutil.Max(m.MaxTargetNameSize, len(target)) 739 | } 740 | 741 | if m.GlideUsed { 742 | phony = append(phony, "glide-create", "glide-install", "glide-update") 743 | } 744 | 745 | if m.DepUsed { 746 | phony = append(phony, "dep-init", "dep-update", "dep-vendor") 747 | } 748 | 749 | if m.ModUsed { 750 | phony = append(phony, "tidy", "mod-init", "mod-update", "mod-download", "mod-vendor") 751 | } 752 | 753 | phony = append(phony, "help") 754 | 755 | return ".PHONY = " + strings.Join(phony, " ") + "\n" 756 | } 757 | 758 | // codebeat:enable[ABC] 759 | 760 | // getDefaultGoal returns DEFAULT_GOAL part of makefile 761 | func (m *Makefile) getDefaultGoal() string { 762 | return ".DEFAULT_GOAL := help" 763 | } 764 | 765 | // getBinTarget generates target for "all" command and all sub-targets 766 | // for each binary 767 | func (m *Makefile) getBinTarget() string { 768 | if len(m.Binaries) == 0 { 769 | return "" 770 | } 771 | 772 | result := "all: " + strings.Join(m.Binaries, " ") + " ## Build all binaries\n\n" 773 | 774 | for i, bin := range m.Binaries { 775 | result += bin + ":\n" 776 | result += getActionText(i+1, len(m.Binaries), "Building "+bin+"…") 777 | 778 | ldFlags := m.getLDFlags() 779 | 780 | if ldFlags != "" { 781 | result += "\t@go build $(VERBOSE_FLAG) -ldflags=\"" + ldFlags + "\" " + bin + ".go\n" 782 | } else { 783 | result += "\t@go build $(VERBOSE_FLAG) " + bin + ".go\n" 784 | } 785 | 786 | result += "\n" 787 | } 788 | 789 | return result 790 | } 791 | 792 | // getInstallTarget generates target for "install" command 793 | func (m *Makefile) getInstallTarget() string { 794 | if len(m.Binaries) == 0 { 795 | return "" 796 | } 797 | 798 | result := "install: ## Install all binaries\n" 799 | result += getActionText(1, 1, "Installing binaries…") 800 | 801 | for _, bin := range m.Binaries { 802 | result += "\t@cp " + bin + " /usr/bin/" + bin + "\n" 803 | } 804 | 805 | return result + "\n" 806 | } 807 | 808 | // getUninstallTarget generates target for "uninstall" command 809 | func (m *Makefile) getUninstallTarget() string { 810 | if len(m.Binaries) == 0 { 811 | return "" 812 | } 813 | 814 | result := "uninstall: ## Uninstall all binaries\n" 815 | result += getActionText(1, 1, "Removing installed binaries…") 816 | 817 | for _, bin := range m.Binaries { 818 | result += "\t@rm -f /usr/bin/" + bin + "\n" 819 | } 820 | 821 | return result + "\n" 822 | } 823 | 824 | // getInitTarget generates target for "init" command 825 | func (m *Makefile) getInitTarget() string { 826 | switch { 827 | case m.GlideUsed: 828 | return "init: glide-update ## Initialize new workspace\n\n" 829 | case m.DepUsed: 830 | return "init: dep-vendor ## Initialize new workspace\n\n" 831 | case m.ModUsed: 832 | return "init: mod-init ## Initialize new module\n\n" 833 | } 834 | 835 | return "" 836 | } 837 | 838 | // getDepsTarget generates target for "deps" command 839 | func (m *Makefile) getDepsTarget() string { 840 | if len(m.BaseImports) == 0 { 841 | if m.ModUsed { 842 | return "deps: mod-download ## Download dependencies\n\n" 843 | } 844 | 845 | return "" 846 | } 847 | 848 | result := "deps: " 849 | 850 | switch { 851 | case m.GlideUsed: 852 | result += "glide-install " 853 | case m.DepUsed: 854 | result += "dep-update " 855 | case m.ModUsed: 856 | result += "mod-download " 857 | } 858 | 859 | result += "## Download dependencies\n" 860 | 861 | if m.GlideUsed || m.DepUsed || m.ModUsed { 862 | return result + "\n" 863 | } 864 | 865 | for _, pkg := range m.BaseImports { 866 | result += "\t@go get -d $(VERBOSE_FLAG) " + pkg + "\n" 867 | } 868 | 869 | return result + "\n" 870 | } 871 | 872 | // getVendorTarget generates target for "vendor" command 873 | func (m *Makefile) getVendorTarget() string { 874 | switch { 875 | case m.GlideUsed: 876 | return "vendor: glide-create ## Make vendored copy of dependencies\n\n" 877 | case m.DepUsed: 878 | return "vendor: dep-init ## Make vendored copy of dependencies\n\n" 879 | case m.ModUsed: 880 | return "vendor: mod-vendor ## Make vendored copy of dependencies\n\n" 881 | } 882 | 883 | return "" 884 | } 885 | 886 | // getUpdateTarget generates target for "update" command 887 | func (m *Makefile) getUpdateTarget() string { 888 | switch { 889 | case m.GlideUsed: 890 | return "update: glide-update ## Update dependencies to the latest versions\n\n" 891 | case m.DepUsed: 892 | return "update: dep-update ## Update dependencies to the latest versions\n\n" 893 | case m.ModUsed: 894 | return "update: mod-update ## Update dependencies to the latest versions\n\n" 895 | } 896 | 897 | result := "update: ## Update dependencies to the latest versions\n" 898 | result += getActionText(1, 1, "Updating dependencies…") 899 | result += "\t@go get -d -u $(VERBOSE_FLAG) ./...\n\n" 900 | 901 | return result 902 | } 903 | 904 | // getDepsTarget generates target for "deps-test" command 905 | func (m *Makefile) getTestDepsTarget() string { 906 | if len(m.TestImports) == 0 { 907 | return "" 908 | } 909 | 910 | pkgMngUsed := m.DepUsed || m.GlideUsed || m.ModUsed 911 | 912 | if pkgMngUsed { 913 | return "" 914 | } 915 | 916 | result := "deps-test: ## Download dependencies for tests\n" 917 | result += getActionText(1, 1, "Downloading tests dependencies…") 918 | 919 | if !pkgMngUsed { 920 | for _, pkg := range m.TestImports { 921 | result += "\t@go get -d $(VERBOSE_FLAG) " + pkg + "\n" 922 | } 923 | } 924 | 925 | return result + "\n" 926 | } 927 | 928 | // getTestTarget generates target for "test" command 929 | func (m *Makefile) getTestTarget() string { 930 | if !m.HasTests { 931 | return "" 932 | } 933 | 934 | targets := "." 935 | 936 | if m.HasSubpackages { 937 | if len(m.TestPaths) > 3 { 938 | targets = "./..." 939 | } else { 940 | targets = strings.Join(m.TestPaths, " ") 941 | } 942 | } 943 | 944 | testTarget := "@go test $(VERBOSE_FLAG)" 945 | 946 | if m.Race { 947 | testTarget += " -race -covermode=atomic" 948 | } else { 949 | testTarget += " -covermode=count" 950 | } 951 | 952 | result := "test: ## Run tests\n" 953 | result += getActionText(1, 1, "Starting tests…") 954 | result += "ifdef COVERAGE_FILE ## Save coverage data into file (String)\n" 955 | result += "\t" + testTarget + " -coverprofile=$(COVERAGE_FILE) " + strings.Join(m.TestPaths, " ") + "\n" 956 | result += "else\n" 957 | result += "\t" + testTarget + " " + targets + "\n" 958 | result += "endif\n\n" 959 | 960 | m.MaxOptionNameSize = mathutil.Max(m.MaxOptionNameSize, len("COVERAGE_FILE")) 961 | 962 | return result 963 | } 964 | 965 | // getFuzzTarget generates target for "fuzz" command 966 | func (m *Makefile) getFuzzTarget() string { 967 | if len(m.FuzzPaths) == 0 { 968 | return "" 969 | } 970 | 971 | result := "gen-fuzz: ## Generate archives for fuzz testing\n" 972 | result += "\t@which go-fuzz-build &>/dev/null || go install github.com/dvyukov/go-fuzz/go-fuzz-build@latest\n" 973 | result += getActionText(1, 1, "Generating fuzzing data…") 974 | 975 | for _, pkg := range m.FuzzPaths { 976 | if pkg == "." { 977 | result += fmt.Sprintf("\t@go-fuzz-build -o fuzz.zip %s\n", m.PkgBase) 978 | } else { 979 | pkgName := strings.ReplaceAll(pkg, "/", "-") 980 | binName := pkgName + "-fuzz.zip" 981 | 982 | result += fmt.Sprintf("\t@go-fuzz-build -o %s %s/%s\n", binName, m.PkgBase, pkg) 983 | } 984 | } 985 | 986 | return result + "\n" 987 | } 988 | 989 | // getBenchTarget generates target for "benchmark" command 990 | func (m *Makefile) getBenchTarget() string { 991 | if !m.Benchmark { 992 | return "" 993 | } 994 | 995 | result := "benchmark: ## Run benchmarks\n" 996 | result += getActionText(1, 1, "Starting benchmarks…") 997 | 998 | if containsPackage(m.TestImports, checkPackageImports) { 999 | result += "\t@go test -check.v -check.b -check.bmem\n" 1000 | } else { 1001 | result += "\t@go test -bench=.\n" 1002 | } 1003 | 1004 | return result + "\n" 1005 | } 1006 | 1007 | // getFmtTarget generates target for "fmt" command 1008 | func (m *Makefile) getFmtTarget() string { 1009 | result := "fmt: ## Format source code with gofmt\n" 1010 | result += getActionText(1, 1, "Formatting sources…") 1011 | result += "\t@find . -name \"*.go\" -exec gofmt -s -w {} \\;\n" 1012 | 1013 | return result + "\n" 1014 | } 1015 | 1016 | // getVetTarget generates target for "vet" command 1017 | func (m *Makefile) getVetTarget() string { 1018 | result := "vet: ## Runs 'go vet' over sources\n" 1019 | result += getActionText(1, 1, "Running 'go vet' over sources…") 1020 | result += "\t@go vet -composites=false -printfuncs=LPrintf,TLPrintf,TPrintf,log.Debug,log.Info,log.Warn,log.Error,log.Critical,log.Print ./...\n" 1021 | 1022 | return result + "\n" 1023 | } 1024 | 1025 | // getCleanTarget generates target for "clean" command 1026 | func (m *Makefile) getCleanTarget() string { 1027 | if len(m.Binaries) == 0 { 1028 | return "" 1029 | } 1030 | 1031 | result := "clean: ## Remove generated files\n" 1032 | result += getActionText(1, 1, "Removing built binaries…") 1033 | 1034 | for _, bin := range m.Binaries { 1035 | result += "\t@rm -f " + bin + "\n" 1036 | } 1037 | 1038 | return result + "\n" 1039 | } 1040 | 1041 | // getGlideTarget generates target for "glide-install" and 1042 | // "glide-update" commands 1043 | func (m *Makefile) getGlideTarget() string { 1044 | if !m.GlideUsed { 1045 | return "" 1046 | } 1047 | 1048 | result := "glide-create:\n" 1049 | result += getActionText(1, 1, "Glide initialization…") 1050 | result += "\t@which glide &>/dev/null || (printf '\\e[31mGlide is not installed\\e[0m' ; exit 1)\n" 1051 | result += "\t@glide init\n" 1052 | result += "\n" 1053 | 1054 | result += "glide-install:\n" 1055 | result += getActionText(1, 1, "Installing dependencies…") 1056 | result += "\t@which glide &>/dev/null || (printf '\\e[31mGlide is not installed\\e[0m' ; exit 1)\n" 1057 | result += "\t@test -s glide.yaml || glide init\n" 1058 | result += "\t@glide install\n" 1059 | result += "\n" 1060 | 1061 | result += "glide-update:\n" 1062 | result += getActionText(1, 1, "Updating dependencies…") 1063 | result += "\t@which glide &>/dev/null || (printf '\\e[31mGlide is not installed\\e[0m' ; exit 1)\n" 1064 | result += "\t@test -s glide.yaml || glide init\n" 1065 | result += "\t@glide update\n\n" 1066 | 1067 | return result 1068 | } 1069 | 1070 | // getDepTarget generate target for "dep-init" and "dep-update" commands 1071 | func (m *Makefile) getDepTarget() string { 1072 | if !m.DepUsed { 1073 | return "" 1074 | } 1075 | 1076 | result := "dep-init:\n" 1077 | result += getActionText(1, 1, "Dep initialization…") 1078 | result += "\t@which dep &>/dev/null || go get -u -v github.com/golang/dep/cmd/dep\n" 1079 | result += "\t@dep init\n\n" 1080 | 1081 | result += "dep-update:\n" 1082 | result += getActionText(1, 1, "Updating dependencies…") 1083 | result += "\t@which dep &>/dev/null || go get -u -v github.com/golang/dep/cmd/dep\n" 1084 | result += "\t@test -s Gopkg.toml || dep init\n" 1085 | result += "\t@test -s Gopkg.lock && dep ensure -update || dep ensure\n\n" 1086 | 1087 | result += "dep-vendor:\n" 1088 | result += getActionText(1, 1, "Vendoring dependencies…") 1089 | result += "\t@which dep &>/dev/null || go get -u -v github.com/golang/dep/cmd/dep\n" 1090 | result += "\t@dep ensure\n\n" 1091 | 1092 | return result 1093 | } 1094 | 1095 | // getModTarget generates target for "mod-init" and "mod-update" commands 1096 | func (m *Makefile) getModTarget() string { 1097 | if !m.ModUsed { 1098 | return "" 1099 | } 1100 | 1101 | result := "tidy: ## Cleanup dependencies\n" 1102 | result += getActionText(1, 2, "Tidying up dependencies…") 1103 | result += "ifdef COMPAT ## Compatible Go version (String)\n" 1104 | result += "\t@go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT) -go=$(COMPAT)\n" 1105 | result += "else\n" 1106 | result += "\t@go mod tidy $(VERBOSE_FLAG)\n" 1107 | result += "endif\n" 1108 | result += getActionText(2, 2, "Updating vendored dependencies…") 1109 | result += "\t@test -d vendor && rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || :\n\n" 1110 | 1111 | result += "mod-init:\n" 1112 | result += getActionText(1, 3, "Modules initialization…") 1113 | result += "\t@rm -f go.mod go.sum\n" 1114 | result += "ifdef MODULE_PATH ## Module path for initialization (String)\n" 1115 | result += "\t@go mod init $(MODULE_PATH)\n" 1116 | result += "else\n" 1117 | result += "\t@go mod init\n" 1118 | result += "endif\n\n" 1119 | result += getActionText(2, 3, "Dependencies cleanup…") 1120 | result += "ifdef COMPAT ## Compatible Go version (String)\n" 1121 | result += "\t@go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT) -go=$(COMPAT)\n" 1122 | result += "else\n" 1123 | result += "\t@go mod tidy $(VERBOSE_FLAG)\n" 1124 | result += "endif\n" 1125 | result += getActionText(3, 3, "Stripping toolchain info…") 1126 | result += "\t@grep -q 'toolchain ' go.mod && go mod edit -toolchain=none || :\n\n" 1127 | 1128 | result += "mod-update:\n" 1129 | result += getActionText(1, 4, "Updating dependencies…") 1130 | result += "ifdef UPDATE_ALL ## Update all dependencies (Flag)\n" 1131 | result += "\t@go get -u $(VERBOSE_FLAG) all\n" 1132 | result += "else\n" 1133 | result += "\t@go get -u $(VERBOSE_FLAG) ./...\n" 1134 | result += "endif\n\n" 1135 | result += getActionText(2, 4, "Stripping toolchain info…") 1136 | result += "\t@grep -q 'toolchain ' go.mod && go mod edit -toolchain=none || :\n\n" 1137 | result += getActionText(3, 4, "Dependencies cleanup…") 1138 | result += "ifdef COMPAT\n" 1139 | result += "\t@go mod tidy $(VERBOSE_FLAG) -compat=$(COMPAT)\n" 1140 | result += "else\n" 1141 | result += "\t@go mod tidy $(VERBOSE_FLAG)\n" 1142 | result += "endif\n\n" 1143 | result += getActionText(4, 4, "Updating vendored dependencies…") 1144 | result += "\t@test -d vendor && rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || :\n\n" 1145 | 1146 | result += "mod-download:\n" 1147 | result += getActionText(1, 1, "Downloading dependencies…") 1148 | result += "\t@go mod download\n\n" 1149 | 1150 | result += "mod-vendor:\n" 1151 | result += getActionText(1, 1, "Vendoring dependencies…") 1152 | result += "\t@rm -rf vendor && go mod vendor $(VERBOSE_FLAG) || :\n\n" 1153 | 1154 | m.MaxOptionNameSize = mathutil.Max(m.MaxOptionNameSize, len("MODULE_PATH")) 1155 | 1156 | return result 1157 | } 1158 | 1159 | // getHelpTarget generates target for "help" command 1160 | func (m *Makefile) getHelpTarget() string { 1161 | targetNameSize := strconv.Itoa(m.MaxTargetNameSize) 1162 | optionNameSize := strconv.Itoa(m.MaxOptionNameSize) 1163 | 1164 | result := "help: ## Show this info\n" 1165 | result += "\t@printf '\\n\\033[1mTargets:\\033[0m\\n\\n'\n" 1166 | result += "\t@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \\\n" 1167 | result += "\t\t| awk 'BEGIN {FS = \":.*?## \"}; {printf \" \\033[33m%-" + targetNameSize + "s\\033[0m %s\\n\", $$1, $$2}'\n" 1168 | result += "\t@printf '\\n\\033[1mVariables:\\033[0m\\n\\n'\n" 1169 | result += "\t@grep -E '^ifdef [A-Z_]+ .*?## .*$$' $(abspath $(lastword $(MAKEFILE_LIST))) \\\n" 1170 | result += "\t\t| sed 's/ifdef //' \\\n" 1171 | result += "\t\t| sort -h \\\n" 1172 | result += "\t\t| awk 'BEGIN {FS = \" .*?## \"}; {printf \" \\033[32m%-" + optionNameSize + "s\\033[0m %s\\n\", $$1, $$2}'\n" 1173 | result += "\t@echo ''\n" 1174 | result += "\t@printf '\\033[90mGenerated by GoMakeGen " + VER + "\\033[0m\\n\\n'\n\n" 1175 | 1176 | return result 1177 | } 1178 | 1179 | // getGenerationComment returns comment with all used flags 1180 | func (m *Makefile) getGenerationComment() string { 1181 | result := "# This Makefile generated by GoMakeGen " + VER + " using next command:\n" 1182 | result += "# gomakegen " 1183 | 1184 | if m.GlideUsed { 1185 | result += fmt.Sprintf("--%s ", getOptionName(OPT_GLIDE)) 1186 | } 1187 | 1188 | if m.DepUsed { 1189 | result += fmt.Sprintf("--%s ", getOptionName(OPT_DEP)) 1190 | } 1191 | 1192 | if m.ModUsed { 1193 | result += fmt.Sprintf("--%s ", getOptionName(OPT_MOD)) 1194 | } 1195 | 1196 | if m.Strip { 1197 | result += fmt.Sprintf("--%s ", getOptionName(OPT_STRIP)) 1198 | } 1199 | 1200 | if m.Benchmark { 1201 | result += fmt.Sprintf("--%s ", getOptionName(OPT_BENCHMARK)) 1202 | } 1203 | 1204 | if m.Race { 1205 | result += fmt.Sprintf("--%s ", getOptionName(OPT_RACE)) 1206 | } 1207 | 1208 | if m.CGO { 1209 | result += fmt.Sprintf("--%s ", getOptionName(OPT_CGO)) 1210 | } 1211 | 1212 | result += ".\n" 1213 | result += "#\n" 1214 | result += "# More info: https://kaos.sh/gomakegen\n\n" 1215 | 1216 | return result 1217 | } 1218 | 1219 | // getDefaultVariables generates default variables definitions 1220 | func (m *Makefile) getDefaultVariables() string { 1221 | var result string 1222 | 1223 | result += "ifdef VERBOSE ## Print verbose information (Flag)\n" 1224 | result += "VERBOSE_FLAG = -v\n" 1225 | result += "endif\n\n" 1226 | 1227 | result += "ifdef PROXY ## Force proxy usage for downloading dependencies (Flag)\n" 1228 | result += "export GOPROXY=https://proxy.golang.org/cached-only,direct\n" 1229 | result += "endif\n\n" 1230 | 1231 | if m.CGO { 1232 | result += "export CGO_ENABLED=1\n\n" 1233 | } else { 1234 | result += "ifdef CGO ## Enable CGO usage (Flag)\n" 1235 | result += "export CGO_ENABLED=1\n" 1236 | result += "else\n" 1237 | result += "export CGO_ENABLED=0\n" 1238 | result += "endif\n\n" 1239 | } 1240 | 1241 | result += "MAKEDIR = $(dir $(realpath $(firstword $(MAKEFILE_LIST))))\n" 1242 | result += "GITREV ?= $(shell test -s $(MAKEDIR)/.git && git rev-parse --short HEAD)\n\n" 1243 | 1244 | return result 1245 | } 1246 | 1247 | // getLDFlags returns LDFLAGS for build command 1248 | func (m *Makefile) getLDFlags() string { 1249 | var flags []string 1250 | 1251 | if m.Strip { 1252 | flags = append(flags, "-s", "-w") 1253 | } 1254 | 1255 | flags = append(flags, "-X main.gitrev=$(GITREV)") 1256 | 1257 | return strings.Join(flags, " ") 1258 | } 1259 | 1260 | // ////////////////////////////////////////////////////////////////////////////////// // 1261 | 1262 | // getActionText generates command with action description 1263 | func getActionText(cur, total int, text string) string { 1264 | if total <= 1 { 1265 | return fmtc.Sprintfn("\t@echo \"{c*}%s{!}\"", text) 1266 | } 1267 | 1268 | var buf bytes.Buffer 1269 | 1270 | buf.WriteString("\t@echo \"") 1271 | buf.WriteString(fmtc.Sprintf("{g}%s{!}", strings.Repeat("•", cur))) 1272 | 1273 | if cur != total { 1274 | buf.WriteString(fmtc.Sprintf("{s-}%s{!}", strings.Repeat("•", total-cur))) 1275 | } 1276 | 1277 | buf.WriteString(fmtc.Sprintf(" {c*}%s{!}\"\n", text)) 1278 | 1279 | return buf.String() 1280 | } 1281 | 1282 | // getGoVersion returns current go version 1283 | func getGoVersion() version.Version { 1284 | cmd := exec.Command("go", "version") 1285 | output, err := cmd.Output() 1286 | 1287 | if err != nil { 1288 | return version.Version{} 1289 | } 1290 | 1291 | rawVersion := strutil.ReadField(string(output), 2, false, ' ') 1292 | rawVersion = strutil.Exclude(rawVersion, "go") 1293 | 1294 | ver, _ := version.Parse(rawVersion) 1295 | 1296 | return ver 1297 | } 1298 | 1299 | // getOptionName parses option name in options package notation 1300 | // and returns long option name 1301 | func getOptionName(opt string) string { 1302 | longOpt, _ := options.ParseOptionName(opt) 1303 | return longOpt 1304 | } 1305 | 1306 | // getSeparator returns separator 1307 | func getSeparator() string { 1308 | return strings.Repeat("#", SEPARATOR_SIZE) 1309 | } 1310 | 1311 | // ////////////////////////////////////////////////////////////////////////////////// // 1312 | 1313 | // genCompletion generates completion for different shells 1314 | func genCompletion() int { 1315 | info := genUsage() 1316 | 1317 | switch options.GetS(OPT_COMPLETION) { 1318 | case "bash": 1319 | fmt.Print(bash.Generate(info, "gomakegen")) 1320 | case "fish": 1321 | fmt.Print(fish.Generate(info, "gomakegen")) 1322 | case "zsh": 1323 | fmt.Print(zsh.Generate(info, optMap, "gomakegen")) 1324 | default: 1325 | return 1 1326 | } 1327 | 1328 | return 0 1329 | } 1330 | 1331 | // printMan prints man page 1332 | func printMan() { 1333 | fmt.Println(man.Generate(genUsage(), genAbout(""))) 1334 | } 1335 | 1336 | // genUsage generates usage info 1337 | func genUsage() *usage.Info { 1338 | info := usage.NewInfo("", "source-dir") 1339 | 1340 | info.AppNameColorTag = colorTagApp 1341 | 1342 | info.AddOption(OPT_GLIDE, "Add target to fetching dependencies with glide") 1343 | info.AddOption(OPT_DEP, "Add target to fetching dependencies with dep") 1344 | info.AddOption(OPT_MOD, "Add target to fetching dependencies with go mod {s-}(default for Go ≥ 1.18){!}") 1345 | info.AddOption(OPT_STRIP, "Strip binaries") 1346 | info.AddOption(OPT_BENCHMARK, "Add target to run benchmarks") 1347 | info.AddOption(OPT_RACE, "Add target to test race conditions") 1348 | info.AddOption(OPT_CGO, "Enable CGO usage") 1349 | info.AddOption(OPT_OUTPUT, "Output file {s-}(Makefile by default){!}", "file") 1350 | info.AddOption(OPT_NO_COLOR, "Disable colors in output") 1351 | info.AddOption(OPT_HELP, "Show this help message") 1352 | info.AddOption(OPT_VER, "Show version") 1353 | 1354 | info.AddExample( 1355 | ".", "Generate makefile for project in current directory and save as Makefile", 1356 | ) 1357 | 1358 | info.AddExample( 1359 | "$GOPATH/src/github.com/profile/project", 1360 | "Generate makefile for github.com/profile/project and save as Makefile", 1361 | ) 1362 | 1363 | info.AddExample( 1364 | "$GOPATH/src/github.com/profile/project -o project.make", 1365 | "Generate makefile for github.com/profile/project and save as project.make", 1366 | ) 1367 | 1368 | return info 1369 | } 1370 | 1371 | // genAbout generates info about version 1372 | func genAbout(gitRev string) *usage.About { 1373 | about := &usage.About{ 1374 | App: APP, 1375 | Version: VER, 1376 | Desc: DESC, 1377 | Year: 2009, 1378 | Owner: "ESSENTIAL KAOS", 1379 | 1380 | AppNameColorTag: colorTagApp, 1381 | VersionColorTag: colorTagVer, 1382 | DescSeparator: "{s}—{!}", 1383 | 1384 | License: "Apache License, Version 2.0 ", 1385 | } 1386 | 1387 | if gitRev != "" { 1388 | about.Build = "git:" + gitRev 1389 | about.UpdateChecker = usage.UpdateChecker{"essentialkaos/gomakegen", update.GitHubChecker} 1390 | } 1391 | 1392 | return about 1393 | } 1394 | --------------------------------------------------------------------------------