commit d67d814144d01dede5a0bef48e84f2169f9f72b1 Author: Sherif Emad Date: Sun Nov 8 15:39:22 2026 +0200 init diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml new file mode 100644 index 0000000..e6a4d69 --- /dev/null +++ b/.gitea/workflows/lint.yml @@ -0,0 +1,44 @@ +name: lint + +on: + push: + pull_request: + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install linters + run: | + if [ "$(id -u)" -eq 0 ]; then SUDO=""; else SUDO="sudo"; fi + $SUDO apt-get update -qq + $SUDO apt-get install -y -qq shellcheck yamllint + - name: shellcheck + run: shellcheck scripts/*.sh + - name: yamllint + run: yamllint -d relaxed actions/ .gitea/ consumer-example/ + + smoke: + runs-on: ubuntu-latest + needs: lint + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: hello + uses: ./actions/hello + with: + name: smoke-test + - name: notify + uses: ./actions/notify + with: + status: ok + message: smoke test + - name: auto-tag (dry run) + id: tag + uses: ./actions/auto-tag + with: + tag-type: dev + - name: show result + run: echo "next tag would be ${{ steps.tag.outputs.tag }}" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..adc0854 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +## v1.0.0 - 2026-11-08 +### Added +- Gitea Actions port of the GitLab ci-templates repo +- Composite actions: `actions/hello`, `actions/notify`, `actions/auto-tag` +- Scripts: `scripts/hello.sh`, `scripts/notify.sh`, `scripts/auto-tag.sh` +- Lint and smoke-test workflow in `.gitea/workflows/lint.yml` + +### Changed +- None + +### Fixed +- None + +### Breaking +- (none) + +## v1.1.0 - 2026-11-08 +### Added +- `actions/check-tags` and `scripts/check-tags.sh` (port of the Jenkins "Check Tags" stage) + +### Changed +- None + +### Fixed +- None + +### Breaking +- (none) diff --git a/README.md b/README.md new file mode 100644 index 0000000..2becdd5 --- /dev/null +++ b/README.md @@ -0,0 +1,499 @@ +# ci-templates + +Shared Gitea Actions scripts and reusable actions. Projects reference this repo instead of copy-pasting workflow code. + +- **Actions** (`actions//action.yml`) are composite actions that projects call with `uses:`. +- **Scripts** (`scripts/*.sh`) are bash scripts that the actions run. They live in the same repo and the same tag as the actions. + +> Why is this simpler than the GitLab version? `uses: org/repo/path@ref` checks out the whole repo at that ref, so an action can call `${{ github.action_path }}/../../scripts/x.sh` directly. There is no separate clone step, no job token allowlist, and only one version pin. + +--- + +## Table of contents + +1. [Repo layout](#1-repo-layout) +2. [Quick start: using the repo from a project](#2-quick-start-using-the-repo-from-a-project) +3. [How it works](#3-how-it-works) +4. [Catalog](#4-catalog) +5. [Standards](#5-standards) +6. [Adding a new script](#6-adding-a-new-script) +7. [Adding a new action](#7-adding-a-new-action) +8. [Testing changes](#8-testing-changes) +9. [Versioning and releases](#9-versioning-and-releases) +10. [One-time setup](#10-one-time-setup) +11. [Troubleshooting](#11-troubleshooting) +12. [Contribution checklist](#12-contribution-checklist) + +--- + +## 1. Repo layout + +``` +ci-templates/ +├── .gitea/workflows/ +│ └── lint.yml # lints this repo (shellcheck + yamllint) and smoke-tests the actions +├── README.md # this file +├── CHANGELOG.md # one entry per release +├── scripts/ +│ ├── hello.sh +│ ├── notify.sh +│ └── auto-tag.sh +├── actions/ +│ ├── hello/action.yml # calls scripts/hello.sh +│ ├── notify/action.yml # calls scripts/notify.sh +│ └── auto-tag/action.yml # calls scripts/auto-tag.sh +└── consumer-example/ + └── .gitea/workflows/ci.yml # sample workflow for a consuming project +``` + +--- + +## 2. Quick start: using the repo from a project + +Add this to the consuming project's `.gitea/workflows/ci.yml`. Replace `gitea.example.com` and `devops/ci-templates` with the real host and path of this repo. + +```yaml +name: ci +on: + push: + branches: [main] + +jobs: + say-hello: + runs-on: ubuntu-latest + steps: + - uses: https://gitea.example.com/devops/ci-templates/actions/hello@v1.0.0 # always pin a tag, avoid main + with: + name: Sherif +``` + +Short form: if the instance sets `DEFAULT_ACTIONS_URL = self` in `app.ini` (`[actions]` section), you can write `uses: devops/ci-templates/actions/hello@v1.0.0` instead of the full URL. Without it, short names resolve to github.com. + +Rules for consumers: + +- Always pin a tag in `uses: ...@vX.Y.Z`. That one pin controls both the action YAML and the scripts. +- Configure actions through `with:` inputs. The defaults are documented in each `action.yml` header comment. +- Actions never set `runs-on`, triggers or conditions. The consumer's workflow decides when and where a job runs. +- The runner image must have `bash` (and `git` for `auto-tag`). + +--- + +## 3. How it works + +``` +consumer workflow + │ + └─ job step: uses: /devops/ci-templates/actions/hello@v1.0.0 + │ + ├─ runner fetches the repo at ref v1.0.0 + ├─ reads actions/hello/action.yml (composite action) + └─ step runs: + ${{ github.action_path }}/../../scripts/hello.sh "$GREET_NAME" +``` + +`github.action_path` points to the checked-out `actions/hello` directory, so `../../scripts/` is the scripts folder of the same tag. Actions and scripts can never be out of sync. + +Results are returned to the caller through action **outputs** (for example `steps.tag.outputs.tag`). To pass them to later jobs, expose them as job `outputs:` and read them with `needs..outputs.`. + +--- + +## 4. Catalog + +Keep this section current. Update it in the same pull request that adds or changes a script or action. + +### Actions + +| Path | Purpose | Needs | +|---|---|---| +| `actions/hello` | Prints a greeting and CI info (example) | bash | +| `actions/notify` | Prints a notification line (stub for a webhook) | bash | +| `actions/auto-tag` | Calculates (and optionally pushes) the next git tag | bash, git, checkout with `fetch-depth: 0` | +| `actions/check-tags` | + +### Scripts + +| Script | Purpose | Inputs | +|---|---|---| +| `scripts/hello.sh` | Prints a greeting and CI info | arg 1: name (default `world`) | +| `scripts/notify.sh` | Prints a notification line (stub for a webhook) | arg 1: status, arg 2: message | +| `scripts/auto-tag.sh` | Calculates the next tag, writes `tag.env`, optionally pushes | env: `TAG_TYPE`, `TAG_ENV`, `PUSH_TAG`, `GIT_PUSH_TOKEN` | + +### Action inputs + +| Action | Input | Default | Meaning | +|---|---|---|---| +| `hello` | `name` | `world` | Name to greet | +| `notify` | `status` | `info` | Status word in the message | +| `notify` | `message` | `pipeline step finished` | Message text | +| `auto-tag` | `tag-type` | none, **required** | Tag prefix: `dev`, `beta`, `prod`, ... | +| `auto-tag` | `tag-env` | empty | `production` switches to the `-..` scheme | +| `auto-tag` | `push-tag` | `"false"` | `"true"` creates and pushes the tag | +| `auto-tag` | `push-token` | empty | Token with write access to the consuming repo. Required only when `push-tag` is `"true"`. Pass a secret. | + +### Action outputs + +| Action | Output | Meaning | +|---|---|---| +| `auto-tag` | `tag` | The new tag | +| `auto-tag` | `previous-tag` | Latest existing tag with this prefix (empty if none) | +| `auto-tag` | `stream` | The tag type (prefix) | + +### Auto-tag behavior + +This ports the Jenkins AutoTag stage. It tags the **consuming** repo, unrelated to the releases of this repo. + +| Mode | Latest tag | New tag | Starting point | +|---|---|---|---| +| non-production (`tag-env` not `production`) | `dev-5` | `dev-6` | `dev-0` → `dev-1` | +| `tag-env: production` | `prod-1.2.3` | `prod-2.2.3` | `prod-1.0.0` → `prod-2.0.0` | + +In production mode only the first number is bumped and major/minor are carried over. The first production tag is therefore `-2.0.0`, not `-1.0.0`. This matches the original Groovy logic. + +The script also writes `tag.env` (`TAG`, `STREAM`, `PREVIOUS_TAG`) in the working directory for local use. + +--- + +## 5. Standards + +### 5.1 Naming + +- Files and directories: `kebab-case`. Scripts end in `.sh`; every action is a directory containing `action.yml`. +- Action names use the topic: `auto-tag`, `deploy-k8s`. +- Action inputs and outputs: `kebab-case` (`tag-type`, `previous-tag`). +- Script environment variables: `UPPER_SNAKE_CASE`, with a shared prefix when several belong together. +- One concern per action. Prefer several small actions over one large one. + +### 5.2 Scripts + +Every script must: + +- Start with `#!/usr/bin/env bash` and `set -euo pipefail`. +- Begin with a header comment: purpose, usage line, inputs (args and env vars), outputs. +- Validate required inputs early with a clear message: `X="${X:?X is required}"`. +- Read configuration from environment variables or arguments. Never hardcode hosts, repo paths, or credentials. +- Print errors to stderr and exit non-zero on failure. Print a short log of what it is doing. +- Never echo secrets. Do not enable `set -x` in scripts that handle tokens. +- Pass `shellcheck` with no warnings. +- Be executable and committed as such (`chmod +x`, see section 6). +- Prefer `sed -n 1p` over `head -n 1` after a pipe in scripts using `pipefail` (avoids SIGPIPE failures). +- Write results to `$GITHUB_OUTPUT` (when set) so actions can expose them as outputs. + +### 5.3 Actions + +Every action must: + +- Be a **composite action** (`runs: using: composite`) in `actions//action.yml`. +- Start with a header comment: purpose, runner requirements, and every input and output (required or optional, with defaults). +- Declare every input with a `description`, and a `default` for optional ones. Required inputs have `required: true` and the script fails loudly if missing. +- Pass inputs to scripts through `env:`, never by interpolating `${{ inputs.x }}` directly into `run:` (prevents shell injection). +- Call scripts through `${{ github.action_path }}/../../scripts/.sh`. +- Set `shell: bash` on every `run` step (required in composite actions). +- Not set `runs-on`, triggers, `if:` or `continue-on-error`. The consumer decides when and where a job runs. +- Pin any image or action it uses (`actions/checkout@v4`, not `@main`). +- Not install heavy tooling at runtime. Document what the runner needs instead. +- Expose results through `outputs:` mapped from a step `id`. + +### 5.4 Compatibility rules (what you may change without breaking consumers) + +| Change | Allowed in | +|---|---| +| Fix a bug, no interface change | patch | +| Add a new script or action | minor | +| Add a new **optional** input with a safe default | minor | +| Add a new output | minor | +| Rename or remove an action, input, output, script, or file | **major** | +| Change a default value so behavior differs | **major** | +| Change script arguments or output format | **major** | +| Make an optional input required | **major** | + +When in doubt, treat it as breaking. + +### 5.5 Commits and pull requests + +- Never push directly to `main`. Use a branch and a pull request. +- Commit messages: short imperative summary, optionally prefixed (`feat:`, `fix:`, `docs:`, `chore:`). Breaking changes are marked `feat!:` or `fix!:` and explained in the body. +- Every PR updates the [catalog](#4-catalog) and, for user-visible changes, `CHANGELOG.md`. +- The repo workflow (shellcheck + yamllint + smoke test) must be green before merging. + +--- + +## 6. Adding a new script + +1. Create the file under `scripts/`: + + ```bash + #!/usr/bin/env bash + # + # Usage: my-script.sh + # Inputs (env vars): FOO (required), BAR (optional, default x) + # Outputs: + set -euo pipefail + + ARG="${1:?usage: my-script.sh }" + FOO="${FOO:?FOO is required}" + BAR="${BAR:-x}" + + echo "doing the thing with ${ARG}" + ``` + +2. Make it executable, and make sure git records that: + + ```bash + chmod +x scripts/my-script.sh + git add scripts/my-script.sh + git update-index --chmod=+x scripts/my-script.sh + ``` + +3. Lint and run it locally: + + ```bash + shellcheck scripts/my-script.sh + FOO=1 ./scripts/my-script.sh test + ``` + +4. Expose it through an action (see next section) so projects can use it. +5. Add it to the [catalog](#4-catalog). + +--- + +## 7. Adding a new action + +1. Create `actions//action.yml`: + + ```yaml + # Action: . + # + # Inputs consumers set: + # foo required what it is + # bar optional default "x" + # + # Outputs: + # + # Needs: bash on the runner. + + name: my-action + description: + inputs: + foo: + description: what it is + required: true + bar: + description: what it is + required: false + default: x + outputs: + result: + description: what it is + value: ${{ steps.run.outputs.RESULT }} + runs: + using: composite + steps: + - name: Run my-script.sh + id: run + shell: bash + env: + FOO: ${{ inputs.foo }} + BAR: ${{ inputs.bar }} + run: '"${{ github.action_path }}/../../scripts/my-script.sh" "$FOO"' + ``` + +2. Validate it: + + ```bash + python3 -c "import yaml; yaml.safe_load(open('actions//action.yml')); print('ok')" + yamllint -d relaxed actions/ + ``` + +3. Add a usage example to `consumer-example/.gitea/workflows/ci.yml`. +4. Add a step to the `smoke` job in `.gitea/workflows/lint.yml` that calls it with `uses: ./actions/`. +5. Add it to the [catalog](#4-catalog) and to `CHANGELOG.md`. +6. Test it from a real consumer repo on a branch (next section). + +--- + +## 8. Testing changes + +### Level 1: local, no Gitea needed + +```bash +bash -n scripts/*.sh # syntax check +shellcheck scripts/*.sh # lint +``` + +For scripts that use git (like `auto-tag.sh`), test against a throwaway repo: + +```bash +mkdir /tmp/tagtest && cd /tmp/tagtest +git init -q . && git commit -q --allow-empty -m init +git tag dev-1 && git tag dev-9 && git tag dev-10 +TAG_TYPE=dev /path/to/ci-templates/scripts/auto-tag.sh # expect dev-11 +TAG_TYPE=prod TAG_ENV=production /path/to/ci-templates/scripts/auto-tag.sh # expect prod-2.0.0 +``` + +### Level 2: this repo's own workflow + +`.gitea/workflows/lint.yml` runs shellcheck and yamllint, then smoke-tests every action with `uses: ./actions/`. Keep it green. + +### Level 3: real consumer workflow, on a branch + +1. Push your changes to a branch, e.g. `feat/new-action`. +2. In a test repo, point the pin at the branch: + + ```yaml + jobs: + my-test: + runs-on: ubuntu-latest + steps: + - uses: https://gitea.example.com/devops/ci-templates/actions/my-topic@feat/new-action + with: + foo: bar + ``` + +3. Run the workflow and read the job log. +4. Merge, release a tag, then switch consumers to the tag. + +--- + +## 9. Versioning and releases + +This repo uses **semantic versioning** with git tags: `vMAJOR.MINOR.PATCH`. Consumers pin a tag, so a change on `main` can never break a workflow until someone upgrades on purpose. + +### 9.1 Choosing the next version + +Use the table in [section 5.4](#54-compatibility-rules-what-you-may-change-without-breaking-consumers). + +| Example change | Bump | +|---|---| +| Fix a typo in an error message | `v1.0.0` → `v1.0.1` | +| Add `actions/deploy-k8s` | `v1.0.1` → `v1.1.0` | +| Rename `actions/hello` to `actions/greet` | `v1.1.0` → `v2.0.0` | + +### 9.2 Release steps + +```bash +# 1. be on an up-to-date main, with the PR merged and the workflow green +git checkout main && git pull + +# 2. update CHANGELOG.md (see format below) and commit it +git add CHANGELOG.md +git commit -m "docs: changelog for v1.1.0" +git push origin main + +# 3. create an annotated tag and push it +git tag -a v1.1.0 -m "v1.1.0: add auto-tag action" +git push origin v1.1.0 +``` + +Optionally also maintain a **moving major tag** (`v1`) so consumers who accept non-breaking updates can follow it: + +```bash +git tag -fa v1 -m "v1 -> v1.1.0" +git push --force origin v1 +``` + +Runners may cache a fetched action by ref, so a moving tag can lag on busy runners. Pinning the full version is the reliable choice. + +If the push is rejected (for example by protected-tag rules), delete the remote tag and push it again. Never move a full-version tag like `v1.1.0` once published. To fix a bad release, publish `v1.1.1`. + +Consider protecting `v*` tags (Repository Settings → Tags → Protected tags) so only maintainers can create them. Optionally also create a Gitea Release from the tag with the changelog text. + +### 9.3 Changelog format + +Newest first, one section per release: + +```markdown +# Changelog + +## v1.1.0 - 2026-11-15 +### Added +- `actions/deploy-k8s` and `scripts/deploy-k8s.sh` + +### Changed +- ... + +### Fixed +- ... + +### Breaking +- (none) +``` + +### 9.4 Upgrading a consumer + +Change the **one** pin in the consuming repo, then run its workflow: + +```yaml +- uses: https://gitea.example.com/devops/ci-templates/actions/hello@v1.1.0 # <- here +``` + +For a major upgrade, read the `Breaking` section of the changelog first. + +### 9.5 Deprecation + +Do not delete an action or input abruptly. Keep the old name working for at least one minor release, print a `WARNING: X is deprecated, use Y` line from the step, note it in the changelog, and remove it in the next major. + +### 9.6 Auto-tag vs releases of this repo + +`auto-tag` generates tags such as `dev-12` or `prod-3.0.1` for **other** repos. This repo's own releases are always manual `vX.Y.Z` tags. Do not mix the two schemes. + +--- + +## 10. One-time setup + +1. **Create the repo** in Gitea as `devops/ci-templates`. Visibility `public` (simplest) or `internal`/`private` with the access notes below. +2. **Enable Actions** on the instance (`[actions] ENABLED = true`) and have at least one `act_runner` registered with the label your workflows use (`ubuntu-latest` in these examples). The runner image needs `bash` and `git`, and Node.js for `actions/checkout`. +3. **Let consumers resolve the actions.** + - Either use the full URL in `uses:` (as in the examples), or set `DEFAULT_ACTIONS_URL = self` in `app.ini` to allow the short form. + - For a `private` repo, the workflow token must be able to read it. Safest options: make this repo `internal`/`public` within your org, or keep consumers in the same org. + - `actions/checkout@v4` itself resolves from github.com by default. If the runner has no internet, mirror it into Gitea and use its full URL. +4. **Tag auto-pushing (only if you use `push-tag: "true"`).** In the consuming repo: + - Create an access token with write access to repository contents (a dedicated bot user with Write role is best). + - Save it as a repository or org **secret** named `GIT_PUSH_TOKEN` and pass it as `push-token: ${{ secrets.GIT_PUSH_TOKEN }}`. +5. **Protect `main`** and require pull requests and a green check. +6. Optionally protect `v*` tags. + +--- + +## 11. Troubleshooting + +| Symptom | Likely cause | Fix | +|---|---|---| +| Step fails resolving `uses:` (clone error, 404, "repository not found") | Wrong host/path in the URL, short form used without `DEFAULT_ACTIONS_URL = self`, or runner cannot read the repo | Use the full URL, check the path, make the repo readable by the runner | +| Runner tries github.com for `devops/ci-templates/...` | Short form without `DEFAULT_ACTIONS_URL = self` | Use the full URL or set the option | +| `hello.sh: No such file or directory` | Action called from a copy that does not include `scripts/`, or `github.action_path` unsupported on an old runner | Reference the action by `uses:` from the repo (not copied files); update `act_runner` | +| `Permission denied` running a script | Executable bit not committed | `git update-index --chmod=+x scripts/`, commit | +| `bash: not found` / `git: not found` | Slim runner image without them | Use a runner image that includes them | +| `Required property is missing: shell` | A composite `run` step without `shell:` | Add `shell: bash` | +| auto-tag always returns the first tag | Shallow clone, tags missing | Checkout with `fetch-depth: 0` | +| `latest tag '...' is not in the expected format` | A tag with the same prefix but a different format exists (e.g. `dev-abc`) | Delete or rename the odd tag, or use a different `tag-type` | +| `steps.tag.outputs.tag` empty | Wrong step `id`, or action failed before writing outputs | Check the id and the step log | +| Tag output empty in a later job | Job output not declared | Add `outputs:` to the job and use `needs..outputs.tag` | +| New behavior not showing after release | Runner cached the old ref (usually with moving tags like `v1`) | Pin the full tag, or clear the runner cache | +| `push-tag: "true"` fails on push | Token missing, no write access, or tag protection blocks it | Check the secret, the bot's role, and protected tag rules | +| `fatal:` couldn't find remote ref in check-tags | The branch input does not exist on origin, or the workflow ran on a tag ref | Pass branch: explicitly | +| `TAGS_VERSION` must be one of major|minor|test|cib | Wrong tags-version value | Use one of the four values | + +--- + +## 12. Contribution checklist + +Copy into every pull request: + +```markdown +- [ ] Script has shebang, `set -euo pipefail`, header comment, input validation +- [ ] `shellcheck` clean; script executable and committed as such +- [ ] Action is composite, passes inputs via `env:`, sets `shell: bash` on every run step +- [ ] Action header documents requirements, inputs, outputs with defaults +- [ ] No `runs-on`/triggers/`if:` inside actions; third-party actions pinned +- [ ] Smoke step added to `.gitea/workflows/lint.yml` +- [ ] Tested locally and from a consumer repo on a branch +- [ ] Catalog in README updated +- [ ] CHANGELOG.md updated; version bump chosen per section 5.4 +- [ ] Breaking change? Marked in the commit, changelog, and bumped as major +``` + +--- + +## Future option: reusable workflows + +Gitea also supports `workflow_call` reusable workflows (check your Gitea version). They suit whole pipelines (build, test, deploy) while composite actions suit single steps. If this repo grows, add them under `.gitea/workflows/` and keep the same versioning rules above. diff --git a/actions/auto-tag/action.yml b/actions/auto-tag/action.yml new file mode 100644 index 0000000..0ed44cf --- /dev/null +++ b/actions/auto-tag/action.yml @@ -0,0 +1,55 @@ +# Action: auto-tag. Calculates (and optionally pushes) the next git tag +# of the CONSUMING repo. Unrelated to releases of ci-templates itself. +# +# Inputs consumers set: +# tag-type required tag prefix: dev, beta, prod, ... +# tag-env optional "production" -> -.. scheme +# push-tag optional "true" creates and pushes the tag (default "false") +# push-token optional token with write access; required when push-tag=true +# +# Outputs: tag, previous-tag, stream +# +# Needs: bash and git on the runner, and a checkout with full tag history: +# - uses: actions/checkout@v4 +# with: { fetch-depth: 0 } + +name: auto-tag +description: Calculates (and optionally pushes) the next git tag +inputs: + tag-type: + description: "Tag prefix: dev, beta, prod, ..." + required: true + tag-env: + description: "Set to production for the -.. scheme" + required: false + default: "" + push-tag: + description: "true creates and pushes the tag" + required: false + default: "false" + push-token: + description: "Token with write access. Required only when push-tag is true" + required: false + default: "" +outputs: + tag: + description: The new tag + value: ${{ steps.calc.outputs.TAG }} + previous-tag: + description: The latest existing tag with this prefix (empty if none) + value: ${{ steps.calc.outputs.PREVIOUS_TAG }} + stream: + description: The tag type (prefix) + value: ${{ steps.calc.outputs.STREAM }} +runs: + using: composite + steps: + - name: Calculate next tag + id: calc + shell: bash + env: + TAG_TYPE: ${{ inputs.tag-type }} + TAG_ENV: ${{ inputs.tag-env }} + PUSH_TAG: ${{ inputs.push-tag }} + GIT_PUSH_TOKEN: ${{ inputs.push-token }} + run: '"${{ github.action_path }}/../../scripts/auto-tag.sh"' diff --git a/actions/check-tags/action.yml b/actions/check-tags/action.yml new file mode 100644 index 0000000..aa1c080 --- /dev/null +++ b/actions/check-tags/action.yml @@ -0,0 +1,48 @@ +# Action: check-tags. Decides the next semantic-version tag for the CONSUMING +# repo, or reports skip=true when the branch head is already tagged. +# Calculates only: it does not create or push a tag. +# +# Inputs consumers set: +# tags-version required major | minor | test | cib +# major -> main-v..

, bumps major +# minor -> dev-v..

, bumps minor +# test -> test-v..

, bumps patch +# cib -> cib-v..

, bumps patch +# branch optional branch to compare against (default: current ref name) +# +# Outputs: tag, previous-tag, skip +# +# Needs: bash and git on the runner, and a checkout with full history: +# - uses: actions/checkout@v4 +# with: { fetch-depth: 0 } + +name: check-tags +description: Calculates the next semver tag, or skips when the head is already tagged +inputs: + tags-version: + description: "major, minor, test or cib" + required: true + branch: + description: "Branch to compare against. Defaults to the current ref name" + required: false + default: "" +outputs: + tag: + description: The new tag, or the existing latest tag when skip is true + value: ${{ steps.calc.outputs.TAG }} + previous-tag: + description: The latest existing tag with this prefix (empty if none) + value: ${{ steps.calc.outputs.PREVIOUS_TAG }} + skip: + description: '"true" when the branch head already carries the latest tag' + value: ${{ steps.calc.outputs.SKIP }} +runs: + using: composite + steps: + - name: Check tags + id: calc + shell: bash + env: + TAGS_VERSION: ${{ inputs.tags-version }} + BRANCH_NAME: ${{ inputs.branch }} + run: '"${{ github.action_path }}/../../scripts/check-tags.sh"' \ No newline at end of file diff --git a/actions/hello/action.yml b/actions/hello/action.yml new file mode 100644 index 0000000..1b928a2 --- /dev/null +++ b/actions/hello/action.yml @@ -0,0 +1,22 @@ +# Action: hello. Prints a greeting and CI info (example action). +# +# Inputs consumers set: +# name optional default "world" +# +# Needs: bash on the runner. + +name: hello +description: Prints a greeting and CI info +inputs: + name: + description: Name to greet + required: false + default: world +runs: + using: composite + steps: + - name: Run hello.sh + shell: bash + env: + GREET_NAME: ${{ inputs.name }} + run: '"${{ github.action_path }}/../../scripts/hello.sh" "$GREET_NAME"' diff --git a/actions/notify/action.yml b/actions/notify/action.yml new file mode 100644 index 0000000..60aa873 --- /dev/null +++ b/actions/notify/action.yml @@ -0,0 +1,28 @@ +# Action: notify. Prints a notification line (stub for a webhook). +# +# Inputs consumers set: +# status optional default "info" +# message optional default "pipeline step finished" +# +# Needs: bash on the runner. + +name: notify +description: Prints a notification line +inputs: + status: + description: Status word in the message + required: false + default: info + message: + description: Message text + required: false + default: pipeline step finished +runs: + using: composite + steps: + - name: Run notify.sh + shell: bash + env: + NOTIFY_STATUS: ${{ inputs.status }} + NOTIFY_MESSAGE: ${{ inputs.message }} + run: '"${{ github.action_path }}/../../scripts/notify.sh" "$NOTIFY_STATUS" "$NOTIFY_MESSAGE"' diff --git a/consumer-example/.gitea/workflows/ci.yml b/consumer-example/.gitea/workflows/ci.yml new file mode 100644 index 0000000..aebca90 --- /dev/null +++ b/consumer-example/.gitea/workflows/ci.yml @@ -0,0 +1,45 @@ +# Sample workflow for a consuming project. +# Copy to /.gitea/workflows/ci.yml and adjust the host/org. +# +# If your Gitea instance has DEFAULT_ACTIONS_URL = self (app.ini, [actions]), +# you can use the short form devops/ci-templates/actions/hello@v1.0.0. +# Otherwise use the full URL as below. + +name: ci + +on: + push: + branches: [main] + +jobs: + hello: + runs-on: ubuntu-latest + steps: + - uses: https://gitea.example.com/devops/ci-templates/actions/hello@v1.0.0 + with: + name: Sherif + + tag: + runs-on: ubuntu-latest + needs: hello + outputs: + tag: ${{ steps.tag.outputs.tag }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # auto-tag needs the full tag history + - id: tag + uses: https://gitea.example.com/devops/ci-templates/actions/auto-tag@v1.0.0 + with: + tag-type: dev + push-tag: "true" + push-token: ${{ secrets.GIT_PUSH_TOKEN }} + + notify: + runs-on: ubuntu-latest + needs: tag + steps: + - uses: https://gitea.example.com/devops/ci-templates/actions/notify@v1.0.0 + with: + status: success + message: "tagged ${{ needs.tag.outputs.tag }}" diff --git a/scripts/auto-tag.sh b/scripts/auto-tag.sh new file mode 100755 index 0000000..ba1d76d --- /dev/null +++ b/scripts/auto-tag.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Calculates the next git tag for the current repo and optionally pushes it. +# Usage: auto-tag.sh +# Inputs (env vars): +# TAG_TYPE required tag prefix: dev, beta, prod, ... +# TAG_ENV optional "production" switches to -.. +# PUSH_TAG optional "true" creates and pushes the tag (default false) +# GIT_PUSH_TOKEN optional token with write access; required when PUSH_TAG=true +# Outputs: +# stdout log, tag.env (TAG, STREAM, PREVIOUS_TAG) in the current directory, +# and TAG / STREAM / PREVIOUS_TAG written to $GITHUB_OUTPUT when it is set. +# Requires: full tag history (checkout with fetch-depth: 0). +set -euo pipefail + +TAG_TYPE="${TAG_TYPE:?TAG_TYPE is required}" +TAG_ENV="${TAG_ENV:-}" +PUSH_TAG="${PUSH_TAG:-false}" + +if [[ "${PUSH_TAG}" == "true" ]]; then + : "${GIT_PUSH_TOKEN:?GIT_PUSH_TOKEN is required when PUSH_TAG=true}" +fi + +if [[ "${TAG_ENV}" == "production" ]]; then + PATTERN='^'"${TAG_TYPE}"'-[0-9]+\.[0-9]+\.[0-9]+$' +else + PATTERN='^'"${TAG_TYPE}"'-[0-9]+$' +fi + +echo "auto-tag: type=${TAG_TYPE} env=${TAG_ENV:-} push=${PUSH_TAG}" + +# Latest tag with this prefix (version sort, newest first). +PREVIOUS_TAG="$(git tag --list "${TAG_TYPE}-*" | sort -V -r | sed -n 1p)" + +if [[ -z "${PREVIOUS_TAG}" ]]; then + if [[ "${TAG_ENV}" == "production" ]]; then + TAG="${TAG_TYPE}-2.0.0" + else + TAG="${TAG_TYPE}-1" + fi +else + if ! [[ "${PREVIOUS_TAG}" =~ ${PATTERN} ]]; then + echo "ERROR: latest tag '${PREVIOUS_TAG}' is not in the expected format for TAG_TYPE=${TAG_TYPE} (pattern ${PATTERN})" >&2 + exit 1 + fi + VERSION="${PREVIOUS_TAG#"${TAG_TYPE}"-}" + if [[ "${TAG_ENV}" == "production" ]]; then + MAX="${VERSION%%.*}" + REST="${VERSION#*.}" + TAG="${TAG_TYPE}-$((MAX + 1)).${REST}" + else + TAG="${TAG_TYPE}-$((VERSION + 1))" + fi +fi + +echo "previous tag: ${PREVIOUS_TAG:-}" +echo "next tag: ${TAG}" + +{ + echo "TAG=${TAG}" + echo "STREAM=${TAG_TYPE}" + echo "PREVIOUS_TAG=${PREVIOUS_TAG}" +} > tag.env + +if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + cat tag.env >> "${GITHUB_OUTPUT}" +fi + +if [[ "${PUSH_TAG}" == "true" ]]; then + SERVER_URL="${GITHUB_SERVER_URL:?GITHUB_SERVER_URL is required when PUSH_TAG=true}" + REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is required when PUSH_TAG=true}" + PROTO="${SERVER_URL%%://*}" + HOST="${SERVER_URL#*://}" + git tag "${TAG}" + git push "${PROTO}://oauth2:${GIT_PUSH_TOKEN}@${HOST}/${REPO}.git" "refs/tags/${TAG}" >/dev/null 2>&1 \ + || { echo "ERROR: failed to push tag ${TAG} (check token scope and tag protection)" >&2; exit 1; } + echo "pushed tag ${TAG}" +fi diff --git a/scripts/check-tags.sh b/scripts/check-tags.sh new file mode 100644 index 0000000..ac4a592 --- /dev/null +++ b/scripts/check-tags.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# Decides the next semantic-version tag for the current repo, or skips when the +# branch head is already tagged. Ports the Jenkins "Check Tags" stage. +# Usage: check-tags.sh +# Inputs (env vars): +# TAGS_VERSION required major | minor | test | cib +# major -> prefix main-v, bumps MAJOR (minor/patch reset) +# minor -> prefix dev-v, bumps MINOR (patch reset) +# test -> prefix test-v, bumps PATCH +# cib -> prefix cib-v, bumps PATCH +# BRANCH_NAME optional branch to compare against (default: $GITHUB_REF_NAME) +# Outputs: +# stdout log, tag.env (TAG, PREVIOUS_TAG, SKIP) in the current directory, +# and the same three written to $GITHUB_OUTPUT when it is set. +# TAG = the new tag, or the existing latest tag when SKIP=true +# SKIP = true when the branch head already carries the latest tag +# Requires: full history and tags (checkout with fetch-depth: 0). +# Does not create or push a tag; it only calculates it. +set -euo pipefail + +TAGS_VERSION="${TAGS_VERSION:?TAGS_VERSION is required (major|minor|test|cib)}" +BRANCH_NAME="${BRANCH_NAME:-${GITHUB_REF_NAME:-}}" +BRANCH_NAME="${BRANCH_NAME:?BRANCH_NAME is required (or run inside Gitea Actions)}" + +case "${TAGS_VERSION}" in + major) PREFIX="main-v" ;; + minor) PREFIX="dev-v" ;; + test) PREFIX="test-v" ;; + cib) PREFIX="cib-v" ;; + *) + echo "ERROR: TAGS_VERSION must be one of major|minor|test|cib, got '${TAGS_VERSION}'" >&2 + exit 1 + ;; +esac + +echo "check-tags: version=${TAGS_VERSION} prefix=${PREFIX} branch=${BRANCH_NAME}" + +git fetch origin "${BRANCH_NAME}" +git fetch --tags --force --prune origin + +PREVIOUS_TAG="$(git tag --list "${PREFIX}*" | sort -V -r | sed -n 1p)" +echo "latest tag for prefix ${PREFIX}: ${PREVIOUS_TAG:-}" + +LATEST_COMMIT="$(git rev-parse "origin/${BRANCH_NAME}")" +LATEST_TAG_COMMIT="" +if [[ -n "${PREVIOUS_TAG}" ]]; then + LATEST_TAG_COMMIT="$(git rev-list -n 1 "${PREVIOUS_TAG}")" +fi + +if [[ "${LATEST_COMMIT}" == "${LATEST_TAG_COMMIT}" ]]; then + echo "No new commits since latest tag ${PREVIOUS_TAG}. Skipping tagging." + TAG="${PREVIOUS_TAG}" + SKIP="true" +else + echo "New commit detected. Incrementing tag..." + + MAJOR=1 + MINOR=0 + PATCH=0 + + if [[ -n "${PREVIOUS_TAG}" ]]; then + if [[ "${PREVIOUS_TAG}" =~ ^${PREFIX}([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then + MAJOR=$((10#${BASH_REMATCH[1]})) + MINOR=$((10#${BASH_REMATCH[2]})) + PATCH=$((10#${BASH_REMATCH[3]})) + else + echo "WARNING: latest tag '${PREVIOUS_TAG}' does not follow semantic versioning. Using defaults." >&2 + fi + fi + + case "${TAGS_VERSION}" in + major) + MAJOR=$((MAJOR + 1)) + MINOR=0 + PATCH=0 + ;; + minor) + MINOR=$((MINOR + 1)) + PATCH=0 + ;; + *) + PATCH=$((PATCH + 1)) + ;; + esac + + TAG="${PREFIX}${MAJOR}.${MINOR}.${PATCH}" + SKIP="false" + echo "New tag will be: ${TAG}" +fi + +{ + echo "TAG=${TAG}" + echo "PREVIOUS_TAG=${PREVIOUS_TAG}" + echo "SKIP=${SKIP}" +} > tag.env + +if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + cat tag.env >> "${GITHUB_OUTPUT}" +fi \ No newline at end of file diff --git a/scripts/hello.sh b/scripts/hello.sh new file mode 100755 index 0000000..a3cd337 --- /dev/null +++ b/scripts/hello.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Prints a greeting and basic CI info. +# Usage: hello.sh [name] +# Inputs (args): name (optional, default "world") +# Outputs: greeting on stdout +set -euo pipefail + +NAME="${1:-world}" + +echo "Hello, ${NAME}!" +echo "repository: ${GITHUB_REPOSITORY:-unknown}" +echo "ref: ${GITHUB_REF:-unknown}" +echo "sha: ${GITHUB_SHA:-unknown}" +echo "run id: ${GITHUB_RUN_ID:-unknown}" diff --git a/scripts/notify.sh b/scripts/notify.sh new file mode 100755 index 0000000..63100e5 --- /dev/null +++ b/scripts/notify.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Prints a notification line (stub: replace with a webhook call later). +# Usage: notify.sh +# Inputs (args): status (required), message (required) +# Outputs: one line on stdout +set -euo pipefail + +STATUS="${1:?usage: notify.sh }" +MESSAGE="${2:?usage: notify.sh }" + +echo "[notify] ${STATUS}: ${MESSAGE} (${GITHUB_REPOSITORY:-unknown} @ ${GITHUB_SHA:-unknown})"