Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1df72a5124 | |||
| 5ace9d5756 | |||
| 8449a9317c | |||
| 263bbbd1ed | |||
| a68993d26f | |||
| 7f404f3492 | |||
| 1615655c00 | |||
| 8c3605ed52 |
@@ -5,6 +5,36 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
This project uses [Semantic Versioning](https://semver.org).
|
||||
|
||||
## [0.3.1] - 2026-06-26
|
||||
|
||||
### Changed
|
||||
|
||||
- **`glint graph` default mode** — no-mode invocation now prints the job tree only (previously printed tree + `---` separator + Mermaid include graph). Use `glint graph includes` for the Mermaid include-dependency output.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`glint check --help`** — `--proxy` option was implemented but missing from the help text.
|
||||
- **`glint graph --help`** — `--cache-dir`, `--offline`, and `--proxy` options were implemented but missing from the help text.
|
||||
- **CI test** — `TestLoad_ReadError` skipped when running as root; Gitea runners execute as root which bypasses file permission checks, causing the test to fail.
|
||||
|
||||
## [0.3.0] - 2026-06-26
|
||||
|
||||
### Added
|
||||
|
||||
- **`glint render` subcommand** — resolves all `include:` and `extends:` chains and writes the fully flattened pipeline to a single YAML file (default: `rendered.gitlab-ci.yml`; use `--output -` for stdout). Strips the consumed `include:` and `extends:` keys; retains template jobs (`.name`). Accepts the same network flags as `glint check` (`--token`, `--gitlab-url`, `--cache-dir`, `--offline`, `--proxy`). Useful for inspecting what GitLab CI actually sees or running further local tooling.
|
||||
|
||||
- **`glint check --no-warn`** — discard all warning findings before output and exit-code calculation. Mixed pipelines (errors + warnings) still exit 2 but only errors are printed. Warnings-only pipelines report "OK" and exit 0.
|
||||
|
||||
- **`glint graph --no-skipped`** — remove jobs that evaluate to `skipped` in the given context (or the implicit `branch=main` default) from all graph output: tree, SVG, HTML, and Mermaid.
|
||||
|
||||
- **Colorized, columnized text output** — `glint check` (text format) now renders findings in four aligned columns: location, rule ID, severity, message. `error` is printed in bold red; `warning` in bold orange. Colors are auto-detected (stdout must be a terminal) and suppressed when `NO_COLOR` is set. Location uses `file:line:col` format when column information is available.
|
||||
|
||||
- **`line:col` locations** — `Column int` added to `model.Job` (set from the YAML parser's `yaml.Node.Column`) and propagated to `Finding.Column` across all linter rules. Plain-text and `Finding.String()` now emit `file:line:col` when column is known.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Exit codes** *(breaking)* — `glint check` now exits `2` when one or more error findings are present (previously `1`) and `10` when findings contain only warnings. Exit `0` remains for a clean pipeline. Errors take precedence over warnings. Scripts that test `[ $? -eq 1 ]` need to be updated to `[ $? -eq 2 ]`.
|
||||
|
||||
## [0.2.31] - 2026-06-26
|
||||
|
||||
### Added
|
||||
|
||||
+48
-9
@@ -118,6 +118,30 @@ Jobs whose name starts with `.` are reusable templates; most rules are skipped f
|
||||
|
||||
---
|
||||
|
||||
## Pipeline rendering (`glint render`)
|
||||
|
||||
`glint render <PIPELINE>` resolves all `include:` and `extends:` chains and
|
||||
writes the fully flattened pipeline to a single YAML file. This is what GitLab
|
||||
CI processes server-side.
|
||||
|
||||
```bash
|
||||
glint render .gitlab-ci.yml # writes rendered.gitlab-ci.yml
|
||||
glint render --output merged.yml .gitlab-ci.yml # custom output path
|
||||
glint render --output - .gitlab-ci.yml | yq . # stream to stdout
|
||||
glint render --offline --cache-dir ~/.cache/glint .gitlab-ci.yml
|
||||
```
|
||||
|
||||
**Output order:** `stages`, `variables`, `default`, `workflow`, template jobs
|
||||
(`.name`, alphabetical), then regular jobs (alphabetical). The `include:` key
|
||||
(consumed by resolution) and `extends:` keys (merged into each job) are
|
||||
stripped. All other fields are preserved verbatim.
|
||||
|
||||
Accepts the same network flags as `glint check`: `--token`, `--gitlab-url`,
|
||||
`--cache-dir`, `--offline`, `--proxy`. When writing to a file (not stdout)
|
||||
a summary line is printed to stderr: `rendered: <file> (N job(s), M stage(s))`.
|
||||
|
||||
---
|
||||
|
||||
## Context simulation
|
||||
|
||||
Pass `--branch`, `--tag`, `--source`, or `--var` to evaluate `rules:if:` and
|
||||
@@ -184,27 +208,37 @@ test-job active active
|
||||
|
||||
---
|
||||
|
||||
## Output formats
|
||||
## Output formats (`glint check`)
|
||||
|
||||
Pass `--format` to `glint check`. In structured formats the summary line is
|
||||
written to stderr so stdout contains only the machine-readable payload.
|
||||
|
||||
| Format | Flag | Description |
|
||||
|--------|------|-------------|
|
||||
| Text (default) | `--format text` | Ruff-style `file:line: RULE [sev] message` |
|
||||
| Text (default) | `--format text` | Four aligned columns (location, rule, severity, message); `error` in bold red, `warning` in bold orange; colors auto-detected (suppressed when `NO_COLOR` is set or stdout is not a terminal) |
|
||||
| JSON | `--format json` | Stable schema (version 1); `findings` array + `summary` block |
|
||||
| SARIF 2.1.0 | `--format sarif` | Consumed by GitHub Code Scanning and GitLab SAST |
|
||||
| JUnit XML | `--format junit` | CI test-report artifact (`artifacts:reports:junit`) |
|
||||
| GitHub annotations | `--format github` | `::error file=…,line=…,title=RULE::message` inline PR comments |
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `0` | No findings (clean pipeline) |
|
||||
| `2` | One or more error findings |
|
||||
| `10` | One or more warning findings, no errors |
|
||||
|
||||
Use `--no-warn` to suppress all warnings; a pipeline with only warnings then exits `0`.
|
||||
|
||||
**JSON schema (`schema_version: 1`):**
|
||||
```json
|
||||
{
|
||||
"schema_version": 1,
|
||||
"glint_version": "v0.2.20",
|
||||
"glint_version": "v0.3.0",
|
||||
"pipeline": ".gitlab-ci.yml",
|
||||
"findings": [
|
||||
{"rule":"GL004","severity":"error","file":".gitlab-ci.yml","line":14,
|
||||
{"rule":"GL004","severity":"error","file":".gitlab-ci.yml","line":14,"column":1,
|
||||
"job":"deploy","message":"stage \"production\" is not defined in 'stages'"}
|
||||
],
|
||||
"summary": {"total": 1, "errors": 1, "warnings": 0}
|
||||
@@ -283,10 +317,10 @@ jobs or pipeline-level findings.
|
||||
|
||||
| Mode | Output |
|
||||
|------|--------|
|
||||
| `tree` (default) | Terminal job tree: stages as branches, jobs as leaves; annotated with `[manual]`, `[delayed]`, `[trigger]` where applicable |
|
||||
| `includes` | Mermaid flowchart to stdout; colour-coded nodes by include type (local, remote, project, component, template) |
|
||||
| `tree` *(default)* | Terminal job tree: stages as branches, jobs as leaves; annotated with `[manual]`, `[delayed]`, `[trigger]` where applicable |
|
||||
| `includes` | Mermaid flowchart of include dependencies to stdout; colour-coded by include type (local, remote, project, component, template) |
|
||||
| `pipeline` | GitLab CI-style SVG/PNG written to `--out` directory (default: `glint-out/`); converted to PNG when `rsvg-convert`, `inkscape`, or `magick` is available |
|
||||
| `all` | `includes` to stdout + `pipeline` file path to stderr |
|
||||
| `all` | `includes` Mermaid to stdout + `pipeline` SVG/PNG path to stderr |
|
||||
|
||||
**`glint graph pipeline --format <FORMAT>`**
|
||||
|
||||
@@ -296,6 +330,8 @@ jobs or pipeline-level findings.
|
||||
| `mermaid` | Print Mermaid flowchart to stdout (paste into [mermaid.live](https://mermaid.live)) |
|
||||
| `html` | Write self-contained HTML to `--out` with mouse pan/zoom and a click-to-open job-detail sidebar |
|
||||
|
||||
**Context flags** (`--branch`, `--tag`, `--source`, `--var`, `--changes`, `--changes-from`) work on all modes and annotate or colour jobs based on their evaluated state. Use `--no-skipped` to remove jobs that would not run in the given context from all output entirely (tree, SVG, HTML, and Mermaid).
|
||||
|
||||
**Visual distinctions in SVG and HTML output:**
|
||||
|
||||
- **Regular** — blue circle with checkmark
|
||||
@@ -303,7 +339,7 @@ jobs or pipeline-level findings.
|
||||
- **Trigger** — purple circle with chevron
|
||||
- **Delayed** — yellow circle with clock
|
||||
- **`when: on_failure`** — red circle (`#d9534f`) with X mark; dashed chip border
|
||||
- **Skipped** (with `--branch`/`--tag`/`--source` context flags) — grey circle, dimmed job name
|
||||
- **Skipped** (with context flags, without `--no-skipped`) — grey circle, dimmed job name
|
||||
|
||||
In DAG pipelines (any job has `needs:`) the pipeline graph uses job-to-job
|
||||
Bézier connectors. In classic mode a bus-bar pattern (vertical rail + per-job
|
||||
@@ -318,7 +354,10 @@ shown as a tooltip in SVG viewers and as a sidebar panel in HTML output.
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `glint render <PIPELINE>` | Resolve all includes and extends; write the fully merged pipeline to a single YAML file. See [Pipeline rendering](#pipeline-rendering-glint-render) above. |
|
||||
| `glint explain <RULE>` | Print description, rationale, bad-YAML example, and fix for a rule. Case-insensitive (`gl007` = `GL007`). |
|
||||
| `glint explain` | List all rules with ID, severity, and title. |
|
||||
| `--list-vars` | Print all resolved pipeline variables (pipeline + workflow rules + context) to stderr before linting. |
|
||||
| `--no-warn` | (`glint check`) Discard all warning findings before output and exit-code calculation. |
|
||||
| `--no-skipped` | (`glint graph`) Remove skipped jobs from graph output entirely. |
|
||||
| `--list-vars` | (`glint check`, `glint graph`) Print all resolved pipeline variables to stderr before continuing. |
|
||||
| `--version` / `-v` | Print the compiled version string. |
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License"></a>
|
||||
<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/release-v0.2.31-blue.svg" alt="Release"></a>
|
||||
<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/release-v0.3.1-blue.svg" alt="Release"></a>
|
||||
</p>
|
||||
|
||||
> **Disclaimer:** This tool was built through iterative AI-assisted development with [Claude](https://claude.ai). It is experimental, incomplete, and not intended for production use. Coverage of GitLab CI keywords is best-effort and may lag behind GitLab's evolving spec. Use it at your own discretion — no correctness guarantees are made. Contributions and bug reports are welcome.
|
||||
@@ -17,10 +17,11 @@ A local tool to validate and lint `.gitlab-ci.yml` pipelines without needing a G
|
||||
|
||||
- **Lints** — 45 rules covering pipeline structure, keyword constraints, `needs:`/`dependencies:` graphs, expression reachability, and deprecations (GL001–GL045); run `glint explain <ID>` for any rule
|
||||
- **Resolves includes** — local files, HTTPS URLs, GitLab project templates, and CI/CD Catalog components, with offline cache support and HTTP proxy support (`--proxy` flag or `proxy:` in `.glint.yml`)
|
||||
- **Renders merged pipeline** — `glint render` resolves all includes and `extends:` chains into a single flat YAML file, matching what GitLab CI actually processes
|
||||
- **Simulates context** — `--branch`, `--tag`, `--source` flags evaluate `rules:if:` and `only`/`except` to show which jobs would be active, manual, or skipped; `--context branch=main --context branch=develop` prints a multi-column comparison table across multiple contexts in one run
|
||||
- **Multiple output formats** — `--format text` (default, ruff-style), `json`, `sarif` (GitHub Code Scanning / GitLab SAST), `junit`, `github` (PR annotations)
|
||||
- **Project config** — `.glint.yml` for rule suppression, severity overrides, token/URL/proxy defaults; `# glint: ignore RULE` for per-job inline suppression
|
||||
- **Graph visualization** — `glint graph` prints a terminal job tree; `glint graph pipeline` renders a GitLab CI-style SVG/PNG; `--format mermaid` emits a Mermaid flowchart; `--format html` produces a self-contained HTML file with pan/zoom and a job-detail sidebar; context flags grey out skipped jobs
|
||||
- **Multiple output formats** — `--format text` (default, colorized and column-aligned), `json`, `sarif` (GitHub Code Scanning / GitLab SAST), `junit`, `github` (PR annotations); exits `2` on errors, `10` on warnings only
|
||||
- **Project config** — `.glint.yml` for rule suppression, severity overrides, token/URL/proxy defaults; `# glint: ignore RULE` for per-job inline suppression; `--no-warn` flag to suppress all warnings
|
||||
- **Graph visualization** — `glint graph` prints a terminal job tree (default); `glint graph includes` emits a Mermaid include-dependency graph; `glint graph pipeline` renders a GitLab CI-style SVG/PNG; `--format mermaid` or `--format html` for alternative pipeline output; `--no-skipped` hides jobs that would not run in the given context
|
||||
- **LSP server** — `glint lsp` starts a Language Server Protocol server over stdin/stdout; connect with any LSP client to get inline diagnostics (rule ID as code, error/warning severity) in VS Code, Neovim, Emacs, JetBrains, etc.
|
||||
- **VS Code extension** — `editors/vscode/` wraps the LSP server; inline squiggles for every glint rule directly in the editor
|
||||
|
||||
@@ -51,15 +52,15 @@ task build
|
||||
glint [OPTIONS] <COMMAND>
|
||||
|
||||
Commands:
|
||||
check Lint a pipeline file — exits 0 (clean) or 1 (errors found)
|
||||
check Lint a pipeline file — exits 0 (clean), 2 (errors), or 10 (warnings only)
|
||||
render Resolve all includes and extends into a single merged YAML file
|
||||
graph Visualise the pipeline as a job tree or Mermaid graph
|
||||
explain Print description and fix for a lint rule
|
||||
explain Show description and fix for a lint rule (e.g. glint explain GL007)
|
||||
lsp Start a Language Server Protocol server (stdin/stdout)
|
||||
```
|
||||
|
||||
Run `glint <command> --help` for all flags. See [USAGE.md](USAGE.md) for full
|
||||
examples covering output formats, context simulation, remote includes, cache,
|
||||
graph modes, and project configuration.
|
||||
Run `glint <command> --help` for all flags. See [FEATURES.md](FEATURES.md) for the
|
||||
complete feature reference.
|
||||
|
||||
## Integrations
|
||||
|
||||
@@ -70,7 +71,7 @@ Add to `.pre-commit-config.yaml` in your repository to run glint automatically w
|
||||
```yaml
|
||||
repos:
|
||||
- repo: https://git.k3nny.fr/k3nny/glint
|
||||
rev: v0.2.28
|
||||
rev: v0.3.0
|
||||
hooks:
|
||||
- id: glint
|
||||
```
|
||||
@@ -88,7 +89,7 @@ include:
|
||||
|
||||
# As a Catalog component (after publishing to a GitLab instance):
|
||||
include:
|
||||
- component: $CI_SERVER_FQDN/k3nny/glint/check@v0.2.28
|
||||
- component: $CI_SERVER_FQDN/k3nny/glint/check@v0.3.0
|
||||
inputs:
|
||||
stage: validate # optional, default: validate
|
||||
allow_failure: true # optional, default: false
|
||||
@@ -101,7 +102,7 @@ The component downloads the glint Linux binary, runs `glint check`, and respects
|
||||
Copy [`action.yml`](action.yml) from this repository, or mirror this repo to GitHub as `k3nny/glint` and reference it directly:
|
||||
|
||||
```yaml
|
||||
- uses: k3nny/glint@v0.2.28
|
||||
- uses: k3nny/glint@v0.3.0
|
||||
with:
|
||||
file: .gitlab-ci.yml # optional, default: .gitlab-ci.yml
|
||||
args: '--format sarif' # optional
|
||||
|
||||
@@ -53,6 +53,7 @@ The current rule set covers the most common sources of broken pipelines. These a
|
||||
- [x] **Recursive include depth limit** — shipped v0.2.17; depth capped at 100 (matching GitLab); project/component includes now tracked in visited set to prevent cross-file cycles
|
||||
- [x] **Offline mode / cache** — shipped v0.2.17; `--cache-dir DIR` persists fetched templates; `--offline` serves from cache only; default cache dir (`~/.cache/glint`) used automatically with `--offline`
|
||||
- [x] **`include: inputs:`** — shipped v0.2.17; `$[[ inputs.KEY ]]` and `$[[ inputs.KEY | default(…) ]]` placeholders in fetched component YAML are substituted from the include's `with:` block before parsing
|
||||
- [x] **`glint render` subcommand** — shipped v0.3.0; resolves all `include:` and `extends:` chains into a single flat YAML file; strips consumed keys; accepts same network flags as `glint check`; default output `rendered.gitlab-ci.yml`, use `--output -` for stdout
|
||||
|
||||
---
|
||||
|
||||
@@ -79,6 +80,7 @@ The SVG renderer and terminal tree cover the basic layout. These would bring it
|
||||
- [x] **Mermaid pipeline output** — shipped v0.2.25; `glint graph pipeline --format mermaid` prints a Mermaid flowchart to stdout (paste into mermaid.live)
|
||||
- [x] **Same-stage job ordering** — shipped v0.2.26; jobs within a stage that have `needs:` between each other are placed in topological sub-columns (left-to-right by depth); stage header spans all sub-columns
|
||||
- [x] **Graph links rendered behind job chips** — shipped v0.2.26; SVG connectors (Bézier curves and bus-bar stubs) are drawn before job chips so lines pass behind rectangles
|
||||
- [x] **`glint graph --no-skipped`** — shipped v0.3.0; removes jobs evaluated as `skipped` in the given context from tree, SVG, HTML, and Mermaid output
|
||||
|
||||
---
|
||||
|
||||
@@ -86,6 +88,8 @@ The SVG renderer and terminal tree cover the basic layout. These would bring it
|
||||
|
||||
- [x] **File and line numbers on findings** — shipped post-v0.2.0; every finding includes the source file and exact line of the job key; works across local includes, remote project templates, and fetched component templates
|
||||
- [x] **Ruff-style output format** — shipped v0.2.11; findings follow `file:line: RULEID [severity] message` matching the convention used by ruff and other modern linters
|
||||
- [x] **Colorized, columnized text output** — shipped v0.3.0; four aligned columns (location, rule, severity, message); `error` in bold red, `warning` in bold orange; auto-detected terminal color (respects `NO_COLOR`)
|
||||
- [x] **`line:col` locations** — shipped v0.3.0; `Column int` on `model.Job` and `Finding`; text output and `Finding.String()` emit `file:line:col` when column is known
|
||||
- [x] **`needs: optional: true` false-positive errors** — shipped post-v0.2.0; optional missing needs are downgraded to `[WARNING]`
|
||||
- [x] **`extends:` jobs with missing script false errors** — shipped post-v0.2.0; jobs using `extends:` that have no `script` after resolution emit `[WARNING]` (the script may come from an unfetchable remote base)
|
||||
- [x] **`rules:if:` static reachability (GL042)** — shipped v0.2.20; warns when all `rules:if:` conditions evaluate to false given declared variable values (only fires when all referenced vars are declared in YAML)
|
||||
@@ -129,3 +133,5 @@ The SVG renderer and terminal tree cover the basic layout. These would bring it
|
||||
- [x] **Subcommand CLI** — shipped v0.2.0 (2026-06-11); `glint check` / `glint graph [mode]` with ruff-style `--help`
|
||||
- [x] **Changelog automation** — shipped v0.2.27; `cliff.toml` configures git-cliff to produce Keep-a-Changelog–compatible release notes from Conventional Commits; `task changelog` regenerates `CHANGELOG.md`, `task changelog-next` previews unreleased entries
|
||||
- [x] **Fuzz testing** — shipped v0.2.27; `FuzzParseBytes` and `FuzzSanitizeYAMLEscapes` in `internal/model/fuzz_test.go`; seeds run as regular tests in CI; `task fuzz` runs them continuously (default 30 s)
|
||||
- [x] **`glint check --no-warn`** — shipped v0.3.0; discards all warning findings before output and exit-code calculation; mixed pipelines (errors + warnings) still exit 2 but only errors are printed; warnings-only pipelines exit 0
|
||||
- [x] **Exit codes 2 / 10** *(breaking)* — shipped v0.3.0; `glint check` exits `2` when errors are present (previously `1`) and `10` when findings contain only warnings; exit `0` for clean
|
||||
|
||||
+15
-15
@@ -68,31 +68,31 @@ tasks:
|
||||
- cmd: ./{{.BINARY}} check --branch feat/x testdata/rules_if_expr.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/workflow_vars.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check --branch main testdata/workflow_vars.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check --branch develop testdata/workflow_vars.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check --branch feat/x testdata/workflow_vars.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/workflow_escape.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/variable_refs.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/variable_refs_included.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/dead_rules.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/new_rules_valid.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/new_rules_invalid.yml
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/samba/.gitlab-ci.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/samba/.gitlab-ci-coverage.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/samba/.gitlab-ci-private.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check --format json testdata/valid.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check --format sarif testdata/valid.yml
|
||||
@@ -104,15 +104,15 @@ tasks:
|
||||
- cmd: ./{{.BINARY}} check testdata/config_ignored/.gitlab-ci.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/config_severity/.gitlab-ci.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/config_suppress/.gitlab-ci.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/static_dead_rules.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/inherit_dead.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/inherit_dead_fields.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} check testdata/rules_needs_valid.yml
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/rules_needs_invalid.yml
|
||||
@@ -124,7 +124,7 @@ tasks:
|
||||
- cmd: ./{{.BINARY}} explain GL044
|
||||
ignore_error: false
|
||||
- cmd: ./{{.BINARY}} check testdata/insecure_remote_include.yml
|
||||
ignore_error: false
|
||||
ignore_error: true
|
||||
- cmd: ./{{.BINARY}} explain
|
||||
ignore_error: false
|
||||
|
||||
|
||||
+88
-17
@@ -66,7 +66,8 @@ const globalUsage = `glint: Lint and visualise GitLab CI pipelines locally.
|
||||
Usage: glint [OPTIONS] <COMMAND>
|
||||
|
||||
Commands:
|
||||
check Lint a pipeline file — exits 0 (clean) or 1 (errors found)
|
||||
check Lint a pipeline file — exits 0 (clean), 2 (errors), or 10 (warnings only)
|
||||
render Resolve all includes and extends into a single merged YAML file
|
||||
graph Visualise the pipeline as a job tree or Mermaid graph
|
||||
explain Show description and fix for a lint rule (e.g. glint explain GL007)
|
||||
lsp Start a Language Server Protocol server (stdin/stdout)
|
||||
@@ -87,6 +88,8 @@ func main() {
|
||||
switch os.Args[1] {
|
||||
case "check":
|
||||
cmdCheck(os.Args[2:])
|
||||
case "render":
|
||||
cmdRender(os.Args[2:])
|
||||
case "graph":
|
||||
cmdGraph(os.Args[2:])
|
||||
case "explain":
|
||||
@@ -121,6 +124,7 @@ func cmdCheck(args []string) {
|
||||
offline := fs.Bool("offline", false, "skip all network calls; serve only from --cache-dir")
|
||||
proxy := fs.String("proxy", "", "HTTP proxy URL for remote includes and GitLab API calls (e.g. http://proxy:8080); overrides system proxy env vars")
|
||||
format := fs.String("format", "text", "output format: text, json, sarif, junit, github")
|
||||
noWarn := fs.Bool("no-warn", false, "suppress warning findings; only errors are shown and affect the exit code")
|
||||
branch := fs.String("branch", "", "simulate a branch push (sets CI_COMMIT_BRANCH, …)")
|
||||
tag := fs.String("tag", "", "simulate a tag push (sets CI_COMMIT_TAG, …)")
|
||||
source := fs.String("source", "", "set CI_PIPELINE_SOURCE")
|
||||
@@ -137,7 +141,11 @@ func cmdCheck(args []string) {
|
||||
fmt.Fprint(os.Stderr, `Lint a GitLab CI pipeline file.
|
||||
|
||||
Resolves local includes and extends chains, then runs all lint rules.
|
||||
Exits 0 when no errors are found, 1 when at least one error is reported.
|
||||
|
||||
Exit codes:
|
||||
0 no findings (clean)
|
||||
2 one or more errors
|
||||
10 one or more warnings, no errors
|
||||
|
||||
Usage: glint check [OPTIONS] <PIPELINE>
|
||||
|
||||
@@ -149,6 +157,10 @@ Options:
|
||||
Output format for findings.
|
||||
[default: text] [possible values: text, json, sarif, junit, github]
|
||||
|
||||
--no-warn
|
||||
Suppress warning findings. Only errors are printed and counted toward
|
||||
the exit code; warnings are ignored entirely.
|
||||
|
||||
--token <TOKEN>
|
||||
GitLab personal access token. Required to fetch project: includes;
|
||||
component: includes are attempted unauthenticated.
|
||||
@@ -169,6 +181,12 @@ Options:
|
||||
having no token). Implies the default cache dir (~/.cache/glint) when
|
||||
--cache-dir is not set.
|
||||
|
||||
--proxy <URL>
|
||||
HTTP proxy URL for remote includes and GitLab API calls
|
||||
(e.g. http://proxy:8080). Overrides system proxy env vars
|
||||
(HTTP_PROXY / HTTPS_PROXY). Also configurable via proxy: in
|
||||
.glint.yml.
|
||||
|
||||
--branch <NAME>
|
||||
Simulate a branch push. Populates: CI_COMMIT_BRANCH,
|
||||
CI_COMMIT_REF_NAME, CI_COMMIT_REF_SLUG, CI_PIPELINE_SOURCE=push.
|
||||
@@ -232,10 +250,12 @@ Examples:
|
||||
glint check --branch main --var DEPLOY_ENV=production .gitlab-ci.yml
|
||||
glint check --cache-dir ~/.cache/glint .gitlab-ci.yml
|
||||
glint check --offline --cache-dir ~/.cache/glint .gitlab-ci.yml
|
||||
glint check --no-warn .gitlab-ci.yml
|
||||
glint check --changes src/main.go --changes Dockerfile .gitlab-ci.yml
|
||||
glint check --changes-from origin/main .gitlab-ci.yml
|
||||
glint check --context branch=main --context branch=develop .gitlab-ci.yml
|
||||
glint check --context branch=main --context tag=v1.0.0 --context source=schedule .gitlab-ci.yml
|
||||
glint check --proxy http://proxy.example.com:8080 .gitlab-ci.yml
|
||||
`)
|
||||
}
|
||||
_ = fs.Parse(args)
|
||||
@@ -402,7 +422,19 @@ Examples:
|
||||
|
||||
findings := linter.Lint(p, skipped)
|
||||
findings = applyConfig(findings, glintCfg, p.Suppressions)
|
||||
errCount, _ := countSeverities(findings)
|
||||
|
||||
// --no-warn: discard warnings before any output or exit-code calculation.
|
||||
if *noWarn {
|
||||
kept := findings[:0]
|
||||
for _, f := range findings {
|
||||
if f.Severity != linter.Warning {
|
||||
kept = append(kept, f)
|
||||
}
|
||||
}
|
||||
findings = kept
|
||||
}
|
||||
|
||||
errCount, warnCount := countSeverities(findings)
|
||||
|
||||
// In structured formats the summary line goes to stderr so stdout is clean.
|
||||
summaryOut := os.Stdout
|
||||
@@ -420,19 +452,27 @@ Examples:
|
||||
case "github":
|
||||
writeGitHub(os.Stdout, findings)
|
||||
default: // "text"
|
||||
for _, f := range findings {
|
||||
fmt.Println(f)
|
||||
}
|
||||
writeTextFindings(os.Stdout, findings)
|
||||
}
|
||||
|
||||
if len(findings) == 0 {
|
||||
fmt.Fprintf(summaryOut, "OK: %s — no issues found (%d job(s), %d stage(s))\n", path, len(p.Jobs), len(p.Stages))
|
||||
} else {
|
||||
fmt.Fprintf(summaryOut, "%d finding(s): %d error(s)\n", len(findings), errCount)
|
||||
switch {
|
||||
case errCount > 0 && warnCount > 0:
|
||||
fmt.Fprintf(summaryOut, "%d finding(s): %d error(s), %d warning(s)\n", len(findings), errCount, warnCount)
|
||||
case errCount > 0:
|
||||
fmt.Fprintf(summaryOut, "%d finding(s): %d error(s)\n", len(findings), errCount)
|
||||
default:
|
||||
fmt.Fprintf(summaryOut, "%d finding(s): %d warning(s)\n", len(findings), warnCount)
|
||||
}
|
||||
}
|
||||
|
||||
if errCount > 0 {
|
||||
exit(1)
|
||||
switch {
|
||||
case errCount > 0:
|
||||
exit(2)
|
||||
case warnCount > 0:
|
||||
exit(10)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,12 +498,12 @@ func cmdGraph(args []string) {
|
||||
format := fs.String("format", "svg", "pipeline output format: svg, mermaid, or html")
|
||||
fs.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "glint %s\n\n", version)
|
||||
fmt.Fprint(os.Stderr, `Visualise the pipeline as a job tree and/or Mermaid graph.
|
||||
fmt.Fprint(os.Stderr, `Visualise the pipeline as a job tree or graph.
|
||||
|
||||
Usage: glint graph [MODE] [OPTIONS] <PIPELINE>
|
||||
|
||||
Arguments:
|
||||
[MODE] Graph mode; must appear before options [default: tree+includes]
|
||||
[MODE] Graph mode; must appear before options [default: tree]
|
||||
[possible values: tree, includes, pipeline, all]
|
||||
<PIPELINE> Path to the .gitlab-ci.yml file
|
||||
|
||||
@@ -490,6 +530,22 @@ Options:
|
||||
GitLab instance URL.
|
||||
[env: CI_SERVER_URL | GITLAB_URL] [default: https://gitlab.com]
|
||||
|
||||
--cache-dir <DIR>
|
||||
Cache fetched remote templates (project: and component: includes) in
|
||||
DIR. The directory is created on first use. Subsequent runs read from
|
||||
cache first, avoiding repeated network calls.
|
||||
|
||||
--offline
|
||||
Do not make any network calls. All remote includes must already be
|
||||
present in --cache-dir; missing entries emit a warning. Implies the
|
||||
default cache dir (~/.cache/glint) when --cache-dir is not set.
|
||||
|
||||
--proxy <URL>
|
||||
HTTP proxy URL for remote includes and GitLab API calls
|
||||
(e.g. http://proxy:8080). Overrides system proxy env vars
|
||||
(HTTP_PROXY / HTTPS_PROXY). Also configurable via proxy: in
|
||||
.glint.yml.
|
||||
|
||||
--branch <NAME>
|
||||
Simulate a branch push. Jobs in tree output are annotated with their
|
||||
evaluated state ([skipped] or [manual]; no tag means active).
|
||||
@@ -515,6 +571,12 @@ Options:
|
||||
Run "git diff --name-only <REF>" to determine changed files for
|
||||
rules:changes: evaluation.
|
||||
|
||||
--no-skipped
|
||||
Omit jobs that would be skipped in the given context. Requires at
|
||||
least one context flag (--branch, --tag, --source, --var) or the
|
||||
implicit default context (branch=main). Skipped jobs are removed
|
||||
from the tree, SVG, HTML, and Mermaid output entirely.
|
||||
|
||||
--list-vars
|
||||
Print all pipeline-level variables collected from the root file and
|
||||
every included file (sorted KEY=VALUE) to stderr, then continue
|
||||
@@ -530,21 +592,24 @@ always evaluated.
|
||||
Examples:
|
||||
glint graph .gitlab-ci.yml
|
||||
glint graph tree .gitlab-ci.yml
|
||||
glint graph includes .gitlab-ci.yml > includes.mmd
|
||||
glint graph tree --branch develop .gitlab-ci.yml
|
||||
glint graph tree --tag v1.0.0 .gitlab-ci.yml
|
||||
glint graph tree --list-vars .gitlab-ci.yml
|
||||
glint graph tree --changes src/main.go .gitlab-ci.yml
|
||||
glint graph includes .gitlab-ci.yml > includes.mmd
|
||||
glint graph pipeline .gitlab-ci.yml
|
||||
glint graph pipeline --out /tmp/graphs .gitlab-ci.yml
|
||||
glint graph pipeline --format mermaid .gitlab-ci.yml
|
||||
glint graph pipeline --format html .gitlab-ci.yml
|
||||
glint graph tree --no-skipped --branch main .gitlab-ci.yml
|
||||
glint graph pipeline --no-skipped --branch develop .gitlab-ci.yml
|
||||
glint graph all .gitlab-ci.yml > includes.mmd
|
||||
`)
|
||||
}
|
||||
branch := fs.String("branch", "", "simulate a branch push (sets CI_COMMIT_BRANCH, …)")
|
||||
tag := fs.String("tag", "", "simulate a tag push (sets CI_COMMIT_TAG, …)")
|
||||
source := fs.String("source", "", "set CI_PIPELINE_SOURCE")
|
||||
noSkipped := fs.Bool("no-skipped", false, "hide jobs that would be skipped in the given context (requires a context)")
|
||||
listVars := fs.Bool("list-vars", false, "print all collected pipeline variables to stderr, then continue")
|
||||
var vars multiFlag
|
||||
fs.Var(&vars, "var", "set a CI variable as KEY=VALUE; repeatable")
|
||||
@@ -633,12 +698,18 @@ Examples:
|
||||
printVars(p, ctx)
|
||||
}
|
||||
|
||||
// --no-skipped: remove jobs that evaluate to skipped in the current context
|
||||
// before handing the pipeline to any graph function.
|
||||
if *noSkipped && !ctx.IsEmpty() {
|
||||
for name, job := range p.Jobs {
|
||||
if !strings.HasPrefix(name, ".") && cicontext.EvalJob(job, ctx) == cicontext.JobSkipped {
|
||||
delete(p.Jobs, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case "default":
|
||||
fmt.Print(graph.Tree(p, ctx))
|
||||
fmt.Println("---")
|
||||
fmt.Print(graph.Includes(path, p.Include, cfg))
|
||||
case "tree":
|
||||
case "default", "tree":
|
||||
fmt.Print(graph.Tree(p, ctx))
|
||||
case "includes":
|
||||
fmt.Print(graph.Includes(path, p.Include, cfg))
|
||||
|
||||
+22
-22
@@ -112,7 +112,7 @@ func TestCmdCheck_MissingFile(t *testing.T) {
|
||||
if *code != 2 { t.Errorf("missing file: want exit(2), got %d", *code) }
|
||||
}
|
||||
|
||||
func TestCmdCheck_WithErrors_ExitsOne(t *testing.T) {
|
||||
func TestCmdCheck_WithErrors_ExitsTwo(t *testing.T) {
|
||||
code := captureExit(t)
|
||||
// Pipeline with an error finding (invalid stage reference)
|
||||
content := `
|
||||
@@ -123,7 +123,7 @@ test-job:
|
||||
`
|
||||
path := writePipeline(t, content)
|
||||
cmdCheck([]string{path})
|
||||
if *code != 1 { t.Errorf("pipeline with errors: want exit(1), got %d", *code) }
|
||||
if *code != 2 { t.Errorf("pipeline with errors: want exit(2), got %d", *code) }
|
||||
}
|
||||
|
||||
func TestCmdCheck_FormatJSON(t *testing.T) {
|
||||
@@ -703,10 +703,10 @@ func TestCmdCheck_ChangesFrom_Fails(t *testing.T) {
|
||||
|
||||
code := captureExit(t)
|
||||
path := writePipeline(t, minimalPipeline)
|
||||
// Should warn but not crash; pipeline is clean → no exit(1).
|
||||
// Should warn but not crash; pipeline is clean → no exit(2).
|
||||
cmdCheck([]string{"--changes-from", "origin/main", path})
|
||||
if *code == 1 {
|
||||
t.Errorf("expected no exit(1) when --changes-from fails gracefully, got %d", *code)
|
||||
if *code == 2 {
|
||||
t.Errorf("expected no exit(2) when --changes-from fails gracefully, got %d", *code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -753,10 +753,10 @@ build-job:
|
||||
`
|
||||
path := writePipeline(t, content)
|
||||
// build-job's rule fires only if src/** matches; with 0 changed files it is skipped.
|
||||
// Pipeline is clean (no lint errors) → no exit(1).
|
||||
// Pipeline is clean (no lint errors) → no exit(2).
|
||||
cmdCheck([]string{"--changes-from", "origin/main", path})
|
||||
if *code == 1 {
|
||||
t.Errorf("unexpected exit(1): %d", *code)
|
||||
if *code == 2 {
|
||||
t.Errorf("unexpected exit(2): %d", *code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -770,8 +770,8 @@ func TestCmdGraph_ChangesFrom_Fails(t *testing.T) {
|
||||
code := captureExit(t)
|
||||
path := writePipeline(t, minimalPipeline)
|
||||
cmdGraph([]string{"tree", "--changes-from", "origin/main", path})
|
||||
if *code == 1 {
|
||||
t.Errorf("unexpected exit(1) when --changes-from fails in graph mode")
|
||||
if *code == 2 {
|
||||
t.Errorf("unexpected exit(2) when --changes-from fails in graph mode")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,8 +785,8 @@ func TestCmdGraph_ChangesFrom_Success(t *testing.T) {
|
||||
code := captureExit(t)
|
||||
path := writePipeline(t, minimalPipeline)
|
||||
cmdGraph([]string{"tree", "--changes-from", "origin/main", path})
|
||||
if *code == 1 {
|
||||
t.Errorf("unexpected exit(1) in graph --changes-from success path")
|
||||
if *code == 2 {
|
||||
t.Errorf("unexpected exit(2) in graph --changes-from success path")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -801,8 +801,8 @@ func TestCmdGraph_ChangesFrom_EmptyDiff(t *testing.T) {
|
||||
path := writePipeline(t, minimalPipeline)
|
||||
// reliable=true, allChanged nil → allChanged = []string{} branch hit
|
||||
cmdGraph([]string{"tree", "--changes-from", "origin/main", path})
|
||||
if *code == 1 {
|
||||
t.Errorf("unexpected exit(1) in graph --changes-from empty diff")
|
||||
if *code == 2 {
|
||||
t.Errorf("unexpected exit(2) in graph --changes-from empty diff")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -818,8 +818,8 @@ build-job:
|
||||
`
|
||||
path := writePipeline(t, content)
|
||||
cmdGraph([]string{"tree", "--changes", "src/app.go", path})
|
||||
if *code == 1 {
|
||||
t.Errorf("unexpected exit(1) with valid pipeline and --changes flag")
|
||||
if *code == 2 {
|
||||
t.Errorf("unexpected exit(2) with valid pipeline and --changes flag")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -848,7 +848,7 @@ deploy-job:
|
||||
// by rules evaluation → needs cross-check suppressed → exit 0.
|
||||
code := captureExit(t)
|
||||
cmdCheck([]string{"--branch", "main", path})
|
||||
if *code == 1 {
|
||||
if *code == 2 {
|
||||
t.Error("skipped job's needs: error should be suppressed in context-scoped lint")
|
||||
}
|
||||
}
|
||||
@@ -873,8 +873,8 @@ deploy-job:
|
||||
|
||||
code := captureExit(t)
|
||||
cmdCheck([]string{"--tag", "v1.0.0", path})
|
||||
if *code != 1 {
|
||||
t.Error("active job's bad needs: should still produce GL027 error")
|
||||
if *code != 2 {
|
||||
t.Error("active job's bad needs: should still produce GL027 error (exit 2)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -883,7 +883,7 @@ func TestCmdCheck_ContextScopedLinting_SkippedSet_IsNilWhenAllActive(t *testing.
|
||||
code := captureExit(t)
|
||||
path := writePipeline(t, minimalPipeline)
|
||||
cmdCheck([]string{"--branch", "main", path})
|
||||
if *code == 1 {
|
||||
if *code == 2 {
|
||||
t.Error("valid pipeline with all-active jobs should not produce errors")
|
||||
}
|
||||
}
|
||||
@@ -1142,8 +1142,8 @@ test-job:
|
||||
`
|
||||
path := writePipeline(t, content)
|
||||
cmdCheck([]string{"--context", "branch=main", path})
|
||||
if *code != 1 {
|
||||
t.Errorf("multi-context error pipeline: want exit(1), got %d", *code)
|
||||
if *code != 2 {
|
||||
t.Errorf("multi-context error pipeline: want exit(2), got %d", *code)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.k3nny.fr/glint/internal/linter"
|
||||
)
|
||||
|
||||
// ANSI escape sequences used for colorized output.
|
||||
const (
|
||||
ansiReset = "\033[0m"
|
||||
ansiBold = "\033[1m"
|
||||
ansiDim = "\033[2m"
|
||||
ansiRed = "\033[31m"
|
||||
ansiOrange = "\033[33m" // rendered as orange/amber in most terminals
|
||||
)
|
||||
|
||||
// colorEnabled reports whether ANSI color should be used when writing to w.
|
||||
// Colors are suppressed when NO_COLOR is set or when w is not a terminal.
|
||||
func colorEnabled(w io.Writer) bool {
|
||||
if os.Getenv("NO_COLOR") != "" {
|
||||
return false
|
||||
}
|
||||
f, ok := w.(*os.File)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
return err == nil && (fi.Mode()&os.ModeCharDevice) != 0
|
||||
}
|
||||
|
||||
// writeTextFindings prints findings in a columnized format with optional
|
||||
// ANSI color. All findings are scanned first to compute column widths so
|
||||
// that each field aligns across all output lines.
|
||||
//
|
||||
// Output columns (space-separated, no borders):
|
||||
//
|
||||
// location RULE severity message
|
||||
func writeTextFindings(w io.Writer, findings []linter.Finding) {
|
||||
if len(findings) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
color := colorEnabled(w)
|
||||
|
||||
// Pre-compute locations and maximum location width.
|
||||
locs := make([]string, len(findings))
|
||||
maxLoc := 0
|
||||
for i, f := range findings {
|
||||
locs[i] = findingLocation(f)
|
||||
if len(locs[i]) > maxLoc {
|
||||
maxLoc = len(locs[i])
|
||||
}
|
||||
}
|
||||
|
||||
// Rule IDs are always 5 chars (GL001–GL999).
|
||||
const ruleWidth = 5
|
||||
// Severity width: "warning" = 7 chars.
|
||||
const sevWidth = 7
|
||||
|
||||
for i, f := range findings {
|
||||
loc := locs[i]
|
||||
rule := f.Rule
|
||||
sev := strings.ToLower(string(f.Severity))
|
||||
|
||||
msg := f.Message
|
||||
if f.Job != "" {
|
||||
msg = fmt.Sprintf("job %q: %s", f.Job, msg)
|
||||
}
|
||||
|
||||
if color {
|
||||
var sevSeq string
|
||||
if f.Severity == linter.Error {
|
||||
sevSeq = ansiRed + ansiBold
|
||||
} else {
|
||||
sevSeq = ansiOrange + ansiBold
|
||||
}
|
||||
fmt.Fprintf(w, "%s%-*s%s %s%-*s%s %s%-*s%s %s\n",
|
||||
ansiDim, maxLoc, loc, ansiReset,
|
||||
ansiBold, ruleWidth, rule, ansiReset,
|
||||
sevSeq, sevWidth, sev, ansiReset,
|
||||
msg,
|
||||
)
|
||||
} else {
|
||||
fmt.Fprintf(w, "%-*s %-*s %-*s %s\n",
|
||||
maxLoc, loc,
|
||||
ruleWidth, rule,
|
||||
sevWidth, sev,
|
||||
msg,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// findingLocation formats the file:line:col location string for a finding.
|
||||
func findingLocation(f linter.Finding) string {
|
||||
if f.File == "" {
|
||||
return ""
|
||||
}
|
||||
switch {
|
||||
case f.Line > 0 && f.Column > 0:
|
||||
return fmt.Sprintf("%s:%d:%d", f.File, f.Line, f.Column)
|
||||
case f.Line > 0:
|
||||
return fmt.Sprintf("%s:%d", f.File, f.Line)
|
||||
default:
|
||||
return f.File
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.k3nny.fr/glint/internal/config"
|
||||
"git.k3nny.fr/glint/internal/fetcher"
|
||||
"git.k3nny.fr/glint/internal/model"
|
||||
"git.k3nny.fr/glint/internal/resolver"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func cmdRender(args []string) {
|
||||
fs := flag.NewFlagSet("glint render", flag.ExitOnError)
|
||||
output := fs.String("output", "", "output file path (default: rendered.gitlab-ci.yml; use - for stdout)")
|
||||
token := fs.String("token", "", "GitLab personal access token (overrides GITLAB_TOKEN)")
|
||||
gitlabURL := fs.String("gitlab-url", "", "GitLab instance URL (overrides CI_SERVER_URL / GITLAB_URL)")
|
||||
cacheDir := fs.String("cache-dir", "", "directory to cache fetched remote includes")
|
||||
offline := fs.Bool("offline", false, "skip all network calls; serve only from --cache-dir")
|
||||
proxy := fs.String("proxy", "", "HTTP proxy URL for remote includes (e.g. http://proxy:8080)")
|
||||
fs.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "glint %s\n\n", version)
|
||||
fmt.Fprint(os.Stderr, `Resolve all includes and extends into a single merged YAML file.
|
||||
|
||||
Performs the same include resolution and extends merging that GitLab CI
|
||||
does server-side, then writes the fully flattened pipeline to a single file.
|
||||
Useful for inspecting the resolved pipeline or running further local tooling.
|
||||
|
||||
The output file strips 'include:' (consumed by resolution) and 'extends:'
|
||||
(applied to each job) keys. All other fields are preserved verbatim.
|
||||
Template jobs (names starting with '.') are retained.
|
||||
|
||||
Usage: glint render [OPTIONS] <PIPELINE>
|
||||
|
||||
Arguments:
|
||||
<PIPELINE> Path to the .gitlab-ci.yml file to resolve
|
||||
|
||||
Options:
|
||||
--output <FILE>
|
||||
Write the rendered pipeline to FILE.
|
||||
Use '-' to write to stdout.
|
||||
[default: rendered.gitlab-ci.yml]
|
||||
|
||||
--token <TOKEN>
|
||||
GitLab personal access token for fetching project: and component:
|
||||
includes.
|
||||
[env: GITLAB_TOKEN | CI_JOB_TOKEN | GITLAB_PRIVATE_TOKEN]
|
||||
|
||||
--gitlab-url <URL>
|
||||
GitLab instance URL.
|
||||
[env: CI_SERVER_URL | GITLAB_URL] [default: https://gitlab.com]
|
||||
|
||||
--cache-dir <DIR>
|
||||
Cache directory for fetched remote includes.
|
||||
|
||||
--offline
|
||||
Do not make any network calls; use cache only.
|
||||
|
||||
--proxy <URL>
|
||||
HTTP proxy URL for remote includes and GitLab API calls.
|
||||
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
Examples:
|
||||
glint render .gitlab-ci.yml
|
||||
glint render --output merged.yml .gitlab-ci.yml
|
||||
glint render --output - .gitlab-ci.yml | yq .
|
||||
glint render --offline --cache-dir ~/.cache/glint .gitlab-ci.yml
|
||||
`)
|
||||
}
|
||||
_ = fs.Parse(args)
|
||||
|
||||
if fs.NArg() != 1 {
|
||||
fs.Usage()
|
||||
exit(2)
|
||||
return
|
||||
}
|
||||
path := fs.Arg(0)
|
||||
rootDir := filepath.Dir(filepath.Clean(path))
|
||||
|
||||
glintCfg, cfgErr := config.Load(rootDir)
|
||||
if cfgErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: [warning] %s: %v\n", path, config.Filename, cfgErr)
|
||||
}
|
||||
|
||||
fetcherToken := *token
|
||||
if fetcherToken == "" {
|
||||
fetcherToken = glintCfg.Token
|
||||
}
|
||||
fetcherURL := *gitlabURL
|
||||
if fetcherURL == "" {
|
||||
fetcherURL = glintCfg.URL
|
||||
}
|
||||
resolvedCacheDir := *cacheDir
|
||||
if resolvedCacheDir == "" {
|
||||
resolvedCacheDir = glintCfg.CacheDir
|
||||
}
|
||||
if *offline && resolvedCacheDir == "" {
|
||||
resolvedCacheDir = defaultCacheDir()
|
||||
}
|
||||
resolvedProxy := *proxy
|
||||
if resolvedProxy == "" {
|
||||
resolvedProxy = glintCfg.Proxy
|
||||
}
|
||||
|
||||
cfg := fetcher.AutoConfig().WithOverrides(fetcherURL, fetcherToken, resolvedCacheDir, *offline).WithProxy(resolvedProxy)
|
||||
|
||||
p, err := model.Parse(path)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||
exit(2)
|
||||
return
|
||||
}
|
||||
|
||||
warnings, _ := resolver.ResolveIncludes(p, cfg, rootDir)
|
||||
for _, w := range warnings {
|
||||
fmt.Fprintf(os.Stderr, "%s: [warning] include %s\n", path, w)
|
||||
}
|
||||
|
||||
extWarnings, err := resolver.Resolve(p)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: resolving extends: %v\n", err)
|
||||
exit(2)
|
||||
return
|
||||
}
|
||||
for _, w := range extWarnings {
|
||||
fmt.Fprintf(os.Stderr, "%s: [warning] job %q extends unknown job %q; extends chain skipped\n", path, w.Job, w.Base)
|
||||
}
|
||||
|
||||
doc, err := buildRenderDoc(p)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: building output: %v\n", err)
|
||||
exit(2)
|
||||
return
|
||||
}
|
||||
|
||||
outPath := *output
|
||||
if outPath == "" {
|
||||
outPath = "rendered.gitlab-ci.yml"
|
||||
}
|
||||
|
||||
var w interface{ Write([]byte) (int, error) }
|
||||
if outPath == "-" {
|
||||
w = os.Stdout
|
||||
} else {
|
||||
f, err := os.Create(outPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: creating output file: %v\n", err)
|
||||
exit(2)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
w = f
|
||||
}
|
||||
|
||||
enc := yaml.NewEncoder(w)
|
||||
enc.SetIndent(2)
|
||||
if err := enc.Encode(doc); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: writing output: %v\n", err)
|
||||
exit(2)
|
||||
return
|
||||
}
|
||||
_ = enc.Close()
|
||||
|
||||
if outPath != "-" {
|
||||
jobCount := 0
|
||||
for name := range p.Jobs {
|
||||
if !strings.HasPrefix(name, ".") {
|
||||
jobCount++
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "rendered: %s (%d job(s), %d stage(s))\n", outPath, jobCount, len(p.Stages))
|
||||
}
|
||||
}
|
||||
|
||||
// buildRenderDoc constructs an ordered yaml.Node document from the resolved
|
||||
// pipeline. Pipeline-level keys (stages, variables, default, workflow) come
|
||||
// first, followed by template jobs (.name) then regular jobs, both sorted
|
||||
// alphabetically. 'include:' and 'extends:' are omitted — they have been
|
||||
// consumed by the resolution passes.
|
||||
func buildRenderDoc(p *model.Pipeline) (*yaml.Node, error) {
|
||||
root := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
|
||||
addField := func(key string, val any) error {
|
||||
n, err := anyToNode(val)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encoding %q: %w", key, err)
|
||||
}
|
||||
root.Content = append(root.Content,
|
||||
&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key},
|
||||
n,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(p.Stages) > 0 {
|
||||
if err := addField("stages", p.Stages); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if len(p.Variables) > 0 {
|
||||
if err := addField("variables", p.Variables); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if p.Default != nil {
|
||||
if err := addField("default", p.Default); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if p.Workflow != nil {
|
||||
if err := addField("workflow", p.Workflow); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Collect and sort job names: template jobs first, then regular jobs.
|
||||
var templates, regular []string
|
||||
for name := range p.RawJobs {
|
||||
if strings.HasPrefix(name, ".") {
|
||||
templates = append(templates, name)
|
||||
} else {
|
||||
regular = append(regular, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(templates)
|
||||
sort.Strings(regular)
|
||||
|
||||
for _, name := range append(templates, regular...) {
|
||||
raw := p.RawJobs[name]
|
||||
// Copy to avoid mutating the shared map; strip resolution-consumed keys.
|
||||
cleaned := make(map[string]any, len(raw))
|
||||
for k, v := range raw {
|
||||
if k == "extends" {
|
||||
continue
|
||||
}
|
||||
cleaned[k] = v
|
||||
}
|
||||
if err := addField(name, cleaned); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
doc := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// anyToNode converts an arbitrary Go value to a *yaml.Node by round-tripping
|
||||
// through yaml.Marshal / yaml.Unmarshal, which preserves all value types.
|
||||
func anyToNode(v any) (*yaml.Node, error) {
|
||||
data, err := yaml.Marshal(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var doc yaml.Node
|
||||
if err := yaml.Unmarshal(data, &doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if doc.Kind == yaml.DocumentNode && len(doc.Content) > 0 {
|
||||
return doc.Content[0], nil
|
||||
}
|
||||
return &doc, nil
|
||||
}
|
||||
@@ -103,6 +103,9 @@ func TestLoad_StopsAtGitRoot(t *testing.T) {
|
||||
// TestLoad_ReadError covers the !os.IsNotExist(err) branch (config.go:59-61)
|
||||
// when the file exists but is not readable.
|
||||
func TestLoad_ReadError(t *testing.T) {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("skipping: root bypasses file permission checks")
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
cfgPath := filepath.Join(tmp, Filename)
|
||||
if err := os.WriteFile(cfgPath, []byte("ignore: []"), 0o000); err != nil {
|
||||
|
||||
@@ -30,6 +30,7 @@ func checkDependencies(p *model.Pipeline, skipped map[string]bool) []Finding {
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: fmt.Sprintf("'dependencies' references unknown job %q", dep),
|
||||
})
|
||||
continue
|
||||
@@ -43,6 +44,7 @@ func checkDependencies(p *model.Pipeline, skipped map[string]bool) []Finding {
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: fmt.Sprintf("'dependencies' job %q must be in an earlier stage (in %q, current job is in %q)", dep, depJob.Stage, job.Stage),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@ func evalRulesReachability(name string, job model.Job, jobVars map[string]string
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: "rules: block can never activate: all if: conditions evaluate to false given the declared pipeline variables",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ func checkJobInheritCompleteness(p *model.Pipeline, name string, job model.Job)
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: "'inherit: default:' is declared but the pipeline has no 'default:' block — declaration has no effect",
|
||||
}}
|
||||
}
|
||||
@@ -70,6 +71,7 @@ func checkJobInheritCompleteness(p *model.Pipeline, name string, job model.Job)
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: fmt.Sprintf(
|
||||
"'inherit: default: [%s]': %s not defined in the 'default:' block — %s",
|
||||
strings.Join(dead, ", "),
|
||||
|
||||
@@ -22,15 +22,19 @@ type Finding struct {
|
||||
Job string // empty for pipeline-level findings
|
||||
File string // source file where the finding originates
|
||||
Line int // line number in File (0 = unknown)
|
||||
Column int // column number in File (0 = unknown; 1-indexed)
|
||||
Message string
|
||||
}
|
||||
|
||||
func (f Finding) String() string {
|
||||
var loc string
|
||||
if f.File != "" {
|
||||
if f.Line > 0 {
|
||||
switch {
|
||||
case f.Line > 0 && f.Column > 0:
|
||||
loc = fmt.Sprintf("%s:%d:%d: ", f.File, f.Line, f.Column)
|
||||
case f.Line > 0:
|
||||
loc = fmt.Sprintf("%s:%d: ", f.File, f.Line)
|
||||
} else {
|
||||
default:
|
||||
loc = fmt.Sprintf("%s: ", f.File)
|
||||
}
|
||||
}
|
||||
@@ -225,6 +229,7 @@ func checkJob(name string, job model.Job, stageSet map[string]bool) []Finding {
|
||||
if findings[i].Job != "" && findings[i].File == "" {
|
||||
findings[i].File = job.File
|
||||
findings[i].Line = job.Line
|
||||
findings[i].Column = job.Column
|
||||
}
|
||||
}
|
||||
return findings
|
||||
|
||||
@@ -53,6 +53,7 @@ func checkNeeds(p *model.Pipeline, skipped map[string]bool) []Finding {
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: fmt.Sprintf("needs unknown job %q", entry.job),
|
||||
})
|
||||
continue
|
||||
@@ -71,6 +72,7 @@ func checkNeeds(p *model.Pipeline, skipped map[string]bool) []Finding {
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: fmt.Sprintf(
|
||||
"needs %q which is in a later stage (%q after %q)",
|
||||
entry.job, neededJob.Stage, job.Stage,
|
||||
@@ -111,6 +113,7 @@ func checkRulesNeeds(p *model.Pipeline, skipped map[string]bool) []Finding {
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: fmt.Sprintf(
|
||||
"rules[%d].needs: references unknown job %q",
|
||||
i, entry.job,
|
||||
@@ -171,6 +174,7 @@ func detectNeedsCycles(graph map[string][]string, jobs map[string]model.Job) []F
|
||||
Job: name,
|
||||
File: j.File,
|
||||
Line: j.Line,
|
||||
Column: j.Column,
|
||||
Message: fmt.Sprintf("circular dependency in needs: %v → %s", path, name),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -148,6 +148,7 @@ func checkVariableRefs(p *model.Pipeline) []Finding {
|
||||
Job: name,
|
||||
File: job.File,
|
||||
Line: job.Line,
|
||||
Column: job.Column,
|
||||
Message: fmt.Sprintf("rules[%d].if: $%s is not declared in pipeline or job variables:", i, varName),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -83,7 +83,8 @@ func ParseBytes(data []byte) (*Pipeline, error) {
|
||||
return nil, fmt.Errorf("parsing job %q: %w", key, err)
|
||||
}
|
||||
j.Name = key
|
||||
j.Line = keyNode.Line // exact line of the job name key
|
||||
j.Line = keyNode.Line // exact line of the job name key
|
||||
j.Column = keyNode.Column // exact column of the job name key
|
||||
p.Jobs[key] = j
|
||||
}
|
||||
|
||||
|
||||
@@ -45,9 +45,10 @@ type Workflow struct {
|
||||
}
|
||||
|
||||
type Job struct {
|
||||
Name string // set by parser, not from YAML
|
||||
File string // source file; set by Parse / resolver
|
||||
Line int // line of the job key in its source file; set by parser
|
||||
Name string // set by parser, not from YAML
|
||||
File string // source file; set by Parse / resolver
|
||||
Line int // line of the job key in its source file; set by parser
|
||||
Column int // column of the job key (1-indexed); set by parser
|
||||
Stage string `yaml:"stage"`
|
||||
Script any `yaml:"script"` // []string or string (block scalar)
|
||||
Run any `yaml:"run"` // alternative to script (CI steps)
|
||||
|
||||
@@ -80,12 +80,15 @@ func Resolve(p *model.Pipeline) ([]ExtendWarning, error) {
|
||||
return extWarnings, fmt.Errorf("job %q: re-decoding merged definition: %w", name, err)
|
||||
}
|
||||
j.Name = name
|
||||
// Preserve source location — File/Line are not part of the YAML map
|
||||
// Preserve source location — these fields are not part of the YAML map
|
||||
// and are lost during the encode/decode round-trip.
|
||||
orig := p.Jobs[name]
|
||||
j.File = orig.File
|
||||
j.Line = orig.Line
|
||||
j.Column = orig.Column
|
||||
p.Jobs[name] = j
|
||||
// Write merged raw map back so p.RawJobs always reflects post-extends state.
|
||||
p.RawJobs[name] = merged
|
||||
}
|
||||
|
||||
return extWarnings, nil
|
||||
|
||||
Reference in New Issue
Block a user