Skip to content

Commit

Permalink
config: add clone-repo-switch option
Browse files Browse the repository at this point in the history
Configures whether to automatically switch to the new session after the
`clone-repo` command finishes
`Always` will always switch tmux to the new session
`Never` will always create the new session in the background
When set to `Foreground`, the new session will only be opened in the
background if the active tmux session has changed since starting the
clone process (for long clone processes on larger repos)
  • Loading branch information
junglerobba committed Dec 7, 2024
1 parent 61f7723 commit 048535b
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 3 deletions.
32 changes: 30 additions & 2 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{collections::HashMap, env::current_dir, fs::canonicalize, path::PathBu

use crate::{
clone::git_clone,
configs::{Config, SearchDirectory, SessionSortOrderConfig},
configs::{CloneRepoSwitchConfig, Config, SearchDirectory, SessionSortOrderConfig},
dirty_paths::DirtyUtf8Path,
execute_command, get_single_selection,
marks::{marks_command, MarksCommand},
Expand Down Expand Up @@ -105,6 +105,13 @@ pub struct ConfigCommand {
#[arg(long, value_name = "Alphabetical | LastAttached")]
/// Set the sort order of the sessions in the switch command
session_sort_order: Option<SessionSortOrderConfig>,
#[arg(long, value_name = "Always | Never | Foreground", verbatim_doc_comment)]
/// Whether to automatically switch to the new session after the `clone-repo` command finishes
/// `Always` will always switch tmux to the new session
/// `Never` will always create the new session in the background
/// When set to `Foreground`, the new session will only be opened in the background if the active
/// tmux session has changed since starting the clone process (for long clone processes on larger repos)
clone_repo_switch: Option<CloneRepoSwitchConfig>,
}

#[derive(Debug, Args)]
Expand Down Expand Up @@ -428,6 +435,10 @@ fn config_command(args: &ConfigCommand, mut config: Config) -> Result<()> {
config.session_sort_order = Some(order.to_owned());
}

if let Some(switch) = &args.clone_repo_switch {
config.clone_repo_switch = Some(switch.to_owned());
}

config.save().change_context(TmsError::ConfigError)?;
println!("Configuration has been stored");
Ok(())
Expand Down Expand Up @@ -650,11 +661,26 @@ fn clone_repo_command(args: &CloneRepoCommand, config: Config, tmux: &Tmux) -> R
let repo_name = repo_name.trim_end_matches(".git");
path.push(repo_name);

let previous_session = tmux.current_session("#{session_name}");

println!("Cloning into '{repo_name}'...");
let repo = git_clone(&args.repository, &path)?;

let mut session_name = repo_name.to_string();

let switch_config = config
.clone_repo_switch
.unwrap_or(CloneRepoSwitchConfig::Always);

let switch = match switch_config {
CloneRepoSwitchConfig::Always => true,
CloneRepoSwitchConfig::Never => false,
CloneRepoSwitchConfig::Foreground => {
let active_session = tmux.current_session("#{session_name}");
previous_session == active_session
}
};

if tmux.session_exists(&session_name) {
session_name = format!(
"{}/{}",
Expand All @@ -669,7 +695,9 @@ fn clone_repo_command(args: &CloneRepoCommand, config: Config, tmux: &Tmux) -> R

tmux.new_session(Some(&session_name), Some(&path.display().to_string()));
tmux.set_up_tmux_env(&repo, &session_name)?;
tmux.switch_to_session(&session_name);
if switch {
tmux.switch_to_session(&session_name);
}

Ok(())
}
Expand Down
24 changes: 24 additions & 0 deletions src/configs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pub struct Config {
pub bookmarks: Option<Vec<String>>,
pub session_configs: Option<HashMap<String, SessionConfig>>,
pub marks: Option<HashMap<String, String>>,
pub clone_repo_switch: Option<CloneRepoSwitchConfig>,
}

impl Config {
Expand Down Expand Up @@ -368,6 +369,29 @@ impl ValueEnum for SessionSortOrderConfig {
}
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum CloneRepoSwitchConfig {
Always,
Never,
Foreground,
}

impl ValueEnum for CloneRepoSwitchConfig {
fn value_variants<'a>() -> &'a [Self] {
&[Self::Always, Self::Never, Self::Foreground]
}

fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
match self {
CloneRepoSwitchConfig::Always => Some(clap::builder::PossibleValue::new("Always")),
CloneRepoSwitchConfig::Never => Some(clap::builder::PossibleValue::new("Never")),
CloneRepoSwitchConfig::Foreground => {
Some(clap::builder::PossibleValue::new("Foreground"))
}
}
}
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct SessionConfig {
pub create_script: Option<PathBuf>,
Expand Down
11 changes: 11 additions & 0 deletions src/tmux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ impl Tmux {
Tmux::stdout_to_string(output)
}

pub fn current_session(&self, format: &str) -> String {
let output = self.execute_tmux_command(&[
"list-sessions",
"-F",
format,
"-f",
"#{session_attached}",
]);
Tmux::stdout_to_string(output)
}

pub fn kill_session(&self, session: &str) -> process::Output {
self.execute_tmux_command(&["kill-session", "-t", session])
}
Expand Down
7 changes: 6 additions & 1 deletion tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ use pretty_assertions::assert_eq;
use ratatui::style::Color;
use std::{fs, str::FromStr};
use tempfile::tempdir;
use tms::configs::{Config, PickerColorConfig, SearchDirectory, SessionSortOrderConfig};
use tms::configs::{
CloneRepoSwitchConfig, Config, PickerColorConfig, SearchDirectory, SessionSortOrderConfig,
};

#[test]
fn tms_fails_with_missing_config() -> anyhow::Result<()> {
Expand Down Expand Up @@ -64,6 +66,7 @@ fn tms_config() -> anyhow::Result<()> {
bookmarks: None,
session_configs: None,
marks: None,
clone_repo_switch: Some(CloneRepoSwitchConfig::Always),
};

let mut tms = Command::cargo_bin("tms")?;
Expand Down Expand Up @@ -99,6 +102,8 @@ fn tms_config() -> anyhow::Result<()> {
&picker_info_color.to_string(),
"--picker-prompt-color",
&picker_prompt_color.to_string(),
"--clone-repo-switch",
"Always",
]);

tms.assert().success().code(0);
Expand Down

0 comments on commit 048535b

Please sign in to comment.