Compare commits

..

1 Commits

Author SHA1 Message Date
lukaszraczylo 53c059c091 Skip update test in CI. 2022-02-10 14:45:57 +00:00
20 changed files with 1135 additions and 790 deletions
-20
View File
@@ -1,20 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug, to be confirmed
assignees: lukaszraczylo
---
**Describe the bug**
A clear and concise description of what the bug is.
**Output with debug**
[ paste output of the command with `-d` flag here ]
**Expected behavior**
A clear and concise description of what you expected to happen.
**Additional context**
Add any other context about the problem here.
-11
View File
@@ -1,11 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "gomod" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
-74
View File
@@ -1,74 +0,0 @@
name: Autoupdate go.mod and go.sum
on:
workflow_dispatch:
schedule:
- cron: "0 3 * * *"
env:
GO_VERSION: ">=1.21"
jobs:
# This job is responsible for preparation of the build
# environment variables.
prepare:
name: Preparing build context
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Install Go
uses: actions/setup-go@v5
id: cache
with:
go-version: ${{env.GO_VERSION}}
cache-dependency-path: "**/*.sum"
- name: Go get dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: |
go get ./...
# This job is responsible for running tests and linting the codebase
test:
name: "Unit testing"
runs-on: ubuntu-latest
container: golang:1
needs: [prepare]
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # Ensure full history is checked out
token: ${{ secrets.GHCR_TOKEN }}
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{env.GO_VERSION}}
cache-dependency-path: "**/*.sum"
- name: Install dependencies
run: |
apt-get update
apt-get install ca-certificates make -y
update-ca-certificates
go mod tidy
go get -u -v ./...
go mod tidy -v
- name: Run unit tests
run: |
export GITHUB_TOKEN=${{ secrets.GHCR_TOKEN }}
CI_RUN=${CI} make test
git config --global --add safe.directory /__w/semver-generator/semver-generator
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "Update go.mod and go.sum"
commit_options: "--no-verify --signoff"
file_pattern: "go.mod go.sum"
+88 -91
View File
@@ -6,7 +6,6 @@ on:
paths-ignore:
- '**.md'
- '**/release.yaml'
- 'action.yml'
branches:
- "master"
- "main"
@@ -15,7 +14,6 @@ env:
ENABLE_CODE_LINT: false
ENABLE_CODE_SCANS: false
DEPLOY: false
GO_VERSION: 1.21
jobs:
prepare:
@@ -30,29 +28,27 @@ jobs:
RELEASE_VERSION: ${{ steps.get_env.outputs.RELEASE_VERSION }}
steps:
- name: Checkout repo
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
fetch-depth: '0'
- name: Setting environment variables
id: get_env
run: |
DOWNLOAD_URL=$(curl -s https://api.github.com/repos/lukaszraczylo/semver-generator/releases/latest | grep -E ".*browser_download_url.*linux-" | grep -vE "(arm64|md5)" \
DOWNLOAD_URL=$(curl -s https://api.github.com/repos/lukaszraczylo/semver-generator/releases/latest \
| grep browser_download_url \
| grep semver-gen-linux-amd64 \
| cut -d '"' -f 4)
curl -s -L -o semver-gen "$DOWNLOAD_URL" && chmod +x semver-gen
TMP_SANITISED_REPOSITORY_NAME=$(echo ${{ github.event.repository.name }} | sed -e 's|\.|-|g')
TMP_GITHUB_COMMITS_COUNT=$(git rev-list --count HEAD)
TMP_GITHUB_COUNT_NUMBER=$(echo ${GITHUB_RUN_NUMBER})
TMP_RELEASE_VERSION=$(./semver-gen generate -l -c config-release.yaml | sed -e 's|SEMVER ||g')
echo ">> Release version: $TMP_RELEASE_VERSION <<"
# Setting outputs
echo "SANITISED_REPOSITORY_NAME=$TMP_SANITISED_REPOSITORY_NAME" > $GITHUB_OUTPUT
echo "DOCKER_IMAGE=ghcr.io/${{ github.repository_owner }}/$TMP_SANITISED_REPOSITORY_NAME" >> $GITHUB_OUTPUT
echo "GITHUB_COMMIT_NUMBER=$TMP_GITHUB_COMMITS_COUNT" >> $GITHUB_OUTPUT
echo "GITHUB_SHA=$(echo ${GITHUB_SHA::8})" >> $GITHUB_OUTPUT
echo "GITHUB_RUN_ID=$TMP_GITHUB_COUNT_NUMBER" >> $GITHUB_OUTPUT
echo "RELEASE_VERSION=$TMP_RELEASE_VERSION" >> $GITHUB_OUTPUT
echo "::set-output name=SANITISED_REPOSITORY_NAME::$TMP_SANITISED_REPOSITORY_NAME"
echo "::set-output name=DOCKER_IMAGE::ghcr.io/${{ github.repository_owner }}/$TMP_SANITISED_REPOSITORY_NAME"
echo "::set-output name=GITHUB_COMMIT_NUMBER::$TMP_GITHUB_COMMITS_COUNT"
echo "::set-output name=GITHUB_SHA::$(echo ${GITHUB_SHA::8})"
echo "::set-output name=GITHUB_RUN_ID::$TMP_GITHUB_COUNT_NUMBER"
echo "::set-output name=RELEASE_VERSION::$TMP_RELEASE_VERSION"
test:
needs: [ prepare ]
@@ -63,11 +59,7 @@ jobs:
CI: true
steps:
- name: Checkout repo
uses: actions/checkout@v3
- name: Install Go
uses: actions/setup-go@v3
with:
go-version: ${{ env.GO_VERSION }}
uses: actions/checkout@v2
- name: Lint Code Base
if: env.ENABLE_CODE_LINT == true
env:
@@ -86,12 +78,11 @@ jobs:
run: |
make test CI_RUN=${CI}
- name: Upload codecov result
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v1
continue-on-error: true
with:
token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos
files: coverage.out
fail_ci_if_error: false
code_scans:
needs: [ prepare ]
@@ -99,11 +90,7 @@ jobs:
runs-on: ubuntu-20.04
steps:
- name: Checkout repo
uses: actions/checkout@v3
- name: Install Go
uses: actions/setup-go@v3
with:
go-version: ${{ env.GO_VERSION }}
uses: actions/checkout@v2
- name: Configure git for private modules
run: |
make update
@@ -118,70 +105,20 @@ jobs:
with:
args: ./...
build-binary:
build:
needs: [ prepare, test, code_scans ]
name: Binary compilation and release
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Install Go
uses: actions/setup-go@v3
with:
go-version: ${{ env.GO_VERSION }}
- name: Build binaries
run: |
LOCAL_VERSION=${{ needs.prepare.outputs.RELEASE_VERSION }} make dist-release
- name: Get list of the commits since last release
run: |
echo "$(git log $(git describe --tags --abbrev=0)..HEAD --pretty=format:"%h %s")" > .release_notes
- name: Create release [semver]
uses: ncipollo/release-action@v1
with:
bodyFile: ./.release_notes
name: version ${{ needs.prepare.outputs.RELEASE_VERSION }}
token: ${{ secrets.GHCR_TOKEN }}
tag: ${{ needs.prepare.outputs.RELEASE_VERSION }}
prerelease: ${{ github.ref != 'refs/heads/master' && github.ref != 'refs/heads/main' }}
artifacts: "dist/*"
allowUpdates: true
- name: Delete existing v1 tag and release
run: |
gh release delete v1 --cleanup-tag -y
env:
GH_TOKEN: ${{ secrets.GHCR_TOKEN }}
- name: Create release [v1]
uses: ncipollo/release-action@v1
with:
bodyFile: ./.release_notes
name: v1 - ${{ needs.prepare.outputs.RELEASE_VERSION }}
token: ${{ secrets.GHCR_TOKEN }}
tag: v1
prerelease: ${{ github.ref != 'refs/heads/master' && github.ref != 'refs/heads/main' }}
artifacts: "dist/*"
allowUpdates: true
makeLatest: false
build-docker:
needs: [ prepare, test, code_scans, build-binary ]
name: Docker image build
name: Docker image build (regular:multiarch)
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v3
uses: actions/checkout@v2
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
uses: docker/setup-buildx-action@v1
- name: Login to GHCR
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.ACTOR }}
@@ -189,24 +126,20 @@ jobs:
- name: Prepare for push
id: prep
run: |
if [ -z "${{ needs.prepare.outputs.RELEASE_VERSION }}" ]; then
TAGS="${{ needs.prepare.outputs.DOCKER_IMAGE }}:${{ needs.prepare.outputs.GITHUB_SHA }},${{ needs.prepare.outputs.DOCKER_IMAGE }}:latest,${{ needs.prepare.outputs.DOCKER_IMAGE }}:v1"
else
TAGS="${{ needs.prepare.outputs.DOCKER_IMAGE }}:${{ needs.prepare.outputs.GITHUB_SHA }},${{ needs.prepare.outputs.DOCKER_IMAGE }}:${{ needs.prepare.outputs.RELEASE_VERSION }},${{ needs.prepare.outputs.DOCKER_IMAGE }}:latest,${{ needs.prepare.outputs.DOCKER_IMAGE }}:v1"
fi
echo "TAGS=$TAGS" >> $GITHUB_OUTPUT
TAGS="${{ needs.prepare.outputs.DOCKER_IMAGE }}:${{ needs.prepare.outputs.GITHUB_SHA }},${{ needs.prepare.outputs.DOCKER_IMAGE }}:${{ needs.prepare.outputs.RELEASE_VERSION }},${{ needs.prepare.outputs.DOCKER_IMAGE }}:latest"
echo ::set-output name=tags::${TAGS}
BRANCH=$(echo ${GITHUB_REF##*/} | tr '[A-Z]' '[a-z]')
LABELS="org.opencontainers.image.revision=${{ needs.prepare.outputs.GITHUB_SHA }}"
LABELS="$LABELS,org.opencontainers.image.created=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
LABELS="$LABELS,org.opencontainers.image.version=$VERSION"
LABELS="$LABELS,com.github.repo.branch=$BRANCH"
LABELS="$LABELS,com.github.repo.dockerfile=Dockerfile"
echo "LABELS=$LABELS" >> $GITHUB_OUTPUT
echo ::set-output name=labels::${LABELS}
BUILD_ARGS="BRANCH=$BRANCH"
echo "args=$BUILD_ARGS" >> $GITHUB_OUTPUT
echo ::set-output name=args::${BUILD_ARGS}
- name: Build image
id: docker_build
uses: docker/build-push-action@v4
uses: docker/build-push-action@v2
with:
builder: ${{ steps.buildx.outputs.name }}
platforms: linux/arm64,linux/amd64
@@ -220,3 +153,67 @@ jobs:
${{ steps.prep.outputs.args }}
labels: ${{ steps.prep.outputs.labels }}
no-cache: false
- name: Scan image
uses: anchore/scan-action@v2
if: ${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main' }}
with:
image: "${{ needs.prepare.outputs.DOCKER_IMAGE }}:${{ needs.prepare.outputs.GITHUB_SHA }}"
fail-build: true
build-binary:
needs: [ prepare, test, code_scans ]
name: Binary compilation and release
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Compile binary
uses: thatisuday/go-cross-build@v1.0.2
with:
platforms: linux/amd64,darwin/amd64,windows/amd64,linux/arm64,darwin/amd64,darwin/arm64
name: semver-gen
package: ./
compress: false
dest: dist
ldflags: -s -w -X main.PKG_VERSION=${{ needs.prepare.outputs.RELEASE_VERSION }}
- name: Get list of the commits since last release
run: |
echo "$(git log $(git describe --tags --abbrev=0)..HEAD --pretty=format:"%h %s")" > .release_notes
- name: Create Release
id: create_release
uses: marvinpinto/action-automatic-releases@latest
if: ${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
files: dist/semver-gen-*
automatic_release_tag: ${{ needs.prepare.outputs.RELEASE_VERSION }}
title: version ${{ needs.prepare.outputs.RELEASE_VERSION }}
# tag: ${{ needs.prepare.outputs.RELEASE_VERSION }}
# name: ${{ needs.prepare.outputs.RELEASE_VERSION }}
# body_path: .release_notes
# draft: false
prerelease: ${{ github.ref != 'refs/heads/master' && github.ref != 'refs/heads/main' }}
# - name: Delete previous v1 release asset
# uses: mknejp/delete-release-assets@v1
# with:
# token: ${{ github.token }}
# fail-if-no-assets: false
# fail-if-no-release: false
# tag: v1
# assets: 'semver-gen-*'
- name: Create Release V1
id: create_release_global
uses: marvinpinto/action-automatic-releases@latest
if: ${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
files: dist/semver-gen-*
automatic_release_tag: v1
title: version v1:${{ needs.prepare.outputs.RELEASE_VERSION }}
prerelease: ${{ github.ref != 'refs/heads/master' && github.ref != 'refs/heads/main' }}
+1 -3
View File
@@ -1,4 +1,2 @@
semver-gen
coverage.out
.vscode
.DS_Store
coverage.out
+14 -7
View File
@@ -1,10 +1,17 @@
FROM golang:1-bullseye as baseimg
WORKDIR /go/src/app
COPY . /go/src/app/
RUN CGO_ENABLED=1 make build
# syntax=docker/dockerfile:1.2.1-labs
FROM ubuntu:jammy
COPY --from=baseimg /go/src/app/semver-gen /go/src/app/semver-gen
COPY --from=baseimg /go/src/app/config-release.yaml /go/src/app/config.yaml
FROM golang:1-alpine as baseimg
RUN apk add make
WORKDIR /go/src/app
ENV GO111MODULE=on CGO_ENABLED=1 GOOS=linux
COPY . /go/src/app/
RUN make
FROM alpine:latest
RUN apk add --no-cache ca-certificates
WORKDIR /go/src/app
COPY --from=baseimg /go/src/app/semver-gen .
COPY --from=baseimg /go/src/app/config-release.yaml config.yaml
COPY --from=baseimg /go/src/app/entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
+7 -37
View File
@@ -1,51 +1,21 @@
LOCAL_VERSION?=""
LOCAL_VERSION?=$(shell semver-gen generate -l -c config-release.yaml | sed -e 's|SEMVER ||g')
CI_RUN?=false
ADDITIONAL_BUILD_FLAGS=""
LDFLAGS=-s -w -X main.PKG_VERSION=${LOCAL_VERSION}
ifeq ($(CI_RUN), true)
ADDITIONAL_BUILD_FLAGS="-test.short"
endif
ifneq ($(shell which semver-gen), "")
LOCAL_VERSION="0.0.0-dev"
else
LOCAL_VERSION=$(shell semver-gen generate -l -c config-release.yaml | sed -e 's|SEMVER ||g')
endif
all: build
.PHONY: help
help: ## display this help
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n\nTargets:\n"} /^[a-zA-Z0-9_-]+:.*?##/ { printf " \033[36m%-20s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
.PHONY: all
all: build ## Build all targets
.PHONY: build
build: ## Build binary
build:
go build -o semver-gen -ldflags="-s -w -X main.PKG_VERSION=${LOCAL_VERSION}" *.go
# .PHONY: run
# run: build ## Build binary and execute it
# @./semver-gen
run: build
@./semver-gen
.PHONY: test
test: ## Run whole test suite
test:
@go test ./... $(ADDITIONAL_BUILD_FLAGS) -v -race -cover -coverprofile=coverage.out
.PHONY: update
update: ## Update dependencies
update:
@go get -u ./...
@go mod tidy
.PHONY: update-all
update-all: ## Update all dependencies and sub-packages
@go get -u ./...
dist-release: ## Build all binaries
rm -fr dist/ || true
mkdir -p dist/
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -a -installsuffix cgo -o dist/semver-gen-linux-amd64
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="$(LDFLAGS)" -a -installsuffix cgo -o dist/semver-gen-linux-arm64
CGO_ENABLED=0 GOOS=darwin go build -ldflags="$(LDFLAGS)" -a -installsuffix cgo -o dist/semver-gen-darwin-amd64
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="$(LDFLAGS)" -a -installsuffix cgo -o dist/semver-gen-darwin-arm64
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -a -installsuffix cgo -o dist/semver-gen-windows-amd64.exe
+3 -7
View File
@@ -13,8 +13,8 @@ Project created overnight, to prove that management of semantic versioning is NO
- [As a binary](#as-a-binary)
- [As a github action](#as-a-github-action)
- [As a docker container](#as-a-docker-container)
- [Calculations example \[standard\]](#calculations-example-standard)
- [Calculations example \[strict matching\]](#calculations-example-strict-matching)
- [Calculations example [standard]](#calculations-example-standard)
- [Calculations example [strict matching]](#calculations-example-strict-matching)
- [Release candidates](#release-candidates)
- [Example configuration](#example-configuration)
- [Good to know](#good-to-know)
@@ -78,7 +78,6 @@ Flags:
-h, --help help for semver-gen
-l, --local Use local repository
-r, --repository string Remote repository URL. (default "https://github.com/lukaszraczylo/simple-gql-client")
-b, --branch string Remote repository URL Branch. (default "main")
-s, --strict Strict matching
-u, --update Update binary with latest
-v, --version Display version
@@ -112,8 +111,6 @@ jobs:
# when using remote repository, especially with private one:
github_username: lukaszraczylo
github_token: MySupeRSecr3tPa$$w0rd
strict: true
existing: false
- name: Semver check
run: |
echo "Semantic version detected: ${{ steps.semver.outputs.semantic_version }}"
@@ -195,5 +192,4 @@ wording:
### Good to know
* Word matching uses fuzzy search AND is case INSENSITIVE
* I do not recommend using common words ( like "the" from the example configuration )
* You can specify env variable `LOG_LEVEL=debug` to see what exactly happens during the calculations
* I do not recommend using common words ( like "the" from the example configuration )
+11 -20
View File
@@ -1,39 +1,30 @@
# action.yml
name: "Semantic Version Generator"
description: "Automagic semantic version generator"
name: 'Semantic Version Generator'
description: 'Automagic semantic version generator'
author: Lukasz Raczylo
branding:
icon: chevron-right
color: gray-dark
inputs:
config_file:
description: "Configuration file"
description: 'Configuration file'
required: false
repository_url:
description: "Repository URL"
description: 'Repository URL'
required: false
default: "https://github.com/lukaszraczylo/simple-gql-client"
default: 'https://github.com/lukaszraczylo/simple-gql-client'
repository_local:
description: "Use already cloned repository in current directory"
description: 'Use already cloned repository in current directory'
required: false
github_token:
description: "GitHub Personal Access Token OR password"
description: 'GitHub Personal Access Token OR password'
required: false
github_username:
description: "GitHub or other git hosting provider username"
required: false
strict:
description: "Strict mode"
required: false
existing:
description: "Respect existing tags"
required: false
debugmode:
description: "Debug mode"
description: 'GitHub or other git hosting provider username'
required: false
outputs:
semantic_version:
description: "Calculated semantic version"
description: 'Calculated semantic version'
runs:
using: "docker"
image: "docker://ghcr.io/lukaszraczylo/semver-generator:latest"
using: 'docker'
image: Dockerfile
+19 -22
View File
@@ -6,22 +6,18 @@ import (
"os"
"runtime"
"github.com/lukaszraczylo/ask"
graphql "github.com/lukaszraczylo/go-simple-graphql"
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
"github.com/melbahja/got"
"github.com/tidwall/gjson"
)
func updatePackage() bool {
ghToken, ghTokenSet := os.LookupEnv("GITHUB_TOKEN")
if ghTokenSet {
binaryName := fmt.Sprintf("semver-gen-%s-%s", runtime.GOOS, runtime.GOARCH)
logger.Info(&libpack_logger.LogMessage{Message: "Checking for updates", Pairs: map[string]interface{}{"binaryName": binaryName}})
fmt.Println("Downloading", binaryName)
gql := graphql.NewConnection()
gql.SetEndpoint("https://api.github.com/graphql")
gql.SetOutput("mapstring")
gql.Endpoint = "https://api.github.com/graphql"
headers := map[string]interface{}{
"Authorization": fmt.Sprintf("Bearer %s", ghToken),
}
@@ -44,36 +40,36 @@ func updatePackage() bool {
}`
result, err := gql.Query(query, variables, headers)
if err != nil {
logger.Error(&libpack_logger.LogMessage{Message: "Unable to query GitHub API", Pairs: map[string]interface{}{"error": err.Error()}})
fmt.Println("Query error", err)
return false
}
output, ok := ask.For(result, "repository.latestRelease.releaseAssets.edges[0].node.downloadUrl").String("")
if !ok {
logger.Error(&libpack_logger.LogMessage{Message: "Unable to obtain download url for the binary", Pairs: map[string]interface{}{"binary": binaryName, "output": output}})
result = gjson.Get(result, "repository.latestRelease.releaseAssets.edges.0.node.downloadUrl").String()
if result == "" {
fmt.Println("Unable to obtain download url for the binary", binaryName)
return false
}
if flag.Lookup("test.v") == nil && os.Getenv("CI") == "" {
downloadedBinaryPath := fmt.Sprintf("/tmp/%s", binaryName)
g := got.New()
err = g.Download(output, downloadedBinaryPath)
err = g.Download(result, downloadedBinaryPath)
if err != nil {
logger.Error(&libpack_logger.LogMessage{Message: "Unable to download binary", Pairs: map[string]interface{}{"error": err.Error(), "binaryPath": downloadedBinaryPath}})
fmt.Println("Unable to download binary", err.Error())
return false
}
currentBinary, err := os.Executable()
if err != nil {
logger.Error(&libpack_logger.LogMessage{Message: "Unable to obtain current binary path", Pairs: map[string]interface{}{"error": err.Error()}})
fmt.Println("Unable to obtain current binary path", err.Error())
return false
}
err = os.Rename(downloadedBinaryPath, currentBinary)
if err != nil {
logger.Error(&libpack_logger.LogMessage{Message: "Unable to overwrite current binary", Pairs: map[string]interface{}{"error": err.Error()}})
fmt.Println("Unable to overwrite current binary", err.Error())
return false
}
err = os.Chmod(currentBinary, 0777)
if err != nil {
logger.Error(&libpack_logger.LogMessage{Message: "Unable to make binary executable", Pairs: map[string]interface{}{"error": err.Error()}})
fmt.Println("Unable to make binary executable", err.Error())
return false
}
}
@@ -85,7 +81,7 @@ func checkLatestRelease() (string, bool) {
ghToken, ghTokenSet := os.LookupEnv("GITHUB_TOKEN")
if ghTokenSet {
gql := graphql.NewConnection()
gql.SetEndpoint("https://api.github.com/graphql")
gql.Endpoint = "https://api.github.com/graphql"
headers := map[string]interface{}{
"Authorization": fmt.Sprintf("bearer %s", ghToken),
}
@@ -103,14 +99,15 @@ func checkLatestRelease() (string, bool) {
}`
result, err := gql.Query(query, variables, headers)
if err != nil {
logger.Error(&libpack_logger.LogMessage{Message: "Unable to query GitHub API", Pairs: map[string]interface{}{"error": err.Error()}})
fmt.Println("Query error >>", err)
return "", false
}
output, _ := ask.For(result, "repository.releases.nodes[0].tag.name").String("")
if output == "v1" {
output, _ = ask.For(result, "repository.releases.nodes[1].tag.name").String("")
fmt.Println(result)
result = gjson.Get(result, "repository.releases.nodes.0.tag.name").String()
if result == "v1" {
result = gjson.Get(result, "repository.releases.nodes.1.tag.name").String()
}
return output, true
return result, true
} else {
return "[no GITHUB_TOKEN set]", false
}
-4
View File
@@ -2,12 +2,9 @@ package cmd
import (
"testing"
libpack_logging "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
)
func Test_checkLatestRelease(t *testing.T) {
logger = libpack_logging.New()
tests := []struct {
name string
want string
@@ -29,7 +26,6 @@ func Test_checkLatestRelease(t *testing.T) {
}
func Test_updatePackage(t *testing.T) {
logger = libpack_logging.New()
if testing.Short() {
t.Skip("Skipping test in short / CI mode")
}
+45 -122
View File
@@ -1,4 +1,3 @@
// Project: semver-generator
/*
Copyright © 2021 LUKASZ RACZYLO <lukasz$raczylo,com>
@@ -18,6 +17,7 @@ limitations under the License.
package cmd
import (
"flag"
"fmt"
"net/url"
"os"
@@ -32,7 +32,6 @@ import (
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/lithammer/fuzzysearch/fuzzy"
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
"github.com/lukaszraczylo/pandati"
"github.com/spf13/viper"
)
@@ -41,7 +40,6 @@ var (
err error
repo *Setup
PKG_VERSION string
logger *libpack_logger.Logger
)
type Wording struct {
@@ -52,12 +50,11 @@ type Wording struct {
}
type Force struct {
Commit string
Patch int
Minor int
Major int
Commit string
Existing bool
Strict bool
}
type SemVer struct {
@@ -69,25 +66,24 @@ type SemVer struct {
}
type Setup struct {
RepositoryHandler *git.Repository
RepositoryName string
RepositoryBranch string
RepositoryLocalPath string
LocalConfigFile string
Wording Wording
RepositoryHandler *git.Repository
Commits []CommitDetails
Tags []TagDetails
Force Force
Semver SemVer
Wording Wording
Force Force
Generate bool
LocalConfigFile string
UseLocal bool
}
type CommitDetails struct {
Timestamp time.Time
Hash string
Author string
Message string
Timestamp time.Time
}
type TagDetails struct {
@@ -97,42 +93,31 @@ type TagDetails struct {
func checkMatches(content []string, targets []string) bool {
if fuzzy.MatchNormalizedFold(strings.Join(content, " "), "Merge branch") {
logger.Debug(&libpack_logger.LogMessage{
Message: "Merge detected, ignoring commits within",
Pairs: map[string]interface{}{"content": strings.Join(content, " ")},
})
debugPrint(fmt.Sprintln("Merge detected, ignoring commits within:", content))
return false
}
var r []string
for _, tgt := range targets {
r = fuzzy.FindNormalizedFold(tgt, content)
if len(r) > 0 {
logger.Debug(&libpack_logger.LogMessage{
Message: "Found match",
Pairs: map[string]interface{}{"target": tgt, "match": strings.Join(r, ","), "content": strings.Join(content, " ")},
})
debugPrint(fmt.Sprintln("Found match for ", tgt, "|", strings.Join(r, ",")))
return true
}
}
return false
}
func debugPrint(content string) {
if params.varDebug && flag.Lookup("test.v") == nil {
fmt.Println("DEBUG:", content)
}
}
var extractNumber = regexp.MustCompile("[0-9]+")
func parseExistingSemver(tagName string, currentSemver SemVer) (semanticVersion SemVer) {
logger.Debug(&libpack_logger.LogMessage{
Message: "Parsing existing semver",
Pairs: map[string]interface{}{"tag": tagName},
})
func parseExistingSemver(tagName string) (semanticVersion SemVer) {
var tagNameParts []string
tagNameParts = strings.Split(tagName, ".")
if len(tagNameParts) < 3 {
logger.Debug(&libpack_logger.LogMessage{
Message: "Unable to parse incompatible semver ( non x.y.z )",
Pairs: map[string]interface{}{"tag": tagName},
})
return currentSemver
}
semanticVersion.Major, _ = strconv.Atoi(extractNumber.FindAllString(tagNameParts[0], -1)[0])
semanticVersion.Minor, _ = strconv.Atoi(extractNumber.FindAllString(tagNameParts[1], -1)[0])
semanticVersion.Patch, _ = strconv.Atoi(extractNumber.FindAllString(tagNameParts[2], -1)[0])
@@ -148,22 +133,16 @@ func (s *Setup) CalculateSemver() SemVer {
if params.varExisting || s.Force.Existing {
for _, tagHash := range s.Tags {
if commit.Hash == tagHash.Hash {
logger.Debug(&libpack_logger.LogMessage{
Message: "Found existing tag",
Pairs: map[string]interface{}{"tag": tagHash.Name, "commit": strings.TrimSuffix(commit.Message, "\n")},
})
s.Semver = parseExistingSemver(tagHash.Name, s.Semver)
debugPrint(fmt.Sprintln("Found existing tag:", tagHash.Name, "related to", commit.Message))
s.Semver = parseExistingSemver(tagHash.Name)
continue
}
}
}
if !params.varStrict && !s.Force.Strict {
if !params.varStrict {
s.Semver.Patch++
logger.Debug(&libpack_logger.LogMessage{
Message: "Incrementing patch (DEFAULT)",
Pairs: map[string]interface{}{"commit": strings.TrimSuffix(commit.Message, "\n"), "semver": s.getSemver()},
})
debugPrint(fmt.Sprintln("Incrementing patch (DEFAULT) on ", strings.TrimSuffix(commit.Message, "\n"), "| Semver:", s.getSemver()))
}
commitSlice := strings.Fields(commit.Message)
matchPatch := checkMatches(commitSlice, s.Wording.Patch)
@@ -172,20 +151,14 @@ func (s *Setup) CalculateSemver() SemVer {
matchReleaseCandidate := checkMatches(commitSlice, s.Wording.Release)
if matchPatch {
s.Semver.Patch++
logger.Debug(&libpack_logger.LogMessage{
Message: "Incrementing patch (WORDING)",
Pairs: map[string]interface{}{"commit": strings.TrimSuffix(commit.Message, "\n"), "semver": s.getSemver()},
})
debugPrint(fmt.Sprintln("Incrementing patch (WORDING) on ", strings.TrimSuffix(commit.Message, "\n"), "| Semver:", s.getSemver()))
continue
}
if matchReleaseCandidate {
s.Semver.Release++
s.Semver.Patch = 1
s.Semver.EnableReleaseCandidate = true
logger.Debug(&libpack_logger.LogMessage{
Message: "Incrementing release candidate (WORDING)",
Pairs: map[string]interface{}{"commit": strings.TrimSuffix(commit.Message, "\n"), "semver": s.getSemver()},
})
debugPrint(fmt.Sprintln("Incrementing release candidate (WORDING) on ", strings.TrimSuffix(commit.Message, "\n"), "| Semver:", s.getSemver()))
continue
}
if matchMinor {
@@ -193,10 +166,7 @@ func (s *Setup) CalculateSemver() SemVer {
s.Semver.Patch = 1
s.Semver.EnableReleaseCandidate = false
s.Semver.Release = 0
logger.Debug(&libpack_logger.LogMessage{
Message: "Incrementing minor (WORDING)",
Pairs: map[string]interface{}{"commit": strings.TrimSuffix(commit.Message, "\n"), "semver": s.getSemver()},
})
debugPrint(fmt.Sprintln("Incrementing minor (WORDING) on ", strings.TrimSuffix(commit.Message, "\n"), "| Semver:", s.getSemver()))
continue
}
if matchMajor {
@@ -205,10 +175,7 @@ func (s *Setup) CalculateSemver() SemVer {
s.Semver.Patch = 1
s.Semver.EnableReleaseCandidate = false
s.Semver.Release = 0
logger.Debug(&libpack_logger.LogMessage{
Message: "Incrementing major (WORDING)",
Pairs: map[string]interface{}{"commit": strings.TrimSuffix(commit.Message, "\n"), "semver": s.getSemver()},
})
debugPrint(fmt.Sprintln("Incrementing major (WORDING) on ", strings.TrimSuffix(commit.Message, "\n"), "| Semver:", s.getSemver()))
continue
}
}
@@ -216,19 +183,14 @@ func (s *Setup) CalculateSemver() SemVer {
}
func (s *Setup) ListExistingTags() {
logger.Debug(&libpack_logger.LogMessage{
Message: "Listing existing tags",
})
debugPrint(fmt.Sprintln("Listing existing tags"))
refs, err := s.RepositoryHandler.Tags()
if err != nil {
panic(err)
}
if err := refs.ForEach(func(ref *plumbing.Reference) error {
s.Tags = append(s.Tags, TagDetails{Name: ref.Name().Short(), Hash: ref.Hash().String()})
logger.Debug(&libpack_logger.LogMessage{
Message: "Found tag",
Pairs: map[string]interface{}{"tag": ref.Name().Short(), "hash": ref.Hash().String()},
})
debugPrint(fmt.Sprintln("Found tag:", ref.Name().Short(), ref.Hash().String()))
return nil
}); err != nil {
panic(err)
@@ -255,16 +217,11 @@ func (s *Setup) ListCommits() ([]CommitDetails, error) {
return nil
})
logger.Debug(&libpack_logger.LogMessage{
Message: "Listing commits",
Pairs: map[string]interface{}{"commits": tmpResults},
})
debugPrint(fmt.Sprintln("\n---COMMITS BEFORE CUT---\n", s.Commits))
for commitId, cmt := range tmpResults {
if s.Force.Commit != "" && cmt.Hash == s.Force.Commit {
logger.Debug(&libpack_logger.LogMessage{
Message: "Found commit match",
Pairs: map[string]interface{}{"commit": cmt.Hash, "index": commitId},
})
debugPrint(fmt.Sprintln(">>>> FOUND MATCH", len(s.Commits), len(tmpResults[commitId:])))
s.Commits = tmpResults[commitId:]
break
} else {
@@ -272,10 +229,7 @@ func (s *Setup) ListCommits() ([]CommitDetails, error) {
}
}
logger.Debug(&libpack_logger.LogMessage{
Message: "Commits after cut",
Pairs: map[string]interface{}{"commits": s.Commits},
})
debugPrint(fmt.Sprintln("\n---COMMITS AFTER CUT---\n", s.Commits))
return s.Commits, err
}
@@ -283,18 +237,13 @@ func (s *Setup) Prepare() error {
if !repo.UseLocal {
u, err := url.Parse(s.RepositoryName)
if err != nil {
logger.Error(&libpack_logger.LogMessage{
Message: "Unable to parse repository URL",
Pairs: map[string]interface{}{"error": err.Error(), "url": s.RepositoryName},
})
fmt.Println("Unable to parse repository URL", s.RepositoryName, "Error:", err.Error())
return err
}
s.RepositoryLocalPath = fmt.Sprintf("/tmp/semver/%s/%s", u.Path, s.RepositoryBranch)
s.RepositoryLocalPath = fmt.Sprintf("/tmp/semver/%s", u.Path)
os.RemoveAll(s.RepositoryLocalPath)
s.RepositoryHandler, err = git.PlainClone(s.RepositoryLocalPath, false, &git.CloneOptions{
URL: s.RepositoryName,
ReferenceName: plumbing.NewBranchReferenceName(s.RepositoryBranch),
SingleBranch: true,
URL: s.RepositoryName,
Auth: &http.BasicAuth{
Username: os.Getenv("GITHUB_USERNAME"),
Password: os.Getenv("GITHUB_TOKEN"),
@@ -302,20 +251,14 @@ func (s *Setup) Prepare() error {
Tags: git.AllTags,
})
if err != nil {
logger.Error(&libpack_logger.LogMessage{
Message: "Unable to clone repository",
Pairs: map[string]interface{}{"error": err.Error(), "url": s.RepositoryName},
})
fmt.Println("Unable to reach repository", s.RepositoryName, "Error:", err.Error())
return err
}
} else {
s.RepositoryLocalPath = "./"
s.RepositoryHandler, err = git.PlainOpen(s.RepositoryLocalPath)
if err != nil {
logger.Error(&libpack_logger.LogMessage{
Message: "Unable to open local repository",
Pairs: map[string]interface{}{"error": err.Error(), "path": s.RepositoryLocalPath},
})
fmt.Println("Unable to reach repository", s.RepositoryName, "Error:", err.Error())
return err
}
}
@@ -325,24 +268,15 @@ func (s *Setup) Prepare() error {
func (s *Setup) ForcedVersioning() {
if !pandati.IsZero(s.Force.Major) {
logger.Debug(&libpack_logger.LogMessage{
Message: "Forced versioning (MAJOR)",
Pairs: map[string]interface{}{"major": s.Force.Major},
})
debugPrint(fmt.Sprintln("Forced versioning (MAJOR)", s.Force.Major))
s.Semver.Major = s.Force.Major
}
if !pandati.IsZero(s.Force.Minor) {
logger.Debug(&libpack_logger.LogMessage{
Message: "Forced versioning (MINOR)",
Pairs: map[string]interface{}{"minor": s.Force.Minor},
})
debugPrint(fmt.Sprintln("Forced versioning (MINOR)", s.Force.Minor))
s.Semver.Minor = s.Force.Minor
}
if !pandati.IsZero(s.Force.Patch) {
logger.Debug(&libpack_logger.LogMessage{
Message: "Forced versioning (PATCH)",
Pairs: map[string]interface{}{"patch": s.Force.Minor},
})
debugPrint(fmt.Sprintln("Forced versioning (PATCH)", s.Force.Patch))
s.Semver.Patch = s.Force.Patch
}
}
@@ -368,22 +302,15 @@ func (s *Setup) getSemver() (semverReturned string) {
}
func main() {
logger = libpack_logger.New()
if params.varShowVersion {
var outdatedMsg string
latestRelease, latestRelaseOk := checkLatestRelease()
if PKG_VERSION != latestRelease && latestRelaseOk {
outdatedMsg = fmt.Sprintf("(Latest available: %s)", latestRelease)
}
logger.Info(&libpack_logger.LogMessage{
Message: "semver-gen",
Pairs: map[string]interface{}{"version": PKG_VERSION, "outdated": outdatedMsg},
})
fmt.Println("semver-gen", PKG_VERSION, "", outdatedMsg, "\tMore information: https://github.com/lukaszraczylo/semver-generator")
if outdatedMsg != "" {
logger.Info(&libpack_logger.LogMessage{
Message: "semver-gen",
Pairs: map[string]interface{}{"message": "You can update automatically with: semver-gen -u"},
})
fmt.Println("You can update automatically with: semver-gen -u")
}
return
}
@@ -394,20 +321,16 @@ func main() {
if repo.Generate || params.varGenerateInTest {
err := repo.ReadConfig(repo.LocalConfigFile)
if err != nil {
logger.Error(&libpack_logger.LogMessage{
Message: "Unable to find config file semver.yaml. Using defaults and flags.",
Pairs: map[string]interface{}{"file": repo.LocalConfigFile},
})
fmt.Println("Unable to find config file", repo.LocalConfigFile)
os.Exit(1)
}
err = repo.Prepare()
if err != nil {
logger.Critical(&libpack_logger.LogMessage{
Message: "Unable to prepare repository",
Pairs: map[string]interface{}{"error": err.Error()},
})
fmt.Println("Unable to prepare repository")
os.Exit(1)
}
repo.ListCommits()
if params.varExisting || repo.Force.Existing {
if params.varExisting {
repo.ListExistingTags()
}
repo.ForcedVersioning()
+36 -89
View File
@@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,7 +21,6 @@ import (
"testing"
git "github.com/go-git/go-git/v5"
libpack_logging "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
"github.com/lukaszraczylo/pandati"
assertions "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
@@ -37,17 +36,12 @@ var (
)
func (suite *Tests) SetupTest() {
err := os.Chdir(testCurrentPath)
if err != nil {
logger.Critical(&libpack_logging.LogMessage{Message: "Unable to change directory to test directory", Pairs: map[string]any{"error": err}})
}
os.Chdir(testCurrentPath)
assert = assertions.New(suite.T())
params.varDebug = true
params.varRepoBranch = "main"
}
func TestSuite(t *testing.T) {
logger = libpack_logging.New()
testCurrentPath, _ = os.Getwd()
suite.Run(t, new(Tests))
}
@@ -58,8 +52,8 @@ func (suite *Tests) TestSetup_getSemver() {
}
tests := []struct {
name string
want string
fields fields
want string
}{
{
name: "Return 1.3.7",
@@ -112,13 +106,13 @@ func (suite *Tests) TestSetup_getSemver() {
func (suite *Tests) TestSetup_ForcedVersioning() {
type fields struct {
Force Force
Semver SemVer
Force Force
}
tests := []struct {
name string
want string
fields fields
want string
}{
{
name: "No versioning",
@@ -217,8 +211,8 @@ func (suite *Tests) TestSetup_ReadConfig() {
}
tests := []struct {
name string
args args
fields fields
args args
wordingEmpty bool
wantErr bool
}{
@@ -290,15 +284,14 @@ func (suite *Tests) Test_checkMatches() {
func (suite *Tests) TestSetup_ListCommits() {
type fields struct {
RepositoryHandler *git.Repository
RepositoryName string
RepositoryBranch string
RepositoryLocalPath string
RepositoryHandler *git.Repository
LocalConfigFile string
Wording Wording
Commits []CommitDetails
Force Force
Semver SemVer
Wording Wording
Force Force
}
tests := []struct {
@@ -310,8 +303,7 @@ func (suite *Tests) TestSetup_ListCommits() {
{
name: "List commits from existing repository",
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client",
RepositoryBranch: "master",
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client",
},
noCommits: false,
wantErr: false,
@@ -319,8 +311,7 @@ func (suite *Tests) TestSetup_ListCommits() {
{
name: "List commits from non-existing repository",
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client-dead",
RepositoryBranch: "main",
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client-dead",
},
noCommits: true,
wantErr: true,
@@ -328,8 +319,7 @@ func (suite *Tests) TestSetup_ListCommits() {
{
name: "List commits starting with certain hash",
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client",
RepositoryBranch: "master",
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client",
Force: Force{
Commit: "f6ee82113afb32ee95eac892d1155582a2f85166",
},
@@ -343,7 +333,6 @@ func (suite *Tests) TestSetup_ListCommits() {
s := &Setup{}
s.ReadConfig(tt.fields.LocalConfigFile)
s.RepositoryName = tt.fields.RepositoryName
s.RepositoryBranch = tt.fields.RepositoryBranch
s.Force = tt.fields.Force
s.Prepare()
listOfCommits, err := s.ListCommits()
@@ -360,9 +349,8 @@ func (suite *Tests) TestSetup_ListCommits() {
func (suite *Tests) TestSetup_CalculateSemver() {
type fields struct {
RepositoryName string
BranchName string
LocalConfigFile string
Force Force
LocalConfigFile string
}
type wantSemver struct {
Major int
@@ -380,7 +368,6 @@ func (suite *Tests) TestSetup_CalculateSemver() {
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/semver-generator-test-repo",
LocalConfigFile: "meta.yaml",
BranchName: "main",
},
strictMatching: false,
wantSemver: wantSemver{
@@ -394,7 +381,6 @@ func (suite *Tests) TestSetup_CalculateSemver() {
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/semver-generator-test-repo",
LocalConfigFile: "meta.yaml",
BranchName: "main",
},
strictMatching: true,
wantSemver: wantSemver{
@@ -408,7 +394,6 @@ func (suite *Tests) TestSetup_CalculateSemver() {
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/semver-generator-test-repo",
LocalConfigFile: "meta.yaml",
BranchName: "main",
Force: Force{
Major: 1,
Minor: 1,
@@ -427,7 +412,6 @@ func (suite *Tests) TestSetup_CalculateSemver() {
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/semver-generator-test-repo",
LocalConfigFile: "meta.yaml",
BranchName: "main",
Force: Force{
Major: 1,
Minor: 1,
@@ -458,7 +442,6 @@ func (suite *Tests) TestSetup_CalculateSemver() {
s := &Setup{}
s.ReadConfig(tt.fields.LocalConfigFile)
s.RepositoryName = tt.fields.RepositoryName
s.RepositoryBranch = tt.fields.BranchName
s.Prepare()
s.ForcedVersioning()
s.Force = tt.fields.Force
@@ -472,10 +455,31 @@ func (suite *Tests) TestSetup_CalculateSemver() {
}
}
func (suite *Tests) Test_debugPrint() {
type args struct {
content string
}
tests := []struct {
name string
args args
}{
{
name: "Test debug print",
args: args{
content: "Test debug",
},
},
}
for _, tt := range tests {
suite.T().Run(tt.name, func(t *testing.T) {
debugPrint(tt.args.content)
})
}
}
func (suite *Tests) Test_main() {
type vars struct {
varRepoName string
varRepoBranch string
varLocalCfg string
varUseLocal bool
varShowVersion bool
@@ -565,11 +569,7 @@ func (suite *Tests) Test_parseExistingSemver() {
}
for _, tt := range tests {
suite.T().Run(tt.name, func(t *testing.T) {
got := parseExistingSemver(tt.args.tagName, SemVer{
Major: 1,
Minor: 1,
Patch: 1,
})
got := parseExistingSemver(tt.args.tagName)
assert.Equal(tt.wantSemanticVersion.Major, got.Major, "Unexpected MAJOR semver result in "+tt.name)
assert.Equal(tt.wantSemanticVersion.Minor, got.Minor, "Unexpected MINOR semver result in "+tt.name)
assert.Equal(tt.wantSemanticVersion.Patch, got.Patch, "Unexpected PATCH semver result in "+tt.name)
@@ -577,56 +577,3 @@ func (suite *Tests) Test_parseExistingSemver() {
})
}
}
func (suite *Tests) TestSetup_ListExistingTags() {
type fields struct {
RepositoryHandler *git.Repository
RepositoryName string
RepositoryBranch string
RepositoryLocalPath string
LocalConfigFile string
Wording Wording
Commits []CommitDetails
Force Force
Semver SemVer
}
tests := []struct {
name string
fields fields
noTags bool
}{
{
name: "List tags from existing repository",
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client",
RepositoryBranch: "master",
},
noTags: false,
},
{
name: "List tags from non-existing repository",
fields: fields{
RepositoryName: "https://github.com/lukaszraczylo/simple-gql-client-dead",
RepositoryBranch: "master",
},
noTags: true,
},
}
for _, tt := range tests {
suite.T().Run(tt.name, func(t *testing.T) {
s := &Setup{}
s.ReadConfig(tt.fields.LocalConfigFile)
s.RepositoryName = tt.fields.RepositoryName
s.RepositoryBranch = tt.fields.RepositoryBranch
s.Force = tt.fields.Force
s.Prepare()
s.ListExistingTags()
if tt.noTags {
assert.Equal(len(s.Tags), 0, "Unexpected number of tags in "+tt.name)
} else {
assert.GreaterOrEqual(len(s.Tags), 1, "Unexpected number of tags in "+tt.name)
}
})
}
}
+1 -7
View File
@@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -41,10 +41,6 @@ func (r *Setup) setupCobra() {
if err != nil {
panic(err)
}
r.RepositoryBranch, err = rootCmd.Flags().GetString("branch")
if err != nil {
panic(err)
}
r.LocalConfigFile, err = rootCmd.Flags().GetString("config")
if err != nil {
panic(err)
@@ -57,7 +53,6 @@ func (r *Setup) setupCobra() {
type myParams struct {
varRepoName string
varRepoBranch string
varLocalCfg string
varUseLocal bool
varShowVersion bool
@@ -74,7 +69,6 @@ func init() {
repo = &Setup{}
cobra.OnInitialize(repo.setupCobra)
rootCmd.PersistentFlags().StringVarP(&params.varRepoName, "repository", "r", "https://github.com/lukaszraczylo/simple-gql-client", "Remote repository URL.")
rootCmd.PersistentFlags().StringVarP(&params.varRepoBranch, "branch", "b", "main", "Remote repository URL Branch.")
rootCmd.PersistentFlags().StringVarP(&params.varLocalCfg, "config", "c", "semver.yaml", "Path to config file")
rootCmd.PersistentFlags().BoolVarP(&params.varUseLocal, "local", "l", false, "Use local repository")
rootCmd.PersistentFlags().BoolVarP(&params.varShowVersion, "version", "v", false, "Display version")
-2
View File
@@ -3,8 +3,6 @@ force:
major: 1
minor: 4
existing: true
strict: false
commit: 960207e4677476ad31a9f389f74eaf9f33d49613
wording:
patch:
- update
+1 -2
View File
@@ -1,8 +1,7 @@
version: 1
force:
major: 1
existing: false
strict: false
existing: true
wording:
patch:
- update
+6 -36
View File
@@ -1,11 +1,10 @@
#!/bin/bash
set -e
#!/bin/sh -l
set -o pipefail
FLAGS="$SEMVER_RAW_FLAGS"
FLAGS=""
if [[ -z "$INPUT_CONFIG_FILE" ]]; then
echo "Set the configuration file path."
exit 1
else
FLAGS="${FLAGS} -c $INPUT_CONFIG_FILE"
fi
@@ -19,26 +18,10 @@ if [[ ! -z "$INPUT_REPOSITORY_URL" ]]; then
FLAGS="${FLAGS} -r $INPUT_REPOSITORY_URL"
fi
if [[ ! -z "$INPUT_REPOSITORY_BRANCH" ]]; then
FLAGS="${FLAGS} -b $INPUT_REPOSITORY_BRANCH"
fi
if [[ ! -z "$INPUT_REPOSITORY_LOCAL" ]]; then
FLAGS="${FLAGS} -l"
fi
if [[ ! -z "$INPUT_STRICT" ]]; then
FLAGS="${FLAGS} -s"
fi
if [[ ! -z "$INPUT_EXISTING" ]]; then
FLAGS="${FLAGS} -e"
fi
if [[ ! -z "$INPUT_DEBUGMODE" ]]; then
FLAGS="${FLAGS} --debug"
fi
if [[ "${FLAGS}" == "" && "$*" == "" ]]; then
exit 1
fi
@@ -51,21 +34,8 @@ if [[ ! -z "$INPUT_GITHUB_USERNAME" ]]; then
export GITHUB_USERNAME=$INPUT_GITHUB_USERNAME
fi
if [[ ! -z "$INPUT_DEBUGMODE" ]]; then
echo "DEBUG MODE ENABLED"
echo "----"
ls -lA
echo "----"
pwd
echo "----"
echo "FLAGS: $FLAGS"
echo "----"
/go/src/app/semver-gen generate $FLAGS $*
echo "----"
fi
cd /github/workspace
OUT_SEMVER_GEN=$(/go/src/app/semver-gen generate $FLAGS $*)
[ $? -eq 0 ] || exit 1
CLEAN_SEMVER=$(echo $OUT_SEMVER_GEN | sed -e 's|SEMVER ||g')
echo "semantic_version=$CLEAN_SEMVER" >> $GITHUB_OUTPUT
echo $OUT_SEMVER_GEN
echo "::set-output name=semantic_version::$(echo $OUT_SEMVER_GEN | sed -e 's|SEMVER ||g')"
echo $OUT_SEMVER_GEN
+45 -60
View File
@@ -1,73 +1,58 @@
module github.com/lukaszraczylo/semver-generator
go 1.22.4
go 1.17
require (
github.com/go-git/go-git/v5 v5.12.0
github.com/lithammer/fuzzysearch v1.1.8
github.com/lukaszraczylo/ask v0.0.0-20230927103145-2ff1123b4415
github.com/lukaszraczylo/go-simple-graphql v1.2.21
github.com/lukaszraczylo/graphql-monitoring-proxy v0.23.21
github.com/lukaszraczylo/pandati v0.0.29
github.com/melbahja/got v0.7.0
github.com/spf13/cobra v1.8.1
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.9.0
github.com/go-git/go-git/v5 v5.4.2
github.com/lithammer/fuzzysearch v1.1.3
github.com/lukaszraczylo/go-simple-graphql v1.0.50
github.com/lukaszraczylo/pandati v0.0.10
github.com/melbahja/got v0.6.1
github.com/spf13/cobra v1.3.0
github.com/spf13/viper v1.10.1
github.com/stretchr/testify v1.7.0
github.com/tidwall/gjson v1.14.0
)
require (
dario.cat/mergo v1.0.1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.0.0 // indirect
github.com/avast/retry-go/v4 v4.6.0 // indirect
github.com/cloudflare/circl v1.4.0 // indirect
github.com/cyphar/filepath-securejoin v0.3.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/go-git/go-billy/v5 v5.5.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/gookit/color v1.5.4 // indirect
github.com/gookit/goutil v0.6.16 // indirect
github.com/Microsoft/go-winio v0.5.1 // indirect
github.com/ProtonMail/go-crypto v0.0.0-20220113124808-70ae35bab23f // indirect
github.com/acomagu/bufpipe v1.0.3 // indirect
github.com/allegro/bigcache/v3 v3.0.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emirpasic/gods v1.12.0 // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/go-git/gcfg v1.5.0 // indirect
github.com/go-git/go-billy/v5 v5.3.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pjbgf/sha1cd v0.3.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rs/zerolog v1.33.0 // indirect
github.com/sagikazarmark/locafero v0.6.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
github.com/skeema/knownhosts v1.3.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.7.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kevinburke/ssh_config v1.1.0 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rs/zerolog v1.26.1 // indirect
github.com/sergi/go-diff v1.2.0 // indirect
github.com/spf13/afero v1.8.1 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tidwall/gjson v1.17.3 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/wI2L/jsondiff v0.6.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/term v0.23.0 // indirect
golang.org/x/text v0.17.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/xanzy/ssh-agent v0.3.1 // indirect
golang.org/x/crypto v0.0.0-20220209195652-db638375bc3a // indirect
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect
golang.org/x/text v0.3.7 // indirect
gopkg.in/ini.v1 v1.66.4 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
+857 -175
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,