Skip to content

Commit df47590

Browse files
committed
SDS: run cargo fmt && clippy
Signed-off-by: Harshit Jain <reach@harsh1998.dev>
1 parent 8b1a404 commit df47590

11 files changed

Lines changed: 127 additions & 103 deletions

File tree

.github/workflows/rust.yml

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,18 @@ jobs:
3030
- uses: dtolnay/rust-toolchain@stable
3131
- run: cargo clippy -- -D warnings
3232

33-
coverage:
34-
name: Code coverage
35-
runs-on: ubuntu-latest
33+
macos:
34+
name: MacOS
35+
runs-on: macos-latest
36+
steps:
37+
- uses: actions/checkout@v4
38+
- uses: dtolnay/rust-toolchain@stable
39+
- run: cargo test --all-features -vv
40+
41+
windows:
42+
name: Windows
43+
runs-on: windows-latest
3644
steps:
3745
- uses: actions/checkout@v4
3846
- uses: dtolnay/rust-toolchain@stable
39-
- run: cargo install cargo-tarpaulin
40-
- run: cargo tarpaulin --ignore-tests
47+
- run: cargo test --all-features -vv

src/cli.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,4 @@ pub struct Cli {
5151
/// Password for basic authentication.
5252
#[arg(long)]
5353
pub password: Option<String>,
54-
}
54+
}

src/error.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,16 @@ pub enum AppError {
1717
impl fmt::Display for AppError {
1818
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1919
match self {
20-
AppError::Io(err) => write!(f, "IO error: {}", err),
21-
AppError::Glob(err) => write!(f, "Glob pattern error: {}", err),
22-
AppError::AddrParse(err) => write!(f, "Address parse error: {}", err),
20+
AppError::Io(err) => write!(f, "IO error: {err}"),
21+
AppError::Glob(err) => write!(f, "Glob pattern error: {err}"),
22+
AppError::AddrParse(err) => write!(f, "Address parse error: {err}"),
2323
AppError::InvalidPath => write!(f, "Invalid path"),
24-
AppError::DirectoryNotFound(path) => write!(f, "Directory not found: {}", path),
24+
AppError::DirectoryNotFound(path) => write!(f, "Directory not found: {path}"),
2525
AppError::Forbidden => write!(f, "Forbidden"),
2626
AppError::NotFound => write!(f, "Not Found"),
2727
AppError::BadRequest => write!(f, "Bad Request"),
2828
AppError::Unauthorized => write!(f, "Unauthorized"),
29-
AppError::InternalServerError(msg) => write!(f, "Internal server error: {}", msg),
29+
AppError::InternalServerError(msg) => write!(f, "Internal server error: {msg}"),
3030
}
3131
}
3232
}

src/fs.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,26 @@ use std::time::SystemTime;
1010

1111
/// Checks if the given path is a directory.
1212
pub fn is_directory(file_directory: &Arc<Mutex<PathBuf>>) -> Result<bool, AppError> {
13-
let dir_guard = file_directory.lock().map_err(|_| {
14-
AppError::InternalServerError("Failed to lock directory mutex".to_string())
15-
})?;
13+
let dir_guard = file_directory
14+
.lock()
15+
.map_err(|_| AppError::InternalServerError("Failed to lock directory mutex".to_string()))?;
1616
Ok(Path::new(&*dir_guard).is_dir())
1717
}
1818

1919
/// Generates an HTML directory listing for a given path.
2020
pub fn generate_directory_listing(path: &Path, log_prefix: &str) -> Result<String, AppError> {
21-
debug!("{} Generating directory listing for: '{}'", log_prefix, path.display());
21+
debug!(
22+
"{} Generating directory listing for: '{}'",
23+
log_prefix,
24+
path.display()
25+
);
2226

2327
let mut entries: Vec<PathBuf> = Vec::new();
2428
for entry_result in fs::read_dir(path)? {
2529
match entry_result {
2630
Ok(entry) => entries.push(entry.path()),
2731
Err(e) => {
28-
warn!("{} Skipping directory entry due to error: {}", log_prefix, e);
32+
warn!("{log_prefix} Skipping directory entry due to error: {e}");
2933
}
3034
}
3135
}
@@ -124,16 +128,19 @@ pub fn generate_directory_listing(path: &Path, log_prefix: &str) -> Result<Strin
124128
</tr>
125129
</thead>
126130
<tbody>
127-
{}
131+
{table_rows_html}
128132
</tbody>
129133
</table>
130134
</div>
131135
</body>
132136
</html>
133-
"#,
134-
table_rows_html
137+
"#
138+
);
139+
debug!(
140+
"{} Directory listing HTML generated for: '{}'",
141+
log_prefix,
142+
path.display()
135143
);
136-
debug!("{} Directory listing HTML generated for: '{}'", log_prefix, path.display());
137144
Ok(html)
138145
}
139146

@@ -150,7 +157,6 @@ pub fn generate_directory_row_html(path: &Path, _log_prefix: &str) -> Result<Str
150157
let relative_path = percent_encode_path(Path::new(&filename.to_string()));
151158

152159
Ok(format!(
153-
"<tr><td><a href=\"{}\">{}</a></td><td>{}</td><td>{}</td></tr>",
154-
relative_path, filename, file_size_human, last_modified_str
160+
"<tr><td><a href=\"{relative_path}\">{filename}</a></td><td>{file_size_human}</td><td>{last_modified_str}</td></tr>"
155161
))
156162
}

src/http.rs

Lines changed: 55 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
use base64::engine::general_purpose;
2-
use base64::Engine;
31
use crate::error::AppError;
42
use crate::fs::generate_directory_listing;
53
use crate::response::send_response;
64
use crate::utils::get_request_path;
5+
use base64::engine::general_purpose;
6+
use base64::Engine;
77
use glob::Pattern;
88
use log::{debug, error, info, warn};
99
use std::collections::HashMap;
@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};
1414
use std::sync::{Arc, Mutex};
1515
use std::time::Duration;
1616

17+
#[allow(clippy::too_many_arguments)]
1718
pub fn handle_client(
1819
mut stream: TcpStream,
1920
file_directory: &Arc<Mutex<PathBuf>>,
@@ -41,6 +42,7 @@ pub fn handle_client(
4142
}
4243
}
4344

45+
#[allow(clippy::too_many_arguments)]
4446
fn handle_request(
4547
stream: &mut TcpStream,
4648
file_directory: &Arc<Mutex<PathBuf>>,
@@ -64,7 +66,7 @@ fn handle_request(
6466
}
6567
};
6668

67-
debug!("{} Request line: {}", log_prefix, request_line);
69+
debug!("{log_prefix} Request line: {request_line}");
6870

6971
let mut headers_map = HashMap::new();
7072
for line in lines_iter {
@@ -77,14 +79,20 @@ fn handle_request(
7779
}
7880
}
7981

80-
if let (Some(username), Some(password)) = (username.as_ref().as_ref(), password.as_ref().as_ref()) {
82+
if let (Some(username), Some(password)) =
83+
(username.as_ref().as_ref(), password.as_ref().as_ref())
84+
{
8185
if !authenticate(&headers_map, username, password)? {
8286
return Err(AppError::Unauthorized);
8387
}
8488
}
8589

8690
let request_path_str = get_request_path(&request_line);
87-
let request_path = PathBuf::from(request_path_str.strip_prefix('/').unwrap_or(request_path_str));
91+
let request_path = PathBuf::from(
92+
request_path_str
93+
.strip_prefix('/')
94+
.unwrap_or(request_path_str),
95+
);
8896

8997
let full_path = file_directory.lock().unwrap().join(&request_path);
9098
let canonical_path = match full_path.canonicalize() {
@@ -108,13 +116,7 @@ fn handle_request(
108116
.iter()
109117
.any(|pattern| pattern.matches_path(&request_path))
110118
{
111-
serve_file(
112-
stream,
113-
&canonical_path,
114-
headers_map,
115-
chunk_size,
116-
log_prefix,
117-
)?;
119+
serve_file(stream, &canonical_path, headers_map, chunk_size, log_prefix)?;
118120
} else {
119121
warn!(
120122
"{} File extension not allowed for path: '{}'",
@@ -130,33 +132,42 @@ fn handle_request(
130132
fn send_error_response(stream: &mut TcpStream, err: AppError, log_prefix: &str) {
131133
let (status_code, status_text, body) = match err {
132134
AppError::NotFound => (404, "Not Found", "The requested resource was not found."),
133-
AppError::Forbidden => (403, "Forbidden", "You do not have permission to access this resource."),
134-
AppError::BadRequest => (400, "Bad Request", "The server could not understand the request."),
135+
AppError::Forbidden => (
136+
403,
137+
"Forbidden",
138+
"You do not have permission to access this resource.",
139+
),
140+
AppError::BadRequest => (
141+
400,
142+
"Bad Request",
143+
"The server could not understand the request.",
144+
),
135145
AppError::Unauthorized => (401, "Unauthorized", "Authentication required."),
136146
AppError::InternalServerError(ref msg) => (500, "Internal Server Error", msg.as_str()),
137147
AppError::Io(ref e)
138148
if e.kind() == ErrorKind::ConnectionReset
139149
|| e.kind() == ErrorKind::BrokenPipe
140150
|| e.kind() == ErrorKind::WouldBlock =>
141151
{
142-
warn!(
143-
"{} Connection error when sending response: {}",
144-
log_prefix, e
145-
);
152+
warn!("{log_prefix} Connection error when sending response: {e}");
146153
return;
147154
}
148-
_ => (500, "Internal Server Error", "An unexpected error occurred."),
155+
_ => (
156+
500,
157+
"Internal Server Error",
158+
"An unexpected error occurred.",
159+
),
149160
};
150161

151-
error!("{} Responding with error {}: {}", log_prefix, status_code, status_text);
162+
error!("{log_prefix} Responding with error {status_code}: {status_text}");
152163

153164
let mut headers = HashMap::new();
154165
if status_code == 401 {
155166
headers.insert("WWW-Authenticate", "Basic realm=\"Restricted\"");
156167
}
157168

158169
if let Err(e) = send_response(stream, status_code, status_text, body, log_prefix) {
159-
error!("{} Failed to send error response: {}", log_prefix, e);
170+
error!("{log_prefix} Failed to send error response: {e}");
160171
}
161172
}
162173

@@ -195,7 +206,11 @@ fn serve_file(
195206
chunk_size: usize,
196207
log_prefix: &str,
197208
) -> Result<(), AppError> {
198-
info!("{} serve_file started for: '{}'", log_prefix, path.display());
209+
info!(
210+
"{} serve_file started for: '{}'",
211+
log_prefix,
212+
path.display()
213+
);
199214
let mut file = match File::open(path) {
200215
Ok(f) => f,
201216
Err(e) if e.kind() == ErrorKind::NotFound => return Err(AppError::NotFound),
@@ -220,13 +235,11 @@ fn serve_file(
220235

221236
let content_length = end_byte - start_byte + 1;
222237
let mut response = format!(
223-
"HTTP/1.1 {} {}\r\nContent-Disposition: attachment; filename=\"{}\"\r\nContent-Length: {}\r\nContent-Type: application/octet-stream\r\nAccept-Ranges: bytes\r\n",
224-
status_code, status_text, filename, content_length
238+
"HTTP/1.1 {status_code} {status_text}\r\nContent-Disposition: attachment; filename=\"{filename}\"\r\nContent-Length: {content_length}\r\nContent-Type: application/octet-stream\r\nAccept-Ranges: bytes\r\n"
225239
);
226240
if status_code == 206 {
227241
response.push_str(&format!(
228-
"Content-Range: bytes {}-{}/{}\r\n",
229-
start_byte, end_byte, file_size
242+
"Content-Range: bytes {start_byte}-{end_byte}/{file_size}\r\n"
230243
));
231244
}
232245
response.push_str("\r\n");
@@ -246,20 +259,28 @@ fn serve_file(
246259
bytes_remaining -= bytes_read as u64;
247260
}
248261

249-
info!("{} serve_file finished for: '{}'", log_prefix, path.display());
262+
info!(
263+
"{} serve_file finished for: '{}'",
264+
log_prefix,
265+
path.display()
266+
);
250267
Ok(())
251268
}
252269

253270
/// Serves a directory listing as an HTML page.
254-
fn serve_directory(
255-
stream: &mut TcpStream,
256-
path: &Path,
257-
log_prefix: &str,
258-
) -> Result<(), AppError> {
259-
info!("{} serve_directory started for: '{}'", log_prefix, path.display());
271+
fn serve_directory(stream: &mut TcpStream, path: &Path, log_prefix: &str) -> Result<(), AppError> {
272+
info!(
273+
"{} serve_directory started for: '{}'",
274+
log_prefix,
275+
path.display()
276+
);
260277
let html = generate_directory_listing(path, log_prefix)?;
261278
send_response(stream, 200, "OK", &html, log_prefix)?;
262-
info!("{} serve_directory finished for: '{}'", log_prefix, path.display());
279+
info!(
280+
"{} serve_directory finished for: '{}'",
281+
log_prefix,
282+
path.display()
283+
);
263284
Ok(())
264285
}
265286

src/lib.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,16 @@
55
/// This library contains the core logic for the server. The `run` function
66
/// initializes and starts the server based on command-line arguments.
77
pub mod cli;
8-
pub mod response;
9-
pub mod server;
108
pub mod error;
11-
pub mod http;
129
pub mod fs;
10+
pub mod http;
11+
pub mod response;
12+
pub mod server;
1313
pub mod utils;
1414

15-
use log::{error};
1615
use crate::cli::Cli;
1716
use clap::Parser;
17+
use log::error;
1818

1919
/// Initializes the logger, parses command-line arguments, and starts the server.
2020
///
@@ -37,12 +37,10 @@ pub fn run() {
3737
}
3838
env_logger::init();
3939

40-
log::debug!("Log level set to: {}", log_level);
40+
log::debug!("Log level set to: {log_level}");
4141

4242
if let Err(e) = server::run_server(cli, None, None) {
43-
error!("Server error: {}", e);
43+
error!("Server error: {e}");
4444
std::process::exit(1);
4545
}
4646
}
47-
48-

src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ use hdl_sv::run;
22

33
fn main() {
44
run();
5-
}
5+
}

0 commit comments

Comments
 (0)