11
This commit is contained in:
67
src-tauri/src/oem_id.rs
Normal file
67
src-tauri/src/oem_id.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
//! 从应用数据目录的 `oem` 文件读取 OEM 编号。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
pub const DEFAULT_OEM_ID: i64 = 1;
|
||||
|
||||
/// 应用数据目录下的 OEM 配置文件名。
|
||||
pub const OEM_FILE_NAME: &str = "oem";
|
||||
|
||||
pub fn read_oem_id_file(path: &Path) -> i64 {
|
||||
let content = match std::fs::read_to_string(path) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return DEFAULT_OEM_ID,
|
||||
};
|
||||
parse_oem_id_content(&content).unwrap_or(DEFAULT_OEM_ID)
|
||||
}
|
||||
|
||||
fn parse_oem_id_content(content: &str) -> Option<i64> {
|
||||
let trimmed = content.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
|
||||
if let Some(id) = value.get("oem_id").and_then(|v| v.as_i64()) {
|
||||
if id >= 1 {
|
||||
return Some(id);
|
||||
}
|
||||
}
|
||||
if let Some(id) = value.as_i64() {
|
||||
if id >= 1 {
|
||||
return Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let first_line = trimmed.lines().next()?.trim();
|
||||
let id: i64 = first_line.parse().ok()?;
|
||||
if id >= 1 {
|
||||
Some(id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_integer_line() {
|
||||
assert_eq!(parse_oem_id_content("2\n"), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_json_object() {
|
||||
assert_eq!(parse_oem_id_content(r#"{"oem_id":3}"#), Some(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_defaults_none() {
|
||||
assert_eq!(parse_oem_id_content("abc"), None);
|
||||
assert_eq!(parse_oem_id_content(""), None);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user