1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
use std::{collections::BTreeSet, path::PathBuf};
use clap::{arg, Args, Subcommand, ValueEnum};
use colored::Colorize;
use git_lib::repo::GitRepo;
use tracing::{debug, error, instrument, trace};
use crate::{
config::{config_env::ConfigEnvKey, config_file::AxlContext},
helper::fzf_get_sessions,
multiplexer::{Multiplexer, Multiplexers},
project::{
project_directory::{ConfigProjectDirectory, ResolvedProjectDirectory},
project_type::{ConfigProject, ResolvedProject},
},
};
#[derive(Args, Debug)]
pub struct SessionArgs {
#[arg(short, long)]
/// Which multiplexer session should be created.
pub multiplexer: Multiplexers,
}
#[derive(Args, Debug)]
pub struct ProjectArgs {
/// Manually set the project root dir.
#[arg(long, env)]
projects_directory_file: PathBuf,
}
#[derive(Args, Debug)]
pub struct FilterArgs {
/// Comma delimited list of tags narrowing projects that will be operated on.
#[arg(long, short, value_delimiter = ',')]
tags: Vec<String>,
}
#[derive(Subcommand, Debug)]
pub enum ProjectSubcommand {
/// Open a session.
Open {
#[clap(flatten)]
proj_args: ProjectArgs,
#[clap(flatten)]
filter_args: FilterArgs,
#[clap(flatten)]
sess_args: SessionArgs,
},
/// Open a scratch session. defaults: (name = scratch, path = $HOME)
Scratch {
#[clap(flatten)]
proj_args: ProjectArgs,
#[clap(flatten)]
sess_args: SessionArgs,
#[arg(short, long)]
/// Name of session, defaults to project_dir name
name: Option<String>,
#[arg(short, long)]
/// Name of session, defaults to project_dir name
project_dir: Option<PathBuf>,
},
/// Kill sessions.
Kill {
#[clap(flatten)]
sess_args: SessionArgs,
},
/// Open new unique session in $HOME and increment prefix (available: 0-9).
Home {
#[clap(flatten)]
sess_args: SessionArgs,
},
/// List all projects tracked in your config list.
List {
#[clap(flatten)]
proj_args: ProjectArgs,
#[clap(flatten)]
filter_args: FilterArgs,
#[arg(short, long, value_enum, default_value_t=OutputFormat::Debug)]
output: OutputFormat,
},
/// List all tags used on projects tracked in your config list.
ListTags {
#[clap(flatten)]
proj_args: ProjectArgs,
#[arg(short, long, value_enum, default_value_t=OutputFormat::Debug)]
output: OutputFormat,
},
/// Select projects to bring into axl tracking
///
/// This will pick projects, from a specified directory, and give a yaml string to add into your config file.
Import {
#[clap(flatten)]
proj_args: ProjectArgs,
/// The projects directory to pick from
#[arg(short, long)]
directory: PathBuf,
},
/// Show a report of projects
///
/// This will show you projects tracked in your config file, and the projects in your project
/// directory that are not tracked.
Report {
#[clap(flatten)]
proj_args: ProjectArgs,
#[clap(flatten)]
filter_args: FilterArgs,
},
/// Clone a new repo into your projects dir.
New {
#[clap(flatten)]
proj_args: ProjectArgs,
/// remote uri of repository you would like to add
ssh_uri: String,
}, // Like ThePrimagen Harpoon in nvim but for multiplexer sessions
// Harpoon(ProjectArgs),
// Test,
// Reconsile projects defined in config with projects in the directory.
//
// This will not be descructive. It will only add projects from config that are not already in project folder.
// if you want to remove a project you should remove it from your config, and then manually
// /// remove it from the file
// Sync,
}
#[derive(ValueEnum, Debug, Clone)]
pub enum OutputFormat {
/// rust debug print.
Debug,
/// pretty printed json.
Json,
/// raw printed json.
JsonR,
/// yaml.
Yaml,
/// csv for excel spreadsheets.
Csv,
}
impl ProjectSubcommand {
#[instrument(skip(project_sub_cmd, _context), err)]
pub fn handle_cmd(project_sub_cmd: Self, _context: AxlContext) -> anyhow::Result<()> {
match project_sub_cmd {
Self::Open {
proj_args,
filter_args,
sess_args,
} => {
debug!(
"using [{:?}] projects file.",
proj_args.projects_directory_file
);
let projects_directory_file = ResolvedProjectDirectory::new_filtered(
&ConfigProjectDirectory::new(&proj_args.projects_directory_file)?,
&filter_args.tags,
)?;
let project = projects_directory_file.get_project()?;
sess_args.multiplexer.open(&proj_args, project)?;
Ok(())
}
Self::Scratch {
proj_args,
sess_args,
name,
project_dir,
} => {
sess_args.multiplexer.open(
&proj_args,
ResolvedProject::new(
&project_dir.unwrap_or(PathBuf::try_from(ConfigEnvKey::Home)?),
name.unwrap_or_else(|| "scratch".to_string()),
"".to_owned(),
BTreeSet::new(),
),
)?;
Ok(())
}
Self::Kill { sess_args } => {
let sessions = sess_args.multiplexer.get_sessions();
debug!("sessions: {sessions:?}");
let picked_sessions = fzf_get_sessions(sessions)?;
let current_session = sess_args.multiplexer.get_current_session();
debug!("current session: {current_session}");
sess_args
.multiplexer
.kill_sessions(picked_sessions, ¤t_session)?;
Ok(())
}
Self::Home { sess_args } => sess_args.multiplexer.unique_session(),
Self::New { proj_args, ssh_uri } => {
debug!(
"using [{:?}] projects file.",
proj_args.projects_directory_file
);
let mut project_directory = ResolvedProjectDirectory::new(
&ConfigProjectDirectory::new(&proj_args.projects_directory_file)?,
)?;
if project_directory
.projects
.iter()
.filter(|config_proj| config_proj.remote == ssh_uri)
.count()
> 0
{
eprintln!(
"{}",
"Project with this remote is already tracked.".red().bold()
);
return Ok(());
}
debug!("Attempting to clone {ssh_uri}...");
let results =
GitRepo::from_url_multi(&[&ssh_uri], &project_directory.projects_directory);
for result in results {
if let Err(err) = result {
error!("Failed cloning with: {err:?}");
}
}
project_directory.add_config_projects(vec![ConfigProject {
name: None,
remote: ssh_uri,
tags: BTreeSet::new(),
}])?;
println!("project was added to your root project_directory config.\nYou can now move it to a different group manually.");
Ok(())
}
Self::Report {
proj_args,
filter_args,
} => {
let filtered_project_directory = ResolvedProjectDirectory::new_filtered(
&ConfigProjectDirectory::new(&proj_args.projects_directory_file)?,
&filter_args.tags,
)?;
trace!(
"getting projects from fs [{}]",
&filtered_project_directory
.projects_directory
.to_string_lossy()
);
let projects_fs = ResolvedProjectDirectory::get_projects_from_fs(
&filtered_project_directory.projects_directory,
)?;
trace!("got projects from fs [{:#?}]", &projects_fs);
trace!(
"getting projects from project_directory_file [{}] remotes",
&proj_args.projects_directory_file.to_string_lossy()
);
let projects_remotes = filtered_project_directory.get_projects_from_remotes()?;
trace!(
"got projects from project_directory_file remotes [{:#?}]",
&projects_fs
);
let filtered = projects_fs
.0
.iter()
.filter(|p| {
!projects_remotes
.iter()
.map(|p_c| p_c.name.clone())
.any(|x| x == p.name)
})
.collect::<Vec<_>>();
println!(
"PROJECTS REPORT ({})",
filtered_project_directory
.projects_directory
.to_string_lossy()
);
println!("===============");
println!(
"file system: {}\nconfig list: {}\nnot tracked: {}\nignored: {}\n",
projects_fs.0.len(),
projects_remotes.len(),
filtered.len(),
projects_fs.1.len(),
);
if !filtered.is_empty() {
println!(
"items in [{}] not tracked in config list: ",
filtered_project_directory
.projects_directory
.to_string_lossy()
);
println!("{:#?}", filtered.iter().collect::<Vec<_>>());
}
if !projects_fs.1.is_empty() {
println!(
"ignored items in [{}]: ",
filtered_project_directory
.projects_directory
.to_string_lossy()
);
println!("{:#?}", projects_fs.1.iter().collect::<Vec<_>>());
}
Ok(())
}
Self::Import {
proj_args,
directory,
} => {
let mut project_directory_file = ResolvedProjectDirectory::new(
&ConfigProjectDirectory::new(&proj_args.projects_directory_file)?,
)?;
let existing_projects = project_directory_file
.projects
.clone()
.into_iter()
.map(|ep| ep.remote)
.collect::<Vec<_>>();
trace!("existing: {existing_projects:?}");
let selected_projects = ResolvedProjectDirectory::pick_config_projects(
ResolvedProjectDirectory::get_projects_from_fs(&directory)?
.0
.into_iter()
.filter(|sp| !existing_projects.contains(&sp.remote))
.map(|sp| ConfigProject {
name: None,
remote: sp.remote,
tags: sp.tags,
})
.collect::<Vec<_>>(),
)?;
trace!("selected: {selected_projects:?}");
project_directory_file.add_config_projects(selected_projects)?;
Ok(())
}
Self::List {
proj_args,
filter_args,
output,
} => {
let filtered_project_directory = ResolvedProjectDirectory::new_filtered(
&ConfigProjectDirectory::new(&proj_args.projects_directory_file)?,
&filter_args.tags,
)?;
let projects = filtered_project_directory.get_projects_from_remotes()?;
match output {
OutputFormat::Debug => {
println!("{:#?}", projects);
}
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&projects)?)
}
OutputFormat::Yaml => println!("{}", serde_yaml::to_string(&projects)?),
OutputFormat::Csv => println!(
"{},",
projects
.iter()
.map(|p| p.name.clone())
.collect::<Vec<_>>()
.join(",\n")
),
OutputFormat::JsonR => {
println!("{}", serde_json::to_string(&projects)?)
}
}
Ok(())
}
Self::ListTags { proj_args, output } => {
let project_directory = ResolvedProjectDirectory::new(
&ConfigProjectDirectory::new(&proj_args.projects_directory_file)?,
)?;
let tags = project_directory.get_projects_from_remotes()?.iter().fold(
BTreeSet::new(),
|mut acc, project| {
acc.extend(project.tags.clone());
acc
},
);
match output {
OutputFormat::Debug => {
println!("{:#?}", tags);
}
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&tags)?)
}
OutputFormat::Yaml => println!("{}", serde_yaml::to_string(&tags)?),
OutputFormat::Csv => {
println!("{},", tags.iter().cloned().collect::<Vec<_>>().join(",\n"))
}
OutputFormat::JsonR => {
println!("{}", serde_json::to_string(&tags)?)
}
}
Ok(())
}
}
}
}