use serde_json::{json, Value};
pub const EXIT_OK: i32 = 0;
pub const EXIT_RUNTIME: i32 = 1;
pub const EXIT_USAGE: i32 = 2;
pub const EXIT_GATE: i32 = 3;
pub fn envelope(command: &str, mut payload: Value, untrusted: &[&str]) -> Value {
if let Some(map) = payload.as_object_mut() {
map.insert(
"schemaVersion".into(),
json!(rhwp::schema_registry::ENVELOPE_SCHEMA_VERSION),
);
map.insert("tool".into(), json!("rhwp-agent"));
map.insert("command".into(), json!(command));
map.insert("version".into(), json!(rhwp::version()));
map.insert("untrustedContent".into(), json!(!untrusted.is_empty()));
map.insert("untrustedFields".into(), json!(untrusted));
}
payload
}
pub fn write_stdout(text: &str, newline: bool) {
use std::io::Write;
let stdout = std::io::stdout();
let mut lock = stdout.lock();
let result = if newline {
writeln!(lock, "{text}")
} else {
write!(lock, "{text}")
};
if let Err(e) = result {
eprintln!("오류: stdout 쓰기 실패 - {e}");
std::process::exit(EXIT_RUNTIME);
}
}
#[macro_export]
macro_rules! outln {
($($arg:tt)*) => { $crate::envelope::write_stdout(&format!($($arg)*), true) };
}
#[macro_export]
macro_rules! outp {
($($arg:tt)*) => { $crate::envelope::write_stdout(&format!($($arg)*), false) };
}
pub fn print_json(value: &Value) {
match serde_json::to_string_pretty(value) {
Ok(s) => crate::outln!("{s}"),
Err(e) => eprintln!("오류: JSON 직렬화 실패 - {e}"),
}
}
pub fn read_file(path: &str) -> Result<Vec<u8>, String> {
std::fs::read(path).map_err(|e| format!("파일을 읽을 수 없습니다 - {path}: {e}"))
}
pub struct LoadFail {
pub needs_password: bool,
pub message: String,
}
pub fn open_core(path: &str) -> Result<rhwp::document_core::DocumentCore, i32> {
let data = read_file(path).map_err(|m| {
eprintln!("오류: {m}");
EXIT_RUNTIME
})?;
load_core(&data).map_err(|fail| {
eprintln!("오류: 문서를 열 수 없습니다 - {path}: {}", fail.message);
EXIT_RUNTIME
})
}
pub fn field_display_name(field: &rhwp::document_core::queries::field_query::FieldInfo) -> String {
field
.field
.ctrl_data_name
.clone()
.filter(|n| !n.is_empty())
.unwrap_or_else(|| field.field.command.clone())
}
pub fn load_core(data: &[u8]) -> Result<rhwp::document_core::DocumentCore, LoadFail> {
rhwp::document_core::DocumentCore::from_bytes(data).map_err(|e| {
let message = e.to_string();
let lower = message.to_lowercase();
let needs_password =
message.contains("암호") || lower.contains("password") || lower.contains("encrypt");
LoadFail {
needs_password,
message,
}
})
}
pub fn format_token(format: rhwp::parser::FileFormat) -> &'static str {
use rhwp::parser::FileFormat;
match format {
FileFormat::Hwp => "hwp5",
FileFormat::Hwpx => "hwpx",
FileFormat::Hwp3 => "hwp3",
FileFormat::Hml => "hml",
FileFormat::Pdf => "pdf",
FileFormat::DrmProtected => "drm-protected",
FileFormat::Empty => "empty",
FileFormat::Unknown => "unknown",
}
}
pub fn page_texts(core: &rhwp::document_core::DocumentCore) -> Result<Vec<String>, String> {
let count = core.page_count();
let mut pages = Vec::with_capacity(count as usize);
for page in 0..count {
match core.extract_page_text_native(page) {
Ok(text) => pages.push(text),
Err(e) => return Err(format!("{page}쪽 텍스트 추출 실패 - {e}")),
}
}
Ok(pages)
}
pub fn hex_hash(data: &[u8]) -> String {
blake3::hash(data).to_hex().to_string()
}
pub fn text_hash(pages: &[String]) -> String {
let mut hasher = blake3::Hasher::new();
for page in pages {
hasher.update(page.as_bytes());
hasher.update(&[0x1e]);
}
hasher.finalize().to_hex().to_string()
}
pub fn closest<'a, I: Iterator<Item = &'a str>>(input: &str, candidates: I) -> Option<&'a str> {
let mut best: Option<(usize, &str)> = None;
for cand in candidates {
let d = levenshtein(input, cand);
if best.map(|(bd, _)| d < bd).unwrap_or(true) {
best = Some((d, cand));
}
}
best.and_then(|(d, name)| (d <= name.len().div_ceil(2)).then_some(name))
}
pub struct OneFile {
pub json: bool,
pub path: String,
}
pub fn one_file(args: &[String], usage: &str) -> Result<OneFile, i32> {
let mut json = false;
let mut path: Option<String> = None;
for arg in args {
match arg.as_str() {
"--json" => json = true,
other if other.starts_with('-') => {
eprintln!("오류: 알 수 없는 옵션입니다 - {other}");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
}
other => {
if path.is_some() {
eprintln!("오류: 파일이 너무 많습니다 - {other}");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
}
path = Some(other.to_string());
}
}
}
let Some(path) = path else {
eprintln!("오류: 파일 경로가 필요합니다.");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
};
Ok(OneFile { json, path })
}
pub fn two_files(args: &[String], usage: &str) -> Result<(bool, String, String), i32> {
let mut json = false;
let mut paths: Vec<String> = Vec::new();
for arg in args {
match arg.as_str() {
"--json" => json = true,
other if other.starts_with('-') => {
eprintln!("오류: 알 수 없는 옵션입니다 - {other}");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
}
other => paths.push(other.to_string()),
}
}
if paths.len() != 2 {
eprintln!("오류: 파일 두 개가 필요합니다.");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
}
Ok((json, paths[0].clone(), paths[1].clone()))
}
pub fn one_file_value(
args: &[String],
usage: &str,
flag: &str,
) -> Result<(OneFile, Option<String>), i32> {
let mut json = false;
let mut path: Option<String> = None;
let mut value: Option<String> = None;
let mut i = 0;
while i < args.len() {
let arg = args[i].as_str();
if arg == "--json" {
json = true;
i += 1;
continue;
}
if arg == flag {
let Some(v) = args.get(i + 1) else {
eprintln!("오류: {flag} 뒤에 값이 필요합니다.");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
};
value = Some(v.clone());
i += 2;
continue;
}
if arg.starts_with('-') {
eprintln!("오류: 알 수 없는 옵션입니다 - {arg}");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
}
if path.is_some() {
eprintln!("오류: 파일이 너무 많습니다 - {arg}");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
}
path = Some(arg.to_string());
i += 1;
}
let Some(path) = path else {
eprintln!("오류: 파일 경로가 필요합니다.");
eprintln!("사용법: {usage}");
return Err(EXIT_USAGE);
};
Ok((OneFile { json, path }, value))
}
fn levenshtein(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let mut prev: Vec<usize> = (0..=b.len()).collect();
let mut cur = vec![0usize; b.len() + 1];
for (i, ca) in a.iter().enumerate() {
cur[0] = i + 1;
for (j, cb) in b.iter().enumerate() {
let cost = if ca == cb { 0 } else { 1 };
cur[j + 1] = (prev[j] + cost).min(prev[j + 1] + 1).min(cur[j] + 1);
}
std::mem::swap(&mut prev, &mut cur);
}
prev[b.len()]
}