feat(integrations): add Git hosting integrations and repo listing
Add support for integrating with external Git hosts (GitLab, Gitea, and Azure DevOps). The backend gains a client to fetch paginated repository lists, normalise base URLs, and surface provider errors. Credentials are loaded from the OS keychain and a Tauri command is exposed for the frontend to list integration repositories. - Implement integration client with pagination, deserialization, and provider-specific handling. - Centralise keychain credential loading and expose listing command. - Update UI to manage integration metadata, persist settings, and save/remove tokens to the OS keychain for cloning and operations.
This commit is contained in:
+12
-10
@@ -2878,6 +2878,17 @@ fn cred_entry(key: &str) -> Result<keyring::Entry, String> {
|
||||
keyring::Entry::new(CRED_SERVICE, key).map_err(|err| format!("Keychain unavailable: {err}"))
|
||||
}
|
||||
|
||||
pub(crate) fn load_stored_credential(key: &str) -> Result<Option<StoredCredential>, String> {
|
||||
let entry = cred_entry(key)?;
|
||||
match entry.get_password() {
|
||||
Ok(json) => serde_json::from_str::<StoredCredential>(&json)
|
||||
.map(Some)
|
||||
.map_err(|err| format!("Stored credentials unreadable: {err}")),
|
||||
Err(keyring::Error::NoEntry) => Ok(None),
|
||||
Err(err) => Err(format!("Keychain access failed: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the remote URL used for auth key derivation (upstream remote of the
|
||||
/// current branch, falling back to `origin`, then the first configured remote).
|
||||
#[tauri::command(async)]
|
||||
@@ -3061,16 +3072,7 @@ fn push_args_for_repo_to(
|
||||
|
||||
#[tauri::command(async)]
|
||||
pub fn cred_load(key: String) -> Result<Option<StoredCredential>, String> {
|
||||
let entry = cred_entry(&key)?;
|
||||
match entry.get_password() {
|
||||
Ok(json) => {
|
||||
let cred = serde_json::from_str::<StoredCredential>(&json)
|
||||
.map_err(|err| format!("Stored credentials unreadable: {err}"))?;
|
||||
Ok(Some(cred))
|
||||
}
|
||||
Err(keyring::Error::NoEntry) => Ok(None),
|
||||
Err(err) => Err(format!("Keychain access failed: {err}")),
|
||||
}
|
||||
load_stored_credential(&key)
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
use crate::git::load_stored_credential;
|
||||
use reqwest::blocking::{Client, Response};
|
||||
use reqwest::header::{ACCEPT, USER_AGENT};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
const PAGE_SIZE: usize = 100;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IntegrationRepository {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub full_name: String,
|
||||
pub description: String,
|
||||
pub clone_url: String,
|
||||
pub ssh_url: String,
|
||||
pub web_url: String,
|
||||
pub updated_at: String,
|
||||
pub private: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct GitLabProject {
|
||||
id: u64,
|
||||
name: String,
|
||||
path_with_namespace: String,
|
||||
#[serde(default)]
|
||||
description: Option<String>,
|
||||
http_url_to_repo: String,
|
||||
#[serde(default)]
|
||||
ssh_url_to_repo: String,
|
||||
#[serde(default)]
|
||||
web_url: String,
|
||||
#[serde(default)]
|
||||
last_activity_at: String,
|
||||
#[serde(default)]
|
||||
visibility: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct GiteaRepository {
|
||||
id: u64,
|
||||
name: String,
|
||||
full_name: String,
|
||||
#[serde(default)]
|
||||
description: String,
|
||||
clone_url: String,
|
||||
#[serde(default)]
|
||||
ssh_url: String,
|
||||
#[serde(default)]
|
||||
html_url: String,
|
||||
#[serde(default)]
|
||||
updated_at: String,
|
||||
#[serde(default)]
|
||||
private: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AzureRepositoryList {
|
||||
#[serde(default)]
|
||||
value: Vec<AzureRepository>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AzureRepository {
|
||||
id: String,
|
||||
name: String,
|
||||
project: AzureProject,
|
||||
#[serde(default, rename = "remoteUrl")]
|
||||
remote_url: String,
|
||||
#[serde(default, rename = "sshUrl")]
|
||||
ssh_url: String,
|
||||
#[serde(default, rename = "webUrl")]
|
||||
web_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AzureProject {
|
||||
name: String,
|
||||
}
|
||||
|
||||
fn integration_key(provider: &str, account_id: Option<&str>) -> Result<String, String> {
|
||||
if provider == "azure-devops" {
|
||||
if let Some(account_id) = account_id.filter(|value| !value.is_empty()) {
|
||||
if account_id.len() > 80
|
||||
|| !account_id.chars().all(|character| {
|
||||
character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
|
||||
})
|
||||
{
|
||||
return Err("Invalid integration account identifier.".to_string());
|
||||
}
|
||||
if account_id != "default" {
|
||||
return Ok(format!("integration:{provider}:{account_id}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(format!("integration:{provider}"))
|
||||
}
|
||||
|
||||
fn client() -> Result<Client, String> {
|
||||
Client::builder()
|
||||
.timeout(Duration::from_secs(25))
|
||||
.build()
|
||||
.map_err(|err| format!("Could not initialize the integration client: {err}"))
|
||||
}
|
||||
|
||||
fn normalized_base_url(base_url: &str) -> Result<String, String> {
|
||||
let base_url = base_url.trim().trim_end_matches('/');
|
||||
if !(base_url.starts_with("https://") || base_url.starts_with("http://")) {
|
||||
return Err("The integration URL must start with http:// or https://.".to_string());
|
||||
}
|
||||
Ok(base_url.to_string())
|
||||
}
|
||||
|
||||
fn response_error(response: Response, provider: &str) -> String {
|
||||
let status = response.status();
|
||||
let detail = response.text().ok().and_then(|body| {
|
||||
serde_json::from_str::<serde_json::Value>(&body)
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
value
|
||||
.get("message")
|
||||
.or_else(|| value.get("error"))
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::to_string)
|
||||
})
|
||||
});
|
||||
match detail {
|
||||
Some(detail) if !detail.trim().is_empty() => {
|
||||
format!("{provider} returned {status}: {detail}")
|
||||
}
|
||||
_ => format!("{provider} returned {status}."),
|
||||
}
|
||||
}
|
||||
|
||||
fn gitlab_repositories(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
token: &str,
|
||||
) -> Result<Vec<IntegrationRepository>, String> {
|
||||
let mut repositories = Vec::new();
|
||||
let mut page = 1usize;
|
||||
loop {
|
||||
let response = client
|
||||
.get(format!("{base_url}/api/v4/projects"))
|
||||
.header(USER_AGENT, "Gitty")
|
||||
.header(ACCEPT, "application/json")
|
||||
.header("PRIVATE-TOKEN", token)
|
||||
.query(&[
|
||||
("membership", "true"),
|
||||
("simple", "true"),
|
||||
("order_by", "last_activity_at"),
|
||||
("sort", "desc"),
|
||||
("per_page", &PAGE_SIZE.to_string()),
|
||||
("page", &page.to_string()),
|
||||
])
|
||||
.send()
|
||||
.map_err(|err| format!("Could not reach GitLab: {err}"))?;
|
||||
if !response.status().is_success() {
|
||||
return Err(response_error(response, "GitLab"));
|
||||
}
|
||||
let next_page = response
|
||||
.headers()
|
||||
.get("x-next-page")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let projects = response
|
||||
.json::<Vec<GitLabProject>>()
|
||||
.map_err(|err| format!("GitLab returned an unreadable repository list: {err}"))?;
|
||||
repositories.extend(projects.into_iter().map(|project| IntegrationRepository {
|
||||
id: project.id.to_string(),
|
||||
name: project.name,
|
||||
full_name: project.path_with_namespace,
|
||||
description: project.description.unwrap_or_default(),
|
||||
clone_url: project.http_url_to_repo,
|
||||
ssh_url: project.ssh_url_to_repo,
|
||||
web_url: project.web_url,
|
||||
updated_at: project.last_activity_at,
|
||||
private: project.visibility == "private",
|
||||
}));
|
||||
if next_page.is_empty() {
|
||||
break;
|
||||
}
|
||||
page = next_page.parse().unwrap_or(page + 1);
|
||||
}
|
||||
Ok(repositories)
|
||||
}
|
||||
|
||||
fn gitea_repositories(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
token: &str,
|
||||
) -> Result<Vec<IntegrationRepository>, String> {
|
||||
let mut repositories = Vec::new();
|
||||
let mut page = 1usize;
|
||||
loop {
|
||||
let response = client
|
||||
.get(format!("{base_url}/api/v1/user/repos"))
|
||||
.header(USER_AGENT, "Gitty")
|
||||
.header(ACCEPT, "application/json")
|
||||
.header("Authorization", format!("token {token}"))
|
||||
.query(&[
|
||||
("limit", PAGE_SIZE.to_string()),
|
||||
("page", page.to_string()),
|
||||
("sort", "updated".to_string()),
|
||||
])
|
||||
.send()
|
||||
.map_err(|err| format!("Could not reach Gitea: {err}"))?;
|
||||
if !response.status().is_success() {
|
||||
return Err(response_error(response, "Gitea"));
|
||||
}
|
||||
let page_repositories = response
|
||||
.json::<Vec<GiteaRepository>>()
|
||||
.map_err(|err| format!("Gitea returned an unreadable repository list: {err}"))?;
|
||||
let count = page_repositories.len();
|
||||
repositories.extend(page_repositories.into_iter().map(|repository| {
|
||||
IntegrationRepository {
|
||||
id: repository.id.to_string(),
|
||||
name: repository.name,
|
||||
full_name: repository.full_name,
|
||||
description: repository.description,
|
||||
clone_url: repository.clone_url,
|
||||
ssh_url: repository.ssh_url,
|
||||
web_url: repository.html_url,
|
||||
updated_at: repository.updated_at,
|
||||
private: repository.private,
|
||||
}
|
||||
}));
|
||||
if count < PAGE_SIZE {
|
||||
break;
|
||||
}
|
||||
page += 1;
|
||||
}
|
||||
Ok(repositories)
|
||||
}
|
||||
|
||||
fn azure_repositories(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
username: &str,
|
||||
token: &str,
|
||||
) -> Result<Vec<IntegrationRepository>, String> {
|
||||
let response = client
|
||||
.get(format!("{base_url}/_apis/git/repositories"))
|
||||
.header(USER_AGENT, "Gitty")
|
||||
.header(ACCEPT, "application/json")
|
||||
.basic_auth(username, Some(token))
|
||||
.query(&[("api-version", "7.1")])
|
||||
.send()
|
||||
.map_err(|err| format!("Could not reach Azure DevOps: {err}"))?;
|
||||
if !response.status().is_success() {
|
||||
return Err(response_error(response, "Azure DevOps"));
|
||||
}
|
||||
let repositories = response
|
||||
.json::<AzureRepositoryList>()
|
||||
.map_err(|err| format!("Azure DevOps returned an unreadable repository list: {err}"))?;
|
||||
Ok(repositories
|
||||
.value
|
||||
.into_iter()
|
||||
.map(|repository| IntegrationRepository {
|
||||
id: repository.id,
|
||||
full_name: format!("{}/{}", repository.project.name, repository.name),
|
||||
name: repository.name,
|
||||
description: String::new(),
|
||||
clone_url: repository.remote_url,
|
||||
ssh_url: repository.ssh_url,
|
||||
web_url: repository.web_url,
|
||||
updated_at: String::new(),
|
||||
private: true,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_integration_repositories(
|
||||
provider: String,
|
||||
base_url: String,
|
||||
account_id: Option<String>,
|
||||
) -> Result<Vec<IntegrationRepository>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let credential_key = integration_key(&provider, account_id.as_deref())?;
|
||||
let credential = load_stored_credential(&credential_key)?
|
||||
.ok_or_else(|| "No token is stored for this integration.".to_string())?;
|
||||
let base_url = normalized_base_url(&base_url)?;
|
||||
let client = client()?;
|
||||
match provider.as_str() {
|
||||
"gitlab" | "gitlab-self-hosted" => {
|
||||
gitlab_repositories(&client, &base_url, &credential.password)
|
||||
}
|
||||
"azure-devops" => azure_repositories(
|
||||
&client,
|
||||
&base_url,
|
||||
if credential.username.trim().is_empty() {
|
||||
"gitty"
|
||||
} else {
|
||||
&credential.username
|
||||
},
|
||||
&credential.password,
|
||||
),
|
||||
"gitea" => gitea_repositories(&client, &base_url, &credential.password),
|
||||
_ => Err("Unsupported integration provider.".to_string()),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|err| format!("Could not load integration repositories: {err}"))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base_urls_are_normalized_and_validated() {
|
||||
assert_eq!(
|
||||
normalized_base_url(" https://gitlab.example.com/ ").unwrap(),
|
||||
"https://gitlab.example.com"
|
||||
);
|
||||
assert!(normalized_base_url("gitlab.example.com").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integration_credential_keys_match_the_frontend() {
|
||||
assert_eq!(integration_key("gitea", None).unwrap(), "integration:gitea");
|
||||
assert_eq!(
|
||||
integration_key("azure-devops", Some("org-123")).unwrap(),
|
||||
"integration:azure-devops:org-123"
|
||||
);
|
||||
assert_eq!(
|
||||
integration_key("azure-devops", Some("default")).unwrap(),
|
||||
"integration:azure-devops"
|
||||
);
|
||||
assert!(integration_key("azure-devops", Some("../invalid")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_repository_payloads_deserialize() {
|
||||
let gitlab: Vec<GitLabProject> = serde_json::from_str(
|
||||
r#"[{"id":7,"name":"app","path_with_namespace":"team/app","description":"Demo","http_url_to_repo":"https://gitlab.test/team/app.git","ssh_url_to_repo":"git@gitlab.test:team/app.git","web_url":"https://gitlab.test/team/app","last_activity_at":"2026-08-29T10:00:00Z","visibility":"private"}]"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(gitlab[0].path_with_namespace, "team/app");
|
||||
assert_eq!(gitlab[0].visibility, "private");
|
||||
|
||||
let gitea: Vec<GiteaRepository> = serde_json::from_str(
|
||||
r#"[{"id":8,"name":"api","full_name":"team/api","description":"","clone_url":"https://gitea.test/team/api.git","ssh_url":"git@gitea.test:team/api.git","html_url":"https://gitea.test/team/api","updated_at":"2026-08-29T11:00:00Z","private":false}]"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(gitea[0].full_name, "team/api");
|
||||
assert!(!gitea[0].private);
|
||||
|
||||
let azure: AzureRepositoryList = serde_json::from_str(
|
||||
r#"{"value":[{"id":"repo-id","name":"web","project":{"name":"Platform"},"remoteUrl":"https://dev.azure.com/org/Platform/_git/web","sshUrl":"git@ssh.dev.azure.com:v3/org/Platform/web","webUrl":"https://dev.azure.com/org/Platform/_git/web"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(azure.value[0].project.name, "Platform");
|
||||
assert_eq!(
|
||||
azure.value[0].remote_url,
|
||||
"https://dev.azure.com/org/Platform/_git/web"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
mod badge;
|
||||
mod external_tools;
|
||||
mod git;
|
||||
mod integrations;
|
||||
mod telemetry;
|
||||
|
||||
use badge::set_sync_badge;
|
||||
@@ -32,6 +33,7 @@ use git::{
|
||||
stash_drop, stash_pop, stash_push, undo_last_commit, unlock_worktree, unstage_files,
|
||||
untrack_paths, update_remote,
|
||||
};
|
||||
use integrations::list_integration_repositories;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use tauri::{Emitter, Manager};
|
||||
@@ -432,6 +434,7 @@ async fn main() {
|
||||
cred_load,
|
||||
cred_save,
|
||||
cred_delete,
|
||||
list_integration_repositories,
|
||||
set_sync_badge,
|
||||
close_splashscreen,
|
||||
set_telemetry_enabled,
|
||||
|
||||
+65
-2
@@ -117,6 +117,7 @@
|
||||
launchExternalMerge,
|
||||
launchExternalTool,
|
||||
credLoad,
|
||||
credDelete,
|
||||
credSave,
|
||||
getFilePatch,
|
||||
readConflict,
|
||||
@@ -158,6 +159,9 @@
|
||||
ExplorerNodeKind,
|
||||
ExternalDiffScope,
|
||||
ExternalToolsSettings,
|
||||
GitIntegrationSecretUpdate,
|
||||
GitIntegrationSettings,
|
||||
GitIntegrationProvider,
|
||||
GitBlameLine,
|
||||
GitBranch as GitBranchInfo,
|
||||
GitCommit,
|
||||
@@ -190,6 +194,11 @@
|
||||
normaliseExternalToolsSettings,
|
||||
resolveDetectedExternalToolPrograms,
|
||||
} from "./lib/externalTools";
|
||||
import {
|
||||
defaultGitIntegrationSettings,
|
||||
integrationCredentialKey,
|
||||
normaliseGitIntegrationSettings,
|
||||
} from "./lib/integrations";
|
||||
|
||||
import {
|
||||
orgKeyFromUrl,
|
||||
@@ -259,6 +268,7 @@
|
||||
const CUSTOM_THEME_KEY = "gitlite.customTheme.v1";
|
||||
const APP_LANGUAGE_KEY = "gitlite.language.v1";
|
||||
const EXTERNAL_TOOLS_SETTINGS_KEY = "gitlite.externalTools.v1";
|
||||
const GIT_INTEGRATIONS_SETTINGS_KEY = "gitlite.integrations.v1";
|
||||
const AUTO_REFRESH_ENABLED_KEY = "gitlite.autoRefreshEnabled.v1";
|
||||
const COMMIT_PANEL_HEIGHT_KEY = "gitlite.commitPanelHeight.v1";
|
||||
const LEFT_SIDEBAR_WIDTH_KEY = "gitlite.leftSidebarWidth.v1";
|
||||
@@ -372,6 +382,7 @@
|
||||
let customTheme: CustomThemeColors = loadCustomTheme();
|
||||
let appLanguage: AppLanguage = loadLanguagePreference();
|
||||
let externalToolsSettings: ExternalToolsSettings = loadExternalToolsSettings();
|
||||
let gitIntegrationSettings: GitIntegrationSettings = loadGitIntegrationSettings();
|
||||
let externalToolsConfigured = hasStoredExternalToolsSettings();
|
||||
let detectedExternalTools: DetectedExternalTool[] = [];
|
||||
let externalToolsDetectionPending = true;
|
||||
@@ -1260,7 +1271,33 @@
|
||||
if (appTheme === "system") applyThemePreference(appTheme);
|
||||
}
|
||||
|
||||
function saveAppSettings(next: AnalyticsSettings, nextTheme: AppTheme, nextAppearance: AppAppearance, nextCustomTheme: CustomThemeColors, nextLanguage: AppLanguage, nextAutoRefresh: boolean, nextExternalTools: ExternalToolsSettings) {
|
||||
async function saveAppSettings(next: AnalyticsSettings, nextTheme: AppTheme, nextAppearance: AppAppearance, nextCustomTheme: CustomThemeColors, nextLanguage: AppLanguage, nextAutoRefresh: boolean, nextExternalTools: ExternalToolsSettings, nextIntegrations: GitIntegrationSettings, integrationSecrets: GitIntegrationSecretUpdate[]) {
|
||||
const integrationsToSave = structuredClone(nextIntegrations);
|
||||
try {
|
||||
for (const update of integrationSecrets) {
|
||||
const key = integrationCredentialKey(update.provider, update.accountId);
|
||||
const azureOrganization = update.provider === "azure-devops" && update.accountId
|
||||
? integrationsToSave.azureDevOpsOrganizations.find((organization) => organization.id === update.accountId)
|
||||
: undefined;
|
||||
const providerConfig = integrationsToSave.providers[update.provider];
|
||||
if (update.removeToken) {
|
||||
await credDelete(key);
|
||||
if (azureOrganization) azureOrganization.tokenStored = false;
|
||||
else providerConfig.tokenStored = false;
|
||||
} else if (update.token) {
|
||||
const username = (azureOrganization?.username ?? providerConfig.username).trim() || "oauth2";
|
||||
await credSave(key, username, update.token, "token");
|
||||
if (azureOrganization) azureOrganization.tokenStored = true;
|
||||
else providerConfig.tokenStored = true;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
errorMessage = appLanguage === "de"
|
||||
? `Integration konnte nicht gespeichert werden: ${String(error)}`
|
||||
: `Could not save integration: ${String(error)}`;
|
||||
return;
|
||||
}
|
||||
|
||||
const autoRefreshWasEnabled = autoRefreshEnabled;
|
||||
analyticsSettings = next;
|
||||
appTheme = nextTheme;
|
||||
@@ -1269,12 +1306,14 @@
|
||||
appLanguage = nextLanguage;
|
||||
autoRefreshEnabled = nextAutoRefresh;
|
||||
externalToolsSettings = nextExternalTools;
|
||||
gitIntegrationSettings = integrationsToSave;
|
||||
persistAnalyticsSettings(next);
|
||||
persistThemePreference(nextTheme);
|
||||
persistAppearancePreference(nextAppearance, nextCustomTheme);
|
||||
persistLanguagePreference(nextLanguage);
|
||||
persistStoredBoolean(AUTO_REFRESH_ENABLED_KEY, nextAutoRefresh);
|
||||
persistExternalToolsSettings(nextExternalTools);
|
||||
persistGitIntegrationSettings(integrationsToSave);
|
||||
externalToolsConfigured = true;
|
||||
setTelemetryEnabled(next.enabled);
|
||||
appSettingsOpen = false;
|
||||
@@ -2578,6 +2617,11 @@
|
||||
trackEvent("clone_dialog_opened");
|
||||
}
|
||||
|
||||
function cloneFromDialog(remoteUrl: string, parentPath: string, directoryName: string, provider?: GitIntegrationProvider, accountId?: string) {
|
||||
const credentialKey = provider ? integrationCredentialKey(provider, accountId) : undefined;
|
||||
void cloneRepo(remoteUrl, parentPath, directoryName, undefined, undefined, credentialKey, false, provider ? "token" : "credentials");
|
||||
}
|
||||
|
||||
function openRepoManagement() {
|
||||
if (isBusy) return;
|
||||
activeView = "management";
|
||||
@@ -4587,6 +4631,22 @@
|
||||
}
|
||||
}
|
||||
|
||||
function loadGitIntegrationSettings(): GitIntegrationSettings {
|
||||
try {
|
||||
return normaliseGitIntegrationSettings(JSON.parse(localStorage.getItem(GIT_INTEGRATIONS_SETTINGS_KEY) ?? "null"));
|
||||
} catch {
|
||||
return defaultGitIntegrationSettings();
|
||||
}
|
||||
}
|
||||
|
||||
function persistGitIntegrationSettings(next: GitIntegrationSettings) {
|
||||
try {
|
||||
localStorage.setItem(GIT_INTEGRATIONS_SETTINGS_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
// Metadata persistence is best-effort; tokens remain in the OS keychain.
|
||||
}
|
||||
}
|
||||
|
||||
function hasStoredExternalToolsSettings(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(EXTERNAL_TOOLS_SETTINGS_KEY) != null;
|
||||
@@ -5710,6 +5770,7 @@
|
||||
language={appLanguage}
|
||||
autoRefresh={autoRefreshEnabled}
|
||||
externalTools={externalToolsSettings}
|
||||
integrations={gitIntegrationSettings}
|
||||
detectedTools={detectedExternalTools}
|
||||
detectionPending={externalToolsDetectionPending}
|
||||
detectionUnavailable={externalToolsDetectionUnavailable}
|
||||
@@ -6043,7 +6104,9 @@
|
||||
<CloneRepositoryDialog
|
||||
isBusy={operation === "Cloning repository"}
|
||||
error={cloneDialogError}
|
||||
onClone={cloneRepo}
|
||||
language={appLanguage}
|
||||
integrations={gitIntegrationSettings}
|
||||
onClone={cloneFromDialog}
|
||||
onClose={() => { if (!isBusy) cloneDialogOpen = false; }}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
@@ -6,11 +6,13 @@
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
CircleDashed,
|
||||
CloudCog,
|
||||
Code2,
|
||||
FolderOpen,
|
||||
GitCompare,
|
||||
GitMerge,
|
||||
Languages,
|
||||
KeyRound,
|
||||
Palette,
|
||||
RefreshCw,
|
||||
RotateCw,
|
||||
@@ -29,6 +31,7 @@
|
||||
type ExternalToolKind,
|
||||
type ExternalToolPreset,
|
||||
} from "../externalTools";
|
||||
import { configuredIntegrationCount, defaultGitIntegrationSettings } from "../integrations";
|
||||
import type {
|
||||
AnalyticsSettings,
|
||||
AppAppearance,
|
||||
@@ -37,11 +40,14 @@
|
||||
CustomThemeColors,
|
||||
DetectedExternalTool,
|
||||
ExternalToolsSettings,
|
||||
GitIntegrationSecretUpdate,
|
||||
GitIntegrationSettings,
|
||||
ToolOpenMode,
|
||||
} from "../types";
|
||||
import IntegrationSettingsPage from "./IntegrationSettingsPage.svelte";
|
||||
import SelectMenu from "./SelectMenu.svelte";
|
||||
|
||||
type SettingsPage = "general" | "tools";
|
||||
type SettingsPage = "general" | "integrations" | "tools";
|
||||
|
||||
interface Props {
|
||||
analytics: AnalyticsSettings;
|
||||
@@ -51,11 +57,12 @@
|
||||
language: AppLanguage;
|
||||
autoRefresh: boolean;
|
||||
externalTools: ExternalToolsSettings;
|
||||
integrations: GitIntegrationSettings;
|
||||
detectedTools: DetectedExternalTool[];
|
||||
detectionPending: boolean;
|
||||
detectionUnavailable: boolean;
|
||||
onRefreshDetectedTools: () => void | Promise<void>;
|
||||
onSave: (settings: AnalyticsSettings, theme: AppTheme, appearance: AppAppearance, customTheme: CustomThemeColors, language: AppLanguage, autoRefresh: boolean, externalTools: ExternalToolsSettings) => void;
|
||||
onSave: (settings: AnalyticsSettings, theme: AppTheme, appearance: AppAppearance, customTheme: CustomThemeColors, language: AppLanguage, autoRefresh: boolean, externalTools: ExternalToolsSettings, integrations: GitIntegrationSettings, integrationSecrets: GitIntegrationSecretUpdate[]) => void | Promise<void>;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -67,6 +74,7 @@
|
||||
language = "en",
|
||||
autoRefresh = true,
|
||||
externalTools,
|
||||
integrations,
|
||||
detectedTools = [],
|
||||
detectionPending = false,
|
||||
detectionUnavailable = false,
|
||||
@@ -77,7 +85,7 @@
|
||||
|
||||
const toolKinds: ExternalToolKind[] = ["editor", "diff", "merge", "terminal", "fileManager"];
|
||||
|
||||
let activePage = $state<SettingsPage>("tools");
|
||||
let activePage = $state<SettingsPage>("integrations");
|
||||
let activeToolKind = $state<ExternalToolKind>("editor");
|
||||
let advancedOpen = $state(false);
|
||||
let analyticsEnabled = $state(true);
|
||||
@@ -87,6 +95,9 @@
|
||||
let selectedLanguage = $state<AppLanguage>("en");
|
||||
let autoRefreshEnabled = $state(true);
|
||||
let tools = $state<ExternalToolsSettings>(defaultExternalToolsSettings());
|
||||
let integrationDraft = $state<GitIntegrationSettings>(defaultGitIntegrationSettings());
|
||||
let integrationSecretUpdates = $state<GitIntegrationSecretUpdate[]>([]);
|
||||
let saving = $state(false);
|
||||
const isGerman = $derived(selectedLanguage === "de");
|
||||
|
||||
$effect(() => {
|
||||
@@ -97,14 +108,21 @@
|
||||
selectedLanguage = language;
|
||||
autoRefreshEnabled = autoRefresh;
|
||||
tools = structuredClone(externalTools);
|
||||
integrationDraft = structuredClone(integrations);
|
||||
});
|
||||
|
||||
function save() {
|
||||
onSave({
|
||||
...analytics,
|
||||
enabled: analyticsEnabled,
|
||||
noticeSeen: true,
|
||||
}, selectedTheme, selectedAppearance, $state.snapshot(customColors), selectedLanguage, autoRefreshEnabled, $state.snapshot(tools));
|
||||
async function save() {
|
||||
if (saving) return;
|
||||
saving = true;
|
||||
try {
|
||||
await onSave({
|
||||
...analytics,
|
||||
enabled: analyticsEnabled,
|
||||
noticeSeen: true,
|
||||
}, selectedTheme, selectedAppearance, $state.snapshot(customColors), selectedLanguage, autoRefreshEnabled, $state.snapshot(tools), $state.snapshot(integrationDraft), $state.snapshot(integrationSecretUpdates));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetCustomColors() {
|
||||
@@ -315,10 +333,22 @@
|
||||
</span>
|
||||
{#if !detectionUnavailable}<em>{detectedTools.length}</em>{/if}
|
||||
</button>
|
||||
<button type="button" class:active={activePage === "integrations"} onclick={() => { activePage = "integrations"; }}>
|
||||
<CloudCog size={16} aria-hidden="true" />
|
||||
<span>
|
||||
<strong>{isGerman ? "Integrationen" : "Integrations"}</strong>
|
||||
<small>GitLab, Azure DevOps & Gitea</small>
|
||||
</span>
|
||||
<em>{configuredIntegrationCount(integrationDraft)}</em>
|
||||
</button>
|
||||
|
||||
<div class="settings-nav-note">
|
||||
<ShieldCheck size={15} aria-hidden="true" />
|
||||
<p>{isGerman ? "Tool-Argumente werden direkt und ohne zusätzliche Shell übergeben." : "Tool arguments are passed directly without an extra shell."}</p>
|
||||
{#if activePage === "integrations"}<KeyRound size={15} aria-hidden="true" />{:else}<ShieldCheck size={15} aria-hidden="true" />{/if}
|
||||
<p>
|
||||
{activePage === "integrations"
|
||||
? (isGerman ? "Tokens werden sicher im Schlüsselbund des Betriebssystems gespeichert." : "Tokens are stored securely in the operating system keychain.")
|
||||
: (isGerman ? "Tool-Argumente werden direkt und ohne zusätzliche Shell übergeben." : "Tool arguments are passed directly without an extra shell.")}
|
||||
</p>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@@ -399,7 +429,7 @@
|
||||
</label>
|
||||
</section>
|
||||
</div>
|
||||
{:else}
|
||||
{:else if activePage === "tools"}
|
||||
<div class="settings-page-head tools-page-head">
|
||||
<div>
|
||||
<h3>{isGerman ? "Externe Tools" : "External tools"}</h3>
|
||||
@@ -518,6 +548,19 @@
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
{:else}
|
||||
<div class="settings-page-head">
|
||||
<div>
|
||||
<h3>{isGerman ? "Integrationen" : "Integrations"}</h3>
|
||||
<p>{isGerman ? "Verbinde Gitty mit deinen Git-Hosting-Diensten." : "Connect Gitty to your Git hosting services."}</p>
|
||||
</div>
|
||||
</div>
|
||||
<IntegrationSettingsPage
|
||||
language={selectedLanguage}
|
||||
settings={integrationDraft}
|
||||
onChange={(next) => { integrationDraft = next; }}
|
||||
onSecretsChange={(updates) => { integrationSecretUpdates = updates; }}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -526,7 +569,7 @@
|
||||
<span>{isGerman ? "Änderungen werden erst beim Speichern übernommen." : "Changes are applied only after saving."}</span>
|
||||
<div>
|
||||
<button class="btn-secondary" type="button" onclick={onClose}>{isGerman ? "Abbrechen" : "Cancel"}</button>
|
||||
<button class="btn-primary" type="submit"><Check size={16} aria-hidden="true" />{isGerman ? "Änderungen speichern" : "Save changes"}</button>
|
||||
<button class="btn-primary" type="submit" disabled={saving}><Check size={16} aria-hidden="true" />{saving ? (isGerman ? "Wird gespeichert…" : "Saving…") : (isGerman ? "Änderungen speichern" : "Save changes")}</button>
|
||||
</div>
|
||||
</footer>
|
||||
</form>
|
||||
@@ -663,7 +706,8 @@
|
||||
.app-settings-head { min-height: 58px; padding: 10px 12px; }
|
||||
.app-settings-mark { width: 34px; height: 34px; }
|
||||
.settings-nav button small, .settings-nav button em { display: none; }
|
||||
.settings-nav > button { grid-template-columns: auto minmax(0, 1fr); }
|
||||
.settings-nav > button { grid-template-columns: auto minmax(0, 1fr); gap: 5px; padding-inline: 6px; }
|
||||
.settings-nav button strong { font-size: 10px; }
|
||||
.settings-page-head { align-items: stretch; flex-direction: column; }
|
||||
.tool-rescan-button { align-self: flex-start; }
|
||||
.general-settings-grid { grid-template-columns: 1fr; }
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from "svelte";
|
||||
import { open as openDialog } from "@tauri-apps/plugin-dialog";
|
||||
import { Download, FolderOpen, LoaderCircle, X } from "@lucide/svelte";
|
||||
import { Cloud, Download, FolderOpen, GitBranch, Globe2, LoaderCircle, LockKeyhole, RefreshCw, Search, X } from "@lucide/svelte";
|
||||
import { listIntegrationRepositories } from "../git";
|
||||
import { configuredIntegrationSources } from "../integrations";
|
||||
import type { AppLanguage, GitIntegrationProvider, GitIntegrationRepository, GitIntegrationSettings, GitIntegrationSource } from "../types";
|
||||
|
||||
type CloneSource = "url" | "integrations";
|
||||
|
||||
interface Props {
|
||||
isBusy: boolean;
|
||||
error: string;
|
||||
onClone: (remoteUrl: string, parentPath: string, directoryName: string) => void;
|
||||
language: AppLanguage;
|
||||
integrations: GitIntegrationSettings;
|
||||
onClone: (remoteUrl: string, parentPath: string, directoryName: string, provider?: GitIntegrationProvider, accountId?: string) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
isBusy = false,
|
||||
error = "",
|
||||
onClone = () => {},
|
||||
onClose = () => {},
|
||||
}: Props = $props();
|
||||
|
||||
let { isBusy = false, error = "", language = "en", integrations, onClone = () => {}, onClose = () => {} }: Props = $props();
|
||||
let source = $state<CloneSource>("url");
|
||||
let remoteUrl = $state("");
|
||||
let parentPath = $state("");
|
||||
let directoryName = $state("");
|
||||
@@ -25,28 +27,35 @@
|
||||
let browseError = $state("");
|
||||
let visibleError = $state("");
|
||||
let errorHideTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let selectedSourceId = $state("");
|
||||
let selectedRepositoryId = $state("");
|
||||
let repositorySearch = $state("");
|
||||
let repositoriesBySource = $state<Record<string, GitIntegrationRepository[]>>({});
|
||||
let loadingSourceId = $state("");
|
||||
let repositoryError = $state("");
|
||||
let repositoryRequestId = 0;
|
||||
|
||||
let directorySuggestion = $derived(directoryNameFromRemoteUrl(remoteUrl));
|
||||
let canSubmit = $derived(
|
||||
!isBusy &&
|
||||
remoteUrl.trim().length > 0 &&
|
||||
parentPath.trim().length > 0,
|
||||
);
|
||||
const isGerman = $derived(language === "de");
|
||||
const configuredSources = $derived(configuredIntegrationSources(integrations));
|
||||
const activeSource = $derived(configuredSources.find((candidate) => candidate.id === selectedSourceId));
|
||||
const activeRepositories = $derived(activeSource ? repositoriesBySource[activeSource.id] ?? [] : []);
|
||||
const filteredRepositories = $derived.by(() => {
|
||||
const query = repositorySearch.trim().toLocaleLowerCase();
|
||||
if (!query) return activeRepositories;
|
||||
return activeRepositories.filter((repository) => `${repository.fullName} ${repository.description}`.toLocaleLowerCase().includes(query));
|
||||
});
|
||||
const selectedRepository = $derived(activeRepositories.find((repository) => repository.id === selectedRepositoryId));
|
||||
const directorySuggestion = $derived(directoryNameFromRemoteUrl(remoteUrl));
|
||||
const canSubmit = $derived(!isBusy && remoteUrl.trim().length > 0 && parentPath.trim().length > 0);
|
||||
|
||||
$effect(() => {
|
||||
const nextError = error || browseError;
|
||||
if (errorHideTimer) clearTimeout(errorHideTimer);
|
||||
visibleError = nextError;
|
||||
if (nextError) {
|
||||
errorHideTimer = setTimeout(() => {
|
||||
visibleError = "";
|
||||
}, 6000);
|
||||
}
|
||||
if (nextError) errorHideTimer = setTimeout(() => { visibleError = ""; }, 6000);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (errorHideTimer) clearTimeout(errorHideTimer);
|
||||
});
|
||||
onDestroy(() => { if (errorHideTimer) clearTimeout(errorHideTimer); });
|
||||
|
||||
function directoryNameFromRemoteUrl(url: string): string {
|
||||
const trimmed = url.trim().split(/[?#]/, 1)[0]?.replace(/[\\/]+$/g, "") ?? "";
|
||||
@@ -64,112 +73,185 @@
|
||||
if (isBusy) return;
|
||||
browseError = "";
|
||||
try {
|
||||
const selected = await openDialog({
|
||||
title: "Select clone destination",
|
||||
directory: true,
|
||||
multiple: false,
|
||||
defaultPath: parentPath.trim() || undefined,
|
||||
});
|
||||
if (typeof selected !== "string") return;
|
||||
parentPath = selected;
|
||||
} catch (error) {
|
||||
browseError = errorToMessage(error);
|
||||
}
|
||||
const selected = await openDialog({ title: isGerman ? "Zielordner zum Klonen auswählen" : "Select clone destination", directory: true, multiple: false, defaultPath: parentPath.trim() || undefined });
|
||||
if (typeof selected === "string") parentPath = selected;
|
||||
} catch (error) { browseError = errorToMessage(error); }
|
||||
}
|
||||
|
||||
function handleRemoteInput(event: Event) {
|
||||
const nextRemoteUrl = (event.currentTarget as HTMLInputElement).value;
|
||||
function setRemoteUrl(nextRemoteUrl: string) {
|
||||
remoteUrl = nextRemoteUrl;
|
||||
if (directoryNameEdited) return;
|
||||
directoryAutoName = directoryNameFromRemoteUrl(nextRemoteUrl);
|
||||
directoryName = directoryAutoName;
|
||||
}
|
||||
|
||||
function handleRemoteInput(event: Event) {
|
||||
setRemoteUrl((event.currentTarget as HTMLInputElement).value);
|
||||
selectedRepositoryId = "";
|
||||
}
|
||||
|
||||
function handleDirectoryInput(event: Event) {
|
||||
const nextDirectoryName = (event.currentTarget as HTMLInputElement).value;
|
||||
directoryNameEdited = nextDirectoryName.trim().length > 0 && nextDirectoryName !== directoryAutoName;
|
||||
}
|
||||
|
||||
function submit(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
onClone(remoteUrl.trim(), parentPath.trim(), directoryName.trim());
|
||||
function selectRepository(repository: GitIntegrationRepository) {
|
||||
selectedRepositoryId = repository.id;
|
||||
setRemoteUrl(repository.cloneUrl);
|
||||
}
|
||||
|
||||
function sortRepositories(repositories: GitIntegrationRepository[]): GitIntegrationRepository[] {
|
||||
return [...repositories].sort((left, right) => left.fullName.localeCompare(
|
||||
right.fullName,
|
||||
isGerman ? "de" : "en",
|
||||
{ numeric: true, sensitivity: "base" },
|
||||
));
|
||||
}
|
||||
|
||||
async function loadRepositories(integrationSource: GitIntegrationSource, force = false) {
|
||||
selectedSourceId = integrationSource.id;
|
||||
selectedRepositoryId = "";
|
||||
repositorySearch = "";
|
||||
repositoryError = "";
|
||||
if (!force && repositoriesBySource[integrationSource.id]) return;
|
||||
const requestId = ++repositoryRequestId;
|
||||
loadingSourceId = integrationSource.id;
|
||||
try {
|
||||
const repositories = await listIntegrationRepositories(integrationSource.provider, integrationSource.baseUrl, integrationSource.accountId);
|
||||
if (requestId === repositoryRequestId) repositoriesBySource = { ...repositoriesBySource, [integrationSource.id]: sortRepositories(repositories) };
|
||||
} catch (error) {
|
||||
if (requestId === repositoryRequestId) repositoryError = errorToMessage(error);
|
||||
} finally {
|
||||
if (requestId === repositoryRequestId) loadingSourceId = "";
|
||||
}
|
||||
}
|
||||
|
||||
function showIntegrations() {
|
||||
source = "integrations";
|
||||
const nextSource = configuredSources.find((candidate) => candidate.id === selectedSourceId) ?? configuredSources[0];
|
||||
if (nextSource) void loadRepositories(nextSource);
|
||||
}
|
||||
|
||||
function showUrlInput() {
|
||||
source = "url";
|
||||
selectedRepositoryId = "";
|
||||
}
|
||||
|
||||
function formatUpdatedAt(value: string): string {
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? "" : new Intl.DateTimeFormat(isGerman ? "de-DE" : "en-US", { dateStyle: "medium" }).format(date);
|
||||
}
|
||||
|
||||
function submit(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
if (canSubmit) onClone(remoteUrl.trim(), parentPath.trim(), directoryName.trim(), source === "integrations" ? activeSource?.provider : undefined, source === "integrations" ? activeSource?.accountId : undefined);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="dialog-backdrop" role="presentation">
|
||||
<div class="dialog clone-repository-dialog" role="dialog" aria-modal="true" aria-label="Clone repository" tabindex="-1">
|
||||
<div class="dialog clone-repository-dialog" role="dialog" aria-modal="true" aria-label={isGerman ? "Repository klonen" : "Clone repository"} tabindex="-1">
|
||||
<header class="dialog-header">
|
||||
<div>
|
||||
<span class="eyebrow">Repository Management</span>
|
||||
<h2 class="mt-0.5 text-ink text-base font-bold leading-tight">Clone repository</h2>
|
||||
</div>
|
||||
<button class="dialog-close" type="button" onclick={onClose} disabled={isBusy} title="Close">
|
||||
<X size={18} aria-hidden="true" />
|
||||
</button>
|
||||
<div><span class="eyebrow">Repository Management</span><h2 class="mt-0.5 text-ink text-base font-bold leading-tight">{isGerman ? "Repository klonen" : "Clone repository"}</h2></div>
|
||||
<button class="dialog-close" type="button" onclick={onClose} disabled={isBusy} title={isGerman ? "Schließen" : "Close"} aria-label={isGerman ? "Klonen schließen" : "Close clone dialog"}><X size={18} /></button>
|
||||
</header>
|
||||
|
||||
<form class="clone-dialog-form" onsubmit={submit}>
|
||||
<label class="clone-dialog-field">
|
||||
<span>Remote URL</span>
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input
|
||||
bind:value={remoteUrl}
|
||||
oninput={handleRemoteInput}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
placeholder="https://github.com/org/project.git"
|
||||
disabled={isBusy}
|
||||
autofocus
|
||||
/>
|
||||
</label>
|
||||
<div class="clone-source-tabs" role="tablist" aria-label={isGerman ? "Repository-Quelle" : "Repository source"}>
|
||||
<button type="button" role="tab" aria-selected={source === "url"} class:active={source === "url"} onclick={showUrlInput}><Globe2 size={15} />URL</button>
|
||||
<button type="button" role="tab" aria-selected={source === "integrations"} class:active={source === "integrations"} onclick={showIntegrations}><Cloud size={15} />{isGerman ? "Integrationen" : "Integrations"}{#if configuredSources.length}<em>{configuredSources.length}</em>{/if}</button>
|
||||
</div>
|
||||
|
||||
<label class="clone-dialog-field">
|
||||
<span>Destination</span>
|
||||
<div class="clone-dialog-path-field">
|
||||
<input
|
||||
bind:value={parentPath}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
placeholder="Choose parent folder"
|
||||
disabled={isBusy}
|
||||
/>
|
||||
<button class="btn-secondary" type="button" onclick={chooseParentFolder} disabled={isBusy}>
|
||||
<FolderOpen size={14} aria-hidden="true" />
|
||||
Browse
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label class="clone-dialog-field">
|
||||
<span>Folder name</span>
|
||||
<input
|
||||
bind:value={directoryName}
|
||||
oninput={handleDirectoryInput}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
placeholder={directorySuggestion || "Optional"}
|
||||
disabled={isBusy}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{#if visibleError}
|
||||
<div class="clone-dialog-error" role="alert">{visibleError}</div>
|
||||
{#if source === "url"}
|
||||
<label class="clone-dialog-field">
|
||||
<span>{isGerman ? "Remote-URL" : "Remote URL"}</span>
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input value={remoteUrl} oninput={handleRemoteInput} autocomplete="off" spellcheck="false" placeholder="https://gitlab.com/org/project.git" disabled={isBusy} autofocus />
|
||||
</label>
|
||||
{:else}
|
||||
<section class="integration-browser" aria-label={isGerman ? "Repositories aus Integrationen" : "Repositories from integrations"}>
|
||||
{#if configuredSources.length === 0}
|
||||
<div class="integration-empty"><Cloud size={26} /><strong>{isGerman ? "Keine aktive Integration" : "No active integration"}</strong><p>{isGerman ? "Richte unter Einstellungen → Integrationen zuerst GitLab, Azure DevOps oder Gitea ein." : "Set up GitLab, Azure DevOps, or Gitea under Settings → Integrations first."}</p></div>
|
||||
{:else}
|
||||
<div class="integration-provider-tabs" role="tablist" aria-label={isGerman ? "Konfigurierte Anbieter" : "Configured providers"}>
|
||||
{#each configuredSources as integrationSource}<button type="button" role="tab" aria-selected={selectedSourceId === integrationSource.id} class:active={selectedSourceId === integrationSource.id} onclick={() => loadRepositories(integrationSource)}>{integrationSource.provider === "azure-devops" ? `Azure · ${integrationSource.label}` : integrationSource.label}</button>{/each}
|
||||
</div>
|
||||
<div class="repository-toolbar">
|
||||
<label><Search size={14} /><input bind:value={repositorySearch} placeholder={isGerman ? "Repositories filtern…" : "Filter repositories…"} aria-label={isGerman ? "Repositories filtern" : "Filter repositories"} /></label>
|
||||
<button type="button" onclick={() => activeSource && loadRepositories(activeSource, true)} disabled={!activeSource || loadingSourceId.length > 0} title={isGerman ? "Neu laden" : "Refresh"} aria-label={isGerman ? "Repository-Liste neu laden" : "Refresh repository list"}><RefreshCw class={loadingSourceId ? "spin" : ""} size={14} /></button>
|
||||
</div>
|
||||
<div class="repository-list" aria-live="polite">
|
||||
{#if loadingSourceId}
|
||||
<div class="repository-state"><LoaderCircle class="spin" size={20} /><span>{isGerman ? "Repositories werden geladen…" : "Loading repositories…"}</span></div>
|
||||
{:else if repositoryError}
|
||||
<div class="repository-state repository-state-error"><strong>{isGerman ? "Repositories konnten nicht geladen werden" : "Could not load repositories"}</strong><span>{repositoryError}</span></div>
|
||||
{:else if filteredRepositories.length === 0}
|
||||
<div class="repository-state"><GitBranch size={20} /><span>{repositorySearch ? (isGerman ? "Keine passenden Repositories." : "No matching repositories.") : (isGerman ? "Keine Repositories gefunden." : "No repositories found.")}</span></div>
|
||||
{:else}
|
||||
{#each filteredRepositories as repository (repository.id)}
|
||||
<button type="button" class="repository-option" class:selected={selectedRepositoryId === repository.id} onclick={() => selectRepository(repository)}>
|
||||
<span class="repository-option-icon"><GitBranch size={16} /></span>
|
||||
<span class="repository-option-copy"><strong>{repository.fullName}</strong><small>{repository.description || repository.cloneUrl}</small></span>
|
||||
<span class="repository-option-meta">{#if repository.private}<LockKeyhole size={12} aria-label={isGerman ? "Privat" : "Private"} />{/if}{formatUpdatedAt(repository.updatedAt)}</span>
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
{#if selectedRepository}<div class="selected-repository"><span>{isGerman ? "Ausgewählt" : "Selected"}</span><strong>{selectedRepository.fullName}</strong><code>{selectedRepository.cloneUrl}</code></div>{/if}
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<div class="clone-dialog-actions">
|
||||
<button class="btn-secondary" type="button" onclick={onClose} disabled={isBusy}>
|
||||
Cancel
|
||||
</button>
|
||||
<button class="btn-primary" type="submit" disabled={!canSubmit}>
|
||||
{#if isBusy}
|
||||
<LoaderCircle class="spin" size={16} aria-hidden="true" />
|
||||
{:else}
|
||||
<Download size={16} aria-hidden="true" />
|
||||
{/if}
|
||||
Clone
|
||||
</button>
|
||||
<div class="clone-target-grid">
|
||||
<label class="clone-dialog-field"><span>{isGerman ? "Ziel" : "Destination"}</span><div class="clone-dialog-path-field"><input bind:value={parentPath} autocomplete="off" spellcheck="false" placeholder={isGerman ? "Übergeordneten Ordner auswählen" : "Choose parent folder"} disabled={isBusy} /><button class="btn-secondary" type="button" onclick={chooseParentFolder} disabled={isBusy}><FolderOpen size={14} />{isGerman ? "Durchsuchen" : "Browse"}</button></div></label>
|
||||
<label class="clone-dialog-field"><span>{isGerman ? "Ordnername" : "Folder name"}</span><input bind:value={directoryName} oninput={handleDirectoryInput} autocomplete="off" spellcheck="false" placeholder={directorySuggestion || "Optional"} disabled={isBusy} /></label>
|
||||
</div>
|
||||
|
||||
{#if visibleError}<div class="clone-dialog-error" role="alert">{visibleError}</div>{/if}
|
||||
<div class="clone-dialog-actions"><button class="btn-secondary" type="button" onclick={onClose} disabled={isBusy}>{isGerman ? "Abbrechen" : "Cancel"}</button><button class="btn-primary" type="submit" disabled={!canSubmit}>{#if isBusy}<LoaderCircle class="spin" size={16} />{:else}<Download size={16} />{/if}{isGerman ? "Klonen" : "Clone"}</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.clone-repository-dialog { width: min(760px, calc(100vw - 32px)); }
|
||||
.clone-source-tabs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px; padding: 4px; border: 1px solid var(--color-border-subtle); border-radius: 9px; background: var(--app-settings-row-bg); }
|
||||
.clone-source-tabs button { min-height: 36px; border-color: transparent; color: var(--color-ink-dim); background: transparent; font-size: 11px; font-weight: 800; }
|
||||
.clone-source-tabs button.active { border-color: var(--color-border-input); color: var(--color-ink); background: var(--color-surface-raised); box-shadow: 0 2px 8px rgba(0,0,0,.12); }
|
||||
.clone-source-tabs button.active :global(svg) { color: var(--color-accent); }
|
||||
.clone-source-tabs em { display: grid; place-items: center; min-width: 19px; height: 18px; padding: 0 5px; border-radius: 9px; color: var(--color-accent); background: color-mix(in srgb, var(--color-accent) 12%, transparent); font-size: 9px; font-style: normal; }
|
||||
.integration-browser { display: grid; gap: 9px; min-height: 270px; padding: 11px; border: 1px solid var(--color-border-subtle); border-radius: 10px; background: color-mix(in srgb, var(--app-settings-row-bg) 72%, transparent); }
|
||||
.integration-provider-tabs { display: flex; gap: 5px; overflow-x: auto; }
|
||||
.integration-provider-tabs button { flex: 0 0 auto; min-height: 29px; padding: 0 9px; border-color: transparent; color: var(--color-ink-dim); background: transparent; font-size: 10px; font-weight: 750; }
|
||||
.integration-provider-tabs button.active { border-color: color-mix(in srgb, var(--color-accent) 30%, var(--color-border)); color: var(--color-ink); background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface-raised)); }
|
||||
.repository-toolbar { display: grid; grid-template-columns: minmax(0, 1fr) 32px; gap: 6px; }
|
||||
.repository-toolbar label { position: relative; min-width: 0; }
|
||||
.repository-toolbar label > :global(svg) { position: absolute; z-index: 1; top: 10px; left: 10px; color: var(--color-ink-faint); }
|
||||
.repository-toolbar input { height: 34px; padding-left: 31px; font-size: 11px; }
|
||||
.repository-toolbar button { min-height: 32px; padding: 0; }
|
||||
.repository-list { min-height: 162px; max-height: 250px; overflow: auto; border: 1px solid var(--color-border-subtle); border-radius: 8px; background: var(--color-surface-raised); }
|
||||
.repository-option { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 9px; width: 100%; min-height: 52px; padding: 7px 9px; border: 0; border-bottom: 1px solid var(--color-border-subtle); border-radius: 0; color: var(--color-ink-dim); background: transparent; text-align: left; }
|
||||
.repository-option:last-child { border-bottom: 0; }
|
||||
.repository-option:hover { color: var(--color-ink); background: var(--color-surface-hover); }
|
||||
.repository-option.selected { color: var(--color-ink); background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface-hover)); box-shadow: inset 2px 0 0 var(--color-accent); }
|
||||
.repository-option-icon { display: grid; place-items: center; width: 30px; height: 30px; border: 1px solid var(--color-border-subtle); border-radius: 7px; color: var(--color-accent); background: color-mix(in srgb, var(--color-accent) 7%, transparent); }
|
||||
.repository-option-copy { display: grid; min-width: 0; gap: 3px; }
|
||||
.repository-option-copy strong, .repository-option-copy small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.repository-option-copy strong { color: inherit; font-size: 10.5px; }
|
||||
.repository-option-copy small { color: var(--color-ink-faint); font-size: 9px; }
|
||||
.repository-option-meta { display: flex; align-items: center; gap: 5px; color: var(--color-ink-faint); font-size: 8.5px; }
|
||||
.repository-state, .integration-empty { display: grid; place-items: center; align-content: center; min-height: 160px; padding: 20px; color: var(--color-ink-faint); text-align: center; }
|
||||
.repository-state { gap: 7px; font-size: 10.5px; }
|
||||
.repository-state strong, .integration-empty strong { color: var(--color-ink); font-size: 11px; }
|
||||
.repository-state-error strong { color: #e86060; }
|
||||
.repository-state-error span { max-width: 520px; line-height: 1.45; }
|
||||
.integration-empty { min-height: 235px; gap: 8px; }
|
||||
.integration-empty :global(svg) { color: var(--color-accent); }
|
||||
.integration-empty p { max-width: 400px; margin: 0; color: var(--color-ink-faint); font-size: 10px; line-height: 1.5; }
|
||||
.selected-repository { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 3px 8px; min-width: 0; padding: 8px 9px; border-left: 2px solid var(--color-accent); background: color-mix(in srgb, var(--color-accent) 6%, transparent); }
|
||||
.selected-repository span { color: var(--color-accent); font-size: 8.5px; font-weight: 850; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.selected-repository strong { overflow: hidden; color: var(--color-ink); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.selected-repository code { grid-column: 2; overflow: hidden; color: var(--color-ink-faint); font: 8.5px var(--font-mono); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.clone-target-grid { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(150px, .75fr); gap: 10px; }
|
||||
@media (max-width: 620px) { .clone-repository-dialog { width: min(620px, calc(100vw - 20px)); } .clone-target-grid { grid-template-columns: 1fr; } .repository-option-meta { display: none; } }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
<script lang="ts">
|
||||
import { Building2, CheckCircle2, CircleDashed, Eye, EyeOff, KeyRound, Plus, Server, Trash2 } from "@lucide/svelte";
|
||||
import { siGitea, siGitlab, type SimpleIcon } from "simple-icons";
|
||||
import { gitIntegrationProviders, organizationNameFromUrl, providerLabel } from "../integrations";
|
||||
import type { AppLanguage, AzureDevOpsOrganization, GitIntegrationConfig, GitIntegrationProvider, GitIntegrationSecretUpdate, GitIntegrationSettings } from "../types";
|
||||
|
||||
interface Props {
|
||||
language: AppLanguage;
|
||||
settings: GitIntegrationSettings;
|
||||
onChange: (settings: GitIntegrationSettings) => void;
|
||||
onSecretsChange: (updates: GitIntegrationSecretUpdate[]) => void;
|
||||
}
|
||||
|
||||
let { language, settings, onChange, onSecretsChange }: Props = $props();
|
||||
let selected = $state<GitIntegrationProvider>("gitlab");
|
||||
let selectedAzureOrganizationId = $state("");
|
||||
let tokenValues = $state<Record<string, string>>({});
|
||||
let secretUpdates = $state<Record<string, GitIntegrationSecretUpdate>>({});
|
||||
let showToken = $state(false);
|
||||
|
||||
const isGerman = $derived(language === "de");
|
||||
const selectedAzureOrganization = $derived(settings.azureDevOpsOrganizations.find((organization) => organization.id === selectedAzureOrganizationId));
|
||||
const current = $derived<GitIntegrationConfig | AzureDevOpsOrganization | undefined>(selected === "azure-devops" ? selectedAzureOrganization : settings.providers[selected]);
|
||||
const currentAccountId = $derived(selected === "azure-devops" ? selectedAzureOrganization?.id : undefined);
|
||||
|
||||
const azureDevOpsIcon: SimpleIcon = {
|
||||
title: "Azure DevOps", slug: "azuredevops", hex: "0078D4", source: "https://azure.microsoft.com/products/devops", svg: "",
|
||||
path: "M0 8.877 2.247 5.91l8.405-3.416v19.127l-8.405-3.53L0 15.123V8.877Zm12.154-6.968 11.846 2.423v15.336l-11.846 2.423V1.909Z",
|
||||
};
|
||||
const providerIcons: Record<GitIntegrationProvider, SimpleIcon> = { gitlab: siGitlab, "gitlab-self-hosted": siGitlab, "azure-devops": azureDevOpsIcon, gitea: siGitea };
|
||||
|
||||
function providerDescription(provider: GitIntegrationProvider): string {
|
||||
const descriptions = isGerman
|
||||
? { gitlab: "Cloud-Konto auf gitlab.com", "gitlab-self-hosted": "Eigene GitLab-Instanz", "azure-devops": "Mehrere Organisationen", gitea: "Cloud- oder eigene Instanz" }
|
||||
: { gitlab: "Cloud account on gitlab.com", "gitlab-self-hosted": "Your own GitLab instance", "azure-devops": "Multiple organizations", gitea: "Cloud or self-hosted instance" };
|
||||
return descriptions[provider];
|
||||
}
|
||||
|
||||
function secretId(provider: GitIntegrationProvider, accountId?: string): string {
|
||||
return accountId ? `${provider}:${accountId}` : provider;
|
||||
}
|
||||
|
||||
function emitSecrets() {
|
||||
onSecretsChange(Object.values(secretUpdates));
|
||||
}
|
||||
|
||||
function updateCurrent(patch: Partial<GitIntegrationConfig & AzureDevOpsOrganization>) {
|
||||
if (!current) return;
|
||||
if (selected === "azure-devops" && selectedAzureOrganization) {
|
||||
onChange({
|
||||
...settings,
|
||||
azureDevOpsOrganizations: settings.azureDevOpsOrganizations.map((organization) => organization.id === selectedAzureOrganization.id ? { ...organization, ...patch } : organization),
|
||||
});
|
||||
return;
|
||||
}
|
||||
onChange({ ...settings, providers: { ...settings.providers, [selected]: { ...settings.providers[selected], ...patch } } });
|
||||
}
|
||||
|
||||
function setToken(value: string) {
|
||||
if (!current) return;
|
||||
const id = secretId(selected, currentAccountId);
|
||||
tokenValues[id] = value;
|
||||
if (value.trim()) secretUpdates[id] = { provider: selected, accountId: currentAccountId, token: value };
|
||||
else delete secretUpdates[id];
|
||||
tokenValues = { ...tokenValues };
|
||||
secretUpdates = { ...secretUpdates };
|
||||
emitSecrets();
|
||||
}
|
||||
|
||||
function forgetToken() {
|
||||
if (!current) return;
|
||||
const id = secretId(selected, currentAccountId);
|
||||
tokenValues[id] = "";
|
||||
secretUpdates[id] = { provider: selected, accountId: currentAccountId, removeToken: true };
|
||||
tokenValues = { ...tokenValues };
|
||||
secretUpdates = { ...secretUpdates };
|
||||
updateCurrent({ enabled: false, tokenStored: false });
|
||||
emitSecrets();
|
||||
}
|
||||
|
||||
function pendingRemoval(provider: GitIntegrationProvider, accountId?: string): boolean {
|
||||
return secretUpdates[secretId(provider, accountId)]?.removeToken === true;
|
||||
}
|
||||
|
||||
function tokenValue(): string {
|
||||
return tokenValues[secretId(selected, currentAccountId)] ?? "";
|
||||
}
|
||||
|
||||
function selectProvider(provider: GitIntegrationProvider) {
|
||||
selected = provider;
|
||||
showToken = false;
|
||||
if (provider === "azure-devops" && !settings.azureDevOpsOrganizations.some((organization) => organization.id === selectedAzureOrganizationId)) {
|
||||
selectedAzureOrganizationId = settings.azureDevOpsOrganizations[0]?.id ?? "";
|
||||
}
|
||||
}
|
||||
|
||||
function createOrganizationId(): string {
|
||||
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
|
||||
return `org-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function addAzureOrganization() {
|
||||
const id = createOrganizationId();
|
||||
const number = settings.azureDevOpsOrganizations.length + 1;
|
||||
const organization: AzureDevOpsOrganization = {
|
||||
id,
|
||||
name: isGerman ? `Organisation ${number}` : `Organization ${number}`,
|
||||
enabled: true,
|
||||
baseUrl: "https://dev.azure.com/",
|
||||
username: "",
|
||||
tokenStored: false,
|
||||
};
|
||||
onChange({ ...settings, azureDevOpsOrganizations: [...settings.azureDevOpsOrganizations, organization] });
|
||||
selectedAzureOrganizationId = id;
|
||||
showToken = false;
|
||||
}
|
||||
|
||||
function removeAzureOrganization(organization: AzureDevOpsOrganization) {
|
||||
const id = secretId("azure-devops", organization.id);
|
||||
if (organization.tokenStored) secretUpdates[id] = { provider: "azure-devops", accountId: organization.id, removeToken: true };
|
||||
else delete secretUpdates[id];
|
||||
delete tokenValues[id];
|
||||
secretUpdates = { ...secretUpdates };
|
||||
tokenValues = { ...tokenValues };
|
||||
const remaining = settings.azureDevOpsOrganizations.filter((candidate) => candidate.id !== organization.id);
|
||||
onChange({ ...settings, azureDevOpsOrganizations: remaining });
|
||||
selectedAzureOrganizationId = remaining[0]?.id ?? "";
|
||||
showToken = false;
|
||||
emitSecrets();
|
||||
}
|
||||
|
||||
function organizationDisplayName(organization: AzureDevOpsOrganization): string {
|
||||
return organization.name.trim() || organizationNameFromUrl(organization.baseUrl) || (isGerman ? "Unbenannte Organisation" : "Unnamed organization");
|
||||
}
|
||||
|
||||
function isOrganizationConfigured(organization: AzureDevOpsOrganization): boolean {
|
||||
return organization.tokenStored && organization.baseUrl.trim().length > 0 && !pendingRemoval("azure-devops", organization.id);
|
||||
}
|
||||
|
||||
function isConfigured(provider: GitIntegrationProvider): boolean {
|
||||
if (provider === "azure-devops") return settings.azureDevOpsOrganizations.some(isOrganizationConfigured);
|
||||
const config = settings.providers[provider];
|
||||
return config.tokenStored && config.baseUrl.trim().length > 0 && !pendingRemoval(provider);
|
||||
}
|
||||
|
||||
function currentConfigured(): boolean {
|
||||
if (!current) return false;
|
||||
return current.tokenStored && current.baseUrl.trim().length > 0 && !pendingRemoval(selected, currentAccountId);
|
||||
}
|
||||
|
||||
function baseUrlPlaceholder(): string {
|
||||
if (selected === "azure-devops") return "https://dev.azure.com/meine-organisation";
|
||||
if (selected === "gitlab") return "https://gitlab.com";
|
||||
if (selected === "gitlab-self-hosted") return "https://gitlab.example.com";
|
||||
return "https://gitea.example.com";
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="integration-layout">
|
||||
<div class="integration-providers" role="tablist" aria-label={isGerman ? "Git-Anbieter" : "Git providers"}>
|
||||
{#each gitIntegrationProviders as provider}
|
||||
<button type="button" role="tab" aria-selected={selected === provider} class:active={selected === provider} onclick={() => selectProvider(provider)}>
|
||||
<span class="provider-logo" style={`--provider-color:#${providerIcons[provider].hex}`}><svg viewBox="0 0 24 24" aria-hidden="true"><path d={providerIcons[provider].path} /></svg></span>
|
||||
<span class="provider-copy"><strong>{providerLabel(provider)}</strong><small>{providerDescription(provider)}</small></span>
|
||||
<span class="provider-state" class:configured={isConfigured(provider)} title={isConfigured(provider) ? (isGerman ? "Konfiguriert" : "Configured") : (isGerman ? "Nicht verbunden" : "Not connected")}></span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<section class="integration-config" aria-label={`${providerLabel(selected)} ${isGerman ? "konfigurieren" : "configuration"}`}>
|
||||
<header class="integration-summary">
|
||||
<span class="provider-logo provider-logo-large" style={`--provider-color:#${providerIcons[selected].hex}`}><svg viewBox="0 0 24 24" aria-hidden="true"><path d={providerIcons[selected].path} /></svg></span>
|
||||
<div><h4>{providerLabel(selected)}</h4><p>{providerDescription(selected)}</p></div>
|
||||
{#if selected === "azure-devops"}
|
||||
<span class="integration-status" class:configured={isConfigured(selected)}><Building2 size={13} />{settings.azureDevOpsOrganizations.length} {isGerman ? "Orgas" : "orgs"}</span>
|
||||
{:else}
|
||||
<span class="integration-status" class:configured={currentConfigured()}>{#if currentConfigured()}<CheckCircle2 size={13} />{:else}<CircleDashed size={13} />{/if}{currentConfigured() ? (isGerman ? "Konfiguriert" : "Configured") : (isGerman ? "Nicht verbunden" : "Not connected")}</span>
|
||||
{/if}
|
||||
</header>
|
||||
|
||||
{#if selected === "azure-devops"}
|
||||
<div class="azure-organizations">
|
||||
<div class="azure-organizations-head"><div><strong>{isGerman ? "Organisationen" : "Organizations"}</strong><small>{isGerman ? "Jede Organisation verwendet einen eigenen Token." : "Each organization uses its own token."}</small></div><button type="button" onclick={addAzureOrganization}><Plus size={14} />{isGerman ? "Hinzufügen" : "Add"}</button></div>
|
||||
{#if settings.azureDevOpsOrganizations.length === 0}
|
||||
<div class="azure-organizations-empty"><Building2 size={22} /><span>{isGerman ? "Noch keine Azure-DevOps-Organisation angelegt." : "No Azure DevOps organization has been added yet."}</span><button type="button" onclick={addAzureOrganization}><Plus size={14} />{isGerman ? "Erste Organisation anlegen" : "Add first organization"}</button></div>
|
||||
{:else}
|
||||
<div class="azure-organization-list" role="tablist" aria-label={isGerman ? "Azure-DevOps-Organisationen" : "Azure DevOps organizations"}>
|
||||
{#each settings.azureDevOpsOrganizations as organization (organization.id)}
|
||||
<div class="azure-organization-row" class:active={selectedAzureOrganizationId === organization.id}>
|
||||
<button type="button" role="tab" aria-selected={selectedAzureOrganizationId === organization.id} onclick={() => { selectedAzureOrganizationId = organization.id; showToken = false; }}>
|
||||
<span><strong>{organizationDisplayName(organization)}</strong><small>{organization.baseUrl}</small></span><i class:configured={isOrganizationConfigured(organization)}></i>
|
||||
</button>
|
||||
<button class="azure-remove" type="button" onclick={() => removeAzureOrganization(organization)} title={isGerman ? "Organisation entfernen" : "Remove organization"} aria-label={`${organizationDisplayName(organization)} ${isGerman ? "entfernen" : "remove"}`}><Trash2 size={13} /></button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if current}
|
||||
{#if selected === "azure-devops"}
|
||||
<label class="integration-field"><span><Building2 size={13} />{isGerman ? "Anzeigename" : "Display name"}</span><input value={selectedAzureOrganization?.name ?? ""} oninput={(event) => updateCurrent({ name: event.currentTarget.value })} placeholder={isGerman ? "z. B. Contoso Platform" : "e.g. Contoso Platform"} /></label>
|
||||
{/if}
|
||||
|
||||
<label class="integration-field">
|
||||
<span><Server size={13} />{selected === "azure-devops" ? (isGerman ? "Organisations-URL" : "Organization URL") : (isGerman ? "Server-URL" : "Server URL")}</span>
|
||||
<input value={current.baseUrl} oninput={(event) => updateCurrent({ baseUrl: event.currentTarget.value })} placeholder={baseUrlPlaceholder()} spellcheck="false" inputmode="url" />
|
||||
<small>{isGerman ? "Basis-URL ohne Repository-Pfad." : "Base URL without a repository path."}</small>
|
||||
</label>
|
||||
|
||||
<label class="integration-field"><span>{isGerman ? "Benutzername oder E-Mail" : "Username or email"}</span><input value={current.username} oninput={(event) => updateCurrent({ username: event.currentTarget.value })} autocomplete="off" placeholder={selected === "azure-devops" ? "name@example.com" : (isGerman ? "Benutzername" : "Username")} spellcheck="false" /></label>
|
||||
|
||||
<label class="integration-field">
|
||||
<span><KeyRound size={13} />Personal Access Token</span>
|
||||
<div class="token-row"><input type={showToken ? "text" : "password"} value={tokenValue()} oninput={(event) => setToken(event.currentTarget.value)} autocomplete="new-password" placeholder={current.tokenStored && !pendingRemoval(selected, currentAccountId) ? (isGerman ? "Token ist sicher gespeichert" : "Token is stored securely") : (isGerman ? "Token einfügen" : "Paste token")} spellcheck="false" /><button type="button" onclick={() => { showToken = !showToken; }} title={showToken ? (isGerman ? "Token ausblenden" : "Hide token") : (isGerman ? "Token anzeigen" : "Show token")} aria-label={showToken ? (isGerman ? "Token ausblenden" : "Hide token") : (isGerman ? "Token anzeigen" : "Show token")}>{#if showToken}<EyeOff size={15} />{:else}<Eye size={15} />{/if}</button></div>
|
||||
<small>{isGerman ? "Der Token wird separat im Schlüsselbund des Betriebssystems gespeichert." : "The token is stored separately in the operating system keychain."}</small>
|
||||
</label>
|
||||
|
||||
<div class="integration-actions">
|
||||
<label class="integration-enabled"><span><strong>{selected === "azure-devops" ? (isGerman ? "Organisation aktivieren" : "Enable organization") : (isGerman ? "Integration aktivieren" : "Enable integration")}</strong><small>{isGerman ? "Für Hosting- und Clone-Funktionen verwenden." : "Use for hosting and clone features."}</small></span><input type="checkbox" checked={current.enabled} onchange={(event) => updateCurrent({ enabled: event.currentTarget.checked })} /></label>
|
||||
{#if current.tokenStored && !pendingRemoval(selected, currentAccountId)}<button class="forget-token" type="button" onclick={forgetToken}><Trash2 size={14} />{isGerman ? "Gespeicherten Token entfernen" : "Remove stored token"}</button>{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.integration-layout { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 14px; min-height: 420px; }
|
||||
.integration-providers { display: flex; flex-direction: column; gap: 5px; }
|
||||
.integration-providers > button { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; min-height: 64px; padding: 9px 10px; border: 1px solid var(--color-border-subtle); border-radius: 9px; color: var(--color-ink-dim); background: var(--app-settings-row-bg); text-align: left; }
|
||||
.integration-providers > button:hover { color: var(--color-ink); border-color: var(--color-border); background: var(--color-surface-hover); }
|
||||
.integration-providers > button.active { border-color: color-mix(in srgb, var(--color-accent) 34%, var(--color-border)); color: var(--color-ink); background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface-raised)); box-shadow: inset 2px 0 0 var(--color-accent); }
|
||||
.provider-logo { display: grid; place-items: center; width: 32px; height: 32px; border: 1px solid color-mix(in srgb, var(--provider-color) 34%, var(--color-border)); border-radius: 8px; color: var(--provider-color); background: color-mix(in srgb, var(--provider-color) 10%, transparent); }
|
||||
.provider-logo svg { width: 17px; height: 17px; fill: currentColor; }
|
||||
.provider-logo-large { width: 42px; height: 42px; border-radius: 10px; }
|
||||
.provider-logo-large svg { width: 22px; height: 22px; }
|
||||
.provider-copy { display: grid; min-width: 0; gap: 3px; }
|
||||
.provider-copy strong { color: inherit; font-size: 11px; }
|
||||
.provider-copy small { overflow: hidden; color: var(--color-ink-faint); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.provider-state { width: 7px; height: 7px; border-radius: 50%; background: var(--color-ink-faint); }
|
||||
.provider-state.configured { background: var(--color-success); box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-success) 12%, transparent); }
|
||||
.integration-config { display: grid; align-content: start; gap: 13px; min-width: 0; padding: 16px; border: 1px solid var(--color-border-subtle); border-radius: 12px; background: color-mix(in srgb, var(--app-settings-row-bg) 72%, transparent); }
|
||||
.integration-summary { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 11px; padding-bottom: 13px; border-bottom: 1px solid var(--color-border-subtle); }
|
||||
.integration-summary h4 { margin: 0; color: var(--color-ink); font-size: 14px; }
|
||||
.integration-summary p { margin: 3px 0 0; color: var(--color-ink-dim); font-size: 10.5px; }
|
||||
.integration-status { display: inline-flex; align-items: center; gap: 5px; padding: 5px 7px; border: 1px solid var(--color-border-subtle); border-radius: 6px; color: var(--color-ink-faint); font-size: 9px; font-weight: 750; }
|
||||
.integration-status.configured { border-color: color-mix(in srgb, var(--color-success) 24%, var(--color-border)); color: var(--color-success); background: color-mix(in srgb, var(--color-success) 6%, transparent); }
|
||||
.azure-organizations { display: grid; gap: 8px; padding: 10px; border: 1px solid var(--color-border-subtle); border-radius: 9px; background: var(--color-surface-raised); }
|
||||
.azure-organizations-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.azure-organizations-head > div { display: grid; gap: 2px; }
|
||||
.azure-organizations-head strong { color: var(--color-ink); font-size: 10.5px; }
|
||||
.azure-organizations-head small { color: var(--color-ink-faint); font-size: 8.5px; }
|
||||
.azure-organizations-head button, .azure-organizations-empty button { min-height: 27px; padding: 0 8px; font-size: 9.5px; font-weight: 750; }
|
||||
.azure-organization-list { display: grid; gap: 5px; max-height: 142px; overflow: auto; }
|
||||
.azure-organization-row { display: grid; grid-template-columns: minmax(0, 1fr) 30px; gap: 4px; border: 1px solid var(--color-border-subtle); border-radius: 7px; background: color-mix(in srgb, var(--app-settings-row-bg) 72%, transparent); }
|
||||
.azure-organization-row.active { border-color: color-mix(in srgb, var(--color-accent) 38%, var(--color-border)); box-shadow: inset 2px 0 0 var(--color-accent); }
|
||||
.azure-organization-row > button:first-child { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; min-height: 42px; padding: 5px 8px; border: 0; color: var(--color-ink-dim); background: transparent; text-align: left; }
|
||||
.azure-organization-row > button:first-child span { display: grid; min-width: 0; gap: 2px; }
|
||||
.azure-organization-row strong, .azure-organization-row small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.azure-organization-row strong { color: var(--color-ink); font-size: 10px; }
|
||||
.azure-organization-row small { color: var(--color-ink-faint); font-size: 8.5px; }
|
||||
.azure-organization-row i { width: 6px; height: 6px; border-radius: 50%; background: var(--color-ink-faint); }
|
||||
.azure-organization-row i.configured { background: var(--color-success); }
|
||||
.azure-remove { min-height: 30px; align-self: center; padding: 0; border: 0; color: var(--color-ink-faint); background: transparent; }
|
||||
.azure-remove:hover { color: #e86060; background: color-mix(in srgb, #e86060 8%, transparent); }
|
||||
.azure-organizations-empty { display: grid; place-items: center; gap: 7px; padding: 14px; color: var(--color-ink-faint); text-align: center; }
|
||||
.azure-organizations-empty > :global(svg) { color: var(--color-accent); }
|
||||
.azure-organizations-empty span { font-size: 9.5px; }
|
||||
.integration-field { display: grid; gap: 6px; min-width: 0; color: var(--color-ink-muted); font-size: 10.5px; font-weight: 750; }
|
||||
.integration-field > span { display: flex; align-items: center; gap: 5px; }
|
||||
.integration-field input { height: 36px; border-color: var(--color-border); background: var(--color-surface-raised); font-size: 11px; }
|
||||
.integration-field small { color: var(--color-ink-faint); font-size: 9.5px; font-weight: 500; }
|
||||
.token-row { display: grid; grid-template-columns: minmax(0, 1fr) 36px; gap: 6px; }
|
||||
.token-row button { display: grid; place-items: center; min-height: 36px; padding: 0; }
|
||||
.integration-actions { display: grid; gap: 10px; padding-top: 2px; }
|
||||
.integration-enabled { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 14px; padding: 11px 12px; border: 1px solid var(--color-border-subtle); border-radius: 8px; background: var(--color-surface-raised); }
|
||||
.integration-enabled > span { display: grid; gap: 3px; }
|
||||
.integration-enabled strong { color: var(--color-ink); font-size: 10.5px; }
|
||||
.integration-enabled small { color: var(--color-ink-faint); font-size: 9px; }
|
||||
.integration-enabled input { width: 32px; height: 18px; accent-color: var(--color-accent); }
|
||||
.forget-token { justify-self: start; min-height: 28px; color: #e86060; font-size: 10px; }
|
||||
@media (max-width: 680px) { .integration-layout { grid-template-columns: 1fr; min-height: 0; } .integration-providers { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } .integration-providers > button { min-height: 54px; } .provider-copy small { display: none; } }
|
||||
@media (max-width: 430px) { .integration-providers { grid-template-columns: 1fr; } .integration-summary { grid-template-columns: auto minmax(0, 1fr); } .integration-status { grid-column: 1 / -1; justify-self: start; } .azure-organizations-head { align-items: stretch; flex-direction: column; } .azure-organizations-head button { align-self: start; } }
|
||||
</style>
|
||||
@@ -15,6 +15,8 @@ import type {
|
||||
GitCommit,
|
||||
GitCommitComparison,
|
||||
GitIgnoreKind,
|
||||
GitIntegrationProvider,
|
||||
GitIntegrationRepository,
|
||||
GitLfsStatus,
|
||||
GitRepositoryFile,
|
||||
GitRemote,
|
||||
@@ -54,6 +56,10 @@ export function detectExternalTools(): Promise<DetectedExternalTool[]> {
|
||||
return invoke<DetectedExternalTool[]>("detect_external_tools");
|
||||
}
|
||||
|
||||
export function listIntegrationRepositories(provider: GitIntegrationProvider, baseUrl: string, accountId?: string): Promise<GitIntegrationRepository[]> {
|
||||
return invoke<GitIntegrationRepository[]>("list_integration_repositories", { provider, baseUrl, accountId: accountId ?? null });
|
||||
}
|
||||
|
||||
export function launchExternalTool(path: string, command: ExternalToolCommand, file?: string): Promise<void> {
|
||||
return invoke<void>("launch_external_tool", { path, file: file ?? null, command });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import type {
|
||||
AzureDevOpsOrganization,
|
||||
GitIntegrationConfig,
|
||||
GitIntegrationProvider,
|
||||
GitIntegrationSource,
|
||||
GitIntegrationSettings,
|
||||
} from "./types";
|
||||
|
||||
export const gitIntegrationProviders: GitIntegrationProvider[] = [
|
||||
"gitlab",
|
||||
"gitlab-self-hosted",
|
||||
"azure-devops",
|
||||
"gitea",
|
||||
];
|
||||
|
||||
const defaults: Record<GitIntegrationProvider, Omit<GitIntegrationConfig, "provider">> = {
|
||||
gitlab: {
|
||||
enabled: false,
|
||||
baseUrl: "https://gitlab.com",
|
||||
username: "",
|
||||
tokenStored: false,
|
||||
},
|
||||
"gitlab-self-hosted": {
|
||||
enabled: false,
|
||||
baseUrl: "",
|
||||
username: "",
|
||||
tokenStored: false,
|
||||
},
|
||||
"azure-devops": {
|
||||
enabled: false,
|
||||
baseUrl: "https://dev.azure.com/",
|
||||
username: "",
|
||||
tokenStored: false,
|
||||
},
|
||||
gitea: {
|
||||
enabled: false,
|
||||
baseUrl: "",
|
||||
username: "",
|
||||
tokenStored: false,
|
||||
},
|
||||
};
|
||||
|
||||
export function defaultGitIntegrationSettings(): GitIntegrationSettings {
|
||||
return {
|
||||
providers: Object.fromEntries(
|
||||
gitIntegrationProviders.map((provider) => [provider, { provider, ...defaults[provider] }]),
|
||||
) as GitIntegrationSettings["providers"],
|
||||
azureDevOpsOrganizations: [],
|
||||
};
|
||||
}
|
||||
|
||||
function normaliseAzureOrganization(value: unknown): AzureDevOpsOrganization | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const stored = value as Partial<AzureDevOpsOrganization>;
|
||||
const id = typeof stored.id === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(stored.id) ? stored.id : "";
|
||||
if (!id) return null;
|
||||
return {
|
||||
id,
|
||||
name: typeof stored.name === "string" ? stored.name : "",
|
||||
enabled: stored.enabled === true,
|
||||
baseUrl: typeof stored.baseUrl === "string" ? stored.baseUrl : "",
|
||||
username: typeof stored.username === "string" ? stored.username : "",
|
||||
tokenStored: stored.tokenStored === true,
|
||||
};
|
||||
}
|
||||
|
||||
export function normaliseGitIntegrationSettings(value: unknown): GitIntegrationSettings {
|
||||
const fallback = defaultGitIntegrationSettings();
|
||||
if (!value || typeof value !== "object") return fallback;
|
||||
const storedProviders = (value as Partial<GitIntegrationSettings>).providers;
|
||||
if (!storedProviders || typeof storedProviders !== "object") return fallback;
|
||||
|
||||
for (const provider of gitIntegrationProviders) {
|
||||
const stored = storedProviders[provider] as Partial<GitIntegrationConfig> | undefined;
|
||||
if (!stored || typeof stored !== "object") continue;
|
||||
fallback.providers[provider] = {
|
||||
provider,
|
||||
enabled: stored.enabled === true,
|
||||
baseUrl: typeof stored.baseUrl === "string" ? stored.baseUrl : fallback.providers[provider].baseUrl,
|
||||
username: typeof stored.username === "string" ? stored.username : "",
|
||||
tokenStored: stored.tokenStored === true,
|
||||
};
|
||||
}
|
||||
|
||||
const storedOrganizations = (value as Partial<GitIntegrationSettings>).azureDevOpsOrganizations;
|
||||
if (Array.isArray(storedOrganizations)) {
|
||||
const seen = new Set<string>();
|
||||
fallback.azureDevOpsOrganizations = storedOrganizations
|
||||
.map(normaliseAzureOrganization)
|
||||
.filter((organization): organization is AzureDevOpsOrganization => {
|
||||
if (!organization || seen.has(organization.id)) return false;
|
||||
seen.add(organization.id);
|
||||
return true;
|
||||
});
|
||||
} else {
|
||||
const legacy = fallback.providers["azure-devops"];
|
||||
const hasLegacyConfiguration = legacy.enabled || legacy.tokenStored || legacy.username.trim().length > 0 || !/^https:\/\/dev\.azure\.com\/?$/i.test(legacy.baseUrl.trim());
|
||||
if (hasLegacyConfiguration) {
|
||||
fallback.azureDevOpsOrganizations = [{
|
||||
id: "default",
|
||||
name: "Azure DevOps",
|
||||
enabled: legacy.enabled,
|
||||
baseUrl: legacy.baseUrl,
|
||||
username: legacy.username,
|
||||
tokenStored: legacy.tokenStored,
|
||||
}];
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function integrationCredentialKey(provider: GitIntegrationProvider, accountId?: string): string {
|
||||
if (provider === "azure-devops" && accountId && accountId !== "default") {
|
||||
return `integration:${provider}:${accountId}`;
|
||||
}
|
||||
return `integration:${provider}`;
|
||||
}
|
||||
|
||||
export function configuredIntegrationSources(settings: GitIntegrationSettings): GitIntegrationSource[] {
|
||||
const sources: GitIntegrationSource[] = [];
|
||||
for (const provider of gitIntegrationProviders) {
|
||||
if (provider === "azure-devops") continue;
|
||||
const config = settings.providers[provider];
|
||||
if (config.enabled && config.tokenStored && config.baseUrl.trim()) {
|
||||
sources.push({ id: provider, provider, label: providerLabel(provider), baseUrl: config.baseUrl });
|
||||
}
|
||||
}
|
||||
for (const organization of settings.azureDevOpsOrganizations) {
|
||||
if (!organization.enabled || !organization.tokenStored || !organization.baseUrl.trim()) continue;
|
||||
sources.push({
|
||||
id: `azure-devops:${organization.id}`,
|
||||
provider: "azure-devops",
|
||||
accountId: organization.id,
|
||||
label: organization.name.trim() || organizationNameFromUrl(organization.baseUrl) || "Azure DevOps",
|
||||
baseUrl: organization.baseUrl,
|
||||
});
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
export function configuredIntegrationCount(settings: GitIntegrationSettings): number {
|
||||
return configuredIntegrationSources(settings).length;
|
||||
}
|
||||
|
||||
export function providerLabel(provider: GitIntegrationProvider): string {
|
||||
return {
|
||||
gitlab: "GitLab.com",
|
||||
"gitlab-self-hosted": "GitLab Self-Managed",
|
||||
"azure-devops": "Azure DevOps",
|
||||
gitea: "Gitea",
|
||||
}[provider];
|
||||
}
|
||||
|
||||
export function organizationNameFromUrl(value: string): string {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.pathname.split("/").filter(Boolean)[0] ?? "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,57 @@ export type AppTheme = "system" | "light" | "dark";
|
||||
export type AppAppearance = "modern" | "classic" | "custom";
|
||||
export type AppLanguage = "en" | "de";
|
||||
|
||||
export type GitIntegrationProvider = "gitlab" | "gitlab-self-hosted" | "azure-devops" | "gitea";
|
||||
|
||||
export interface GitIntegrationConfig {
|
||||
provider: GitIntegrationProvider;
|
||||
enabled: boolean;
|
||||
baseUrl: string;
|
||||
username: string;
|
||||
tokenStored: boolean;
|
||||
}
|
||||
|
||||
export interface GitIntegrationSettings {
|
||||
providers: Record<GitIntegrationProvider, GitIntegrationConfig>;
|
||||
azureDevOpsOrganizations: AzureDevOpsOrganization[];
|
||||
}
|
||||
|
||||
export interface AzureDevOpsOrganization {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
baseUrl: string;
|
||||
username: string;
|
||||
tokenStored: boolean;
|
||||
}
|
||||
|
||||
export interface GitIntegrationSecretUpdate {
|
||||
provider: GitIntegrationProvider;
|
||||
accountId?: string;
|
||||
token?: string;
|
||||
removeToken?: boolean;
|
||||
}
|
||||
|
||||
export interface GitIntegrationSource {
|
||||
id: string;
|
||||
provider: GitIntegrationProvider;
|
||||
accountId?: string;
|
||||
label: string;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
export interface GitIntegrationRepository {
|
||||
id: string;
|
||||
name: string;
|
||||
fullName: string;
|
||||
description: string;
|
||||
cloneUrl: string;
|
||||
sshUrl: string;
|
||||
webUrl: string;
|
||||
updatedAt: string;
|
||||
private: boolean;
|
||||
}
|
||||
|
||||
export interface CustomThemeColors {
|
||||
background: string;
|
||||
surface: string;
|
||||
|
||||
Reference in New Issue
Block a user