stages:
- check
- preview_docs
- publish_docs
- cleanup_preview
before_script:
- apt-get update -y
- apt-get install -y curl jq
- curl -sL https://deb.nodesource.com/setup_current.x | bash -
- apt-get install -y nodejs
- npm install -g fern-api
check:
stage: check
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
script:
- echo "Checking API is valid"
- fern check
preview_docs:
stage: preview_docs
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
script:
- echo "Generating preview for branch $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME..."
- |
OUTPUT=$(fern generate --docs --preview --id "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME" --force 2>&1) || true
echo "$OUTPUT"
DEMO_URL=$(echo "$OUTPUT" | grep -oE -m1 '(https://[^[:space:]]+-preview-[^[:space:]]+) ' | tr -d ' ')
echo "Preview URL: $DEMO_URL"
- |
if [ -z "$DEMO_URL" ]; then
echo "No preview URL found"
exit 1
fi
curl --location --request POST \
--header "PRIVATE-TOKEN: $REPO_TOKEN" \
--header "Content-Type: application/json" \
--url "https://gitlab.com/api/v4/projects/$CI_MERGE_REQUEST_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID/notes" \
--data-raw "{ \"body\": \"Preview your docs [here]($DEMO_URL)\" }"
publish_docs:
stage: publish_docs
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
script:
- echo "Publishing Docs"
- fern generate --docs
cleanup_preview:
stage: cleanup_preview
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
script:
- echo "Looking up merged MR for commit $CI_COMMIT_SHA..."
- |
MR_INFO=$(curl -sf --header "PRIVATE-TOKEN: $REPO_TOKEN" \
"https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/repository/commits/$CI_COMMIT_SHA/merge_requests") || {
echo "Failed to query MRs for commit — skipping cleanup"
exit 0
}
SOURCE_BRANCH=$(echo "$MR_INFO" | jq -r 'map(select(.state == "merged")) | .[0].source_branch // empty')
if [ -z "$SOURCE_BRANCH" ]; then
echo "No merged MR found for this commit (likely a direct push to main) — skipping cleanup"
exit 0
fi
echo "Deleting preview for branch: $SOURCE_BRANCH"
fern docs preview delete --id "$SOURCE_BRANCH" || echo "Preview deletion returned non-zero — it may already be gone"