Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(connections): GitLab/Gitea/Bitbucket repo pickers + path selector

Juan Denis03504c6517d2
diff --git a/backend/app/api/source_connections.py b/backend/app/api/source_connections.py
index 2b1588bf..347162b1 100644
--- a/backend/app/api/source_connections.py
+++ b/backend/app/api/source_connections.py
@@ -273,3 +273,135 @@ def _gitlab_error(exc):
return data.get('message') or data.get('error_description') or data.get('error') or str(exc)
except Exception:
return response.text or str(exc)
+
+
+@source_connections_bp.route('/bitbucket/status', methods=['GET'])
+@jwt_required()
+def bitbucket_status():
+ user_id = int(get_jwt_identity())
+ return jsonify(SourceConnectionService.get_bitbucket_status(user_id)), 200
+
+
+@source_connections_bp.route('/bitbucket/authorize', methods=['GET'])
+@jwt_required()
+def bitbucket_authorize():
+ redirect_uri = request.args.get('redirect_uri', '')
+ if not redirect_uri:
+ return jsonify({'error': 'redirect_uri is required'}), 400
+
+ try:
+ auth_url, state = SourceConnectionService.generate_bitbucket_authorize_url(redirect_uri)
+ return jsonify({'auth_url': auth_url, 'state': state}), 200
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 400
+
+
+@source_connections_bp.route('/bitbucket/callback', methods=['POST'])
+@jwt_required()
+def bitbucket_callback():
+ user_id = int(get_jwt_identity())
+ data = request.get_json() or {}
+ code = data.get('code', '')
+ state = data.get('state', '')
+ redirect_uri = data.get('redirect_uri', '')
+
+ if not code or not state or not redirect_uri:
+ return jsonify({'error': 'code, state, and redirect_uri are required'}), 400
+
+ try:
+ connection = SourceConnectionService.complete_bitbucket_callback(
+ user_id=user_id,
+ code=code,
+ state=state,
+ redirect_uri=redirect_uri,
+ )
+ return jsonify({'connection': connection.to_dict()}), 200
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 400
+ except HTTPError as exc:
+ return jsonify({'error': _bitbucket_error(exc)}), 400
+
+
+@source_connections_bp.route('/bitbucket/repos', methods=['GET'])
+@jwt_required()
+def bitbucket_repositories():
+ user_id = int(get_jwt_identity())
+ search = request.args.get('search', '')
+ page = request.args.get('page', 1, type=int)
+ per_page = request.args.get('per_page', 50, type=int)
+
+ try:
+ repos = SourceConnectionService.list_bitbucket_repositories(user_id, search, page, per_page)
+ return jsonify({'repos': repos}), 200
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 400
+ except HTTPError as exc:
+ return jsonify({'error': _bitbucket_error(exc)}), 400
+
+
+@source_connections_bp.route('/bitbucket/repos/<path:full_name>/branches', methods=['GET'])
+@jwt_required()
+def bitbucket_branches(full_name):
+ user_id = int(get_jwt_identity())
+
+ try:
+ branches = SourceConnectionService.list_bitbucket_branches(user_id, full_name)
+ return jsonify({'branches': branches}), 200
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 400
+ except HTTPError as exc:
+ return jsonify({'error': _bitbucket_error(exc)}), 400
+
+
+@source_connections_bp.route('/bitbucket/repos/<path:full_name>/manifest', methods=['GET'])
+@jwt_required()
+def bitbucket_repository_manifest(full_name):
+ user_id = int(get_jwt_identity())
+ ref = request.args.get('ref') or None
+
+ try:
+ manifest = SourceConnectionService.get_bitbucket_repository_manifest(user_id, full_name, ref)
+ return jsonify({'manifest': manifest}), 200
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 400
+ except HTTPError as exc:
+ return jsonify({'error': _bitbucket_error(exc)}), 400
+
+
+@source_connections_bp.route('/bitbucket', methods=['DELETE'])
+@jwt_required()
+def disconnect_bitbucket():
+ user_id = int(get_jwt_identity())
+ try:
+ SourceConnectionService.disconnect(user_id, 'bitbucket')
+ return jsonify({'message': 'Bitbucket disconnected'}), 200
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 404
+
+
+@source_connections_bp.route('/admin/bitbucket', methods=['GET'])
+@admin_required
+def bitbucket_admin_config():
+ return jsonify({'config': SourceConnectionService.get_bitbucket_config(redacted=True)}), 200
+
+
+@source_connections_bp.route('/admin/bitbucket', methods=['PUT'])
+@admin_required
+def update_bitbucket_admin_config():
+ user = User.query.get(get_jwt_identity())
+ result = SourceConnectionService.update_bitbucket_config(
+ request.get_json() or {},
+ user_id=user.id if user else None,
+ )
+ return jsonify(result), 200
+
+
+def _bitbucket_error(exc):
+ response = getattr(exc, 'response', None)
+ if response is None:
+ return str(exc)
+ try:
+ data = response.json()
+ return data.get('error_description') or data.get('error', {}).get('message') or data.get('message') or str(exc)
+ except Exception:
+ return response.text or str(exc)
diff --git a/backend/app/services/source_connection_service.py b/backend/app/services/source_connection_service.py
index 8364117b..78c16ef5 100644
--- a/backend/app/services/source_connection_service.py
+++ b/backend/app/services/source_connection_service.py
@@ -219,7 +219,7 @@ class SourceConnectionService:
id=connection_id,
user_id=user_id,
).first()
- if not connection or connection.provider not in ('github', 'gitlab'):
+ if not connection or connection.provider not in ('github', 'gitlab', 'bitbucket'):
raise ValueError('Source connection not found')
token = cls._decrypt_connection_token(connection)
@@ -227,6 +227,10 @@ class SourceConnectionService:
repo_path = cls._gitlab_repo_path(full_name)
public_url = f'https://gitlab.com/{repo_path}.git'
auth_url = f'https://oauth2:{quote(token, safe="")}@gitlab.com/{repo_path}.git'
+ elif connection.provider == 'bitbucket':
+ workspace, repo_slug = cls._split_full_name(full_name)
+ public_url = f'https://bitbucket.org/{workspace}/{repo_slug}.git'
+ auth_url = f'https://x-token-auth:{quote(token, safe="")}@bitbucket.org/{workspace}/{repo_slug}.git'
else:
owner, repo = cls._split_full_name(full_name)
public_url = f'https://github.com/{owner}/{repo}.git'
@@ -405,6 +409,269 @@ class SourceConnectionService:
db.session.commit()
return manifest
+ # ------------------------------------------------------------------
+ # Bitbucket
+ # ------------------------------------------------------------------
+
+ BITBUCKET_AUTHORIZE_URL = 'https://bitbucket.org/site/oauth2/authorize'
+ BITBUCKET_TOKEN_URL = 'https://bitbucket.org/site/oauth2/access_token'
+ BITBUCKET_API_URL = 'https://api.bitbucket.org/2.0'
+ BITBUCKET_SCOPES = ['repository:read', 'account:read']
+
+ @classmethod
+ def get_bitbucket_config(cls, redacted=False):
+ client_id = (
+ SettingsService.get('source_bitbucket_client_id', '')
+ or os.environ.get('SOURCE_BITBUCKET_CLIENT_ID', '')
+ or os.environ.get('SERVERKIT_BITBUCKET_CLIENT_ID', '')
+ )
+ client_secret = (
+ SettingsService.get('source_bitbucket_client_secret', '')
+ or os.environ.get('SOURCE_BITBUCKET_CLIENT_SECRET', '')
+ or os.environ.get('SERVERKIT_BITBUCKET_CLIENT_SECRET', '')
+ )
+
+ if redacted and client_secret:
+ client_secret = f'****{client_secret[-4:]}'
+
+ return {
+ 'client_id': client_id,
+ 'client_secret': client_secret,
+ 'configured': bool(client_id and client_secret),
+ 'scopes': cls.BITBUCKET_SCOPES,
+ }
+
+ @classmethod
+ def update_bitbucket_config(cls, data, user_id=None):
+ updated = []
+ if 'client_id' in data:
+ SettingsService.set('source_bitbucket_client_id', data.get('client_id') or '', user_id=user_id)
+ updated.append('client_id')
+ if 'client_secret' in data:
+ value = data.get('client_secret') or ''
+ if not (isinstance(value, str) and value.startswith('****')):
+ SettingsService.set('source_bitbucket_client_secret', value, user_id=user_id)
+ updated.append('client_secret')
+ return {'updated': updated, 'config': cls.get_bitbucket_config(redacted=True)}
+
+ @classmethod
+ def generate_bitbucket_authorize_url(cls, redirect_uri):
+ config = cls.get_bitbucket_config()
+ if not config['configured']:
+ raise ValueError('Bitbucket source connection is not configured')
+
+ state = secrets.token_urlsafe(32)
+ session['source_bitbucket_state'] = state
+
+ params = {
+ 'client_id': config['client_id'],
+ 'response_type': 'code',
+ 'state': state,
+ }
+ return f'{cls.BITBUCKET_AUTHORIZE_URL}?{urlencode(params)}', state
+
+ @classmethod
+ def complete_bitbucket_callback(cls, user_id, code, state, redirect_uri):
+ expected_state = session.pop('source_bitbucket_state', None)
+ if not expected_state or state != expected_state:
+ raise ValueError('Invalid Bitbucket OAuth state')
+
+ config = cls.get_bitbucket_config()
+ if not config['configured']:
+ raise ValueError('Bitbucket source connection is not configured')
+
+ token_response = requests.post(
+ cls.BITBUCKET_TOKEN_URL,
+ auth=(config['client_id'], config['client_secret']),
+ headers={'Accept': 'application/json'},
+ data={
+ 'grant_type': 'authorization_code',
+ 'code': code,
+ 'redirect_uri': redirect_uri,
+ },
+ timeout=15,
+ )
+ token_response.raise_for_status()
+ token_data = token_response.json()
+ if token_data.get('error'):
+ raise ValueError(token_data.get('error_description') or token_data['error'])
+
+ access_token = token_data.get('access_token')
+ if not access_token:
+ raise ValueError('Bitbucket did not return an access token')
+
+ profile = cls._bitbucket_get(access_token, '/user')
+ connection = SourceConnection.query.filter_by(user_id=user_id, provider='bitbucket').first()
+ if not connection:
+ connection = SourceConnection(user_id=user_id, provider='bitbucket')
+ db.session.add(connection)
+
+ connection.provider_account_id = str(profile.get('uuid') or '').strip('{}')
+ connection.provider_username = profile.get('username') or ''
+ connection.display_name = profile.get('display_name') or profile.get('username') or ''
+ connection.avatar_url = (profile.get('links', {}).get('avatar', {}) or {}).get('href', '')
+ connection.access_token_encrypted = encrypt_secret(access_token)
+ connection.scope = ' '.join(token_data.get('scopes', [])) or ' '.join(cls.BITBUCKET_SCOPES)
+ connection.updated_at = datetime.utcnow()
+ connection.last_used_at = datetime.utcnow()
+
+ db.session.commit()
+ return connection
+
+ @classmethod
+ def get_bitbucket_status(cls, user_id):
+ connection = cls.get_connection(user_id, 'bitbucket')
+ return {
+ 'configured': cls.get_bitbucket_config()['configured'],
+ 'connection': connection.to_dict() if connection else None,
+ }
+
+ @classmethod
+ def list_bitbucket_repositories(cls, user_id, search='', page=1, per_page=50):
+ token = cls._get_bitbucket_token(user_id)
+ params = {
+ 'role': 'member',
+ 'sort': '-updated_on',
+ 'pagelen': min(max(int(per_page or 50), 1), 100),
+ 'page': max(int(page or 1), 1),
+ }
+ data = cls._bitbucket_get(token, f'/repositories?{urlencode(params)}')
+ repos = data.get('values', [])
+
+ search_text = (search or '').strip().lower()
+ if search_text:
+ repos = [
+ repo for repo in repos
+ if search_text in repo.get('full_name', '').lower()
+ or search_text in (repo.get('description') or '').lower()
+ ]
+
+ connection = cls.get_connection(user_id, 'bitbucket')
+ if connection:
+ connection.last_used_at = datetime.utcnow()
+ db.session.commit()
+
+ return [cls._bitbucket_repo_payload(repo) for repo in repos]
+
+ @classmethod
+ def list_bitbucket_branches(cls, user_id, full_name):
+ token = cls._get_bitbucket_token(user_id)
+ workspace, repo_slug = cls._split_full_name(full_name)
+ path = f'/repositories/{quote(workspace)}/{quote(repo_slug)}/refs/branches?pagelen=100'
+ data = cls._bitbucket_get(token, path)
+ return [
+ {
+ 'name': branch.get('name'),
+ 'protected': False,
+ }
+ for branch in data.get('values', [])
+ ]
+
+ @classmethod
+ def get_bitbucket_repository_manifest(cls, user_id, full_name, ref=None):
+ token = cls._get_bitbucket_token(user_id)
+ workspace, repo_slug = cls._split_full_name(full_name)
+ root_files = cls._bitbucket_list_root_files(token, workspace, repo_slug, ref)
+ file_map = {}
+
+ for file_name in RepositoryManifestService.supported_files():
+ if root_files and file_name not in root_files:
+ continue
+ content = cls._bitbucket_get_file_content(token, workspace, repo_slug, file_name, ref)
+ if content is not None:
+ file_map[file_name] = content
+
+ manifest = RepositoryManifestService.analyze_files(file_map, root_files=root_files)
+ connection = cls.get_connection(user_id, 'bitbucket')
+ if connection:
+ connection.last_used_at = datetime.utcnow()
+ db.session.commit()
+ return manifest
+
+ @classmethod
+ def _get_bitbucket_token(cls, user_id):
+ connection = cls.get_connection(user_id, 'bitbucket')
+ if not connection:
+ raise ValueError('Bitbucket is not connected')
+ return cls._decrypt_connection_token(connection)
+
+ @classmethod
+ def _bitbucket_get(cls, token, path):
+ response = requests.get(
+ f'{cls.BITBUCKET_API_URL}{path}',
+ headers=cls._bitbucket_headers(token),
+ timeout=20,
+ )
+ response.raise_for_status()
+ return response.json()
+
+ @staticmethod
+ def _bitbucket_headers(token):
+ return {
+ 'Accept': 'application/json',
+ 'Authorization': f'Bearer {token}',
+ }
+
+ @classmethod
+ def _bitbucket_list_root_files(cls, token, workspace, repo_slug, ref=None):
+ params = {}
+ if ref:
+ params['at'] = ref
+ response = requests.get(
+ f'{cls.BITBUCKET_API_URL}/repositories/{quote(workspace)}/{quote(repo_slug)}/src/{ref or "master"}/',
+ headers=cls._bitbucket_headers(token),
+ params=params,
+ timeout=20,
+ )
+ response.raise_for_status()
+ data = response.json()
+ if not isinstance(data.get('values'), list):
+ return []
+ return [
+ item.get('path') for item in data['values']
+ if item.get('type') == 'commit_file' and item.get('path')
+ ]
+
+ @classmethod
+ def _bitbucket_get_file_content(cls, token, workspace, repo_slug, file_name, ref=None):
+ params = {}
+ if ref:
+ params['at'] = ref
+ response = requests.get(
+ f'{cls.BITBUCKET_API_URL}/repositories/{quote(workspace)}/{quote(repo_slug)}/src/{ref or "master"}/{quote(file_name, safe="")}',
+ headers=cls._bitbucket_headers(token),
+ params=params,
+ timeout=20,
+ )
+ if response.status_code == 404:
+ return None
+ response.raise_for_status()
+ return response.text
+
+ @staticmethod
+ def _bitbucket_repo_payload(repo):
+ clone_links = repo.get('links', {}).get('clone', []) or []
+ https_clone = next((link.get('href') for link in clone_links if link.get('name') == 'https'), None)
+ html_url = (repo.get('links', {}).get('html', {}) or {}).get('href', '')
+ mainbranch = repo.get('mainbranch', {}) or {}
+ owner = repo.get('owner', {}) or {}
+ return {
+ 'id': str(repo.get('uuid', '')).strip('{}'),
+ 'name': repo.get('name'),
+ 'full_name': repo.get('full_name'),
+ 'description': repo.get('description'),
+ 'private': repo.get('is_private', False),
+ 'fork': False,
+ 'archived': False,
+ 'default_branch': mainbranch.get('name') or 'master',
+ 'html_url': html_url,
+ 'clone_url': https_clone or f"https://bitbucket.org/{repo.get('full_name')}.git",
+ 'owner': {
+ 'login': owner.get('username'),
+ 'avatar_url': (owner.get('links', {}).get('avatar', {}) or {}).get('href', ''),
+ },
+ }
+
@classmethod
def _get_github_token(cls, user_id):
connection = cls.get_connection(user_id, 'github')
diff --git a/frontend/src/components/git/BitbucketRepoPicker.jsx b/frontend/src/components/git/BitbucketRepoPicker.jsx
new file mode 100644
index 00000000..8b87f018
--- /dev/null
+++ b/frontend/src/components/git/BitbucketRepoPicker.jsx
@@ -0,0 +1,171 @@
+import { useState, useEffect, useCallback } from 'react';
+import { SiBitbucket } from 'react-icons/si';
+import { Search, RefreshCw, Check } from 'lucide-react';
+import { Link } from 'react-router-dom';
+import api from '../../services/api';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+// One-click "Connect with Bitbucket" repo picker — mirrors the GitHub/GitLab
+// pickers. The backend payload already includes clone_url.
+function cloneUrl(repo) {
+ return repo.clone_url || `https://bitbucket.org/${repo.full_name}.git`;
+}
+
+const BitbucketRepoPicker = ({ onPick }) => {
+ const [status, setStatus] = useState(null); // { configured, connection }
+ const [loading, setLoading] = useState(true);
+ const [repos, setRepos] = useState([]);
+ const [reposLoading, setReposLoading] = useState(false);
+ const [search, setSearch] = useState('');
+ const [selected, setSelected] = useState(null);
+ const [branches, setBranches] = useState([]);
+ const [branch, setBranch] = useState('');
+
+ const connection = status?.connection;
+ const configured = status?.configured;
+
+ const loadStatus = useCallback(async () => {
+ setLoading(true);
+ try {
+ setStatus(await api.getBitbucketSourceStatus());
+ } catch {
+ setStatus(null);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { loadStatus(); }, [loadStatus]);
+
+ const loadRepos = useCallback(async (q = '') => {
+ setReposLoading(true);
+ try {
+ const data = await api.listBitbucketRepositories({ search: q, perPage: 80 });
+ setRepos(data.repos || []);
+ } catch {
+ setRepos([]);
+ } finally {
+ setReposLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { if (connection) loadRepos(); }, [connection, loadRepos]);
+
+ useEffect(() => {
+ if (!selected) return undefined;
+ const b = selected.default_branch || 'main';
+ setBranch(b);
+ onPick?.({ repoUrl: cloneUrl(selected), fullName: selected.full_name, branch: b });
+ let cancelled = false;
+ api.listBitbucketBranches(selected.full_name)
+ .then((data) => { if (!cancelled) setBranches(data.branches || []); })
+ .catch(() => { if (!cancelled) setBranches([]); });
+ return () => { cancelled = true; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selected]);
+
+ function pickBranch(b) {
+ setBranch(b);
+ if (selected) onPick?.({ repoUrl: cloneUrl(selected), fullName: selected.full_name, branch: b });
+ }
+
+ async function connectBitbucket() {
+ try {
+ const redirectUri = `${window.location.origin}/connections/callback/bitbucket`;
+ sessionStorage.setItem('sourceConnectionReturnTo', window.location.pathname + window.location.search);
+ const { auth_url } = await api.startSourceConnection('bitbucket', redirectUri);
+ window.location.href = auth_url;
+ } catch {
+ /* a retry surfaces the host's toast; nothing to do here */
+ }
+ }
+
+ if (loading) return null;
+
+ if (!configured) {
+ return (
+ <div className="git-connect__gh git-connect__gh--hint">
+ <SiBitbucket size={15} aria-hidden="true" />
+ <span>
+ Set up the Bitbucket connection in <Link to="/settings/connections">Settings</Link> to
+ pick a repo in one click instead of pasting a URL.
+ </span>
+ </div>
+ );
+ }
+
+ if (!connection) {
+ return (
+ <div className="git-connect__gh git-connect__gh--connect">
+ <SiBitbucket size={18} aria-hidden="true" />
+ <div className="git-connect__gh-text">
+ <strong>Connect with Bitbucket</strong>
+ <span>Authorize once, then choose a repository instead of pasting a URL.</span>
+ </div>
+ <Button type="button" onClick={connectBitbucket}>
+ <SiBitbucket size={15} /> Connect Bitbucket
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="git-connect__gh git-connect__gh--picker">
+ <div className="git-connect__gh-account">
+ {connection.avatar_url && <img src={connection.avatar_url} alt="" />}
+ <span className="git-connect__gh-account-name">
+ <strong>{connection.display_name || connection.provider_username}</strong>
+ <small>@{connection.provider_username}</small>
+ </span>
+ <Button type="button" variant="outline" size="sm" onClick={() => loadRepos(search)}>
+ <RefreshCw size={14} className={reposLoading ? 'spinning' : ''} /> Refresh
+ </Button>
+ </div>
+
+ <div className="git-connect__gh-search">
+ <Search size={15} aria-hidden="true" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search your repositories"
+ onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); loadRepos(search); } }}
+ />
+ </div>
+
+ <div className="git-connect__gh-list">
+ {reposLoading && <div className="git-connect__gh-state">Loading repositories…</div>}
+ {!reposLoading && repos.length === 0 && <div className="git-connect__gh-state">No repositories found.</div>}
+ {!reposLoading && repos.map((repo) => (
+ <button
+ type="button"
+ key={repo.id}
+ className={`git-connect__gh-repo${selected?.id === repo.id ? ' is-active' : ''}`}
+ onClick={() => setSelected(repo)}
+ >
+ <span className="git-connect__gh-repo-main">
+ <strong>{repo.full_name}</strong>
+ <small>{repo.description || 'No description'}</small>
+ </span>
+ <span className="git-connect__gh-repo-vis">{repo.private ? 'Private' : 'Public'}</span>
+ {selected?.id === repo.id && <Check size={15} />}
+ </button>
+ ))}
+ </div>
+
+ {selected && branches.length > 0 && (
+ <div className="git-connect__gh-branch">
+ <label htmlFor="bb-branch">Branch</label>
+ <select id="bb-branch" value={branch} onChange={(e) => pickBranch(e.target.value)}>
+ {branches.map((b) => {
+ const name = typeof b === 'string' ? b : b.name;
+ return <option key={name} value={name}>{name}</option>;
+ })}
+ </select>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default BitbucketRepoPicker;
diff --git a/frontend/src/components/git/GitProviders.jsx b/frontend/src/components/git/GitProviders.jsx
index ff87805f..41f11a1a 100644
--- a/frontend/src/components/git/GitProviders.jsx
+++ b/frontend/src/components/git/GitProviders.jsx
@@ -18,8 +18,8 @@ import { GitBranch } from 'lucide-react';
export const GIT_PROVIDERS = [
{ key: 'github', label: 'GitHub', Icon: SiGithub, hint: 'One-click or URL', match: /github\.com/i, oauth: true, placeholder: 'https://github.com/user/repo.git' },
{ key: 'gitlab', label: 'GitLab', Icon: SiGitlab, hint: 'Cloud or self-managed', match: /gitlab\./i, oauth: true, placeholder: 'https://gitlab.com/group/project.git' },
- { key: 'bitbucket', label: 'Bitbucket', Icon: SiBitbucket, hint: 'Paste a URL', match: /bitbucket\.org/i, placeholder: 'https://bitbucket.org/user/repo.git' },
- { key: 'gitea', label: 'Gitea', Icon: SiGitea, hint: 'Self-hosted', match: /gitea/i, placeholder: 'https://gitea.example.com/user/repo.git' },
+ { key: 'bitbucket', label: 'Bitbucket', Icon: SiBitbucket, hint: 'One-click or URL', match: /bitbucket\.org/i, oauth: true, placeholder: 'https://bitbucket.org/user/repo.git' },
+ { key: 'gitea', label: 'Gitea', Icon: SiGitea, hint: 'Self-hosted', match: /gitea/i, local: true, placeholder: 'https://gitea.example.com/user/repo.git' },
{ key: 'other', label: 'SSH / Other', Icon: GitBranch, hint: 'Any Git remote', match: null, placeholder: 'git@host:user/repo.git' },
];
@@ -37,25 +37,29 @@ export function detectProvider(url) {
// The provider strip: every supported host as a chip with its brand mark, label,
// and one-liner. Static by default (just "explains the others"); pass `onSelect`
// to make the chips REAL radio buttons that pick the connection method.
-export function RepoProviderStrip({ detected, selected, onSelect }) {
+export function RepoProviderStrip({ detected, selected, onSelect, giteaStatus }) {
const interactive = typeof onSelect === 'function';
const activeKey = selected ?? detected;
+ const giteaRunning = giteaStatus?.installed && giteaStatus?.running;
return (
<div
className="git-connect__providers"
role={interactive ? 'radiogroup' : 'list'}
aria-label="Git providers"
>
- {GIT_PROVIDERS.map(({ key, label, Icon, hint }) => {
+ {GIT_PROVIDERS.map(({ key, label, Icon, hint, local }) => {
const active = activeKey === key;
- const className = `git-connect__provider${active ? ' git-connect__provider--active' : ''}${interactive ? ' git-connect__provider--btn' : ''}`;
+ const className = `git-connect__provider${active ? ' git-connect__provider--active' : ''}${interactive ? ' git-connect__provider--btn' : ''}${local && giteaRunning ? ' git-connect__provider--live' : ''}`;
+ const displayHint = key === 'gitea' && giteaRunning
+ ? 'Local server running'
+ : hint;
const inner = (
<>
<span className="git-connect__provider-icon">
<Icon size={18} aria-hidden="true" />
</span>
<span className="git-connect__provider-label">{label}</span>
- <span className="git-connect__provider-hint">{hint}</span>
+ <span className="git-connect__provider-hint">{displayHint}</span>
</>
);
return interactive ? (
diff --git a/frontend/src/components/git/GiteaRepoPicker.jsx b/frontend/src/components/git/GiteaRepoPicker.jsx
new file mode 100644
index 00000000..3d491692
--- /dev/null
+++ b/frontend/src/components/git/GiteaRepoPicker.jsx
@@ -0,0 +1,172 @@
+import { useState, useEffect, useCallback } from 'react';
+import { SiGitea } from 'react-icons/si';
+import { Search, RefreshCw, Check, Server } from 'lucide-react';
+import { Link } from 'react-router-dom';
+import api from '../../services/api';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+// Local Gitea repo picker. Uses the ServerKit-managed Gitea instance when it is
+// installed and running. The backend's formatted repo payload already includes
+// clone_url, so we emit that directly.
+function cloneUrl(repo) {
+ return repo.clone_url || repo.html_url || repo.ssh_url || '';
+}
+
+function splitFullName(fullName) {
+ const parts = (fullName || '').split('/');
+ return parts.length >= 2 ? [parts[0], parts.slice(1).join('/')] : [null, null];
+}
+
+const GiteaRepoPicker = ({ onPick }) => {
+ const [status, setStatus] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [repos, setRepos] = useState([]);
+ const [reposLoading, setReposLoading] = useState(false);
+ const [search, setSearch] = useState('');
+ const [selected, setSelected] = useState(null);
+ const [branches, setBranches] = useState([]);
+ const [branch, setBranch] = useState('');
+
+ const installed = status?.installed;
+ const running = status?.running;
+
+ const loadStatus = useCallback(async () => {
+ setLoading(true);
+ try {
+ const data = await api.getGiteaStatus();
+ setStatus(data);
+ } catch {
+ setStatus(null);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { loadStatus(); }, [loadStatus]);
+
+ const loadRepos = useCallback(async (q = '') => {
+ setReposLoading(true);
+ try {
+ const data = await api.getGiteaRepositories(200);
+ let list = data.repositories || data.repos || [];
+ if (q.trim()) {
+ const lower = q.trim().toLowerCase();
+ list = list.filter((r) =>
+ (r.full_name || r.name || '').toLowerCase().includes(lower)
+ );
+ }
+ setRepos(list);
+ } catch {
+ setRepos([]);
+ } finally {
+ setReposLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { if (installed && running) loadRepos(); }, [installed, running, loadRepos]);
+
+ useEffect(() => {
+ if (!selected) return undefined;
+ const [owner, repo] = splitFullName(selected.full_name);
+ const b = selected.default_branch || 'main';
+ setBranch(b);
+ onPick?.({ repoUrl: cloneUrl(selected), fullName: selected.full_name, branch: b });
+ let cancelled = false;
+ if (owner && repo) {
+ api.getGiteaBranches(owner, repo)
+ .then((data) => { if (!cancelled) setBranches(data.branches || []); })
+ .catch(() => { if (!cancelled) setBranches([]); });
+ }
+ return () => { cancelled = true; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selected]);
+
+ function pickBranch(b) {
+ setBranch(b);
+ if (selected) onPick?.({ repoUrl: cloneUrl(selected), fullName: selected.full_name, branch: b });
+ }
+
+ if (loading) return null;
+
+ if (!installed) {
+ return (
+ <div className="git-connect__gh git-connect__gh--hint">
+ <SiGitea size={15} aria-hidden="true" />
+ <span>
+ Install the ServerKit Git server in <Link to="/git">Git</Link> to
+ pick a local repository instead of pasting a URL.
+ </span>
+ </div>
+ );
+ }
+
+ if (!running) {
+ return (
+ <div className="git-connect__gh git-connect__gh--hint">
+ <Server size={15} aria-hidden="true" />
+ <span>
+ Your Gitea server is installed but not running. Start it from <Link to="/git">Git</Link>.
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <div className="git-connect__gh git-connect__gh--picker">
+ <div className="git-connect__gh-account">
+ <span className="git-connect__gh-account-name">
+ <strong>Local Gitea</strong>
+ <small>Repositories on this ServerKit instance</small>
+ </span>
+ <Button type="button" variant="outline" size="sm" onClick={() => loadRepos(search)}>
+ <RefreshCw size={14} className={reposLoading ? 'spinning' : ''} /> Refresh
+ </Button>
+ </div>
+
+ <div className="git-connect__gh-search">
+ <Search size={15} aria-hidden="true" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search local repositories"
+ onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); loadRepos(search); } }}
+ />
+ </div>
+
+ <div className="git-connect__gh-list">
+ {reposLoading && <div className="git-connect__gh-state">Loading repositories…</div>}
+ {!reposLoading && repos.length === 0 && <div className="git-connect__gh-state">No local repositories found.</div>}
+ {!reposLoading && repos.map((repo) => (
+ <button
+ type="button"
+ key={repo.id}
+ className={`git-connect__gh-repo${selected?.id === repo.id ? ' is-active' : ''}`}
+ onClick={() => setSelected(repo)}
+ >
+ <span className="git-connect__gh-repo-main">
+ <strong>{repo.full_name}</strong>
+ <small>{repo.description || 'No description'}</small>
+ </span>
+ <span className="git-connect__gh-repo-vis">{repo.private ? 'Private' : 'Public'}</span>
+ {selected?.id === repo.id && <Check size={15} />}
+ </button>
+ ))}
+ </div>
+
+ {selected && branches.length > 0 && (
+ <div className="git-connect__gh-branch">
+ <label htmlFor="gt-branch">Branch</label>
+ <select id="gt-branch" value={branch} onChange={(e) => pickBranch(e.target.value)}>
+ {branches.map((b) => {
+ const name = typeof b === 'string' ? b : b.name;
+ return <option key={name} value={name}>{name}</option>;
+ })}
+ </select>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default GiteaRepoPicker;
diff --git a/frontend/src/components/git/GitlabRepoPicker.jsx b/frontend/src/components/git/GitlabRepoPicker.jsx
new file mode 100644
index 00000000..63e00963
--- /dev/null
+++ b/frontend/src/components/git/GitlabRepoPicker.jsx
@@ -0,0 +1,172 @@
+import { useState, useEffect, useCallback } from 'react';
+import { SiGitlab } from 'react-icons/si';
+import { Search, RefreshCw, Check } from 'lucide-react';
+import { Link } from 'react-router-dom';
+import api from '../../services/api';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+// One-click "Connect with GitLab" repo picker — mirrors GithubRepoPicker but uses
+// the GitLab source-connection OAuth flow. GitLab's API payload does not include
+// a clone_url, so we build one from the full_name.
+function cloneUrl(repo) {
+ return `https://gitlab.com/${repo.full_name}.git`;
+}
+
+const GitlabRepoPicker = ({ onPick }) => {
+ const [status, setStatus] = useState(null); // { configured, connection }
+ const [loading, setLoading] = useState(true);
+ const [repos, setRepos] = useState([]);
+ const [reposLoading, setReposLoading] = useState(false);
+ const [search, setSearch] = useState('');
+ const [selected, setSelected] = useState(null);
+ const [branches, setBranches] = useState([]);
+ const [branch, setBranch] = useState('');
+
+ const connection = status?.connection;
+ const configured = status?.configured;
+
+ const loadStatus = useCallback(async () => {
+ setLoading(true);
+ try {
+ setStatus(await api.getGitlabSourceStatus());
+ } catch {
+ setStatus(null);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { loadStatus(); }, [loadStatus]);
+
+ const loadRepos = useCallback(async (q = '') => {
+ setReposLoading(true);
+ try {
+ const data = await api.listGitlabRepositories({ search: q, perPage: 80 });
+ setRepos(data.repos || []);
+ } catch {
+ setRepos([]);
+ } finally {
+ setReposLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { if (connection) loadRepos(); }, [connection, loadRepos]);
+
+ useEffect(() => {
+ if (!selected) return undefined;
+ const b = selected.default_branch || 'main';
+ setBranch(b);
+ onPick?.({ repoUrl: cloneUrl(selected), fullName: selected.full_name, branch: b });
+ let cancelled = false;
+ api.listGitlabBranches(selected.full_name)
+ .then((data) => { if (!cancelled) setBranches(data.branches || []); })
+ .catch(() => { if (!cancelled) setBranches([]); });
+ return () => { cancelled = true; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selected]);
+
+ function pickBranch(b) {
+ setBranch(b);
+ if (selected) onPick?.({ repoUrl: cloneUrl(selected), fullName: selected.full_name, branch: b });
+ }
+
+ async function connectGitlab() {
+ try {
+ const redirectUri = `${window.location.origin}/connections/callback/gitlab`;
+ sessionStorage.setItem('sourceConnectionReturnTo', window.location.pathname + window.location.search);
+ const { auth_url } = await api.startSourceConnection('gitlab', redirectUri);
+ window.location.href = auth_url;
+ } catch {
+ /* a retry surfaces the host's toast; nothing to do here */
+ }
+ }
+
+ if (loading) return null;
+
+ if (!configured) {
+ return (
+ <div className="git-connect__gh git-connect__gh--hint">
+ <SiGitlab size={15} aria-hidden="true" />
+ <span>
+ Set up the GitLab connection in <Link to="/settings/connections">Settings</Link> to
+ pick a repo in one click instead of pasting a URL.
+ </span>
+ </div>
+ );
+ }
+
+ if (!connection) {
+ return (
+ <div className="git-connect__gh git-connect__gh--connect">
+ <SiGitlab size={18} aria-hidden="true" />
+ <div className="git-connect__gh-text">
+ <strong>Connect with GitLab</strong>
+ <span>Authorize once, then choose a repository instead of pasting a URL.</span>
+ </div>
+ <Button type="button" onClick={connectGitlab}>
+ <SiGitlab size={15} /> Connect GitLab
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="git-connect__gh git-connect__gh--picker">
+ <div className="git-connect__gh-account">
+ {connection.avatar_url && <img src={connection.avatar_url} alt="" />}
+ <span className="git-connect__gh-account-name">
+ <strong>{connection.display_name || connection.provider_username}</strong>
+ <small>@{connection.provider_username}</small>
+ </span>
+ <Button type="button" variant="outline" size="sm" onClick={() => loadRepos(search)}>
+ <RefreshCw size={14} className={reposLoading ? 'spinning' : ''} /> Refresh
+ </Button>
+ </div>
+
+ <div className="git-connect__gh-search">
+ <Search size={15} aria-hidden="true" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search your repositories"
+ onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); loadRepos(search); } }}
+ />
+ </div>
+
+ <div className="git-connect__gh-list">
+ {reposLoading && <div className="git-connect__gh-state">Loading repositories…</div>}
+ {!reposLoading && repos.length === 0 && <div className="git-connect__gh-state">No repositories found.</div>}
+ {!reposLoading && repos.map((repo) => (
+ <button
+ type="button"
+ key={repo.id}
+ className={`git-connect__gh-repo${selected?.id === repo.id ? ' is-active' : ''}`}
+ onClick={() => setSelected(repo)}
+ >
+ <span className="git-connect__gh-repo-main">
+ <strong>{repo.full_name}</strong>
+ <small>{repo.description || repo.language || 'No description'}</small>
+ </span>
+ <span className="git-connect__gh-repo-vis">{repo.private ? 'Private' : 'Public'}</span>
+ {selected?.id === repo.id && <Check size={15} />}
+ </button>
+ ))}
+ </div>
+
+ {selected && branches.length > 0 && (
+ <div className="git-connect__gh-branch">
+ <label htmlFor="gl-branch">Branch</label>
+ <select id="gl-branch" value={branch} onChange={(e) => pickBranch(e.target.value)}>
+ {branches.map((b) => {
+ const name = typeof b === 'string' ? b : b.name;
+ return <option key={name} value={name}>{name}</option>;
+ })}
+ </select>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default GitlabRepoPicker;
diff --git a/frontend/src/components/git/PathSelector.jsx b/frontend/src/components/git/PathSelector.jsx
new file mode 100644
index 00000000..1d13d035
--- /dev/null
+++ b/frontend/src/components/git/PathSelector.jsx
@@ -0,0 +1,109 @@
+import { useState } from 'react';
+import { X, Plus, FolderTree } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+
+// Smart tracked-path selector for WordPress Git connections. Replaces the raw
+// textarea with removable chips, common-path shortcuts, and custom-path input.
+const QUICK_PATHS = [
+ { label: 'Themes', value: 'wp-content/themes' },
+ { label: 'Plugins', value: 'wp-content/plugins' },
+ { label: 'Uploads', value: 'wp-content/uploads' },
+ { label: 'MU Plugins', value: 'wp-content/mu-plugins' },
+];
+
+function normalizePath(value) {
+ return value
+ .replace(/\\/g, '/')
+ .split('/')
+ .filter((p) => p.trim())
+ .join('/')
+ .replace(/^\//, '')
+ .replace(/\/$/, '');
+}
+
+const PathSelector = ({ paths, onChange, label, hint, id }) => {
+ const [inputValue, setInputValue] = useState('');
+
+ function addPath(raw) {
+ const normalized = normalizePath(raw);
+ if (!normalized) return;
+ if (paths.includes(normalized)) return;
+ onChange([...paths, normalized]);
+ setInputValue('');
+ }
+
+ function removePath(path) {
+ onChange(paths.filter((p) => p !== path));
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ addPath(inputValue);
+ }
+ }
+
+ return (
+ <div className="git-path-selector">
+ {label && <label htmlFor={id} className="git-path-selector__label">{label}</label>}
+
+ <div className="git-path-selector__quick">
+ {QUICK_PATHS.map(({ label: quickLabel, value }) => {
+ const active = paths.includes(value);
+ return (
+ <button
+ type="button"
+ key={value}
+ className={`git-path-selector__chip git-path-selector__chip--quick${active ? ' is-active' : ''}`}
+ onClick={() => (active ? removePath(value) : addPath(value))}
+ aria-pressed={active}
+ >
+ {active ? <X size={12} aria-hidden="true" /> : <Plus size={12} aria-hidden="true" />}
+ {quickLabel}
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="git-path-selector__add">
+ <span className="git-path-selector__add-icon"><FolderTree size={14} aria-hidden="true" /></span>
+ <input
+ id={id}
+ type="text"
+ className="ui-input"
+ value={inputValue}
+ onChange={(e) => setInputValue(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder="wp-content/custom-path"
+ />
+ <Button type="button" variant="outline" size="sm" onClick={() => addPath(inputValue)}>
+ <Plus size={14} aria-hidden="true" /> Add
+ </Button>
+ </div>
+
+ {paths.length > 0 ? (
+ <ul className="git-path-selector__list">
+ {paths.map((path) => (
+ <li key={path} className="git-path-selector__item">
+ <code>{path}</code>
+ <button
+ type="button"
+ className="git-path-selector__remove"
+ onClick={() => removePath(path)}
+ aria-label={`Remove ${path}`}
+ >
+ <X size={12} aria-hidden="true" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="git-path-selector__empty">No paths tracked yet. Choose a shortcut above or type a custom path.</p>
+ )}
+
+ {hint && <span className="git-connect__field-hint">{hint}</span>}
+ </div>
+ );
+};
+
+export default PathSelector;
diff --git a/frontend/src/components/git/RepoConnectForm.jsx b/frontend/src/components/git/RepoConnectForm.jsx
index 3c654590..70e9c26e 100644
--- a/frontend/src/components/git/RepoConnectForm.jsx
+++ b/frontend/src/components/git/RepoConnectForm.jsx
@@ -3,25 +3,32 @@ import { GitBranch, Unlink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
-import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
+import api from '../../services/api';
import { RepoProviderStrip, ProviderBadge, detectProvider, GIT_PROVIDERS } from './GitProviders';
import GithubRepoPicker from './GithubRepoPicker';
+import GitlabRepoPicker from './GitlabRepoPicker';
+import BitbucketRepoPicker from './BitbucketRepoPicker';
+import GiteaRepoPicker from './GiteaRepoPicker';
+import PathSelector from './PathSelector';
// Canonical "connect a repository" form, shared across ServerKit's surfaces
// (WordPress Git settings, the New Service page, the service connect modal).
// It owns the form state and submits via the `onConnect` callback; when a repo
-// is already connected it shows the connected summary + Disconnect. Everything
-// host-specific (intro copy, whether tracked paths are shown, defaults) is a
-// prop so each caller can dress it without forking the markup.
+// is already connected it shows the connected summary + Disconnect.
+//
+// Provider-specific fast paths:
+// - GitHub / GitLab: OAuth repo picker (URL fallback below it).
+// - Gitea: detect the local ServerKit Gitea instance and list its repos.
+// - Bitbucket / SSH / Other: paste-a-URL flow.
//
// props:
// gitStatus { connected, repo_url, branch, auto_deploy, last_deploy_* }
// onConnect async ({ repo_url, branch, paths, auto_deploy }) => void
// onDisconnect async () => void
// intro { title, subtitle }
-// showPaths render the "tracked paths" textarea (WordPress)
-// defaultPaths / pathsLabel / pathsHint / pathsPlaceholder
+// showPaths render the tracked-path selector (WordPress)
+// defaultPaths / pathsLabel / pathsHint
// urlPlaceholder / submitLabel
// idPrefix unique id prefix (so two forms can coexist on one page)
const RepoConnectForm = ({
@@ -34,9 +41,8 @@ const RepoConnectForm = ({
},
showPaths = false,
defaultPaths = [],
- pathsLabel = 'Tracked paths (one per line)',
+ pathsLabel = 'Tracked paths',
pathsHint = '',
- pathsPlaceholder = '',
urlPlaceholder = 'https://github.com/user/repo.git',
submitLabel = 'Connect Repository',
idPrefix = 'repo',
@@ -50,12 +56,12 @@ const RepoConnectForm = ({
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
+ const [giteaStatus, setGiteaStatus] = useState(null);
const isConnected = gitStatus?.connected;
const provider = detectProvider(formData.repoUrl);
- // Which provider chip is chosen — drives the connect method (GitHub shows the
- // one-click picker; everyone else gets a paste-a-URL field). A recognized URL
+ // Which provider chip is chosen — drives the connect method. A recognized URL
// wins over a manual click.
const [selectedKey, setSelectedKey] = useState(enableGithub ? 'github' : 'other');
useEffect(() => {
@@ -63,16 +69,32 @@ const RepoConnectForm = ({
}, [provider?.key]);
const selectedProvider = GIT_PROVIDERS.find((p) => p.key === selectedKey) || GIT_PROVIDERS[0];
+ // Detect local Gitea so we can badge the provider card and offer the local repo picker.
+ useEffect(() => {
+ let cancelled = false;
+ api.getGiteaStatus()
+ .then((data) => { if (!cancelled) setGiteaStatus(data); })
+ .catch(() => { if (!cancelled) setGiteaStatus(null); });
+ return () => { cancelled = true; };
+ }, []);
+
function handleChange(e) {
const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
}
- function handlePathsChange(e) {
- const paths = e.target.value.split('\n').filter((p) => p.trim());
+ function handlePathsChange(paths) {
setFormData((prev) => ({ ...prev, paths }));
}
+ function handleRepoPick({ repoUrl, branch }) {
+ setFormData((prev) => ({
+ ...prev,
+ repoUrl: repoUrl || prev.repoUrl,
+ branch: branch || prev.branch,
+ }));
+ }
+
async function handleConnect(e) {
e.preventDefault();
setError('');
@@ -156,6 +178,8 @@ const RepoConnectForm = ({
);
}
+ const giteaRunning = giteaStatus?.installed && giteaStatus?.running;
+
return (
<form className="git-connect git-connect--card" onSubmit={handleConnect}>
<div className="git-connect__intro">
@@ -168,19 +192,43 @@ const RepoConnectForm = ({
</div>
</div>
- <RepoProviderStrip detected={provider?.key} selected={selectedKey} onSelect={setSelectedKey} />
+ <RepoProviderStrip
+ detected={provider?.key}
+ selected={selectedKey}
+ onSelect={setSelectedKey}
+ giteaStatus={giteaStatus}
+ />
- {enableGithub && selectedKey === 'github' && (
+ {selectedKey === 'github' && enableGithub && (
<>
- <GithubRepoPicker
- onPick={({ repoUrl, branch }) =>
- setFormData((p) => ({ ...p, repoUrl, branch: branch || p.branch }))
- }
- />
+ <GithubRepoPicker onPick={handleRepoPick} />
<div className="git-connect__or"><span>or paste a URL</span></div>
</>
)}
+ {selectedKey === 'gitlab' && (
+ <>
+ <GitlabRepoPicker onPick={handleRepoPick} />
+ <div className="git-connect__or"><span>or paste a URL</span></div>
+ </>
+ )}
+
+ {selectedKey === 'bitbucket' && (
+ <>
+ <BitbucketRepoPicker onPick={handleRepoPick} />
+ <div className="git-connect__or"><span>or paste a URL</span></div>
+ </>
+ )}
+
+ {selectedKey === 'gitea' && (
+ <>
+ <GiteaRepoPicker onPick={handleRepoPick} />
+ {!giteaRunning && (
+ <div className="git-connect__or"><span>or paste a URL</span></div>
+ )}
+ </>
+ )}
+
{error && <div className="error-message">{error}</div>}
<div className="git-connect__field">
@@ -210,17 +258,13 @@ const RepoConnectForm = ({
</div>
{showPaths && (
- <div className="git-connect__field">
- <Label htmlFor={`${idPrefix}-paths`}>{pathsLabel}</Label>
- <Textarea
- id={`${idPrefix}-paths`}
- value={formData.paths.join('\n')}
- onChange={handlePathsChange}
- placeholder={pathsPlaceholder}
- rows={3}
- />
- {pathsHint && <span className="git-connect__field-hint">{pathsHint}</span>}
- </div>
+ <PathSelector
+ id={`${idPrefix}-paths`}
+ paths={formData.paths}
+ onChange={handlePathsChange}
+ label={pathsLabel}
+ hint={pathsHint}
+ />
)}
<div className="git-connect__toggle">
diff --git a/frontend/src/components/icons/ProviderBrands.jsx b/frontend/src/components/icons/ProviderBrands.jsx
index 412d1905..8eef6de5 100644
--- a/frontend/src/components/icons/ProviderBrands.jsx
+++ b/frontend/src/components/icons/ProviderBrands.jsx
@@ -7,7 +7,7 @@
// Simple Icons render with `fill="currentColor"`, so the surrounding SCSS controls
// the color with no inline styles.
import {
- SiGithub, SiGitlab, SiCloudflare, SiDigitalocean,
+ SiGithub, SiGitlab, SiBitbucket, SiCloudflare, SiDigitalocean,
SiHetzner, SiVultr, SiAkamai, SiGodaddy, SiNamecheap, SiBackblaze,
} from 'react-icons/si';
import { FaAws } from 'react-icons/fa';
@@ -19,6 +19,7 @@ import { Mail, HardDrive, Plug } from 'lucide-react';
const PROVIDER_ICONS = {
github: SiGithub,
gitlab: SiGitlab,
+ bitbucket: SiBitbucket,
cloudflare: SiCloudflare,
route53: FaAws,
digitalocean: SiDigitalocean,
diff --git a/frontend/src/components/settings/connections/ConnectionsHub.jsx b/frontend/src/components/settings/connections/ConnectionsHub.jsx
index dceefac0..c2a10a82 100644
--- a/frontend/src/components/settings/connections/ConnectionsHub.jsx
+++ b/frontend/src/components/settings/connections/ConnectionsHub.jsx
@@ -24,8 +24,8 @@ export default function ConnectionsHub() {
const { isAdmin } = useAuth();
const toast = useToast();
- const [sourceStatus, setSourceStatus] = useState({ github: null, gitlab: null });
- const [sourceConfig, setSourceConfig] = useState({ github: null, gitlab: null });
+ const [sourceStatus, setSourceStatus] = useState({ github: null, gitlab: null, bitbucket: null });
+ const [sourceConfig, setSourceConfig] = useState({ github: null, gitlab: null, bitbucket: null });
const [dnsProviders, setDnsProviders] = useState([]);
const [cloudProviders, setCloudProviders] = useState([]);
const [storageConfig, setStorageConfig] = useState(null);
@@ -39,9 +39,10 @@ export default function ConnectionsHub() {
const loadData = useCallback(async () => {
try {
- const [ghStatus, glStatus, dns, cloudP, storage, relay, regConns, regDomains, allConns] = await Promise.all([
+ const [ghStatus, glStatus, bbStatus, dns, cloudP, storage, relay, regConns, regDomains, allConns] = await Promise.all([
api.getGithubSourceStatus().catch(() => null),
api.getGitlabSourceStatus().catch(() => null),
+ api.getBitbucketSourceStatus().catch(() => null),
api.getEmailDNSProviders().then((d) => d.providers || []).catch(() => []),
api.getCloudProviders().then((d) => d.providers || []).catch(() => []),
api.getStorageConfig().catch(() => null),
@@ -50,7 +51,7 @@ export default function ConnectionsHub() {
api.getRegistrarDomains().then((d) => d.domains || []).catch(() => []),
api.getAllConnections().then((d) => d.connections || []).catch(() => []),
]);
- setSourceStatus({ github: ghStatus, gitlab: glStatus });
+ setSourceStatus({ github: ghStatus, gitlab: glStatus, bitbucket: bbStatus });
setDnsProviders(dns);
setCloudProviders(cloudP);
setStorageConfig(storage);
@@ -59,13 +60,15 @@ export default function ConnectionsHub() {
setRegistrarDomains(regDomains);
setAllConnections(allConns);
if (isAdmin) {
- const [ghCfg, glCfg] = await Promise.all([
+ const [ghCfg, glCfg, bbCfg] = await Promise.all([
api.getGithubSourceConfig().catch(() => null),
api.getGitlabSourceConfig().catch(() => null),
+ api.getBitbucketSourceConfig().catch(() => null),
]);
setSourceConfig({
github: ghCfg?.config || { client_id: '', client_secret: '' },
gitlab: glCfg?.config || { client_id: '', client_secret: '' },
+ bitbucket: bbCfg?.config || { client_id: '', client_secret: '' },
});
}
} finally {
@@ -101,6 +104,7 @@ export default function ConnectionsHub() {
const onSaveSourceConfig = useCallback(async (provider, config) => {
try {
if (provider.provider === 'gitlab') await api.updateGitlabSourceConfig(config);
+ else if (provider.provider === 'bitbucket') await api.updateBitbucketSourceConfig(config);
else await api.updateGithubSourceConfig(config);
toast.success(`${provider.name} OAuth app saved`);
await loadData();
diff --git a/frontend/src/components/settings/connections/providerCatalog.js b/frontend/src/components/settings/connections/providerCatalog.js
index e5ce0fb9..c6df32bc 100644
--- a/frontend/src/components/settings/connections/providerCatalog.js
+++ b/frontend/src/components/settings/connections/providerCatalog.js
@@ -30,6 +30,11 @@ export const CONNECTION_PROVIDERS = [
blurb: 'Cloud GitLab repositories, imported the same way as GitHub.',
docUrl: 'https://gitlab.com/-/profile/applications', manageHref: '/services/new',
},
+ {
+ id: 'bitbucket', category: 'source', name: 'Bitbucket', kind: 'source', provider: 'bitbucket',
+ blurb: 'Bitbucket Cloud repositories, imported the same way as GitHub.',
+ docUrl: 'https://bitbucket.org/[workspace]/workspace/settings/oauth-consumers/new', manageHref: '/services/new',
+ },
// ── Infrastructure (cloud servers) ──
{
diff --git a/frontend/src/components/wordpress/GitConnectForm.jsx b/frontend/src/components/wordpress/GitConnectForm.jsx
index 13f88d95..a690a5c7 100644
--- a/frontend/src/components/wordpress/GitConnectForm.jsx
+++ b/frontend/src/components/wordpress/GitConnectForm.jsx
@@ -13,9 +13,8 @@ const GitConnectForm = (props) => (
}}
showPaths
defaultPaths={['wp-content/themes', 'wp-content/plugins']}
- pathsLabel="Tracked paths (one per line)"
+ pathsLabel="Tracked paths"
pathsHint="Paths relative to the WordPress root that should be tracked."
- pathsPlaceholder={'wp-content/themes\nwp-content/plugins'}
/>
);
diff --git a/frontend/src/pages/SourceConnectionCallback.jsx b/frontend/src/pages/SourceConnectionCallback.jsx
index 03b74337..e162d9d3 100644
--- a/frontend/src/pages/SourceConnectionCallback.jsx
+++ b/frontend/src/pages/SourceConnectionCallback.jsx
@@ -1,9 +1,22 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
-import { Github, Loader2 } from 'lucide-react';
+import { Github, Gitlab, GitBranch, Loader2 } from 'lucide-react';
+import { SiBitbucket } from 'react-icons/si';
import api from '../services/api';
import { useToast } from '../contexts/ToastContext';
+const PROVIDER_LABELS = {
+ github: 'GitHub',
+ gitlab: 'GitLab',
+ bitbucket: 'Bitbucket',
+};
+
+const PROVIDER_ICONS = {
+ github: Github,
+ gitlab: Gitlab,
+ bitbucket: SiBitbucket,
+};
+
const SourceConnectionCallback = () => {
const { provider } = useParams();
const [searchParams] = useSearchParams();
@@ -12,6 +25,9 @@ const SourceConnectionCallback = () => {
const [error, setError] = useState('');
const didComplete = useRef(false);
+ const label = PROVIDER_LABELS[provider] || provider;
+ const Icon = PROVIDER_ICONS[provider] || GitBranch;
+
useEffect(() => {
if (didComplete.current) return;
didComplete.current = true;
@@ -23,30 +39,30 @@ const SourceConnectionCallback = () => {
const returnTo = sessionStorage.getItem('sourceConnectionReturnTo') || '/settings/connections';
if (!code || !state) {
- setError('GitHub did not return a valid authorization response.');
+ setError(`${label} did not return a valid authorization response.`);
return;
}
try {
await api.completeSourceConnection(provider, code, state, redirectUri);
sessionStorage.removeItem('sourceConnectionReturnTo');
- toast.success('GitHub connected');
+ toast.success(`${label} connected`);
navigate(returnTo, { replace: true });
} catch (err) {
- setError(err.message || 'Failed to connect GitHub');
+ setError(err.message || `Failed to connect ${label}`);
}
}
completeConnection();
- }, [navigate, provider, searchParams, toast]);
+ }, [navigate, provider, searchParams, toast, label]);
return (
<div className="auth-page">
<div className="auth-card">
<div className="auth-logo">
- <Github size={32} />
+ <Icon size={32} />
</div>
- <h1>Connecting GitHub</h1>
+ <h1>Connecting {label}</h1>
{error ? (
<>
<p className="auth-error">{error}</p>
diff --git a/frontend/src/services/api/files.js b/frontend/src/services/api/files.js
index a282cfc8..aa63b18a 100644
--- a/frontend/src/services/api/files.js
+++ b/frontend/src/services/api/files.js
@@ -393,6 +393,19 @@ export async function getGiteaVersion() {
return this.request('/git/version');
}
+// Self-documenting aliases for the local Gitea endpoints used by repo pickers.
+export async function getGiteaStatus() {
+ return this.request('/git/status');
+}
+
+export async function getGiteaRepositories(limit = 50) {
+ return this.request(`/git/repos?limit=${limit}`);
+}
+
+export async function getGiteaBranches(owner, repo) {
+ return this.request(`/git/repos/${owner}/${repo}/branches`);
+}
+
// Git Deployments
export async function getAppDeployments(appId, limit = 20) {
return this.request(`/git/deployments/app/${appId}?limit=${limit}`);
diff --git a/frontend/src/services/api/sourceConnections.js b/frontend/src/services/api/sourceConnections.js
index 8bb80f95..ad7e6400 100644
--- a/frontend/src/services/api/sourceConnections.js
+++ b/frontend/src/services/api/sourceConnections.js
@@ -56,6 +56,25 @@ export async function getGitlabSourceStatus() {
return this.request('/source-connections/gitlab/status');
}
+export async function listGitlabRepositories({ search = '', page = 1, perPage = 50 } = {}) {
+ const params = new URLSearchParams();
+ if (search) params.set('search', search);
+ params.set('page', page);
+ params.set('per_page', perPage);
+ return this.request(`/source-connections/gitlab/repos?${params.toString()}`);
+}
+
+export async function listGitlabBranches(fullName) {
+ return this.request(`/source-connections/gitlab/repos/${encodeURIComponent(fullName)}/branches`);
+}
+
+export async function inspectGitlabRepositoryManifest(fullName, ref = null) {
+ const params = new URLSearchParams();
+ if (ref) params.set('ref', ref);
+ const query = params.toString();
+ return this.request(`/source-connections/gitlab/repos/${encodeURIComponent(fullName)}/manifest${query ? `?${query}` : ''}`);
+}
+
export async function getGitlabSourceConfig() {
return this.request('/source-connections/admin/gitlab');
}
@@ -66,3 +85,39 @@ export async function updateGitlabSourceConfig(config) {
body: config,
});
}
+
+// Bitbucket mirrors the GitHub surface.
+
+export async function getBitbucketSourceStatus() {
+ return this.request('/source-connections/bitbucket/status');
+}
+
+export async function listBitbucketRepositories({ search = '', page = 1, perPage = 50 } = {}) {
+ const params = new URLSearchParams();
+ if (search) params.set('search', search);
+ params.set('page', page);
+ params.set('per_page', perPage);
+ return this.request(`/source-connections/bitbucket/repos?${params.toString()}`);
+}
+
+export async function listBitbucketBranches(fullName) {
+ return this.request(`/source-connections/bitbucket/repos/${encodeURIComponent(fullName)}/branches`);
+}
+
+export async function inspectBitbucketRepositoryManifest(fullName, ref = null) {
+ const params = new URLSearchParams();
+ if (ref) params.set('ref', ref);
+ const query = params.toString();
+ return this.request(`/source-connections/bitbucket/repos/${encodeURIComponent(fullName)}/manifest${query ? `?${query}` : ''}`);
+}
+
+export async function getBitbucketSourceConfig() {
+ return this.request('/source-connections/admin/bitbucket');
+}
+
+export async function updateBitbucketSourceConfig(config) {
+ return this.request('/source-connections/admin/bitbucket', {
+ method: 'PUT',
+ body: config,
+ });
+}
diff --git a/frontend/src/styles/components/_git-connect.scss b/frontend/src/styles/components/_git-connect.scss
index bdfbcea4..4909e83c 100644
--- a/frontend/src/styles/components/_git-connect.scss
+++ b/frontend/src/styles/components/_git-connect.scss
@@ -481,3 +481,128 @@
}
}
}
+
+// Provider card with a detected local service running.
+.git-connect__provider--live {
+ border-color: var(--green-dim, rgba(74, 222, 128, 0.35));
+ background: var(--green-bg);
+
+ .git-connect__provider-icon {
+ background: var(--green-bg);
+ color: var(--green);
+ }
+
+ .git-connect__provider-hint {
+ color: var(--green);
+ }
+}
+
+// Tracked-path selector (replaces the raw textarea).
+.git-path-selector {
+ display: grid;
+ gap: $space-3;
+
+ &__label {
+ color: $text-secondary;
+ font-size: $font-size-sm;
+ font-weight: $font-weight-medium;
+ }
+
+ &__quick {
+ display: flex;
+ flex-wrap: wrap;
+ gap: $space-2;
+ }
+
+ &__chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 5px 10px;
+ border: 1px solid var(--border);
+ border-radius: $radius-full;
+ background: var(--surface);
+ color: $text-secondary;
+ font-size: 12px;
+ cursor: pointer;
+ transition: border-color $transition-fast, background $transition-fast, color $transition-fast;
+
+ &:hover {
+ border-color: var(--border-strong);
+ background: var(--surface-2);
+ }
+
+ &--quick.is-active {
+ border-color: var(--accent-dim);
+ background: var(--accent-bg);
+ color: var(--accent-bright);
+ }
+ }
+
+ &__add {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+
+ .ui-input {
+ flex: 1;
+ min-width: 0;
+ }
+ }
+
+ &__add-icon {
+ display: inline-flex;
+ color: var(--text-faint);
+ flex-shrink: 0;
+ }
+
+ &__list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: $space-2;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ }
+
+ &__item {
+ display: inline-flex;
+ align-items: center;
+ gap: $space-1;
+ padding: 4px 8px 4px 10px;
+ background: var(--bg-code);
+ border: 1px solid var(--border-soft);
+ border-radius: $radius-md;
+ font-size: 12.5px;
+
+ code {
+ font-family: var(--mono);
+ color: var(--text-code);
+ }
+ }
+
+ &__remove {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ padding: 0;
+ border: none;
+ border-radius: $radius-sm;
+ background: transparent;
+ color: var(--text-faint);
+ cursor: pointer;
+
+ &:hover {
+ background: var(--red-bg);
+ color: var(--red);
+ }
+ }
+
+ &__empty {
+ margin: 0;
+ color: var(--text-faint);
+ font-size: $font-size-xs;
+ }
+}