mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-08-18 16:02:10 +00:00
51d8db6602
* docs: add design doc for automatic git-to-windmill pull sync
* docs: add migration plan and implementation phases to git-sync pull design
* feat(git-sync): add auto_pull settings schema and pull enqueue primitive
Adds AutoPullSettings/AutoPullMode/AutoPullStatus on GitRepositorySettings
(workspace_settings.git_sync JSONB), the GIT_SYNC_PULL_SCRIPT_PATH constant,
and should_pull/effective_poll_interval_s helpers with unit tests. Exports the
EE enqueue_git_pull_job primitive. Foundation for repo→Windmill auto-pull.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(git-sync): poll repos and auto-pull new commits into the workspace
Phase 1 of automatic repo → Windmill sync. A monitor task (EE-licensed,
single-replica via advisory lock) git ls-remotes each auto-pull-enabled
repository ~every minute and enqueues a pull when the tracked branch moves,
reusing the {workspace_id}:git_sync concurrency key so pulls serialize with
in-flight push commits.
- windmill-store: background (no-authed) resolver get_git_repo_head_for_autopull
that resolves the repo resource (incl. $var: refs) and ls-remotes; GitHub-App
repos are skipped here and will sync via webhooks (phase 2).
- monitor.rs: poll/reconcile/persist with optimistic sha advance and failure
status; targeted jsonb update so concurrent settings edits aren't clobbered.
- edit_git_sync_repository: preserve server-owned auto_pull state on UI save.
- openapi: AutoPullSettings/AutoPullMode/AutoPullStatus + auto_pull field.
- frontend: per-repo "Automatically deploy changes from Git" toggle with last
sync status; demote the GitHub Actions link to an advanced CI option.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(git-sync): wire webhook lifecycle + receiver; share reconcile logic
OSS side of phase 2 auto-pull webhooks:
- edit_git_sync_repository creates/removes the repo webhook on save (EE-gated,
best-effort → falls back to polling).
- monitor poller now delegates to the shared windmill_git_sync reconcile/persist
helpers (also used by the webhook receiver), removing duplicated logic.
- export the shared reconcile/persist/failure helpers; bump EE ref.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(git-sync): bump EE ref for phase 3 in-app PR creation
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(git-sync): show webhook vs polling status on the auto-pull toggle
When a repo has an active webhook (auto_pull.webhook_id set), the status line
reads "instant via webhook"; otherwise it reads the ~1-minute polling cadence.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(git-sync): post PR diff check on dry-run completion (phase 4)
Worker completion hook in process_completed_job: when a DeploymentCallback job
carrying the __git_sync_pr_check marker finishes, parse the dry-run SyncResponse
and patch the GitHub check run with the diff summary (success/neutral/failure).
Export enqueue_git_pull_dry_run; bump EE ref.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(git-sync): bump EE ref (drop unused GHES webhook_secret)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* revert(git-sync): defer phase 4 PR diff checks (OSS side)
Remove the worker completion hook that posted the PR check run, drop the
enqueue_git_pull_dry_run re-export and the orphaned sqlx cache, bump EE ref.
Phases 1-3 (polling, webhooks, in-app PR creation) are unaffected.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Revert "revert(git-sync): defer phase 4 PR diff checks (OSS side)"
This reverts commit 0137d3ca48.
* chore(git-sync): point EE ref at restored phase 4 commit
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(git-sync): bump EE ref for clone_ref dry-run
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(git-sync): bump init-repository hub script to v28784
Picks up the clone_ref param (windmill-integrations#158) so the phase 4 PR-check
dry-run can clone the PR head. Backward compatible; manual pull/push and the
automated pull/poller/webhook all move to the same published version.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(git-sync): bump EE ref for auto-pull admin-permissioning fix
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(git-sync): bump EE ref for superadmin pull fallback
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(git-sync): refresh auto-pull tooltip; bump EE ref for webhook secret encryption
The auto-pull toggle tooltip claimed GitHub App repos would sync via
webhooks "in a future update"; webhook delivery now works, so describe
the webhook-vs-polling behavior accurately. Bump the EE ref to pick up
encrypting the webhook HMAC secret at rest.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix(git-sync): poll app-backed repos in auto/polling mode
The auto-pull poller skipped app-backed repos (the ls-remote head check
can't authenticate a tokenless URL), so auto- and polling-mode app repos
never synced when their webhook wasn't live. Wire the poller to fetch the
head via the GitHub API for app repos and reconcile. Bump the EE ref.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(git-sync): auto-pull UI — direction split, delivery mode, fallback notice
Reorganize the repository card into two clearly labeled directions:
"Push to Git on deploy (Windmill → Git)" and "Pull from Git (Git →
Windmill)". In the pull section:
- new connections default to auto-pull enabled (webhook with polling
fallback); existing repos load with auto-pull off and are unchanged
- a Delivery selector chooses "Webhook with polling fallback" or
"Polling only (air-gapped)"
- a notice surfaces webhook_error when delivery falls back to polling
- a reminder to remove any pre-existing GitHub Action that pushed into
Windmill, to avoid conflicting double-syncs
Adds the webhook_error field to AutoPullSettings (+ openapi) and bumps
the EE ref.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(git-sync): clearer push indicator + gate webhook delivery to app repos
- Push-on-deploy is shown with a check icon + concise line (via the
shared GitSyncModeDisplay, restyled from the oversized "Sync:" text);
the setup wizard reuses it without the check (pre-save preview).
- The delivery-mode selector only shows for GitHub App-backed repos;
token-based repos show a "webhooks require the GitHub App (managed or
GHES)" note with a docs link and poll instead. Bumps the EE ref.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat(git-sync): fork auto-sync (phase 5) + live deploy check (phase 6)
Phase 5 — fork auto-sync configured at the parent (replaces the *-to-forks
GitHub Actions):
- Add fork_open_prs + fork_pull_sync to GitRepositorySettings (openapi + UI).
- UI: two "Forks of this workspace" toggles in the repo card, gated on
app-backed and not-a-fork; serialize the flags on save.
- On fork creation, strip the inherited auto_pull block (and fork_* flags) from
the copied git_sync repo: a fork must not carry the parent's webhook id (it
would delete the parent's hook on disable) or self-poll on top of the parent's
fan-out. Push-direction config + installation are still inherited unchanged.
Phase 6 — live deploy status check on the commit (Cloudflare-style): an
in-progress "Windmill" check on the head commit that flips to "Deployed N
changes"; completion handled by the generalized git-sync check hook.
Bump EE ref for the phase 5-6 EE implementation.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* chore(git-sync): bump EE ref for PAT auto-pull mode normalization
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): address PR review findings
- webhook_secret: redact from the settings API response and Debug output (still
persisted encrypted); it's a server-only HMAC key the UI never needs.
- poller: honor each repo's effective poll interval (relaxed ~10 min when a
webhook is live) instead of probing every ~60s tick.
- settings save: roll back a just-created webhook if the settings transaction
doesn't commit, so a failed save can't orphan a hook.
- auto-pull head check: fail SSH remotes with an actionable message (background
polling has no SSH identity) instead of a confusing ls-remote error.
- deploy/PR check summary: a pull result carrying neither changes nor a settings
diff now falls back to the unsummarized path instead of a false "in sync".
- UI: reset isGithubApp on resource change / failed fetch so webhook + fork
controls can't show for the wrong repo.
- tests: cover parse_git_sync_changes and format_change_list edge cases.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): correct feature gating for OSS builds
- monitor.rs: keep the AUTO_PULL_LAST_POLL static, slack const, and
poll_git_auto_pull_inner all behind #[cfg(feature = "private")] (an inserted
static had split the cfg off the function, ungating it in OSS builds).
- edit_git_sync_repository: the webhook create/rollback block references
windmill_common::git_sync_ee (private module), so gate it on
all(enterprise, private) instead of enterprise only.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* chore(sqlx): cache workspace_diff query pulled in from origin/main
Re-merged origin/main (advanced past the earlier merge); regenerate the offline
sqlx entry for the new workspace_comparison test query so SQLX_OFFLINE builds
(cargo_test) pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): address Codex review findings (webhook cleanup on delete)
- Deleting a git-sync repository now tears down its managed GitHub webhook
(deletion bypassed the sync_repo_webhook lifecycle, orphaning the hook so
GitHub kept delivering to the instance).
- Worker completion hook rolls back the optimistic auto-pull sha on job failure
(OSS side of the EE change) + caches the new marker query. Bump EE ref.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): delete repo webhook after the removal commits
Codex re-review nits:
- delete_git_sync_repository deleted the webhook before the settings transaction
committed; a failed save would then leave the repo pointing at a hook that no
longer exists (sync_repo_webhook treats a set webhook_id as live and won't
recreate it). Capture the hook id, commit the DB removal, then delete the hook.
- Reword a fork-copy comment to drop drafting-history wording per AGENTS.md.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): reconcile the edit-path webhook after the settings commit
Codex nit: edit_git_sync_repository ran sync_repo_webhook before the transaction
committed. The rollback only covered created hooks, but sync_repo_webhook also
deletes a hook on disable/switch-to-polling — a commit failure then left the DB
with a webhook_id whose hook was already gone (and it wouldn't be recreated).
Save + commit first, then reconcile the webhook against the durable config and
persist any hook id/secret change (best-effort). Bump EE ref.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): preserve webhook secret on whole-config save + default on visible add
Codex nits:
- edit_git_sync_config saved the client config verbatim, so the webhook_secret
redacted from the GET response would be dropped (breaking delivery). Preserve
server-owned auto-pull state (webhook id/secret, synced sha, last status) per
repo from the existing settings, matching edit_git_sync_repository.
- addSyncRepository (the visible add path) didn't set the auto_pull default, so
new sync repos added from the UI came up with auto-deploy off. Match
addRepository's default (webhook + polling fallback).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* refactor(git-sync): drop fork_pull_sync (parent-level keep-forks-in-sync)
Removes the "Keep forks in sync with the tracked branch" toggle and its
fan-out. Pulling the tracked branch straight into every fork was the
inconsistent piece; the consistent model is per-fork branch sync (each
fork tracks its own wm-fork/** branch), which is a separate follow-up.
fork_open_prs is kept. Also tightens the fork toggle-section spacing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): detect dev workspaces in CLI fork branch derivation
isForkWorkspace / computeGitSyncDeployBranch keyed off the wm-fork- id
prefix. Dev workspaces are forks with a custom, prefix-less id, so their
wm-fork/** branch was never derived or created. Detect them via
parent_workspace_id too (which the backend already passes), mirroring the
backend's `parent.is_some() || wm-fork- prefix` rule.
Pairs with the hub-script clone-flag fix (windmill-integrations#163); both
take effect once the CLI is released and the pinned version is bumped.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): reconcile webhooks on full-config save
edit_git_sync_config preserved server-owned webhook fields but never
created or deleted the managed GitHub webhook, so enabling auto-pull
through the whole-config endpoint only polled, and disabling or removing
a repo left an orphan hook still delivering. Mirror the per-repository
endpoint: after the commit is durable, reconcile every saved repo's
webhook (sync_repo_webhook) and delete the hooks of repos the save
removed, including the clear-whole-config case. Addresses the Codex nit.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): address Codex nits (webhook orphan on cleared auto_pull, fork detection)
- edit_git_sync_config: also delete a repo's old webhook when the save drops
the repo OR clears its auto_pull. Webhook fields are only preserved onto a
Some auto_pull, so a save that present-but-clears a repo would otherwise
orphan its hook.
- GitSyncRepositoryCard: isFork now uses parent_workspace_id OR the wm-fork-
prefix (was AND), matching the backend/CLI rule, so prefix-less dev
workspaces are detected as forks and don't show the parent fork-PR toggle.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* docs(git-sync): update design doc for the dropped fork_pull_sync
Phase 5 documented "Keep forks in sync with the tracked branch"
(fork_pull_sync) and its fan-out as implemented; that feature was removed.
Rewrite the section to reflect what ships (fork_open_prs), note the drop +
the per-fork-branch follow-up, and remove the stale fan-out mentions
elsewhere. Addresses the Codex nit.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): redact webhook secrets from workspace export; fix doc endpoints
- Export (P1): strip the server-owned auto_pull state (webhook secret/id/error
+ synced sha + last pull status) from git_sync before it is written into an
export's settings.json for both settings formats. The HMAC webhook secret
must never leave the server (matching the GET-settings redaction), and a
re-imported workspace must not inherit another install's hook/sync state.
- Docs: the webhook receiver is a single per-workspace endpoint
/api/w/{workspace}/github_app/webhook (host-aware for managed + self-managed);
update the stale push_webhook/{id} and instance-global /api/github_app/webhook
references.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): skip deleted/archived workspaces in the auto-pull poller
The poller scanned workspace_settings directly, so an archived (soft-deleted)
or renamed-away workspace — whose settings row persists — kept polling and
could enqueue a pull into a dead workspace. Join workspace and require
NOT deleted. The EE webhook receiver gets the same filter (ee ref bumped).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): never trust client-supplied server-owned auto-pull fields
Both write endpoints (edit_git_sync_repository, edit_git_sync_config)
persisted caller-supplied auto_pull.webhook_id / webhook_secret /
webhook_error / last_synced_sha / last_pull_status when adding a repo or
newly enabling auto-pull, letting a client inject a webhook id/secret or
fake sync state. Strip those server-owned fields from the request up front;
existing repos re-derive them from the DB (carried over), new ones start
clean and the server (re)creates the webhook.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): merge webhook fields post-commit instead of clobbering the row
The post-commit webhook reconcile in edit_git_sync_repository and
edit_git_sync_config wrote the whole pre-reconcile git_sync snapshot back
after the main save committed. A concurrent git-sync edit or poller status
write that landed in the gap could then be dropped by the stale snapshot.
Re-read the current row and merge only the reconciled webhook id/secret/error
for the repos the reconcile actually changed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* feat(git-sync): parent-managed fork sync + PR-on-deploy toggles
Fork sync (push-on-merge-to-forks parity): a parent-level
auto_pull.sync_forks toggle routes changes on each fork's wm-fork/** branch
into that fork workspace, via the parent's existing webhook and one extra
fork-heads listing per poll tick (git ls-remote pattern for token repos,
git/matching-refs for app-backed). Fork state is a server-written
status-only auto_pull blob on the fork's own repo entry; the fork's card
shows a read-only "managed in the parent workspace" line with its branch
and last pull status. Dev workspaces (prefix-less ids) use the same branch
parsing (unit-tested in windmill-common).
PR-on-deploy: opening PRs for Windmill-pushed branches moves into the
deploy pipeline, per repo toggle (promotion_open_prs on the promotion
repo; parent-level fork_open_prs for fork deploys). The push job carries a
marker and the job-completion hook derives the pushed branch (helper
unit-tested against the CLI formula) and opens the PR outbound, so it
works without inbound webhooks; the webhook-side wm_deploy PR arm is
removed. The documented open-pr-* GitHub Actions remain valid alternatives
(PR creation is idempotent).
Fork guards: promotion mode, enabled auto-pull, and fork_open_prs are
rejected on fork workspaces (they are parent-managed; a fork's deploys
always target its wm-fork/** branch) and the promotion card is hidden in a
fork's settings. Enabling auto-pull now also requires EE, and the
post-commit webhook reconcile persists the normalized delivery mode.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* feat(git-sync): dev workspaces sync with their environment-label branch
A dev workspace's git branch is its environment label verbatim (dev/
staging, default dev) — a first-class env branch like the documented
push-on-merge-staging layout — instead of the wm-fork/** form. The label
rides the deploy job args (backend → hub script → CLI
--dev-workspace-label), the PR completion hook derives the same head, the
webhook/poller route label branches into the matching dev-workspace child
(poller lists them alongside wm-fork/* via extra ls-remote refs / per-label
API lookups), and manual pulls from the UI pass clone_ref accordingly. The
CLI refuses to deploy when the label branch equals the checked-out tracked
branch, which would otherwise commit fork content straight to it.
Because the branch is keyed on the label, the label is now immutable after
creation: set at create/attach only, the set_dev_workspace_label endpoint
is removed and the settings tab shows it read-only.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* feat(git-sync): nested fork routing + fork-of-dev branch rooting
A fork of a dev workspace now roots its wm-fork/** branch on the dev's
environment-label branch (the content it diverged from) and its PR merges
back into that branch: the backend passes parent_dev_workspace_label with
the deploy (parent row joined in both enqueue paths), the CLI gains
--parent-dev-workspace-label and checks it before the wm-fork- prefix
fallback when rooting a fork-of-a-fork branch, and the PR completion hook
uses it as the PR base.
Fork sync routing covers the whole live descendant chain of the
webhook/poller workspace (recursive, depth-capped) instead of direct
children only, and fork_open_prs is resolved at the root ancestor — only
the root can hold auto-pull config, so grandchild forks sync through it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* feat(git-sync): PR deploy-preview comment, clearer check copy, app-only hints
- The PR diff completion hook maintains one managed comment on the PR
(Cloudflare deploy-preview style: workspace, status, commit, collapsible
change list), upserted per synchronize via a hidden marker. The check run
stays for required-check gating.
- A settings difference in the diff summary is worded by cause: the PR
changes wmill.yaml, vs pre-existing drift between the repo's wmill.yaml
and the workspace, vs undetermined (neutral wording).
- Deploy-status check titles name the target workspace ("Deployed 2
change(s) to staging"), since GitHub shows a head commit's checks on any
PR containing it and a bare "Deployed" read as if the PR had deployed.
- Token-based repos see a hint pointing at the open-pr-on-commit /
open-pr-on-fork-commit workflows where the app-only PR toggles would be;
an API-set toggle on a non-app repo now logs a warning naming the
fallback; the design doc lists app-only features and their degradation.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): EE-gate auto-pull UI, fork pull clone_ref, no-op push PR gate
- CE: the auto-pull and fork-PR toggles are disabled with an EE badge, and
new sync repos only default them on when licensed (basic git sync is
available on CE since #8493, but auto-pull is EE and the backend rejects it)
- The pull modal passes clone_ref for wm-fork- forks (wm-fork/<tracked>/<id>)
so a manual pull fetches the fork branch instead of the tracked branch head
- PR-on-deploy skips no-op pushes: when the push script reports pushed=false
(e.g. the deploy was caused by an auto-pull), the completion hook no longer
ensures a PR, so closed PRs aren't recreated by the sync loop
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* chore: refresh package-lock after main merge (windmill-utils-internal 1.8.2)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* test: auto-pull e2e integration tests; fix PR comment table formatting
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): runtime license gate for auto-pull saves; user/group promotion-branch parity
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): explain in-sync PR verdicts with the repo's sync filter scope
A PR that only touches files outside the repository's include paths gets
"In sync", which reads as a wrong verdict; the check summary (and managed
comment) now name the filters, e.g. "Only files matching this repository's
sync filters deploy on merge: `f/**` (excluding `f/pat/**`)."
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* feat(git-sync): clearer card copy/structure; surface PR-creation failures
- Fork sync toggle renamed and kept in the pull section; the fork PR toggle
moves to the push section with a note that push settings apply to forks
- Fork/dev workspaces' push section names their actual branch instead of the
tracked-branch line; promotion repos hide the pull direction (promotion
pushes deploy branches on top of a sync-mode setup)
- Promotion mode line describes the wm_deploy/** branch + merge-to-promote
flow; workflow-fallback hints lead with the how-to and link to the docs;
test connection button demoted from accent per brand guidelines
- New server-owned open_pr_error on repo settings: the deploy completion hook
records why a PR couldn't be opened (e.g. app permission not yet approved)
and clears it on the next success; shown as a warning under the PR toggles
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix: cfg-gate scope-note helper (dead code on OSS builds)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): license-gate preserved auto-pull; attach strips parent-only settings
- edit_git_sync_repository re-checks the runtime Enterprise gate against the
EFFECTIVE repo state after preservation: the older-client arm copies the
existing auto_pull back, which the request-side check never saw
- attach_dev_workspace now mirrors the fork-creation copy on the attached
workspace's own git sync: promotion repos dropped, auto_pull/fork PRs/PR
error stripped, and any managed webhook deleted after commit (the attached
workspace is parent-managed and must not keep pulling its old tracked branch)
- integration test: attaching an auto-pull-enabled workspace strips it
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): detach clears standalone parent; reject label == tracked branch
- detach_dev_workspace clears parent_workspace_id for prefix-less (attached
standalone) workspaces so they stop classifying as forks and deploying to
wm-fork/** branches; wm-fork- re-designated forks keep their parent; cache
invalidations mirror attach
- dev-workspace create/attach reject an environment label that equals a
git-sync repository's tracked branch (prod's or the candidate's): deploys
would target the very branch the repo syncs from, and the CLI guard would
fail every push job after the fact
- CLI unit tests: prefix-less fork beats wm_deploy derivation; isForkWorkspace
parent-id argument
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* chore(git-sync): bump hub script pins (push 28786, pull 28785)
Published from windmill-integrations #163 with windmill-cli@1.753.1-gitsync.0:
dev-workspace label deploys, fork-of-dev rooting, fork checkout on the
existing remote branch, and the pushed-flag result.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): no parent-only defaults on fork repos; rename strips webhook state
- addSyncRepository skips the auto_pull/fork_open_prs defaults on fork/dev
workspaces where the backend rejects them (saving a new sync repo from an
EE fork 400'd deterministically)
- change_workspace_id strips webhook id/secret/error from the copied git_sync
and deletes the stale GitHub hooks post-commit: they deliver to the old
(archived) workspace URL, so the new workspace would report a live webhook
while polling at the relaxed interval; next save re-registers cleanly
- EE: PR diff checks for contributor-fork PRs clone the synthetic
pull/<n>/head ref (head.ref doesn't exist in the base repo)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* chore(git-sync): bump pull script pin to hub/28787 (synthetic PR ref support)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): targeted jsonb update for open_pr_error (no full-blob clobber)
The full read-modify-write raced the poller's concurrent last_synced_sha /
last_pull_status writes on the same column; mirror the EE status writer and
update only the matching repository element's open_pr_error key.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* style(git-sync): inline EE badge on gated toggles (matches settings nav)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* copy(git-sync): both directions in page/card descriptions; clearer promotion flow
- Page header and sync-card description mention the pull direction, not only
push-on-deploy
- Promotion description walks the actual flow (wm_deploy/** branch, merge to
promote, sync the target workspace) and points at the PR toggle / workflow;
the Git Promotion docs link now also shows on configured cards, not only in
the empty state
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): resolve branch-less resources' default branch for fork sync
A git resource without an explicit branch polled as the bare "HEAD" ref,
which the fork/dev-label fan-out cannot scope (wm-fork/<branch>/*), so fork
sync silently never ran on polling-only repos. Resolve the remote's default
branch name with `ls-remote --symref HEAD` (one call for name + head sha);
"HEAD" only remains when resolution fails. The polling e2e test now uses a
branch-less resource to cover this shape.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): runtime license gate for in-app PR creation
promotion_open_prs/fork_open_prs are rejected on save without an Enterprise
plan (like auto_pull), and the deploy completion hook re-checks the plan
before opening PRs so flags stored while licensed stop driving GitHub calls
after a lapse.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* feat(git-sync): app-aware pull defaults, always webhook delivery, token-repo guidance
- Pull-from-Git defaults on only for app-backed repos (applied when the
selected resource resolves); polling is opt-in for token repositories,
with a warning alert recommending the GitHub App (instant pull + in-app
PRs) or the sync GitHub workflow
- App repos always use webhook delivery with polling fallback: the delivery
selector is gone and a stored polling mode is normalized back to auto
- Post-save modal reflects the auto-pull state instead of telling the user
to turn on a toggle that is already on
- Non-app PR hints recommend the GitHub App explicitly
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* copy(git-sync): single info box for token-repo pull guidance
Merges the instant-pull recommendation with the GitHub Action conflict note,
shown only for non-app repos; app repos need neither, and the redundant
'instant webhook sync requires' line is gone.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* copy(git-sync): keep the GitHub Action conflict note on app repos
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* copy(git-sync): anchor docs links to their exact sections
GitHub App references point at integrations/git_repository#github-app, the
workflow hints at deploy_gh_gl#github-actions-setup, and the sync workflow
at git_sync#github-actions (all anchors verified against the live docs).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* copy(git-sync): fork workflow hint links to git_sync#github-actions
open-pr-on-fork-commit is documented on the git_sync page, not deploy_gh_gl.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* fix(git-sync): fork PRs are opt-in on new connections too
Only auto-pull and fork sync default on for new app-backed connections;
opening pull requests stays a deliberate per-repo decision.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* feat(git-sync): default the managed PR on for new app-backed promotion repos
A promotion deploy's wm_deploy/** branch exists to be merged; without a PR
it's an orphaned branch. Fork PRs stay opt-in. Also scope the sync-repo
auto-pull default to sync mode so promotion repos can't pick it up.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* docs(git-sync): GHES self-managed app permission setup
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* docs(git-sync): frame permission update against GitHub Actions, not polling
Existing installations don't have polling; their git-to-Windmill direction
runs on GitHub Actions today, so the approval text describes the update as
replacing those workflows and notes every feature is opt-in.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PP5gBSPfo1YtkL1sWVAjJm
* copy(workspaces): drop 'cosmetic' qualifier from dev-workspace label UI
* chore: update ee-repo-ref to 9b2a6375f838436cf68cff449cc9bc621cca5281
This commit updates the EE repository reference after PR #632 was merged in windmill-ee-private.
Previous ee-repo-ref: 99eef24e2f0402b9a997cde5f67be52ee5d54b0e
New ee-repo-ref: 9b2a6375f838436cf68cff449cc9bc621cca5281
Automated by sync-ee-ref workflow.
* fix(git-sync): reject '/' in fork and dev workspace ids
* fix(git-sync): bound auto-pull git probes with a per-command timeout
* fix(git-sync): persist webhook reconcile via targeted jsonb updates
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
1087 lines
43 KiB
Python
1087 lines
43 KiB
Python
import os
|
|
import shutil
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
import uuid
|
|
|
|
import git as gitpython
|
|
|
|
from .wmill_integration_test_utils import WindmillClient, GiteaClient
|
|
|
|
|
|
# Script content template for bun/TypeScript scripts
|
|
def ts_script(body: str) -> str:
|
|
return f"export async function main() {{\n {body}\n}}\n"
|
|
|
|
|
|
def unique_name(prefix: str = "git-sync-test") -> str:
|
|
return f"{prefix}-{uuid.uuid4().hex[:8]}"
|
|
|
|
|
|
class GitSyncTestBase(unittest.TestCase):
|
|
"""Shared fixture + helpers for git sync e2e tests (no tests of its own).
|
|
|
|
setUpClass binds the client and cleanup lists on each concrete subclass,
|
|
so every test class gets its own Windmill client and cleanup scope."""
|
|
|
|
_client: WindmillClient
|
|
_gitea: GiteaClient
|
|
_repos_to_cleanup: list
|
|
_fork_workspaces_to_cleanup: list
|
|
|
|
@classmethod
|
|
def setUpClass(cls) -> None:
|
|
print("Running {}".format(cls.__name__))
|
|
cls._client = WindmillClient()
|
|
cls._gitea = GiteaClient()
|
|
cls._gitea.setup_admin()
|
|
cls._repos_to_cleanup = []
|
|
cls._fork_workspaces_to_cleanup = []
|
|
|
|
@classmethod
|
|
def tearDownClass(cls) -> None:
|
|
# Disable git sync to avoid interfering with other tests
|
|
try:
|
|
cls._client.configure_git_sync({"repositories": []})
|
|
except Exception as e:
|
|
print(f"Warning: failed to disable git sync: {e}")
|
|
|
|
for fork_id in cls._fork_workspaces_to_cleanup:
|
|
try:
|
|
cls._client.delete_workspace(fork_id)
|
|
except Exception as e:
|
|
print(f"Warning: failed to delete fork workspace {fork_id}: {e}")
|
|
|
|
for repo_name in cls._repos_to_cleanup:
|
|
cls._gitea.delete_repo(repo_name)
|
|
|
|
def setUp(self):
|
|
"""Wait for any pending deployment callbacks from previous tests to drain."""
|
|
time.sleep(2)
|
|
# Wait until no new deployment callback jobs appear for 4 seconds
|
|
prev_count = self._client.count_deployment_callback_jobs()
|
|
for _ in range(3):
|
|
time.sleep(2)
|
|
cur_count = self._client.count_deployment_callback_jobs()
|
|
if cur_count == prev_count:
|
|
break
|
|
prev_count = cur_count
|
|
|
|
def _create_test_repo(self) -> tuple:
|
|
"""Create a Gitea repo and return (repo_name, docker_clone_url)."""
|
|
name = unique_name()
|
|
docker_url = self._gitea.create_repo(name)
|
|
self._repos_to_cleanup.append(name)
|
|
return name, docker_url
|
|
|
|
def _setup_git_sync_resource(self, repo_name: str, branch: str = "main") -> str:
|
|
"""Create a git_repository resource pointing to the Gitea repo.
|
|
An empty branch leaves the field unset (repo default). Returns the
|
|
resource path."""
|
|
resource_path = f"u/admin/git_sync_{repo_name.replace('-', '_')}"
|
|
docker_url = self._gitea.get_docker_clone_url(repo_name)
|
|
self._client.create_resource(
|
|
path=resource_path,
|
|
resource_type="git_repository",
|
|
value={
|
|
"url": docker_url,
|
|
**({"branch": branch} if branch else {}),
|
|
"is_github_app": False,
|
|
},
|
|
update_if_exists=True,
|
|
)
|
|
return resource_path
|
|
|
|
def _configure_single_repo_sync(
|
|
self,
|
|
resource_path: str,
|
|
include_type=None,
|
|
include_path=None,
|
|
use_individual_branch=False,
|
|
group_by_folder=False,
|
|
):
|
|
"""Configure git sync with a single repository (auto-managed script)."""
|
|
repo_settings = {
|
|
"git_repo_resource_path": f"$res:{resource_path}",
|
|
"use_individual_branch": use_individual_branch,
|
|
"group_by_folder": group_by_folder,
|
|
}
|
|
if include_type or include_path:
|
|
repo_settings["settings"] = {
|
|
"include_type": include_type or [],
|
|
"include_path": include_path if include_path is not None else ["**"],
|
|
}
|
|
|
|
self._client.configure_git_sync({
|
|
"repositories": [repo_settings],
|
|
})
|
|
|
|
def _clone_repo(self, repo_name: str, branch: str = None) -> str:
|
|
"""Clone the repo to a temp dir and return the path."""
|
|
host_url = self._gitea.get_host_clone_url(repo_name)
|
|
tmp_dir = tempfile.mkdtemp()
|
|
self.addCleanup(shutil.rmtree, tmp_dir, ignore_errors=True)
|
|
args = {}
|
|
if branch:
|
|
args["branch"] = branch
|
|
gitpython.Repo.clone_from(host_url, tmp_dir, **args)
|
|
return tmp_dir
|
|
|
|
def _clone_repo_all_branches(self, repo_name: str) -> str:
|
|
"""Clone the repo fetching all branches."""
|
|
host_url = self._gitea.get_host_clone_url(repo_name)
|
|
tmp_dir = tempfile.mkdtemp()
|
|
self.addCleanup(shutil.rmtree, tmp_dir, ignore_errors=True)
|
|
gitpython.Repo.clone_from(host_url, tmp_dir, no_single_branch=True)
|
|
return tmp_dir
|
|
|
|
def _list_repo_files(self, repo_dir: str, branch: str = None) -> list:
|
|
"""List all tracked files in the repo (relative paths)."""
|
|
repo = gitpython.Repo(repo_dir)
|
|
if branch:
|
|
commit = repo.refs[branch].commit
|
|
else:
|
|
commit = repo.head.commit
|
|
return [item.path for item in commit.tree.traverse()]
|
|
|
|
def _read_file_content(self, repo_dir: str, file_path: str) -> str:
|
|
"""Read a file's content from the repo working tree."""
|
|
full_path = os.path.join(repo_dir, file_path)
|
|
with open(full_path, "r") as f:
|
|
return f.read()
|
|
|
|
def _get_commit_count(self, repo_dir: str, branch: str = "main") -> int:
|
|
repo = gitpython.Repo(repo_dir)
|
|
return len(list(repo.iter_commits(branch)))
|
|
|
|
def _get_last_commit_message(self, repo_dir: str, branch: str = "main") -> str:
|
|
repo = gitpython.Repo(repo_dir)
|
|
return repo.iter_commits(branch).__next__().message
|
|
|
|
def _get_branches(self, repo_dir: str) -> list:
|
|
repo = gitpython.Repo(repo_dir)
|
|
return [ref.name for ref in repo.remote().refs]
|
|
|
|
def _create_folder(self, folder_name: str):
|
|
"""Create a folder in the workspace, ignoring errors if it already exists."""
|
|
try:
|
|
self._client._client.post(
|
|
f"/api/w/{self._client._workspace}/folders/create",
|
|
json={"name": folder_name},
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
def _wait_until(self, predicate, timeout: int, interval: int = 5, message: str = ""):
|
|
"""Poll predicate() until it returns truthy or timeout (seconds) elapses.
|
|
Exceptions from the predicate count as 'not yet' (transient API errors)."""
|
|
start = time.time()
|
|
last_error = None
|
|
while time.time() - start < timeout:
|
|
try:
|
|
if predicate():
|
|
return
|
|
last_error = None
|
|
except Exception as e:
|
|
last_error = e
|
|
time.sleep(interval)
|
|
suffix = f" (last error: {last_error})" if last_error else ""
|
|
self.fail(f"Timed out after {timeout}s: {message}{suffix}")
|
|
|
|
def _find_repo_settings(self, resource_path: str) -> dict:
|
|
"""Return this workspace's stored git sync settings for the given resource."""
|
|
settings = self._client.get_workspace_settings()
|
|
for repo in (settings.get("git_sync") or {}).get("repositories", []):
|
|
if resource_path in repo.get("git_repo_resource_path", ""):
|
|
return repo
|
|
return None
|
|
|
|
def _deploy_seed_script(self, name_prefix: str) -> str:
|
|
"""Deploy a script and wait for its push to git. Returns the script path."""
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
script_path = f"u/admin/{unique_name(name_prefix)}"
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 'seed'"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
return script_path
|
|
|
|
def _repo_script_file(self, repo_name: str, script_path: str, branch: str = None) -> str:
|
|
"""Find the .ts file for a deployed script in the repo."""
|
|
repo_dir = self._clone_repo(repo_name, branch=branch)
|
|
files = self._list_repo_files(repo_dir)
|
|
matching = [f for f in files if script_path in f and f.endswith(".ts")]
|
|
self.assertTrue(
|
|
len(matching) > 0,
|
|
f"Expected '{script_path}' .ts file in repo files: {files}",
|
|
)
|
|
return matching[0]
|
|
|
|
|
|
class TestGitSync(GitSyncTestBase):
|
|
# ──────────────────────────────────────────────────
|
|
# Core happy-path tests
|
|
# ──────────────────────────────────────────────────
|
|
|
|
def test_script_deploy_syncs_to_git(self):
|
|
"""Deploy a script and verify it appears in the git repo with correct content."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(
|
|
resource_path,
|
|
include_type=["script"],
|
|
)
|
|
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
|
|
script_path = f"u/admin/{unique_name('sync_test')}"
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 42"),
|
|
language="bun",
|
|
)
|
|
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
repo_dir = self._clone_repo(repo_name)
|
|
files = self._list_repo_files(repo_dir)
|
|
|
|
# The script should appear in the repo
|
|
matching = [f for f in files if script_path in f]
|
|
self.assertTrue(
|
|
len(matching) > 0,
|
|
f"Expected script '{script_path}' in repo files: {files}",
|
|
)
|
|
|
|
# Verify file content matches what we deployed
|
|
script_file = [f for f in matching if f.endswith(".ts")][0]
|
|
content = self._read_file_content(repo_dir, script_file)
|
|
self.assertIn(
|
|
"return 42",
|
|
content,
|
|
f"Expected 'return 42' in script content: {content}",
|
|
)
|
|
|
|
def test_multi_repo_routing(self):
|
|
"""Two repos with different path filters receive the correct objects."""
|
|
repo_name_a, _ = self._create_test_repo()
|
|
repo_name_b, _ = self._create_test_repo()
|
|
res_path_a = self._setup_git_sync_resource(repo_name_a)
|
|
res_path_b = self._setup_git_sync_resource(repo_name_b)
|
|
|
|
folder_a = unique_name("folder_a")
|
|
folder_b = unique_name("folder_b")
|
|
|
|
self._client.configure_git_sync({
|
|
"repositories": [
|
|
{
|
|
"git_repo_resource_path": f"$res:{res_path_a}",
|
|
"use_individual_branch": False,
|
|
"group_by_folder": False,
|
|
"settings": {
|
|
"include_type": ["script"],
|
|
"include_path": [f"f/{folder_a}/**"],
|
|
},
|
|
},
|
|
{
|
|
"git_repo_resource_path": f"$res:{res_path_b}",
|
|
"use_individual_branch": False,
|
|
"group_by_folder": False,
|
|
"settings": {
|
|
"include_type": ["script"],
|
|
"include_path": [f"f/{folder_b}/**"],
|
|
},
|
|
},
|
|
],
|
|
})
|
|
|
|
self._create_folder(folder_a)
|
|
self._create_folder(folder_b)
|
|
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
|
|
script_a = f"f/{folder_a}/script_a"
|
|
script_b = f"f/{folder_b}/script_b"
|
|
|
|
self._client.create_script(
|
|
path=script_a,
|
|
content=ts_script("return 'a'"),
|
|
language="bun",
|
|
)
|
|
self._client.create_script(
|
|
path=script_b,
|
|
content=ts_script("return 'b'"),
|
|
language="bun",
|
|
)
|
|
|
|
# Wait for at least 2 deployment callback jobs
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=2)
|
|
time.sleep(3)
|
|
|
|
# Verify repo A has script_a but not script_b
|
|
repo_dir_a = self._clone_repo(repo_name_a)
|
|
files_a = self._list_repo_files(repo_dir_a)
|
|
self.assertTrue(
|
|
any("script_a" in f for f in files_a),
|
|
f"Expected script_a in repo A files: {files_a}",
|
|
)
|
|
self.assertFalse(
|
|
any("script_b" in f for f in files_a),
|
|
f"Did not expect script_b in repo A files: {files_a}",
|
|
)
|
|
|
|
# Verify repo B has script_b but not script_a
|
|
repo_dir_b = self._clone_repo(repo_name_b)
|
|
files_b = self._list_repo_files(repo_dir_b)
|
|
self.assertTrue(
|
|
any("script_b" in f for f in files_b),
|
|
f"Expected script_b in repo B files: {files_b}",
|
|
)
|
|
self.assertFalse(
|
|
any("script_a" in f for f in files_b),
|
|
f"Did not expect script_a in repo B files: {files_b}",
|
|
)
|
|
|
|
def test_script_update_creates_new_commit_with_updated_content(self):
|
|
"""Updating a script should produce a new commit with the new content."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(resource_path, include_type=["script"])
|
|
|
|
script_path = f"u/admin/{unique_name('update_test')}"
|
|
|
|
# Create initial script
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 1"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
repo_dir = self._clone_repo(repo_name)
|
|
initial_commits = self._get_commit_count(repo_dir)
|
|
|
|
# Update the script
|
|
update_count = self._client.count_deployment_callback_jobs()
|
|
self._client.update_script(
|
|
path=script_path,
|
|
content=ts_script("return 2"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(update_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
# Re-clone and check commit count increased
|
|
repo_dir2 = self._clone_repo(repo_name)
|
|
new_commits = self._get_commit_count(repo_dir2)
|
|
self.assertGreater(
|
|
new_commits,
|
|
initial_commits,
|
|
f"Expected more commits after update: {new_commits} vs {initial_commits}",
|
|
)
|
|
|
|
# Verify file content reflects the update
|
|
files = self._list_repo_files(repo_dir2)
|
|
script_file = [f for f in files if script_path in f and f.endswith(".ts")][0]
|
|
content = self._read_file_content(repo_dir2, script_file)
|
|
self.assertIn(
|
|
"return 2",
|
|
content,
|
|
f"Expected 'return 2' in updated script content: {content}",
|
|
)
|
|
self.assertNotIn(
|
|
"return 1",
|
|
content,
|
|
f"Did not expect 'return 1' in updated script content: {content}",
|
|
)
|
|
|
|
def test_deploy_multiple_object_types(self):
|
|
"""Deploy a script, flow, and variable and verify all appear in the repo."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(
|
|
resource_path,
|
|
include_type=["script", "flow", "variable"],
|
|
)
|
|
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
|
|
suffix = unique_name("multi")
|
|
script_path = f"u/admin/{suffix}_script"
|
|
flow_path = f"u/admin/{suffix}_flow"
|
|
var_path = f"u/admin/{suffix}_var"
|
|
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 'multi'"),
|
|
language="bun",
|
|
)
|
|
self._client.create_flow(
|
|
path=flow_path,
|
|
flow_value_json="""{
|
|
"summary": "test flow",
|
|
"value": {
|
|
"modules": [{
|
|
"id": "a",
|
|
"value": {
|
|
"type": "rawscript",
|
|
"content": "export async function main() { return 1 }",
|
|
"language": "bun",
|
|
"input_transforms": {},
|
|
"tag": ""
|
|
}
|
|
}]
|
|
},
|
|
"schema": {
|
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
"properties": {},
|
|
"required": [],
|
|
"type": "object",
|
|
"order": []
|
|
}
|
|
}""",
|
|
)
|
|
self._client.create_variable(
|
|
path=var_path,
|
|
value="test_value",
|
|
)
|
|
|
|
# Wait for 3 deployment callbacks (one per object)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=3)
|
|
time.sleep(3)
|
|
|
|
repo_dir = self._clone_repo(repo_name)
|
|
files = self._list_repo_files(repo_dir)
|
|
files_str = "\n".join(files)
|
|
|
|
self.assertTrue(
|
|
any(suffix + "_script" in f for f in files),
|
|
f"Expected script in repo:\n{files_str}",
|
|
)
|
|
self.assertTrue(
|
|
any(suffix + "_flow" in f for f in files),
|
|
f"Expected flow in repo:\n{files_str}",
|
|
)
|
|
self.assertTrue(
|
|
any(suffix + "_var" in f for f in files),
|
|
f"Expected variable in repo:\n{files_str}",
|
|
)
|
|
|
|
# ──────────────────────────────────────────────────
|
|
# Commit message verification
|
|
# ──────────────────────────────────────────────────
|
|
|
|
def test_commit_message_format(self):
|
|
"""Verify commit messages have the [WM] prefix."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(resource_path, include_type=["script"])
|
|
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
script_path = f"u/admin/{unique_name('commit_msg')}"
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 'msg'"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
repo_dir = self._clone_repo(repo_name)
|
|
commit_msg = self._get_last_commit_message(repo_dir)
|
|
|
|
self.assertTrue(
|
|
commit_msg.startswith("[WM]"),
|
|
f"Expected commit message to start with '[WM]', got: {commit_msg!r}",
|
|
)
|
|
|
|
# ──────────────────────────────────────────────────
|
|
# Rename handling
|
|
# ──────────────────────────────────────────────────
|
|
|
|
def test_rename_removes_old_file(self):
|
|
"""Renaming a script should remove the old file and create the new one."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(resource_path, include_type=["script"])
|
|
|
|
old_path = f"u/admin/{unique_name('rename_old')}"
|
|
|
|
# Create initial script
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
self._client.create_script(
|
|
path=old_path,
|
|
content=ts_script("return 'old'"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
# Verify old script exists in repo
|
|
repo_dir = self._clone_repo(repo_name)
|
|
files = self._list_repo_files(repo_dir)
|
|
old_name = old_path.split("/")[-1]
|
|
self.assertTrue(
|
|
any(old_name in f for f in files),
|
|
f"Expected old script '{old_name}' in repo: {files}",
|
|
)
|
|
|
|
# Create new script at different path (simulates rename)
|
|
new_path = f"u/admin/{unique_name('rename_new')}"
|
|
rename_count = self._client.count_deployment_callback_jobs()
|
|
self._client.create_script(
|
|
path=new_path,
|
|
content=ts_script("return 'renamed'"),
|
|
language="bun",
|
|
)
|
|
# Also delete the old script
|
|
self._client.delete_script(old_path)
|
|
# Wait for both create and delete deployment callbacks
|
|
self._client.wait_for_sync_jobs(rename_count, min_new=2)
|
|
time.sleep(3)
|
|
|
|
# Verify new script exists
|
|
repo_dir2 = self._clone_repo(repo_name)
|
|
files2 = self._list_repo_files(repo_dir2)
|
|
new_name = new_path.split("/")[-1]
|
|
self.assertTrue(
|
|
any(new_name in f for f in files2),
|
|
f"Expected new script '{new_name}' in repo: {files2}",
|
|
)
|
|
self.assertFalse(
|
|
any(old_name in f for f in files2),
|
|
f"Expected old script '{old_name}' to be removed: {files2}",
|
|
)
|
|
|
|
# ──────────────────────────────────────────────────
|
|
# Promotion mode (individual branches)
|
|
# ──────────────────────────────────────────────────
|
|
|
|
def test_promotion_mode_creates_per_object_branches(self):
|
|
"""In promotion mode (use_individual_branch=True), each deploy creates
|
|
a branch named wm_deploy/{workspace}/{path_type}/{path} with the content
|
|
on that branch, not on main."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(
|
|
resource_path,
|
|
include_type=["script"],
|
|
use_individual_branch=True,
|
|
)
|
|
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
script_path = f"u/admin/{unique_name('promo')}"
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 'promotion'"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
# Clone with all branches
|
|
repo_dir = self._clone_repo_all_branches(repo_name)
|
|
branches = self._get_branches(repo_dir)
|
|
|
|
# Should have a branch matching wm_deploy pattern
|
|
wm_branches = [b for b in branches if "wm_deploy/" in b]
|
|
self.assertTrue(
|
|
len(wm_branches) > 0,
|
|
f"Expected wm_deploy/ branch, got branches: {branches}",
|
|
)
|
|
|
|
# The branch name should contain 'script' (the path_type)
|
|
deploy_branch = wm_branches[0]
|
|
self.assertIn(
|
|
"script",
|
|
deploy_branch,
|
|
f"Expected 'script' in branch name: {deploy_branch}",
|
|
)
|
|
|
|
# The script path (with / replaced by __) should appear in the branch name
|
|
script_name = script_path.split("/")[-1]
|
|
self.assertIn(
|
|
script_name,
|
|
deploy_branch.replace("/", "__"),
|
|
f"Expected script name '{script_name}' in branch: {deploy_branch}",
|
|
)
|
|
|
|
# Verify main branch does NOT have the script
|
|
main_files = self._list_repo_files(repo_dir, branch="origin/main")
|
|
self.assertFalse(
|
|
any(script_name in f for f in main_files),
|
|
f"Did not expect script on main branch, but found it: {main_files}",
|
|
)
|
|
|
|
# Verify the deploy branch HAS the script
|
|
local_branch_name = deploy_branch.replace("origin/", "")
|
|
repo = gitpython.Repo(repo_dir)
|
|
repo.git.checkout(local_branch_name)
|
|
branch_files = self._list_repo_files(repo_dir)
|
|
self.assertTrue(
|
|
any(script_name in f for f in branch_files),
|
|
f"Expected script on deploy branch '{local_branch_name}': {branch_files}",
|
|
)
|
|
|
|
def test_promotion_mode_group_by_folder(self):
|
|
"""With use_individual_branch=True and group_by_folder=True, the branch name
|
|
uses the folder prefix (first 2 path segments joined by __) instead of the
|
|
full path."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(
|
|
resource_path,
|
|
include_type=["script"],
|
|
use_individual_branch=True,
|
|
group_by_folder=True,
|
|
)
|
|
|
|
folder_name = unique_name("grp")
|
|
self._create_folder(folder_name)
|
|
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
script_path = f"f/{folder_name}/{unique_name('grp_script')}"
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 'grouped'"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
repo_dir = self._clone_repo_all_branches(repo_name)
|
|
branches = self._get_branches(repo_dir)
|
|
|
|
wm_branches = [b for b in branches if "wm_deploy/" in b]
|
|
self.assertTrue(
|
|
len(wm_branches) > 0,
|
|
f"Expected wm_deploy/ branch with group_by_folder: {branches}",
|
|
)
|
|
|
|
# With group_by_folder, the branch should contain the folder prefix
|
|
# format: wm_deploy/{workspace}/f__{folder_name}
|
|
deploy_branch = wm_branches[0]
|
|
expected_folder_part = f"f__{folder_name}"
|
|
self.assertIn(
|
|
expected_folder_part,
|
|
deploy_branch,
|
|
f"Expected folder-grouped branch name containing '{expected_folder_part}', got: {deploy_branch}",
|
|
)
|
|
|
|
# ──────────────────────────────────────────────────
|
|
# Exclude path filtering
|
|
# ──────────────────────────────────────────────────
|
|
|
|
def test_exclude_path_filtering(self):
|
|
"""Scripts in excluded paths should not be synced to the repo."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
|
|
folder_inc = unique_name("inc")
|
|
folder_exc = unique_name("exc")
|
|
self._create_folder(folder_inc)
|
|
self._create_folder(folder_exc)
|
|
|
|
self._client.configure_git_sync({
|
|
"repositories": [{
|
|
"git_repo_resource_path": f"$res:{resource_path}",
|
|
"use_individual_branch": False,
|
|
"group_by_folder": False,
|
|
"settings": {
|
|
"include_type": ["script"],
|
|
"include_path": ["f/**"],
|
|
"exclude_path": [f"f/{folder_exc}/**"],
|
|
},
|
|
}],
|
|
})
|
|
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
|
|
script_inc = f"f/{folder_inc}/included_script"
|
|
script_exc = f"f/{folder_exc}/excluded_script"
|
|
|
|
self._client.create_script(
|
|
path=script_inc,
|
|
content=ts_script("return 'included'"),
|
|
language="bun",
|
|
)
|
|
self._client.create_script(
|
|
path=script_exc,
|
|
content=ts_script("return 'excluded'"),
|
|
language="bun",
|
|
)
|
|
|
|
# Only 1 sync job expected (the excluded one should not trigger)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(5)
|
|
# Verify no extra sync jobs arrived for the excluded script
|
|
final_count = self._client.count_deployment_callback_jobs()
|
|
self.assertEqual(
|
|
final_count, initial_count + 1,
|
|
f"Expected exactly 1 new sync job, got {final_count - initial_count}",
|
|
)
|
|
|
|
repo_dir = self._clone_repo(repo_name)
|
|
files = self._list_repo_files(repo_dir)
|
|
|
|
self.assertTrue(
|
|
any("included_script" in f for f in files),
|
|
f"Expected included_script in repo: {files}",
|
|
)
|
|
self.assertFalse(
|
|
any("excluded_script" in f for f in files),
|
|
f"Did not expect excluded_script in repo: {files}",
|
|
)
|
|
|
|
# ──────────────────────────────────────────────────
|
|
# Workspace fork
|
|
# ──────────────────────────────────────────────────
|
|
|
|
def test_workspace_fork_creates_branch(self):
|
|
"""Forking a workspace with git sync configured should create a
|
|
fork branch in the git repo."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
|
|
# Configure git sync on the parent workspace (sync mode, not promotion)
|
|
self._configure_single_repo_sync(
|
|
resource_path,
|
|
include_type=["script"],
|
|
)
|
|
|
|
# Deploy a script first so there's content in the repo
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
script_path = f"u/admin/{unique_name('fork_base')}"
|
|
self._client.create_script(
|
|
path=script_path,
|
|
content=ts_script("return 'base'"),
|
|
language="bun",
|
|
)
|
|
self._client.wait_for_sync_jobs(initial_count, min_new=1)
|
|
time.sleep(3)
|
|
|
|
# Create workspace fork
|
|
fork_id = f"wm-fork-{uuid.uuid4().hex[:8]}"
|
|
fork_name = f"Fork {fork_id}"
|
|
self._fork_workspaces_to_cleanup.append(fork_id)
|
|
|
|
# Step 1: Create git branches for the fork
|
|
job_ids = self._client.create_workspace_fork_branch(fork_id, fork_name)
|
|
if job_ids:
|
|
self._client.wait_for_jobs_by_ids(job_ids, timeout=90)
|
|
time.sleep(3)
|
|
|
|
# Step 2: Create the fork workspace
|
|
self._client.create_workspace_fork(fork_id, fork_name)
|
|
|
|
# Verify a fork branch was created in the git repo
|
|
repo_dir = self._clone_repo_all_branches(repo_name)
|
|
branches = self._get_branches(repo_dir)
|
|
|
|
# Fork branches are named: wm-fork/{original_branch}/{fork_id}
|
|
fork_branches = [b for b in branches if "wm-fork" in b]
|
|
self.assertTrue(
|
|
len(fork_branches) > 0,
|
|
f"Expected a wm-fork branch in the repo after forking, got: {branches}",
|
|
)
|
|
|
|
|
|
class TestGitSyncAutoPull(GitSyncTestBase):
|
|
"""Auto-pull (git → Windmill, EE): polling, fork-branch routing, settings
|
|
semantics. Webhook delivery and PR features need a GitHub App and are
|
|
covered by manual verification instead."""
|
|
|
|
# The poller visits repos about once a minute; a pull then runs as a job.
|
|
# Two poll cycles + job execution, with slack for a loaded CI runner.
|
|
PULL_TIMEOUT = 240
|
|
|
|
def _seed_wmill_yaml(self, repo_name: str, branch: str = "main"):
|
|
"""Commit a minimal wmill.yaml: the pull CLI requires one in the repo.
|
|
Real setups get it from the init/settings-push flow; pushes alone
|
|
don't write it."""
|
|
self._gitea.create_file(
|
|
repo_name,
|
|
"wmill.yaml",
|
|
"defaultTs: bun\n"
|
|
"includes:\n"
|
|
' - "**"\n'
|
|
"excludes: []\n"
|
|
"codebases: []\n"
|
|
"skipVariables: true\n"
|
|
"skipResources: true\n"
|
|
"skipResourceTypes: true\n"
|
|
"skipSecrets: true\n"
|
|
"includeSchedules: false\n"
|
|
"includeTriggers: false\n",
|
|
branch=branch,
|
|
)
|
|
|
|
def _configure_auto_pull(self, resource_path: str, sync_forks: bool = False):
|
|
"""Single sync repo with auto-pull enabled in polling mode."""
|
|
auto_pull = {"enabled": True, "mode": "polling"}
|
|
if sync_forks:
|
|
auto_pull["sync_forks"] = True
|
|
self._client.configure_git_sync({
|
|
"repositories": [{
|
|
"git_repo_resource_path": f"$res:{resource_path}",
|
|
"use_individual_branch": False,
|
|
"group_by_folder": False,
|
|
"settings": {
|
|
"include_type": ["script"],
|
|
"include_path": ["**"],
|
|
},
|
|
"auto_pull": auto_pull,
|
|
}],
|
|
})
|
|
|
|
def test_polling_applies_remote_commit(self):
|
|
"""A commit pushed to the tracked branch is deployed into the workspace
|
|
by the poller, the pull status is recorded, and the resulting no-op
|
|
push callback does not add a commit (no sync loop)."""
|
|
repo_name, _ = self._create_test_repo()
|
|
# Branch-less resource: the poller resolves the repo's default branch
|
|
# via ls-remote --symref (a bare HEAD ref would disable fork scoping).
|
|
resource_path = self._setup_git_sync_resource(repo_name, branch="")
|
|
self._configure_single_repo_sync(resource_path, include_type=["script"])
|
|
|
|
# Seed the repo through a normal deploy, then find the script's file.
|
|
script_path = self._deploy_seed_script("autopull")
|
|
script_file = self._repo_script_file(repo_name, script_path)
|
|
self._seed_wmill_yaml(repo_name)
|
|
|
|
self._configure_auto_pull(resource_path)
|
|
|
|
# External commit on the tracked branch (not [WM]-prefixed).
|
|
self._gitea.create_file(
|
|
repo_name, script_file, ts_script("return 'pulled from git'")
|
|
)
|
|
|
|
self._wait_until(
|
|
lambda: "pulled from git" in self._client.get_script_content(script_path),
|
|
timeout=self.PULL_TIMEOUT,
|
|
message=f"workspace script {script_path} was not updated from git",
|
|
)
|
|
|
|
# Pull status is recorded on the repo settings.
|
|
repo_settings = self._find_repo_settings(resource_path)
|
|
status = (repo_settings.get("auto_pull") or {}).get("last_pull_status") or {}
|
|
self.assertTrue(
|
|
status.get("success"),
|
|
f"Expected successful last_pull_status, got: {repo_settings.get('auto_pull')}",
|
|
)
|
|
|
|
# The pull-caused deploy triggers a push callback; since the workspace
|
|
# now matches the repo it must not create a commit (loop safety).
|
|
time.sleep(10)
|
|
repo_dir = self._clone_repo(repo_name)
|
|
last_msg = self._get_last_commit_message(repo_dir)
|
|
self.assertIn(
|
|
script_file,
|
|
last_msg,
|
|
f"Expected the external commit to stay the branch head (no [WM] "
|
|
f"loop commit), got: {last_msg!r}",
|
|
)
|
|
|
|
# A whole-config resave without server-owned fields (what a UI/CLI
|
|
# round-trip sends) must not clobber the recorded pull state.
|
|
self._configure_auto_pull(resource_path)
|
|
repo_settings = self._find_repo_settings(resource_path)
|
|
status = (repo_settings.get("auto_pull") or {}).get("last_pull_status") or {}
|
|
self.assertTrue(
|
|
status.get("success"),
|
|
f"Expected last_pull_status to survive a config resave, got: "
|
|
f"{repo_settings.get('auto_pull')}",
|
|
)
|
|
|
|
def test_fork_branch_commit_deploys_into_fork(self):
|
|
"""With sync_forks on the parent, a commit on a fork's wm-fork/** branch
|
|
is deployed into the fork workspace and leaves the parent untouched."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(resource_path, include_type=["script"])
|
|
|
|
script_path = self._deploy_seed_script("forkpull")
|
|
script_file = self._repo_script_file(repo_name, script_path)
|
|
# Seed before the fork branch is created so the branch inherits it.
|
|
self._seed_wmill_yaml(repo_name)
|
|
|
|
self._configure_auto_pull(resource_path, sync_forks=True)
|
|
|
|
# Create the fork (branch first, then workspace), like the UI does.
|
|
fork_id = f"wm-fork-{uuid.uuid4().hex[:8]}"
|
|
self._fork_workspaces_to_cleanup.append(fork_id)
|
|
job_ids = self._client.create_workspace_fork_branch(fork_id, f"Fork {fork_id}")
|
|
if job_ids:
|
|
self._client.wait_for_jobs_by_ids(job_ids, timeout=90)
|
|
time.sleep(3)
|
|
self._client.create_workspace_fork(fork_id, f"Fork {fork_id}")
|
|
|
|
fork_branch = f"wm-fork/main/{fork_id[len('wm-fork-'):]}"
|
|
self._gitea.create_file(
|
|
repo_name, script_file, ts_script("return 'fork only'"),
|
|
branch=fork_branch,
|
|
)
|
|
|
|
fork_client = WindmillClient(workspace=fork_id)
|
|
self._wait_until(
|
|
lambda: "fork only" in fork_client.get_script_content(script_path),
|
|
timeout=self.PULL_TIMEOUT,
|
|
message=f"fork workspace {fork_id} did not receive the fork-branch commit",
|
|
)
|
|
|
|
# The parent workspace must not see the fork-branch content.
|
|
self.assertNotIn(
|
|
"fork only",
|
|
self._client.get_script_content(script_path),
|
|
"Parent workspace received a commit from a fork branch",
|
|
)
|
|
|
|
def test_settings_normalization_and_redaction(self):
|
|
"""Webhook mode on a token repo is persisted as polling; server-owned
|
|
webhook fields are never exposed; legacy repos gain no auto_pull key."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
|
|
# Token-based repos can't register webhooks: a webhook-mode save is
|
|
# normalized to polling and that normalization is persisted.
|
|
self._client.configure_git_sync({
|
|
"repositories": [{
|
|
"git_repo_resource_path": f"$res:{resource_path}",
|
|
"use_individual_branch": False,
|
|
"group_by_folder": False,
|
|
"settings": {"include_type": ["script"], "include_path": ["**"]},
|
|
"auto_pull": {"enabled": True, "mode": "webhook"},
|
|
}],
|
|
})
|
|
repo_settings = self._find_repo_settings(resource_path)
|
|
auto_pull = repo_settings.get("auto_pull") or {}
|
|
self.assertEqual(
|
|
auto_pull.get("mode"),
|
|
"polling",
|
|
f"Expected webhook mode to normalize to polling on a token repo: {auto_pull}",
|
|
)
|
|
self.assertNotIn("webhook_secret", auto_pull)
|
|
self.assertIsNone(auto_pull.get("webhook_id"))
|
|
|
|
# A repo saved without auto_pull stays without it (legacy round-trip).
|
|
self._configure_single_repo_sync(resource_path, include_type=["script"])
|
|
repo_settings = self._find_repo_settings(resource_path)
|
|
self.assertIsNone(
|
|
repo_settings.get("auto_pull"),
|
|
f"Legacy repo config unexpectedly gained auto_pull: {repo_settings}",
|
|
)
|
|
|
|
def test_fork_rejects_parent_only_git_sync_settings(self):
|
|
"""Fork workspaces cannot enable auto-pull, promotion mode, or
|
|
fork-PR creation on their own git sync settings."""
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = self._setup_git_sync_resource(repo_name)
|
|
self._configure_single_repo_sync(resource_path, include_type=["script"])
|
|
|
|
fork_id = f"wm-fork-{uuid.uuid4().hex[:8]}"
|
|
self._fork_workspaces_to_cleanup.append(fork_id)
|
|
self._client.create_workspace_fork(fork_id, f"Fork {fork_id}")
|
|
fork_client = WindmillClient(workspace=fork_id)
|
|
|
|
base_repo = {"git_repo_resource_path": f"$res:{resource_path}"}
|
|
rejected = [
|
|
{**base_repo, "auto_pull": {"enabled": True, "mode": "polling"}},
|
|
{**base_repo, "use_individual_branch": True},
|
|
{**base_repo, "fork_open_prs": True},
|
|
]
|
|
for repo in rejected:
|
|
response = fork_client.edit_git_sync_repository(
|
|
f"$res:{resource_path}", repo
|
|
)
|
|
self.assertEqual(
|
|
response.status_code,
|
|
400,
|
|
f"Expected 400 saving {repo} on a fork, got "
|
|
f"{response.status_code}: {response.content.decode()}",
|
|
)
|
|
|
|
def test_attach_dev_workspace_strips_auto_pull(self):
|
|
"""Attaching a workspace as a dev workspace strips its own auto-pull:
|
|
dev/fork sync is parent-managed, so a pre-attach auto-pull must not
|
|
keep pulling the old tracked branch."""
|
|
candidate_id = f"it-dev-cand-{uuid.uuid4().hex[:8]}"
|
|
self._fork_workspaces_to_cleanup.append(candidate_id)
|
|
candidate = WindmillClient(workspace=candidate_id)
|
|
|
|
repo_name, _ = self._create_test_repo()
|
|
resource_path = f"u/admin/git_sync_{repo_name.replace('-', '_')}"
|
|
candidate.create_resource(
|
|
path=resource_path,
|
|
resource_type="git_repository",
|
|
value={
|
|
"url": self._gitea.get_docker_clone_url(repo_name),
|
|
"branch": "main",
|
|
"is_github_app": False,
|
|
},
|
|
update_if_exists=True,
|
|
)
|
|
candidate.configure_git_sync({
|
|
"repositories": [{
|
|
"git_repo_resource_path": f"$res:{resource_path}",
|
|
"use_individual_branch": False,
|
|
"group_by_folder": False,
|
|
"settings": {"include_type": ["script"], "include_path": ["**"]},
|
|
"auto_pull": {"enabled": True, "mode": "polling"},
|
|
}],
|
|
})
|
|
|
|
response = self._client._client.post(
|
|
f"/api/w/{self._client._workspace}/workspaces/attach_dev_workspace",
|
|
json={"dev_workspace_id": candidate_id, "dev_workspace_label": "dev"},
|
|
)
|
|
self.assertEqual(
|
|
response.status_code // 100,
|
|
2,
|
|
f"attach_dev_workspace failed: {response.content.decode()}",
|
|
)
|
|
|
|
repo_settings = None
|
|
for repo in (candidate.get_workspace_settings().get("git_sync") or {}).get(
|
|
"repositories", []
|
|
):
|
|
if resource_path in repo.get("git_repo_resource_path", ""):
|
|
repo_settings = repo
|
|
self.assertIsNotNone(repo_settings, "candidate lost its sync repo on attach")
|
|
self.assertIsNone(
|
|
repo_settings.get("auto_pull"),
|
|
f"auto_pull survived the attach: {repo_settings}",
|
|
)
|
|
|
|
def test_webhook_receiver_ignores_unknown_deliveries(self):
|
|
"""An unsolicited webhook delivery (no registered hook) is not an error
|
|
and enqueues nothing."""
|
|
initial_count = self._client.count_deployment_callback_jobs()
|
|
response = self._client._client.post(
|
|
f"/api/w/{self._client._workspace}/github_app/webhook",
|
|
json={"ref": "refs/heads/main", "after": "0" * 40},
|
|
headers={
|
|
"X-GitHub-Event": "push",
|
|
"X-GitHub-Hook-ID": "999999999",
|
|
"X-Hub-Signature-256": "sha256=" + "0" * 64,
|
|
},
|
|
)
|
|
self.assertLess(
|
|
response.status_code,
|
|
500,
|
|
f"Webhook receiver errored on unknown delivery: "
|
|
f"{response.status_code} {response.content.decode()}",
|
|
)
|
|
time.sleep(3)
|
|
self.assertEqual(
|
|
self._client.count_deployment_callback_jobs(),
|
|
initial_count,
|
|
"Unknown webhook delivery enqueued a job",
|
|
)
|