Skip to content

Commit a503bd4

Browse files
committed
improv: switch from constants to enum for app status
1 parent 8df2375 commit a503bd4

10 files changed

Lines changed: 84 additions & 53 deletions

File tree

src/application.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
use std::fmt::{Display, Formatter};
22
use std::process::Command;
33

4-
use crate::Error;
4+
use crate::{DevmodeStatus, Error};
55
use cmd_lib::run_cmd;
66
use serde::{Deserialize, Serialize};
77

88
use crate::constants::commands::*;
9-
use crate::constants::messages::NO_EDITOR_SET;
109
use crate::constants::names::*;
1110

1211
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
@@ -70,7 +69,7 @@ impl Display for Application {
7069
Application::VSCode => write!(f, "{}", VSCODE_NAME),
7170
Application::Vim => write!(f, "{}", VIM_NAME),
7271
Application::Custom => write!(f, "{}", CUSTOM_NAME),
73-
_ => write!(f, "{}", NO_EDITOR_SET),
72+
_ => write!(f, "{}", DevmodeStatus::NoEditorSet.to_string()),
7473
}
7574
}
7675
}

src/cli/src/cli.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use clap::{Parser, Subcommand};
22
use devmode::action::Action;
3-
use devmode::Error;
3+
use devmode::{DevmodeStatus, Error};
44
use fs_extra::{dir, move_items};
55
use libset::routes::home;
66
use regex::bytes::Regex;
@@ -9,8 +9,6 @@ use std::fs;
99
use std::path::PathBuf;
1010
use url_builder::URLBuilder;
1111

12-
use devmode::constants::messages::*;
13-
1412
use crate::input::{
1513
clone_setup, config_all, config_editor, config_host, config_owner, fork_setup, overwrite,
1614
select_repo,
@@ -247,7 +245,7 @@ impl Cli {
247245
let reader = create_paths_reader()?;
248246
let paths = find_paths(reader, project)?;
249247
if paths.is_empty() {
250-
return devmode::error(NO_PROJECT_FOUND);
248+
return Err(Error::String(DevmodeStatus::NoProjectFound.to_string()));
251249
} else if paths.len() > 1 {
252250
let paths: Vec<&str> = paths.iter().map(|s| s as &str).collect();
253251
let path = select_repo(paths)?.to_string();
@@ -260,9 +258,8 @@ impl Cli {
260258
let reader = create_paths_reader()?;
261259
let paths = find_paths(reader, project)?;
262260
if paths.is_empty() {
263-
return devmode::error(NO_PROJECT_FOUND);
261+
return Err(Error::String(DevmodeStatus::NoProjectFound.to_string()));
264262
} else if paths.len() > 1 {
265-
eprintln!("{}", MORE_PROJECTS_FOUND); // TODO: Let user decide which
266263
let paths: Vec<&str> = paths.iter().map(|s| s as &str).collect();
267264
let path = select_repo(paths)?;
268265
OpenAction::new(project).update(vec![path])
@@ -277,7 +274,9 @@ impl Cli {
277274
} else if rx.is_match(args.get(0).unwrap().as_bytes()) {
278275
ForkAction::parse_url(args.get(0).unwrap(), rx, upstream.to_string())?
279276
} else if args.len() == 1 {
280-
let options = Settings::current().ok_or(Error::Generic(APP_OPTIONS_NOT_FOUND))?;
277+
let options = Settings::current().ok_or(Error::String(
278+
DevmodeStatus::AppSettingsNotFound.to_string(),
279+
))?;
281280
let host = Host::from(&options.host);
282281
let repo = args
283282
.get(0)
@@ -417,7 +416,6 @@ impl Cli {
417416
let path = if paths.is_empty() {
418417
return devmode::error("Could not locate the {add} repository.");
419418
} else if paths.len() > 1 {
420-
eprintln!("{}", MORE_PROJECTS_FOUND);
421419
let paths: Vec<&str> = paths.iter().map(|s| s as &str).collect();
422420
select_repo(paths)?
423421
} else {
@@ -451,7 +449,6 @@ impl Cli {
451449
"Could not locate the {remove} repository inside {name}",
452450
);
453451
} else if paths.len() > 1 {
454-
eprintln!("{}", MORE_PROJECTS_FOUND);
455452
let paths: Vec<&str> = paths.iter().map(|s| s as &str).collect();
456453
select_repo(paths)?
457454
} else {
@@ -493,5 +490,7 @@ impl Cli {
493490
}
494491

495492
fn get_settings() -> Result<Settings, Error> {
496-
Settings::current().ok_or(Error::Generic(APP_OPTIONS_NOT_FOUND))
493+
Settings::current().ok_or(Error::String(
494+
DevmodeStatus::AppSettingsNotFound.to_string(),
495+
))
497496
}

src/cli/src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ fn main() -> Result<(), Error> {
1010
start_logger();
1111
let cli = Cli::parse();
1212
if let Err(e) = cli.run() {
13-
log::error!("{}", e);
13+
log::error!("{}", e)
1414
}
1515
Ok(())
1616
}

src/constants.rs

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,26 +22,3 @@ pub mod commands {
2222
pub const VSCODE_CMD: &str = "code";
2323
pub const VIM_CMD: &str = "vim";
2424
}
25-
26-
pub mod messages {
27-
pub const NO_PROJECT_FOUND: &str = "No project was found. \n\
28-
If you know this project exists, run `dm config -m` to refresh the paths file.";
29-
pub const MORE_PROJECTS_FOUND: &str = "Two or more projects found.";
30-
pub const NO_SETTINGS_CHANGED: &str = "No settings were changed.";
31-
pub const SETTINGS_UPDATED: &str = "Settings updated.";
32-
pub const FAILED_TO_WRITE_CONFIG: &str = "Failed to write changes to `settings.toml`.";
33-
pub const FAILED_TO_PARSE: &str = "Failed to parse app options.";
34-
pub const UNABLE_TO_MAP_URL: &str = "Could not map url.";
35-
pub const FAILED_TO_CLONE_REPO: &str = "Failed to clone repository.";
36-
pub const FAILED_TO_SET_REMOTE: &str = "Failed to set remote.";
37-
pub const FAILED_TO_GET_BRANCH: &str = "Failed to get branch.";
38-
pub const OPENING_WARNING: &str =
39-
"If the editor does not support openning from a path, you'll have to open it yourself.";
40-
pub const NO_EDITOR_SET: &str = "No editor set, run `dm config -e` to configure it.";
41-
pub const APP_OPTIONS_NOT_FOUND: &str =
42-
"The current app options could not be found.\nRun `dm cf --all` to reconfigure them.";
43-
44-
pub fn _failed_to(action: &str, obj: &str) -> String {
45-
format!("Failed to {} `{}`.", action, obj)
46-
}
47-
}

src/fork.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use git2::Repository;
44
use libset::routes::home;
55
use regex::bytes::Regex;
66

7-
use crate::constants::messages::*;
87
use crate::host::Host;
98
use crate::project::OpenAction;
109
use crate::{error, Error};
@@ -112,7 +111,7 @@ impl ForkAction {
112111
if path.is_empty() {
113112
println!("Seems that you haven't cloned the repository locally.");
114113
}
115-
let project = Repository::open(Path::new(&path)).expect(NO_PROJECT_FOUND);
114+
let project = Repository::open(Path::new(&path))?;
116115
project.remote("upstream", &self.upstream)?;
117116
Ok(())
118117
}

src/git_pull.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@ use std::io;
66
use std::io::Write;
77
use std::path::Path;
88

9-
use crate::constants::messages::FAILED_TO_GET_BRANCH;
10-
use crate::error;
119
use crate::error::Error;
10+
use crate::DevmodeStatus;
1211

1312
pub fn pull(repo_path: &Path) -> Result<(), Error> {
1413
let remote_name = "origin";
@@ -124,7 +123,7 @@ fn get_branch(repo: &Repository) -> Result<String, Error> {
124123
let head = head.as_ref().and_then(|h| h.shorthand());
125124
match head {
126125
Some(branch) => Ok(String::from(branch)),
127-
None => error::error(FAILED_TO_GET_BRANCH),
126+
None => Err(Error::String(DevmodeStatus::FailedToGetBranch.to_string())),
128127
}
129128
}
130129

src/lib.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,13 @@ pub mod application;
33
pub mod clone;
44
pub mod constants;
55
pub mod editor;
6+
67
mod error;
7-
pub use error::{error, Error};
8+
pub use error::*;
9+
10+
mod status;
11+
pub use status::*;
12+
813
pub mod fork;
914
pub mod git_pull;
1015
pub mod host;

src/project.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,9 @@ use libset::routes::{data, home};
99
use walkdir::WalkDir;
1010

1111
use crate::application::Application;
12-
use crate::constants::messages::*;
1312
use crate::error::Error;
14-
use crate::git_pull;
1513
use crate::settings::Settings;
14+
use crate::{git_pull, DevmodeStatus};
1615

1716
pub struct OpenAction {
1817
pub name: String,
@@ -90,10 +89,12 @@ pub fn open_project(name: &str, paths: Vec<String>) -> Result<(), Error> {
9089
"Opening {} in {}... \n\n{}",
9190
name,
9291
path.clone(),
93-
OPENING_WARNING
92+
DevmodeStatus::OpenedProjectWithWarning.to_string()
9493
);
9594
git_pull::status_short(path.clone())?;
96-
let options = Settings::current().ok_or(Error::Generic(APP_OPTIONS_NOT_FOUND))?;
95+
let options = Settings::current().ok_or(Error::String(
96+
DevmodeStatus::AppSettingsNotFound.to_string(),
97+
))?;
9798
if let Application::Custom = options.editor.app {
9899
let command_editor = options.editor.command;
99100
let route = path.replace('\\', "/");

src/settings.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ use libset::element::Content;
33
use libset::{config::Config, format::FileFormat, new_file};
44
use serde::{Deserialize, Serialize};
55

6-
use crate::constants::messages::*;
76
use crate::editor::Editor;
8-
use crate::Error;
7+
use crate::{DevmodeStatus, Error};
98

109
#[derive(Serialize, Deserialize, Debug, Clone, Default, Eq, PartialEq)]
1110
pub struct Settings {
@@ -51,15 +50,19 @@ impl Settings {
5150
if current_settings.is_none() {
5251
Config::set::<Settings>("devmode/settings.toml", self.clone(), FileFormat::TOML)
5352
.map_err(|e| Error::String(e.to_string()))?;
54-
log::info!("Settings set correctly.");
55-
} else if self != &current_settings.ok_or(Error::Generic(FAILED_TO_PARSE))? {
53+
crate::info(DevmodeStatus::SettingsUpdated);
54+
} else if self
55+
!= &current_settings.ok_or(Error::String(
56+
DevmodeStatus::FailedToParseSettings.to_string(),
57+
))?
58+
{
5659
Config::set::<Settings>("devmode/settings.toml", self.clone(), FileFormat::TOML)
5760
.map_err(|e| Error::String(e.to_string()))?;
5861
if !hide_output {
59-
log::info!("{}", SETTINGS_UPDATED);
62+
crate::info(DevmodeStatus::SettingsUpdated);
6063
}
6164
} else if !hide_output {
62-
log::info!("{}", NO_SETTINGS_CHANGED);
65+
crate::info(DevmodeStatus::NoSettingsChanged);
6366
}
6467
Ok(())
6568
}

src/status.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use std::fmt::Display;
2+
3+
#[derive(Debug)]
4+
pub enum DevmodeStatus {
5+
NoProjectFound,
6+
NoSettingsChanged,
7+
SettingsUpdated,
8+
FailedToWriteSettings,
9+
FailedToParseSettings,
10+
UnableToMapUrl,
11+
FailedToCloneRepository,
12+
FailedToSetRemote,
13+
FailedToGetBranch,
14+
OpenedProjectWithWarning,
15+
NoEditorSet,
16+
AppSettingsNotFound,
17+
}
18+
19+
impl Display for DevmodeStatus {
20+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21+
match self {
22+
DevmodeStatus::NoProjectFound => write!(f, "No project was found"),
23+
DevmodeStatus::NoSettingsChanged => write!(f, "No settings were changed"),
24+
DevmodeStatus::SettingsUpdated => write!(f, "Settings updated"),
25+
DevmodeStatus::FailedToWriteSettings => write!(f, "Failed to write settings"),
26+
DevmodeStatus::FailedToParseSettings => write!(f, "Failed to parse settings"),
27+
DevmodeStatus::UnableToMapUrl => write!(f, "Failed to map url"),
28+
DevmodeStatus::FailedToCloneRepository => write!(f, "Failed to clone repository"),
29+
DevmodeStatus::FailedToSetRemote => write!(f, "Failed to set remote repository"),
30+
DevmodeStatus::FailedToGetBranch => write!(f, "Failed to get branch"),
31+
DevmodeStatus::OpenedProjectWithWarning => {
32+
write!(
33+
f,
34+
"If the editor does not support openning from a path, open it yourself"
35+
)
36+
}
37+
DevmodeStatus::NoEditorSet => {
38+
write!(f, "No editor set, run `dm config -e` to configure it")
39+
}
40+
DevmodeStatus::AppSettingsNotFound => {
41+
write!(f, "The current app options could not be found.\nRun `dm cf --all` to reconfigure them")
42+
}
43+
}
44+
}
45+
}
46+
47+
pub fn info(status: DevmodeStatus) {
48+
println!("{}", status.to_string());
49+
}

0 commit comments

Comments
 (0)