Merged
feat: scripts/bg, CLI voor agents (pipelines, MRs, issues, branches, releases, bestanden)
timfa
wants to merge
1 commit
from
cursor/bg-script
into
stage
Overview Commits 1 Pipelines 3 Changes 3
scripts/bg (bash + curl + jq). Subcommandos: pipeline status|wait|logs|retry|list, mr list|show|create|merge|comment, issue list|show|create|comment|close|reopen, branch create, release create, file get. Token optioneel (publieke reads), nooit geprint.
pipeline wait: wacht tot er een pipeline is voor de selectie (--sha, --mr, --branch, --id), daarna tot hij klaar is. Exit 0 success, 1 failed of canceled (met het einde van de log van elke mislukte job), 2 timeout. allow_failure-jobs die faalden worden een waarschuwing.
Hangt voor --sha/--mr en de MR-filters af van !40. Docs: docs/agents.md. Tests: scripts/bg_test.go met een nep-API (exitcodes, logs, waarschuwing, token niet in de output).
Activity
- timfa Pipeline #164 is Canceled 24 October 2026
- timfa opened this merge request 24 October 2026
- timfa Pipeline #168 is Passed 24 October 2026
- timfa Pipeline #170 is Passed 24 October 2026
-
timfa
pushed
24 October 2026
feat: scripts/bg, een kleine CLI voor agents, met docs/agents.md Merge branch 'cursor/api-agents' into 'stage' fix(api): release aanmaken op privé repo geeft niet-leden 404 feat(api): pipelines filteren op sha/ref/mr, MR's op branch en status, anoniem lezen van publieke projecten
- timfa merged this merge request 24 October 2026
Commits
Pipelines
Changes
@@ -0,0 +1,90 @@
# BlueGit voor agents en scripts
`scripts/bg` is een kleine CLI op de BlueGit-API. Hij heeft alleen `bash`, `curl` en `jq` nodig.
```sh
export BLUEGIT_URL=https://git.timfalken.com # standaard
export BLUEGIT_TOKEN=... # optioneel, nooit printen
scripts/bg help
```
## Rechten
- **Publieke projecten** zijn zonder token leesbaar, net als in de UI. Dat geldt voor status, pipelines, jobs, logs, MR's, issues, bestanden en releases.
- **Privé projecten**, en projecten in een privé groep, geven `404` zonder token of als je geen lid bent. Je ziet dus ook niet of zo'n project bestaat.
- **Schrijven** (MR, notitie, issue, branch, release, retry) vraagt altijd een token, met de rol die de UI ook vraagt. Zonder token krijg je `401`, met te weinig rechten `403`.
- **Een token** werkt met de rechten van de eigenaar, beperkt door de scopes van het token (`read_api`, `api`, …).
`bg` zet fouten op stderr met de HTTP-code en eindigt met exit 1. Een 404 kan dus ook "geen toegang" betekenen.
## Pipelines
```sh
bg pipeline status timfa/bluegit --branch stage # nieuwste pipeline op een branch
bg pipeline status timfa/bluegit --sha 3e6b2f1 # op commit (prefix van 7+ tekens)
bg pipeline status timfa/bluegit --mr 40 # van MR 40 (incl. pushes naar de bronbranch)
bg pipeline status timfa/bluegit --id 158
bg pipeline wait timfa/bluegit --sha "$(git rev-parse HEAD)" --timeout 1200 --interval 10
bg pipeline logs timfa/bluegit 158 611
bg pipeline retry timfa/bluegit 158 # alleen mislukte jobs (+ wat daarop wachtte)
bg pipeline retry timfa/bluegit 158 --all # nieuwe pipeline
```
`wait` wacht eerst tot er voor de selectie een pipeline is (handig direct na een push) en daarna tot die klaar is. De exitcodes:
| exit | betekenis |
|---|---|
| 0 | success |
| 1 | failed of canceled; de laatste 80 regels van elke mislukte job staan op stderr (`BG_LOG_LINES` om aan te passen) |
| 2 | timeout |
Jobs met `allow_failure` die faalden geven een waarschuwing, maar het blijft exit 0.
Typisch voor een cloud-agent na een push:
```sh
git push bluegit HEAD:refs/heads/mijn-branch
sha=$(git rev-parse HEAD)
if scripts/bg pipeline wait timfa/bluegit --sha "$sha" --timeout 1800; then
echo groen
else
echo "rood of timeout ($?)"; exit 1
fi
```
## Merge requests
```sh
bg mr list timfa/bluegit # open
bg mr list timfa/bluegit --state all --source mijn-branch
bg mr create timfa/bluegit --source mijn-branch --target stage --title "fix: ..." --description "..."
bg mr show timfa/bluegit 40
bg mr comment timfa/bluegit 40 "Ziet er goed uit"
bg mr merge timfa/bluegit 40 # verwijdert de bronbranch; --keep-source om te houden
```
## Issues, branches, releases, bestanden
```sh
bg issue list timfa/bluegit [open|closed|all]
bg issue create timfa/bluegit "Titel" "Beschrijving"
bg issue comment timfa/bluegit 7 "Opgelost in !40"
bg issue close timfa/bluegit 7
bg branch create timfa/bluegit mijn-branch --from stage
bg release create timfa/bluegit v1.2.0 --commit <sha> --asset build:bluegit:bluegit-linux-amd64
bg file get timfa/bluegit README.md --ref stage
```
Een release-asset komt uit een artifact van een job in dezelfde repo (`JOB:PAD[:NAAM]`). Een los bestand uploaden kan de API nog niet.
## Ruwe API
De CLI is dun. Alles staat ook in `/api/v1/openapi.json`. Handige filters:
- `GET /api/v1/projects/{owner}/{repo}/pipelines?sha=…|ref=…|mr=…`
- `GET /api/v1/projects/{owner}/{repo}/merge_requests?state=open|merged|closed|all&source_branch=…&target_branch=…`
- `GET /api/v1/projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/log`
Owner en repo zijn twee padsegmenten (`timfa/bluegit`), niet urlencoded.
@@ -0,0 +1,90 @@# BlueGit voor agents en scripts`scripts/bg` is een kleine CLI op de BlueGit-API. Hij heeft alleen `bash`, `curl` en `jq` nodig.```shexport BLUEGIT_URL=https://git.timfalken.com # standaardexport BLUEGIT_TOKEN=... # optioneel, nooit printenscripts/bg help```## Rechten- **Publieke projecten** zijn zonder token leesbaar, net als in de UI. Dat geldt voor status, pipelines, jobs, logs, MR's, issues, bestanden en releases.- **Privé projecten**, en projecten in een privé groep, geven `404` zonder token of als je geen lid bent. Je ziet dus ook niet of zo'n project bestaat.- **Schrijven** (MR, notitie, issue, branch, release, retry) vraagt altijd een token, met de rol die de UI ook vraagt. Zonder token krijg je `401`, met te weinig rechten `403`.- **Een token** werkt met de rechten van de eigenaar, beperkt door de scopes van het token (`read_api`, `api`, …).`bg` zet fouten op stderr met de HTTP-code en eindigt met exit 1. Een 404 kan dus ook "geen toegang" betekenen.## Pipelines```shbg pipeline status timfa/bluegit --branch stage # nieuwste pipeline op een branchbg pipeline status timfa/bluegit --sha 3e6b2f1 # op commit (prefix van 7+ tekens)bg pipeline status timfa/bluegit --mr 40 # van MR 40 (incl. pushes naar de bronbranch)bg pipeline status timfa/bluegit --id 158bg pipeline wait timfa/bluegit --sha "$(git rev-parse HEAD)" --timeout 1200 --interval 10bg pipeline logs timfa/bluegit 158 611bg pipeline retry timfa/bluegit 158 # alleen mislukte jobs (+ wat daarop wachtte)bg pipeline retry timfa/bluegit 158 --all # nieuwe pipeline````wait` wacht eerst tot er voor de selectie een pipeline is (handig direct na een push) en daarna tot die klaar is. De exitcodes:| exit | betekenis ||---|---|| 0 | success || 1 | failed of canceled; de laatste 80 regels van elke mislukte job staan op stderr (`BG_LOG_LINES` om aan te passen) || 2 | timeout |Jobs met `allow_failure` die faalden geven een waarschuwing, maar het blijft exit 0.Typisch voor een cloud-agent na een push:```shgit push bluegit HEAD:refs/heads/mijn-branchsha=$(git rev-parse HEAD)if scripts/bg pipeline wait timfa/bluegit --sha "$sha" --timeout 1800; then echo groenelse echo "rood of timeout ($?)"; exit 1fi```## Merge requests```shbg mr list timfa/bluegit # openbg mr list timfa/bluegit --state all --source mijn-branchbg mr create timfa/bluegit --source mijn-branch --target stage --title "fix: ..." --description "..."bg mr show timfa/bluegit 40bg mr comment timfa/bluegit 40 "Ziet er goed uit"bg mr merge timfa/bluegit 40 # verwijdert de bronbranch; --keep-source om te houden```## Issues, branches, releases, bestanden```shbg issue list timfa/bluegit [open|closed|all]bg issue create timfa/bluegit "Titel" "Beschrijving"bg issue comment timfa/bluegit 7 "Opgelost in !40"bg issue close timfa/bluegit 7bg branch create timfa/bluegit mijn-branch --from stagebg release create timfa/bluegit v1.2.0 --commit <sha> --asset build:bluegit:bluegit-linux-amd64bg file get timfa/bluegit README.md --ref stage```Een release-asset komt uit een artifact van een job in dezelfde repo (`JOB:PAD[:NAAM]`). Een los bestand uploaden kan de API nog niet.## Ruwe APIDe CLI is dun. Alles staat ook in `/api/v1/openapi.json`. Handige filters:- `GET /api/v1/projects/{owner}/{repo}/pipelines?sha=…|ref=…|mr=…`- `GET /api/v1/projects/{owner}/{repo}/merge_requests?state=open|merged|closed|all&source_branch=…&target_branch=…`- `GET /api/v1/projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/log`Owner en repo zijn twee padsegmenten (`timfa/bluegit`), niet urlencoded.@@ -0,0 +1,208 @@
#!/usr/bin/env bash
# bg: kleine BlueGit-CLI voor mensen en agents. Alleen bash, curl en jq.
#
# BLUEGIT_URL standaard https://git.timfalken.com
# BLUEGIT_TOKEN optioneel; nodig voor schrijven en voor privé projecten.
# Wordt nooit geprint.
#
# Zie docs/agents.md of `bg help`.
set -euo pipefail
BASE="${BLUEGIT_URL:-https://git.timfalken.com}"
BASE="${BASE%/}"
API="$BASE/api/v1"
die() { echo "bg: $*" >&2; exit 64; }
command -v curl >/dev/null || die "curl ontbreekt"
command -v jq >/dev/null || die "jq ontbreekt"
# req METHOD PATH [JSON] -> body op stdout; bij HTTP >= 400 de fout op stderr en exit 1.
req() {
local method=$1 path=$2 data=${3:-} out code
local args=(-sS -X "$method" -w '\n%{http_code}' -H "Accept: application/json")
[[ -n "${BLUEGIT_TOKEN:-}" ]] && args+=(-H "Authorization: Bearer ${BLUEGIT_TOKEN}")
[[ -n "$data" ]] && args+=(-H "Content-Type: application/json" --data-binary "$data")
out=$(curl "${args[@]}" "$API$path") || { echo "bg: verbinding mislukt: $method $path" >&2; return 1; }
code=${out##*$'\n'}
out=${out%$'\n'*}
if (( code >= 400 )); then
local msg
msg=$(printf '%s' "$out" | jq -r '.message // .error // empty' 2>/dev/null || true)
echo "bg: HTTP $code bij $method $path${msg:+: $msg}" >&2
[[ $code == 404 ]] && echo "bg: (bestaat niet, of je hebt geen toegang)" >&2
return 1
fi
printf '%s' "$out"
}
get() { req GET "$1"; }
enc() { jq -rn --arg v "$1" '$v|@uri'; }
proj() { [[ "$1" == */* ]] || die "project moet owner/repo zijn: $1"; echo "/projects/$1"; }
issues() { echo "/repos/$1/issues"; }
json() { jq -cn "$@"; }
# ---------- pipelines ----------
# select_pipeline PROJECT ARGS... -> pipeline-JSON (of leeg als er nog geen is)
select_query() {
local q=""
while (($#)); do
case $1 in
--sha) q="sha=$2"; shift 2 ;;
--mr) q="mr=$2"; shift 2 ;;
--branch|--ref) q="ref=$(enc "$2")"; shift 2 ;;
--id) q="id=$2"; shift 2 ;;
--timeout|--interval) shift 2 ;;
*) die "onbekende optie: $1" ;;
esac
done
echo "$q"
}
find_pipeline() {
local p=$1 q=$2
if [[ $q == id=* ]]; then get "$(proj "$p")/pipelines/${q#id=}"; return; fi
get "$(proj "$p")/pipelines?per_page=1${q:+&$q}" | jq -c '.[0] // empty'
}
show_pipeline() {
local p=$1 pipe=$2
jq -r '"pipeline #\(.id) \(.status) \(.ref|sub("^refs/heads/";"")) \(.sha[0:8]) \(.web_url)"' <<<"$pipe"
get "$(proj "$p")/pipelines/$(jq -r .id <<<"$pipe")/jobs" |
jq -r '.[] | " \(.id)\t\(.status)\t\(.stage)/\(.name)\(if .allow_failure then " (allow_failure)" else "" end)"'
}
failed_logs() {
local p=$1 id=$2 jobs
jobs=$(get "$(proj "$p")/pipelines/$id/jobs")
jq -r '.[]|select(.status=="failed" and .allow_failure)|"bg: waarschuwing: \(.name) (#\(.id)) faalde (allow_failure)"' <<<"$jobs" >&2
for j in $(jq -r '.[]|select(.status=="failed" and (.allow_failure|not))|.id' <<<"$jobs"); do
echo "----- log job $j (laatste ${BG_LOG_LINES:-80} regels) -----" >&2
get "$(proj "$p")/pipelines/$id/jobs/$j/log" | tail -n "${BG_LOG_LINES:-80}" >&2 || true
done
}
cmd_pipeline() {
local sub=${1:-}; shift || true
case $sub in
status)
local p=${1:?project}; shift
local q pipe; q=$(select_query "$@")
pipe=$(find_pipeline "$p" "$q")
[[ -n "$pipe" ]] || { echo "geen pipeline gevonden" >&2; exit 3; }
show_pipeline "$p" "$pipe" ;;
wait)
local p=${1:?project}; shift
local timeout=1800 interval=10 a=("$@")
while (($#)); do case $1 in --timeout) timeout=$2; shift 2 ;; --interval) interval=$2; shift 2 ;; *) shift ;; esac; done
local q pipe status start=$SECONDS last=""
q=$(select_query "${a[@]}")
while :; do
pipe=$(find_pipeline "$p" "$q" || true)
status=$(jq -r '.status // empty' <<<"${pipe:-{\}}")
if [[ -n "$status" && "$status" != "$last" ]]; then
echo "pipeline #$(jq -r .id <<<"$pipe"): $status" >&2; last=$status
fi
case $status in
success) show_pipeline "$p" "$pipe"; failed_logs "$p" "$(jq -r .id <<<"$pipe")" 2>&1 | grep '^bg: waarschuwing' >&2 || true; exit 0 ;;
failed|canceled) show_pipeline "$p" "$pipe"; failed_logs "$p" "$(jq -r .id <<<"$pipe")"; exit 1 ;;
esac
(( SECONDS - start >= timeout )) && { echo "bg: timeout na ${timeout}s (status ${status:-geen pipeline})" >&2; exit 2; }
sleep "$interval"
done ;;
logs) get "$(proj "${1:?project}")/pipelines/${2:?pipeline-id}/jobs/${3:?job-id}/log" ;;
retry)
local mode=failed
[[ ${3:-} == --all ]] && mode=all
req POST "$(proj "${1:?project}")/pipelines/${2:?pipeline-id}/retry" "$(json --arg m "$mode" '{mode:$m}')" | jq -r '"pipeline #\(.id) \(.status) \(.web_url)"' ;;
list) get "$(proj "${1:?project}")/pipelines?per_page=${2:-10}" | jq -r '.[]|"\(.id)\t\(.status)\t\(.ref|sub("^refs/heads/";""))\t\(.sha[0:8])"' ;;
*) die "pipeline status|wait|logs|retry|list" ;;
esac
}
# ---------- merge requests ----------
cmd_mr() {
local sub=${1:-}; shift || true
case $sub in
list)
local p=${1:?project}; shift; local q="state=open"
while (($#)); do case $1 in --state) q="state=$2"; shift 2 ;; --source) q+="&source_branch=$(enc "$2")"; shift 2 ;; --target) q+="&target_branch=$(enc "$2")"; shift 2 ;; *) die "onbekende optie $1" ;; esac; done
get "$(proj "$p")/merge_requests?per_page=100&$q" | jq -r '.[]|"!\(.iid)\t\(.state)\t\(.source_branch) -> \(.target_branch)\t\(.title)"' ;;
show) get "$(proj "${1:?project}")/merge_requests/${2:?nummer}" | jq . ;;
create)
local p=${1:?project}; shift; local src="" tgt="" title="" desc="" remove=true
while (($#)); do case $1 in --source) src=$2; shift 2 ;; --target) tgt=$2; shift 2 ;; --title) title=$2; shift 2 ;; --description) desc=$2; shift 2 ;; --keep-source) remove=false; shift ;; *) die "onbekende optie $1" ;; esac; done
[[ -n $src && -n $tgt && -n $title ]] || die "mr create PROJECT --source B --target B --title T [--description D] [--keep-source]"
req POST "$(proj "$p")/merge_requests" "$(json --arg s "$src" --arg t "$tgt" --arg ti "$title" --arg d "$desc" --argjson r "$remove" '{source_branch:$s,target_branch:$t,title:$ti,description:$d,remove_source_branch:$r}')" | jq -r '"!\(.iid) \(.web_url)"' ;;
merge)
local remove=true; [[ ${3:-} == --keep-source ]] && remove=false
req POST "$(proj "${1:?project}")/merge_requests/${2:?nummer}/merge" "$(json --argjson r "$remove" '{remove_source_branch:$r}')" | jq -r '"\(.state) \(.web_url)"' ;;
comment) req POST "$(proj "${1:?project}")/merge_requests/${2:?nummer}/notes" "$(json --arg b "${3:?tekst}" '{body:$b}')" | jq -r '"notitie \(.id)"' ;;
*) die "mr list|show|create|merge|comment" ;;
esac
}
# ---------- issues ----------
cmd_issue() {
local sub=${1:-}; shift || true
case $sub in
list) get "$(issues "${1:?project}")?state=${2:-open}" | jq -r '.issues[]|"#\(.id)\t\(.status)\t\(.title)"' ;;
show) get "$(issues "${1:?project}")/${2:?nummer}" | jq . ;;
create) req POST "$(issues "${1:?project}")" "$(json --arg t "${2:?titel}" --arg d "${3:-}" '{title:$t,description:$d}')" | jq -r '"#\(.id) \(.web_url)"' ;;
comment) req POST "$(issues "${1:?project}")/${2:?nummer}/notes" "$(json --arg b "${3:?tekst}" '{body:$b}')" >/dev/null && echo "ok" ;;
close|reopen)
local st=closed; [[ $sub == reopen ]] && st=open
req PUT "$(issues "${1:?project}")/${2:?nummer}" "$(json --arg s "$st" '{state:$s}')" | jq -r '"#\(.id) \(.status)"' ;;
*) die "issue list|show|create|comment|close|reopen" ;;
esac
}
# ---------- overig ----------
cmd_branch() {
[[ ${1:-} == create ]] || die "branch create PROJECT NAAM [--from REF]"
local p=${2:?project} name=${3:?naam} from=""
[[ ${4:-} == --from ]] && from=${5:?ref}
req POST "$(proj "$p")/repository/branches" "$(json --arg n "$name" --arg f "$from" '{name:$n} + (if $f=="" then {} else {from:$f} end)')" | jq -r '.name // .'
}
cmd_release() {
[[ ${1:-} == create ]] || die "release create PROJECT TAG [--commit SHA] [--name N] [--body B] [--asset JOB:PAD[:NAAM]]..."
local p=${2:?project} tag=${3:?tag}; shift 3
local commit="" name="" body="" assets="[]"
while (($#)); do case $1 in
--commit) commit=$2; shift 2 ;; --name) name=$2; shift 2 ;; --body) body=$2; shift 2 ;;
--asset) IFS=: read -r j pth nm <<<"$2"; assets=$(jq -c --arg j "$j" --arg p "$pth" --arg n "${nm:-}" '. + [{job:$j,path:$p} + (if $n=="" then {} else {name:$n} end)]' <<<"$assets"); shift 2 ;;
*) die "onbekende optie $1" ;; esac; done
req POST "$(proj "$p")/releases" "$(json --arg t "$tag" --arg c "$commit" --arg n "$name" --arg b "$body" --argjson a "$assets" '{tag:$t,commit:$c,name:$n,body:$b,assets:$a}')" | jq -c .
}
cmd_file() {
[[ ${1:-} == get ]] || die "file get PROJECT PAD [--ref REF]"
local p=${2:?project} path=${3:?pad} ref=""
[[ ${4:-} == --ref ]] && ref="?ref=$(enc "${5:?ref}")"
local body; body=$(get "$(proj "$p")/repository/files/$(enc "$path")$ref")
if jq -e '.content and .encoding=="base64"' <<<"$body" >/dev/null 2>&1; then jq -r .content <<<"$body" | base64 -d
elif jq -e '.content' <<<"$body" >/dev/null 2>&1; then jq -r .content <<<"$body"
else printf '%s' "$body"; fi
}
usage() {
sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'
cat <<'U'
bg pipeline status PROJECT [--sha X | --mr N | --branch B | --id P]
bg pipeline wait PROJECT [selectie] [--timeout 1800] [--interval 10] exit 0 ok, 1 mislukt, 2 timeout
bg pipeline logs PROJECT PIPELINE JOB
bg pipeline retry PROJECT PIPELINE [--all]
bg pipeline list PROJECT [N]
bg mr list|show|create|merge|comment ...
bg issue list|show|create|comment|close|reopen ...
bg branch create PROJECT NAAM [--from REF]
bg release create PROJECT TAG [--commit SHA] [--asset JOB:PAD[:NAAM]]
bg file get PROJECT PAD [--ref REF]
U
}
case ${1:-help} in
pipeline|pl) shift; cmd_pipeline "$@" ;;
mr) shift; cmd_mr "$@" ;;
issue) shift; cmd_issue "$@" ;;
branch) shift; cmd_branch "$@" ;;
release) shift; cmd_release "$@" ;;
file) shift; cmd_file "$@" ;;
help|-h|--help) usage ;;
*) usage >&2; exit 64 ;;
esac
@@ -0,0 +1,208 @@#!/usr/bin/env bash# bg: kleine BlueGit-CLI voor mensen en agents. Alleen bash, curl en jq.## BLUEGIT_URL standaard https://git.timfalken.com# BLUEGIT_TOKEN optioneel; nodig voor schrijven en voor privé projecten.# Wordt nooit geprint.## Zie docs/agents.md of `bg help`.set -euo pipefailBASE="${BLUEGIT_URL:-https://git.timfalken.com}"BASE="${BASE%/}"API="$BASE/api/v1"die() { echo "bg: $*" >&2; exit 64; }command -v curl >/dev/null || die "curl ontbreekt"command -v jq >/dev/null || die "jq ontbreekt"# req METHOD PATH [JSON] -> body op stdout; bij HTTP >= 400 de fout op stderr en exit 1.req() { local method=$1 path=$2 data=${3:-} out code local args=(-sS -X "$method" -w '\n%{http_code}' -H "Accept: application/json") [[ -n "${BLUEGIT_TOKEN:-}" ]] && args+=(-H "Authorization: Bearer ${BLUEGIT_TOKEN}") [[ -n "$data" ]] && args+=(-H "Content-Type: application/json" --data-binary "$data") out=$(curl "${args[@]}" "$API$path") || { echo "bg: verbinding mislukt: $method $path" >&2; return 1; } code=${out##*$'\n'} out=${out%$'\n'*} if (( code >= 400 )); then local msg msg=$(printf '%s' "$out" | jq -r '.message // .error // empty' 2>/dev/null || true) echo "bg: HTTP $code bij $method $path${msg:+: $msg}" >&2 [[ $code == 404 ]] && echo "bg: (bestaat niet, of je hebt geen toegang)" >&2 return 1 fi printf '%s' "$out"}get() { req GET "$1"; }enc() { jq -rn --arg v "$1" '$v|@uri'; }proj() { [[ "$1" == */* ]] || die "project moet owner/repo zijn: $1"; echo "/projects/$1"; }issues() { echo "/repos/$1/issues"; }json() { jq -cn "$@"; }# ---------- pipelines ----------# select_pipeline PROJECT ARGS... -> pipeline-JSON (of leeg als er nog geen is)select_query() { local q="" while (($#)); do case $1 in --sha) q="sha=$2"; shift 2 ;; --mr) q="mr=$2"; shift 2 ;; --branch|--ref) q="ref=$(enc "$2")"; shift 2 ;; --id) q="id=$2"; shift 2 ;; --timeout|--interval) shift 2 ;; *) die "onbekende optie: $1" ;; esac done echo "$q"}find_pipeline() { local p=$1 q=$2 if [[ $q == id=* ]]; then get "$(proj "$p")/pipelines/${q#id=}"; return; fi get "$(proj "$p")/pipelines?per_page=1${q:+&$q}" | jq -c '.[0] // empty'}show_pipeline() { local p=$1 pipe=$2 jq -r '"pipeline #\(.id) \(.status) \(.ref|sub("^refs/heads/";"")) \(.sha[0:8]) \(.web_url)"' <<<"$pipe" get "$(proj "$p")/pipelines/$(jq -r .id <<<"$pipe")/jobs" | jq -r '.[] | " \(.id)\t\(.status)\t\(.stage)/\(.name)\(if .allow_failure then " (allow_failure)" else "" end)"'}failed_logs() { local p=$1 id=$2 jobs jobs=$(get "$(proj "$p")/pipelines/$id/jobs") jq -r '.[]|select(.status=="failed" and .allow_failure)|"bg: waarschuwing: \(.name) (#\(.id)) faalde (allow_failure)"' <<<"$jobs" >&2 for j in $(jq -r '.[]|select(.status=="failed" and (.allow_failure|not))|.id' <<<"$jobs"); do echo "----- log job $j (laatste ${BG_LOG_LINES:-80} regels) -----" >&2 get "$(proj "$p")/pipelines/$id/jobs/$j/log" | tail -n "${BG_LOG_LINES:-80}" >&2 || true done}cmd_pipeline() { local sub=${1:-}; shift || true case $sub in status) local p=${1:?project}; shift local q pipe; q=$(select_query "$@") pipe=$(find_pipeline "$p" "$q") [[ -n "$pipe" ]] || { echo "geen pipeline gevonden" >&2; exit 3; } show_pipeline "$p" "$pipe" ;; wait) local p=${1:?project}; shift local timeout=1800 interval=10 a=("$@") while (($#)); do case $1 in --timeout) timeout=$2; shift 2 ;; --interval) interval=$2; shift 2 ;; *) shift ;; esac; done local q pipe status start=$SECONDS last="" q=$(select_query "${a[@]}") while :; do pipe=$(find_pipeline "$p" "$q" || true) status=$(jq -r '.status // empty' <<<"${pipe:-{\}}") if [[ -n "$status" && "$status" != "$last" ]]; then echo "pipeline #$(jq -r .id <<<"$pipe"): $status" >&2; last=$status fi case $status in success) show_pipeline "$p" "$pipe"; failed_logs "$p" "$(jq -r .id <<<"$pipe")" 2>&1 | grep '^bg: waarschuwing' >&2 || true; exit 0 ;; failed|canceled) show_pipeline "$p" "$pipe"; failed_logs "$p" "$(jq -r .id <<<"$pipe")"; exit 1 ;; esac (( SECONDS - start >= timeout )) && { echo "bg: timeout na ${timeout}s (status ${status:-geen pipeline})" >&2; exit 2; } sleep "$interval" done ;; logs) get "$(proj "${1:?project}")/pipelines/${2:?pipeline-id}/jobs/${3:?job-id}/log" ;; retry) local mode=failed [[ ${3:-} == --all ]] && mode=all req POST "$(proj "${1:?project}")/pipelines/${2:?pipeline-id}/retry" "$(json --arg m "$mode" '{mode:$m}')" | jq -r '"pipeline #\(.id) \(.status) \(.web_url)"' ;; list) get "$(proj "${1:?project}")/pipelines?per_page=${2:-10}" | jq -r '.[]|"\(.id)\t\(.status)\t\(.ref|sub("^refs/heads/";""))\t\(.sha[0:8])"' ;; *) die "pipeline status|wait|logs|retry|list" ;; esac}# ---------- merge requests ----------cmd_mr() { local sub=${1:-}; shift || true case $sub in list) local p=${1:?project}; shift; local q="state=open" while (($#)); do case $1 in --state) q="state=$2"; shift 2 ;; --source) q+="&source_branch=$(enc "$2")"; shift 2 ;; --target) q+="&target_branch=$(enc "$2")"; shift 2 ;; *) die "onbekende optie $1" ;; esac; done get "$(proj "$p")/merge_requests?per_page=100&$q" | jq -r '.[]|"!\(.iid)\t\(.state)\t\(.source_branch) -> \(.target_branch)\t\(.title)"' ;; show) get "$(proj "${1:?project}")/merge_requests/${2:?nummer}" | jq . ;; create) local p=${1:?project}; shift; local src="" tgt="" title="" desc="" remove=true while (($#)); do case $1 in --source) src=$2; shift 2 ;; --target) tgt=$2; shift 2 ;; --title) title=$2; shift 2 ;; --description) desc=$2; shift 2 ;; --keep-source) remove=false; shift ;; *) die "onbekende optie $1" ;; esac; done [[ -n $src && -n $tgt && -n $title ]] || die "mr create PROJECT --source B --target B --title T [--description D] [--keep-source]" req POST "$(proj "$p")/merge_requests" "$(json --arg s "$src" --arg t "$tgt" --arg ti "$title" --arg d "$desc" --argjson r "$remove" '{source_branch:$s,target_branch:$t,title:$ti,description:$d,remove_source_branch:$r}')" | jq -r '"!\(.iid) \(.web_url)"' ;; merge) local remove=true; [[ ${3:-} == --keep-source ]] && remove=false req POST "$(proj "${1:?project}")/merge_requests/${2:?nummer}/merge" "$(json --argjson r "$remove" '{remove_source_branch:$r}')" | jq -r '"\(.state) \(.web_url)"' ;; comment) req POST "$(proj "${1:?project}")/merge_requests/${2:?nummer}/notes" "$(json --arg b "${3:?tekst}" '{body:$b}')" | jq -r '"notitie \(.id)"' ;; *) die "mr list|show|create|merge|comment" ;; esac}# ---------- issues ----------cmd_issue() { local sub=${1:-}; shift || true case $sub in list) get "$(issues "${1:?project}")?state=${2:-open}" | jq -r '.issues[]|"#\(.id)\t\(.status)\t\(.title)"' ;; show) get "$(issues "${1:?project}")/${2:?nummer}" | jq . ;; create) req POST "$(issues "${1:?project}")" "$(json --arg t "${2:?titel}" --arg d "${3:-}" '{title:$t,description:$d}')" | jq -r '"#\(.id) \(.web_url)"' ;; comment) req POST "$(issues "${1:?project}")/${2:?nummer}/notes" "$(json --arg b "${3:?tekst}" '{body:$b}')" >/dev/null && echo "ok" ;; close|reopen) local st=closed; [[ $sub == reopen ]] && st=open req PUT "$(issues "${1:?project}")/${2:?nummer}" "$(json --arg s "$st" '{state:$s}')" | jq -r '"#\(.id) \(.status)"' ;; *) die "issue list|show|create|comment|close|reopen" ;; esac}# ---------- overig ----------cmd_branch() { [[ ${1:-} == create ]] || die "branch create PROJECT NAAM [--from REF]" local p=${2:?project} name=${3:?naam} from="" [[ ${4:-} == --from ]] && from=${5:?ref} req POST "$(proj "$p")/repository/branches" "$(json --arg n "$name" --arg f "$from" '{name:$n} + (if $f=="" then {} else {from:$f} end)')" | jq -r '.name // .'}cmd_release() { [[ ${1:-} == create ]] || die "release create PROJECT TAG [--commit SHA] [--name N] [--body B] [--asset JOB:PAD[:NAAM]]..." local p=${2:?project} tag=${3:?tag}; shift 3 local commit="" name="" body="" assets="[]" while (($#)); do case $1 in --commit) commit=$2; shift 2 ;; --name) name=$2; shift 2 ;; --body) body=$2; shift 2 ;; --asset) IFS=: read -r j pth nm <<<"$2"; assets=$(jq -c --arg j "$j" --arg p "$pth" --arg n "${nm:-}" '. + [{job:$j,path:$p} + (if $n=="" then {} else {name:$n} end)]' <<<"$assets"); shift 2 ;; *) die "onbekende optie $1" ;; esac; done req POST "$(proj "$p")/releases" "$(json --arg t "$tag" --arg c "$commit" --arg n "$name" --arg b "$body" --argjson a "$assets" '{tag:$t,commit:$c,name:$n,body:$b,assets:$a}')" | jq -c .}cmd_file() { [[ ${1:-} == get ]] || die "file get PROJECT PAD [--ref REF]" local p=${2:?project} path=${3:?pad} ref="" [[ ${4:-} == --ref ]] && ref="?ref=$(enc "${5:?ref}")" local body; body=$(get "$(proj "$p")/repository/files/$(enc "$path")$ref") if jq -e '.content and .encoding=="base64"' <<<"$body" >/dev/null 2>&1; then jq -r .content <<<"$body" | base64 -d elif jq -e '.content' <<<"$body" >/dev/null 2>&1; then jq -r .content <<<"$body" else printf '%s' "$body"; fi}usage() { sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//' cat <<'U' bg pipeline status PROJECT [--sha X | --mr N | --branch B | --id P] bg pipeline wait PROJECT [selectie] [--timeout 1800] [--interval 10] exit 0 ok, 1 mislukt, 2 timeout bg pipeline logs PROJECT PIPELINE JOB bg pipeline retry PROJECT PIPELINE [--all] bg pipeline list PROJECT [N] bg mr list|show|create|merge|comment ... bg issue list|show|create|comment|close|reopen ... bg branch create PROJECT NAAM [--from REF] bg release create PROJECT TAG [--commit SHA] [--asset JOB:PAD[:NAAM]] bg file get PROJECT PAD [--ref REF]U}case ${1:-help} in pipeline|pl) shift; cmd_pipeline "$@" ;; mr) shift; cmd_mr "$@" ;; issue) shift; cmd_issue "$@" ;; branch) shift; cmd_branch "$@" ;; release) shift; cmd_release "$@" ;; file) shift; cmd_file "$@" ;; help|-h|--help) usage ;; *) usage >&2; exit 64 ;;esac@@ -0,0 +1,97 @@
package scripts
import (
"bytes"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
)
// fakeBlueGit geeft eerst geen pipeline, dan running, dan final.
func fakeBlueGit(t *testing.T, final string, token string) (*httptest.Server, *atomic.Int32) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token != "" && r.Header.Get("Authorization") != "Bearer "+token {
http.Error(w, `{"message":"no"}`, 401)
return
}
switch {
case r.URL.Path == "/api/v1/projects/tim/app/pipelines":
if r.URL.Query().Get("sha") != "abcdef1" {
t.Errorf("sha-filter ontbreekt: %s", r.URL.RawQuery)
}
n := calls.Add(1)
switch {
case n == 1:
fmt.Fprint(w, `[]`)
case n == 2:
fmt.Fprint(w, `[{"id":9,"status":"running","ref":"refs/heads/x","sha":"abcdef1000","web_url":"u"}]`)
default:
fmt.Fprintf(w, `[{"id":9,"status":%q,"ref":"refs/heads/x","sha":"abcdef1000","web_url":"u"}]`, final)
}
case r.URL.Path == "/api/v1/projects/tim/app/pipelines/9/jobs":
fmt.Fprint(w, `[{"id":1,"name":"test","stage":"test","status":"failed","allow_failure":false},{"id":2,"name":"aur","stage":"release","status":"failed","allow_failure":true}]`)
case r.URL.Path == "/api/v1/projects/tim/app/pipelines/9/jobs/1/log":
fmt.Fprint(w, "regel 1\nFOUT hier\n")
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv, &calls
}
func runBG(t *testing.T, url, token string, args ...string) (int, string, string) {
t.Helper()
for _, bin := range []string{"bash", "curl", "jq"} {
if _, err := exec.LookPath(bin); err != nil {
t.Skip(bin + " ontbreekt")
}
}
cmd := exec.Command(filepath.Join("..", "scripts", "bg"), args...)
cmd.Env = append(os.Environ(), "BLUEGIT_URL="+url, "BLUEGIT_TOKEN="+token)
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
err := cmd.Run()
code := 0
var ee *exec.ExitError
if errors.As(err, &ee) {
code = ee.ExitCode()
} else if err != nil {
t.Fatal(err)
}
return code, out.String(), errb.String()
}
func TestBGWaitExitCodes(t *testing.T) {
const tok = "bg_geheimtoken123"
srv, _ := fakeBlueGit(t, "success", tok)
code, out, errs := runBG(t, srv.URL, tok, "pipeline", "wait", "tim/app", "--sha", "abcdef1", "--interval", "0")
if code != 0 || !strings.Contains(out, "pipeline #9 success") {
t.Fatalf("success: %d %s %s", code, out, errs)
}
if strings.Contains(out+errs, tok) {
t.Fatal("token geprint")
}
srv, _ = fakeBlueGit(t, "failed", "")
code, out, errs = runBG(t, srv.URL, "", "pipeline", "wait", "tim/app", "--sha", "abcdef1", "--interval", "0")
if code != 1 || !strings.Contains(errs, "FOUT hier") || !strings.Contains(errs, "waarschuwing: aur") {
t.Fatalf("failed: %d %s %s", code, out, errs)
}
srv, _ = fakeBlueGit(t, "running", "")
code, _, errs = runBG(t, srv.URL, "", "pipeline", "wait", "tim/app", "--sha", "abcdef1", "--interval", "1", "--timeout", "2")
if code != 2 || !strings.Contains(errs, "timeout") {
t.Fatalf("timeout: %d %s", code, errs)
}
code, _, errs = runBG(t, srv.URL, "", "mr", "show", "tim/app", "5")
if code != 1 || !strings.Contains(errs, "404") {
t.Fatalf("404: %d %s", code, errs)
}
}
@@ -0,0 +1,97 @@package scriptsimport ( "bytes" "errors" "fmt" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "sync/atomic" "testing")// fakeBlueGit geeft eerst geen pipeline, dan running, dan final.func fakeBlueGit(t *testing.T, final string, token string) (*httptest.Server, *atomic.Int32) { var calls atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if token != "" && r.Header.Get("Authorization") != "Bearer "+token { http.Error(w, `{"message":"no"}`, 401) return } switch { case r.URL.Path == "/api/v1/projects/tim/app/pipelines": if r.URL.Query().Get("sha") != "abcdef1" { t.Errorf("sha-filter ontbreekt: %s", r.URL.RawQuery) } n := calls.Add(1) switch { case n == 1: fmt.Fprint(w, `[]`) case n == 2: fmt.Fprint(w, `[{"id":9,"status":"running","ref":"refs/heads/x","sha":"abcdef1000","web_url":"u"}]`) default: fmt.Fprintf(w, `[{"id":9,"status":%q,"ref":"refs/heads/x","sha":"abcdef1000","web_url":"u"}]`, final) } case r.URL.Path == "/api/v1/projects/tim/app/pipelines/9/jobs": fmt.Fprint(w, `[{"id":1,"name":"test","stage":"test","status":"failed","allow_failure":false},{"id":2,"name":"aur","stage":"release","status":"failed","allow_failure":true}]`) case r.URL.Path == "/api/v1/projects/tim/app/pipelines/9/jobs/1/log": fmt.Fprint(w, "regel 1\nFOUT hier\n") default: http.NotFound(w, r) } })) t.Cleanup(srv.Close) return srv, &calls}func runBG(t *testing.T, url, token string, args ...string) (int, string, string) { t.Helper() for _, bin := range []string{"bash", "curl", "jq"} { if _, err := exec.LookPath(bin); err != nil { t.Skip(bin + " ontbreekt") } } cmd := exec.Command(filepath.Join("..", "scripts", "bg"), args...) cmd.Env = append(os.Environ(), "BLUEGIT_URL="+url, "BLUEGIT_TOKEN="+token) var out, errb bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &errb err := cmd.Run() code := 0 var ee *exec.ExitError if errors.As(err, &ee) { code = ee.ExitCode() } else if err != nil { t.Fatal(err) } return code, out.String(), errb.String()}func TestBGWaitExitCodes(t *testing.T) { const tok = "bg_geheimtoken123" srv, _ := fakeBlueGit(t, "success", tok) code, out, errs := runBG(t, srv.URL, tok, "pipeline", "wait", "tim/app", "--sha", "abcdef1", "--interval", "0") if code != 0 || !strings.Contains(out, "pipeline #9 success") { t.Fatalf("success: %d %s %s", code, out, errs) } if strings.Contains(out+errs, tok) { t.Fatal("token geprint") } srv, _ = fakeBlueGit(t, "failed", "") code, out, errs = runBG(t, srv.URL, "", "pipeline", "wait", "tim/app", "--sha", "abcdef1", "--interval", "0") if code != 1 || !strings.Contains(errs, "FOUT hier") || !strings.Contains(errs, "waarschuwing: aur") { t.Fatalf("failed: %d %s %s", code, out, errs) } srv, _ = fakeBlueGit(t, "running", "") code, _, errs = runBG(t, srv.URL, "", "pipeline", "wait", "tim/app", "--sha", "abcdef1", "--interval", "1", "--timeout", "2") if code != 2 || !strings.Contains(errs, "timeout") { t.Fatalf("timeout: %d %s", code, errs) } code, _, errs = runBG(t, srv.URL, "", "mr", "show", "tim/app", "5") if code != 1 || !strings.Contains(errs, "404") { t.Fatalf("404: %d %s", code, errs) }}