Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ All notable changes to AngKorGit are documented here. The format follows

## [Unreleased]

### Added
- **Clone from saved accounts** (#47). Browse and search repositories from your
GitHub, GitLab or Bitbucket Cloud accounts in the clone dialog. AngKorGit
remembers the selected account for that repository.

## [0.28.0] — 2026-11-15

The hooks release. AngKorGit now runs the hooks Git runs after a checkout, a pull or
Expand Down
43 changes: 36 additions & 7 deletions CLAUDE.md

Large diffs are not rendered by default.

46 changes: 43 additions & 3 deletions apps/desktop/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::sync::{Mutex, OnceLock};

use tauri::{AppHandle, Emitter, State};

use crate::core::accounts::AccountRef;
use crate::core::post_hooks::{self, Hooked};
use crate::core::types::*;
use crate::core::{
Expand Down Expand Up @@ -198,26 +199,45 @@ pub async fn repo_clone(
url: String,
into: String,
branch: Option<String>,
account: Option<AccountRef>,
) -> AppResult<String> {
let emitter = app.clone();
let rejected_account = account.clone();
let cloned = blocking_post_hooks(&app, into, move |into| {
post_hooks::clone(
&url,
into,
branch.as_deref(),
account.as_ref(),
move |pct| {
let _ = emitter.emit("clone-progress", pct);
},
false,
)
})
.await?;
.await;
if matches!(&cloned, Err(AppError::Git(error)) if error.code() == git2::ErrorCode::Auth) {
if let Some(account) = rejected_account {
confirm_clone_account_rejection(account).await;
}
}
let cloned = cloned?;
let root = cloned.value.clone();
report(&app, &root, cloned);
crate::state::recent_add(&app, &root)?;
Ok(root)
}

async fn confirm_clone_account_rejection(account: AccountRef) {
let selected = account.clone();
let Ok((info, token)) = blocking(move || selected.with_token()).await else {
return;
};
if crate::forge_repositories::account_token_rejected(&info, &token).await {
let _ = blocking(move || account.mark_rejected(&token)).await;
}
}

#[tauri::command]
pub fn recent_repositories(app: AppHandle) -> AppResult<Vec<RecentRepository>> {
crate::state::recent_list(&app)
Expand All @@ -239,8 +259,18 @@ pub fn recent_remove(app: AppHandle, path: String) -> AppResult<Vec<RecentReposi
}

#[tauri::command]
pub async fn config_get(path: Option<String>, key: String) -> AppResult<Option<String>> {
blocking(move || repo::get_config(path.as_deref(), &key)).await
pub async fn config_get(
path: Option<String>,
key: String,
local: Option<bool>,
) -> AppResult<Option<String>> {
blocking(move || {
if let (true, Some(path)) = (local.unwrap_or(false), path.as_deref()) {
return repo::get_local_config(path, &key);
}
repo::get_config(path.as_deref(), &key)
})
.await
}

#[tauri::command]
Expand Down Expand Up @@ -1125,6 +1155,16 @@ pub fn account_list() -> Vec<crate::core::accounts::AccountInfo> {
crate::core::accounts::list()
}

#[tauri::command]
pub async fn account_forge_request(
host: String,
username: String,
url: String,
) -> AppResult<crate::http::HttpResponse> {
let (account, token) = blocking(move || AccountRef { host, username }.with_token()).await?;
crate::forge_repositories::request(&account, &token, url).await
}

#[tauri::command]
pub async fn account_add(
host: String,
Expand Down
195 changes: 192 additions & 3 deletions apps/desktop/src-tauri/src/core/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,84 @@ pub struct AccountInfo {
pub is_default: bool,
}

#[derive(Clone, Deserialize)]
pub struct AccountRef {
pub host: String,
pub username: String,
}

impl AccountRef {
pub fn with_token(&self) -> AppResult<(AccountInfo, String)> {
self.resolve(&list(), token_of)
}

pub fn mark_rejected(&self, token: &str) -> AppResult<()> {
let host = normalize_host(&self.host);
let Ok(cache) = token_cache().lock() else {
return Ok(());
};
if cache
.get(&entry_name(&host, &self.username))
.and_then(Option::as_deref)
!= Some(token)
{
return Ok(());
}
mark_matching_unverified(|account| {
account.host == host
&& account.username == self.username
&& (account.verified || account.verified_at.is_none())
})
}

fn resolve(
&self,
accounts: &[AccountInfo],
token: impl FnOnce(&str, &str) -> Option<String>,
) -> AppResult<(AccountInfo, String)> {
let host = normalize_host(&self.host);
let account = find_in(accounts, &host, &self.username).ok_or_else(|| {
AppError::other(format!(
"The saved account {} on {host} no longer exists.",
self.username
))
})?;
let token = token(&account.host, &account.username).ok_or_else(|| {
AppError::other(format!(
"The token for {} on {} is missing from the system keychain. Reconnect the account in Settings → Authentication.",
account.username, account.host
))
})?;
Ok((account.clone(), token))
}
}

pub fn https_account_origin(host: &str) -> Option<reqwest::Url> {
let url = reqwest::Url::parse(&format!("https://{host}/")).ok()?;
(url.host().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& url.path() == "/"
&& url.query().is_none()
&& url.fragment().is_none())
.then_some(url)
}

pub fn clone_url(account: &AccountInfo, raw: &str) -> Option<reqwest::Url> {
let url = reqwest::Url::parse(raw).ok()?;
let origin = https_account_origin(&account.host)?;
(matches!(
account.provider.as_str(),
"github" | "gitlab" | "gitlab-self" | "bitbucket"
) && url.origin() == origin.origin()
&& url.username().is_empty()
&& url.password().is_none()
&& url.query().is_none()
&& url.fragment().is_none()
&& url.path() != "/")
.then_some(url)
}

fn meta_path() -> Option<PathBuf> {
CONFIG_DIR.get().map(|dir| dir.join("accounts.json"))
}
Expand Down Expand Up @@ -140,8 +218,12 @@ fn save_list(accounts: &[AccountInfo]) -> AppResult<()> {

pub fn find(host: &str, username: &str) -> Option<AccountInfo> {
let host = normalize_host(host);
list()
.into_iter()
find_in(&list(), &host, username).cloned()
}

fn find_in<'a>(accounts: &'a [AccountInfo], host: &str, username: &str) -> Option<&'a AccountInfo> {
accounts
.iter()
.find(|a| a.host == host && a.username == username)
}

Expand Down Expand Up @@ -296,10 +378,16 @@ pub fn candidates(host: &str, preferred: Option<&str>) -> Vec<(String, String)>

pub fn mark_unverified(host: &str, username: &str) -> AppResult<()> {
let host = normalize_host(host);
mark_matching_unverified(|account| {
account.verified && hosts_match(&account.host, &host) && account.username == username
})
}

fn mark_matching_unverified(matches: impl Fn(&AccountInfo) -> bool) -> AppResult<()> {
let mut accounts = list();
let mut changed = false;
for account in accounts.iter_mut() {
if hosts_match(&account.host, &host) && account.username == username && account.verified {
if matches(account) {
account.verified = false;
account.verified_at = Some(now_epoch());
changed = true;
Expand Down Expand Up @@ -408,6 +496,107 @@ mod tests {
assert!(accounts[0].is_default);
}

#[test]
fn selecting_a_saved_account_never_uses_the_host_default() {
let accounts = [
account("github.com", "work", true),
account("github.com", "personal", false),
];
let selected = AccountRef {
host: "github.com".into(),
username: "personal".into(),
};
let (account, token) = selected
.resolve(&accounts, |host, username| {
assert_eq!((host, username), ("github.com", "personal"));
Some("personal-token".into())
})
.unwrap();
assert_eq!(account.username, "personal");
assert_eq!(token, "personal-token");

let missing = selected.resolve(&accounts, |_, username| {
assert_eq!(username, "personal");
None
});
assert!(
matches!(missing, Err(error) if error.to_string().contains("missing from the system keychain"))
);
let removed = selected.resolve(&accounts[..1], |_, _| {
panic!("must not look up another account's token")
});
assert!(matches!(removed, Err(error) if error.to_string().contains("no longer exists")));
}

#[test]
fn account_clone_urls_are_credential_free_and_match_the_saved_origin() {
let work = account("github.com", "work", true);
assert!(clone_url(&work, "https://github.com:443/org/repo.git").is_some());
for url in [
"https://github.com.example.org/org/repo.git",
"https://github.com:8443/org/repo.git",
"https://api.github.com/org/repo.git",
"https://user:secret@github.com/org/repo.git",
"https://github.com/org/repo.git?token=secret",
"http://github.com/org/repo.git",
"git@github.com:org/repo.git",
] {
assert!(clone_url(&work, url).is_none(), "{url}");
}
let self_hosted = AccountInfo {
provider: "gitlab-self".into(),
..account("git.local:8080", "work", true)
};
assert!(clone_url(&self_hosted, "https://git.local:8080/org/subgroup/repo.git").is_some());
assert!(clone_url(&self_hosted, "http://git.local:8080/org/subgroup/repo.git").is_none());
}

#[test]
fn a_recorded_rejection_preserves_the_preferred_git_credential() {
let dir = tempfile::tempdir().unwrap();
CONFIG_DIR.set(dir.path().to_path_buf()).unwrap();
let host = "git.example.test";
let selected = AccountRef {
host: host.into(),
username: "work".into(),
};
let unchecked = AccountInfo {
verified: false,
..account(host, "personal", false)
};
save_list(&[
account(host, "work", true),
account("git.example.test:8443", "work", true),
unchecked,
])
.unwrap();
token_cache().lock().unwrap().extend([
(entry_name(host, "work"), Some("current-token".into())),
(
entry_name("git.example.test:8443", "work"),
Some("other-port-token".into()),
),
(entry_name(host, "personal"), Some("unchecked-token".into())),
]);

selected.mark_rejected("previous-token").unwrap();
assert!(find(host, "work").unwrap().verified);
selected.mark_rejected("current-token").unwrap();
let rejected = find(host, "work").unwrap();
assert!(!rejected.verified);
assert!(rejected.verified_at.is_some());
assert!(find("git.example.test:8443", "work").unwrap().verified);
let usable = candidates(host, Some("work"));
assert_eq!(
usable,
[
("work".into(), "current-token".into()),
("work".into(), "other-port-token".into()),
("personal".into(), "unchecked-token".into()),
]
);
}

#[test]
fn ordered_for_host_puts_preferred_before_default() {
let accounts = vec![
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src-tauri/src/core/post_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::path::Path;

use git2::Oid;

use super::accounts::AccountRef;
use super::hooks::{run_post, PostHook, PostHooks};
use super::types::{
CommitOutcome, DiscardBatch, DiscardFailure, HookWarning, OpOutcome, RebaseTodoEntry,
Expand Down Expand Up @@ -331,10 +332,11 @@ pub fn clone(
url: &str,
into: &str,
branch: Option<&str>,
account: Option<&AccountRef>,
on_progress: impl Fn(u32) + Send,
no_verify: bool,
) -> AppResult<Hooked<String>> {
let root = remote::clone(url, into, branch, on_progress)?;
let root = remote::clone(url, into, branch, account, on_progress)?;
let path = root.clone();
Ok(checked_out(&path, root, no_verify))
}
Expand Down
Loading
Loading