Skip to content

Modern Docker Management, Designed for Everyone

feat: git repo sync for compose projects (#1089)

Kyle Mendell10ac44bcce4a
diff --git a/.gitignore b/.gitignore
index 87db1b50d..cd1d539a3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -40,3 +40,4 @@ tests/package-lock.json
.pnpm-store/**
.pnpm-store
.claude/settings.local.json
+.claude/**
diff --git a/backend/go.mod b/backend/go.mod
index 00a08e2e2..9a3c463c9 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -19,6 +19,7 @@ require (
github.com/gin-contrib/cors v1.7.6
github.com/gin-gonic/gin v1.11.0
github.com/glebarez/sqlite v1.11.0
+ github.com/go-git/go-git/v5 v5.16.4
github.com/go-co-op/gocron/v2 v2.19.0
github.com/goccy/go-yaml v1.19.1
github.com/golang-jwt/jwt/v5 v5.3.0
@@ -46,9 +47,11 @@ require (
)
require (
+ dario.cat/mergo v1.0.2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/DefangLabs/secret-detector v0.0.0-20250811234530-d4b4214cd679 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
+ github.com/ProtonMail/go-crypto v1.3.0 // indirect
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/goterm v1.0.4 // indirect
@@ -58,6 +61,7 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
+ github.com/cloudflare/circl v1.6.1 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/containerd/console v1.0.5 // indirect
github.com/containerd/containerd/api v1.10.0 // indirect
@@ -69,6 +73,7 @@ require (
github.com/containerd/platforms v1.0.0-rc.2 // indirect
github.com/containerd/ttrpc v1.2.7 // indirect
github.com/containerd/typeurl/v2 v2.2.3 // indirect
+ github.com/cyphar/filepath-securejoin v0.4.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/buildx v0.30.1 // indirect
@@ -80,12 +85,15 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.9.1 // indirect
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 // indirect
+ github.com/emirpasic/gods v1.18.1 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsevents v0.2.0 // indirect
github.com/fvbommel/sortorder v1.1.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.10 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
+ github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
+ github.com/go-git/go-billy/v5 v5.6.2 // indirect
github.com/go-jose/go-jose/v4 v4.1.3 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
@@ -97,6 +105,7 @@ require (
github.com/goccy/go-json v0.10.5 // indirect
github.com/gofrs/flock v0.13.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
+ github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
@@ -112,10 +121,12 @@ require (
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.7.6 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
+ github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jonboulle/clockwork v0.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
+ github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/klauspost/compress v1.18.1 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
@@ -149,6 +160,7 @@ require (
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
+ github.com/pjbgf/sha1cd v0.3.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
@@ -163,8 +175,10 @@ require (
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
github.com/secure-systems-lab/go-securesystemslib v0.9.1 // indirect
+ github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
github.com/shibumi/go-pathspec v1.3.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
+ github.com/skeema/knownhosts v1.3.1 // indirect
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/theupdateframework/notary v0.7.0 // indirect
@@ -178,6 +192,7 @@ require (
github.com/tonistiigi/vt100 v0.0.0-20240514184818-90bafcd6abab // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
+ github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xhit/go-str2duration/v2 v2.1.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
@@ -208,6 +223,7 @@ require (
google.golang.org/grpc v1.77.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
+ gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.66.8 // indirect
modernc.org/mathutil v1.7.1 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 4f31a9300..8ba99034d 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -1,3 +1,5 @@
+dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
+dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
@@ -7,10 +9,13 @@ github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/DefangLabs/secret-detector v0.0.0-20250811234530-d4b4214cd679 h1:qNT7R4qrN+5u5ajSbqSW1opHP4LA8lzA+ASyw5MQZjs=
github.com/DefangLabs/secret-detector v0.0.0-20250811234530-d4b4214cd679/go.mod h1:blbwPQh4DTlCZEfk1BLU4oMIhLda2U+A840Uag9DsZw=
+github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/Microsoft/hcsshim v0.14.0-rc.1 h1:qAPXKwGOkVn8LlqgBN8GS0bxZ83hOJpcjxzmlQKxKsQ=
github.com/Microsoft/hcsshim v0.14.0-rc.1/go.mod h1:hTKFGbnDtQb1wHiOWv4v0eN+7boSWAHyK/tNAaYZL0c=
+github.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBiRGFrw=
+github.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE=
github.com/Shopify/logrus-bugsnag v0.0.0-20170309145241-6dbc35f2c30d h1:hi6J4K6DKrR4/ljxn6SF6nURyu785wKMuQcjt7H3VCQ=
github.com/Shopify/logrus-bugsnag v0.0.0-20170309145241-6dbc35f2c30d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
@@ -19,6 +24,10 @@ github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuy
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/anchore/go-struct-converter v0.0.0-20221118182256-c68fdcfa2092 h1:aM1rlcoLz8y5B2r4tTLMiVTrMtpfY0O8EScKJxaSaEc=
github.com/anchore/go-struct-converter v0.0.0-20221118182256-c68fdcfa2092/go.mod h1:rYqSE9HbjzpHTI74vwPvae4ZVYZd1lue2ta6xHPdblA=
+github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
+github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
+github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
+github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/beorn7/perks v0.0.0-20150223135152-b965b613227f/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
@@ -51,6 +60,8 @@ github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuh
github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/cloudflare/cfssl v0.0.0-20180223231731-4e2dcbde5004 h1:lkAMpLVBDaj17e85keuznYcH5rqI438v41pKcBl4ZxQ=
github.com/cloudflare/cfssl v0.0.0-20180223231731-4e2dcbde5004/go.mod h1:yMWuSON2oQp+43nFtAV/uvKQIFpSPerB57DCt9t8sSA=
+github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=
+github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb h1:EDmT6Q9Zs+SbUoc7Ik9EfrFqcylYqgPZ9ANSbTAntnE=
@@ -94,6 +105,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
+github.com/cyphar/filepath-securejoin v0.4.1 h1:JyxxyPEaktOD+GAnqIqTf9A8tHyAG22rowi7HkoSU1s=
+github.com/cyphar/filepath-securejoin v0.4.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI=
github.com/danielgtaylor/huma/v2 v2.34.1 h1:EmOJAbzEGfy0wAq/QMQ1YKfEMBEfE94xdBRLPBP0gwQ=
github.com/danielgtaylor/huma/v2 v2.34.1/go.mod h1:ynwJgLk8iGVgoaipi5tgwIQ5yoFNmiu+QdhU7CEEmhk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -141,10 +154,14 @@ github.com/ebitengine/purego v0.9.1 h1:a/k2f2HQU3Pi399RPW1MOaZyhKJL9w/xFpKAg4q1s
github.com/ebitengine/purego v0.9.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 h1:XBBHcIb256gUJtLmY22n99HaZTz+r2Z51xUPi01m3wg=
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203/go.mod h1:E1jcSv8FaEny+OP/5k9UxZVw9YFWGj7eI4KR/iOBqCg=
+github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
+github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 h1:oP4q0fw+fOSWn3DfFi4EXdT+B+gTtzx8GC9xsc26Znk=
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6/go.mod h1:iL2twTeMvZnrg54ZoPDNfJaJaqy0xIQFuBdrLsmspwQ=
github.com/emersion/go-smtp v0.24.0 h1:g6AfoF140mvW0vLNPD/LuCBLEAdlxOjIXqbIkJIS6Wk=
github.com/emersion/go-smtp v0.24.0/go.mod h1:ZtRRkbTyp2XTHCA+BmyTFTrj8xY4I+b4McvHxCU2gsQ=
+github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
+github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
@@ -171,8 +188,18 @@ github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
+github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
+github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-co-op/gocron/v2 v2.19.0 h1:OKf2y6LXPs/BgBI2fl8PxUpNAI1DA9Mg+hSeGOS38OU=
github.com/go-co-op/gocron/v2 v2.19.0/go.mod h1:5lEiCKk1oVJV39Zg7/YG10OnaVrDAV5GGR6O0663k6U=
+github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
+github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
+github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
+github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
+github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
+github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
+github.com/go-git/go-git/v5 v5.16.4 h1:7ajIEZHZJULcyJebDLo99bGgS0jRrOxzZG4uCk2Yb2Y=
+github.com/go-git/go-git/v5 v5.16.4/go.mod h1:4Ge4alE/5gPs30F2H1esi2gPd69R0C39lolkucHBOp8=
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
@@ -269,6 +296,8 @@ github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
+github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
github.com/jinzhu/gorm v0.0.0-20170222002820-5409931a1bb8 h1:CZkYfurY6KGhVtlalI4QwQ6T0Cu6iuY3e0x5RLu96WE=
@@ -289,6 +318,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
+github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
+github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co=
@@ -385,6 +416,8 @@ github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W
github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA=
+github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k=
+github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY=
github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
@@ -403,6 +436,8 @@ github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3v
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
+github.com/pjbgf/sha1cd v0.3.2 h1:a9wb0bp1oC2TGwStyn0Umc/IGKQnEgF0vVaZ8QF8eo4=
+github.com/pjbgf/sha1cd v0.3.2/go.mod h1:zQWigSxVmsHEZow5qaLtPYxpcKMMQpa09ixqBxuCS6A=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
@@ -453,6 +488,8 @@ github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEV
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/secure-systems-lab/go-securesystemslib v0.9.1 h1:nZZaNz4DiERIQguNy0cL5qTdn9lR8XKHf4RUyG1Sx3g=
github.com/secure-systems-lab/go-securesystemslib v0.9.1/go.mod h1:np53YzT0zXGMv6x4iEWc9Z59uR+x+ndLwCLqPYpLXVU=
+github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8=
+github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/shibumi/go-pathspec v1.3.0 h1:QUyMZhFo0Md5B8zV8x2tesohbb5kfbpTi9rBnKh5dkI=
github.com/shibumi/go-pathspec v1.3.0/go.mod h1:Xutfslp817l2I1cZvgcfeMQJG5QnU2lh5tVaaMCl3jE=
github.com/shirou/gopsutil/v4 v4.25.12 h1:e7PvW/0RmJ8p8vPGJH4jvNkOyLmbkXgXW4m6ZPic6CY=
@@ -460,8 +497,11 @@ github.com/shirou/gopsutil/v4 v4.25.12/go.mod h1:EivAfP5x2EhLp2ovdpKSozecVXn1Tmu
github.com/sirupsen/logrus v1.0.6/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
+github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
+github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
github.com/spdx/tools-golang v0.5.5 h1:61c0KLfAcNqAjlg6UNMdkwpMernhw3zVRwDZ2x9XOmk=
@@ -518,6 +558,8 @@ github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/vbatts/tar-split v0.12.2 h1:w/Y6tjxpeiFMR47yzZPlPj/FcPLpXbTUi/9H7d3CPa4=
github.com/vbatts/tar-split v0.12.2/go.mod h1:eF6B6i6ftWQcDqEn3/iGFRFRo8cBIMSJVOpnNdfTMFA=
+github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
+github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=
github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
@@ -593,6 +635,7 @@ golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLL
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
@@ -615,8 +658,12 @@ golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210331175145-43e1dd70ce54/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -629,6 +676,7 @@ golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
@@ -659,6 +707,7 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks
gopkg.in/cenkalti/backoff.v2 v2.2.1 h1:eJ9UAg01/HIHG987TwxvnzK2MgxXq97YY6rYDpY9aII=
gopkg.in/cenkalti/backoff.v2 v2.2.1/go.mod h1:S0QdOvT2AlerfSBkp0O+dk+bbIMaNbEmVk876gPCthU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
@@ -669,11 +718,14 @@ gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/rethinkdb/rethinkdb-go.v6 v6.2.1 h1:d4KQkxAaAiRY2h5Zqis161Pv91A37uZyJOx73duwUwM=
gopkg.in/rethinkdb/rethinkdb-go.v6 v6.2.1/go.mod h1:WbjuEoo1oadwzQ4apSDU+JTvmllEHtsNHS6y7vFc7iw=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
+gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
+gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 7227c10c0..2b777f138 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -26,7 +26,7 @@ func Bootstrap(ctx context.Context) error {
SetupGinLogger(cfg)
ConfigureGormLogger(cfg)
- slog.InfoContext(ctx, "Arcane is starting")
+ slog.InfoContext(ctx, "Arcane is starting", "version", config.Version)
appCtx, cancelApp := context.WithCancel(ctx)
defer cancelApp()
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 3d3d6286d..2dc4b404d 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -50,6 +50,11 @@ func registerJobs(appCtx context.Context, scheduler *job.Scheduler, appServices
slog.ErrorContext(appCtx, "Failed to register filesystem watcher job", "error", err)
}
+ gitOpsSyncJob := job.NewGitOpsSyncJob(scheduler, appServices.GitOpsSync, appServices.Settings)
+ if err := gitOpsSyncJob.Register(appCtx); err != nil {
+ slog.ErrorContext(appCtx, "Failed to register GitOps sync job", slog.Any("error", err))
+ }
+
setupJobScheduleCallbacks(appServices, appConfig, environmentHealthJob, analyticsJob, eventCleanupJob)
setupSettingsCallbacks(appServices, appConfig, imagePollingJob, autoUpdateJob, environmentHealthJob, fsWatcherJob)
}
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index d33617ee6..75d47993a 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -118,6 +118,8 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {
CustomizeSearch: appServices.CustomizeSearch,
System: appServices.System,
SystemUpgrade: appServices.SystemUpgrade,
+ GitRepository: appServices.GitRepository,
+ GitOpsSync: appServices.GitOpsSync,
Config: cfg,
})
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index 4050a74b1..a31be52b8 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -38,6 +38,8 @@ type Services struct {
Notification *services.NotificationService
Apprise *services.AppriseService
ApiKey *services.ApiKeyService
+ GitRepository *services.GitRepositoryService
+ GitOpsSync *services.GitOpsSyncService
Font *services.FontService
}
@@ -75,6 +77,8 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, svcs.ContainerRegistry, svcs.Docker)
svcs.SystemUpgrade = services.NewSystemUpgradeService(svcs.Docker, svcs.Version, svcs.Event)
svcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image, svcs.Notification, svcs.SystemUpgrade)
+ svcs.GitRepository = services.NewGitRepositoryService(db, cfg.GitWorkDir, svcs.Event)
+ svcs.GitOpsSync = services.NewGitOpsSyncService(db, svcs.GitRepository, svcs.Project, svcs.Event)
return svcs, dockerClient, nil
}
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 8bea4672f..240297a7d 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -1166,3 +1166,139 @@ type ApiKeyDeletionError struct {
func (e *ApiKeyDeletionError) Error() string {
return "Failed to delete API key"
}
+
+type GitRepositoryListError struct {
+ Err error
+}
+
+func (e *GitRepositoryListError) Error() string {
+ return fmt.Sprintf("Failed to list git repositories: %v", e.Err)
+}
+
+type GitRepositoryCreationError struct {
+ Err error
+}
+
+func (e *GitRepositoryCreationError) Error() string {
+ return "Failed to create git repository"
+}
+
+type GitRepositoryRetrievalError struct {
+ Err error
+}
+
+func (e *GitRepositoryRetrievalError) Error() string {
+ return "Failed to retrieve git repository"
+}
+
+type GitRepositoryUpdateError struct {
+ Err error
+}
+
+func (e *GitRepositoryUpdateError) Error() string {
+ return "Failed to update git repository"
+}
+
+type GitRepositoryDeletionError struct {
+ Err error
+}
+
+func (e *GitRepositoryDeletionError) Error() string {
+ return "Failed to delete git repository"
+}
+
+type GitRepositoryTestError struct {
+ Err error
+}
+
+func (e *GitRepositoryTestError) Error() string {
+ return fmt.Sprintf("Failed to test git repository connection: %v", e.Err)
+}
+
+type GitRepositoryMappingError struct {
+ Err error
+}
+
+func (e *GitRepositoryMappingError) Error() string {
+ return "Failed to map git repository"
+}
+
+type GitRepositorySyncError struct {
+ Err error
+}
+
+func (e *GitRepositorySyncError) Error() string {
+ return fmt.Sprintf("Failed to sync git repositories: %v", e.Err)
+}
+
+type GitOpsSyncListError struct {
+ Err error
+}
+
+func (e *GitOpsSyncListError) Error() string {
+ return fmt.Sprintf("Failed to list GitOps syncs: %v", e.Err)
+}
+
+type GitOpsSyncCreationError struct {
+ Err error
+}
+
+func (e *GitOpsSyncCreationError) Error() string {
+ return "Failed to create GitOps sync"
+}
+
+type GitOpsSyncRetrievalError struct {
+ Err error
+}
+
+func (e *GitOpsSyncRetrievalError) Error() string {
+ return "Failed to retrieve GitOps sync"
+}
+
+type GitOpsSyncUpdateError struct {
+ Err error
+}
+
+func (e *GitOpsSyncUpdateError) Error() string {
+ return "Failed to update GitOps sync"
+}
+
+type GitOpsSyncDeletionError struct {
+ Err error
+}
+
+func (e *GitOpsSyncDeletionError) Error() string {
+ return "Failed to delete GitOps sync"
+}
+
+type GitOpsSyncPerformError struct {
+ Err error
+}
+
+func (e *GitOpsSyncPerformError) Error() string {
+ return "Failed to perform GitOps sync"
+}
+
+type GitOpsSyncStatusError struct {
+ Err error
+}
+
+func (e *GitOpsSyncStatusError) Error() string {
+ return "Failed to get GitOps sync status"
+}
+
+type GitOpsSyncBrowseError struct {
+ Err error
+}
+
+func (e *GitOpsSyncBrowseError) Error() string {
+ return "Failed to browse GitOps sync files"
+}
+
+type GitOpsSyncMappingError struct {
+ Err error
+}
+
+func (e *GitOpsSyncMappingError) Error() string {
+ return "Failed to map GitOps sync"
+}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index dfbb80f5c..56bdcd3ef 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -46,8 +46,9 @@ type Config struct {
GPUMonitoringEnabled bool
GPUType string
- FilePerm os.FileMode
- DirPerm os.FileMode
+ FilePerm os.FileMode
+ DirPerm os.FileMode
+ GitWorkDir string
}
func Load() *Config {
@@ -80,8 +81,9 @@ func Load() *Config {
GPUMonitoringEnabled: getBoolEnvOrDefault("GPU_MONITORING_ENABLED", false),
GPUType: getEnvOrDefault("GPU_TYPE", "auto"),
- FilePerm: getFileModeEnvOrDefault("FILE_PERM", 0644),
- DirPerm: getFileModeEnvOrDefault("DIR_PERM", 0755),
+ FilePerm: getFileModeEnvOrDefault("FILE_PERM", 0644),
+ DirPerm: getFileModeEnvOrDefault("DIR_PERM", 0755),
+ GitWorkDir: getEnvOrDefault("GIT_WORK_DIR", "data/git"),
}
common.FilePerm = cfg.FilePerm
diff --git a/backend/internal/huma/handlers/environments.go b/backend/internal/huma/handlers/environments.go
index 10cee4361..84561f7f9 100644
--- a/backend/internal/huma/handlers/environments.go
+++ b/backend/internal/huma/handlers/environments.go
@@ -121,11 +121,11 @@ type PairAgentOutput struct {
Body base.ApiResponse[environment.AgentPairResponse]
}
-type SyncRegistriesInput struct {
+type SyncEnvironmentInput struct {
ID string `path:"id" doc:"Environment ID"`
}
-type SyncRegistriesOutput struct {
+type SyncEnvironmentOutput struct {
Body base.ApiResponse[base.MessageResponse]
}
@@ -277,17 +277,17 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
}, h.PairAgent)
huma.Register(api, huma.Operation{
- OperationID: "syncEnvironmentRegistries",
+ OperationID: "syncEnvironment",
Method: "POST",
- Path: "/environments/{id}/sync-registries",
- Summary: "Sync container registries",
- Description: "Sync container registries to a remote environment",
+ Path: "/environments/{id}/sync",
+ Summary: "Sync environment",
+ Description: "Sync container registries and git repositories to a remote environment",
Tags: []string{"Environments"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- }, h.SyncRegistries)
+ }, h.SyncEnvironment)
huma.Register(api, huma.Operation{
OperationID: "pairEnvironment",
@@ -400,61 +400,69 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
useApiKey := input.Body.UseApiKey != nil && *input.Body.UseApiKey
if useApiKey {
- // New API key-based pairing flow
- env.Status = string(models.EnvironmentStatusPending)
+ return h.createEnvironmentWithApiKey(ctx, env, user)
+ }
- created, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)
- if err != nil {
- return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())
- }
+ return h.createEnvironmentLegacy(ctx, env, user, input.Body)
+}
- // Generate API key for environment
- apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, created.ID, user.ID)
- if err != nil {
- slog.ErrorContext(ctx, "Failed to create environment API key", "environmentID", created.ID, "error", err.Error())
- return nil, huma.Error500InternalServerError("Failed to create environment API key")
- }
+func (h *EnvironmentHandler) createEnvironmentWithApiKey(ctx context.Context, env *models.Environment, user *models.User) (*CreateEnvironmentOutput, error) {
+ // New API key-based pairing flow
+ env.Status = string(models.EnvironmentStatusPending)
- // Store the API key in AccessToken field (encrypted) for manager-to-agent auth
- encryptedKey := apiKeyDto.Key // Store the full key
+ created, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())
+ }
- // Link API key to environment and store encrypted key for manager use
- updates := map[string]interface{}{
- "api_key_id": apiKeyDto.ID,
- "access_token": encryptedKey,
- }
- created, err = h.environmentService.UpdateEnvironment(ctx, created.ID, updates, &user.ID, &user.Username)
- if err != nil {
- slog.ErrorContext(ctx, "Failed to link API key to environment", "environmentID", created.ID, "error", err.Error())
- return nil, huma.Error500InternalServerError("Failed to link API key")
- }
+ // Generate API key for environment
+ apiKeyDto, err := h.apiKeyService.CreateEnvironmentApiKey(ctx, created.ID, user.ID)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to create environment API key", "environmentID", created.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to create environment API key")
+ }
- out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)
- if mapErr != nil {
- return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
- }
+ // Store the API key in AccessToken field (encrypted) for manager-to-agent auth
+ encryptedKey := apiKeyDto.Key // Store the full key
- return &CreateEnvironmentOutput{
- Body: base.ApiResponse[EnvironmentWithApiKey]{
- Success: true,
- Data: EnvironmentWithApiKey{
- Environment: out,
- ApiKey: &apiKeyDto.Key,
- },
- },
- }, nil
+ // Link API key to environment and store encrypted key for manager use
+ updates := map[string]interface{}{
+ "api_key_id": apiKeyDto.ID,
+ "access_token": encryptedKey,
+ }
+ created, err = h.environmentService.UpdateEnvironment(ctx, created.ID, updates, &user.ID, &user.Username)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to link API key to environment", "environmentID", created.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to link API key")
}
+ out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateEnvironmentOutput{
+ Body: base.ApiResponse[EnvironmentWithApiKey]{
+ Success: true,
+ Data: EnvironmentWithApiKey{
+ Environment: out,
+ ApiKey: &apiKeyDto.Key,
+ },
+ },
+ }, nil
+}
+
+func (h *EnvironmentHandler) createEnvironmentLegacy(ctx context.Context, env *models.Environment, user *models.User, body environment.Create) (*CreateEnvironmentOutput, error) {
// Legacy pairing flows
- if (input.Body.AccessToken == nil || *input.Body.AccessToken == "") && input.Body.BootstrapToken != nil && *input.Body.BootstrapToken != "" {
- token, err := h.environmentService.PairAgentWithBootstrap(ctx, input.Body.ApiUrl, *input.Body.BootstrapToken)
+ if (body.AccessToken == nil || *body.AccessToken == "") && body.BootstrapToken != nil && *body.BootstrapToken != "" {
+ token, err := h.environmentService.PairAgentWithBootstrap(ctx, body.ApiUrl, *body.BootstrapToken)
if err != nil {
- slog.ErrorContext(ctx, "Failed to pair with agent", "apiUrl", input.Body.ApiUrl, "error", err.Error())
+ slog.ErrorContext(ctx, "Failed to pair with agent", "apiUrl", body.ApiUrl, "error", err.Error())
return nil, huma.Error502BadGateway((&common.AgentPairingError{Err: err}).Error())
}
env.AccessToken = &token
- } else if input.Body.AccessToken != nil && *input.Body.AccessToken != "" {
- env.AccessToken = input.Body.AccessToken
+ } else if body.AccessToken != nil && *body.AccessToken != "" {
+ env.AccessToken = body.AccessToken
}
created, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)
@@ -462,7 +470,7 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())
}
- // Sync registries in background (intentionally detached from request context)
+ // Sync registries and git repositories in background (intentionally detached from request context)
if created.AccessToken != nil && *created.AccessToken != "" {
go func(envID string, envName string) { //nolint:contextcheck // intentional background context for async task
bgCtx := context.Background()
@@ -471,6 +479,13 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
"environmentID", envID, "environmentName", envName, "error", err.Error())
}
}(created.ID, created.Name)
+ go func(envID string, envName string) { //nolint:contextcheck // intentional background context for async task
+ bgCtx := context.Background()
+ if err := h.environmentService.SyncRepositoriesToEnvironment(bgCtx, envID); err != nil {
+ slog.WarnContext(bgCtx, "Failed to sync git repositories to new environment",
+ "environmentID", envID, "environmentName", envName, "error", err.Error())
+ }
+ }(created.ID, created.Name)
}
out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)
@@ -726,8 +741,8 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu
}, nil
}
-// SyncRegistries syncs container registries to an environment.
-func (h *EnvironmentHandler) SyncRegistries(ctx context.Context, input *SyncRegistriesInput) (*SyncRegistriesOutput, error) {
+// SyncEnvironment syncs container registries and git repositories to an environment.
+func (h *EnvironmentHandler) SyncEnvironment(ctx context.Context, input *SyncEnvironmentInput) (*SyncEnvironmentOutput, error) {
if h.environmentService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -736,15 +751,21 @@ func (h *EnvironmentHandler) SyncRegistries(ctx context.Context, input *SyncRegi
return nil, err
}
+ // Sync registries
if err := h.environmentService.SyncRegistriesToEnvironment(ctx, input.ID); err != nil {
- return nil, huma.Error500InternalServerError((&common.RegistrySyncError{Err: err}).Error())
+ slog.WarnContext(ctx, "Failed to sync registries", "environmentID", input.ID, "error", err.Error())
+ }
+
+ // Sync git repositories
+ if err := h.environmentService.SyncRepositoriesToEnvironment(ctx, input.ID); err != nil {
+ slog.WarnContext(ctx, "Failed to sync git repositories", "environmentID", input.ID, "error", err.Error())
}
- return &SyncRegistriesOutput{
+ return &SyncEnvironmentOutput{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
- Message: "Registries synced successfully",
+ Message: "Environment synced successfully",
},
},
}, nil
@@ -822,6 +843,13 @@ func (h *EnvironmentHandler) triggerPostUpdateTasks(environmentID string, update
"environmentID", envID, "environmentName", envName, "error", err.Error())
}
}(environmentID, updated.Name)
+ go func(envID string, envName string) {
+ ctx := context.Background()
+ if err := h.environmentService.SyncRepositoriesToEnvironment(ctx, envID); err != nil {
+ slog.WarnContext(ctx, "Failed to sync git repositories after environment update",
+ "environmentID", envID, "environmentName", envName, "error", err.Error())
+ }
+ }(environmentID, updated.Name)
}
}
diff --git a/backend/internal/huma/handlers/git_repositories.go b/backend/internal/huma/handlers/git_repositories.go
new file mode 100644
index 000000000..587f25e74
--- /dev/null
+++ b/backend/internal/huma/handlers/git_repositories.go
@@ -0,0 +1,452 @@
+package handlers
+
+import (
+ "context"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/gitops"
+)
+
+// GitRepositoryHandler handles git repository management endpoints.
+type GitRepositoryHandler struct {
+ repoService *services.GitRepositoryService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+// GitRepositoryPaginatedResponse is the paginated response for git repositories.
+type GitRepositoryPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []gitops.GitRepository `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListGitRepositoriesInput struct {
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction"`
+ Start int `query:"start" default:"0" doc:"Start index"`
+ Limit int `query:"limit" default:"20" doc:"Items per page"`
+}
+
+type ListGitRepositoriesOutput struct {
+ Body GitRepositoryPaginatedResponse
+}
+
+type CreateGitRepositoryInput struct {
+ Body models.CreateGitRepositoryRequest
+}
+
+type CreateGitRepositoryOutput struct {
+ Body base.ApiResponse[gitops.GitRepository]
+}
+
+type GetGitRepositoryInput struct {
+ ID string `path:"id" doc:"Repository ID"`
+}
+
+type GetGitRepositoryOutput struct {
+ Body base.ApiResponse[gitops.GitRepository]
+}
+
+type UpdateGitRepositoryInput struct {
+ ID string `path:"id" doc:"Repository ID"`
+ Body models.UpdateGitRepositoryRequest
+}
+
+type UpdateGitRepositoryOutput struct {
+ Body base.ApiResponse[gitops.GitRepository]
+}
+
+type DeleteGitRepositoryInput struct {
+ ID string `path:"id" doc:"Repository ID"`
+}
+
+type DeleteGitRepositoryOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type TestGitRepositoryInput struct {
+ ID string `path:"id" doc:"Repository ID"`
+ Branch string `query:"branch" doc:"Branch to test (optional, defaults to main)"`
+}
+
+type TestGitRepositoryOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type ListBranchesInput struct {
+ ID string `path:"id" doc:"Repository ID"`
+}
+
+type ListBranchesOutput struct {
+ Body base.ApiResponse[gitops.BranchesResponse]
+}
+
+type BrowseFilesInput struct {
+ ID string `path:"id" doc:"Repository ID"`
+ Branch string `query:"branch" doc:"Branch to browse"`
+ Path string `query:"path" doc:"Path within repository (optional)"`
+}
+
+type BrowseFilesOutput struct {
+ Body base.ApiResponse[gitops.BrowseResponse]
+}
+
+type SyncGitRepositoriesInput struct {
+ Body gitops.RepositorySyncRequest
+}
+
+type SyncGitRepositoriesOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterGitRepositories registers all git repository endpoints.
+func RegisterGitRepositories(api huma.API, repoService *services.GitRepositoryService) {
+ h := &GitRepositoryHandler{repoService: repoService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listGitRepositories",
+ Method: "GET",
+ Path: "/customize/git-repositories",
+ Summary: "List git repositories",
+ Description: "Get a paginated list of git repositories",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListRepositories)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "createGitRepository",
+ Method: "POST",
+ Path: "/customize/git-repositories",
+ Summary: "Create a git repository",
+ Description: "Create a new git repository configuration",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateRepository)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getGitRepository",
+ Method: "GET",
+ Path: "/customize/git-repositories/{id}",
+ Summary: "Get a git repository",
+ Description: "Get a git repository by ID",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetRepository)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateGitRepository",
+ Method: "PUT",
+ Path: "/customize/git-repositories/{id}",
+ Summary: "Update a git repository",
+ Description: "Update an existing git repository configuration",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateRepository)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteGitRepository",
+ Method: "DELETE",
+ Path: "/customize/git-repositories/{id}",
+ Summary: "Delete a git repository",
+ Description: "Delete a git repository configuration by ID",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteRepository)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "testGitRepository",
+ Method: "POST",
+ Path: "/customize/git-repositories/{id}/test",
+ Summary: "Test a git repository",
+ Description: "Test connectivity and authentication to a git repository",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.TestRepository)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listGitRepositoryBranches",
+ Method: "GET",
+ Path: "/customize/git-repositories/{id}/branches",
+ Summary: "List repository branches",
+ Description: "Get all branches from a git repository with default branch detection",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListBranches)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "browseGitRepositoryFiles",
+ Method: "GET",
+ Path: "/customize/git-repositories/{id}/files",
+ Summary: "Browse repository files",
+ Description: "Browse files and directories in a git repository",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.BrowseFiles)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "syncGitRepositories",
+ Method: "POST",
+ Path: "/git-repositories/sync",
+ Summary: "Sync git repositories",
+ Description: "Sync git repositories from a manager to this agent instance",
+ Tags: []string{"Git Repositories"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.SyncRepositories)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// ListRepositories returns a paginated list of git repositories.
+func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *ListGitRepositoriesInput) (*ListGitRepositoriesOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+
+ repositories, paginationResp, err := h.repoService.GetRepositoriesPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.GitRepositoryListError{Err: err}).Error())
+ }
+
+ return &ListGitRepositoriesOutput{
+ Body: GitRepositoryPaginatedResponse{
+ Success: true,
+ Data: repositories,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// CreateRepository creates a new git repository.
+func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *CreateGitRepositoryInput) (*CreateGitRepositoryOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ repo, err := h.repoService.CreateRepository(ctx, input.Body)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryCreationError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.GitRepository, gitops.GitRepository](repo)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.GitRepositoryMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateGitRepositoryOutput{
+ Body: base.ApiResponse[gitops.GitRepository]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetRepository returns a git repository by ID.
+func (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitRepositoryInput) (*GetGitRepositoryOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ repo, err := h.repoService.GetRepositoryByID(ctx, input.ID)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryRetrievalError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.GitRepository, gitops.GitRepository](repo)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.GitRepositoryMappingError{Err: mapErr}).Error())
+ }
+
+ return &GetGitRepositoryOutput{
+ Body: base.ApiResponse[gitops.GitRepository]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// UpdateRepository updates an existing git repository.
+func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *UpdateGitRepositoryInput) (*UpdateGitRepositoryOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ repo, err := h.repoService.UpdateRepository(ctx, input.ID, input.Body)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryUpdateError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.GitRepository, gitops.GitRepository](repo)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.GitRepositoryMappingError{Err: mapErr}).Error())
+ }
+
+ return &UpdateGitRepositoryOutput{
+ Body: base.ApiResponse[gitops.GitRepository]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// DeleteRepository deletes a git repository by ID.
+func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *DeleteGitRepositoryInput) (*DeleteGitRepositoryOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.repoService.DeleteRepository(ctx, input.ID); err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositoryDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteGitRepositoryOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Repository deleted successfully",
+ },
+ },
+ }, nil
+}
+
+// TestRepository tests connectivity and authentication to a git repository.
+func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGitRepositoryInput) (*TestGitRepositoryOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.repoService.TestConnection(ctx, input.ID, input.Branch); err != nil {
+ return nil, huma.Error400BadRequest((&common.GitRepositoryTestError{Err: err}).Error())
+ }
+
+ return &TestGitRepositoryOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Connection successful",
+ },
+ },
+ }, nil
+}
+
+// ListBranches returns all branches from a git repository.
+func (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBranchesInput) (*ListBranchesOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ branches, err := h.repoService.ListBranches(ctx, input.ID)
+ if err != nil {
+ return nil, huma.Error400BadRequest((&common.GitRepositoryTestError{Err: err}).Error())
+ }
+
+ return &ListBranchesOutput{
+ Body: base.ApiResponse[gitops.BranchesResponse]{
+ Success: true,
+ Data: gitops.BranchesResponse{
+ Branches: branches,
+ },
+ },
+ }, nil
+}
+
+// BrowseFiles returns files and directories from a git repository.
+func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFilesInput) (*BrowseFilesOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.Branch == "" {
+ return nil, huma.Error400BadRequest("branch parameter is required")
+ }
+
+ result, err := h.repoService.BrowseFiles(ctx, input.ID, input.Branch, input.Path)
+ if err != nil {
+ return nil, huma.Error400BadRequest((&common.GitRepositoryTestError{Err: err}).Error())
+ }
+
+ return &BrowseFilesOutput{
+ Body: base.ApiResponse[gitops.BrowseResponse]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+// SyncRepositories syncs git repositories from a manager to this agent instance.
+func (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *SyncGitRepositoriesInput) (*SyncGitRepositoriesOutput, error) {
+ if h.repoService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := checkAdmin(ctx); err != nil {
+ return nil, err
+ }
+
+ if err := h.repoService.SyncRepositories(ctx, input.Body.Repositories); err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositorySyncError{Err: err}).Error())
+ }
+
+ return &SyncGitRepositoriesOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Repositories synced successfully",
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/gitops_syncs.go b/backend/internal/huma/handlers/gitops_syncs.go
new file mode 100644
index 000000000..7f3fa2ff9
--- /dev/null
+++ b/backend/internal/huma/handlers/gitops_syncs.go
@@ -0,0 +1,449 @@
+package handlers
+
+import (
+ "context"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/gitops"
+)
+
+// GitOpsSyncHandler handles GitOps sync management endpoints.
+type GitOpsSyncHandler struct {
+ syncService *services.GitOpsSyncService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+// GitOpsSyncPaginatedResponse is the paginated response for GitOps syncs.
+type GitOpsSyncPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []gitops.GitOpsSync `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListGitOpsSyncsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction"`
+ Start int `query:"start" default:"0" doc:"Start index"`
+ Limit int `query:"limit" default:"20" doc:"Items per page"`
+}
+
+type ListGitOpsSyncsOutput struct {
+ Body GitOpsSyncPaginatedResponse
+}
+
+type CreateGitOpsSyncInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body gitops.CreateSyncRequest
+}
+
+type CreateGitOpsSyncOutput struct {
+ Body base.ApiResponse[gitops.GitOpsSync]
+}
+
+type GetGitOpsSyncInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ SyncID string `path:"syncId" doc:"Sync ID"`
+}
+
+type GetGitOpsSyncOutput struct {
+ Body base.ApiResponse[gitops.GitOpsSync]
+}
+
+type UpdateGitOpsSyncInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ SyncID string `path:"syncId" doc:"Sync ID"`
+ Body gitops.UpdateSyncRequest
+}
+
+type UpdateGitOpsSyncOutput struct {
+ Body base.ApiResponse[gitops.GitOpsSync]
+}
+
+type DeleteGitOpsSyncInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ SyncID string `path:"syncId" doc:"Sync ID"`
+}
+
+type DeleteGitOpsSyncOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type PerformSyncInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ SyncID string `path:"syncId" doc:"Sync ID"`
+}
+
+type PerformSyncOutput struct {
+ Body base.ApiResponse[gitops.SyncResult]
+}
+
+type GetSyncStatusInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ SyncID string `path:"syncId" doc:"Sync ID"`
+}
+
+type GetSyncStatusOutput struct {
+ Body base.ApiResponse[gitops.SyncStatus]
+}
+
+type BrowseSyncFilesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ SyncID string `path:"syncId" doc:"Sync ID"`
+ Path string `query:"path" doc:"Path to browse (optional)"`
+}
+
+type BrowseSyncFilesOutput struct {
+ Body base.ApiResponse[gitops.BrowseResponse]
+}
+
+type ImportGitOpsSyncsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body []gitops.ImportGitOpsSyncRequest
+}
+
+type ImportGitOpsSyncsOutput struct {
+ Body base.ApiResponse[gitops.ImportGitOpsSyncResponse]
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterGitOpsSyncs registers all GitOps sync endpoints.
+func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService) {
+ h := &GitOpsSyncHandler{syncService: syncService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listGitOpsSyncs",
+ Method: "GET",
+ Path: "/environments/{id}/gitops-syncs",
+ Summary: "List GitOps syncs",
+ Description: "Get a paginated list of GitOps syncs for an environment",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListSyncs)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "createGitOpsSync",
+ Method: "POST",
+ Path: "/environments/{id}/gitops-syncs",
+ Summary: "Create a GitOps sync",
+ Description: "Create a new GitOps sync configuration for an environment",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateSync)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "importGitOpsSyncs",
+ Method: "POST",
+ Path: "/environments/{id}/gitops-syncs/import",
+ Summary: "Import GitOps syncs",
+ Description: "Import multiple GitOps sync configurations from JSON",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ImportSyncs)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getGitOpsSync",
+ Method: "GET",
+ Path: "/environments/{id}/gitops-syncs/{syncId}",
+ Summary: "Get a GitOps sync",
+ Description: "Get a GitOps sync by ID",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetSync)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateGitOpsSync",
+ Method: "PUT",
+ Path: "/environments/{id}/gitops-syncs/{syncId}",
+ Summary: "Update a GitOps sync",
+ Description: "Update an existing GitOps sync configuration",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateSync)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteGitOpsSync",
+ Method: "DELETE",
+ Path: "/environments/{id}/gitops-syncs/{syncId}",
+ Summary: "Delete a GitOps sync",
+ Description: "Delete a GitOps sync configuration by ID",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteSync)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "performGitOpsSync",
+ Method: "POST",
+ Path: "/environments/{id}/gitops-syncs/{syncId}/sync",
+ Summary: "Perform a GitOps sync",
+ Description: "Manually trigger a sync operation",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.PerformSync)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getGitOpsSyncStatus",
+ Method: "GET",
+ Path: "/environments/{id}/gitops-syncs/{syncId}/status",
+ Summary: "Get GitOps sync status",
+ Description: "Get the current status of a GitOps sync",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetStatus)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "browseGitOpsSyncFiles",
+ Method: "GET",
+ Path: "/environments/{id}/gitops-syncs/{syncId}/files",
+ Summary: "Browse GitOps sync files",
+ Description: "Browse files in the synced repository",
+ Tags: []string{"GitOps Syncs"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.BrowseFiles)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// ListSyncs returns a paginated list of GitOps syncs.
+func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSyncsInput) (*ListGitOpsSyncsOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+
+ syncs, paginationResp, err := h.syncService.GetSyncsPaginated(ctx, input.EnvironmentID, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.GitOpsSyncListError{Err: err}).Error())
+ }
+
+ return &ListGitOpsSyncsOutput{
+ Body: GitOpsSyncPaginatedResponse{
+ Success: true,
+ Data: syncs,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// CreateSync creates a new GitOps sync.
+func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSyncInput) (*CreateGitOpsSyncOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ sync, err := h.syncService.CreateSync(ctx, input.EnvironmentID, input.Body)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncCreationError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.GitOpsSync, gitops.GitOpsSync](sync)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.GitOpsSyncMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateGitOpsSyncOutput{
+ Body: base.ApiResponse[gitops.GitOpsSync]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// ImportSyncs imports multiple GitOps syncs.
+func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOpsSyncsInput) (*ImportGitOpsSyncsOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ response, err := h.syncService.ImportSyncs(ctx, input.EnvironmentID, input.Body)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+
+ return &ImportGitOpsSyncsOutput{
+ Body: base.ApiResponse[gitops.ImportGitOpsSyncResponse]{
+ Success: true,
+ Data: *response,
+ },
+ }, nil
+}
+
+// GetSync returns a GitOps sync by ID.
+func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInput) (*GetGitOpsSyncOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ sync, err := h.syncService.GetSyncByID(ctx, input.EnvironmentID, input.SyncID)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncRetrievalError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.GitOpsSync, gitops.GitOpsSync](sync)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.GitOpsSyncMappingError{Err: mapErr}).Error())
+ }
+
+ return &GetGitOpsSyncOutput{
+ Body: base.ApiResponse[gitops.GitOpsSync]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// UpdateSync updates an existing GitOps sync.
+func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSyncInput) (*UpdateGitOpsSyncOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ sync, err := h.syncService.UpdateSync(ctx, input.EnvironmentID, input.SyncID, input.Body)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncUpdateError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.GitOpsSync, gitops.GitOpsSync](sync)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.GitOpsSyncMappingError{Err: mapErr}).Error())
+ }
+
+ return &UpdateGitOpsSyncOutput{
+ Body: base.ApiResponse[gitops.GitOpsSync]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// DeleteSync deletes a GitOps sync by ID.
+func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSyncInput) (*DeleteGitOpsSyncOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.syncService.DeleteSync(ctx, input.EnvironmentID, input.SyncID); err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteGitOpsSyncOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Sync deleted successfully",
+ },
+ },
+ }, nil
+}
+
+// PerformSync manually triggers a sync operation.
+func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncInput) (*PerformSyncOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ result, err := h.syncService.PerformSync(ctx, input.EnvironmentID, input.SyncID)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncPerformError{Err: err}).Error())
+ }
+
+ return &PerformSyncOutput{
+ Body: base.ApiResponse[gitops.SyncResult]{
+ Success: result.Success,
+ Data: *result,
+ },
+ }, nil
+}
+
+// GetStatus returns the current status of a GitOps sync.
+func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusInput) (*GetSyncStatusOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ status, err := h.syncService.GetSyncStatus(ctx, input.EnvironmentID, input.SyncID)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncStatusError{Err: err}).Error())
+ }
+
+ return &GetSyncStatusOutput{
+ Body: base.ApiResponse[gitops.SyncStatus]{
+ Success: true,
+ Data: *status,
+ },
+ }, nil
+}
+
+// BrowseFiles returns the file tree at the specified path in the repository.
+func (h *GitOpsSyncHandler) BrowseFiles(ctx context.Context, input *BrowseSyncFilesInput) (*BrowseSyncFilesOutput, error) {
+ if h.syncService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ response, err := h.syncService.BrowseFiles(ctx, input.EnvironmentID, input.SyncID, input.Path)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitOpsSyncBrowseError{Err: err}).Error())
+ }
+
+ return &BrowseSyncFilesOutput{
+ Body: base.ApiResponse[gitops.BrowseResponse]{
+ Success: true,
+ Data: *response,
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/projects.go b/backend/internal/huma/handlers/projects.go
index 13731b9e3..f3d8217be 100644
--- a/backend/internal/huma/handlers/projects.go
+++ b/backend/internal/huma/handlers/projects.go
@@ -486,6 +486,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
response.CreatedAt = proj.CreatedAt.Format(time.RFC3339)
response.UpdatedAt = proj.UpdatedAt.Format(time.RFC3339)
response.DirName = utils.DerefString(proj.DirName)
+ response.GitOpsManagedBy = proj.GitOpsManagedBy
return &CreateProjectOutput{
Body: base.ApiResponse[project.CreateReponse]{
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index e6e342e2f..11b3619dd 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -141,6 +141,8 @@ type Services struct {
CustomizeSearch *services.CustomizeSearchService
System *services.SystemService
SystemUpgrade *services.SystemUpgradeService
+ GitRepository *services.GitRepositoryService
+ GitOpsSync *services.GitOpsSyncService
Config *config.Config
}
@@ -297,6 +299,8 @@ func registerHandlers(api huma.API, svc *Services) {
var customizeSearchSvc *services.CustomizeSearchService
var systemSvc *services.SystemService
var systemUpgradeSvc *services.SystemUpgradeService
+ var gitRepositorySvc *services.GitRepositoryService
+ var gitOpsSyncSvc *services.GitOpsSyncService
var cfg *config.Config
if svc != nil {
@@ -327,6 +331,8 @@ func registerHandlers(api huma.API, svc *Services) {
customizeSearchSvc = svc.CustomizeSearch
systemSvc = svc.System
systemUpgradeSvc = svc.SystemUpgrade
+ gitRepositorySvc = svc.GitRepository
+ gitOpsSyncSvc = svc.GitOpsSync
cfg = svc.Config
}
handlers.RegisterHealth(api)
@@ -353,4 +359,6 @@ func registerHandlers(api huma.API, svc *Services) {
handlers.RegisterUpdater(api, updaterSvc)
handlers.RegisterCustomize(api, customizeSearchSvc)
handlers.RegisterSystem(api, dockerSvc, systemSvc, systemUpgradeSvc, cfg)
+ handlers.RegisterGitRepositories(api, gitRepositorySvc)
+ handlers.RegisterGitOpsSyncs(api, gitOpsSyncSvc)
}
diff --git a/backend/internal/job/environment_health_job.go b/backend/internal/job/environment_health_job.go
index ac204de8e..799e54fcd 100644
--- a/backend/internal/job/environment_health_job.go
+++ b/backend/internal/job/environment_health_job.go
@@ -99,7 +99,7 @@ func (j *EnvironmentHealthJob) Execute(ctx context.Context) error {
offlineCount++
case status == "online":
onlineCount++
- // Sync registries to online remote environments (skip local environment ID "0")
+ // Sync registries and git repositories to online remote environments (skip local environment ID "0")
if env.ID != "0" {
go func(envID, envName string) {
syncCtx := context.WithoutCancel(ctx)
@@ -114,6 +114,19 @@ func (j *EnvironmentHealthJob) Execute(ctx context.Context) error {
"environment_name", envName)
}
}(env.ID, env.Name)
+ go func(envID, envName string) {
+ syncCtx := context.WithoutCancel(ctx)
+ if err := j.environmentService.SyncRepositoriesToEnvironment(syncCtx, envID); err != nil {
+ slog.WarnContext(syncCtx, "failed to sync git repositories during health check",
+ "environment_id", envID,
+ "environment_name", envName,
+ "error", err)
+ } else {
+ slog.DebugContext(syncCtx, "successfully synced git repositories during health check",
+ "environment_id", envID,
+ "environment_name", envName)
+ }
+ }(env.ID, env.Name)
}
default:
offlineCount++
diff --git a/backend/internal/job/gitops_sync_job.go b/backend/internal/job/gitops_sync_job.go
new file mode 100644
index 000000000..fde75a9a8
--- /dev/null
+++ b/backend/internal/job/gitops_sync_job.go
@@ -0,0 +1,69 @@
+package job
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/go-co-op/gocron/v2"
+)
+
+type GitOpsSyncJob struct {
+ syncService *services.GitOpsSyncService
+ settingsService *services.SettingsService
+ scheduler *Scheduler
+}
+
+func NewGitOpsSyncJob(scheduler *Scheduler, syncService *services.GitOpsSyncService, settingsService *services.SettingsService) *GitOpsSyncJob {
+ return &GitOpsSyncJob{
+ syncService: syncService,
+ settingsService: settingsService,
+ scheduler: scheduler,
+ }
+}
+
+func (j *GitOpsSyncJob) Register(ctx context.Context) error {
+ // Check if GitOps sync is enabled via settings
+ gitopsSyncEnabled := j.settingsService.GetBoolSetting(ctx, "gitopsSyncEnabled", true)
+
+ if !gitopsSyncEnabled {
+ slog.InfoContext(ctx, "GitOps sync disabled; job not registered")
+ return nil
+ }
+
+ // Default interval: 5 minutes
+ interval := 5 * time.Minute
+
+ slog.InfoContext(ctx, "registering GitOps sync job", "interval", interval.String())
+
+ // Ensure single instance
+ j.scheduler.RemoveJobByName("gitops-sync")
+
+ jobDefinition := gocron.DurationJob(interval)
+ return j.scheduler.RegisterJob(
+ ctx,
+ "gitops-sync",
+ jobDefinition,
+ j.Execute,
+ false,
+ )
+}
+
+func (j *GitOpsSyncJob) Execute(ctx context.Context) error {
+ slog.InfoContext(ctx, "GitOps sync run started")
+
+ enabled := j.settingsService.GetBoolSetting(ctx, "gitopsSyncEnabled", true)
+ if !enabled {
+ slog.InfoContext(ctx, "GitOps sync disabled; skipping run")
+ return nil
+ }
+
+ if err := j.syncService.SyncAllEnabled(ctx); err != nil {
+ slog.ErrorContext(ctx, "GitOps sync run failed", "err", err)
+ return err
+ }
+
+ slog.InfoContext(ctx, "GitOps sync run completed")
+ return nil
+}
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index 33c0a848b..6707357f5 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -24,6 +24,7 @@ const (
managementEndpointTest = "/test"
managementEndpointHeartbeat = "/heartbeat"
managementEndpointSyncRegistries = "/sync-registries"
+ managementEndpointSync = "/sync"
managementEndpointDeployment = "/deployment"
managementEndpointAgentPair = "/agent/pair"
managementEndpointVersion = "/version"
@@ -137,6 +138,7 @@ func (m *EnvironmentMiddleware) hasResourcePath(c *gin.Context, envID string) bo
managementEndpointTest,
managementEndpointHeartbeat,
managementEndpointSyncRegistries,
+ managementEndpointSync,
managementEndpointDeployment,
managementEndpointAgentPair,
managementEndpointVersion,
diff --git a/backend/internal/models/customize.go b/backend/internal/models/customize.go
index 32d2c2367..9a56a0343 100644
--- a/backend/internal/models/customize.go
+++ b/backend/internal/models/customize.go
@@ -23,6 +23,11 @@ type CustomizeItem struct {
GlobalVariables CustomizeVariable `key:"globalVariables" meta:"label=Global Variables;type=object;keywords=variables,environment,env,global,config,settings,parameters;category=variables;description=Define reusable variables for all projects" catmeta:"id=variables;title=Variables;icon=code;url=/customize/variables;description=Manage global variables and environment configuration"`
SecretVariables CustomizeVariable `key:"secretVariables" meta:"label=Secret Variables;type=secure;keywords=secrets,sensitive,secure,encrypted,password,api,key;category=variables;description=Manage sensitive and encrypted variables"`
VariableTemplates CustomizeVariable `key:"variableTemplates" meta:"label=Variable Templates;type=array;keywords=templates,reusable,preset,configuration,standard,common;category=variables;description=Create reusable variable configurations"`
+
+ // Git Repositories category
+ GitRepositories CustomizeVariable `key:"gitRepositories" meta:"label=Git Repositories;type=array;keywords=git,repository,repositories,source,code,version,control,github,gitlab,bitbucket;category=git-repositories;description=Manage git repository connections for GitOps" catmeta:"id=git-repositories;title=Git Repositories;icon=git-branch;url=/customize/git-repositories;description=Configure git repositories for Git synchronization"`
+ GitRepositoryDefaults CustomizeVariable `key:"gitRepositoryDefaults" meta:"label=Repository Defaults;type=object;keywords=defaults,settings,configuration,branch,auth,authentication;category=git-repositories;description=Set default settings for git repositories"`
+ GitRepositoryTemplates CustomizeVariable `key:"gitRepositoryTemplates" meta:"label=Repository Templates;type=array;keywords=templates,presets,common,reusable,standard;category=git-repositories;description=Create reusable repository configurations"`
}
type CustomizeVariable struct {
diff --git a/backend/internal/models/event.go b/backend/internal/models/event.go
index b5265871b..d2addbae2 100644
--- a/backend/internal/models/event.go
+++ b/backend/internal/models/event.go
@@ -32,6 +32,18 @@ const (
EventTypeProjectUpdate EventType = "project.update"
EventTypeProjectError EventType = "project.error"
+ EventTypeGitRepositoryCreate EventType = "git.repository.create"
+ EventTypeGitRepositoryUpdate EventType = "git.repository.update"
+ EventTypeGitRepositoryDelete EventType = "git.repository.delete"
+ EventTypeGitRepositoryTest EventType = "git.repository.test"
+ EventTypeGitRepositoryError EventType = "git.repository.error"
+
+ EventTypeGitSyncCreate EventType = "git.sync.create"
+ EventTypeGitSyncUpdate EventType = "git.sync.update"
+ EventTypeGitSyncDelete EventType = "git.sync.delete"
+ EventTypeGitSyncRun EventType = "git.sync.run"
+ EventTypeGitSyncError EventType = "git.sync.error"
+
EventTypeVolumeCreate EventType = "volume.create"
EventTypeVolumeDelete EventType = "volume.delete"
EventTypeVolumeError EventType = "volume.error"
diff --git a/backend/internal/models/git_repository.go b/backend/internal/models/git_repository.go
new file mode 100644
index 000000000..87b744b79
--- /dev/null
+++ b/backend/internal/models/git_repository.go
@@ -0,0 +1,39 @@
+package models
+
+type GitRepository struct {
+ Name string `json:"name" sortable:"true" search:"git,repository,repo,source,version,control,github,gitlab,bitbucket"`
+ URL string `json:"url" sortable:"true" search:"url,git,clone,remote,https,ssh"`
+ AuthType string `json:"authType" sortable:"true" search:"auth,authentication,credentials,token,ssh,http"` // none, http, ssh
+ Username string `json:"username" sortable:"true" search:"username,user,login,account"`
+ Token string `json:"token" search:"token,password,credentials,secret,auth"` // encrypted
+ SSHKey string `json:"sshKey" search:"ssh,key,private,public,certificate"` // encrypted
+ Description *string `json:"description,omitempty" sortable:"true"`
+ Enabled bool `json:"enabled" sortable:"true" search:"enabled,active,disabled"`
+ BaseModel
+}
+
+func (GitRepository) TableName() string {
+ return "git_repositories"
+}
+
+type CreateGitRepositoryRequest struct {
+ Name string `json:"name" binding:"required"`
+ URL string `json:"url" binding:"required"`
+ AuthType string `json:"authType" binding:"required,oneof=none http ssh"`
+ Username string `json:"username,omitempty"`
+ Token string `json:"token,omitempty"`
+ SSHKey string `json:"sshKey,omitempty"`
+ Description *string `json:"description,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+}
+
+type UpdateGitRepositoryRequest struct {
+ Name *string `json:"name,omitempty"`
+ URL *string `json:"url,omitempty"`
+ AuthType *string `json:"authType,omitempty" binding:"omitempty,oneof=none http ssh"`
+ Username *string `json:"username,omitempty"`
+ Token *string `json:"token,omitempty"`
+ SSHKey *string `json:"sshKey,omitempty"`
+ Description *string `json:"description,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+}
diff --git a/backend/internal/models/gitops_sync.go b/backend/internal/models/gitops_sync.go
new file mode 100644
index 000000000..4146ffb28
--- /dev/null
+++ b/backend/internal/models/gitops_sync.go
@@ -0,0 +1,30 @@
+package models
+
+import (
+ "time"
+)
+
+type GitOpsSync struct {
+ Name string `json:"name" sortable:"true" search:"sync,gitops,automation,deploy,deployment,continuous"`
+ EnvironmentID string `json:"environmentId" sortable:"true"`
+ Environment *Environment `json:"environment,omitempty" gorm:"foreignKey:EnvironmentID"`
+ RepositoryID string `json:"repositoryId" sortable:"true"`
+ Repository *GitRepository `json:"repository,omitempty" gorm:"foreignKey:RepositoryID"`
+ Branch string `json:"branch" sortable:"true" search:"branch,main,master,develop,feature,release"`
+ ComposePath string `json:"composePath" sortable:"true" search:"compose,docker-compose,path,file,yaml,yml"`
+ ProjectName string `json:"projectName" sortable:"true" search:"project,name,stack,application,service"` // Name of project to create/update
+ ProjectID *string `json:"projectId,omitempty" sortable:"true"` // Set after project is created
+ Project *Project `json:"project,omitempty" gorm:"foreignKey:ProjectID"`
+ AutoSync bool `json:"autoSync" sortable:"true" search:"auto,automatic,sync,continuous,scheduled"`
+ SyncInterval int `json:"syncInterval" sortable:"true" search:"interval,frequency,schedule,cron,minutes"` // in minutes
+ LastSyncAt *time.Time `json:"lastSyncAt,omitempty" sortable:"true"`
+ LastSyncStatus *string `json:"lastSyncStatus,omitempty" search:"status,success,failed,pending,error"`
+ LastSyncError *string `json:"lastSyncError,omitempty"`
+ LastSyncCommit *string `json:"lastSyncCommit,omitempty" search:"commit,hash,sha,revision"`
+ Enabled bool `json:"enabled" sortable:"true" search:"enabled,active,disabled"`
+ BaseModel
+}
+
+func (GitOpsSync) TableName() string {
+ return "gitops_syncs"
+}
diff --git a/backend/internal/models/project.go b/backend/internal/models/project.go
index 565cbd526..b79052e15 100644
--- a/backend/internal/models/project.go
+++ b/backend/internal/models/project.go
@@ -13,13 +13,14 @@ const (
)
type Project struct {
- Name string `json:"name" sortable:"true"`
- DirName *string `json:"dir_name"`
- Path string `json:"path"`
- Status ProjectStatus `json:"status" sortable:"true"`
- StatusReason *string `json:"status_reason"`
- ServiceCount int `json:"service_count" sortable:"true"`
- RunningCount int `json:"running_count" sortable:"true"`
+ Name string `json:"name" sortable:"true"`
+ DirName *string `json:"dir_name"`
+ Path string `json:"path"`
+ Status ProjectStatus `json:"status" sortable:"true"`
+ StatusReason *string `json:"status_reason"`
+ ServiceCount int `json:"service_count" sortable:"true"`
+ RunningCount int `json:"running_count" sortable:"true"`
+ GitOpsManagedBy *string `json:"gitops_managed_by,omitempty" gorm:"column:gitops_managed_by"`
BaseModel
}
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 50725d507..74ce47ffe 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -19,6 +19,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
"github.com/getarcaneapp/arcane/types/containerregistry"
"github.com/getarcaneapp/arcane/types/environment"
+ "github.com/getarcaneapp/arcane/types/gitops"
"github.com/google/uuid"
"gorm.io/gorm"
)
@@ -576,6 +577,134 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en
return nil
}
+// SyncRepositoriesToEnvironment syncs all git repositories from this manager to a remote environment
+func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context, environmentID string) error {
+ // Get the environment
+ environment, err := s.GetEnvironmentByID(ctx, environmentID)
+ if err != nil {
+ return fmt.Errorf("failed to get environment: %w", err)
+ }
+
+ // Don't sync to local environment (ID "0")
+ if environmentID == "0" {
+ return fmt.Errorf("cannot sync repositories to local environment")
+ }
+
+ slog.InfoContext(ctx, "Starting git repository sync to environment", "environmentID", environmentID, "environmentName", environment.Name, "apiUrl", environment.ApiUrl)
+
+ // Get all git repositories from this manager
+ var repositories []models.GitRepository
+ if err := s.db.WithContext(ctx).Find(&repositories).Error; err != nil {
+ return fmt.Errorf("failed to get git repositories: %w", err)
+ }
+
+ slog.InfoContext(ctx, "Found git repositories to sync", "count", len(repositories))
+
+ // Prepare sync items with decrypted credentials
+ syncItems := make([]gitops.RepositorySync, 0, len(repositories))
+ for _, repo := range repositories {
+ item := gitops.RepositorySync{
+ ID: repo.ID,
+ Name: repo.Name,
+ URL: repo.URL,
+ AuthType: repo.AuthType,
+ Username: repo.Username,
+ Description: repo.Description,
+ Enabled: repo.Enabled,
+ CreatedAt: repo.CreatedAt,
+ }
+ if repo.UpdatedAt != nil {
+ item.UpdatedAt = *repo.UpdatedAt
+ }
+
+ // Decrypt token if present
+ if repo.Token != "" {
+ decryptedToken, err := utils.Decrypt(repo.Token)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to decrypt repository token for sync", "repositoryID", repo.ID, "repositoryName", repo.Name, "error", err.Error())
+ continue
+ }
+ item.Token = decryptedToken
+ }
+
+ // Decrypt SSH key if present
+ if repo.SSHKey != "" {
+ decryptedSSHKey, err := utils.Decrypt(repo.SSHKey)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to decrypt repository SSH key for sync", "repositoryID", repo.ID, "repositoryName", repo.Name, "error", err.Error())
+ continue
+ }
+ item.SSHKey = decryptedSSHKey
+ }
+
+ syncItems = append(syncItems, item)
+ }
+
+ // Prepare the sync request
+ syncReq := gitops.RepositorySyncRequest{
+ Repositories: syncItems,
+ }
+
+ // Marshal the request
+ reqBody, err := json.Marshal(syncReq)
+ if err != nil {
+ return fmt.Errorf("failed to marshal sync request: %w", err)
+ }
+
+ // Send the sync request to the remote environment
+ reqCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+
+ targetURL := strings.TrimRight(environment.ApiUrl, "/") + "/api/git-repositories/sync"
+ req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, targetURL, bytes.NewReader(reqBody))
+ if err != nil {
+ return fmt.Errorf("failed to create sync request: %w", err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+
+ // Use appropriate auth header based on environment type
+ if environment.AccessToken != nil && *environment.AccessToken != "" {
+ req.Header.Set("X-Arcane-Agent-Token", *environment.AccessToken)
+ req.Header.Set("X-API-Key", *environment.AccessToken)
+ slog.DebugContext(ctx, "Set auth headers for git repository sync request")
+ } else {
+ slog.WarnContext(ctx, "No access token available for environment git repository sync", "environmentID", environmentID)
+ }
+
+ slog.InfoContext(ctx, "Sending git repository sync request to agent", "url", targetURL, "repositoryCount", len(syncItems))
+
+ resp, err := s.httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("failed to send sync request: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ slog.ErrorContext(ctx, "Git repository sync request failed", "statusCode", resp.StatusCode, "response", string(body))
+ return fmt.Errorf("sync request failed with status %d: %s", resp.StatusCode, string(body))
+ }
+
+ var result struct {
+ Success bool `json:"success"`
+ Data struct {
+ Message string `json:"message"`
+ } `json:"data"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to decode sync response: %w", err)
+ }
+
+ if !result.Success {
+ return fmt.Errorf("sync failed: %s", result.Data.Message)
+ }
+
+ slog.InfoContext(ctx, "Successfully synced git repositories to environment", "environmentID", environmentID, "environmentName", environment.Name)
+
+ return nil
+}
+
// ProxyRequest sends a request to a remote environment's API.
func (s *EnvironmentService) ProxyRequest(ctx context.Context, envID string, method string, path string, body []byte) ([]byte, int, error) {
environment, err := s.GetEnvironmentByID(ctx, envID)
diff --git a/backend/internal/services/git_repository_service.go b/backend/internal/services/git_repository_service.go
new file mode 100644
index 000000000..6b2f7b618
--- /dev/null
+++ b/backend/internal/services/git_repository_service.go
@@ -0,0 +1,536 @@
+package services
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/git"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "github.com/getarcaneapp/arcane/types/gitops"
+ "gorm.io/gorm"
+)
+
+type GitRepositoryService struct {
+ db *database.DB
+ gitClient *git.Client
+ eventService *EventService
+}
+
+func NewGitRepositoryService(db *database.DB, workDir string, eventService *EventService) *GitRepositoryService {
+ return &GitRepositoryService{
+ db: db,
+ gitClient: git.NewClient(workDir),
+ eventService: eventService,
+ }
+}
+
+func (s *GitRepositoryService) GetRepositoriesPaginated(ctx context.Context, params pagination.QueryParams) ([]gitops.GitRepository, pagination.Response, error) {
+ var repositories []models.GitRepository
+ q := s.db.WithContext(ctx).Model(&models.GitRepository{})
+
+ if term := strings.TrimSpace(params.Search); term != "" {
+ searchPattern := "%" + term + "%"
+ q = q.Where(
+ "name LIKE ? OR url LIKE ? OR COALESCE(description, '') LIKE ?",
+ searchPattern, searchPattern, searchPattern,
+ )
+ }
+
+ if enabled := params.Filters["enabled"]; enabled != "" {
+ switch enabled {
+ case "true", "1":
+ q = q.Where("enabled = ?", true)
+ case "false", "0":
+ q = q.Where("enabled = ?", false)
+ }
+ }
+
+ if authType := params.Filters["authType"]; authType != "" {
+ q = q.Where("auth_type = ?", authType)
+ }
+
+ paginationResp, err := pagination.PaginateAndSortDB(params, q, &repositories)
+ if err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate git repositories: %w", err)
+ }
+
+ out, mapErr := mapper.MapSlice[models.GitRepository, gitops.GitRepository](repositories)
+ if mapErr != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to map repositories: %w", mapErr)
+ }
+
+ return out, paginationResp, nil
+}
+
+func (s *GitRepositoryService) GetRepositoryByID(ctx context.Context, id string) (*models.GitRepository, error) {
+ var repository models.GitRepository
+ if err := s.db.WithContext(ctx).Where("id = ?", id).First(&repository).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("repository not found")
+ }
+ return nil, fmt.Errorf("failed to get repository: %w", err)
+ }
+ return &repository, nil
+}
+
+func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name string) (*models.GitRepository, error) {
+ var repository models.GitRepository
+ if err := s.db.WithContext(ctx).Where("name = ?", name).First(&repository).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("repository not found")
+ }
+ return nil, fmt.Errorf("failed to get repository: %w", err)
+ }
+ return &repository, nil
+}
+
+func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.CreateGitRepositoryRequest) (*models.GitRepository, error) {
+ repository := models.GitRepository{
+ Name: req.Name,
+ URL: req.URL,
+ AuthType: req.AuthType,
+ Username: req.Username,
+ Description: req.Description,
+ Enabled: true,
+ }
+
+ if req.Enabled != nil {
+ repository.Enabled = *req.Enabled
+ }
+
+ // Encrypt sensitive fields
+ if req.Token != "" {
+ encrypted, err := utils.Encrypt(req.Token)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt token: %w", err)
+ }
+ repository.Token = encrypted
+ }
+
+ if req.SSHKey != "" {
+ encrypted, err := utils.Encrypt(req.SSHKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)
+ }
+ repository.SSHKey = encrypted
+ }
+
+ if err := s.db.WithContext(ctx).Create(&repository).Error; err != nil {
+ return nil, fmt.Errorf("failed to create repository: %w", err)
+ }
+
+ // Log event
+ resourceType := "git_repository"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitRepositoryCreate,
+ Severity: models.EventSeveritySuccess,
+ Title: "Git repository created",
+ Description: fmt.Sprintf("Created git repository '%s' (%s)", repository.Name, repository.URL),
+ ResourceType: &resourceType,
+ ResourceID: &repository.ID,
+ ResourceName: &repository.Name,
+ })
+
+ return &repository, nil
+}
+
+func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string, req models.UpdateGitRepositoryRequest) (*models.GitRepository, error) {
+ repository, err := s.GetRepositoryByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+
+ updates := make(map[string]interface{})
+
+ if req.Name != nil {
+ updates["name"] = *req.Name
+ }
+ if req.URL != nil {
+ updates["url"] = *req.URL
+ }
+ if req.AuthType != nil {
+ updates["auth_type"] = *req.AuthType
+ }
+ if req.Username != nil {
+ updates["username"] = *req.Username
+ }
+ if req.Description != nil {
+ updates["description"] = *req.Description
+ }
+ if req.Enabled != nil {
+ updates["enabled"] = *req.Enabled
+ }
+
+ if req.Token != nil {
+ if *req.Token == "" {
+ updates["token"] = ""
+ } else {
+ encrypted, err := utils.Encrypt(*req.Token)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt token: %w", err)
+ }
+ updates["token"] = encrypted
+ }
+ }
+
+ if req.SSHKey != nil {
+ if *req.SSHKey == "" {
+ updates["ssh_key"] = ""
+ } else {
+ encrypted, err := utils.Encrypt(*req.SSHKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)
+ }
+ updates["ssh_key"] = encrypted
+ }
+ }
+
+ if len(updates) > 0 {
+ if err := s.db.WithContext(ctx).Model(repository).Updates(updates).Error; err != nil {
+ return nil, fmt.Errorf("failed to update repository: %w", err)
+ }
+
+ // Log event
+ resourceType := "git_repository"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitRepositoryUpdate,
+ Severity: models.EventSeveritySuccess,
+ Title: "Git repository updated",
+ Description: fmt.Sprintf("Updated git repository '%s'", repository.Name),
+ ResourceType: &resourceType,
+ ResourceID: &repository.ID,
+ ResourceName: &repository.Name,
+ })
+ }
+
+ return s.GetRepositoryByID(ctx, id)
+}
+
+func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string) error {
+ // Check if repository is used by any syncs
+ var count int64
+ if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("repository_id = ?", id).Count(&count).Error; err != nil {
+ return fmt.Errorf("failed to check repository usage: %w", err)
+ }
+
+ if count > 0 {
+ return fmt.Errorf("repository is used by %d sync configuration(s)", count)
+ }
+
+ // Get repository info before deleting
+ repository, err := s.GetRepositoryByID(ctx, id)
+ if err != nil {
+ return err
+ }
+
+ if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.GitRepository{}).Error; err != nil {
+ return fmt.Errorf("failed to delete repository: %w", err)
+ }
+
+ // Log event
+ resourceType := "git_repository"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitRepositoryDelete,
+ Severity: models.EventSeverityInfo,
+ Title: "Git repository deleted",
+ Description: fmt.Sprintf("Deleted git repository '%s'", repository.Name),
+ ResourceType: &resourceType,
+ ResourceID: &repository.ID,
+ ResourceName: &repository.Name,
+ })
+
+ return nil
+}
+
+func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, branch string) error {
+ repository, err := s.GetRepositoryByID(ctx, id)
+ if err != nil {
+ return err
+ }
+
+ authConfig := git.AuthConfig{
+ AuthType: repository.AuthType,
+ Username: repository.Username,
+ }
+
+ if repository.Token != "" {
+ token, err := utils.Decrypt(repository.Token)
+ if err != nil {
+ return fmt.Errorf("failed to decrypt token: %w", err)
+ }
+ authConfig.Token = token
+ }
+
+ if repository.SSHKey != "" {
+ sshKey, err := utils.Decrypt(repository.SSHKey)
+ if err != nil {
+ return fmt.Errorf("failed to decrypt SSH key: %w", err)
+ }
+ authConfig.SSHKey = sshKey
+ }
+
+ if branch == "" {
+ branch = "main"
+ }
+
+ err = s.gitClient.TestConnection(repository.URL, branch, authConfig)
+ if err != nil {
+ // Log error event
+ resourceType := "git_repository"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitRepositoryError,
+ Severity: models.EventSeverityError,
+ Title: "Git repository connection test failed",
+ Description: fmt.Sprintf("Failed to connect to repository '%s': %s", repository.Name, err.Error()),
+ ResourceType: &resourceType,
+ ResourceID: &repository.ID,
+ ResourceName: &repository.Name,
+ })
+ return err
+ }
+
+ // Log success event
+ resourceType := "git_repository"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitRepositoryTest,
+ Severity: models.EventSeveritySuccess,
+ Title: "Git repository connection successful",
+ Description: fmt.Sprintf("Successfully connected to repository '%s'", repository.Name),
+ ResourceType: &resourceType,
+ ResourceID: &repository.ID,
+ ResourceName: &repository.Name,
+ })
+
+ return nil
+}
+
+func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *models.GitRepository) (git.AuthConfig, error) {
+ authConfig := git.AuthConfig{
+ AuthType: repository.AuthType,
+ Username: repository.Username,
+ }
+
+ if repository.Token != "" {
+ token, err := utils.Decrypt(repository.Token)
+ if err != nil {
+ return authConfig, fmt.Errorf("failed to decrypt token: %w", err)
+ }
+ authConfig.Token = token
+ }
+
+ if repository.SSHKey != "" {
+ sshKey, err := utils.Decrypt(repository.SSHKey)
+ if err != nil {
+ return authConfig, fmt.Errorf("failed to decrypt SSH key: %w", err)
+ }
+ authConfig.SSHKey = sshKey
+ }
+
+ return authConfig, nil
+}
+
+func (s *GitRepositoryService) ListBranches(ctx context.Context, id string) ([]gitops.BranchInfo, error) {
+ repository, err := s.GetRepositoryByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+
+ authConfig, err := s.GetAuthConfig(ctx, repository)
+ if err != nil {
+ return nil, err
+ }
+
+ branches, err := s.gitClient.ListBranches(repository.URL, authConfig)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list branches: %w", err)
+ }
+
+ var result []gitops.BranchInfo
+ for _, branch := range branches {
+ result = append(result, gitops.BranchInfo{
+ Name: branch.Name,
+ IsDefault: branch.IsDefault,
+ })
+ }
+
+ return result, nil
+}
+
+func (s *GitRepositoryService) BrowseFiles(ctx context.Context, id, branch, path string) (*gitops.BrowseResponse, error) {
+ repository, err := s.GetRepositoryByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+
+ authConfig, err := s.GetAuthConfig(ctx, repository)
+ if err != nil {
+ return nil, err
+ }
+
+ // Clone the repository
+ repoPath, err := s.gitClient.Clone(repository.URL, branch, authConfig)
+ if err != nil {
+ return nil, fmt.Errorf("failed to clone repository: %w", err)
+ }
+ defer func() {
+ if cleanupErr := s.gitClient.Cleanup(repoPath); cleanupErr != nil {
+ // Log cleanup error but don't fail the operation
+ _ = cleanupErr
+ }
+ }()
+
+ // Browse the tree
+ files, err := s.gitClient.BrowseTree(repoPath, path)
+ if err != nil {
+ return nil, err
+ }
+
+ return &gitops.BrowseResponse{
+ Path: path,
+ Files: files,
+ }, nil
+}
+
+// SyncRepositories syncs repositories from a manager to this agent instance.
+// It creates, updates, or deletes repositories to match the provided list.
+func (s *GitRepositoryService) SyncRepositories(ctx context.Context, syncItems []gitops.RepositorySync) error {
+ existingMap, err := s.getExistingRepositoriesMap(ctx)
+ if err != nil {
+ return err
+ }
+
+ syncedIDs := make(map[string]bool)
+
+ // Process each sync item
+ for _, item := range syncItems {
+ syncedIDs[item.ID] = true
+
+ if err := s.processSyncItem(ctx, item, existingMap); err != nil {
+ return err
+ }
+ }
+
+ // Delete repositories that are not in the sync list
+ return s.deleteUnsynced(ctx, existingMap, syncedIDs)
+}
+
+func (s *GitRepositoryService) getExistingRepositoriesMap(ctx context.Context) (map[string]*models.GitRepository, error) {
+ var existing []models.GitRepository
+ if err := s.db.WithContext(ctx).Find(&existing).Error; err != nil {
+ return nil, fmt.Errorf("failed to get existing repositories: %w", err)
+ }
+
+ existingMap := make(map[string]*models.GitRepository)
+ for i := range existing {
+ existingMap[existing[i].ID] = &existing[i]
+ }
+ return existingMap, nil
+}
+
+func (s *GitRepositoryService) processSyncItem(ctx context.Context, item gitops.RepositorySync, existingMap map[string]*models.GitRepository) error {
+ existing, exists := existingMap[item.ID]
+ if exists {
+ return s.updateExistingRepository(ctx, item, existing)
+ }
+ return s.createNewRepository(ctx, item)
+}
+
+func (s *GitRepositoryService) updateExistingRepository(ctx context.Context, item gitops.RepositorySync, existing *models.GitRepository) error {
+ needsUpdate := s.checkRepositoryNeedsUpdate(item, existing)
+
+ if needsUpdate {
+ // Use Save to trigger GORM callbacks including UpdatedAt
+ if err := s.db.WithContext(ctx).Save(existing).Error; err != nil {
+ return fmt.Errorf("failed to update repository %s: %w", item.ID, err)
+ }
+ }
+
+ return nil
+}
+
+func (s *GitRepositoryService) checkRepositoryNeedsUpdate(item gitops.RepositorySync, existing *models.GitRepository) bool {
+ needsUpdate := utils.UpdateIfChanged(&existing.Name, item.Name)
+ needsUpdate = utils.UpdateIfChanged(&existing.URL, item.URL) || needsUpdate
+ needsUpdate = utils.UpdateIfChanged(&existing.AuthType, item.AuthType) || needsUpdate
+ needsUpdate = utils.UpdateIfChanged(&existing.Username, item.Username) || needsUpdate
+ needsUpdate = utils.UpdateIfChanged(&existing.Description, item.Description) || needsUpdate
+ needsUpdate = utils.UpdateIfChanged(&existing.Enabled, item.Enabled) || needsUpdate
+
+ // Handle Token update
+ if item.Token != "" {
+ encryptedToken, err := utils.Encrypt(item.Token)
+ if err == nil {
+ needsUpdate = utils.UpdateIfChanged(&existing.Token, encryptedToken) || needsUpdate
+ }
+ } else if existing.Token != "" {
+ existing.Token = ""
+ needsUpdate = true
+ }
+
+ // Handle SSH Key update
+ if item.SSHKey != "" {
+ encryptedSSHKey, err := utils.Encrypt(item.SSHKey)
+ if err == nil {
+ needsUpdate = utils.UpdateIfChanged(&existing.SSHKey, encryptedSSHKey) || needsUpdate
+ }
+ } else if existing.SSHKey != "" {
+ existing.SSHKey = ""
+ needsUpdate = true
+ }
+
+ return needsUpdate
+}
+
+func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitops.RepositorySync) error {
+ var encryptedToken, encryptedSSHKey string
+ var err error
+
+ if item.Token != "" {
+ encryptedToken, err = utils.Encrypt(item.Token)
+ if err != nil {
+ return fmt.Errorf("failed to encrypt token for repository %s: %w", item.ID, err)
+ }
+ }
+
+ if item.SSHKey != "" {
+ encryptedSSHKey, err = utils.Encrypt(item.SSHKey)
+ if err != nil {
+ return fmt.Errorf("failed to encrypt SSH key for repository %s: %w", item.ID, err)
+ }
+ }
+
+ repo := models.GitRepository{
+ Name: item.Name,
+ URL: item.URL,
+ AuthType: item.AuthType,
+ Username: item.Username,
+ Token: encryptedToken,
+ SSHKey: encryptedSSHKey,
+ Description: item.Description,
+ Enabled: item.Enabled,
+ }
+ repo.ID = item.ID
+
+ if err := s.db.WithContext(ctx).Create(&repo).Error; err != nil {
+ return fmt.Errorf("failed to create repository %s: %w", item.ID, err)
+ }
+
+ return nil
+}
+
+func (s *GitRepositoryService) deleteUnsynced(ctx context.Context, existingMap map[string]*models.GitRepository, syncedIDs map[string]bool) error {
+ for id := range existingMap {
+ if !syncedIDs[id] {
+ if err := s.db.WithContext(ctx).Delete(&models.GitRepository{}, "id = ?", id).Error; err != nil {
+ return fmt.Errorf("failed to delete repository %s: %w", id, err)
+ }
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.go
new file mode 100644
index 000000000..51edbf49a
--- /dev/null
+++ b/backend/internal/services/gitops_sync_service.go
@@ -0,0 +1,587 @@
+package services
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "github.com/getarcaneapp/arcane/types/gitops"
+ "gorm.io/gorm"
+)
+
+type GitOpsSyncService struct {
+ db *database.DB
+ repoService *GitRepositoryService
+ projectService *ProjectService
+ eventService *EventService
+}
+
+func NewGitOpsSyncService(db *database.DB, repoService *GitRepositoryService, projectService *ProjectService, eventService *EventService) *GitOpsSyncService {
+ return &GitOpsSyncService{
+ db: db,
+ repoService: repoService,
+ projectService: projectService,
+ eventService: eventService,
+ }
+}
+
+func (s *GitOpsSyncService) GetSyncsPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]gitops.GitOpsSync, pagination.Response, error) {
+ var syncs []models.GitOpsSync
+ q := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Preload("Repository").Preload("Project").
+ Where("environment_id = ?", environmentID)
+
+ if term := strings.TrimSpace(params.Search); term != "" {
+ searchPattern := "%" + term + "%"
+ q = q.Where(
+ "name LIKE ? OR branch LIKE ? OR compose_path LIKE ?",
+ searchPattern, searchPattern, searchPattern,
+ )
+ }
+
+ if enabled := params.Filters["enabled"]; enabled != "" {
+ switch enabled {
+ case "true", "1":
+ q = q.Where("enabled = ?", true)
+ case "false", "0":
+ q = q.Where("enabled = ?", false)
+ }
+ }
+
+ if autoSync := params.Filters["autoSync"]; autoSync != "" {
+ switch autoSync {
+ case "true", "1":
+ q = q.Where("auto_sync = ?", true)
+ case "false", "0":
+ q = q.Where("auto_sync = ?", false)
+ }
+ }
+
+ if repositoryID := params.Filters["repositoryId"]; repositoryID != "" {
+ q = q.Where("repository_id = ?", repositoryID)
+ }
+
+ if projectID := params.Filters["projectId"]; projectID != "" {
+ q = q.Where("project_id = ?", projectID)
+ }
+
+ paginationResp, err := pagination.PaginateAndSortDB(params, q, &syncs)
+ if err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate gitops syncs: %w", err)
+ }
+
+ out, mapErr := mapper.MapSlice[models.GitOpsSync, gitops.GitOpsSync](syncs)
+ if mapErr != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to map syncs: %w", mapErr)
+ }
+
+ return out, paginationResp, nil
+}
+
+func (s *GitOpsSyncService) GetSyncByID(ctx context.Context, environmentID, id string) (*models.GitOpsSync, error) {
+ var sync models.GitOpsSync
+ q := s.db.WithContext(ctx).Preload("Repository").Preload("Project").Where("id = ?", id)
+ if environmentID != "" {
+ q = q.Where("environment_id = ?", environmentID)
+ }
+ if err := q.First(&sync).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("sync not found")
+ }
+ return nil, fmt.Errorf("failed to get sync: %w", err)
+ }
+ return &sync, nil
+}
+
+func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string, req gitops.CreateSyncRequest) (*models.GitOpsSync, error) {
+ // Validate repository exists
+ _, err := s.repoService.GetRepositoryByID(ctx, req.RepositoryID)
+ if err != nil {
+ return nil, fmt.Errorf("repository not found: %w", err)
+ }
+
+ // Store the project name - use sync name if project name not provided
+ projectName := req.ProjectName
+ if projectName == "" {
+ projectName = req.Name
+ }
+
+ sync := models.GitOpsSync{
+ Name: req.Name,
+ EnvironmentID: environmentID,
+ RepositoryID: req.RepositoryID,
+ Branch: req.Branch,
+ ComposePath: req.ComposePath,
+ ProjectName: projectName,
+ ProjectID: nil, // Will be set during first sync
+ AutoSync: false,
+ SyncInterval: 60,
+ Enabled: true,
+ }
+
+ if req.AutoSync != nil {
+ sync.AutoSync = *req.AutoSync
+ }
+ if req.SyncInterval != nil {
+ sync.SyncInterval = *req.SyncInterval
+ }
+ if req.Enabled != nil {
+ sync.Enabled = *req.Enabled
+ }
+
+ if err := s.db.WithContext(ctx).Create(&sync).Error; err != nil {
+ return nil, fmt.Errorf("failed to create sync: %w", err)
+ }
+
+ // Log event
+ resourceType := "git_sync"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitSyncCreate,
+ Severity: models.EventSeveritySuccess,
+ Title: "Git sync created",
+ Description: fmt.Sprintf("Created git sync configuration '%s'", sync.Name),
+ ResourceType: &resourceType,
+ ResourceID: &sync.ID,
+ ResourceName: &sync.Name,
+ UserID: &systemUser.ID,
+ Username: &systemUser.Username,
+ })
+
+ if _, err := s.PerformSync(ctx, sync.EnvironmentID, sync.ID); err != nil {
+ slog.ErrorContext(ctx, "Failed to perform initial sync after creation", "syncId", sync.ID, "error", err)
+ // Don't fail the entire creation - the sync config exists and can be retried
+ }
+
+ return s.GetSyncByID(ctx, "", sync.ID)
+}
+
+func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id string, req gitops.UpdateSyncRequest) (*models.GitOpsSync, error) {
+ sync, err := s.GetSyncByID(ctx, environmentID, id)
+ if err != nil {
+ return nil, err
+ }
+
+ updates := make(map[string]interface{})
+
+ if req.Name != nil {
+ updates["name"] = *req.Name
+ }
+ if req.RepositoryID != nil {
+ // Validate repository exists
+ _, err := s.repoService.GetRepositoryByID(ctx, *req.RepositoryID)
+ if err != nil {
+ return nil, fmt.Errorf("repository not found: %w", err)
+ }
+ updates["repository_id"] = *req.RepositoryID
+ }
+ if req.Branch != nil {
+ updates["branch"] = *req.Branch
+ }
+ if req.ComposePath != nil {
+ updates["compose_path"] = *req.ComposePath
+ }
+ if req.ProjectName != nil {
+ updates["project_name"] = *req.ProjectName
+ }
+ if req.AutoSync != nil {
+ updates["auto_sync"] = *req.AutoSync
+ }
+ if req.SyncInterval != nil {
+ updates["sync_interval"] = *req.SyncInterval
+ }
+ if req.Enabled != nil {
+ updates["enabled"] = *req.Enabled
+ }
+
+ if len(updates) > 0 {
+ if err := s.db.WithContext(ctx).Model(sync).Updates(updates).Error; err != nil {
+ return nil, fmt.Errorf("failed to update sync: %w", err)
+ }
+
+ // Log event
+ resourceType := "git_sync"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitSyncUpdate,
+ Severity: models.EventSeveritySuccess,
+ Title: "Git sync updated",
+ Description: fmt.Sprintf("Updated git sync configuration '%s'", sync.Name),
+ ResourceType: &resourceType,
+ ResourceID: &sync.ID,
+ ResourceName: &sync.Name,
+ })
+ }
+
+ return s.GetSyncByID(ctx, environmentID, id)
+}
+
+func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id string) error {
+ // Get sync info before deleting
+ sync, err := s.GetSyncByID(ctx, environmentID, id)
+ if err != nil {
+ return err
+ }
+
+ if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.GitOpsSync{}).Error; err != nil {
+ return fmt.Errorf("failed to delete sync: %w", err)
+ }
+
+ // Log event
+ resourceType := "git_sync"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitSyncDelete,
+ Severity: models.EventSeverityInfo,
+ Title: "Git sync deleted",
+ Description: fmt.Sprintf("Deleted git sync configuration '%s'", sync.Name),
+ ResourceType: &resourceType,
+ ResourceID: &sync.ID,
+ ResourceName: &sync.Name, UserID: &systemUser.ID,
+ Username: &systemUser.Username})
+
+ return nil
+}
+
+func (s *GitOpsSyncService) PerformSync(ctx context.Context, environmentID, id string) (*gitops.SyncResult, error) {
+ sync, err := s.GetSyncByID(ctx, environmentID, id)
+ if err != nil {
+ return nil, err
+ }
+
+ result := &gitops.SyncResult{
+ Success: false,
+ SyncedAt: time.Now(),
+ }
+
+ // Get repository and auth config
+ repository := sync.Repository
+ if repository == nil {
+ return result, s.failSync(ctx, id, result, sync, "Repository not found", "repository not found")
+ }
+
+ authConfig, err := s.repoService.GetAuthConfig(ctx, repository)
+ if err != nil {
+ return result, s.failSync(ctx, id, result, sync, "Failed to get authentication config", err.Error())
+ }
+
+ // Clone the repository
+ repoPath, err := s.repoService.gitClient.Clone(repository.URL, sync.Branch, authConfig)
+ if err != nil {
+ return result, s.failSync(ctx, id, result, sync, "Failed to clone repository", err.Error())
+ }
+ defer func() {
+ if cleanupErr := s.repoService.gitClient.Cleanup(repoPath); cleanupErr != nil {
+ slog.WarnContext(ctx, "Failed to cleanup repository", "path", repoPath, "error", cleanupErr)
+ }
+ }()
+
+ // Get the current commit hash
+ commitHash, err := s.repoService.gitClient.GetCurrentCommit(repoPath)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to get commit hash", "error", err)
+ commitHash = ""
+ }
+
+ // Check if compose file exists
+ if !s.repoService.gitClient.FileExists(repoPath, sync.ComposePath) {
+ errMsg := fmt.Sprintf("compose file not found: %s", sync.ComposePath)
+ return result, s.failSync(ctx, id, result, sync, fmt.Sprintf("Compose file not found at %s", sync.ComposePath), errMsg)
+ }
+
+ // Read compose file content
+ composeContent, err := s.repoService.gitClient.ReadFile(repoPath, sync.ComposePath)
+ if err != nil {
+ return result, s.failSync(ctx, id, result, sync, "Failed to read compose file", err.Error())
+ }
+
+ // Get or create project
+ project, err := s.getOrCreateProject(ctx, sync, id, composeContent, result)
+ if err != nil {
+ return result, err
+ }
+
+ // Update sync status
+ s.updateSyncStatus(ctx, id, "success", "", commitHash)
+
+ result.Success = true
+ result.Message = fmt.Sprintf("Successfully synced compose file from %s to project %s", sync.ComposePath, project.Name)
+
+ // Log success event
+ resourceType := "git_sync"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitSyncRun,
+ Severity: models.EventSeveritySuccess,
+ Title: "Git sync completed",
+ Description: fmt.Sprintf("Successfully synced '%s' to project '%s'", sync.Name, project.Name),
+ ResourceType: &resourceType,
+ ResourceID: &sync.ID,
+ ResourceName: &sync.Name,
+ UserID: &systemUser.ID,
+ Username: &systemUser.Username,
+ })
+
+ slog.InfoContext(ctx, "GitOps sync completed", "syncId", id, "project", project.Name)
+
+ return result, nil
+}
+
+func (s *GitOpsSyncService) updateSyncStatus(ctx context.Context, id, status, errorMsg, commitHash string) {
+ now := time.Now()
+ updates := map[string]interface{}{
+ "last_sync_at": now,
+ "last_sync_status": status,
+ }
+
+ if errorMsg != "" {
+ updates["last_sync_error"] = errorMsg
+ } else {
+ updates["last_sync_error"] = nil
+ }
+
+ if commitHash != "" {
+ updates["last_sync_commit"] = commitHash
+ }
+
+ if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("id = ?", id).Updates(updates).Error; err != nil {
+ slog.ErrorContext(ctx, "Failed to update sync status", "error", err, "syncId", id)
+ }
+}
+
+func (s *GitOpsSyncService) GetSyncStatus(ctx context.Context, environmentID, id string) (*gitops.SyncStatus, error) {
+ sync, err := s.GetSyncByID(ctx, environmentID, id)
+ if err != nil {
+ return nil, err
+ }
+
+ status := &gitops.SyncStatus{
+ ID: sync.ID,
+ Enabled: sync.Enabled,
+ AutoSync: sync.AutoSync,
+ LastSyncAt: sync.LastSyncAt,
+ LastSyncStatus: sync.LastSyncStatus,
+ LastSyncError: sync.LastSyncError,
+ LastSyncCommit: sync.LastSyncCommit,
+ }
+
+ // Calculate next sync time
+ if sync.AutoSync && sync.Enabled && sync.LastSyncAt != nil {
+ nextSync := sync.LastSyncAt.Add(time.Duration(sync.SyncInterval) * time.Minute)
+ status.NextSyncAt = &nextSync
+ }
+
+ return status, nil
+}
+
+func (s *GitOpsSyncService) SyncAllEnabled(ctx context.Context) error {
+ var syncs []models.GitOpsSync
+ if err := s.db.WithContext(ctx).
+ Preload("Repository").
+ Preload("Project").
+ Where("enabled = ? AND auto_sync = ?", true, true).
+ Find(&syncs).Error; err != nil {
+ return fmt.Errorf("failed to get enabled syncs: %w", err)
+ }
+
+ for _, sync := range syncs {
+ // Check if sync is due
+ if sync.LastSyncAt != nil {
+ nextSync := sync.LastSyncAt.Add(time.Duration(sync.SyncInterval) * time.Minute)
+ if time.Now().Before(nextSync) {
+ continue
+ }
+ }
+
+ // Perform sync
+ result, err := s.PerformSync(ctx, sync.EnvironmentID, sync.ID)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to sync", "syncId", sync.ID, "error", err)
+ continue
+ }
+
+ if result.Success {
+ slog.InfoContext(ctx, "Sync completed", "syncId", sync.ID, "message", result.Message)
+ }
+ }
+
+ return nil
+}
+
+func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id string, path string) (*gitops.BrowseResponse, error) {
+ sync, err := s.GetSyncByID(ctx, environmentID, id)
+ if err != nil {
+ return nil, err
+ }
+
+ repository := sync.Repository
+ if repository == nil {
+ return nil, fmt.Errorf("repository not found")
+ }
+
+ authConfig, err := s.repoService.GetAuthConfig(ctx, repository)
+ if err != nil {
+ return nil, err
+ }
+
+ // Clone the repository
+ repoPath, err := s.repoService.gitClient.Clone(repository.URL, sync.Branch, authConfig)
+ if err != nil {
+ return nil, fmt.Errorf("failed to clone repository: %w", err)
+ }
+ defer func() {
+ if cleanupErr := s.repoService.gitClient.Cleanup(repoPath); cleanupErr != nil {
+ slog.WarnContext(ctx, "Failed to cleanup repository", "path", repoPath, "error", cleanupErr)
+ }
+ }()
+
+ // Browse the tree
+ files, err := s.repoService.gitClient.BrowseTree(repoPath, path)
+ if err != nil {
+ return nil, err
+ }
+
+ return &gitops.BrowseResponse{
+ Path: path,
+ Files: files,
+ }, nil
+}
+
+func (s *GitOpsSyncService) ImportSyncs(ctx context.Context, environmentID string, req []gitops.ImportGitOpsSyncRequest) (*gitops.ImportGitOpsSyncResponse, error) {
+ response := &gitops.ImportGitOpsSyncResponse{
+ SuccessCount: 0,
+ FailedCount: 0,
+ Errors: []string{},
+ }
+
+ for _, importItem := range req {
+ // Find repository by name
+ repo, err := s.repoService.GetRepositoryByName(ctx, importItem.GitRepo)
+ if err != nil {
+ response.FailedCount++
+ response.Errors = append(response.Errors, fmt.Sprintf("Stack '%s': Repository '%s' not found (%v)", importItem.SyncName, importItem.GitRepo, err))
+ continue
+ }
+
+ createReq := gitops.CreateSyncRequest{
+ Name: importItem.SyncName,
+ RepositoryID: repo.ID,
+ Branch: importItem.Branch,
+ ComposePath: importItem.DockerComposePath,
+ ProjectName: importItem.SyncName,
+ AutoSync: &importItem.AutoSync,
+ SyncInterval: &importItem.SyncInterval,
+ Enabled: &importItem.Enabled,
+ }
+
+ _, err = s.CreateSync(ctx, environmentID, createReq)
+ if err != nil {
+ response.FailedCount++
+ response.Errors = append(response.Errors, fmt.Sprintf("Stack '%s': %v", importItem.SyncName, err))
+ } else {
+ response.SuccessCount++
+ }
+ }
+
+ return response, nil
+}
+
+func (s *GitOpsSyncService) logSyncError(ctx context.Context, sync *models.GitOpsSync, errorMsg string) {
+ resourceType := "git_sync"
+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeGitSyncError,
+ Severity: models.EventSeverityError,
+ Title: "Git sync failed",
+ Description: fmt.Sprintf("Failed to sync '%s': %s", sync.Name, errorMsg),
+ ResourceType: &resourceType,
+ ResourceID: &sync.ID,
+ ResourceName: &sync.Name, UserID: &systemUser.ID,
+ Username: &systemUser.Username})
+}
+
+func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *gitops.SyncResult, sync *models.GitOpsSync, message, errMsg string) error {
+ result.Message = message
+ result.Error = &errMsg
+ s.updateSyncStatus(ctx, id, "failed", errMsg, "")
+ s.logSyncError(ctx, sync, errMsg)
+ return fmt.Errorf("%s", errMsg)
+}
+
+func (s *GitOpsSyncService) createProjectForSync(ctx context.Context, sync *models.GitOpsSync, id string, composeContent string, result *gitops.SyncResult) (*models.Project, error) {
+ project, err := s.projectService.CreateProject(ctx, sync.ProjectName, composeContent, nil, systemUser)
+ if err != nil {
+ return nil, s.failSync(ctx, id, result, sync, "Failed to create project", err.Error())
+ }
+
+ // Update sync with project ID
+ if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("id = ?", id).Updates(map[string]interface{}{
+ "project_id": project.ID,
+ }).Error; err != nil {
+ return nil, s.failSync(ctx, id, result, sync, "Failed to update sync with project ID", err.Error())
+ }
+
+ // Mark project as GitOps-managed
+ if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", id).Error; err != nil {
+ return nil, s.failSync(ctx, id, result, sync, "Failed to mark project as GitOps-managed", err.Error())
+ }
+
+ slog.InfoContext(ctx, "Created project for GitOps sync", "projectName", sync.ProjectName, "projectId", project.ID)
+
+ // Deploy the project immediately after creation
+ slog.InfoContext(ctx, "Deploying project after initial Git sync", "projectName", project.Name, "projectId", project.ID)
+ if err := s.projectService.DeployProject(ctx, project.ID, systemUser); err != nil {
+ slog.ErrorContext(ctx, "Failed to deploy project after initial Git sync", "error", err, "projectId", project.ID)
+ }
+
+ return project, nil
+}
+
+func (s *GitOpsSyncService) getOrCreateProject(ctx context.Context, sync *models.GitOpsSync, id string, composeContent string, result *gitops.SyncResult) (*models.Project, error) {
+ var project *models.Project
+ var err error
+
+ if sync.ProjectID != nil && *sync.ProjectID != "" {
+ project, err = s.projectService.GetProjectFromDatabaseByID(ctx, *sync.ProjectID)
+ if err != nil {
+ slog.WarnContext(ctx, "Existing project not found, will create new one", "projectId", *sync.ProjectID, "error", err)
+ project = nil
+ }
+ }
+
+ if project == nil {
+ return s.createProjectForSync(ctx, sync, id, composeContent, result)
+ }
+
+ if err := s.updateProjectForSync(ctx, sync, id, project, composeContent, result); err != nil {
+ return nil, err
+ }
+ return project, nil
+}
+
+func (s *GitOpsSyncService) updateProjectForSync(ctx context.Context, sync *models.GitOpsSync, id string, project *models.Project, composeContent string, result *gitops.SyncResult) error {
+ // Get current content to see if it changed
+ oldCompose, _, _ := s.projectService.GetProjectContent(ctx, project.ID)
+ contentChanged := oldCompose != composeContent
+
+ // Update existing project's compose file
+ _, err := s.projectService.UpdateProject(ctx, project.ID, nil, &composeContent, nil)
+ if err != nil {
+ return s.failSync(ctx, id, result, sync, "Failed to update project compose file", err.Error())
+ }
+ slog.InfoContext(ctx, "Updated project compose file", "projectName", project.Name, "projectId", project.ID)
+
+ // If content changed and project is running, redeploy
+ if contentChanged {
+ details, err := s.projectService.GetProjectDetails(ctx, project.ID)
+ if err == nil && (details.Status == string(models.ProjectStatusRunning) || details.Status == string(models.ProjectStatusPartiallyRunning)) {
+ slog.InfoContext(ctx, "Redeploying project due to content change from Git sync", "projectName", project.Name, "projectId", project.ID)
+ if err := s.projectService.RedeployProject(ctx, project.ID, systemUser); err != nil {
+ slog.ErrorContext(ctx, "Failed to redeploy project after Git sync", "error", err, "projectId", project.ID)
+ }
+ }
+ }
+
+ return nil
+}
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index 2c05391e3..23f7f8db6 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -279,79 +279,41 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string
composeContent, envContent, _ := s.GetProjectContent(ctx, projectID)
- // Parse include files from the compose file
- var includeFiles []project.IncludeFile
- composeFile, detectErr := projects.DetectComposeFile(proj.Path)
- if detectErr == nil {
- includes, parseErr := projects.ParseIncludes(composeFile)
- if parseErr == nil {
- slog.InfoContext(ctx, "Parsed includes", "count", len(includes), "projectID", projectID)
- for _, inc := range includes {
- includeFiles = append(includeFiles, project.IncludeFile{
- Path: inc.Path,
- RelativePath: inc.RelativePath,
- Content: inc.Content,
- })
- }
- } else {
- slog.WarnContext(ctx, "Failed to parse includes", "error", parseErr, "projectID", projectID)
- }
- } else {
- slog.WarnContext(ctx, "Failed to detect compose file", "error", detectErr, "projectID", projectID, "path", proj.Path)
- }
-
- services, serr := s.GetProjectServices(ctx, projectID)
-
- var serviceCount, runningCount int
- var liveStatus models.ProjectStatus
-
- if serr == nil && services != nil {
- serviceCount = len(services)
- _, runningCount = s.getServiceCounts(services)
- liveStatus = s.calculateProjectStatus(services)
- } else {
- serviceCount = proj.ServiceCount
- runningCount = proj.RunningCount
- liveStatus = proj.Status
- }
-
var resp project.Details
if err := mapper.MapStruct(proj, &resp); err != nil {
return project.Details{}, fmt.Errorf("failed to map project: %w", err)
}
- resp.Status = string(liveStatus)
+
resp.CreatedAt = proj.CreatedAt.Format(time.RFC3339)
resp.UpdatedAt = proj.UpdatedAt.Format(time.RFC3339)
resp.ComposeContent = composeContent
resp.EnvContent = envContent
- resp.IncludeFiles = includeFiles
- resp.ServiceCount = serviceCount
- resp.RunningCount = runningCount
resp.DirName = utils.DerefString(proj.DirName)
+ resp.GitOpsManagedBy = proj.GitOpsManagedBy
- // Load compose services from the compose file
- projectsDirSetting := s.settingsService.GetStringSetting(ctx, "projectsDirectory", "data/projects")
- projectsDirectory, _ := fs.GetProjectsDirectory(ctx, strings.TrimSpace(projectsDirSetting))
- if composeFile != "" {
- pathMapper, pmErr := s.getPathMapper(ctx)
- if pmErr != nil {
- slog.WarnContext(ctx, "failed to create path mapper, continuing without translation", "error", pmErr)
- }
+ // Default counts/status from DB (will be overridden if runtime check succeeds)
+ resp.ServiceCount = proj.ServiceCount
+ resp.RunningCount = proj.RunningCount
+ resp.Status = string(proj.Status)
- autoInjectEnv := s.settingsService.GetBoolSetting(ctx, "autoInjectEnv", false)
- composeProj, loadErr := projects.LoadComposeProject(ctx, composeFile, normalizeComposeProjectName(proj.Name), projectsDirectory, autoInjectEnv, pathMapper)
- if loadErr == nil && composeProj != nil {
- // Convert map to slice
- svcList := make([]composetypes.ServiceConfig, 0, len(composeProj.Services))
- for _, svc := range composeProj.Services {
- svcList = append(svcList, svc)
- }
- resp.Services = svcList
- }
+ // Enrich with details
+ s.enrichWithIncludeFiles(ctx, proj.Path, &resp)
+ s.enrichWithGitOpsInfo(ctx, proj, &resp)
+
+ // Load compose project for service definitions
+ composeFile, _ := projects.DetectComposeFile(proj.Path)
+ if composeFile != "" {
+ s.enrichWithComposeServiceConfigs(ctx, proj, composeFile, &resp)
}
- // Convert ProjectServiceInfo to project.RuntimeService
+ // Get runtime services and update status/counts
+ services, serr := s.GetProjectServices(ctx, projectID)
if serr == nil && services != nil {
+ resp.ServiceCount = len(services)
+ _, runningCount := s.getServiceCounts(services)
+ resp.RunningCount = runningCount
+ resp.Status = string(s.calculateProjectStatus(services))
+
runtimeServices := make([]project.RuntimeService, len(services))
for i, svc := range services {
runtimeServices[i] = project.RuntimeService{
@@ -371,6 +333,59 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string
return resp, nil
}
+func (s *ProjectService) enrichWithIncludeFiles(ctx context.Context, projectPath string, resp *project.Details) {
+ composeFile, detectErr := projects.DetectComposeFile(projectPath)
+ if detectErr == nil {
+ includes, parseErr := projects.ParseIncludes(composeFile)
+ if parseErr == nil {
+ var includeFiles []project.IncludeFile
+ for _, inc := range includes {
+ includeFiles = append(includeFiles, project.IncludeFile{
+ Path: inc.Path,
+ RelativePath: inc.RelativePath,
+ Content: inc.Content,
+ })
+ }
+ resp.IncludeFiles = includeFiles
+ } else {
+ slog.WarnContext(ctx, "Failed to parse includes", "error", parseErr, "path", projectPath)
+ }
+ }
+}
+
+func (s *ProjectService) enrichWithGitOpsInfo(ctx context.Context, proj *models.Project, resp *project.Details) {
+ if proj.GitOpsManagedBy != nil {
+ var sync models.GitOpsSync
+ if err := s.db.WithContext(ctx).Preload("Repository").Where("id = ?", *proj.GitOpsManagedBy).First(&sync).Error; err == nil {
+ resp.LastSyncCommit = sync.LastSyncCommit
+ if sync.Repository != nil {
+ resp.GitRepositoryURL = sync.Repository.URL
+ }
+ }
+ }
+}
+
+func (s *ProjectService) enrichWithComposeServiceConfigs(ctx context.Context, proj *models.Project, composeFile string, resp *project.Details) {
+ projectsDirSetting := s.settingsService.GetStringSetting(ctx, "projectsDirectory", "data/projects")
+ projectsDirectory, _ := fs.GetProjectsDirectory(ctx, strings.TrimSpace(projectsDirSetting))
+
+ pathMapper, pmErr := s.getPathMapper(ctx)
+ if pmErr != nil {
+ slog.WarnContext(ctx, "failed to create path mapper, continuing without translation", "error", pmErr)
+ }
+
+ autoInjectEnv := s.settingsService.GetBoolSetting(ctx, "autoInjectEnv", false)
+ composeProj, loadErr := projects.LoadComposeProject(ctx, composeFile, normalizeComposeProjectName(proj.Name), projectsDirectory, autoInjectEnv, pathMapper)
+ if loadErr == nil && composeProj != nil {
+ // Convert map to slice
+ svcList := make([]composetypes.ServiceConfig, 0, len(composeProj.Services))
+ for _, svc := range composeProj.Services {
+ svcList = append(svcList, svc)
+ }
+ resp.Services = svcList
+ }
+}
+
func (s *ProjectService) SyncProjectsFromFileSystem(ctx context.Context) error {
projectsDirSetting := s.settingsService.GetStringSetting(ctx, "projectsDirectory", "data/projects")
projectsDir, err := fs.GetProjectsDirectory(ctx, strings.TrimSpace(projectsDirSetting))
@@ -703,9 +718,11 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us
slog.Warn("ensure images present failed (continuing to compose up)", "projectID", projectID, "error", perr)
}
- slog.Info("starting compose up with health check support", "projectID", projectID, "projectName", project.Name, "services", len(project.Services))
+ removeOrphans := projectFromDb.GitOpsManagedBy != nil && *projectFromDb.GitOpsManagedBy != ""
+
+ slog.Info("starting compose up with health check support", "projectID", projectID, "projectName", project.Name, "services", len(project.Services), "removeOrphans", removeOrphans)
// Health/progress streaming (if any) is handled inside projects.ComposeUp via ctx.
- if err := projects.ComposeUp(ctx, project, nil); err != nil {
+ if err := projects.ComposeUp(ctx, project, nil, removeOrphans); err != nil {
slog.Error("compose up failed", "projectName", project.Name, "projectID", projectID, "error", err)
if containers, psErr := s.GetProjectServices(ctx, projectID); psErr == nil {
slog.Info("containers after failed deploy", "projectID", projectID, "containers", containers)
@@ -808,7 +825,8 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent
}
if err := fs.SaveOrUpdateProjectFiles(projectsDirectory, projectPath, composeContent, envContent); err != nil {
- s.db.WithContext(ctx).Delete(proj)
+ // Best-effort cleanup to restore pre-transaction behavior.
+ _ = s.db.WithContext(ctx).Delete(proj).Error
return nil, fmt.Errorf("failed to save project files: %w", err)
}
@@ -1229,6 +1247,7 @@ func (s *ProjectService) mapProjectToDto(ctx context.Context, p models.Project,
resp.CreatedAt = p.CreatedAt.Format(time.RFC3339)
resp.UpdatedAt = p.UpdatedAt.Format(time.RFC3339)
resp.DirName = utils.DerefString(p.DirName)
+ resp.GitOpsManagedBy = p.GitOpsManagedBy
// Find containers for this project
normName := normalizeComposeProjectName(p.Name)
diff --git a/backend/internal/utils/git/git.go b/backend/internal/utils/git/git.go
new file mode 100644
index 000000000..4963161e2
--- /dev/null
+++ b/backend/internal/utils/git/git.go
@@ -0,0 +1,322 @@
+package git
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/getarcaneapp/arcane/types/gitops"
+ "github.com/go-git/go-git/v5"
+ "github.com/go-git/go-git/v5/config"
+ "github.com/go-git/go-git/v5/plumbing"
+ "github.com/go-git/go-git/v5/plumbing/transport"
+ "github.com/go-git/go-git/v5/plumbing/transport/http"
+ "github.com/go-git/go-git/v5/plumbing/transport/ssh"
+)
+
+// Client handles git operations
+type Client struct {
+ workDir string
+}
+
+// NewClient creates a new git client
+func NewClient(workDir string) *Client {
+ return &Client{
+ workDir: workDir,
+ }
+}
+
+// AuthConfig holds authentication configuration
+type AuthConfig struct {
+ AuthType string
+ Username string
+ Token string
+ SSHKey string
+}
+
+// getAuth returns the appropriate transport.AuthMethod
+func (c *Client) getAuth(config AuthConfig) (transport.AuthMethod, error) {
+ switch config.AuthType {
+ case "http":
+ if config.Token != "" {
+ return &http.BasicAuth{
+ Username: config.Username,
+ Password: config.Token,
+ }, nil
+ }
+ return nil, nil
+ case "ssh":
+ if config.SSHKey != "" {
+ publicKeys, err := ssh.NewPublicKeys("git", []byte(config.SSHKey), "")
+ if err != nil {
+ return nil, fmt.Errorf("failed to create ssh auth: %w", err)
+ }
+ return publicKeys, nil
+ }
+ return nil, fmt.Errorf("ssh key required for ssh authentication")
+ case "none":
+ return nil, nil
+ default:
+ return nil, nil
+ }
+}
+
+// Clone clones a repository to a temporary directory
+func (c *Client) Clone(url, branch string, auth AuthConfig) (string, error) {
+ // Create a temporary directory
+ workDir := c.workDir
+ if workDir == "" {
+ workDir = os.TempDir()
+ }
+ // Ensure the work directory exists
+ if err := os.MkdirAll(workDir, 0755); err != nil {
+ return "", fmt.Errorf("failed to create work dir: %w", err)
+ }
+ tmpDir, err := os.MkdirTemp(workDir, "gitops-*")
+ if err != nil {
+ return "", fmt.Errorf("failed to create temp dir: %w", err)
+ }
+
+ authMethod, err := c.getAuth(auth)
+ if err != nil {
+ os.RemoveAll(tmpDir)
+ return "", err
+ }
+
+ cloneOptions := &git.CloneOptions{
+ URL: url,
+ Progress: nil,
+ }
+
+ if authMethod != nil {
+ cloneOptions.Auth = authMethod
+ }
+
+ if branch != "" {
+ cloneOptions.ReferenceName = plumbing.NewBranchReferenceName(branch)
+ cloneOptions.SingleBranch = true
+ }
+
+ _, err = git.PlainClone(tmpDir, false, cloneOptions)
+ if err != nil {
+ os.RemoveAll(tmpDir)
+ return "", fmt.Errorf("failed to clone repository: %w", err)
+ }
+
+ return tmpDir, nil
+}
+
+// GetCurrentCommit returns the HEAD commit hash of a cloned repository
+func (c *Client) GetCurrentCommit(repoPath string) (string, error) {
+ repo, err := git.PlainOpen(repoPath)
+ if err != nil {
+ return "", fmt.Errorf("failed to open repository: %w", err)
+ }
+
+ ref, err := repo.Head()
+ if err != nil {
+ return "", fmt.Errorf("failed to get HEAD: %w", err)
+ }
+
+ return ref.Hash().String(), nil
+}
+
+// BranchInfo holds information about a git branch
+type BranchInfo struct {
+ Name string
+ IsDefault bool
+}
+
+// ListBranches lists all branches in a remote repository
+func (c *Client) ListBranches(url string, auth AuthConfig) ([]BranchInfo, error) {
+ authMethod, err := c.getAuth(auth)
+ if err != nil {
+ return nil, err
+ }
+
+ // Create a remote without cloning
+ rem := git.NewRemote(nil, &config.RemoteConfig{
+ Name: "origin",
+ URLs: []string{url},
+ })
+
+ listOptions := &git.ListOptions{}
+ if authMethod != nil {
+ listOptions.Auth = authMethod
+ }
+
+ refs, err := rem.List(listOptions)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list remote references: %w", err)
+ }
+
+ var branches []BranchInfo
+ var defaultBranch string
+
+ // Find the default branch (HEAD points to it)
+ for _, ref := range refs {
+ if ref.Name().String() == "HEAD" {
+ // HEAD is a symbolic reference that points to the default branch
+ if ref.Target().IsBranch() {
+ defaultBranch = ref.Target().Short()
+ }
+ break
+ }
+ }
+
+ // Collect all branches
+ seen := make(map[string]bool)
+ for _, ref := range refs {
+ if ref.Name().IsBranch() {
+ branchName := ref.Name().Short()
+ if seen[branchName] {
+ continue
+ }
+ seen[branchName] = true
+
+ branches = append(branches, BranchInfo{
+ Name: branchName,
+ IsDefault: branchName == defaultBranch,
+ })
+ }
+ }
+
+ // Sort branches with default first
+ sort.Slice(branches, func(i, j int) bool {
+ if branches[i].IsDefault {
+ return true
+ }
+ if branches[j].IsDefault {
+ return false
+ }
+ return branches[i].Name < branches[j].Name
+ })
+
+ return branches, nil
+}
+
+// ValidatePath ensures the path is safe and doesn't escape the repo
+func ValidatePath(repoPath, requestedPath string) error {
+ // Clean the paths
+ cleanRepoPath := filepath.Clean(repoPath)
+ cleanRequestedPath := filepath.Clean(filepath.Join(repoPath, requestedPath))
+
+ // Check if the requested path is within the repo using relative path validation
+ rel, err := filepath.Rel(cleanRepoPath, cleanRequestedPath)
+ if err != nil {
+ return fmt.Errorf("invalid path: %w", err)
+ }
+ if strings.HasPrefix(rel, "..") || strings.Contains(rel, string(filepath.Separator)+".."+string(filepath.Separator)) {
+ return fmt.Errorf("path traversal attempt detected")
+ }
+
+ return nil
+}
+
+// BrowseTree returns the file tree at the specified path
+func (c *Client) BrowseTree(repoPath, targetPath string) ([]gitops.FileTreeNode, error) {
+ // Validate path to prevent traversal
+ if err := ValidatePath(repoPath, targetPath); err != nil {
+ return nil, err
+ }
+
+ fullPath := filepath.Join(repoPath, targetPath)
+
+ // Check if path exists
+ info, err := os.Stat(fullPath)
+ if err != nil {
+ return nil, fmt.Errorf("path not found: %w", err)
+ }
+
+ if !info.IsDir() {
+ return nil, fmt.Errorf("path is not a directory")
+ }
+
+ entries, err := os.ReadDir(fullPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read directory: %w", err)
+ }
+
+ var nodes []gitops.FileTreeNode
+ for _, entry := range entries {
+ // Skip .git directory
+ if entry.Name() == ".git" {
+ continue
+ }
+
+ info, err := entry.Info()
+ if err != nil {
+ continue
+ }
+
+ nodeType := gitops.FileTreeNodeTypeFile
+ if entry.IsDir() {
+ nodeType = gitops.FileTreeNodeTypeDirectory
+ }
+
+ relativePath := filepath.Join(targetPath, entry.Name())
+ node := gitops.FileTreeNode{
+ Name: entry.Name(),
+ Path: relativePath,
+ Type: nodeType,
+ Size: info.Size(),
+ }
+
+ nodes = append(nodes, node)
+ }
+
+ return nodes, nil
+}
+
+// Cleanup removes a temporary repository directory
+func (c *Client) Cleanup(repoPath string) error {
+ return os.RemoveAll(repoPath)
+}
+
+// CommitInfo holds information about a git commit
+type CommitInfo struct {
+ Hash string
+ Author string
+ Message string
+ Date time.Time
+}
+
+// TestConnection tests if the repository can be accessed with the given credentials
+func (c *Client) TestConnection(url, branch string, auth AuthConfig) error {
+ tmpDir, err := c.Clone(url, branch, auth)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ _ = c.Cleanup(tmpDir)
+ }()
+ return nil
+}
+
+// FileExists checks if a file exists in the repository
+func (c *Client) FileExists(repoPath, filePath string) bool {
+ if err := ValidatePath(repoPath, filePath); err != nil {
+ return false
+ }
+
+ fullPath := filepath.Join(repoPath, filePath)
+ _, err := os.Stat(fullPath)
+ return err == nil
+}
+
+// ReadFile reads a file from the repository
+func (c *Client) ReadFile(repoPath, filePath string) (string, error) {
+ if err := ValidatePath(repoPath, filePath); err != nil {
+ return "", err
+ }
+
+ fullPath := filepath.Join(repoPath, filePath)
+ content, err := os.ReadFile(fullPath)
+ if err != nil {
+ return "", fmt.Errorf("failed to read file: %w", err)
+ }
+ return string(content), nil
+}
diff --git a/backend/internal/utils/projects/cmds.go b/backend/internal/utils/projects/cmds.go
index 36844f46e..951cb2aa3 100644
--- a/backend/internal/utils/projects/cmds.go
+++ b/backend/internal/utils/projects/cmds.go
@@ -42,7 +42,7 @@ func ComposeRestart(ctx context.Context, proj *types.Project, services []string)
return c.svc.Restart(ctx, proj.Name, api.RestartOptions{Services: services})
}
-func ComposeUp(ctx context.Context, proj *types.Project, services []string) error {
+func ComposeUp(ctx context.Context, proj *types.Project, services []string, removeOrphans bool) error {
c, err := NewClient(ctx)
if err != nil {
return err
@@ -51,7 +51,7 @@ func ComposeUp(ctx context.Context, proj *types.Project, services []string) erro
progressWriter, _ := ctx.Value(ProgressWriterKey{}).(io.Writer)
- upOptions, startOptions := composeUpOptions(proj, services)
+ upOptions, startOptions := composeUpOptions(proj, services, removeOrphans)
// If we don't need progress, just run compose up normally.
if progressWriter == nil {
@@ -61,11 +61,12 @@ func ComposeUp(ctx context.Context, proj *types.Project, services []string) erro
return composeUpWithProgress(ctx, c.svc, proj, api.UpOptions{Create: upOptions, Start: startOptions}, progressWriter)
}
-func composeUpOptions(proj *types.Project, services []string) (api.CreateOptions, api.StartOptions) {
+func composeUpOptions(proj *types.Project, services []string, removeOrphans bool) (api.CreateOptions, api.StartOptions) {
upOptions := api.CreateOptions{
Services: services,
Recreate: api.RecreateDiverged,
RecreateDependencies: api.RecreateDiverged,
+ RemoveOrphans: removeOrphans,
}
startOptions := api.StartOptions{
diff --git a/backend/resources/migrations/postgres/028_add_gitops.down.sql b/backend/resources/migrations/postgres/028_add_gitops.down.sql
new file mode 100644
index 000000000..e8f576dfd
--- /dev/null
+++ b/backend/resources/migrations/postgres/028_add_gitops.down.sql
@@ -0,0 +1,5 @@
+-- Remove gitops_managed_by column from projects table
+ALTER TABLE projects DROP COLUMN IF EXISTS gitops_managed_by;
+
+DROP TABLE IF EXISTS gitops_syncs;
+DROP TABLE IF EXISTS git_repositories;
diff --git a/backend/resources/migrations/postgres/028_add_gitops.up.sql b/backend/resources/migrations/postgres/028_add_gitops.up.sql
new file mode 100644
index 000000000..d318417f0
--- /dev/null
+++ b/backend/resources/migrations/postgres/028_add_gitops.up.sql
@@ -0,0 +1,50 @@
+CREATE TABLE IF NOT EXISTS git_repositories (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ url TEXT NOT NULL,
+ auth_type TEXT NOT NULL,
+ username TEXT,
+ token TEXT,
+ ssh_key TEXT,
+ description TEXT,
+ enabled BOOLEAN NOT NULL DEFAULT true,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ
+);
+
+CREATE INDEX IF NOT EXISTS idx_git_repositories_enabled ON git_repositories(enabled);
+CREATE INDEX IF NOT EXISTS idx_git_repositories_name ON git_repositories(name);
+
+CREATE TABLE IF NOT EXISTS gitops_syncs (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ repository_id TEXT NOT NULL,
+ branch TEXT NOT NULL,
+ compose_path TEXT NOT NULL,
+ project_name TEXT NOT NULL,
+ project_id TEXT,
+ auto_sync BOOLEAN NOT NULL DEFAULT false,
+ sync_interval INTEGER NOT NULL DEFAULT 60,
+ last_sync_at TIMESTAMPTZ,
+ last_sync_status TEXT,
+ last_sync_error TEXT,
+ last_sync_commit TEXT,
+ environment_id TEXT NOT NULL DEFAULT '',
+ enabled BOOLEAN NOT NULL DEFAULT true,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ,
+ FOREIGN KEY (repository_id) REFERENCES git_repositories(id) ON DELETE CASCADE,
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE SET NULL,
+ FOREIGN KEY (environment_id) REFERENCES environments(id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_repository_id ON gitops_syncs(repository_id);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_project_id ON gitops_syncs(project_id);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_enabled ON gitops_syncs(enabled);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_auto_sync ON gitops_syncs(auto_sync);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_id ON gitops_syncs(environment_id);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_last_sync_commit ON gitops_syncs(last_sync_commit);
+
+-- Add gitops_managed_by column to projects table
+ALTER TABLE projects ADD COLUMN IF NOT EXISTS gitops_managed_by TEXT;
+CREATE INDEX IF NOT EXISTS idx_projects_gitops_managed_by ON projects(gitops_managed_by);
diff --git a/backend/resources/migrations/sqlite/028_add_gitops.down.sql b/backend/resources/migrations/sqlite/028_add_gitops.down.sql
new file mode 100644
index 000000000..4776b27b2
--- /dev/null
+++ b/backend/resources/migrations/sqlite/028_add_gitops.down.sql
@@ -0,0 +1,6 @@
+-- Remove gitops_managed_by column from projects table
+-- Note: SQLite doesn't support DROP COLUMN directly, so we'll leave it
+-- or need to recreate the table if this is critical
+
+DROP TABLE IF EXISTS gitops_syncs;
+DROP TABLE IF EXISTS git_repositories;
diff --git a/backend/resources/migrations/sqlite/028_add_gitops.up.sql b/backend/resources/migrations/sqlite/028_add_gitops.up.sql
new file mode 100644
index 000000000..63744f1c3
--- /dev/null
+++ b/backend/resources/migrations/sqlite/028_add_gitops.up.sql
@@ -0,0 +1,50 @@
+CREATE TABLE IF NOT EXISTS git_repositories (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ url TEXT NOT NULL,
+ auth_type TEXT NOT NULL,
+ username TEXT,
+ token TEXT,
+ ssh_key TEXT,
+ description TEXT,
+ enabled INTEGER NOT NULL DEFAULT 1,
+
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE INDEX IF NOT EXISTS idx_git_repositories_enabled ON git_repositories(enabled);
+CREATE INDEX IF NOT EXISTS idx_git_repositories_name ON git_repositories(name);
+
+CREATE TABLE IF NOT EXISTS gitops_syncs (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ repository_id TEXT NOT NULL,
+ branch TEXT NOT NULL,
+ compose_path TEXT NOT NULL,
+ project_name TEXT NOT NULL,
+ project_id TEXT,
+ auto_sync INTEGER NOT NULL DEFAULT 0,
+ sync_interval INTEGER NOT NULL DEFAULT 60,
+ last_sync_at DATETIME,
+ last_sync_status TEXT,
+ last_sync_error TEXT,
+ last_sync_commit TEXT,
+ environment_id TEXT NOT NULL DEFAULT '',
+ enabled INTEGER NOT NULL DEFAULT 1,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (repository_id) REFERENCES git_repositories(id) ON DELETE CASCADE,
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE SET NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_environment_id ON gitops_syncs(environment_id);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_repository_id ON gitops_syncs(repository_id);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_project_id ON gitops_syncs(project_id);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_enabled ON gitops_syncs(enabled);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_auto_sync ON gitops_syncs(auto_sync);
+CREATE INDEX IF NOT EXISTS idx_gitops_syncs_last_sync_commit ON gitops_syncs(last_sync_commit);
+
+-- Add gitops_managed_by column to projects table
+ALTER TABLE projects ADD COLUMN gitops_managed_by TEXT;
+CREATE INDEX IF NOT EXISTS idx_projects_gitops_managed_by ON projects(gitops_managed_by);
diff --git a/docker/compose.dev.yaml b/docker/compose.dev.yaml
index 850164bfe..0a138525e 100644
--- a/docker/compose.dev.yaml
+++ b/docker/compose.dev.yaml
@@ -59,6 +59,7 @@ services:
- APP_URL=http://localhost:3000
- PUID=1000
- PGID=1000
+ - LOG_LEVEL=debug
- ENCRYPTION_KEY=dev-encryption-key-replace-in-production-must-be-32-chars
- JWT_SECRET=dev-jwt-secret-replace-in-production-must-be-long-enough
- DATABASE_URL=file:data/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate
@@ -91,6 +92,7 @@ services:
environment:
- GIN_MODE=debug
- ENVIRONMENT=development
+ - LOG_LEVEL=debug
- PORT=3553
- AGENT_MODE=true
- AGENT_TOKEN=arc_Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 43f6d72b2..a4218b700 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -44,7 +44,9 @@
"common_always": "Always",
"common_working_directory": "Working Directory",
"common_remove_selected": "Remove Selected",
- "sync_registries": "Sync Registries",
+ "sync_environment": "Sync",
+ "sync_environment_success": "Environment synced successfully",
+ "sync_environment_failed": "Failed to sync environment",
"common_gateway": "Gateway",
"common_driver_required": "Driver is required",
"common_command": "Command",
@@ -148,6 +150,9 @@
"common_select_locale": "Select locale",
"common_show": "Show",
"common_registry": "Registry",
+ "common_token": "Token",
+ "common_token_placeholder": "Your access token",
+ "common_keep_placeholder": "Leave empty to keep current",
"common_toggle_theme": "Toggle theme",
"common_logout": "Logout",
"common_redeploy": "Redeploy",
@@ -207,11 +212,37 @@
"_comment_common_ui": "=== COMMON - UI COMPONENTS ===",
"common_details_title": "{resource} Details",
"common_details_description": "Basic information about this {resource}",
+ "common_url_required": "URL is required",
+ "common_username_required": "Username is required",
+ "common_name_required": "Name is required",
+ "common_name_placeholder": "Enter a name",
+ "common_description_placeholder": "Enter a description",
+ "common_enabled_description": "Enable or disable this resource",
+ "common_auto_sync_description": "Automatically sync on a schedule",
+ "common_select_placeholder": "Select an option",
+ "common_edit_description": "Update the details for this resource",
+ "common_add_description": "Enter the details for the new resource",
+ "common_save_changes": "Save Changes",
+ "common_save_failed": "Failed to save",
+ "common_test_failed": "Test failed: {resource}",
+ "common_test_success": "Test passed: {resource}",
+ "common_refresh_success": "{resource} refreshed",
+ "common_remove_message": "Are you sure you want to remove {resource}? This action cannot be undone.",
+ "common_required": "This field is required",
+ "common_success": "Success",
+ "common_failed": "Failed",
+ "common_pending": "Pending",
+ "common_active": "Active",
+ "common_successful": "Successful",
+ "common_never": "Never",
+ "resource_repository": "repository",
+ "resource_repository_cap": "Repository",
+ "resource_sync": "sync",
+ "resource_sync_cap": "Sync",
"common_labels_description": "Metadata labels attached to this {resource} for organization and automation",
"common_create_button": "Create {resource}",
"common_add_button": "Add {resource}",
"_comment_common_validation": "=== COMMON - VALIDATION ===",
- "common_username_required": "Username is required",
"common_field_required": "{field} is required",
"common_copied": "Copied to clipboard",
"common_copy_failed": "Failed to copy to clipboard",
@@ -592,6 +623,9 @@
"networks_remove_success": "Network {name} removed successfully",
"_comment_projects": "=== PROJECTS (COMPOSE) ===",
"projects_title": "Projects",
+ "projects_col_provider": "Provider",
+ "projects_provider_local": "Local",
+ "projects_provider_git": "Git",
"compose_subtitle": "View and Manage Compose Projects",
"compose_services": "Services",
"compose_services_description": "Docker Compose services and their current status",
@@ -625,6 +659,7 @@
"compose_convert_action": "Convert to Compose",
"compose_convert_from_docker_run": "Convert from Docker Run",
"compose_project_name_invalid": "Only letters, numbers, and hyphens are allowed",
+ "compose_project_name_invalid_with_underscores": "Only letters, numbers, hyphens, and underscores are allowed",
"compose_compose_file_title": "Docker Compose File",
"compose_env_title": "Environment (.env)",
"compose_compose_placeholder": "Enter YAML…",
@@ -1061,6 +1096,84 @@
"registry_github_url": "ghcr.io",
"registry_google_url": "gcr.io",
"registry_quay_url": "quay.io",
+ "_comment_automation": "=== AUTOMATION ===",
+ "automation_title": "Automation",
+ "automation_subtitle": "Automate deployment and infrastructure management",
+ "_comment_customize_Git": "=== CUSTOMIZATION - Git ===",
+ "git_title": "Git",
+ "git_subtitle": "Manage Git repositories and automated synchronization to projects",
+ "_comment_customize_git_repositories": "=== CUSTOMIZATION - GIT REPOSITORIES ===",
+ "git_repositories_title": "Git Repositories",
+ "git_repositories_subtitle": "Configure Git repository connections for Git synchronization",
+ "git_repository_name": "Repository Name",
+ "git_repository_url": "Repository URL",
+ "git_repository_auth_type": "Authentication Type",
+ "git_repository_auth_none": "None",
+ "git_repository_auth_http": "HTTP (Username/Token)",
+ "git_repository_auth_ssh": "SSH Key",
+ "git_repository_test_connection": "Test Connection",
+ "git_repository_add_title": "Add Git Repository",
+ "git_repository_edit_title": "Edit Git Repository",
+ "git_repository_remove_confirm": "Remove Git Repository",
+ "git_repository_remove_message": "Are you sure you want to remove this repository? This will also remove all associated sync configurations.",
+ "git_repository_ssh_key_label": "SSH Private Key",
+ "git_repository_ssh_key_placeholder": "Paste your SSH private key here",
+ "_comment_customize_Git_syncs": "=== CUSTOMIZATION - GIT SYNCS ===",
+ "git_syncs_title": "Git Syncs",
+ "git_syncs_subtitle": "Manage automated synchronization from Git repositories to projects",
+ "git_sync_name": "Sync Name",
+ "git_sync_repository": "Git Repository",
+ "git_sync_branch": "Branch",
+ "git_sync_compose_path": "Compose File Path",
+ "git_sync_project": "Target Project",
+ "git_sync_auto_sync": "Auto Sync",
+ "git_sync_sync_interval": "Sync Interval (minutes)",
+ "git_sync_last_sync": "Last Sync",
+ "git_sync_next_sync": "Next Sync",
+ "git_sync_status": "Sync Status",
+ "git_sync_perform": "Sync Now",
+ "git_sync_browse_files": "Browse Files",
+ "git_sync_add_title": "Add Git Sync",
+ "git_sync_edit_title": "Edit Git Sync",
+ "git_sync_remove_confirm": "Remove Git Sync",
+ "git_sync_remove_message": "Are you sure you want to remove this sync configuration?",
+ "git_sync_success": "Sync completed successfully",
+ "git_sync_failed": "Sync failed",
+ "git_sync_import_title": "Import GitOps Syncs",
+ "git_sync_import_description": "Paste your JSON configuration below or upload a .json file.",
+ "git_sync_import_json_required": "JSON content is required",
+ "git_sync_import_json_invalid_array": "Input must be a JSON array",
+ "git_sync_import_json_empty": "Array cannot be empty",
+ "git_sync_import_missing_fields": "Item at index {index} is missing required fields (syncName, gitRepo, branch, dockerComposePath)",
+ "git_sync_import_invalid_json": "Invalid JSON format: {error}",
+ "git_sync_import_upload_label": "Upload JSON File",
+ "git_sync_import_content_label": "JSON Content",
+ "git_sync_import_button": "Import Syncs",
+ "git_sync_import_success": "Successfully imported {count} syncs.",
+ "git_sync_import_partial_success": "Imported {successCount} syncs with {failedCount} failures.",
+ "git_sync_import_failed_count": "Failed to import syncs. {count} errors.",
+ "git_sync_import_failed": "Import failed",
+ "git_sync_import_open_button": "Import .JSON",
+ "git_sync_project_description": "Name of the project to create or update from the compose file",
+ "git_sync_browse_files_title": "Browse Repository Files",
+ "git_sync_browse_files_description": "Select a compose file from the repository",
+ "git_sync_browse_root": "Root",
+ "git_sync_browse_no_files": "No files found",
+ "git_sync_browse_compose_label": "Compose",
+ "git_sync_browse_hint": "Only YAML/YML files can be selected as compose files. Click on folders to navigate.",
+ "git_sync_branch_manual_hint": "Enter branch name manually or select a repository to load branches",
+ "git_sync_branch_select_hint": "Select a branch from the list",
+ "git_sync_browse_button_hint": "Select a repository and branch to browse files",
+ "git_sync_loading_branches": "Loading branches...",
+ "git_sync_commit": "Commit",
+ "git_managed_badge": "Git Managed",
+ "git_managed_readonly_alert": "This project is managed by Git. The compose file and project name cannot be edited here. Changes must be made in the connected Git repository.",
+ "git_managed_env_note": "The environment file (.env) can still be edited in Arcane to provide runtime configuration.",
+ "git_environment_card_description": "Configure Git syncs to automatically deploy Docker Compose projects from Git repositories to this environment.",
+ "git_manage_syncs": "Manage Git Syncs",
+ "git_from_git_repo": "From Git Repo",
+ "git_sync_from_git": "Sync from Git",
+ "common_syncing": "Syncing...",
"_comment_customize_variables": "=== CUSTOMIZATION - VARIABLES ===",
"variables_title": "Variables",
"variables_subtitle": "Manage global environment variables that are available to all projects",
@@ -1542,5 +1655,6 @@
"environments_generate_config": "Generate Agent Configuration",
"environments_connect_existing_agent": "Connect to Existing Agent",
"environments_connect_existing_agent_description": "Connect to an already-running agent using a bootstrap token.",
- "project_files": "Project Files"
+ "project_files": "Project Files",
+ "project_includes": "Includes"
}
diff --git a/frontend/src/lib/components/action-button-group/action-button-group.svelte b/frontend/src/lib/components/action-button-group/action-button-group.svelte
index 29cb699fd..be618e089 100644
--- a/frontend/src/lib/components/action-button-group/action-button-group.svelte
+++ b/frontend/src/lib/components/action-button-group/action-button-group.svelte
@@ -2,7 +2,7 @@
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import type { Action, ArcaneButtonSize } from '$lib/components/arcane-button/index.js';
- import { EllipsisIcon } from '$lib/icons';
+ import { EllipsisIcon, type IconType } from '$lib/icons';
import { cn } from '$lib/utils';
export interface ActionButton {
@@ -15,6 +15,7 @@
onclick: () => void;
showOnMobile?: boolean;
badge?: string | number;
+ icon?: IconType | null;
}
interface Props {
@@ -119,6 +120,7 @@
disabled={button.disabled}
onclick={() => {}}
{size}
+ icon={button.icon}
>
{#if button.badge !== undefined}
<span class="text-muted-foreground rounded-full border px-1 py-0.5 text-[10px]">
@@ -139,6 +141,7 @@
disabled={button.disabled}
onclick={button.onclick}
{size}
+ icon={button.icon}
>
{#if button.badge !== undefined}
<span class="text-muted-foreground rounded-full border px-1 py-0.5 text-[10px]">
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelte
index b7c08b3c0..fdacd5f07 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte
@@ -100,9 +100,9 @@
const passAllGlobal: (row: unknown, columnId: string, filterValue: unknown) => boolean = () => true;
- const currentPage = $derived(items.pagination.currentPage ?? requestOptions?.pagination?.page ?? 1);
- const totalPages = $derived(items.pagination.totalPages ?? 1);
- const totalItems = $derived(items.pagination.totalItems ?? 0);
+ const currentPage = $derived(items.pagination?.currentPage ?? requestOptions?.pagination?.page ?? 1);
+ const totalPages = $derived(items.pagination?.totalPages ?? 1);
+ const totalItems = $derived(items.pagination?.totalItems ?? 0);
const pageSize = $derived(requestOptions?.pagination?.limit ?? items?.pagination?.itemsPerPage ?? 20);
const canPrev = $derived(currentPage > 1);
const canNext = $derived(currentPage < totalPages);
diff --git a/frontend/src/lib/components/dialogs/file-browser-dialog.svelte b/frontend/src/lib/components/dialogs/file-browser-dialog.svelte
new file mode 100644
index 000000000..d06e46f4f
--- /dev/null
+++ b/frontend/src/lib/components/dialogs/file-browser-dialog.svelte
@@ -0,0 +1,153 @@
+<script lang="ts">
+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
+ import { gitRepositoryService } from '$lib/services/git-repository-service';
+ import type { FileTreeNode } from '$lib/types/gitops.type';
+ import { FolderOpenIcon, FileTextIcon, ArrowRightIcon } from '$lib/icons';
+ import { m } from '$lib/paraglide/messages';
+
+ type FileBrowserDialogProps = {
+ open: boolean;
+ repositoryId: string;
+ branch: string;
+ onSelect: (filePath: string) => void;
+ };
+
+ let { open = $bindable(false), repositoryId, branch, onSelect }: FileBrowserDialogProps = $props();
+
+ let currentPath = $state('');
+ let files = $state<FileTreeNode[]>([]);
+ let loading = $state(false);
+ let pathSegments = $derived(currentPath.split('/').filter(Boolean));
+
+ async function loadFiles(path: string = '') {
+ if (!repositoryId || !branch) return;
+
+ loading = true;
+ try {
+ const result = await gitRepositoryService.browseFiles(repositoryId, branch, path);
+ files = result.files || [];
+ currentPath = path;
+ } catch (error) {
+ console.error('Failed to load files:', error);
+ files = [];
+ } finally {
+ loading = false;
+ }
+ }
+
+ function handleFileClick(file: FileTreeNode) {
+ if (file.type === 'directory') {
+ loadFiles(file.path);
+ } else {
+ // Only allow selecting compose files
+ if (file.name.endsWith('.yml') || file.name.endsWith('.yaml')) {
+ onSelect(file.path);
+ open = false;
+ }
+ }
+ }
+
+ function goToPath(index: number) {
+ const newPath = pathSegments.slice(0, index + 1).join('/');
+ loadFiles(newPath);
+ }
+
+ function goBack() {
+ const segments = pathSegments.slice(0, -1);
+ loadFiles(segments.join('/'));
+ }
+
+ $effect(() => {
+ if (open && repositoryId && branch) {
+ loadFiles('');
+ }
+ });
+
+ function isComposeFile(fileName: string): boolean {
+ return fileName.endsWith('.yml') || fileName.endsWith('.yaml');
+ }
+</script>
+
+<ResponsiveDialog
+ bind:open
+ title={m.git_sync_browse_files_title()}
+ description={m.git_sync_browse_files_description()}
+ contentClass="max-w-2xl"
+>
+ {#snippet children()}
+ <div class="space-y-4">
+ <!-- Breadcrumb navigation -->
+ <div class="flex items-center gap-2 text-sm">
+ <Button variant="ghost" size="sm" onclick={() => loadFiles('')} disabled={currentPath === ''} class="h-8 px-2">
+ <FolderOpenIcon class="size-4" />
+ <span class="ml-1">{m.git_sync_browse_root()}</span>
+ </Button>
+ {#each pathSegments as segment, index}
+ <ArrowRightIcon class="text-muted-foreground size-4" />
+ <Button variant="ghost" size="sm" onclick={() => goToPath(index)} class="h-8 px-2">
+ {segment}
+ </Button>
+ {/each}
+ </div>
+
+ <!-- File list -->
+ <ScrollArea class="h-96 rounded-md border">
+ {#if loading}
+ <div class="flex items-center justify-center py-8">
+ <Spinner class="size-6" />
+ </div>
+ {:else if files.length === 0}
+ <div class="text-muted-foreground flex items-center justify-center py-8 text-sm">{m.git_sync_browse_no_files()}</div>
+ {:else}
+ <div class="space-y-1 p-2">
+ {#if currentPath !== ''}
+ <button
+ onclick={goBack}
+ class="hover:bg-accent flex w-full items-center gap-2 rounded-md px-3 py-2 text-left transition-colors"
+ >
+ <FolderOpenIcon class="text-muted-foreground size-4" />
+ <span class="text-sm">..</span>
+ </button>
+ {/if}
+ {#each files as file}
+ {@const isCompose = file.type === 'file' && isComposeFile(file.name)}
+ {@const canSelect = file.type === 'directory' || isCompose}
+ <button
+ onclick={() => handleFileClick(file)}
+ disabled={!canSelect}
+ class="hover:bg-accent flex w-full items-center gap-2 rounded-md px-3 py-2 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {#if file.type === 'directory'}
+ <FolderOpenIcon class="size-4 text-blue-500" />
+ {:else}
+ <FileTextIcon class="text-muted-foreground size-4" />
+ {/if}
+ <span class="text-sm {isCompose ? 'font-medium' : ''}">
+ {file.name}
+ </span>
+ {#if isCompose}
+ <span class="bg-primary/10 text-primary ml-auto rounded px-2 py-0.5 text-xs">
+ {m.git_sync_browse_compose_label()}
+ </span>
+ {/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </ScrollArea>
+
+ <p class="text-muted-foreground text-xs">
+ {m.git_sync_browse_hint()}
+ </p>
+ </div>
+ {/snippet}
+
+ {#snippet footer()}
+ <Button variant="outline" onclick={() => (open = false)}>
+ {m.common_cancel()}
+ </Button>
+ {/snippet}
+</ResponsiveDialog>
diff --git a/frontend/src/lib/components/dialogs/gitops-import-dialog.svelte b/frontend/src/lib/components/dialogs/gitops-import-dialog.svelte
new file mode 100644
index 000000000..abf5b6295
--- /dev/null
+++ b/frontend/src/lib/components/dialogs/gitops-import-dialog.svelte
@@ -0,0 +1,123 @@
+<script lang="ts">
+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import { Label } from '$lib/components/ui/label/index.js';
+ import { Textarea } from '$lib/components/ui/textarea/index.js';
+ import { toast } from 'svelte-sonner';
+ import type { ImportGitOpsSyncRequest } from '$lib/types/gitops.type';
+ import { m } from '$lib/paraglide/messages';
+ import { preventDefault } from '$lib/utils/form.utils';
+
+ type GitOpsImportFormProps = {
+ open: boolean;
+ onSubmit: (data: ImportGitOpsSyncRequest[]) => void;
+ isLoading: boolean;
+ };
+
+ let { open = $bindable(false), onSubmit, isLoading }: GitOpsImportFormProps = $props();
+
+ let jsonContent = $state('');
+ let error = $state<string | null>(null);
+
+ function handleSubmit() {
+ error = null;
+ try {
+ if (!jsonContent.trim()) {
+ error = m.git_sync_import_json_required();
+ return;
+ }
+ const data = JSON.parse(jsonContent);
+ if (!Array.isArray(data)) {
+ error = m.git_sync_import_json_invalid_array();
+ return;
+ }
+ // Basic validation of structure
+ if (data.length === 0) {
+ error = m.git_sync_import_json_empty();
+ return;
+ }
+
+ // Optional: validate each item has required fields
+ for (let i = 0; i < data.length; i++) {
+ const item = data[i];
+ if (!item.syncName || !item.gitRepo || !item.branch || !item.dockerComposePath) {
+ error = m.git_sync_import_missing_fields({ index: i });
+ return;
+ }
+ }
+
+ onSubmit(data as ImportGitOpsSyncRequest[]);
+ } catch (e) {
+ error = m.git_sync_import_invalid_json({ error: e instanceof Error ? e.message : String(e) });
+ }
+ }
+
+ function handleFileUpload(event: Event) {
+ const input = event.target as HTMLInputElement;
+ if (input.files && input.files[0]) {
+ const file = input.files[0];
+ const reader = new FileReader();
+ reader.onload = (e) => {
+ if (e.target?.result) {
+ jsonContent = e.target.result as string;
+ }
+ };
+ reader.readAsText(file);
+ }
+ }
+</script>
+
+<ResponsiveDialog
+ bind:open
+ title={m.git_sync_import_title()}
+ description={m.git_sync_import_description()}
+ contentClass="sm:max-w-2xl"
+>
+ {#snippet children()}
+ <div class="grid gap-y-3 py-4">
+ <div class="space-y-1.5">
+ <Label for="json-file">{m.git_sync_import_upload_label()}</Label>
+ <input
+ id="json-file"
+ type="file"
+ accept=".json"
+ onchange={handleFileUpload}
+ class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
+ />
+ </div>
+
+ <div class="space-y-1.5">
+ <Label for="json-content">{m.git_sync_import_content_label()}</Label>
+ <Textarea
+ id="json-content"
+ bind:value={jsonContent}
+ placeholder={`[\n {\n "syncName": "example-sync",\n "gitRepo": "my-repo",\n "branch": "main",\n "dockerComposePath": "docker-compose.yml",\n "autoSync": true,\n "syncInterval": 10,\n "enabled": true\n }\n]`}
+ class="h-[300px] font-mono text-xs"
+ />
+ {#if error}
+ <p class="text-sm text-red-500">{error}</p>
+ {/if}
+ </div>
+ </div>
+ {/snippet}
+
+ {#snippet footer()}
+ <Button
+ type="button"
+ class="arcane-button-cancel flex-1"
+ variant="outline"
+ onclick={() => (open = false)}
+ disabled={isLoading}
+ >
+ {m.common_cancel()}
+ </Button>
+
+ <Button onclick={handleSubmit} class="arcane-button-create flex-1" disabled={isLoading}>
+ {#if isLoading}
+ <Spinner class="mr-2 size-4" />
+ {/if}
+ {m.git_sync_import_button()}
+ </Button>
+ {/snippet}
+</ResponsiveDialog>
diff --git a/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte
new file mode 100644
index 000000000..2ae91cf35
--- /dev/null
+++ b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte
@@ -0,0 +1,291 @@
+<script lang="ts">
+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import FormInput from '$lib/components/form/form-input.svelte';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import * as Select from '$lib/components/ui/select/index.js';
+ import { Label } from '$lib/components/ui/label/index.js';
+ import FileBrowserDialog from '$lib/components/dialogs/file-browser-dialog.svelte';
+ import type { GitOpsSync, GitOpsSyncCreateDto, GitOpsSyncUpdateDto, GitRepository, BranchInfo } from '$lib/types/gitops.type';
+ import { gitRepositoryService } from '$lib/services/git-repository-service';
+ import { z } from 'zod/v4';
+ import { createForm, preventDefault } from '$lib/utils/form.utils';
+ import { m } from '$lib/paraglide/messages';
+ import { FolderOpenIcon } from '$lib/icons';
+
+ type GitOpsSyncFormProps = {
+ open: boolean;
+ syncToEdit: GitOpsSync | null;
+ onSubmit: (detail: { sync: GitOpsSyncCreateDto | GitOpsSyncUpdateDto; isEditMode: boolean }) => void;
+ isLoading: boolean;
+ };
+
+ let { open = $bindable(false), syncToEdit = $bindable(), onSubmit, isLoading }: GitOpsSyncFormProps = $props();
+
+ let isEditMode = $derived(!!syncToEdit);
+ let repositories = $state<GitRepository[]>([]);
+ let branches = $state<BranchInfo[]>([]);
+ let loadingData = $state(true);
+ let loadingBranches = $state(false);
+ let showFileBrowser = $state(false);
+
+ const formSchema = z.object({
+ name: z.string().min(1, m.common_name_required()),
+ repositoryId: z.string().min(1, m.common_required()),
+ branch: z.string().min(1, m.common_required()),
+ composePath: z.string().min(1, m.common_required()),
+ autoSync: z.boolean().default(true),
+ syncInterval: z.number().min(1).default(5),
+ enabled: z.boolean().default(true)
+ });
+
+ let formData = $derived({
+ name: open && syncToEdit ? syncToEdit.name : '',
+ repositoryId: open && syncToEdit ? syncToEdit.repositoryId : '',
+ branch: open && syncToEdit ? syncToEdit.branch : 'main',
+ composePath: open && syncToEdit ? syncToEdit.composePath : 'docker-compose.yml',
+ autoSync: open && syncToEdit ? (syncToEdit.autoSync ?? true) : true,
+ syncInterval: open && syncToEdit ? (syncToEdit.syncInterval ?? 5) : 5,
+ enabled: open && syncToEdit ? (syncToEdit.enabled ?? true) : true
+ });
+
+ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+
+ let selectedRepository = $state<{ value: string; label: string } | undefined>(undefined);
+
+ async function loadBranches(repositoryId: string) {
+ if (!repositoryId) return;
+
+ loadingBranches = true;
+ branches = [];
+ try {
+ const result = await gitRepositoryService.getBranches(repositoryId);
+ branches = result.branches || [];
+
+ // Auto-select default branch if not editing
+ if (!isEditMode && branches.length > 0) {
+ const defaultBranch = branches.find((b) => b.isDefault);
+ if (defaultBranch) {
+ $inputs.branch.value = defaultBranch.name;
+ }
+ }
+ } catch (error) {
+ console.error('Failed to load branches:', error);
+ } finally {
+ loadingBranches = false;
+ }
+ }
+
+ async function loadData() {
+ loadingData = true;
+ // Reset state before loading data to ensure a clean state
+ selectedRepository = undefined;
+ branches = [];
+ loadingBranches = false;
+ showFileBrowser = false;
+
+ try {
+ const reposResult = await gitRepositoryService.getRepositories({ pagination: { page: 1, limit: 100 } });
+ repositories = reposResult.data || [];
+
+ if (syncToEdit) {
+ const repo = repositories.find((r) => r.id === syncToEdit.repositoryId);
+ if (repo) {
+ selectedRepository = { value: repo.id, label: repo.name };
+ await loadBranches(repo.id);
+ }
+ }
+ } catch (error) {
+ console.error('Failed to load data:', error);
+ } finally {
+ loadingData = false;
+ }
+ }
+
+ $effect(() => {
+ if (open) {
+ loadData();
+ if (!isEditMode) {
+ form.reset();
+ }
+ }
+ });
+
+ function handleSubmit() {
+ const data = form.validate();
+ if (!data) return;
+
+ const payload: GitOpsSyncCreateDto | GitOpsSyncUpdateDto = {
+ name: data.name,
+ repositoryId: selectedRepository?.value || data.repositoryId,
+ branch: data.branch,
+ composePath: data.composePath,
+ projectName: data.name,
+ autoSync: data.autoSync,
+ syncInterval: data.syncInterval,
+ enabled: data.enabled
+ };
+
+ onSubmit({ sync: payload, isEditMode });
+ }
+</script>
+
+<ResponsiveDialog
+ bind:open
+ title={isEditMode ? m.git_sync_edit_title() : m.git_sync_add_title()}
+ description={isEditMode ? m.common_edit_description() : m.common_add_description()}
+ contentClass="sm:max-w-2xl"
+>
+ {#snippet children()}
+ {#if loadingData}
+ <div class="flex items-center justify-center py-8">
+ <Spinner class="size-6" />
+ </div>
+ {:else}
+ <form id="sync-form" onsubmit={preventDefault(handleSubmit)} class="grid gap-y-3 py-4">
+ <FormInput label={m.git_sync_name()} type="text" placeholder={m.common_name_placeholder()} bind:input={$inputs.name} />
+
+ <div class="space-y-1.5">
+ <Label for="repository">{m.git_sync_repository()}</Label>
+ <Select.Root
+ type="single"
+ value={selectedRepository?.value}
+ onValueChange={(v) => {
+ if (v) {
+ const repo = repositories.find((r) => r.id === v);
+ if (repo) {
+ selectedRepository = { value: repo.id, label: repo.name };
+ $inputs.repositoryId.value = v;
+ loadBranches(v);
+ }
+ }
+ }}
+ >
+ <Select.Trigger id="repository" class="w-full" aria-invalid={$inputs.repositoryId.error ? 'true' : undefined}>
+ <span>{selectedRepository?.label ?? m.common_select_placeholder()}</span>
+ </Select.Trigger>
+ <Select.Content style="width: var(--bits-select-anchor-width);">
+ {#each repositories as repo}
+ <Select.Item value={repo.id} class="truncate">{repo.name}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ {#if $inputs.repositoryId.error}
+ <p class="mt-1 text-sm text-red-500">{$inputs.repositoryId.error}</p>
+ {/if}
+ </div>
+
+ <div class="space-y-1.5">
+ <Label for="branch">{m.git_sync_branch()}</Label>
+ {#if loadingBranches}
+ <div class="flex items-center gap-2">
+ <Spinner class="size-4" />
+ <span class="text-muted-foreground text-sm">Loading branches...</span>
+ </div>
+ {:else if branches.length > 0}
+ <Select.Root
+ type="single"
+ value={$inputs.branch.value}
+ onValueChange={(v) => {
+ if (v) {
+ $inputs.branch.value = v;
+ }
+ }}
+ >
+ <Select.Trigger id="branch" class="w-full" aria-invalid={$inputs.branch.error ? 'true' : undefined}>
+ <span>{$inputs.branch.value || m.common_select_placeholder()}</span>
+ </Select.Trigger>
+ <Select.Content style="width: var(--bits-select-anchor-width);">
+ {#each branches as branch}
+ <Select.Item value={branch.name} class="truncate">
+ {branch.name}
+ {#if branch.isDefault}
+ <span class="text-muted-foreground ml-2 text-xs">(default)</span>
+ {/if}
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ {:else}
+ <FormInput type="text" placeholder="main" bind:input={$inputs.branch} />
+ {/if}
+ {#if $inputs.branch.error}
+ <p class="mt-1 text-sm text-red-500">{$inputs.branch.error}</p>
+ {/if}
+ <p class="text-muted-foreground text-xs">
+ {branches.length > 0 ? m.git_sync_branch_select_hint() : m.git_sync_branch_manual_hint()}
+ </p>
+ </div>
+
+ <div class="space-y-1.5">
+ <Label for="composePath">{m.git_sync_compose_path()}</Label>
+ <div class="flex gap-2">
+ <div class="flex-1">
+ <FormInput type="text" placeholder="docker-compose.yml" bind:input={$inputs.composePath} />
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ onclick={() => (showFileBrowser = true)}
+ disabled={!selectedRepository?.value || !$inputs.branch.value}
+ title="Browse files"
+ >
+ <FolderOpenIcon class="size-4" />
+ </Button>
+ </div>
+ {#if !selectedRepository?.value || !$inputs.branch.value}
+ <p class="text-muted-foreground text-xs">Select a repository and branch to browse files</p>
+ {/if}
+ </div>
+
+ <SwitchWithLabel
+ id="autoSyncSwitch"
+ label={m.git_sync_auto_sync()}
+ description={m.common_auto_sync_description()}
+ error={$inputs.autoSync.error}
+ bind:checked={$inputs.autoSync.value}
+ />
+
+ <FormInput label={m.git_sync_sync_interval()} type="number" placeholder="5" bind:input={$inputs.syncInterval} />
+
+ <SwitchWithLabel
+ id="isEnabledSwitch"
+ label={m.common_enabled()}
+ description={m.common_enabled_description()}
+ error={$inputs.enabled.error}
+ bind:checked={$inputs.enabled.value}
+ />
+ </form>
+ {/if}
+ {/snippet}
+
+ {#snippet footer()}
+ <Button
+ type="button"
+ class="arcane-button-cancel flex-1"
+ variant="outline"
+ onclick={() => (open = false)}
+ disabled={isLoading}
+ >
+ {m.common_cancel()}
+ </Button>
+
+ <Button type="submit" form="sync-form" class="arcane-button-create flex-1" disabled={isLoading}>
+ {#if isLoading}
+ <Spinner class="mr-2 size-4" />
+ {/if}
+ {isEditMode ? m.common_save_changes() : m.common_add_button({ resource: m.resource_sync_cap() })}
+ </Button>
+ {/snippet}
+</ResponsiveDialog>
+
+<FileBrowserDialog
+ bind:open={showFileBrowser}
+ repositoryId={selectedRepository?.value || ''}
+ branch={$inputs.branch.value}
+ onSelect={(path) => {
+ $inputs.composePath.value = path;
+ }}
+/>
diff --git a/frontend/src/lib/components/sheets/git-repository-sheet.svelte b/frontend/src/lib/components/sheets/git-repository-sheet.svelte
new file mode 100644
index 000000000..b8c2c32a0
--- /dev/null
+++ b/frontend/src/lib/components/sheets/git-repository-sheet.svelte
@@ -0,0 +1,213 @@
+<script lang="ts">
+ import * as Sheet from '$lib/components/ui/sheet/index.js';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import FormInput from '$lib/components/form/form-input.svelte';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import * as Select from '$lib/components/ui/select/index.js';
+ import { Textarea } from '$lib/components/ui/textarea/index.js';
+ import { Label } from '$lib/components/ui/label/index.js';
+ import type { GitRepository, GitRepositoryCreateDto, GitRepositoryUpdateDto } from '$lib/types/gitops.type';
+ import { z } from 'zod/v4';
+ import { createForm, preventDefault } from '$lib/utils/form.utils';
+ import { m } from '$lib/paraglide/messages';
+ import { GitBranchIcon } from '$lib/icons';
+
+ type GitRepositoryFormProps = {
+ open: boolean;
+ repositoryToEdit: GitRepository | null;
+ onSubmit: (detail: { repository: GitRepositoryCreateDto | GitRepositoryUpdateDto; isEditMode: boolean }) => void;
+ isLoading: boolean;
+ };
+
+ let { open = $bindable(false), repositoryToEdit = $bindable(), onSubmit, isLoading }: GitRepositoryFormProps = $props();
+
+ let isEditMode = $derived(!!repositoryToEdit);
+
+ const formSchema = z.object({
+ name: z.string().min(1, m.common_name_required()),
+ url: z.string().min(1, m.common_url_required()),
+ authType: z.enum(['none', 'http', 'ssh']),
+ username: z.string().optional(),
+ token: z.string().optional(),
+ sshKey: z.string().optional(),
+ description: z.string().optional(),
+ enabled: z.boolean().default(true)
+ });
+
+ let formData = $derived({
+ name: open && repositoryToEdit ? repositoryToEdit.name : '',
+ url: open && repositoryToEdit ? repositoryToEdit.url : '',
+ authType: (open && repositoryToEdit ? repositoryToEdit.authType : 'http') as 'none' | 'http' | 'ssh',
+ username: open && repositoryToEdit ? repositoryToEdit.username || '' : '',
+ token: '',
+ sshKey: '',
+ description: open && repositoryToEdit ? repositoryToEdit.description || '' : '',
+ enabled: open && repositoryToEdit ? (repositoryToEdit.enabled ?? true) : true
+ });
+
+ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+
+ let selectedAuthType = $state<{ value: string; label: string }>({
+ value: 'http',
+ label: m.git_repository_auth_http()
+ });
+
+ function getAuthTypeLabel(type: string): string {
+ switch (type) {
+ case 'http':
+ return m.git_repository_auth_http();
+ case 'ssh':
+ return m.git_repository_auth_ssh();
+ default:
+ return m.git_repository_auth_none();
+ }
+ }
+
+ $effect(() => {
+ if (open && repositoryToEdit) {
+ selectedAuthType = {
+ value: repositoryToEdit.authType,
+ label: getAuthTypeLabel(repositoryToEdit.authType)
+ };
+ } else if (open && !repositoryToEdit) {
+ selectedAuthType = { value: 'http', label: m.git_repository_auth_http() };
+ }
+ });
+
+ function handleSubmit() {
+ const data = form.validate();
+ if (!data) return;
+
+ const payload: GitRepositoryCreateDto | GitRepositoryUpdateDto = {
+ name: data.name,
+ url: data.url,
+ authType: selectedAuthType.value,
+ description: data.description,
+ enabled: data.enabled
+ };
+
+ if (selectedAuthType.value === 'http') {
+ if (data.username) payload.username = data.username;
+ if (data.token) payload.token = data.token;
+ } else if (selectedAuthType.value === 'ssh') {
+ if (data.sshKey) payload.sshKey = data.sshKey;
+ }
+
+ onSubmit({ repository: payload, isEditMode });
+ }
+</script>
+
+<Sheet.Root bind:open>
+ <Sheet.Content class="p-6">
+ <Sheet.Header class="space-y-3 border-b pb-6">
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 flex size-10 shrink-0 items-center justify-center rounded-lg">
+ <GitBranchIcon class="text-primary size-5" />
+ </div>
+ <div>
+ <Sheet.Title class="text-xl font-semibold">
+ {isEditMode ? m.git_repository_edit_title() : m.git_repository_add_title()}
+ </Sheet.Title>
+ <Sheet.Description class="text-muted-foreground mt-1 text-sm">
+ {isEditMode ? m.common_edit_description() : m.common_add_description()}
+ </Sheet.Description>
+ </div>
+ </div>
+ </Sheet.Header>
+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-4">
+ <FormInput
+ label={m.git_repository_name()}
+ type="text"
+ placeholder={m.common_name_placeholder()}
+ bind:input={$inputs.name}
+ />
+
+ <FormInput
+ label={m.git_repository_url()}
+ type="text"
+ placeholder="https://github.com/user/repo.git"
+ bind:input={$inputs.url}
+ />
+
+ <div class="space-y-2">
+ <Label for="authType">{m.git_repository_auth_type()}</Label>
+ <Select.Root
+ type="single"
+ bind:value={selectedAuthType.value}
+ onValueChange={(v) => {
+ if (v) {
+ selectedAuthType = { value: v, label: getAuthTypeLabel(v) };
+ $inputs.authType.value = v as any;
+ }
+ }}
+ >
+ <Select.Trigger id="authType">
+ <span>{selectedAuthType.label}</span>
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="none">{m.git_repository_auth_none()}</Select.Item>
+ <Select.Item value="http">{m.git_repository_auth_http()}</Select.Item>
+ <Select.Item value="ssh">{m.git_repository_auth_ssh()}</Select.Item>
+ </Select.Content>
+ </Select.Root>
+ </div>
+
+ {#if selectedAuthType.value === 'http'}
+ <FormInput label={m.common_username()} type="text" bind:input={$inputs.username} />
+ <FormInput
+ label={m.common_token()}
+ type="password"
+ placeholder={isEditMode ? m.common_keep_placeholder() : m.common_token_placeholder()}
+ bind:input={$inputs.token}
+ />
+ {:else if selectedAuthType.value === 'ssh'}
+ {#if $inputs.sshKey}
+ <div class="space-y-2">
+ <Label for="sshKey">{m.git_repository_ssh_key_label()}</Label>
+ <Textarea
+ id="sshKey"
+ bind:value={$inputs.sshKey.value}
+ placeholder={m.git_repository_ssh_key_placeholder()}
+ rows={6}
+ class="font-mono text-xs"
+ />
+ </div>
+ {/if}
+ {/if}
+
+ <FormInput
+ label={m.common_description()}
+ type="text"
+ placeholder={m.common_description_placeholder()}
+ bind:input={$inputs.description}
+ />
+
+ <SwitchWithLabel
+ id="isEnabledSwitch"
+ label={m.common_enabled()}
+ description={m.common_enabled_description()}
+ bind:checked={$inputs.enabled.value}
+ />
+
+ <Sheet.Footer class="flex flex-row gap-2">
+ <Button
+ type="button"
+ class="arcane-button-cancel flex-1"
+ variant="outline"
+ onclick={() => (open = false)}
+ disabled={isLoading}
+ >
+ {m.common_cancel()}
+ </Button>
+
+ <Button type="submit" class="arcane-button-create flex-1" disabled={isLoading}>
+ {#if isLoading}
+ <Spinner class="mr-2 size-4" />
+ {/if}
+ {isEditMode ? m.common_save_changes() : m.common_add_button({ resource: m.resource_repository_cap() })}
+ </Button>
+ </Sheet.Footer>
+ </form>
+ </Sheet.Content>
+</Sheet.Root>
diff --git a/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelte b/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelte
index 46512da8c..5c145a09e 100644
--- a/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-itemgroup.svelte
@@ -25,6 +25,10 @@
const sidebar = useSidebar();
function isActiveItem(url: string): boolean {
+ // Special case: Don't highlight "Environments" when on GitOps page
+ if (url === '/environments' && page.url.pathname.includes('/gitops')) {
+ return false;
+ }
return page.url.pathname === url || (page.url.pathname.startsWith(url) && url !== '/');
}
diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelte
index 3d30c6504..2acf25955 100644
--- a/frontend/src/lib/components/sidebar/sidebar.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar.svelte
@@ -1,5 +1,5 @@
<script lang="ts" module>
- import { navigationItems } from '$lib/config/navigation-config';
+ import { navigationItems, getManagementItems } from '$lib/config/navigation-config';
</script>
<script lang="ts">
@@ -20,6 +20,7 @@
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import VersionInfoDialog from '$lib/components/dialogs/version-info-dialog.svelte';
import { LogoutIcon } from '$lib/icons';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
let {
ref = $bindable(null),
@@ -57,6 +58,9 @@
}
return item;
}) ?? [];
+
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const managementItems = $derived(getManagementItems(currentEnvId));
</script>
<VersionInfoDialog
@@ -91,7 +95,7 @@
{/if}
</Sidebar.Header>
<Sidebar.Content class={!isCollapsed ? '-mt-2' : ''}>
- <SidebarItemGroup label={m.sidebar_management()} items={navigationItems.managementItems} />
+ <SidebarItemGroup label={m.sidebar_management()} items={managementItems} />
<SidebarItemGroup label={m.sidebar_resources()} items={navigationItems.resourceItems} />
{#if isAdmin}
<SidebarItemGroup label={m.sidebar_administration()} items={desktopSettingsItems} />
diff --git a/frontend/src/lib/components/ui/button/button.svelte b/frontend/src/lib/components/ui/button/button.svelte
index ef786c2b7..f7e714a0b 100644
--- a/frontend/src/lib/components/ui/button/button.svelte
+++ b/frontend/src/lib/components/ui/button/button.svelte
@@ -30,7 +30,7 @@
defaultVariants: {
variant: 'default',
size: 'default',
- hoverEffect: 'lift'
+ hoverEffect: 'none'
}
});
@@ -64,7 +64,7 @@
class: className,
variant = 'default',
size = 'default',
- hoverEffect = 'lift',
+ hoverEffect = 'none',
ref = $bindable(null),
href = undefined,
type = 'button',
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index e19126d83..17e45473e 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -15,9 +15,9 @@ import {
VolumesIcon,
EventsIcon,
SettingsIcon,
- JobsIcon
+ JobsIcon,
+ GitBranchIcon
} from '$lib/icons';
-
import { m } from '$lib/paraglide/messages';
export type NavigationItem = {
@@ -107,3 +107,14 @@ export const defaultMobileNavigationSettings: MobileNavigationSettings = {
showLabels: true,
scrollToHide: true
};
+
+export function getManagementItems(environmentId: string): NavigationItem[] {
+ return [
+ ...navigationItems.managementItems,
+ {
+ title: m.git_syncs_title?.() ?? 'Git Sync',
+ url: `/environments/${environmentId}/gitops`,
+ icon: GitBranchIcon
+ }
+ ];
+}
diff --git a/frontend/src/lib/icons/index.ts b/frontend/src/lib/icons/index.ts
index 0b76de821..97cc07a13 100644
--- a/frontend/src/lib/icons/index.ts
+++ b/frontend/src/lib/icons/index.ts
@@ -103,4 +103,7 @@ export { default as VolumeUnusedIcon } from 'virtual:icons/clarity/hard-disk-sol
export { default as VolumeUsedIcon } from 'virtual:icons/clarity/hard-disk-solid-badged';
export { default as OpenIdIcon } from 'virtual:icons/simple-icons/openid';
export { default as LoginIcon } from 'virtual:icons/solar/login-3-linear';
+export { default as GitBranchIcon } from 'virtual:icons/tabler/git-branch';
+export { default as AutomationIcon } from 'virtual:icons/tabler/automation';
export { default as JobsIcon } from 'virtual:icons/solar/alarm-linear';
+export { default as UploadIcon } from 'virtual:icons/solar/upload-minimalistic-linear';
diff --git a/frontend/src/lib/services/env-mgmt-service.ts b/frontend/src/lib/services/env-mgmt-service.ts
index cef95462e..ad64ed192 100644
--- a/frontend/src/lib/services/env-mgmt-service.ts
+++ b/frontend/src/lib/services/env-mgmt-service.ts
@@ -36,8 +36,8 @@ export default class EnvironmentManagementService extends BaseAPIService {
return res.data.data as { status: 'online' | 'offline'; message?: string };
}
- async syncRegistries(environmentId: string): Promise<void> {
- await this.api.post(`/environments/${environmentId}/sync-registries`);
+ async sync(environmentId: string): Promise<void> {
+ await this.api.post(`/environments/${environmentId}/sync`);
}
async getDeploymentSnippets(environmentId: string): Promise<{ dockerRun: string; dockerCompose: string }> {
diff --git a/frontend/src/lib/services/git-repository-service.ts b/frontend/src/lib/services/git-repository-service.ts
new file mode 100644
index 000000000..490a41ab1
--- /dev/null
+++ b/frontend/src/lib/services/git-repository-service.ts
@@ -0,0 +1,51 @@
+import BaseAPIService from './api-service';
+import type {
+ GitRepositoryCreateDto,
+ GitRepositoryUpdateDto,
+ GitRepository,
+ GitRepositoryTestResponse,
+ BranchesResponse,
+ BrowseResponse
+} from '$lib/types/gitops.type';
+import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { transformPaginationParams } from '$lib/utils/params.util';
+
+export default class GitRepositoryService extends BaseAPIService {
+ async getRepositories(options?: SearchPaginationSortRequest): Promise<Paginated<GitRepository>> {
+ const params = transformPaginationParams(options);
+ const res = await this.api.get('/customize/git-repositories', { params });
+ return res.data;
+ }
+
+ async getRepository(id: string): Promise<GitRepository> {
+ return this.handleResponse(this.api.get(`/customize/git-repositories/${id}`));
+ }
+
+ async createRepository(repository: GitRepositoryCreateDto): Promise<GitRepository> {
+ return this.handleResponse(this.api.post(`/customize/git-repositories`, repository));
+ }
+
+ async updateRepository(id: string, repository: GitRepositoryUpdateDto): Promise<GitRepository> {
+ return this.handleResponse(this.api.put(`/customize/git-repositories/${id}`, repository));
+ }
+
+ async deleteRepository(id: string): Promise<void> {
+ return this.handleResponse(this.api.delete(`/customize/git-repositories/${id}`));
+ }
+
+ async testRepository(id: string, branch?: string): Promise<GitRepositoryTestResponse> {
+ const params = branch ? { branch } : {};
+ return this.handleResponse(this.api.post(`/customize/git-repositories/${id}/test`, {}, { params }));
+ }
+
+ async getBranches(id: string): Promise<BranchesResponse> {
+ return this.handleResponse(this.api.get(`/customize/git-repositories/${id}/branches`));
+ }
+
+ async browseFiles(id: string, branch: string, path?: string): Promise<BrowseResponse> {
+ const params = { branch, ...(path && { path }) };
+ return this.handleResponse(this.api.get(`/customize/git-repositories/${id}/files`, { params }));
+ }
+}
+
+export const gitRepositoryService = new GitRepositoryService();
diff --git a/frontend/src/lib/services/gitops-sync-service.ts b/frontend/src/lib/services/gitops-sync-service.ts
new file mode 100644
index 000000000..c79be22f8
--- /dev/null
+++ b/frontend/src/lib/services/gitops-sync-service.ts
@@ -0,0 +1,56 @@
+import BaseAPIService from './api-service';
+import type {
+ GitOpsSyncCreateDto,
+ GitOpsSyncUpdateDto,
+ GitOpsSync,
+ SyncResult,
+ SyncStatus,
+ BrowseResponse,
+ ImportGitOpsSyncRequest,
+ ImportGitOpsSyncResponse
+} from '$lib/types/gitops.type';
+import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { transformPaginationParams } from '$lib/utils/params.util';
+
+export default class GitOpsSyncService extends BaseAPIService {
+ async getSyncs(environmentId: string, options?: SearchPaginationSortRequest): Promise<Paginated<GitOpsSync>> {
+ const params = transformPaginationParams(options);
+ const res = await this.api.get(`/environments/${environmentId}/gitops-syncs`, { params });
+ return res.data;
+ }
+
+ async getSync(environmentId: string, syncId: string): Promise<GitOpsSync> {
+ return this.handleResponse(this.api.get(`/environments/${environmentId}/gitops-syncs/${syncId}`));
+ }
+
+ async createSync(environmentId: string, sync: GitOpsSyncCreateDto): Promise<GitOpsSync> {
+ return this.handleResponse(this.api.post(`/environments/${environmentId}/gitops-syncs`, sync));
+ }
+
+ async updateSync(environmentId: string, syncId: string, sync: GitOpsSyncUpdateDto): Promise<GitOpsSync> {
+ return this.handleResponse(this.api.put(`/environments/${environmentId}/gitops-syncs/${syncId}`, sync));
+ }
+
+ async deleteSync(environmentId: string, syncId: string): Promise<void> {
+ return this.handleResponse(this.api.delete(`/environments/${environmentId}/gitops-syncs/${syncId}`));
+ }
+
+ async performSync(environmentId: string, syncId: string): Promise<SyncResult> {
+ return this.handleResponse(this.api.post(`/environments/${environmentId}/gitops-syncs/${syncId}/sync`));
+ }
+
+ async getSyncStatus(environmentId: string, syncId: string): Promise<SyncStatus> {
+ return this.handleResponse(this.api.get(`/environments/${environmentId}/gitops-syncs/${syncId}/status`));
+ }
+
+ async browseFiles(environmentId: string, syncId: string, path?: string): Promise<BrowseResponse> {
+ const params = path ? { path } : {};
+ return this.handleResponse(this.api.get(`/environments/${environmentId}/gitops-syncs/${syncId}/files`, { params }));
+ }
+
+ async importSyncs(environmentId: string, syncs: ImportGitOpsSyncRequest[]): Promise<ImportGitOpsSyncResponse> {
+ return this.handleResponse(this.api.post(`/environments/${environmentId}/gitops-syncs/import`, syncs));
+ }
+}
+
+export const gitOpsSyncService = new GitOpsSyncService();
diff --git a/frontend/src/lib/types/gitops.type.ts b/frontend/src/lib/types/gitops.type.ts
new file mode 100644
index 000000000..527d75212
--- /dev/null
+++ b/frontend/src/lib/types/gitops.type.ts
@@ -0,0 +1,136 @@
+export interface GitRepositoryCreateDto {
+ name: string;
+ url: string;
+ authType: string;
+ username?: string;
+ token?: string;
+ sshKey?: string;
+ description?: string;
+ enabled?: boolean;
+}
+
+export interface GitRepositoryUpdateDto {
+ name?: string;
+ url?: string;
+ authType?: string;
+ username?: string;
+ token?: string;
+ sshKey?: string;
+ description?: string;
+ enabled?: boolean;
+}
+
+export interface GitRepository {
+ id: string;
+ name: string;
+ url: string;
+ authType: string;
+ username?: string;
+ description?: string;
+ enabled: boolean;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface GitOpsSyncCreateDto {
+ name: string;
+ repositoryId: string;
+ branch: string;
+ composePath: string;
+ projectName?: string;
+ autoSync?: boolean;
+ syncInterval?: number;
+ enabled?: boolean;
+}
+
+export interface GitOpsSyncUpdateDto {
+ name?: string;
+ repositoryId?: string;
+ branch?: string;
+ composePath?: string;
+ projectName?: string;
+ autoSync?: boolean;
+ syncInterval?: number;
+ enabled?: boolean;
+}
+
+export interface GitOpsSync {
+ id: string;
+ name: string;
+ environmentId: string;
+ repositoryId: string;
+ repository?: GitRepository;
+ branch: string;
+ composePath: string;
+ projectName: string;
+ projectId?: string;
+ autoSync: boolean;
+ syncInterval: number;
+ lastSyncAt?: string;
+ lastSyncStatus?: string;
+ lastSyncError?: string;
+ lastSyncCommit?: string;
+ enabled: boolean;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface SyncResult {
+ success: boolean;
+ message: string;
+ error?: string;
+ syncedAt: string;
+}
+
+export interface FileTreeNode {
+ name: string;
+ path: string;
+ type: string;
+ size?: number;
+ children?: FileTreeNode[];
+}
+
+export interface BrowseResponse {
+ path: string;
+ files: FileTreeNode[];
+}
+
+export interface SyncStatus {
+ id: string;
+ enabled: boolean;
+ autoSync: boolean;
+ nextSyncAt?: string;
+ lastSyncAt?: string;
+ lastSyncStatus?: string;
+ lastSyncError?: string;
+ lastSyncCommit?: string;
+}
+
+export interface GitRepositoryTestResponse {
+ message: string;
+}
+
+export interface BranchInfo {
+ name: string;
+ isDefault: boolean;
+}
+
+export interface BranchesResponse {
+ branches: BranchInfo[];
+}
+
+export interface ImportGitOpsSyncRequest {
+ syncName: string;
+ gitRepo: string;
+ branch: string;
+ dockerComposePath: string;
+ autoSync: boolean;
+ syncInterval: number;
+ enabled: boolean;
+}
+
+export interface ImportGitOpsSyncResponse {
+ successCount: number;
+ failedCount: number;
+ errors: string[];
+}
diff --git a/frontend/src/lib/types/project.type.ts b/frontend/src/lib/types/project.type.ts
index 32855ed6c..47374d2fa 100644
--- a/frontend/src/lib/types/project.type.ts
+++ b/frontend/src/lib/types/project.type.ts
@@ -72,6 +72,9 @@ export interface Project {
statusReason?: string;
updatedAt: string;
createdAt: string;
+ gitOpsManagedBy?: string;
+ lastSyncCommit?: string;
+ gitRepositoryURL?: string;
services?: ProjectService[];
runtimeServices?: RuntimeService[];
composeContent?: string;
diff --git a/frontend/src/routes/(app)/customize/+page.svelte b/frontend/src/routes/(app)/customize/+page.svelte
index d38c9b54a..bef86114f 100644
--- a/frontend/src/routes/(app)/customize/+page.svelte
+++ b/frontend/src/routes/(app)/customize/+page.svelte
@@ -9,7 +9,16 @@
import type { CustomizeCategory } from '$lib/types/customize-search.type';
import { debounced } from '$lib/utils/utils';
import * as InputGroup from '$lib/components/ui/input-group/index.js';
- import { SearchIcon, TemplateIcon, ArrowRightIcon, FileTextIcon, RegistryIcon, VariableIcon, CustomizeIcon } from '$lib/icons';
+ import {
+ SearchIcon,
+ TemplateIcon,
+ ArrowRightIcon,
+ FileTextIcon,
+ RegistryIcon,
+ VariableIcon,
+ CustomizeIcon,
+ GitBranchIcon
+ } from '$lib/icons';
import HeaderCard from '$lib/components/header-card.svelte';
let { data } = $props();
@@ -24,7 +33,8 @@
'file-text': FileTextIcon,
layers: TemplateIcon,
package: RegistryIcon,
- code: VariableIcon
+ code: VariableIcon,
+ 'git-branch': GitBranchIcon
};
onMount(async () => {
diff --git a/frontend/src/routes/(app)/customize/git-repositories/+page.svelte b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
new file mode 100644
index 000000000..83ff2df12
--- /dev/null
+++ b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
@@ -0,0 +1,108 @@
+<script lang="ts">
+ import { toast } from 'svelte-sonner';
+ import type { GitRepository, GitRepositoryCreateDto, GitRepositoryUpdateDto } from '$lib/types/gitops.type';
+ import GitRepositoryFormSheet from '$lib/components/sheets/git-repository-sheet.svelte';
+ import RepositoryTable from './repository-table.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { m } from '$lib/paraglide/messages';
+ import { gitRepositoryService } from '$lib/services/git-repository-service';
+ import { untrack } from 'svelte';
+ import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
+
+ let { data } = $props();
+
+ let repositories = $state(untrack(() => data.repositories));
+ let selectedIds = $state<string[]>([]);
+ let isRepositoryDialogOpen = $state(false);
+ let repositoryToEdit = $state<GitRepository | null>(null);
+ let requestOptions = $state(untrack(() => data.repositoryRequestOptions));
+
+ let isLoading = $state({
+ create: false,
+ edit: false,
+ refresh: false
+ });
+
+ async function refreshRepositories() {
+ isLoading.refresh = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(gitRepositoryService.getRepositories(requestOptions)),
+ message: m.common_refresh_failed({ resource: m.git_repositories_title() }),
+ setLoadingState: (value) => (isLoading.refresh = value),
+ onSuccess: async (newRepositories) => {
+ repositories = newRepositories;
+ toast.success(m.common_refresh_success({ resource: m.git_repositories_title() }));
+ }
+ });
+ }
+
+ function openCreateRepositoryDialog() {
+ repositoryToEdit = null;
+ isRepositoryDialogOpen = true;
+ }
+
+ function openEditRepositoryDialog(repository: GitRepository) {
+ repositoryToEdit = repository;
+ isRepositoryDialogOpen = true;
+ }
+
+ async function handleRepositoryDialogSubmit(detail: {
+ repository: GitRepositoryCreateDto | GitRepositoryUpdateDto;
+ isEditMode: boolean;
+ }) {
+ const { repository, isEditMode } = detail;
+ const loadingKey = isEditMode ? 'edit' : 'create';
+ isLoading[loadingKey] = true;
+
+ try {
+ if (isEditMode && repositoryToEdit?.id) {
+ await gitRepositoryService.updateRepository(repositoryToEdit.id, repository as GitRepositoryUpdateDto);
+ toast.success(m.common_update_success({ resource: m.resource_repository() }));
+ } else {
+ await gitRepositoryService.createRepository(repository as GitRepositoryCreateDto);
+ toast.success(m.common_create_success({ resource: m.resource_repository() }));
+ }
+
+ repositories = await gitRepositoryService.getRepositories(requestOptions);
+ isRepositoryDialogOpen = false;
+ } catch (error) {
+ console.error('Error saving repository:', error);
+ toast.error(error instanceof Error ? error.message : m.common_save_failed());
+ } finally {
+ isLoading[loadingKey] = false;
+ }
+ }
+
+ const actionButtons: ActionButton[] = [
+ {
+ id: 'create',
+ action: 'create',
+ label: m.common_add_button({ resource: m.resource_repository_cap() }),
+ onclick: openCreateRepositoryDialog
+ },
+ {
+ id: 'refresh',
+ action: 'restart',
+ label: m.common_refresh(),
+ onclick: refreshRepositories,
+ loading: isLoading.refresh,
+ disabled: isLoading.refresh
+ }
+ ];
+</script>
+
+<ResourcePageLayout title={m.git_repositories_title()} subtitle={m.git_repositories_subtitle()} {actionButtons}>
+ {#snippet mainContent()}
+ <RepositoryTable bind:repositories bind:selectedIds bind:requestOptions onEditRepository={openEditRepositoryDialog} />
+ {/snippet}
+
+ {#snippet additionalContent()}
+ <GitRepositoryFormSheet
+ bind:open={isRepositoryDialogOpen}
+ bind:repositoryToEdit
+ onSubmit={handleRepositoryDialogSubmit}
+ isLoading={isLoading.create || isLoading.edit}
+ />
+ {/snippet}
+</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/customize/git-repositories/+page.ts b/frontend/src/routes/(app)/customize/git-repositories/+page.ts
new file mode 100644
index 000000000..83c7ef2f1
--- /dev/null
+++ b/frontend/src/routes/(app)/customize/git-repositories/+page.ts
@@ -0,0 +1,21 @@
+import { gitRepositoryService } from '$lib/services/git-repository-service';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async () => {
+ const repositoryRequestOptions = resolveInitialTableRequest('arcane-git-repositories-table', {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'name',
+ direction: 'asc'
+ }
+ } satisfies SearchPaginationSortRequest);
+
+ const repositories = await gitRepositoryService.getRepositories(repositoryRequestOptions);
+
+ return { repositories, repositoryRequestOptions };
+};
diff --git a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
new file mode 100644
index 000000000..11ba3060a
--- /dev/null
+++ b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
@@ -0,0 +1,282 @@
+<script lang="ts">
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { toast } from 'svelte-sonner';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { GitRepository } from '$lib/types/gitops.type';
+ import type { ColumnSpec } from '$lib/components/arcane-table';
+ import { UniversalMobileCard } from '$lib/components/arcane-table/index.js';
+ import { format } from 'date-fns';
+ import { m } from '$lib/paraglide/messages';
+ import { gitRepositoryService } from '$lib/services/git-repository-service';
+ import {
+ EllipsisIcon,
+ EditIcon as PencilIcon,
+ TestIcon as TestTubeIcon,
+ TrashIcon as Trash2Icon,
+ GitBranchIcon,
+ ApiKeyIcon as KeyIcon,
+ ExternalLinkIcon as LinkIcon
+ } from '$lib/icons';
+
+ type FieldVisibility = Record<string, boolean>;
+
+ let {
+ repositories = $bindable(),
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onEditRepository
+ }: {
+ repositories: Paginated<GitRepository>;
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onEditRepository: (repository: GitRepository) => void;
+ } = $props();
+
+ let isLoading = $state({
+ removing: false,
+ testing: false
+ });
+ let mobileFieldVisibility = $state<Record<string, boolean>>({});
+
+ async function handleDeleteSelected(ids: string[]) {
+ if (!ids?.length) return;
+
+ openConfirmDialog({
+ title: m.common_remove_title({ resource: `${ids.length} ${m.resource_repository()}(s)` }),
+ message: m.common_remove_message({ resource: `${ids.length} ${m.resource_repository()}(s)` }),
+ confirm: {
+ label: m.common_remove(),
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+
+ let successCount = 0;
+ let failureCount = 0;
+ for (const id of ids) {
+ const repo = repositories.data.find((r) => r.id === id);
+ const result = await tryCatch(gitRepositoryService.deleteRepository(id));
+ if (result.error) {
+ failureCount++;
+ toast.error(m.common_delete_failed({ resource: repo?.name ?? m.common_unknown() }));
+ } else {
+ successCount++;
+ }
+ }
+
+ if (successCount > 0) {
+ toast.success(m.common_delete_success({ resource: `${successCount} ${m.resource_repository()}(s)` }));
+ repositories = await gitRepositoryService.getRepositories(requestOptions);
+ }
+ if (failureCount > 0) toast.error(m.common_delete_failed({ resource: `${failureCount} items` }));
+
+ selectedIds = [];
+ isLoading.removing = false;
+ }
+ }
+ });
+ }
+
+ async function handleDeleteOne(id: string, name: string) {
+ const safeName = name ?? m.common_unknown();
+ openConfirmDialog({
+ title: m.git_repository_remove_confirm(),
+ message: m.git_repository_remove_message(),
+ confirm: {
+ label: m.common_remove(),
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+
+ const result = await tryCatch(gitRepositoryService.deleteRepository(id));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.common_delete_failed({ resource: safeName }),
+ setLoadingState: () => {},
+ onSuccess: async () => {
+ toast.success(m.common_delete_success({ resource: `${m.resource_repository()} "${safeName}"` }));
+ repositories = await gitRepositoryService.getRepositories(requestOptions);
+ }
+ });
+
+ isLoading.removing = false;
+ }
+ }
+ });
+ }
+
+ async function handleTest(id: string, name: string) {
+ isLoading.testing = true;
+ const safeName = name ?? m.common_unknown();
+ const result = await tryCatch(gitRepositoryService.testRepository(id));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.common_test_failed({ resource: safeName }),
+ setLoadingState: () => {},
+ onSuccess: () => {
+ toast.success(m.common_test_success({ resource: safeName }));
+ }
+ });
+ isLoading.testing = false;
+ }
+
+ const columns = [
+ { accessorKey: 'id', title: m.common_id(), hidden: true },
+ {
+ accessorKey: 'name',
+ title: m.git_repository_name(),
+ sortable: true,
+ cell: NameCell
+ },
+ {
+ accessorKey: 'url',
+ title: m.git_repository_url(),
+ sortable: true,
+ cell: UrlCell
+ },
+ {
+ accessorKey: 'authType',
+ title: m.git_repository_auth_type(),
+ sortable: true,
+ cell: AuthTypeCell
+ },
+ {
+ accessorKey: 'enabled',
+ title: m.common_status(),
+ sortable: true,
+ cell: StatusCell
+ },
+ {
+ accessorKey: 'createdAt',
+ title: m.common_created(),
+ sortable: true,
+ cell: CreatedCell
+ }
+ ] satisfies ColumnSpec<GitRepository>[];
+
+ const mobileFields = [
+ { id: 'id', label: m.common_id(), defaultVisible: false },
+ { id: 'name', label: m.git_repository_name(), defaultVisible: true },
+ { id: 'url', label: m.git_repository_url(), defaultVisible: true },
+ { id: 'authType', label: m.git_repository_auth_type(), defaultVisible: true },
+ { id: 'enabled', label: m.common_status(), defaultVisible: true },
+ { id: 'createdAt', label: m.common_created(), defaultVisible: true }
+ ];
+</script>
+
+{#snippet NameCell({ value }: { value: unknown })}
+ <div class="flex items-center gap-2">
+ <GitBranchIcon class="text-muted-foreground size-4" />
+ <span class="font-medium">{value}</span>
+ </div>
+{/snippet}
+
+{#snippet UrlCell({ value }: { value: unknown })}
+ <code class="bg-muted text-muted-foreground rounded px-2 py-1 text-xs">{value}</code>
+{/snippet}
+
+{#snippet AuthTypeCell({ value }: { value: unknown })}
+ {@const authType = String(value)}
+ {#if authType === 'http'}
+ <StatusBadge variant="blue" text={m.git_repository_auth_http()} />
+ {:else if authType === 'ssh'}
+ <StatusBadge variant="purple" text={m.git_repository_auth_ssh()} />
+ {:else}
+ <StatusBadge variant="gray" text={m.git_repository_auth_none()} />
+ {/if}
+{/snippet}
+
+{#snippet StatusCell({ value }: { value: unknown })}
+ {@const enabled = Boolean(value)}
+ <StatusBadge variant={enabled ? 'green' : 'red'} text={enabled ? m.common_enabled() : m.common_disabled()} />
+{/snippet}
+
+{#snippet CreatedCell({ value }: { value: unknown })}
+ <span class="text-sm">{value ? format(new Date(String(value)), 'PP p') : m.common_na()}</span>
+{/snippet}
+
+{#snippet RepositoryMobileCardSnippet({
+ item,
+ mobileFieldVisibility
+}: {
+ row: any;
+ item: GitRepository;
+ mobileFieldVisibility: FieldVisibility;
+})}
+ <UniversalMobileCard
+ {item}
+ icon={{ component: GitBranchIcon, variant: 'blue' as const }}
+ title={(item) => item.name}
+ subtitle={(item) => ((mobileFieldVisibility.id ?? false) ? item.id : item.url)}
+ badges={[{ variant: 'blue' as const, text: m.resource_repository_cap() }]}
+ fields={[
+ {
+ label: m.git_repository_url(),
+ getValue: (item: GitRepository) => item.url,
+ icon: LinkIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility.url ?? true
+ },
+ {
+ label: m.git_repository_auth_type(),
+ getValue: (item: GitRepository) => item.authType,
+ icon: KeyIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility.authType ?? true
+ }
+ ]}
+ rowActions={RowActions}
+ />
+{/snippet}
+
+{#snippet RowActions({ item }: { item: GitRepository })}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">{m.common_open_menu()}</span>
+ <EllipsisIcon />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => handleTest(item.id, item.name)} disabled={isLoading.testing}>
+ <TestTubeIcon class="size-4" />
+ {m.git_repository_test_connection()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onEditRepository(item)}>
+ <PencilIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleDeleteOne(item.id, item.name)}
+ disabled={isLoading.removing}
+ >
+ <Trash2Icon class="size-4" />
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+{/snippet}
+
+<ArcaneTable
+ persistKey="arcane-git-repositories-table"
+ items={repositories}
+ bind:requestOptions
+ bind:selectedIds
+ bind:mobileFieldVisibility
+ onRemoveSelected={(ids) => handleDeleteSelected(ids)}
+ onRefresh={async (options) => (repositories = await gitRepositoryService.getRepositories(options))}
+ {columns}
+ {mobileFields}
+ rowActions={RowActions}
+ mobileCard={RepositoryMobileCardSnippet}
+/>
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelte
index 2b7ba3f78..d94bdef7e 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte
@@ -27,11 +27,13 @@
EnvironmentsIcon,
AlertIcon,
TestIcon,
- RegistryIcon,
+ RefreshIcon,
ResetIcon,
ApiKeyIcon,
DockerBrandIcon,
- SettingsIcon
+ SettingsIcon,
+ GitBranchIcon,
+ ArrowRightIcon
} from '$lib/icons';
let { data } = $props();
@@ -57,7 +59,7 @@
let isRefreshing = $state(false);
let isTestingConnection = $state(false);
let isSaving = $state(false);
- let isSyncingRegistries = $state(false);
+ let isSyncing = $state(false);
let isRegeneratingKey = $state(false);
let showRegenerateDialog = $state(false);
let regeneratedApiKey = $state<string | null>(null);
@@ -237,17 +239,17 @@
}
}
- async function syncRegistries() {
- if (isSyncingRegistries) return;
+ async function syncEnvironment() {
+ if (isSyncing) return;
try {
- isSyncingRegistries = true;
- await environmentManagementService.syncRegistries(environment.id);
- toast.success('Registries synced successfully');
+ isSyncing = true;
+ await environmentManagementService.sync(environment.id);
+ toast.success(m.sync_environment_success());
} catch (error) {
- console.error('Failed to sync registries:', error);
- toast.error('Failed to sync registries');
+ console.error('Failed to sync environment:', error);
+ toast.error(m.sync_environment_failed());
} finally {
- isSyncingRegistries = false;
+ isSyncing = false;
}
}
@@ -433,11 +435,11 @@
<ArcaneButton
action="base"
tone="outline"
- onclick={syncRegistries}
- disabled={isSyncingRegistries}
- loading={isSyncingRegistries}
- icon={RegistryIcon}
- customLabel={m.sync_registries()}
+ onclick={syncEnvironment}
+ disabled={isSyncing}
+ loading={isSyncing}
+ icon={RefreshIcon}
+ customLabel={m.sync_environment()}
/>
{/if}
@@ -860,6 +862,27 @@
</Card.Content>
</Card.Root>
{/if}
+
+ <Card.Root class="flex flex-col">
+ <Card.Header icon={GitBranchIcon}>
+ <div class="flex flex-col space-y-1.5">
+ <Card.Title>
+ <h2>{m.git_syncs_title()}</h2>
+ </Card.Title>
+ <Card.Description>{m.git_subtitle()}</Card.Description>
+ </div>
+ </Card.Header>
+ <Card.Content class="p-4">
+ <p class="text-muted-foreground mb-4 text-sm">{m.git_environment_card_description()}</p>
+ <ArcaneButton
+ action="base"
+ onclick={() => goto(`/environments/${environment.id}/gitops`)}
+ icon={ArrowRightIcon}
+ customLabel={m.git_manage_syncs()}
+ class="w-full"
+ />
+ </Card.Content>
+ </Card.Root>
</div>
<AlertDialog.Root bind:open={showRegenerateDialog}>
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
new file mode 100644
index 000000000..18056ac6c
--- /dev/null
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
@@ -0,0 +1,207 @@
+<script lang="ts">
+ import { toast } from 'svelte-sonner';
+ import type { GitOpsSync, GitOpsSyncCreateDto, GitOpsSyncUpdateDto, ImportGitOpsSyncRequest } from '$lib/types/gitops.type';
+ import GitOpsSyncFormSheet from '$lib/components/dialogs/gitops-sync-dialog.svelte';
+ import GitOpsImportDialog from '$lib/components/dialogs/gitops-import-dialog.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { m } from '$lib/paraglide/messages';
+ import { gitOpsSyncService } from '$lib/services/gitops-sync-service';
+ import { untrack } from 'svelte';
+ import { page } from '$app/state';
+ import { goto } from '$app/navigation';
+ import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
+ import SyncTable from './sync-table.svelte';
+ import { RefreshIcon, ClockIcon, SuccessIcon, GitBranchIcon, UploadIcon } from '$lib/icons';
+
+ let { data } = $props();
+
+ let syncs = $state(untrack(() => data.syncs));
+ let selectedIds = $state<string[]>([]);
+ let isSyncDialogOpen = $state(false);
+ let isImportDialogOpen = $state(false);
+ let syncToEdit = $state<GitOpsSync | null>(null);
+ let syncRequestOptions = $state(untrack(() => data.syncRequestOptions));
+ let environmentId = $derived(data.environmentId);
+
+ let isLoading = $state({
+ create: false,
+ edit: false,
+ refresh: false,
+ import: false
+ });
+
+ const activeSyncs = $derived(syncs.data?.filter((s) => s.enabled && s.autoSync).length ?? 0);
+ const successfulSyncs = $derived(syncs.data?.filter((s) => s.lastSyncStatus === 'success').length ?? 0);
+
+ $effect(() => {
+ if (page.url.searchParams.get('action') === 'create') {
+ // Use a small timeout to ensure the page is fully mounted and ready
+ setTimeout(() => {
+ openCreateSyncDialog();
+ // Remove the query param so it doesn't reopen on refresh
+ const newUrl = new URL(page.url);
+ newUrl.searchParams.delete('action');
+ goto(newUrl.toString(), { replaceState: true, keepFocus: true });
+ }, 100);
+ }
+ });
+
+ async function refreshSyncs() {
+ isLoading.refresh = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(gitOpsSyncService.getSyncs(environmentId, syncRequestOptions)),
+ message: m.common_refresh_failed({ resource: m.git_syncs_title() }),
+ setLoadingState: (value) => (isLoading.refresh = value),
+ onSuccess: async (newSyncs) => {
+ syncs = newSyncs;
+ toast.success(m.common_refresh_success({ resource: m.git_syncs_title() }));
+ }
+ });
+ }
+
+ function openCreateSyncDialog() {
+ syncToEdit = null;
+ isSyncDialogOpen = true;
+ }
+
+ function openEditSyncDialog(sync: GitOpsSync) {
+ syncToEdit = sync;
+ isSyncDialogOpen = true;
+ }
+
+ async function handleSyncDialogSubmit(detail: { sync: GitOpsSyncCreateDto | GitOpsSyncUpdateDto; isEditMode: boolean }) {
+ const { sync, isEditMode } = detail;
+ const loadingKey = isEditMode ? 'edit' : 'create';
+ isLoading[loadingKey] = true;
+
+ try {
+ if (isEditMode && syncToEdit?.id) {
+ await gitOpsSyncService.updateSync(environmentId, syncToEdit.id, sync as GitOpsSyncUpdateDto);
+ toast.success(m.common_update_success({ resource: m.resource_sync() }));
+ } else {
+ await gitOpsSyncService.createSync(environmentId, sync as GitOpsSyncCreateDto);
+ toast.success(m.common_create_success({ resource: m.resource_sync() }));
+ }
+
+ syncs = await gitOpsSyncService.getSyncs(environmentId, syncRequestOptions);
+ isSyncDialogOpen = false;
+ } catch (error) {
+ console.error('Error saving sync:', error);
+ toast.error(error instanceof Error ? error.message : m.common_save_failed());
+ } finally {
+ isLoading[loadingKey] = false;
+ }
+ }
+
+ async function handleImportSubmit(data: ImportGitOpsSyncRequest[]) {
+ isLoading.import = true;
+ try {
+ const response = await gitOpsSyncService.importSyncs(environmentId, data);
+
+ if (response.failedCount === 0) {
+ toast.success(m.git_sync_import_success({ count: response.successCount }));
+ isImportDialogOpen = false;
+ } else {
+ if (response.successCount > 0) {
+ toast.warning(
+ m.git_sync_import_partial_success({ successCount: response.successCount, failedCount: response.failedCount })
+ );
+ } else {
+ toast.error(m.git_sync_import_failed_count({ count: response.failedCount }));
+ }
+
+ // Show error details
+ if (response.errors && response.errors.length > 0) {
+ console.error('Import errors:', response.errors);
+ // Could show a dialog with errors here, for now just toast the first few
+ response.errors.slice(0, 3).forEach((err) => toast.error(err));
+ }
+ }
+
+ syncs = await gitOpsSyncService.getSyncs(environmentId, syncRequestOptions);
+ } catch (error) {
+ console.error('Error importing syncs:', error);
+ toast.error(error instanceof Error ? error.message : m.git_sync_import_failed());
+ } finally {
+ isLoading.import = false;
+ }
+ }
+
+ const actionButtons: ActionButton[] = [
+ {
+ id: 'create',
+ action: 'create',
+ label: m.common_add_button({ resource: m.resource_sync_cap() }),
+ onclick: openCreateSyncDialog
+ },
+ {
+ id: 'import',
+ action: 'create',
+ label: m.git_sync_import_open_button(),
+ icon: UploadIcon,
+ onclick: () => (isImportDialogOpen = true)
+ },
+ {
+ id: 'manage-repos',
+ action: 'edit',
+ label: m.git_repositories_title(),
+ icon: GitBranchIcon,
+ onclick: () => goto('/customize/git-repositories')
+ },
+ {
+ id: 'refresh',
+ action: 'restart',
+ label: m.common_refresh(),
+ onclick: refreshSyncs,
+ loading: isLoading.refresh,
+ disabled: isLoading.refresh
+ }
+ ];
+
+ const statCards = $derived<StatCardConfig[]>([
+ {
+ title: m.common_total(),
+ value: syncs?.pagination?.totalItems ?? 0,
+ icon: RefreshIcon,
+ iconColor: 'text-blue-500',
+ bgColor: 'bg-blue-500/10'
+ },
+ {
+ title: m.common_active(),
+ value: activeSyncs,
+ icon: ClockIcon,
+ iconColor: 'text-purple-500',
+ bgColor: 'bg-purple-500/10'
+ },
+ {
+ title: m.common_successful(),
+ value: successfulSyncs,
+ icon: SuccessIcon,
+ iconColor: 'text-green-500',
+ bgColor: 'bg-green-500/10'
+ }
+ ]);
+</script>
+
+<ResourcePageLayout title={m.git_syncs_title()} subtitle={m.git_subtitle()} {actionButtons} {statCards}>
+ {#snippet mainContent()}
+ <SyncTable
+ {environmentId}
+ bind:syncs
+ bind:selectedIds
+ bind:requestOptions={syncRequestOptions}
+ onEditSync={openEditSyncDialog}
+ />
+ {/snippet}
+
+ {#snippet additionalContent()}
+ <GitOpsSyncFormSheet
+ bind:open={isSyncDialogOpen}
+ bind:syncToEdit
+ onSubmit={handleSyncDialogSubmit}
+ isLoading={isLoading.create || isLoading.edit}
+ />
+ <GitOpsImportDialog bind:open={isImportDialogOpen} onSubmit={handleImportSubmit} isLoading={isLoading.import} />
+ {/snippet}
+</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/+page.ts b/frontend/src/routes/(app)/environments/[id]/gitops/+page.ts
new file mode 100644
index 000000000..e9e575518
--- /dev/null
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/+page.ts
@@ -0,0 +1,27 @@
+import { gitOpsSyncService } from '$lib/services/gitops-sync-service';
+import { environmentManagementService } from '$lib/services/env-mgmt-service';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async ({ params }) => {
+ const environmentId = params.id;
+
+ const syncRequestOptions = resolveInitialTableRequest('arcane-gitops-syncs-table', {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'name',
+ direction: 'asc'
+ }
+ } satisfies SearchPaginationSortRequest);
+
+ const [environment, syncs] = await Promise.all([
+ environmentManagementService.get(environmentId),
+ gitOpsSyncService.getSyncs(environmentId, syncRequestOptions)
+ ]);
+
+ return { environment, environmentId, syncs, syncRequestOptions };
+};
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
new file mode 100644
index 000000000..d868d2675
--- /dev/null
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte
@@ -0,0 +1,348 @@
+<script lang="ts">
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { Button } from '$lib/components/ui/button/index.js';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import { toast } from 'svelte-sonner';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { GitOpsSync } from '$lib/types/gitops.type';
+ import type { Row } from '@tanstack/table-core';
+ import type { ColumnSpec } from '$lib/components/arcane-table';
+ import { UniversalMobileCard } from '$lib/components/arcane-table/index.js';
+ import { format } from 'date-fns';
+ import { m } from '$lib/paraglide/messages';
+ import { gitOpsSyncService } from '$lib/services/gitops-sync-service';
+ import {
+ EllipsisIcon,
+ EditIcon as PencilIcon,
+ StartIcon as PlayIcon,
+ TrashIcon as Trash2Icon,
+ RefreshIcon as RefreshCwIcon,
+ GitBranchIcon,
+ ProjectsIcon as FolderIcon,
+ HashIcon
+ } from '$lib/icons';
+ import { goto } from '$app/navigation';
+ import * as Tooltip from '$lib/components/ui/tooltip/index.js';
+
+ type FieldVisibility = Record<string, boolean>;
+
+ let {
+ environmentId,
+ syncs = $bindable(),
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onEditSync
+ }: {
+ environmentId: string;
+ syncs: Paginated<GitOpsSync>;
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onEditSync: (sync: GitOpsSync) => void;
+ } = $props();
+
+ let isLoading = $state({
+ removing: false,
+ syncing: false
+ });
+ let mobileFieldVisibility = $state<Record<string, boolean>>({});
+
+ async function handleDeleteSelected(ids: string[]) {
+ if (!ids?.length) return;
+
+ openConfirmDialog({
+ title: m.common_remove_title({ resource: `${ids.length} ${m.resource_sync()}(s)` }),
+ message: m.common_remove_message({ resource: `${ids.length} ${m.resource_sync()}(s)` }),
+ confirm: {
+ label: m.common_remove(),
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+
+ let successCount = 0;
+ let failureCount = 0;
+ for (const id of ids) {
+ const sync = syncs.data.find((s) => s.id === id);
+ const result = await tryCatch(gitOpsSyncService.deleteSync(environmentId, id));
+ if (result.error) {
+ failureCount++;
+ toast.error(m.common_delete_failed({ resource: sync?.name ?? m.common_unknown() }));
+ } else {
+ successCount++;
+ }
+ }
+
+ if (successCount > 0) {
+ toast.success(m.common_delete_success({ resource: `${successCount} ${m.resource_sync()}(s)` }));
+ syncs = await gitOpsSyncService.getSyncs(environmentId, requestOptions);
+ }
+ if (failureCount > 0) toast.error(m.common_delete_failed({ resource: `${failureCount} items` }));
+
+ selectedIds = [];
+ isLoading.removing = false;
+ }
+ }
+ });
+ }
+
+ async function handleDeleteOne(id: string, name: string) {
+ const safeName = name ?? m.common_unknown();
+ openConfirmDialog({
+ title: m.git_sync_remove_confirm(),
+ message: m.git_sync_remove_message(),
+ confirm: {
+ label: m.common_remove(),
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+
+ const result = await tryCatch(gitOpsSyncService.deleteSync(environmentId, id));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.common_delete_failed({ resource: safeName }),
+ setLoadingState: () => {},
+ onSuccess: async () => {
+ toast.success(m.common_delete_success({ resource: `${m.resource_sync()} "${safeName}"` }));
+ syncs = await gitOpsSyncService.getSyncs(environmentId, requestOptions);
+ }
+ });
+
+ isLoading.removing = false;
+ }
+ }
+ });
+ }
+
+ async function handlePerformSync(id: string, name: string) {
+ isLoading.syncing = true;
+ const result = await tryCatch(gitOpsSyncService.performSync(environmentId, id));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.git_sync_failed(),
+ setLoadingState: () => {},
+ onSuccess: () => {
+ toast.success(m.git_sync_success());
+ gitOpsSyncService.getSyncs(environmentId, requestOptions).then((newSyncs) => {
+ syncs = newSyncs;
+ });
+ }
+ });
+ isLoading.syncing = false;
+ }
+
+ const columns = [
+ { accessorKey: 'id', title: m.common_id(), hidden: true },
+ {
+ accessorKey: 'name',
+ title: m.git_sync_name(),
+ sortable: true,
+ cell: NameCell
+ },
+ {
+ accessorKey: 'branch',
+ title: m.git_sync_branch(),
+ sortable: true,
+ cell: BranchCell
+ },
+ {
+ accessorKey: 'composePath',
+ title: m.git_sync_compose_path(),
+ sortable: true,
+ cell: PathCell
+ },
+ {
+ accessorKey: 'autoSync',
+ title: m.git_sync_auto_sync(),
+ sortable: true,
+ cell: AutoSyncCell
+ },
+ {
+ accessorKey: 'lastSyncStatus',
+ title: m.git_sync_status(),
+ sortable: true,
+ cell: StatusCell
+ },
+ {
+ accessorKey: 'lastSyncCommit',
+ title: 'Commit',
+ sortable: true,
+ cell: CommitCell
+ },
+ {
+ accessorKey: 'lastSyncAt',
+ title: m.git_sync_last_sync(),
+ sortable: true,
+ cell: LastSyncCell
+ },
+ {
+ accessorKey: 'enabled',
+ title: m.common_status(),
+ sortable: true,
+ cell: EnabledCell
+ }
+ ] satisfies ColumnSpec<GitOpsSync>[];
+
+ const mobileFields = [
+ { id: 'id', label: m.common_id(), defaultVisible: false },
+ { id: 'name', label: m.git_sync_name(), defaultVisible: true },
+ { id: 'branch', label: m.git_sync_branch(), defaultVisible: true },
+ { id: 'composePath', label: m.git_sync_compose_path(), defaultVisible: true },
+ { id: 'autoSync', label: m.git_sync_auto_sync(), defaultVisible: true },
+ { id: 'lastSyncStatus', label: m.git_sync_status(), defaultVisible: true },
+ { id: 'lastSyncCommit', label: 'Commit', defaultVisible: false },
+ { id: 'lastSyncAt', label: m.git_sync_last_sync(), defaultVisible: true },
+ { id: 'enabled', label: m.common_status(), defaultVisible: true }
+ ];
+</script>
+
+{#snippet NameCell({ item, value }: { item: GitOpsSync; value: any; row: Row<GitOpsSync> })}
+ <a class="font-medium hover:underline" href="/projects/{item.projectId}">
+ {value}
+ </a>
+{/snippet}
+
+{#snippet BranchCell({ value }: { value: any; item: GitOpsSync; row: Row<GitOpsSync> })}
+ <div class="flex items-center gap-1.5">
+ <GitBranchIcon class="text-muted-foreground size-3.5" />
+ <code class="bg-muted text-muted-foreground rounded px-2 py-0.5 text-xs">{value}</code>
+ </div>
+{/snippet}
+
+{#snippet PathCell({ value }: { value: any; item: GitOpsSync; row: Row<GitOpsSync> })}
+ <div class="flex items-center gap-1.5">
+ <FolderIcon class="text-muted-foreground size-3.5" />
+ <code class="bg-muted text-muted-foreground rounded px-2 py-0.5 text-xs">{value}</code>
+ </div>
+{/snippet}
+
+{#snippet AutoSyncCell({ value }: { value: any; item: GitOpsSync; row: Row<GitOpsSync> })}
+ <StatusBadge variant={value ? 'blue' : 'gray'} text={value ? m.common_enabled() : m.common_disabled()} />
+{/snippet}
+
+{#snippet StatusCell({ value }: { value: any; item: GitOpsSync; row: Row<GitOpsSync> })}
+ {#if value === 'success'}
+ <StatusBadge variant="green" text={m.common_success()} />
+ {:else if value === 'failed'}
+ <StatusBadge variant="red" text={m.common_failed()} />
+ {:else if value === 'pending'}
+ <StatusBadge variant="amber" text={m.common_pending()} />
+ {:else}
+ <StatusBadge variant="gray" text={m.common_na()} />
+ {/if}
+{/snippet}
+
+{#snippet CommitCell({ value, item }: { value: any; item: GitOpsSync; row: Row<GitOpsSync> })}
+ {#if value}
+ <div class="flex items-center gap-1.5">
+ <HashIcon class="text-muted-foreground size-3.5" />
+ {#if item.repository?.url}
+ <a
+ href="{item.repository.url.replace(/\.git$/, '')}/commit/{value}"
+ target="_blank"
+ class="hover:text-primary bg-muted text-muted-foreground rounded px-2 py-0.5 font-mono text-xs transition-colors"
+ >
+ {value}
+ </a>
+ {:else}
+ <code class="bg-muted text-muted-foreground rounded px-2 py-0.5 font-mono text-xs">
+ {value}
+ </code>
+ {/if}
+ </div>
+ {:else}
+ <span class="text-muted-foreground text-sm">{m.common_na()}</span>
+ {/if}
+{/snippet}
+
+{#snippet LastSyncCell({ value }: { value: any; item: GitOpsSync; row: Row<GitOpsSync> })}
+ <span class="text-sm">{value ? format(new Date(value), 'PP p') : m.common_never()}</span>
+{/snippet}
+
+{#snippet EnabledCell({ value }: { value: any; item: GitOpsSync; row: Row<GitOpsSync> })}
+ <StatusBadge variant={value ? 'green' : 'red'} text={value ? m.common_enabled() : m.common_disabled()} />
+{/snippet}
+
+{#snippet SyncMobileCardSnippet({
+ item,
+ mobileFieldVisibility,
+ row
+}: {
+ item: GitOpsSync;
+ mobileFieldVisibility: FieldVisibility;
+ row: Row<GitOpsSync>;
+})}
+ <UniversalMobileCard
+ {item}
+ icon={{ component: RefreshCwIcon, variant: 'purple' as const }}
+ title={(item) => item.name}
+ subtitle={(item) => ((mobileFieldVisibility.id ?? false) ? item.id : item.branch)}
+ badges={[{ variant: 'purple' as const, text: m.resource_sync_cap() }]}
+ fields={[
+ {
+ label: m.git_sync_branch(),
+ getValue: (item: GitOpsSync) => item.branch,
+ icon: GitBranchIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility.branch ?? true
+ },
+ {
+ label: m.git_sync_compose_path(),
+ getValue: (item: GitOpsSync) => item.composePath,
+ icon: FolderIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility.composePath ?? true
+ }
+ ]}
+ rowActions={RowActions}
+ />
+{/snippet}
+
+{#snippet RowActions({ item, row }: { item: GitOpsSync; row?: Row<GitOpsSync> })}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">{m.common_open_menu()}</span>
+ <EllipsisIcon />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => handlePerformSync(item.id, item.name)} disabled={isLoading.syncing}>
+ <PlayIcon class="size-4" />
+ {m.git_sync_perform()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onEditSync(item)}>
+ <PencilIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleDeleteOne(item.id, item.name)}
+ disabled={isLoading.removing}
+ >
+ <Trash2Icon class="size-4" />
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+{/snippet}
+
+<ArcaneTable
+ persistKey="arcane-gitops-syncs-table"
+ items={syncs}
+ bind:requestOptions
+ bind:selectedIds
+ bind:mobileFieldVisibility
+ onRemoveSelected={(ids) => handleDeleteSelected(ids)}
+ onRefresh={async (options) => (syncs = await gitOpsSyncService.getSyncs(environmentId, options))}
+ {columns}
+ {mobileFields}
+ rowActions={RowActions}
+ mobileCard={SyncMobileCardSnippet}
+/>
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index a35efd8aa..523af73ea 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -3,8 +3,9 @@
import * as Tabs from '$lib/components/ui/tabs/index.js';
import * as TreeView from '$lib/components/ui/tree-view/index.js';
import * as Card from '$lib/components/ui/card';
+ import * as Alert from '$lib/components/ui/alert/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { ArrowLeftIcon, ProjectsIcon, LayersIcon, SettingsIcon, FileTextIcon } from '$lib/icons';
+ import { ArrowLeftIcon, ProjectsIcon, LayersIcon, SettingsIcon, FileTextIcon, AlertIcon } from '$lib/icons';
import { type TabItem } from '$lib/components/tab-bar/index.js';
import TabbedPageLayout from '$lib/layouts/tabbed-page-layout.svelte';
import ActionButtons from '$lib/components/action-buttons.svelte';
@@ -26,6 +27,9 @@
import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
import { untrack } from 'svelte';
import { projectService } from '$lib/services/project-service';
+ import { gitOpsSyncService } from '$lib/services/gitops-sync-service';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { RefreshIcon } from '$lib/icons';
let { data } = $props();
let projectId = $derived(data.projectId);
@@ -41,9 +45,12 @@
redeploying: false,
destroying: false,
pulling: false,
- saving: false
+ saving: false,
+ syncing: false
});
+ const envId = $derived(environmentStore.selected?.id);
+
let originalName = $state(untrack(() => data.editorState.originalName));
let originalComposeContent = $state(untrack(() => data.editorState.originalComposeContent));
let originalEnvContent = $state(untrack(() => data.editorState.originalEnvContent || ''));
@@ -53,9 +60,9 @@
const formSchema = z.object({
name: z
.string()
- .min(1, 'Project name is required')
- .regex(/^[a-z0-9_-]+$/i, 'Only letters, numbers, hyphens, and underscores are allowed'),
- composeContent: z.string().min(1, 'Compose content is required'),
+ .min(1, m.compose_project_name_required())
+ .regex(/^[a-z0-9_-]+$/i, m.compose_project_name_invalid_with_underscores()),
+ composeContent: z.string().min(1, m.compose_compose_content_required()),
envContent: z.string().optional().default('')
});
@@ -74,7 +81,11 @@
JSON.stringify(includeFilesState) !== JSON.stringify(originalIncludeFiles)
);
- let canEditName = $derived(!isLoading.saving && project?.status !== 'running' && project?.status !== 'partially running');
+ let isGitOpsManaged = $derived(!!project?.gitOpsManagedBy);
+ let canEditName = $derived(
+ !isGitOpsManaged && !isLoading.saving && project?.status !== 'running' && project?.status !== 'partially running'
+ );
+ let canEditCompose = $derived(!isGitOpsManaged);
let autoScrollStackLogs = $state(true);
@@ -172,7 +183,7 @@
// First update the main project files
handleApiResultWithCallbacks({
result: await tryCatch(projectService.updateProject(projectId, name, composeContent, envContent)),
- message: 'Failed to Save Project',
+ message: m.common_save_failed(),
setLoadingState: (value) => (isLoading.saving = value),
onSuccess: async (updatedStack: Project) => {
// Then update any changed include files
@@ -182,13 +193,13 @@
projectService.updateProjectIncludeFile(projectId, relativePath, includeFilesState[relativePath])
);
if (includeResult.error) {
- toast.error(`Failed to update ${relativePath}: ${includeResult.error.message || 'Unknown error'}`);
+ toast.error(includeResult.error.message || m.common_update_failed({ resource: relativePath }));
return;
}
}
}
- toast.success('Project updated successfully!');
+ toast.success(m.common_update_success({ resource: m.project() }));
originalName = updatedStack.name;
originalComposeContent = $inputs.composeContent.value;
originalEnvContent = $inputs.envContent.value;
@@ -227,6 +238,20 @@
}
});
}
+
+ async function handleSyncFromGit() {
+ if (!envId || !project?.gitOpsManagedBy) return;
+ isLoading.syncing = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(gitOpsSyncService.performSync(envId, project.gitOpsManagedBy)),
+ message: m.git_sync_failed(),
+ setLoadingState: (value) => (isLoading.syncing = value),
+ onSuccess: async () => {
+ toast.success(m.git_sync_success());
+ await invalidateAll();
+ }
+ });
+ }
</script>
{#if project}
@@ -271,11 +296,31 @@
/>
{/if}
</div>
- {#if project.createdAt}
- <p class="text-muted-foreground mt-0.5 hidden text-xs sm:block">
- {m.common_created()}: {new Date(project.createdAt ?? '').toLocaleDateString()}
- </p>
- {/if}
+ <div class="mt-0.5 flex items-center gap-4">
+ {#if project.createdAt}
+ <p class="text-muted-foreground hidden text-xs sm:block">
+ {m.common_created()}: {new Date(project.createdAt ?? '').toLocaleDateString()}
+ </p>
+ {/if}
+ {#if project.lastSyncCommit}
+ <div class="text-muted-foreground flex items-center gap-1.5 text-xs">
+ <span class="hidden sm:inline">{m.git_sync_commit()}:</span>
+ {#if project.gitRepositoryURL}
+ <a
+ href="{project.gitRepositoryURL.replace(/\.git$/, '')}/commit/{project.lastSyncCommit}"
+ target="_blank"
+ class="hover:text-primary sm:bg-muted font-mono transition-colors sm:rounded sm:px-1.5 sm:py-0.5"
+ >
+ {project.lastSyncCommit}
+ </a>
+ {:else}
+ <span class="sm:bg-muted font-mono sm:rounded sm:px-1.5 sm:py-0.5">
+ {project.lastSyncCommit}
+ </span>
+ {/if}
+ </div>
+ {/if}
+ </div>
{/snippet}
{#snippet headerActions()}
@@ -326,6 +371,51 @@
<Tabs.Content value="compose" class="h-full min-h-0">
<div class="flex h-full min-h-0 flex-col">
+ {#if isGitOpsManaged}
+ <Alert.Root variant="default" class="mb-4">
+ <AlertIcon class="size-4" />
+ <div class="flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
+ <div class="flex-1">
+ <Alert.Title>{m.git_title()} {m.read_only_label()}</Alert.Title>
+ <Alert.Description>
+ {m.git_managed_readonly_alert()}
+ <br />
+ <div class="mt-2 flex flex-col gap-1">
+ {#if project.lastSyncCommit}
+ <div class="flex items-center gap-1.5 font-mono text-xs">
+ <span class="text-muted-foreground">{m.git_sync_commit()}:</span>
+ {#if project.gitRepositoryURL}
+ <a
+ href="{project.gitRepositoryURL.replace(/\.git$/, '')}/commit/{project.lastSyncCommit}"
+ target="_blank"
+ class="bg-muted hover:text-primary rounded px-1.5 py-0.5 transition-colors"
+ >
+ {project.lastSyncCommit}
+ </a>
+ {:else}
+ <span class="bg-muted rounded px-1.5 py-0.5">{project.lastSyncCommit}</span>
+ {/if}
+ </div>
+ {/if}
+ <span class="text-muted-foreground text-xs">
+ {m.git_managed_env_note()}
+ </span>
+ </div>
+ </Alert.Description>
+ </div>
+ <ArcaneButton
+ action="base"
+ tone="outline-primary"
+ loading={isLoading.syncing}
+ onclick={handleSyncFromGit}
+ icon={RefreshIcon}
+ customLabel={m.git_sync_from_git()}
+ loadingLabel={m.common_syncing()}
+ class="shrink-0"
+ />
+ </div>
+ </Alert.Root>
+ {/if}
<div class="mb-4 flex-shrink-0">
<SwitchWithLabel
id="layout-mode-toggle"
@@ -375,8 +465,8 @@
</TreeView.File>
{#if project?.includeFiles && project.includeFiles.length > 0}
- <TreeView.Folder name="Includes">
- {#each project.includeFiles as includeFile}
+ <TreeView.Folder name={m.project_includes()}>
+ {#each project.includeFiles as includeFile (includeFile.relativePath)}
<TreeView.File
name={includeFile.relativePath}
onclick={() => (selectedFile = includeFile.relativePath)}
@@ -401,6 +491,7 @@
language="yaml"
bind:value={$inputs.composeContent.value}
error={$inputs.composeContent.error ?? undefined}
+ readOnly={!canEditCompose}
/>
{:else if selectedFile === 'env'}
<CodePanel
@@ -429,7 +520,7 @@
{#if project?.includeFiles && project.includeFiles.length > 0}
<div class="border-border bg-card rounded-lg border">
<div class="border-border scrollbar-hide flex gap-2 overflow-x-auto border-b p-2">
- {#each project.includeFiles as includeFile}
+ {#each project.includeFiles as includeFile (includeFile.relativePath)}
<ArcaneButton
action="base"
tone={selectedIncludeTab === includeFile.relativePath ? 'outline-primary' : 'ghost'}
@@ -467,6 +558,7 @@
language="yaml"
bind:value={$inputs.composeContent.value}
error={$inputs.composeContent.error ?? undefined}
+ readOnly={!canEditCompose}
/>
</div>
@@ -491,7 +583,7 @@
{#if project.status == 'running'}
<ProjectsLogsPanel projectId={project.id} bind:autoScroll={autoScrollStackLogs} />
{:else}
- <div class="text-muted-foreground py-12 text-center">{m.compose_logs_title()} Unavailable</div>
+ <div class="text-muted-foreground py-12 text-center">{m.compose_logs_title()} {m.common_disabled()}</div>
{/if}
</Tabs.Content>
{/snippet}
@@ -503,7 +595,7 @@
<ProjectsIcon class="text-muted-foreground size-10" />
</div>
<h2 class="mb-3 text-2xl font-medium">
- {data.error ? 'Error Loading Project' : m.common_not_found_title({ resource: m.project() })}
+ {data.error ? m.common_action_failed() : m.common_not_found_title({ resource: m.project() })}
</h2>
<p class="text-muted-foreground mb-8 max-w-md text-center">
{data.error || m.common_not_found_description({ resource: m.project().toLowerCase() })}
diff --git a/frontend/src/routes/(app)/projects/components/CodePanel.svelte b/frontend/src/routes/(app)/projects/components/CodePanel.svelte
index 5b92b92ae..c092ebde3 100644
--- a/frontend/src/routes/(app)/projects/components/CodePanel.svelte
+++ b/frontend/src/routes/(app)/projects/components/CodePanel.svelte
@@ -12,7 +12,8 @@
language,
value = $bindable(),
error,
- autoHeight = false
+ autoHeight = false,
+ readOnly = false
}: {
title: string;
open: boolean;
@@ -20,6 +21,7 @@
value: string;
error?: string;
autoHeight?: boolean;
+ readOnly?: boolean;
} = $props();
const isMobile = new IsMobile();
@@ -35,10 +37,10 @@
<Card.Content class="relative z-0 flex min-h-0 {effectiveAutoHeight ? '' : 'flex-1'} flex-col overflow-visible p-0">
<div class="{effectiveAutoHeight ? '' : 'relative flex-1'} min-h-0 w-full min-w-0">
{#if effectiveAutoHeight}
- <CodeEditor bind:value {language} fontSize="13px" autoHeight={true} />
+ <CodeEditor bind:value {language} fontSize="13px" autoHeight={true} {readOnly} />
{:else}
<div class="absolute inset-0">
- <CodeEditor bind:value {language} fontSize="13px" />
+ <CodeEditor bind:value {language} fontSize="13px" {readOnly} />
</div>
{/if}
</div>
diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelte
index 8da625e1d..d79916d5d 100644
--- a/frontend/src/routes/(app)/projects/new/+page.svelte
+++ b/frontend/src/routes/(app)/projects/new/+page.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { ArrowLeftIcon, TerminalIcon, CopyIcon, InfoIcon, TemplateIcon, AddIcon } from '$lib/icons';
+ import { ArrowLeftIcon, TerminalIcon, CopyIcon, InfoIcon, TemplateIcon, AddIcon, GitBranchIcon } from '$lib/icons';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { Label } from '$lib/components/ui/label/index.js';
import { goto, invalidateAll } from '$app/navigation';
@@ -24,6 +24,7 @@
import { ArrowDownIcon as ChevronDown } from '$lib/icons';
import CodePanel from '../components/CodePanel.svelte';
import EditableName from '../components/EditableName.svelte';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
let { data } = $props();
@@ -251,6 +252,14 @@
<TerminalIcon class="size-4" />
{m.compose_convert_from_docker_run()}
</DropdownMenu.Item>
+ <DropdownMenu.Item
+ class={dropdownItemClass}
+ onclick={async () =>
+ goto(`/environments/${await environmentStore.getCurrentEnvironmentId()}/gitops?action=create`)}
+ >
+ <GitBranchIcon class="size-4" />
+ {m.git_from_git_repo()}
+ </DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item
class={dropdownItemClass}
diff --git a/frontend/src/routes/(app)/projects/projects-table.svelte b/frontend/src/routes/(app)/projects/projects-table.svelte
index 5639f994a..6a4aee38d 100644
--- a/frontend/src/routes/(app)/projects/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/projects-table.svelte
@@ -19,7 +19,9 @@
import { UniversalMobileCard } from '$lib/components/arcane-table';
import { m } from '$lib/paraglide/messages';
import { projectService } from '$lib/services/project-service';
- import { FolderOpenIcon, LayersIcon, CalendarIcon } from '$lib/icons';
+ import { gitOpsSyncService } from '$lib/services/gitops-sync-service';
+ import { FolderOpenIcon, LayersIcon, CalendarIcon, ProjectsIcon, GitBranchIcon, RefreshIcon } from '$lib/icons';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
let {
projects = $bindable(),
@@ -38,7 +40,8 @@
remove: false,
destroy: false,
pull: false,
- updating: false
+ updating: false,
+ syncing: false
});
function getStatusTooltip(project: Project): string | undefined {
@@ -130,11 +133,27 @@
}
}
+ async function handleSyncFromGit(gitOpsSyncId: string) {
+ if (!envId) return;
+ isLoading.syncing = true;
+ const result = await tryCatch(gitOpsSyncService.performSync(envId, gitOpsSyncId));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.git_sync_failed(),
+ setLoadingState: (value) => (isLoading.syncing = value),
+ onSuccess: async () => {
+ toast.success(m.git_sync_success());
+ projects = await projectService.getProjects(requestOptions);
+ }
+ });
+ }
+
const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
const columns = [
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },
+ { accessorKey: 'gitOpsManagedBy', title: m.projects_col_provider(), cell: ProviderCell },
{ accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },
{ accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },
{ accessorKey: 'serviceCount', title: m.compose_services(), sortable: true }
@@ -142,18 +161,44 @@
const mobileFields = [
{ id: 'id', label: m.common_id(), defaultVisible: false },
+ { id: 'provider', label: m.projects_col_provider(), defaultVisible: true },
{ id: 'status', label: m.common_status(), defaultVisible: true },
{ id: 'serviceCount', label: m.compose_services(), defaultVisible: true },
{ id: 'createdAt', label: m.common_created(), defaultVisible: true }
];
let mobileFieldVisibility = $state<Record<string, boolean>>({});
+ const envId = $derived(environmentStore.selected?.id);
</script>
{#snippet NameCell({ item }: { item: Project })}
- <a class="font-medium hover:underline" href="/projects/{item.id}">
- {item.name}
- </a>
+ <div class="flex items-center gap-2">
+ <a class="font-medium hover:underline" href="/projects/{item.id}">
+ {item.name}
+ </a>
+ </div>
+{/snippet}
+
+{#snippet ProviderCell({ item }: { item: Project })}
+ <div class="flex items-center gap-2">
+ {#if item.gitOpsManagedBy}
+ <GitBranchIcon class="size-4" />
+ <a class="font-medium hover:underline" href="/environments/{envId}/gitops">
+ {m.projects_provider_git()}
+ </a>
+ {:else}
+ <ProjectsIcon class="size-4" />
+ <span>{m.projects_provider_local()}</span>
+ {/if}
+ </div>
+{/snippet}
+
+{#snippet ProviderField(value: { icon: any; text: string })}
+ {@const Icon = value.icon}
+ <span class="inline-flex items-center gap-2">
+ <Icon class="size-3" />
+ <span>{value.text}</span>
+ </span>
{/snippet}
{#snippet StatusCell({ item }: { item: Project })}
@@ -196,6 +241,16 @@
: null
]}
fields={[
+ {
+ label: m.projects_col_provider(),
+ type: 'component',
+ getValue: (item: Project) => ({
+ icon: item.gitOpsManagedBy ? GitBranchIcon : ProjectsIcon,
+ text: item.gitOpsManagedBy ? m.projects_provider_git() : m.projects_provider_local()
+ }),
+ component: ProviderField,
+ show: mobileFieldVisibility.provider ?? true
+ },
{
label: m.compose_services(),
getValue: (item: Project) => {
@@ -242,6 +297,20 @@
{m.common_edit()}
</DropdownMenu.Item>
+ {#if item.gitOpsManagedBy}
+ <DropdownMenu.Item
+ onclick={() => handleSyncFromGit(item.gitOpsManagedBy!)}
+ disabled={isLoading.syncing || isAnyLoading}
+ >
+ {#if isLoading.syncing}
+ <Spinner class="size-4" />
+ {:else}
+ <RefreshIcon class="size-4" />
+ {/if}
+ {m.git_sync_from_git()}
+ </DropdownMenu.Item>
+ {/if}
+
{#if item.status !== 'running'}
<DropdownMenu.Item onclick={() => performProjectAction('start', item.id)} disabled={isLoading.start || isAnyLoading}>
{#if isLoading.start}
diff --git a/go.work.sum b/go.work.sum
index 8e54c256c..f61bcdfe9 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -18,8 +18,6 @@ cloud.google.com/go/spanner v1.85.0 h1:VVO3yW+0+Yx9tg4SQaZvJHGAnU6qCnGXQ3NX4E3+s
cloud.google.com/go/spanner v1.85.0/go.mod h1:9zhmtOEoYV06nE4Orbin0dc/ugHzZW9yXuvaM61rpxs=
cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI=
cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU=
-dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
-dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs=
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4=
github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o=
@@ -59,8 +57,6 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapp
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/Microsoft/go-winio v0.4.21/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84=
-github.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBiRGFrw=
-github.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow=
@@ -132,6 +128,8 @@ github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkN
github.com/bits-and-blooms/bitset v1.24.3 h1:Bte86SlO3lwPQqww+7BE9ZuUCKIjfqnG5jtEyqA9y9Y=
github.com/bits-and-blooms/bitset v1.24.3/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
+github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw=
+github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/checkpoint-restore/checkpointctl v1.4.0 h1:3kRns56TArwiyHOMakaumUgSZZlB1hZBkjVgR6IeZ3E=
@@ -188,8 +186,6 @@ github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3
github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/cyberphone/json-canonicalization v0.0.0-20241213102144-19d51d7fe467 h1:uX1JmpONuD549D73r6cgnxyUu18Zb7yHAy5AYU0Pm4Q=
github.com/cyberphone/json-canonicalization v0.0.0-20241213102144-19d51d7fe467/go.mod h1:uzvlm1mxhHkdfqitSA92i7Se+S9ksOn3a3qmv/kyOCw=
-github.com/cyphar/filepath-securejoin v0.4.1 h1:JyxxyPEaktOD+GAnqIqTf9A8tHyAG22rowi7HkoSU1s=
-github.com/cyphar/filepath-securejoin v0.4.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI=
github.com/cznic/mathutil v0.0.0-20180504122225-ca4c9f2c1369 h1:XNT/Zf5l++1Pyg08/HV04ppB0gKxAqtZQBRYiYrUuYk=
github.com/cznic/mathutil v0.0.0-20180504122225-ca4c9f2c1369/go.mod h1:e6NPNENfs9mPDVNRekM7lKScauxd5kXTr1Mfyig6TDM=
github.com/danielgtaylor/mexpr v1.9.1 h1:nA9bsGRmNlJeVCPFgGf7WhrLuKag/+iWfOaJ03iKFPI=
@@ -201,6 +197,8 @@ github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7
github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73 h1:OGNva6WhsKst5OZf7eZOklDztV3hwtTHovdrLHV+MsA=
github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi/U=
github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE=
+github.com/docker/cli-docs-tool v0.10.0/go.mod h1:5EM5zPnT2E7yCLERZmrDA234Vwn09fzRHP4aX1qwp1U=
+github.com/docker/compose/v5 v5.0.0/go.mod h1:BurapGv8zmYnsbSmlpCz5EU2Pi3YFV/PjeUnoFpcw64=
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ+oDZB4KHQFypsfjYlq/C4rfL7D3g8=
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=
github.com/dvsekhvalnov/jose2go v1.7.0 h1:bnQc8+GMnidJZA8zc6lLEAb4xNrIqHwO+9TzqvtQZPo=
@@ -247,6 +245,7 @@ github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/gobuffalo/here v0.6.0 h1:hYrd0a6gDmWxBM4TnrGw8mQg24iSVoIkHEk7FodQcBI=
github.com/gobuffalo/here v0.6.0/go.mod h1:wAG085dHOYqUpf+Ap+WOdrPTp5IYcDAs/x7PLa8Y5fM=
+github.com/goccy/go-yaml v1.19.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gocql/gocql v0.0.0-20210515062232-b7ef815b4556 h1:N/MD/sr6o61X+iZBAT2qEUF023s4KbA8RWfKzl0L6MQ=
github.com/gocql/gocql v0.0.0-20210515062232-b7ef815b4556/go.mod h1:DL0ekTmBSTdlNF25Orwt/JMzqIq3EJ4MVa/J/uK64OY=
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0=
@@ -378,6 +377,7 @@ github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYt
github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg=
github.com/markbates/pkger v0.15.1 h1:3MPelV53RnGSW07izx5xGxl4e/sdRD6zqseIk0rMASY=
github.com/markbates/pkger v0.15.1/go.mod h1:0JoVlrol20BSywW79rN3kdFFsE5xYM+rSCQDXbLhiuI=
+github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
@@ -397,6 +397,7 @@ github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
+github.com/moby/buildkit v0.26.2/go.mod h1:ylDa7IqzVJgLdi/wO7H1qLREFQpmhFbw2fbn4yoTw40=
github.com/moby/policy-helpers v0.0.0-20251105011237-bcaa71c99f14 h1:JO22uXMy3CN7wh7A/wrtYQWV1WYQMg2gh6d8YO325k4=
github.com/moby/policy-helpers v0.0.0-20251105011237-bcaa71c99f14/go.mod h1:HJfK0E8dR+Jpk5anJ3oADg2dRSom1gJK17sqEiiMS7w=
github.com/moby/profiles/seccomp v0.1.0 h1:kVf1lc5ytNB1XPxEdZUVF+oPpbBYJHR50eEvPt/9k8A=
@@ -407,6 +408,7 @@ github.com/moby/sys/mount v0.3.4 h1:yn5jq4STPztkkzSKpZkLcmjue+bZJ0u2AuQY1iNI1Ww=
github.com/moby/sys/mount v0.3.4/go.mod h1:KcQJMbQdJHPlq5lcYT+/CjatWM4PuxKe+XLSVS4J6Os=
github.com/moby/sys/reexec v0.1.0 h1:RrBi8e0EBTLEgfruBOFcxtElzRGTEUkeIFaVXgU7wok=
github.com/moby/sys/reexec v0.1.0/go.mod h1:EqjBg8F3X7iZe5pU6nRZnYCMUTXoxsjiIfHup5wYIN8=
+github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs=
github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns=
github.com/mutecomm/go-sqlcipher/v4 v4.4.0 h1:sV1tWCWGAVlPhNGT95Q+z/txFxuhAYWwHD1afF5bMZg=
@@ -420,6 +422,7 @@ github.com/nakagami/firebirdsql v0.0.0-20190310045651-3c02a58cfed8/go.mod h1:86w
github.com/neo4j/neo4j-go-driver v1.8.1-0.20200803113522-b626aa943eba h1:fhFP5RliM2HW/8XdcO5QngSfFli9GcRIpMXvypTQt6E=
github.com/neo4j/neo4j-go-driver v1.8.1-0.20200803113522-b626aa943eba/go.mod h1:ncO5VaFWh0Nrt+4KT4mOZboaczBZcLuHrG+/sUeP8gI=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
+github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/gomega v1.15.0 h1:WjP/FQ/sk43MRmnEcT+MlDw2TFvkrXlprrPST/IudjU=
@@ -457,12 +460,14 @@ github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPO
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU=
github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U=
+github.com/schollz/progressbar/v3 v3.18.0 h1:uXdoHABRFmNIjUfte/Ex7WtuyVslrw2wVPQmCN62HpA=
+github.com/schollz/progressbar/v3 v3.18.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c=
github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=
-github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8=
-github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/serialx/hashring v0.0.0-20200727003509-22c0c7ab6b1b h1:h+3JX2VoWTFuyQEo87pStk/a99dzIO1mM9KxIyLPGTU=
github.com/serialx/hashring v0.0.0-20200727003509-22c0c7ab6b1b/go.mod h1:/yeG0My1xr/u+HZrFQ1tOQQQQrOawfyMUH13ai5brBc=
+github.com/shirou/gopsutil/v4 v4.25.11 h1:X53gB7muL9Gnwwo2evPSE+SfOrltMoR6V3xJAXZILTY=
+github.com/shirou/gopsutil/v4 v4.25.11/go.mod h1:EivAfP5x2EhLp2ovdpKSozecVXn1TmuG7SMzs/Wh4PU=
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/sigstore/fulcio v1.7.1 h1:RcoW20Nz49IGeZyu3y9QYhyyV3ZKQ85T+FXPKkvE+aQ=
@@ -471,7 +476,6 @@ github.com/sigstore/protobuf-specs v0.4.1 h1:5SsMqZbdkcO/DNHudaxuCUEjj6x29tS2Xby
github.com/sigstore/protobuf-specs v0.4.1/go.mod h1:+gXR+38nIa2oEupqDdzg4qSBT0Os+sP7oYv6alWewWc=
github.com/sigstore/sigstore v1.9.5 h1:Wm1LT9yF4LhQdEMy5A2JeGRHTrAWGjT3ubE5JUSrGVU=
github.com/sigstore/sigstore v1.9.5/go.mod h1:VtxgvGqCmEZN9X2zhFSOkfXxvKUjpy8RpUW39oCtoII=
-github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/smallstep/pkcs7 v0.1.1 h1:x+rPdt2W088V9Vkjho4KtoggyktZJlMduZAtRHm68LU=
github.com/smallstep/pkcs7 v0.1.1/go.mod h1:dL6j5AIz9GHjVEBTXtW+QliALcgM19RtXaTeyxI+AfA=
github.com/snowflakedb/gosnowflake v1.6.19 h1:KSHXrQ5o7uso25hNIzi/RObXtnSGkFgie91X82KcvMY=
@@ -556,23 +560,28 @@ go.opentelemetry.io/otel/exporters/prometheus v0.42.0/go.mod h1:f3bYiqNqhoPxkvI2
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0 h1:UGZ1QwZWY67Z6BmckTU+9Rxn04m2bD3gD6Mk0OIOCPk=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0/go.mod h1:fcwWuDuaObkkChiDlhEpSq9+X1C0omv+s5mBtToAQ64=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
+golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
+golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo=
golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8 h1:LvzTn0GQhWuvKH/kVRS3R3bVAsdQWI7hvfLHGgh9+lU=
golang.org/x/telemetry v0.0.0-20251008203120-078029d740a8/go.mod h1:Pi4ztBfryZoJEkyFTI5/Ocsu2jXyDr6iSdgJiYE/uwE=
+golang.org/x/telemetry v0.0.0-20251111182119-bc8e575c7b54/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
@@ -657,6 +666,7 @@ sigs.k8s.io/structured-merge-diff/v6 v6.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/
sigs.k8s.io/structured-merge-diff/v6 v6.3.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE=
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
+tags.cncf.io/container-device-interface v1.0.1/go.mod h1:JojJIOeW3hNbcnOH2q0NrWNha/JuHoDZcmYxAZwb2i0=
tags.cncf.io/container-device-interface/specs-go v1.0.0 h1:8gLw29hH1ZQP9K1YtAzpvkHCjjyIxHZYzBAvlQ+0vD8=
tags.cncf.io/container-device-interface/specs-go v1.0.0/go.mod h1:u86hoFWqnh3hWz3esofRFKbI261bUlvUfLKGrDhJkgQ=
tags.cncf.io/container-device-interface/specs-go v1.1.0 h1:QRZVeAceQM+zTZe12eyfuJuuzp524EKYwhmvLd+h+yQ=
diff --git a/package.json b/package.json
index a08753a5d..16ac82d83 100644
--- a/package.json
+++ b/package.json
@@ -14,10 +14,8 @@
"preinstall": "npx only-allow pnpm",
"dev": "pnpm --filter arcane-frontend dev",
"build": "pnpm --filter arcane-frontend build",
- "test:up": "docker compose -f tests/setup/compose.yaml up -d --build",
- "test:down": "docker compose -f tests/setup/compose.yaml down",
"test": "pnpm --filter arcane-tests test",
- "format": "pnpm --filter arcane-frontend format",
+ "format": "pnpm --filter arcane-frontend format && gofmt -w -s .",
"check": "pnpm --filter arcane-frontend check",
"knip": "pnpm --filter arcane-frontend knip"
},
diff --git a/types/gitops/gitops.go b/types/gitops/gitops.go
new file mode 100644
index 000000000..3fe278a9c
--- /dev/null
+++ b/types/gitops/gitops.go
@@ -0,0 +1,586 @@
+package gitops
+
+import "time"
+
+// GitRepository represents a reusable Git repository with credentials.
+type GitRepository struct {
+ // ID of the git repository.
+ //
+ // Required: true
+ ID string `json:"id"`
+
+ // Name of the git repository.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // URL of the git repository.
+ //
+ // Required: true
+ URL string `json:"url"`
+
+ // AuthType specifies the authentication method (none, http, ssh).
+ //
+ // Required: true
+ AuthType string `json:"authType"`
+
+ // Username for HTTP authentication.
+ //
+ // Required: false
+ Username string `json:"username,omitempty"`
+
+ // Description of the git repository.
+ //
+ // Required: false
+ Description *string `json:"description,omitempty"`
+
+ // Enabled indicates if the repository is enabled.
+ //
+ // Required: true
+ Enabled bool `json:"enabled"`
+
+ // CreatedAt is the date and time at which the repository was created.
+ //
+ // Required: true
+ CreatedAt time.Time `json:"createdAt"`
+
+ // UpdatedAt is the date and time at which the repository was last updated.
+ //
+ // Required: true
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+// GitOpsSync represents a GitOps sync configuration.
+type GitOpsSync struct {
+ // ID of the gitops sync.
+ //
+ // Required: true
+ ID string `json:"id"`
+
+ // Name of the sync configuration.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // EnvironmentID is the ID of the environment this sync belongs to.
+ //
+ // Required: true
+ EnvironmentID string `json:"environmentId"`
+
+ // RepositoryID is the ID of the git repository to sync from.
+ //
+ // Required: true
+ RepositoryID string `json:"repositoryId"`
+
+ // Repository is the associated git repository.
+ //
+ // Required: false
+ Repository *GitRepository `json:"repository,omitempty"`
+
+ // Branch to sync from.
+ //
+ // Required: true
+ Branch string `json:"branch"`
+
+ // ComposePath is the path to the docker-compose file in the repository.
+ //
+ // Required: true
+ ComposePath string `json:"composePath"`
+
+ // ProjectName is the name used to create/identify the project.
+ //
+ // Required: true
+ ProjectName string `json:"projectName"`
+
+ // ProjectID is the ID of the linked project (set after first sync).
+ //
+ // Required: false
+ ProjectID *string `json:"projectId,omitempty"`
+
+ // AutoSync indicates if the sync should run automatically.
+ //
+ // Required: true
+ AutoSync bool `json:"autoSync"`
+
+ // SyncInterval is the interval in minutes between automatic syncs.
+ //
+ // Required: true
+ SyncInterval int `json:"syncInterval"`
+
+ // LastSyncAt is the date and time of the last successful sync.
+ //
+ // Required: false
+ LastSyncAt *time.Time `json:"lastSyncAt,omitempty"`
+
+ // LastSyncStatus is the status of the last sync attempt.
+ //
+ // Required: false
+ LastSyncStatus *string `json:"lastSyncStatus,omitempty"`
+
+ // LastSyncError is the error message from the last sync attempt if it failed.
+ //
+ // Required: false
+ LastSyncError *string `json:"lastSyncError,omitempty"`
+
+ // LastSyncCommit is the commit hash from the last successful sync.
+ //
+ // Required: false
+ LastSyncCommit *string `json:"lastSyncCommit,omitempty"`
+
+ // Enabled indicates if the sync is enabled.
+ //
+ // Required: true
+ Enabled bool `json:"enabled"`
+
+ // CreatedAt is the date and time at which the sync was created.
+ //
+ // Required: true
+ CreatedAt time.Time `json:"createdAt"`
+
+ // UpdatedAt is the date and time at which the sync was last updated.
+ //
+ // Required: true
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+// CreateRepositoryRequest represents the request to create a git repository.
+type CreateRepositoryRequest struct {
+ // Name of the git repository.
+ //
+ // Required: true
+ Name string `json:"name" binding:"required"`
+
+ // URL of the git repository.
+ //
+ // Required: true
+ URL string `json:"url" binding:"required"`
+
+ // AuthType specifies the authentication method (none, http, ssh).
+ //
+ // Required: true
+ AuthType string `json:"authType" binding:"required"`
+
+ // Username for HTTP authentication.
+ //
+ // Required: false
+ Username string `json:"username,omitempty"`
+
+ // Token for HTTP authentication.
+ //
+ // Required: false
+ Token string `json:"token,omitempty"`
+
+ // SSHKey for SSH authentication.
+ //
+ // Required: false
+ SSHKey string `json:"sshKey,omitempty"`
+
+ // Description of the git repository.
+ //
+ // Required: false
+ Description *string `json:"description,omitempty"`
+
+ // Enabled indicates if the repository is enabled.
+ //
+ // Required: false
+ Enabled *bool `json:"enabled,omitempty"`
+}
+
+// UpdateRepositoryRequest represents the request to update a git repository.
+type UpdateRepositoryRequest struct {
+ // Name of the git repository.
+ //
+ // Required: false
+ Name *string `json:"name,omitempty"`
+
+ // URL of the git repository.
+ //
+ // Required: false
+ URL *string `json:"url,omitempty"`
+
+ // AuthType specifies the authentication method (none, http, ssh).
+ //
+ // Required: false
+ AuthType *string `json:"authType,omitempty"`
+
+ // Username for HTTP authentication.
+ //
+ // Required: false
+ Username *string `json:"username,omitempty"`
+
+ // Token for HTTP authentication.
+ //
+ // Required: false
+ Token *string `json:"token,omitempty"`
+
+ // SSHKey for SSH authentication.
+ //
+ // Required: false
+ SSHKey *string `json:"sshKey,omitempty"`
+
+ // Description of the git repository.
+ //
+ // Required: false
+ Description *string `json:"description,omitempty"`
+
+ // Enabled indicates if the repository is enabled.
+ //
+ // Required: false
+ Enabled *bool `json:"enabled,omitempty"`
+}
+
+// CreateSyncRequest represents the request to create a gitops sync.
+type CreateSyncRequest struct {
+ // Name of the sync configuration.
+ //
+ // Required: true
+ Name string `json:"name" binding:"required"`
+
+ // RepositoryID is the ID of the git repository to sync from.
+ //
+ // Required: true
+ RepositoryID string `json:"repositoryId" binding:"required"`
+
+ // Branch to sync from.
+ //
+ // Required: true
+ Branch string `json:"branch" binding:"required"`
+
+ // ComposePath is the path to the docker-compose file in the repository.
+ //
+ // Required: true
+ ComposePath string `json:"composePath" binding:"required"`
+
+ // ProjectName is the name of the project to create/update.
+ // The actual project will be created on first sync, and ProjectID will be set then.
+ // If not provided, defaults to the sync name.
+ //
+ // Required: false
+ ProjectName string `json:"projectName,omitempty"`
+
+ // AutoSync indicates if the sync should run automatically.
+ //
+ // Required: false
+ AutoSync *bool `json:"autoSync,omitempty"`
+
+ // SyncInterval is the interval in minutes between automatic syncs.
+ //
+ // Required: false
+ SyncInterval *int `json:"syncInterval,omitempty"`
+
+ // Enabled indicates if the sync is enabled.
+ //
+ // Required: false
+ Enabled *bool `json:"enabled,omitempty"`
+}
+
+// UpdateSyncRequest represents the request to update a gitops sync.
+type UpdateSyncRequest struct {
+ // Name of the sync configuration.
+ //
+ // Required: false
+ Name *string `json:"name,omitempty"`
+
+ // RepositoryID is the ID of the git repository to sync from.
+ //
+ // Required: false
+ RepositoryID *string `json:"repositoryId,omitempty"`
+
+ // Branch to sync from.
+ //
+ // Required: false
+ Branch *string `json:"branch,omitempty"`
+
+ // ComposePath is the path to the docker-compose file in the repository.
+ //
+ // Required: false
+ ComposePath *string `json:"composePath,omitempty"`
+
+ // ProjectName is the name of the project to create/update.
+ //
+ // Required: false
+ ProjectName *string `json:"projectName,omitempty"`
+
+ // AutoSync indicates if the sync should run automatically.
+ //
+ // Required: false
+ AutoSync *bool `json:"autoSync,omitempty"`
+
+ // SyncInterval is the interval in minutes between automatic syncs.
+ //
+ // Required: false
+ SyncInterval *int `json:"syncInterval,omitempty"`
+
+ // Enabled indicates if the sync is enabled.
+ //
+ // Required: false
+ Enabled *bool `json:"enabled,omitempty"`
+}
+
+// SyncResult represents the result of a sync operation.
+type SyncResult struct {
+ // Success indicates if the sync was successful.
+ //
+ // Required: true
+ Success bool `json:"success"`
+
+ // Message contains a human-readable message about the sync result.
+ //
+ // Required: true
+ Message string `json:"message"`
+
+ // Error contains error details if the sync failed.
+ //
+ // Required: false
+ Error *string `json:"error,omitempty"`
+
+ // SyncedAt is the timestamp of the sync.
+ //
+ // Required: true
+ SyncedAt time.Time `json:"syncedAt"`
+}
+
+// FileTreeNodeType represents the type of a file tree node.
+type FileTreeNodeType string
+
+const (
+ // FileTreeNodeTypeFile represents a file node.
+ FileTreeNodeTypeFile FileTreeNodeType = "file"
+ // FileTreeNodeTypeDirectory represents a directory node.
+ FileTreeNodeTypeDirectory FileTreeNodeType = "directory"
+)
+
+// FileTreeNode represents a file or directory in the repository.
+type FileTreeNode struct {
+ // Name of the file or directory.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // Path is the full path of the file or directory.
+ //
+ // Required: true
+ Path string `json:"path"`
+
+ // Type indicates if this is a file or directory (use FileTreeNodeTypeFile or FileTreeNodeTypeDirectory).
+ //
+ // Required: true
+ Type FileTreeNodeType `json:"type"`
+
+ // Size of the file in bytes (0 for directories).
+ //
+ // Required: false
+ Size int64 `json:"size,omitempty"`
+
+ // Children contains child nodes for directories.
+ //
+ // Required: false
+ Children []FileTreeNode `json:"children,omitempty"`
+}
+
+// BrowseRequest represents a request to browse repository files.
+type BrowseRequest struct {
+ // Path to browse in the repository.
+ //
+ // Required: false
+ Path string `json:"path,omitempty"`
+}
+
+// BrowseResponse represents the response for browsing repository files.
+type BrowseResponse struct {
+ // Path that was browsed.
+ //
+ // Required: true
+ Path string `json:"path"`
+
+ // Files and directories at the path.
+ //
+ // Required: true
+ Files []FileTreeNode `json:"files"`
+}
+
+// BranchInfo represents information about a git branch.
+type BranchInfo struct {
+ // Name of the branch.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // IsDefault indicates if this is the default branch.
+ //
+ // Required: true
+ IsDefault bool `json:"isDefault"`
+}
+
+// BranchesResponse represents the response for listing repository branches.
+type BranchesResponse struct {
+ // Branches available in the repository.
+ //
+ // Required: true
+ Branches []BranchInfo `json:"branches"`
+}
+
+// RepositorySync represents a git repository for syncing to remote environments.
+type RepositorySync struct {
+ // ID of the git repository.
+ //
+ // Required: true
+ ID string `json:"id" binding:"required"`
+
+ // Name of the git repository.
+ //
+ // Required: true
+ Name string `json:"name" binding:"required"`
+
+ // URL of the git repository.
+ //
+ // Required: true
+ URL string `json:"url" binding:"required"`
+
+ // AuthType specifies the authentication method (none, http, ssh).
+ //
+ // Required: true
+ AuthType string `json:"authType" binding:"required"`
+
+ // Username for HTTP authentication.
+ //
+ // Required: false
+ Username string `json:"username,omitempty"`
+
+ // Token for HTTP authentication (decrypted).
+ //
+ // Required: false
+ Token string `json:"token,omitempty"`
+
+ // SSHKey for SSH authentication (decrypted).
+ //
+ // Required: false
+ SSHKey string `json:"sshKey,omitempty"`
+
+ // Description of the git repository.
+ //
+ // Required: false
+ Description *string `json:"description,omitempty"`
+
+ // Enabled indicates if the repository is enabled.
+ //
+ // Required: true
+ Enabled bool `json:"enabled"`
+
+ // CreatedAt is the date and time at which the repository was created.
+ //
+ // Required: true
+ CreatedAt time.Time `json:"createdAt"`
+
+ // UpdatedAt is the date and time at which the repository was last updated.
+ //
+ // Required: true
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+// RepositorySyncRequest represents a request to sync git repositories to an agent.
+type RepositorySyncRequest struct {
+ // Repositories is a list of git repositories to sync.
+ //
+ // Required: true
+ Repositories []RepositorySync `json:"repositories" binding:"required"`
+}
+
+// SyncStatus represents the current status of a sync configuration.
+type SyncStatus struct {
+ // ID of the sync configuration.
+ //
+ // Required: true
+ ID string `json:"id"`
+
+ // Enabled indicates if the sync is enabled.
+ //
+ // Required: true
+ Enabled bool `json:"enabled"`
+
+ // AutoSync indicates if automatic sync is enabled.
+ //
+ // Required: true
+ AutoSync bool `json:"autoSync"`
+
+ // NextSyncAt is the estimated time of the next automatic sync.
+ //
+ // Required: false
+ NextSyncAt *time.Time `json:"nextSyncAt,omitempty"`
+
+ // LastSyncAt is the time of the last sync.
+ //
+ // Required: false
+ LastSyncAt *time.Time `json:"lastSyncAt,omitempty"`
+
+ // LastSyncStatus is the status of the last sync.
+ //
+ // Required: false
+ LastSyncStatus *string `json:"lastSyncStatus,omitempty"`
+
+ // LastSyncError is the error from the last sync if it failed.
+ //
+ // Required: false
+ LastSyncError *string `json:"lastSyncError,omitempty"`
+
+ // LastSyncCommit is the commit hash from the last successful sync.
+ //
+ // Required: false
+ LastSyncCommit *string `json:"lastSyncCommit,omitempty"`
+}
+
+// ImportGitOpsSyncRequest represents the request to import gitops syncs.
+type ImportGitOpsSyncRequest struct {
+ // SyncName is the name of the sync configuration.
+ //
+ // Required: true
+ SyncName string `json:"syncName"`
+
+ // GitRepo is the repository identifier or URL.
+ //
+ // Required: true
+ GitRepo string `json:"gitRepo"`
+
+ // Branch to sync from.
+ //
+ // Required: true
+ Branch string `json:"branch"`
+
+ // DockerComposePath is the path to the docker-compose file.
+ //
+ // Required: true
+ DockerComposePath string `json:"dockerComposePath"`
+
+ // AutoSync indicates if the sync should run automatically.
+ //
+ // Required: true
+ AutoSync bool `json:"autoSync"`
+
+ // SyncInterval is the interval in minutes between automatic syncs.
+ //
+ // Required: true
+ SyncInterval int `json:"syncInterval"`
+
+ // Enabled indicates if the sync is enabled.
+ //
+ // Required: true
+ Enabled bool `json:"enabled"`
+}
+
+// ImportGitOpsSyncResponse represents the response for importing gitops syncs.
+type ImportGitOpsSyncResponse struct {
+ // SuccessCount is the number of successfully imported syncs.
+ //
+ // Required: true
+ SuccessCount int `json:"successCount"`
+
+ // FailedCount is the number of failed imports.
+ //
+ // Required: true
+ FailedCount int `json:"failedCount"`
+
+ // Errors contains error messages for failed imports.
+ //
+ // Required: true
+ Errors []string `json:"errors"`
+}
diff --git a/types/project/project.go b/types/project/project.go
index 39216df69..df74e60ca 100644
--- a/types/project/project.go
+++ b/types/project/project.go
@@ -157,6 +157,11 @@ type CreateReponse struct {
// Required: true
RunningCount int `json:"runningCount"`
+ // GitOpsManagedBy is the ID of the GitOps sync managing this project (if any).
+ //
+ // Required: false
+ GitOpsManagedBy *string `json:"gitOpsManagedBy,omitempty"`
+
// CreatedAt is the date and time when the project was created.
//
// Required: true
@@ -244,6 +249,21 @@ type Details struct {
//
// Required: false
RuntimeServices []RuntimeService `json:"runtimeServices,omitempty"`
+
+ // GitOpsManagedBy is the ID of the GitOps sync managing this project (if any).
+ //
+ // Required: false
+ GitOpsManagedBy *string `json:"gitOpsManagedBy,omitempty"`
+
+ // LastSyncCommit is the last commit synced from Git (if GitOps managed).
+ //
+ // Required: false
+ LastSyncCommit *string `json:"lastSyncCommit,omitempty"`
+
+ // GitRepositoryURL is the URL of the Git repository (if GitOps managed).
+ //
+ // Required: false
+ GitRepositoryURL string `json:"gitRepositoryURL,omitempty"`
}
// Destroy is used to destroy a project.