Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add versioning tool #3

Merged
merged 23 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .github/workflows/ferretdb_go_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
name: Go
on:
pull_request:
types:
- unlabeled # if GitHub Actions stuck, add and remove "not ready" label to force rebuild
- opened
- reopened
- synchronize
push:
branches:
- ferretdb
tags:
- "*"
schedule:
- cron: "12 0 * * *"

env:
GOPATH: /home/runner/go
GOCACHE: /home/runner/go/cache
GOLANGCI_LINT_CACHE: /home/runner/go/cache/lint
GOMODCACHE: /home/runner/go/mod
GOPROXY: https://proxy.golang.org
GOTOOLCHAIN: local

jobs:
test:
name: Test
# https://www.ubicloud.com/docs/about/pricing#github-actions
# https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#per-minute-rates-for-larger-runners
runs-on: ubicloud-standard-4

timeout-minutes: 15

# Do not run this job in parallel for any PR change or branch push.
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref_name }}
cancel-in-progress: true

if: github.event_name != 'pull_request' || !contains(github.event.pull_request.labels.*.name, 'not ready')

steps:
# TODO https://github.com/FerretDB/github-actions/issues/211
- name: Checkout code
uses: actions/checkout@v4

- name: Setup Go
uses: FerretDB/github-actions/setup-go@main

- name: Run tests
run: |
cd ferretdb_packaging
go mod tidy
go mod verify
go test ./...

- name: Check dirty
if: always()
run: |
git status --untracked-files --ignored
git status
git diff --exit-code
2 changes: 2 additions & 0 deletions ferretdb_packaging/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# FerretDB packaging
!*go.mod
210 changes: 210 additions & 0 deletions ferretdb_packaging/defineversion/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package main defines debian version number of DocumentDB for CI builds.
package main

import (
"flag"
"fmt"
"os"
"regexp"
"slices"
"strings"

"github.com/sethvargo/go-githubactions"
)

func main() {
controlFileF := flag.String("control-file", "../pg_documentdb/documentdb.control", "pg_documentdb/documentdb.control file path")

flag.Parse()

action := githubactions.New()

if *controlFileF == "" {
action.Fatalf("%s", "-control-file flag is empty.")
}

controlDefaultVersion, err := getControlDefaultVersion(*controlFileF)
if err != nil {
action.Fatalf("%s", err)
}

debugEnv(action)

upstreamVersion, err := define(controlDefaultVersion, action.Getenv)
if err != nil {
action.Fatalf("%s", err)
}

setResults(action, upstreamVersion)
}

// controlDefaultVer matches major, minor and patch from default_version field in control file,
// see pg_documentdb_core/documentdb_core.control.
var controlDefaultVer = regexp.MustCompile(`(?m)^default_version\s=\s'(?P<major>[0-9]+)\.(?P<minor>[0-9]+)-(?P<patch>[0-9]+)'$`)

// tagVer matches major, manor, patch and rest of optional string.
// The tag may look like `v0.100.0` and tag with optional string
// may look like `v0.100.0-ferretdb` and `v0.100.0-ferretdb-2.0.1`.
var tagVer = regexp.MustCompile(`^v(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)-?(?P<rest>[0-9a-zA-Z-.]+)?$`)

// disallowedVer matches disallowed characters of upstream version,
// see https://www.debian.org/doc/debian-policy/ch-controlfields.html#version.
var disallowedVer = regexp.MustCompile(`[^A-Za-z0-9~.+]`)

// debugEnv logs all environment variables that start with `GITHUB_` or `INPUT_`
// in debug level.
func debugEnv(action *githubactions.Action) {
res := make([]string, 0, 30)

for _, l := range os.Environ() {
if strings.HasPrefix(l, "GITHUB_") || strings.HasPrefix(l, "INPUT_") {
res = append(res, l)
}
}

slices.Sort(res)

action.Debugf("Dumping environment variables:")

for _, l := range res {
action.Debugf("\t%s", l)
}
}

// getControlDefaultVersion reads the default_version field from the control file,
// and returns the control default version in SemVer format,
// see pg_documentdb_core/documentdb_core.control.
func getControlDefaultVersion(f string) (string, error) {
b, err := os.ReadFile(f)
if err != nil {
return "", err
}

match := controlDefaultVer.FindSubmatch(b)
if match == nil || len(match) != controlDefaultVer.NumSubexp()+1 {
return "", fmt.Errorf("control file did not find default_version: %s", f)
}

major := match[tagVer.SubexpIndex("major")]
minor := match[tagVer.SubexpIndex("minor")]
patch := match[tagVer.SubexpIndex("patch")]

return fmt.Sprintf("%s.%s.%s", major, minor, patch), nil
}

// define returns the upstream version using the environment variables of GitHub Actions.
// The characters not allowed in upstream version including `-` are replaced with `~`.
//
// For release tags, it uses the normalized tag name as the upstream version.
// Remaining GitHub Actions use control default version followed by normalized GitHub Actions reference.
// The upstream version requires digit prefix hence control default version is used.
//
// See upstream version in https://www.debian.org/doc/debian-policy/ch-controlfields.html#version.
func define(controlDefaultVersion string, getenv githubactions.GetenvFunc) (string, error) {
var upstreamVersion string
var err error

switch event := getenv("GITHUB_EVENT_NAME"); event {
case "pull_request", "pull_request_target":
branch := strings.ToLower(getenv("GITHUB_HEAD_REF"))
upstreamVersion = defineForPR(controlDefaultVersion, branch)

case "push", "schedule", "workflow_run":
refName := strings.ToLower(getenv("GITHUB_REF_NAME"))

switch refType := strings.ToLower(getenv("GITHUB_REF_TYPE")); refType {
case "branch":
upstreamVersion, err = defineForBranch(controlDefaultVersion, refName)

case "tag":
upstreamVersion, err = defineForTag(refName)

default:
err = fmt.Errorf("unhandled ref type %q for event %q", refType, event)
}

default:
err = fmt.Errorf("unhandled event type %q", event)
}

if err != nil {
return "", err
}

if upstreamVersion == "" {
return "", fmt.Errorf("both upstreamVersion and err are nil")
}

return upstreamVersion, nil
}

// defineForPR defines debian upstream version for pull requests.
// It replaces special characters in branch name with character `~`.
func defineForPR(controlDefaultVersion, branch string) string {
// for branches like "dependabot/submodules/XXX"
parts := strings.Split(branch, "/")
branch = parts[len(parts)-1]
branch = disallowedVer.ReplaceAllString(branch, "~")

return fmt.Sprintf("%s~pr~%s", controlDefaultVersion, branch)
}

// defineForBranch defines debian upstream version for branches.
func defineForBranch(controlDefaultVersion, branch string) (string, error) {
switch branch {
case "ferretdb":
return fmt.Sprintf("%s~branch~%s", controlDefaultVersion, branch), nil
default:
return "", fmt.Errorf("unhandled branch %q", branch)
}
}

// defineForTag defines debian upstream version for release builds by
// extracting major, minor, patch.
//
// If the tag contains more information such as `v0.100.0-ferretdb-2.0.1`,
// it replaces special characters with `~` returning `0.100.0~ferretdb~2.0.1`.
func defineForTag(tag string) (string, error) {
match := tagVer.FindStringSubmatch(tag)
if match == nil || len(match) != tagVer.NumSubexp()+1 {
return "", fmt.Errorf("unexpected tag syntax %q", tag)
}

major := match[tagVer.SubexpIndex("major")]
minor := match[tagVer.SubexpIndex("minor")]
patch := match[tagVer.SubexpIndex("patch")]

semVer := fmt.Sprintf("%s.%s.%s", major, minor, patch)

rest := match[tagVer.SubexpIndex("rest")]
if rest == "" {
return semVer, nil
}

rest = disallowedVer.ReplaceAllString(rest, "~")

return fmt.Sprintf("%s~%s", semVer, rest), nil
}

// setResults sets action output parameters, summary, etc.
func setResults(action *githubactions.Action, res string) {
output := fmt.Sprintf("version: %s", res)

action.AddStepSummary(output)
action.Infof("%s", output)
action.SetOutput("version", res)
}
Loading
Loading