Skip to content
Merged
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
44 changes: 38 additions & 6 deletions src/commands/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ fn add_github(config: &mut Config) {
email,
alias: alias.clone(),
host: None,
ssh_key: None,
};

set_token(&username, alias.as_deref(), &token);
Expand All @@ -94,6 +95,8 @@ fn add_github(config: &mut Config) {
exit_raw_mode();
}

use crate::utils::scan_ssh_keys;

fn add_manual(config: &mut Config) {
let Some(username) = raw_input("Username", "").filter(|u| !u.is_empty()) else {
return;
Expand Down Expand Up @@ -124,20 +127,49 @@ fn add_manual(config: &mut Config) {
}
}

let token = raw_password("Token/PAT (optional)").unwrap_or_default();
let host_in = raw_input("Host", "github.com").unwrap_or_else(|| "github.com".to_string());
let auth_types = vec!["Token/PAT".to_string(), "SSH Key".to_string()];
let Some(auth_choice) = raw_select("Authentication Type", &auth_types, 0) else {
return;
};

let host = if host_in == "github.com" || host_in.is_empty() {
None
let mut token = String::new();
let mut host = None;
let mut ssh_key = None;

if auth_choice == 0 {
// Token/PAT
token = raw_password("Token/PAT (optional)").unwrap_or_default();
let host_in = raw_input("Host", "github.com").unwrap_or_else(|| "github.com".to_string());
host = if host_in == "github.com" || host_in.is_empty() {
None
} else {
Some(host_in)
};
} else {
Some(host_in)
};
// SSH Key
let (display_items, paths, default_idx) = scan_ssh_keys(&username, &email);
let Some(selection) = raw_select("Keys in ~/.ssh", &display_items, default_idx) else {
return;
};

if selection < paths.len() {
ssh_key = Some(paths[selection].to_string_lossy().to_string());
} else if selection == paths.len() {
let manual = raw_input("SSH Key Path", "").unwrap_or_default();
ssh_key = if manual.is_empty() {
None
} else {
Some(manual)
};
}
}

let account = Account {
username: username.clone(),
email,
alias: alias.clone(),
host,
ssh_key,
};

if !token.is_empty() {
Expand Down
19 changes: 14 additions & 5 deletions src/commands/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ pub fn run(config: &Config, account_id: Option<String>, args: Vec<String>) {
cmd.arg("-c").arg(format!("user.name={}", account.username));
cmd.arg("-c").arg(format!("user.email={}", account.email));

if let Some(ssh_key) = &account.ssh_key {
cmd.arg("-c").arg(format!(
"core.sshCommand={}",
crate::utils::git_ssh_command(ssh_key)
));
}

// Inject inline credential helper if token is available
match crate::models::get_token(&account.username, account.alias.as_deref()) {
Some(token) if !token.is_empty() => {
Expand All @@ -30,11 +37,13 @@ pub fn run(config: &Config, account_id: Option<String>, args: Vec<String>) {
));
}
_ => {
println!(
" {} No token found for {}. Git may prompt for authentication.",
"⚠".yellow(),
account.username.cyan()
);
if account.ssh_key.is_none() || crate::utils::git_args_use_http_transport(&args) {
println!(
" {} No token found for {}. Git may prompt for authentication.",
"⚠".yellow(),
account.username.cyan()
);
}
}
}

Expand Down
133 changes: 109 additions & 24 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,33 +424,37 @@ impl<'a> ListState<'a> {
}

fn apply_switch(&self, account: &crate::models::Account, scope: &str) -> bool {
git_config_set("user.name", &account.username, scope);
git_config_set("user.email", &account.email, scope);

if let Some(alias) = &account.alias {
git_config_set("gitas.alias", alias, scope);
} else {
git_config_unset("gitas.alias", scope);
}

// Enforce the correct username for the credential helper (fixes "sticky" tokens)
let host = account.host.as_deref().unwrap_or("github.com");
let cred_key = format!("credential.https://{}.username", host);
git_config_set(&cred_key, &account.username, scope);

let mut status_lines = Vec::new();
let mut has_status_issue = false;

let host = account.host.as_deref().unwrap_or("github.com");
let mut target_url = None;

// Check authentication BEFORE making any git config changes
if let Some(token) = crate::models::get_token(&account.username, account.alias.as_deref())
.filter(|t| !t.is_empty())
{
let host = account.host.as_deref().unwrap_or("github.com");
let url = (scope == "local")
.then(|| git_config_get("remote.origin.url", "local"))
.flatten();

if scope == "local" && url.is_some() {
git_config_set("credential.useHttpPath", "true", "local");
if scope == "local" {
let remotes = crate::utils::get_http_remotes();
if remotes.is_empty() {
status_lines.push(format!(
" {} No HTTP remotes found. Token authentication may fail.",
"⚠".yellow()
));
has_status_issue = true;
} else if remotes.len() == 1 {
target_url = Some(remotes[0].url.clone());
} else {
let items: Vec<String> = remotes
.iter()
.map(|r| format!("{} ({})", r.name, r.url))
.collect();
if let Some(selection) = raw_select("Select remote for token auth", &items, 0) {
target_url = Some(remotes[selection].url.clone());
} else {
return false;
}
}
}

if let Some(warning) = crate::utils::check_credential_helper() {
Expand All @@ -460,8 +464,25 @@ impl<'a> ListState<'a> {

// Clear any potentially conflicting credentials
git_credential_reject(host);
git_credential_approve(&account.username, &token, host, url.as_deref());
} else {
if let Err(e) =
git_credential_approve(&account.username, &token, host, target_url.as_deref())
{
status_lines.push(format!(" {} {}", "⚠".yellow(), e));
status_lines.push(String::new());
status_lines.push(format!(
"{} Aborted switch due to authentication failure",
"✗".red()
));
raw_show_status(&status_lines, true);
return false;
}

if scope == "local" && target_url.is_some() {
git_config_set("credential.useHttpPath", "true", "local");
}
} else if account.ssh_key.is_none()
|| (scope == "local" && crate::utils::has_http_remotes())
{
has_status_issue = true;
status_lines.push(format!(
" {} No token found for {}. Git may prompt for authentication.",
Expand All @@ -470,6 +491,29 @@ impl<'a> ListState<'a> {
));
}

// Apply all configuration changes now that auth has succeeded
git_config_set("user.name", &account.username, scope);
git_config_set("user.email", &account.email, scope);

if let Some(alias) = &account.alias {
git_config_set("gitas.alias", alias, scope);
} else {
git_config_unset("gitas.alias", scope);
}

if let Some(ssh_key) = &account.ssh_key {
git_config_set(
"core.sshCommand",
&crate::utils::git_ssh_command(ssh_key),
scope,
);
} else if self.current_ssh_command_is_gitas_managed(scope) {
git_config_unset("core.sshCommand", scope);
}

let cred_key = format!("credential.https://{}.username", host);
git_config_set(&cred_key, &account.username, scope);

status_lines.push(String::new());
status_lines.push(format!(
"{} Switched to '{}' ({})",
Expand All @@ -482,6 +526,19 @@ impl<'a> ListState<'a> {
true
}

fn current_ssh_command_is_gitas_managed(&self, scope: &str) -> bool {
let Some(current) = git_config_get("core.sshCommand", scope) else {
return false;
};

self.config
.accounts
.iter()
.filter_map(|account| account.ssh_key.as_deref())
.map(crate::utils::git_ssh_command)
.any(|command| command == current)
}

fn handle_delete(&mut self) -> bool {
if self.config.accounts.is_empty() {
return false;
Expand Down Expand Up @@ -549,6 +606,11 @@ impl<'a> ListState<'a> {
"none"
}
),
format!(
"{:<15} {}",
"SSH Key:".dimmed(),
temp_account.ssh_key.as_deref().unwrap_or("none")
),
"Save Changes".green().to_string(),
"Cancel".dimmed().to_string(),
];
Expand Down Expand Up @@ -598,6 +660,29 @@ impl<'a> ListState<'a> {
}
}
5 => {
let (display_items, paths, default_idx) =
crate::utils::scan_ssh_keys(&temp_account.username, &temp_account.email);
if let Some(selection) =
raw_select("Keys in ~/.ssh", &display_items, default_idx)
{
if selection < paths.len() {
temp_account.ssh_key =
Some(paths[selection].to_string_lossy().to_string());
} else if selection == paths.len() {
let manual = raw_input(
"New SSH Key Path",
temp_account.ssh_key.as_deref().unwrap_or(""),
)
.unwrap_or_default();
temp_account.ssh_key = if manual.is_empty() {
None
} else {
Some(manual)
};
}
}
}
6 => {
if original_username != temp_account.username
|| original_alias != temp_account.alias
{
Expand All @@ -620,7 +705,7 @@ impl<'a> ListState<'a> {
save_config(self.config);
return true;
}
6 => return false,
7 => return false,
_ => {}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub struct Account {
pub alias: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ssh_key: Option<String>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
Expand Down
Loading
Loading