Skip to content

Commit 3342baa

Browse files
committed
style: format Rust sources
1 parent c466ebf commit 3342baa

19 files changed

Lines changed: 189 additions & 242 deletions

‎src-tauri/src/commands.rs‎

Lines changed: 26 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,13 @@ pub async fn config_all(state: State<'_, AppState>, _args: Args) -> Result<Value
136136

137137
#[tauri::command]
138138
pub async fn config_get(state: State<'_, AppState>, args: Args) -> Result<Value, StorageError> {
139-
let key = args
140-
.first()
141-
.and_then(Value::as_str)
142-
.ok_or_else(|| StorageError::InvalidConfigValue {
143-
key: "<arg0>".into(),
144-
reason: "config_get requires a string key as the first argument".into(),
145-
})?;
139+
let key =
140+
args.first()
141+
.and_then(Value::as_str)
142+
.ok_or_else(|| StorageError::InvalidConfigValue {
143+
key: "<arg0>".into(),
144+
reason: "config_get requires a string key as the first argument".into(),
145+
})?;
146146
let cfg = state.config.lock().expect("config mutex poisoned");
147147
Ok(cfg.get_key(key).unwrap_or(Value::Null))
148148
}
@@ -280,11 +280,7 @@ fn apply_launch_at_login(app: &AppHandle<Wry>, enabled: bool) -> Result<(), Stor
280280
///
281281
/// Pinned to `Wry` because the HTTP API server is itself pinned to
282282
/// `Wry` (see the comment in `http_api.rs`).
283-
fn apply_side_effects(
284-
app: &AppHandle<Wry>,
285-
state: &AppState,
286-
touched_keys: &[&str],
287-
) {
283+
fn apply_side_effects(app: &AppHandle<Wry>, state: &AppState, touched_keys: &[&str]) {
288284
let touches_http_api = touched_keys
289285
.iter()
290286
.any(|k| *k == "http_api_on" || *k == "http_api_only_local");
@@ -411,11 +407,7 @@ pub async fn get_content_of_list(
411407
cfg.remove_duplicate_records
412408
};
413409

414-
let content = hosts_apply::aggregate_selected_content(
415-
&list,
416-
&state.paths,
417-
remove_duplicate,
418-
)?;
410+
let content = hosts_apply::aggregate_selected_content(&list, &state.paths, remove_duplicate)?;
419411
Ok(json!(content))
420412
}
421413

@@ -807,9 +799,8 @@ pub async fn get_apply_history(
807799
) -> Result<Value, StorageError> {
808800
let path = state.paths.histories_dir.join("system-hosts.json");
809801
let items = hosts_apply::history::load(&path)?;
810-
let value = serde_json::to_value(items).map_err(|e| {
811-
StorageError::serialize(path.display().to_string(), e)
812-
})?;
802+
let value = serde_json::to_value(items)
803+
.map_err(|e| StorageError::serialize(path.display().to_string(), e))?;
813804
Ok(value)
814805
}
815806

@@ -833,9 +824,8 @@ pub async fn cmd_get_history_list(
833824
) -> Result<Value, StorageError> {
834825
let path = state.paths.histories_dir.join("cmd-after-apply.json");
835826
let items = hosts_apply::cmd_runner::load(&path)?;
836-
let value = serde_json::to_value(items).map_err(|e| {
837-
StorageError::serialize(path.display().to_string(), e)
838-
})?;
827+
let value = serde_json::to_value(items)
828+
.map_err(|e| StorageError::serialize(path.display().to_string(), e))?;
839829
Ok(value)
840830
}
841831

@@ -882,10 +872,7 @@ pub async fn find_set_window_title<R: Runtime + 'static>(
882872
}
883873

884874
#[tauri::command]
885-
pub async fn find_by(
886-
state: State<'_, AppState>,
887-
args: Args,
888-
) -> Result<Value, String> {
875+
pub async fn find_by(state: State<'_, AppState>, args: Args) -> Result<Value, String> {
889876
let keyword = args
890877
.first()
891878
.and_then(Value::as_str)
@@ -901,27 +888,20 @@ pub async fn find_by(
901888
}
902889

903890
#[tauri::command]
904-
pub async fn find_replace_one(
905-
state: State<'_, AppState>,
906-
args: Args,
907-
) -> Result<Value, String> {
891+
pub async fn find_replace_one(state: State<'_, AppState>, args: Args) -> Result<Value, String> {
908892
let request = args
909893
.into_iter()
910894
.next()
911895
.ok_or_else(|| "find_replace_one: args[0] must be a request object".to_string())
912896
.and_then(|v| {
913-
serde_json::from_value(v)
914-
.map_err(|e| format!("find_replace_one: invalid request: {e}"))
897+
serde_json::from_value(v).map_err(|e| format!("find_replace_one: invalid request: {e}"))
915898
})?;
916899
let replaced = find::replace_one_in_manifest(state.inner(), request)?;
917900
Ok(json!(replaced))
918901
}
919902

920903
#[tauri::command]
921-
pub async fn find_replace_all(
922-
state: State<'_, AppState>,
923-
args: Args,
924-
) -> Result<Value, String> {
904+
pub async fn find_replace_all(state: State<'_, AppState>, args: Args) -> Result<Value, String> {
925905
let keyword = args
926906
.first()
927907
.and_then(Value::as_str)
@@ -1079,9 +1059,7 @@ pub async fn open_url(args: Args) -> Value {
10791059
return Value::Null;
10801060
};
10811061
let lower = url.to_ascii_lowercase();
1082-
if lower.starts_with("http://")
1083-
|| lower.starts_with("https://")
1084-
|| lower.starts_with("mailto:")
1062+
if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:")
10851063
{
10861064
let _ = open::that(url);
10871065
} else {
@@ -1234,10 +1212,7 @@ pub async fn import_data<R: Runtime>(
12341212
}
12351213

12361214
#[tauri::command]
1237-
pub async fn import_data_from_url(
1238-
state: State<'_, AppState>,
1239-
args: Args,
1240-
) -> Result<Value, String> {
1215+
pub async fn import_data_from_url(state: State<'_, AppState>, args: Args) -> Result<Value, String> {
12411216
let url = arg_str(&args, 0, "url").map_err(|e| format!("{e:?}"))?;
12421217

12431218
// Build the HTTP client outside of any lock so the proxy snapshot
@@ -1357,7 +1332,13 @@ pub async fn download_update<R: Runtime>(
13571332
.download_and_install(
13581333
move |downloaded, total| {
13591334
let percent = total
1360-
.map(|t| if t > 0 { (downloaded as f64 / t as f64) * 100.0 } else { 0.0 })
1335+
.map(|t| {
1336+
if t > 0 {
1337+
(downloaded as f64 / t as f64) * 100.0
1338+
} else {
1339+
0.0
1340+
}
1341+
})
13611342
.unwrap_or(0.0);
13621343
let _ = app_for_progress.emit(
13631344
"update_download_progress",

‎src-tauri/src/hosts_apply/aggregate.rs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -96,15 +96,15 @@ fn parse_line(line: &str) -> ParsedLine {
9696
Some((before, after)) => (before, after.trim().to_string()),
9797
None => (line, String::new()),
9898
};
99-
let normalized: String = cnt
100-
.trim()
101-
.split_whitespace()
102-
.collect::<Vec<_>>()
103-
.join(" ");
99+
let normalized: String = cnt.trim().split_whitespace().collect::<Vec<_>>().join(" ");
104100
let mut parts = normalized.split(' ').filter(|s| !s.is_empty());
105101
let ip = parts.next().unwrap_or("").to_string();
106102
let domains: Vec<String> = parts.map(|s| s.to_string()).collect();
107-
ParsedLine { ip, domains, comment }
103+
ParsedLine {
104+
ip,
105+
domains,
106+
comment,
107+
}
108108
}
109109

110110
fn format_line(ip: &str, domains: &[String], comment: &str) -> String {

‎src-tauri/src/hosts_apply/cmd_runner.rs‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,7 @@ pub fn load(path: &Path) -> Result<Vec<CommandRunResult>, StorageError> {
145145
if !path.exists() {
146146
return Ok(Vec::new());
147147
}
148-
let bytes = std::fs::read(path)
149-
.map_err(|e| StorageError::io(path.display().to_string(), e))?;
148+
let bytes = std::fs::read(path).map_err(|e| StorageError::io(path.display().to_string(), e))?;
150149
match serde_json::from_slice::<Vec<CommandRunResult>>(&bytes) {
151150
Ok(v) => Ok(v),
152151
Err(_) => match serde_json::from_slice::<Value>(&bytes) {
@@ -155,10 +154,7 @@ pub fn load(path: &Path) -> Result<Vec<CommandRunResult>, StorageError> {
155154
.filter_map(|v| serde_json::from_value::<CommandRunResult>(v).ok())
156155
.collect()),
157156
_ => {
158-
log::warn!(
159-
"{} could not be parsed; treating as empty.",
160-
path.display()
161-
);
157+
log::warn!("{} could not be parsed; treating as empty.", path.display());
162158
Ok(Vec::new())
163159
}
164160
},

‎src-tauri/src/hosts_apply/elevation.rs‎

Lines changed: 13 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,7 @@ mod security_ffi {
105105
authorization: *mut AuthorizationRef,
106106
) -> OSStatus;
107107

108-
pub fn AuthorizationFree(
109-
authorization: AuthorizationRef,
110-
flags: u32,
111-
) -> OSStatus;
108+
pub fn AuthorizationFree(authorization: AuthorizationRef, flags: u32) -> OSStatus;
112109

113110
pub fn AuthorizationExecuteWithPrivileges(
114111
authorization: AuthorizationRef,
@@ -176,12 +173,7 @@ fn get_or_create_auth() -> Result<security_ffi::AuthorizationRef, HostsApplyErro
176173

177174
let mut auth_ref: security_ffi::AuthorizationRef = std::ptr::null_mut();
178175
let status = unsafe {
179-
security_ffi::AuthorizationCreate(
180-
&mut rights,
181-
std::ptr::null(),
182-
flags,
183-
&mut auth_ref,
184-
)
176+
security_ffi::AuthorizationCreate(&mut rights, std::ptr::null(), flags, &mut auth_ref)
185177
};
186178

187179
match status {
@@ -251,13 +243,12 @@ fn execute_privileged_copy(
251243
std::ptr::null(),
252244
];
253245

254-
let exit = unsafe {
255-
run_privileged(auth_ref, b"/bin/cp\0".as_ptr(), cp_args.as_ptr())
256-
}?;
246+
let exit = unsafe { run_privileged(auth_ref, b"/bin/cp\0".as_ptr(), cp_args.as_ptr()) }?;
257247
if exit != 0 {
258248
return Err(HostsApplyError::Io {
259249
message: format!("/bin/cp exited with status {exit}"),
260-
}.into());
250+
}
251+
.into());
261252
}
262253

263254
// --- /bin/chmod 644 dst ---
@@ -267,13 +258,12 @@ fn execute_privileged_copy(
267258
std::ptr::null(),
268259
];
269260

270-
let exit = unsafe {
271-
run_privileged(auth_ref, b"/bin/chmod\0".as_ptr(), chmod_args.as_ptr())
272-
}?;
261+
let exit = unsafe { run_privileged(auth_ref, b"/bin/chmod\0".as_ptr(), chmod_args.as_ptr()) }?;
273262
if exit != 0 {
274263
return Err(HostsApplyError::Io {
275264
message: format!("/bin/chmod exited with status {exit}"),
276-
}.into());
265+
}
266+
.into());
277267
}
278268

279269
Ok(())
@@ -301,8 +291,7 @@ unsafe fn run_privileged(
301291
&mut pipe as *mut *mut libc::FILE as *mut *mut std::ffi::c_void,
302292
);
303293
if status != security_ffi::ERR_AUTHORIZATION_SUCCESS {
304-
let tool_name = std::ffi::CStr::from_ptr(tool as *const i8)
305-
.to_string_lossy();
294+
let tool_name = std::ffi::CStr::from_ptr(tool as *const i8).to_string_lossy();
306295
return Err(MacElevateError::AuthExec(
307296
status,
308297
format!("AEWP({tool_name}): OSStatus {status}"),
@@ -345,16 +334,13 @@ fn elevate_copy(src: &Path, dst: &Path) -> Result<(), HostsApplyError> {
345334

346335
match execute_privileged_copy(auth_ref, src, dst) {
347336
Ok(()) => Ok(()),
348-
Err(MacElevateError::AuthExec(status, msg))
349-
if is_auth_stale(status) =>
350-
{
337+
Err(MacElevateError::AuthExec(status, msg)) if is_auth_stale(status) => {
351338
// Cached authorization was invalidated (timeout, revocation).
352339
// Clear it and retry once — the retry will re-prompt the user.
353340
log::info!("{msg} — re-prompting");
354341
invalidate_cached_auth();
355342
let auth_ref = get_or_create_auth()?;
356-
execute_privileged_copy(auth_ref, src, dst)
357-
.map_err(mac_elevate_to_hosts_error)
343+
execute_privileged_copy(auth_ref, src, dst).map_err(mac_elevate_to_hosts_error)
358344
}
359345
Err(e) => Err(mac_elevate_to_hosts_error(e)),
360346
}
@@ -485,8 +471,8 @@ fn elevate_copy(src: &Path, dst: &Path) -> Result<(), HostsApplyError> {
485471
GetExitCodeProcess, WaitForSingleObject, INFINITE,
486472
};
487473
use windows_sys::Win32::UI::Shell::{
488-
ShellExecuteExW, SEE_MASK_FLAG_NO_UI, SEE_MASK_NOASYNC,
489-
SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,
474+
ShellExecuteExW, SEE_MASK_FLAG_NO_UI, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS,
475+
SHELLEXECUTEINFOW,
490476
};
491477
use windows_sys::Win32::UI::WindowsAndMessaging::SW_HIDE;
492478

‎src-tauri/src/hosts_apply/history.rs‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@ pub fn load(path: &Path) -> Result<Vec<ApplyHistoryItem>, StorageError> {
3838
if !path.exists() {
3939
return Ok(Vec::new());
4040
}
41-
let bytes = std::fs::read(path)
42-
.map_err(|e| StorageError::io(path.display().to_string(), e))?;
41+
let bytes = std::fs::read(path).map_err(|e| StorageError::io(path.display().to_string(), e))?;
4342
// Tolerate either the bare array we write or a wrapped envelope a
4443
// future schema change might add. Unknown wrapping → empty list +
4544
// warning, the journal isn't critical.
@@ -51,10 +50,7 @@ pub fn load(path: &Path) -> Result<Vec<ApplyHistoryItem>, StorageError> {
5150
.filter_map(|v| serde_json::from_value::<ApplyHistoryItem>(v).ok())
5251
.collect()),
5352
_ => {
54-
log::warn!(
55-
"{} could not be parsed; treating as empty.",
56-
path.display()
57-
);
53+
log::warn!("{} could not be parsed; treating as empty.", path.display());
5854
Ok(Vec::new())
5955
}
6056
},
@@ -70,11 +66,7 @@ pub fn save(path: &Path, items: &[ApplyHistoryItem]) -> Result<(), StorageError>
7066
/// Insert a new entry at the end of the journal and trim to
7167
/// `history_limit`. A non-positive limit means "no cap" (matches the
7268
/// Electron behaviour where `history_limit <= 0` skips the trim block).
73-
pub fn insert(
74-
path: &Path,
75-
item: ApplyHistoryItem,
76-
history_limit: i32,
77-
) -> Result<(), StorageError> {
69+
pub fn insert(path: &Path, item: ApplyHistoryItem, history_limit: i32) -> Result<(), StorageError> {
7870
let mut items = load(path)?;
7971
items.push(item);
8072
if history_limit > 0 && items.len() as i32 > history_limit {

‎src-tauri/src/http_api.rs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -203,10 +203,7 @@ async fn api_toggle(
203203
// including choice_mode / folder cascading semantics from
204204
// `setOnStateOfItem`. The envelope is the same `_args` shape every
205205
// other Tauri broadcast in this codebase uses.
206-
let _ = state.app.emit(
207-
"toggle_item",
208-
json!({ "_args": [id, !on] }),
209-
);
206+
let _ = state.app.emit("toggle_item", json!({ "_args": [id, !on] }));
210207
"ok"
211208
}
212209

‎src-tauri/src/import_export.rs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,10 @@ fn import_v4(data: &Value, paths: &V5Paths) -> Result<Value, StorageError> {
243243
.save(paths)?;
244244

245245
if !history_data.is_empty() {
246-
write_history(&paths.histories_dir.join("system-hosts.json"), &history_data)?;
246+
write_history(
247+
&paths.histories_dir.join("system-hosts.json"),
248+
&history_data,
249+
)?;
247250
}
248251

249252
Ok(json!(true))
@@ -353,9 +356,8 @@ pub fn export_to_file(dest: &Path, paths: &V5Paths) -> Result<(), StorageError>
353356
},
354357
});
355358

356-
let bytes = serde_json::to_vec_pretty(&backup).map_err(|e| {
357-
StorageError::serialize(dest.display().to_string(), e)
358-
})?;
359+
let bytes = serde_json::to_vec_pretty(&backup)
360+
.map_err(|e| StorageError::serialize(dest.display().to_string(), e))?;
359361
atomic_write(dest, &bytes)
360362
}
361363

@@ -688,7 +690,8 @@ mod tests {
688690
"format": "switchhosts-backup",
689691
"schemaVersion": 1,
690692
"version": [5, 0, 0, 0],
691-
})).unwrap();
693+
}))
694+
.unwrap();
692695
let result = import_backup_bytes(&bytes, &paths).unwrap();
693696
assert_eq!(result, json!(ERR_INVALID_DATA));
694697
cleanup(&paths);

0 commit comments

Comments
 (0)