Skip to content

Commit ad7ea09

Browse files
committed
Refactor formatting and improve code consistency
This commit refactors code for improved formatting, readability, and consistency across multiple modules. It includes reordering imports, expanding multi-line expressions, improving error handling, updating function signatures, and enhancing test assertions. No functional changes are introduced.
1 parent 456db7c commit ad7ea09

34 files changed

Lines changed: 456 additions & 315 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@
66

77
assets/myadam.jpg
88
.github/copilot-instructions.md
9+
docs/UPDATE_SUMMARIES.md

crates/cargo-rustapi/src/cli.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! CLI argument parsing
22
3+
use crate::commands::{self, GenerateArgs, NewArgs, RunArgs};
34
use clap::{Parser, Subcommand};
4-
use crate::commands::{self, NewArgs, RunArgs, GenerateArgs};
55

66
/// RustAPI CLI - Project scaffolding and development utilities
77
#[derive(Parser, Debug)]

crates/cargo-rustapi/src/commands/docs.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,32 @@ use console::style;
66
/// Open API documentation in browser
77
pub async fn open_docs(port: u16) -> Result<()> {
88
let url = format!("http://localhost:{}/docs", port);
9-
9+
1010
println!("Opening {} in browser...", style(&url).cyan());
11-
11+
1212
// Try to open in browser
1313
#[cfg(target_os = "windows")]
1414
{
1515
tokio::process::Command::new("cmd")
1616
.args(["/C", "start", &url])
1717
.spawn()?;
1818
}
19-
19+
2020
#[cfg(target_os = "macos")]
2121
{
22-
tokio::process::Command::new("open")
23-
.arg(&url)
24-
.spawn()?;
22+
tokio::process::Command::new("open").arg(&url).spawn()?;
2523
}
26-
24+
2725
#[cfg(target_os = "linux")]
2826
{
29-
tokio::process::Command::new("xdg-open")
30-
.arg(&url)
31-
.spawn()?;
27+
tokio::process::Command::new("xdg-open").arg(&url).spawn()?;
3228
}
3329

3430
println!();
35-
println!("{}", style("Make sure your RustAPI server is running!").yellow());
31+
println!(
32+
"{}",
33+
style("Make sure your RustAPI server is running!").yellow()
34+
);
3635
println!("Start it with: {}", style("cargo rustapi run").cyan());
3736

3837
Ok(())

crates/cargo-rustapi/src/commands/generate.rs

Lines changed: 57 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,11 @@ pub async fn generate(args: GenerateArgs) -> Result<()> {
3939

4040
async fn generate_handler(name: &str) -> Result<()> {
4141
let handlers_dir = Path::new("src/handlers");
42-
42+
4343
// Create handlers directory if it doesn't exist
4444
if !handlers_dir.exists() {
4545
fs::create_dir_all(handlers_dir).await?;
46-
46+
4747
// Create mod.rs
4848
let mod_content = format!("pub mod {};\n", name);
4949
fs::write(handlers_dir.join("mod.rs"), mod_content).await?;
@@ -131,27 +131,50 @@ pub struct Update{type_name} {{
131131
let handler_path = handlers_dir.join(format!("{}.rs", name));
132132
fs::write(&handler_path, handler_content).await?;
133133

134-
println!("{} Generated handler: {}", style("✓").green(), handler_path.display());
134+
println!(
135+
"{} Generated handler: {}",
136+
style("✓").green(),
137+
handler_path.display()
138+
);
135139
println!();
136140
println!("Don't forget to register the routes in main.rs:");
137-
println!(" {}", style(format!(".mount(handlers::{}::list)", name)).cyan());
138-
println!(" {}", style(format!(".mount(handlers::{}::get)", name)).cyan());
139-
println!(" {}", style(format!(".mount(handlers::{}::create)", name)).cyan());
140-
println!(" {}", style(format!(".mount(handlers::{}::update)", name)).cyan());
141-
println!(" {}", style(format!(".mount(handlers::{}::delete)", name)).cyan());
141+
println!(
142+
" {}",
143+
style(format!(".mount(handlers::{}::list)", name)).cyan()
144+
);
145+
println!(
146+
" {}",
147+
style(format!(".mount(handlers::{}::get)", name)).cyan()
148+
);
149+
println!(
150+
" {}",
151+
style(format!(".mount(handlers::{}::create)", name)).cyan()
152+
);
153+
println!(
154+
" {}",
155+
style(format!(".mount(handlers::{}::update)", name)).cyan()
156+
);
157+
println!(
158+
" {}",
159+
style(format!(".mount(handlers::{}::delete)", name)).cyan()
160+
);
142161

143162
Ok(())
144163
}
145164

146165
async fn generate_model(name: &str) -> Result<()> {
147166
let models_dir = Path::new("src/models");
148-
167+
149168
// Create models directory if it doesn't exist
150169
if !models_dir.exists() {
151170
fs::create_dir_all(models_dir).await?;
152-
171+
153172
// Create mod.rs
154-
let mod_content = format!("mod {};\npub use {}::*;\n", name.to_lowercase(), name.to_lowercase());
173+
let mod_content = format!(
174+
"mod {};\npub use {}::*;\n",
175+
name.to_lowercase(),
176+
name.to_lowercase()
177+
);
155178
fs::write(models_dir.join("mod.rs"), mod_content).await?;
156179
} else {
157180
// Append to existing mod.rs
@@ -160,7 +183,10 @@ async fn generate_model(name: &str) -> Result<()> {
160183
let mut content = fs::read_to_string(&mod_path).await?;
161184
let lower_name = name.to_lowercase();
162185
if !content.contains(&format!("mod {};", lower_name)) {
163-
content.push_str(&format!("mod {};\npub use {}::*;\n", lower_name, lower_name));
186+
content.push_str(&format!(
187+
"mod {};\npub use {}::*;\n",
188+
lower_name, lower_name
189+
));
164190
fs::write(&mod_path, content).await?;
165191
}
166192
}
@@ -210,16 +236,23 @@ impl {} {{
210236
let model_path = models_dir.join(format!("{}.rs", name.to_lowercase()));
211237
fs::write(&model_path, model_content).await?;
212238

213-
println!("{} Generated model: {}", style("✓").green(), model_path.display());
239+
println!(
240+
"{} Generated model: {}",
241+
style("✓").green(),
242+
model_path.display()
243+
);
214244

215245
Ok(())
216246
}
217247

218248
async fn generate_crud(name: &str) -> Result<()> {
219249
// Generate both handler and model
220250
let type_name = to_pascal_case(name);
221-
222-
println!("{}", style(format!("Generating CRUD for '{}'...", name)).bold());
251+
252+
println!(
253+
"{}",
254+
style(format!("Generating CRUD for '{}'...", name)).bold()
255+
);
223256
println!();
224257

225258
generate_model(&type_name).await?;
@@ -238,16 +271,18 @@ fn capitalize(s: &str) -> String {
238271
}
239272

240273
fn to_pascal_case(s: &str) -> String {
241-
s.split(&['-', '_'][..])
242-
.map(capitalize)
243-
.collect()
274+
s.split(&['-', '_'][..]).map(capitalize).collect()
244275
}
245276

246277
fn singularize(s: &str) -> String {
247-
if s.ends_with("ies") {
248-
format!("{}y", &s[..s.len() - 3])
249-
} else if s.ends_with('s') && !s.ends_with("ss") {
250-
s[..s.len() - 1].to_string()
278+
if let Some(stripped) = s.strip_suffix("ies") {
279+
format!("{}y", stripped)
280+
} else if let Some(stripped) = s.strip_suffix('s') {
281+
if !s.ends_with("ss") {
282+
stripped.to_string()
283+
} else {
284+
s.to_string()
285+
}
251286
} else {
252287
s.to_string()
253288
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
//! CLI commands
22
3+
mod docs;
4+
mod generate;
35
mod new;
46
mod run;
5-
mod generate;
6-
mod docs;
77

8+
pub use docs::open_docs;
9+
pub use generate::{generate, GenerateArgs};
810
pub use new::{new_project, NewArgs};
911
pub use run::{run_dev, RunArgs};
10-
pub use generate::{generate, GenerateArgs};
11-
pub use docs::open_docs;

crates/cargo-rustapi/src/commands/new.rs

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,12 @@ pub async fn new_project(mut args: NewArgs) -> Result<()> {
6363
} else if args.yes {
6464
ProjectTemplate::Minimal
6565
} else {
66-
let templates = ["minimal - Bare minimum app", "api - REST API with CRUD", "web - Web app with templates", "full - Full-featured app"];
66+
let templates = [
67+
"minimal - Bare minimum app",
68+
"api - REST API with CRUD",
69+
"web - Web app with templates",
70+
"full - Full-featured app",
71+
];
6772
let selection = Select::with_theme(&theme)
6873
.with_prompt("Select a template")
6974
.items(&templates)
@@ -98,7 +103,10 @@ pub async fn new_project(mut args: NewArgs) -> Result<()> {
98103
.defaults(&defaults)
99104
.interact()?;
100105

101-
selections.iter().map(|&i| available[i].to_string()).collect()
106+
selections
107+
.iter()
108+
.map(|&i| available[i].to_string())
109+
.collect()
102110
};
103111

104112
// Confirm
@@ -107,7 +115,15 @@ pub async fn new_project(mut args: NewArgs) -> Result<()> {
107115
println!("{}", style("Project configuration:").bold());
108116
println!(" Name: {}", style(&name).cyan());
109117
println!(" Template: {}", style(format!("{:?}", template)).cyan());
110-
println!(" Features: {}", style(if features.is_empty() { "none".to_string() } else { features.join(", ") }).cyan());
118+
println!(
119+
" Features: {}",
120+
style(if features.is_empty() {
121+
"none".to_string()
122+
} else {
123+
features.join(", ")
124+
})
125+
.cyan()
126+
);
111127
println!();
112128

113129
if !Confirm::with_theme(&theme)
@@ -144,16 +160,25 @@ pub async fn new_project(mut args: NewArgs) -> Result<()> {
144160

145161
// Success message
146162
println!();
147-
println!("{}", style("✨ Project created successfully!").green().bold());
163+
println!(
164+
"{}",
165+
style("✨ Project created successfully!").green().bold()
166+
);
148167
println!();
149168
println!("Next steps:");
150169
println!(" {} {}", style("cd").cyan(), name);
151-
println!(" {} {}", style("cargo").cyan(), "run");
170+
println!(" {} run", style("cargo").cyan());
152171
println!();
153-
println!("Then open {} in your browser.", style("http://localhost:8080").cyan());
154-
172+
println!(
173+
"Then open {} in your browser.",
174+
style("http://localhost:8080").cyan()
175+
);
176+
155177
if features.iter().any(|f| f == "swagger-ui") || template == ProjectTemplate::Full {
156-
println!("API docs available at {}", style("http://localhost:8080/docs").cyan());
178+
println!(
179+
"API docs available at {}",
180+
style("http://localhost:8080/docs").cyan()
181+
);
157182
}
158183

159184
Ok(())
@@ -170,8 +195,13 @@ fn validate_project_name(name: &str) -> Result<()> {
170195
}
171196

172197
// Check for valid Rust crate name characters
173-
if !name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
174-
anyhow::bail!("Project name can only contain alphanumeric characters, hyphens, and underscores");
198+
if !name
199+
.chars()
200+
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
201+
{
202+
anyhow::bail!(
203+
"Project name can only contain alphanumeric characters, hyphens, and underscores"
204+
);
175205
}
176206

177207
if name.starts_with('-') || name.starts_with('_') {

crates/cargo-rustapi/src/commands/run.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,17 @@ async fn run_with_watch(args: &RunArgs) -> Result<()> {
7777

7878
if check.is_err() || !check.unwrap().status.success() {
7979
println!("{}", style("cargo-watch not found. Installing...").yellow());
80-
80+
8181
let install = Command::new("cargo")
8282
.args(["install", "cargo-watch"])
8383
.status()
8484
.await?;
8585

8686
if !install.success() {
87-
println!("{}", style("Failed to install cargo-watch. Running without watch mode.").yellow());
87+
println!(
88+
"{}",
89+
style("Failed to install cargo-watch. Running without watch mode.").yellow()
90+
);
8891
return run_cargo(args).await;
8992
}
9093
}

crates/cargo-rustapi/src/templates/full.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ pub async fn generate(name: &str, features: &[String]) -> Result<()> {
1212
"rate-limit".to_string(),
1313
"config".to_string(),
1414
];
15-
15+
1616
// Add user-specified features
1717
for f in features {
1818
if !all_features.contains(f) {
@@ -417,10 +417,7 @@ RUST_LOG=info
417417
fs::write(format!("{name}/.env.example"), env_example).await?;
418418

419419
// Copy .env.example to .env for development
420-
fs::copy(
421-
format!("{name}/.env.example"),
422-
format!("{name}/.env"),
423-
).await?;
420+
fs::copy(format!("{name}/.env.example"), format!("{name}/.env")).await?;
424421

425422
// .gitignore
426423
common::generate_gitignore(name).await?;

crates/cargo-rustapi/src/templates/mod.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
//! Project templates
22
3-
mod minimal;
43
mod api;
5-
mod web;
64
mod full;
5+
mod minimal;
6+
mod web;
77

88
use anyhow::Result;
99
use clap::ValueEnum;
@@ -91,8 +91,14 @@ RUST_LOG=info
9191
if features.is_empty() {
9292
String::new()
9393
} else {
94-
format!(", features = [{}]",
95-
features.iter().map(|f| format!("\"{}\"", f)).collect::<Vec<_>>().join(", "))
94+
format!(
95+
", features = [{}]",
96+
features
97+
.iter()
98+
.map(|f| format!("\"{}\"", f))
99+
.collect::<Vec<_>>()
100+
.join(", ")
101+
)
96102
}
97103
}
98104
}

crates/rustapi-core/src/app.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -468,9 +468,7 @@ impl RustApi {
468468
let path = req.uri().path().to_string();
469469

470470
Box::pin(async move {
471-
let relative_path = path
472-
.strip_prefix(&config.prefix)
473-
.unwrap_or(&path);
471+
let relative_path = path.strip_prefix(&config.prefix).unwrap_or(&path);
474472

475473
match crate::static_files::StaticFile::serve(relative_path, &config).await {
476474
Ok(response) => response,

0 commit comments

Comments
 (0)