Skip to content

Commit

Permalink
improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
edfloreshz committed Nov 1, 2024
1 parent 9b9833e commit 1e37427
Show file tree
Hide file tree
Showing 11 changed files with 164 additions and 166 deletions.
124 changes: 72 additions & 52 deletions src/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ use url_builder::URLBuilder;

use crate::input::{
clone_setup, config_all, config_editor, config_host, config_owner, create_workspace,
fork_setup, overwrite, select_repo,
fork_setup, overwrite, select, select_repo,
};
use devmode::fork::ForkAction;
use devmode::host::Host;
use devmode::project::{find_paths, OpenAction};
use devmode::project::{matching_paths_for, OpenAction};
use devmode::settings::Settings;
use devmode::{clone::CloneAction, constants::patterns::GIT_URL};

Expand Down Expand Up @@ -93,8 +93,6 @@ pub enum Commands {
arg_required_else_help = true
)]
Config {
#[clap(help = "Map your project paths.", short = 'm', long = "map")]
map: bool,
#[clap(help = "Show the current configuration.", short = 's', long = "show")]
show: bool,
#[clap(help = "Configure your settings.", short = 'a', long = "all")]
Expand Down Expand Up @@ -141,6 +139,8 @@ pub enum Commands {
remove: Option<String>,
#[clap(help = "List all workspaces", short = 'l', long = "list")]
list: bool,
#[clap(help = "Show information about a workspace", long = "info")]
info: bool,
},
}

Expand All @@ -153,20 +153,18 @@ impl Cli {
Commands::Update { project } => Cli::update(project),
Commands::Fork { args, upstream } => Cli::fork(args, upstream, rx),
Commands::Config {
map,
show,
all,
editor,
owner,
host,
} => Cli::config(Config {
map: *map,
show: *show,
all: *all,
editor: *editor,
owner: *owner,
host: *host,
none: !map && !show && !all && !editor && !owner && !host,
none: !show && !all && !editor && !owner && !host,
}),
Commands::Workspace {
name,
Expand All @@ -176,6 +174,7 @@ impl Cli {
include,
remove,
list,
info,
} => Cli::workspace(WorkspaceOptions {
name: name.to_owned(),
add: *add,
Expand All @@ -184,6 +183,7 @@ impl Cli {
include: include.to_owned(),
remove: remove.to_owned(),
list: *list,
info: *info,
}),
}
}
Expand Down Expand Up @@ -253,11 +253,11 @@ impl Cli {
}

fn open(project: &str) -> Result<(), Error> {
let paths = find_paths(project)?;
let paths = matching_paths_for(project)?;
if paths.is_empty() {
Err(Error::Devmode(DevmodeError::NoProjectFound))
} else if paths.len() > 1 {
let path = select_repo(project, None)?;
let path = select_repo(paths)?;
OpenAction::new(project).open(path)
} else {
OpenAction::new(project).open(
Expand All @@ -270,11 +270,11 @@ impl Cli {
}

fn update(project: &str) -> Result<(), Error> {
let paths = find_paths(project)?;
let paths = matching_paths_for(project)?;
if paths.is_empty() {
Err(Error::Devmode(DevmodeError::NoProjectFound))
} else if paths.len() > 1 {
let path = select_repo(project, None)?;
let path = select_repo(paths)?;
OpenAction::new(project).update(path)
} else {
OpenAction::new(project).update(
Expand Down Expand Up @@ -323,9 +323,6 @@ impl Cli {
let settings = config_all()?;
settings.write(false)?;
}
if config.map {
OpenAction::make_dev_paths()?
}
if config.editor {
let settings = config_editor()?;
settings.write(false)?
Expand All @@ -349,56 +346,90 @@ impl Cli {
let mut settings =
Settings::current().ok_or(Error::Devmode(DevmodeError::AppSettingsNotFound))?;
let Some(ref workspace_name) = arguments.name else {
let workspaces = settings.workspaces.names;
println!("Currently available workspaces: {workspaces:?}");
return Ok(());
return if arguments.list {
let workspaces = settings.workspaces.names;
println!("Currently available workspaces:");
for workspace in workspaces {
println!("- {}", workspace);
}
Ok(())
} else {
Err(Error::Devmode(DevmodeError::WorkspaceRequired))
};
};
let mut workspace = Workspace::new(&workspace_name);
if settings.workspaces.names.contains(workspace_name) {
if arguments.add {
if settings.workspaces.names.contains(workspace_name) {
return Err(Error::Devmode(DevmodeError::WorkspaceExists(
workspace_name.clone(),
)));
}
let create = create_workspace()?;
if create {
settings.workspaces.names.push(workspace_name.clone());
settings.write(true)?;
println!("Workspace {workspace_name} was added.")
}
} else if settings.workspaces.names.contains(workspace_name) {
let mut workspace = Workspace::new(&workspace_name);
if arguments.delete {
workspace.delete()?;
println!("Workspace {workspace_name} was successfully deleted.");
} else if let Some(ref to) = arguments.rename {
workspace.rename(to)?;
println!("Workspace renamed from {workspace_name} to {to}.");
} else if let Some(ref project) = arguments.include {
let paths: Vec<PathBuf> = find_paths(project)?
} else if let Some(ref project_name) = arguments.include {
let paths: Vec<PathBuf> = matching_paths_for(project_name)?
.iter()
.cloned()
.filter(|path| !path.display().to_string().contains(workspace_name))
.map(PathBuf::from)
.collect();
let project = if paths.len() > 0 {
select_repo(project, Some(workspace_name))?

let project = if paths.len() == 0 {
return Err(Error::Devmode(DevmodeError::ProjectNotFound));
} else if paths.len() > 1 {
let paths: Vec<String> =
paths.iter().map(|s| s.display().to_string()).collect();
PathBuf::from(select(
"repo",
"Select the repository you want to open:",
paths,
)?)
} else {
paths
.get(0)
.ok_or(Error::Devmode(DevmodeError::ProjectNotFound))?
.clone()
paths[0].clone()
};
let mut options = CopyOptions::new();
let destination = project
.parent()
.ok_or(Error::Devmode(DevmodeError::PathNotFound))?
.join(&workspace_name);

if destination.exists() {
if destination.join(project_name).exists() {
options.overwrite = overwrite()?;
}

if !destination.exists() {
std::fs::create_dir_all(&destination)?;
}

move_items(&[project], destination, &options)?;
} else if let Some(ref project_name) = arguments.remove {
let paths: Vec<PathBuf> = find_paths(project_name)?
let paths: Vec<PathBuf> = matching_paths_for(project_name)?
.iter()
.filter(|path| !path.display().to_string().contains(workspace_name))
.map(PathBuf::from)
.cloned()
.filter(|path| path.display().to_string().contains(workspace_name))
.collect();
let project = if paths.len() > 0 {
select_repo(project_name, Some(workspace_name))?
let project = if paths.len() == 0 {
return Err(Error::Devmode(DevmodeError::ProjectNotFound));
} else if paths.len() > 1 {
let paths: Vec<String> =
paths.iter().map(|s| s.display().to_string()).collect();
PathBuf::from(select(
"repo",
"Select the repository you want to open:",
paths,
)?)
} else {
paths
.get(0)
.ok_or(Error::Devmode(DevmodeError::ProjectNotFound))?
.clone()
paths[0].clone()
};
let mut options = dir::CopyOptions::new();
let to = project
Expand All @@ -407,27 +438,16 @@ impl Cli {
.parent()
.ok_or(Error::Devmode(DevmodeError::PathNotFound))?;

if to.join(&project).exists() {
if to.join(project_name).exists() {
options.overwrite = overwrite()?;
}

move_items(&[project.clone()], to, &options)?;
} else if arguments.info {
workspace.info()?;
} else {
println!("Workspace `{workspace_name}` found.");
}
} else if arguments.delete || arguments.rename.is_some() {
return devmode::error("Couldn't find a workspace that matches {name}.");
} else if arguments.add {
settings.workspaces.names.push(workspace_name.clone());
settings.write(true)?;
println!("Workspace {workspace_name} was added.")
} else {
let create = create_workspace()?;
if create {
settings.workspaces.names.push(workspace_name.clone());
settings.write(true)?;
println!("Workspace {workspace_name} was added.")
}
}
Ok(())
}
Expand Down
23 changes: 8 additions & 15 deletions src/cli/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use devmode::constants::names::{CUSTOM_NAME, NONE, VIM_NAME, VSCODE_NAME};
use devmode::editor::Editor;
use devmode::fork::ForkAction;
use devmode::host::Host;
use devmode::project::find_paths;
use devmode::settings::Settings;
use devmode::DevmodeError;
use devmode::{application::Application, Error};
Expand Down Expand Up @@ -148,29 +147,23 @@ pub fn config_editor() -> Result<Settings, Error> {
Ok(settings)
}

pub fn select_repo(project: &str, workspace: Option<&str>) -> Result<PathBuf, Error> {
let paths = if let Some(workspace) = workspace {
find_paths(project)?
.iter()
.filter(|path| path.display().to_string().contains(&workspace))
.map(|path| path.display().to_string().to_owned())
.collect::<Vec<String>>()
pub fn select_repo(paths: Vec<PathBuf>) -> Result<PathBuf, Error> {
let paths: Vec<String> = paths.iter().map(|s| s.display().to_string()).collect();
let repo = if paths.len() > 1 {
select("repo", "Select the repository you want to open:", paths)?
} else {
find_paths(project)?
.iter()
.map(|path| path.display().to_string().to_owned())
.collect::<Vec<String>>()
paths[0].clone()
};
let repo = select("repo", "Select the repository you want to open:", paths)?;

Ok(PathBuf::from(repo))
}

pub fn create_workspace() -> Result<bool, Error> {
let create = confirm("workspace", "Would you like to create this workspace?")?;
let create = confirm("Would you like to create this workspace?", "workspace")?;
Ok(create)
}

pub fn overwrite() -> Result<bool, Error> {
let overwrite = confirm("overwrite", "Found existing repository, overwrite it?")?;
let overwrite = confirm("Found existing repository, overwrite it?", "overwrite")?;
Ok(overwrite)
}
11 changes: 3 additions & 8 deletions src/shared/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ use serde::{Deserialize, Serialize};
use crate::constants::commands::*;
use crate::constants::names::*;

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[derive(Serialize, Default, Deserialize, Debug, Clone, Eq, PartialEq)]
pub enum Application {
VSCode,
Vim,
Custom,
#[default]
None,
}

Expand Down Expand Up @@ -59,19 +60,13 @@ impl Application {
}
}

impl Default for Application {
fn default() -> Self {
Application::None
}
}

impl Display for Application {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Application::VSCode => write!(f, "{}", VSCODE_NAME),
Application::Vim => write!(f, "{}", VIM_NAME),
Application::Custom => write!(f, "{}", CUSTOM_NAME),
_ => write!(f, "{}", DevmodeStatus::NoEditorSet.to_string()),
_ => write!(f, "{}", DevmodeStatus::NoEditorSet),
}
}
}
4 changes: 1 addition & 3 deletions src/shared/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use libset::routes::home;

use crate::action::Action;
use crate::host::Host;
use crate::project::OpenAction;
use crate::{error, git_pull, Error};

#[derive(Debug, Default, Clone, Setters)]
Expand Down Expand Up @@ -51,7 +50,7 @@ impl CloneAction {
if let Some(parent) = path.parent() {
let children: Vec<_> = std::fs::read_dir(parent)?.collect();
if children.is_empty() {
remove_dir_all(&parent)?;
remove_dir_all(parent)?;
}
}
}
Expand All @@ -60,7 +59,6 @@ impl CloneAction {
}

git_pull::status_short(path.to_str().unwrap().to_string())?;
OpenAction::make_dev_paths()?;
Ok(())
}

Expand Down
1 change: 0 additions & 1 deletion src/shared/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#[derive(Debug)]
pub struct Config {
pub map: bool,
pub show: bool,
pub all: bool,
pub editor: bool,
Expand Down
6 changes: 6 additions & 0 deletions src/shared/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ pub mod patterns {
pub const ORG_GIT_URL: &str = r#"(?:git@|https://)(?P<host>gitlab[.][^\s]+[.][^\s]+)[:/](?P<owner>[^\s]+)[/](?P<repo>[^\s,.]+)([.]git)?"#;
}

pub const OS_SLASH: &str = if cfg!(target_os = "windows") {
"\\"
} else {
"/"
};

pub mod names {
pub const VSCODE_NAME: &str = "Visual Studio Code";
pub const VIM_NAME: &str = "Vim";
Expand Down
6 changes: 6 additions & 0 deletions src/shared/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,16 @@ pub enum DevmodeError {
FailedToGetBranch,
#[error("Failed to find workspace")]
WorkspaceMissing,
#[error("Please provide a workspace")]
WorkspaceRequired,
#[error("Workspace {0} already exists")]
WorkspaceExists(String),
#[error("Failed to find project")]
ProjectNotFound,
#[error("Multiple projects found. Please specify the project name.")]
MultipleProjectsFound,
#[error("Path not found")]
PathNotFound,
#[error("File name not found")]
FileNameNotFound,
}
Loading

0 comments on commit 1e37427

Please sign in to comment.