use std::env;
use std::fs;
use std::path::Path;
use std::process;
mod agent_profiles;
mod anchor_log;
mod atomic_file;
mod audit_standard;
mod capsule_sign;
mod cli;
mod disclose;
mod lineage_bundle;
mod mcp_serve;
mod policy_gate;
mod settle;
use cli::commands::edit::runtime::{
check_expect_sha256, edit_output_format, edit_serialize, edit_verify_report, finish_edit_write,
EditOutputFormat,
};
pub(crate) use cli::commands::edit::{
measure_cell_overflow, recolor_cell_text_black, resolve_table_cell,
set_cell_control_char_rejection, CellResolveError,
};
pub(crate) use cli::document_io::{
classify_hwp_error, cli_output_password, cli_password, load_document, load_document_core,
LoadError,
};
use cli::document_io::{
has_global_auth_option, is_batch_invocation, set_cli_output_password, set_cli_password,
strip_global_auth_options, strip_utf8_bom,
};
use cli::integrity::{
cas_test_mark_checked_and_wait, cas_test_synchronize_before_lock, sha256_hex_of, CasPathLock,
};
pub(crate) use cli::units::{hu_to_mm, hu_to_mm_i};
use rhwp::provenance;
use rhwp::schema_registry::ENVELOPE_SCHEMA_VERSION;
const EXIT_OK: i32 = 0;
const EXIT_RUNTIME: i32 = 1;
const EXIT_USAGE: i32 = 2;
fn exit_with(exit_code: i32) {
if exit_code != EXIT_OK {
process::exit(exit_code);
}
}
fn verification_exit_code(page_failed: bool, ir_failed: bool) -> i32 {
if page_failed {
4
} else if ir_failed {
3
} else {
EXIT_OK
}
}
#[cfg(test)]
mod verification_exit_code_tests {
use super::verification_exit_code;
#[test]
fn page_failure_keeps_precedence_when_ir_also_fails() {
assert_eq!(verification_exit_code(false, false), 0);
assert_eq!(verification_exit_code(false, true), 3);
assert_eq!(verification_exit_code(true, false), 4);
assert_eq!(verification_exit_code(true, true), 4);
}
}
fn main() {
let raw_args: Vec<String> = env::args().collect();
if raw_args
.get(1)
.is_some_and(|arg| arg == "__pdf-import-worker-v1")
{
process::exit(cli::commands::pdf_import::run_worker());
}
if is_batch_invocation(&raw_args) && has_global_auth_option(&raw_args) {
eprintln!(
"오류: batch 는 --password·--password-stdin·--output-password·--output-password-stdin 을 지원하지 않습니다. stdin 은 파일 경로 목록 전용입니다."
);
process::exit(EXIT_USAGE);
}
let args = match strip_global_auth_options(raw_args) {
Ok(v) => v,
Err(code) => process::exit(code),
};
if let Some(code) = cli::metadata::help::scoped_help(&args[1..]) {
process::exit(code);
}
match args.get(1).map(|s| s.as_str()) {
Some("--help") | Some("-h") => cli::metadata::help::print_help(),
Some("--version") | Some("-V") => println!("rhwp v{}", rhwp::version()),
Some("export-svg") => exit_with(cli::outputs::vector::export_svg(&args[2..])),
Some("export-render-tree") => {
exit_with(cli::outputs::vector::export_render_tree(&args[2..]))
}
Some("export-structure") => {
exit_with(cli::queries::structure::export_structure(&args[2..]))
}
Some("export-png") => exit_with(cli::outputs::raster::export_png(&args[2..])),
Some("export-kitty") => exit_with(cli::outputs::kitty::export_kitty(&args[2..])),
Some("export-sixel") => exit_with(cli::outputs::sixel::export_sixel(&args[2..])),
Some("export-pdf") => exit_with(cli::outputs::pdf::export_pdf(&args[2..])),
Some("export-text") => exit_with(cli::outputs::text::export_text(&args[2..])),
Some("export-markdown") => exit_with(cli::outputs::text::export_markdown(&args[2..])),
Some("export-tables") => exit_with(cli::outputs::tabular::export_tables(&args[2..])),
Some("export-llm") => exit_with(cli::outputs::text::export_llm(&args[2..])),
Some("table-to-csv") => exit_with(cli::outputs::tabular::table_to_csv(&args[2..])),
Some("csv-to-table") => exit_with(cli::commands::tabular_import::csv_to_table(&args[2..])),
Some("chart-to-csv") => exit_with(cli::outputs::tabular::chart_to_csv(&args[2..])),
Some("csv-to-chart") => exit_with(cli::commands::tabular_import::csv_to_chart(&args[2..])),
Some("export-hwpx") => exit_with(cli::commands::conversion::export_hwpx(&args[2..])),
Some("import-pdf") => exit_with(cli::commands::pdf_import::import_pdf(&args[2..])),
Some("export-hml") => cli::commands::conversion::export_hml(&args[2..]),
Some("export-doclang") => exit_with(cli::outputs::doclang::export_doclang(&args[2..])),
Some("export-ir-schema") => exit_with(cmd_export_ir_schema(&args[2..])),
Some("export-capabilities-schema") => exit_with(cmd_export_capabilities_schema(&args[2..])),
Some("export-ontology") => exit_with(cmd_export_ontology(&args[2..])),
Some("capabilities") => {
exit_with(cli::metadata::capabilities::show_capabilities(&args[2..]))
}
Some("export-provenance-map") => exit_with(
cli::metadata::capabilities::export_provenance_map(&args[2..]),
),
Some("export-agent-manifest") => exit_with(cmd_export_agent_manifest(&args[2..])),
Some("mcp-serve") => exit_with(mcp_serve::run(&args[2..])),
Some("batch") => exit_with(cli::batch::run(&args[2..])),
Some("scan") => exit_with(cli::queries::scan::run(&args[2..])),
Some("threat-scan") => {
exit_with(cli::queries::security_inspection::threat_scan(&args[2..]))
}
Some("info") => exit_with(cli::queries::info::run(&args[2..])),
Some("word-count") => exit_with(cli::queries::document_inventory::word_count(&args[2..])),
Some("bookmarks") => exit_with(cli::queries::document_inventory::bookmarks(&args[2..])),
Some("charts") => exit_with(cli::queries::document_inventory::charts(&args[2..])),
Some("form-value") => exit_with(cli::queries::structured_objects::form_value(&args[2..])),
Some("header-footer") => {
exit_with(cli::queries::structured_objects::header_footer(&args[2..]))
}
Some("headers-footers") => exit_with(cli::queries::structured_objects::headers_footers(
&args[2..],
)),
Some("digest") => exit_with(cli::queries::digest::digest_document(&args[2..])),
Some("dump") => exit_with(cli::queries::control_dump::run(&args[2..])),
Some("dump-note-shape") => {
exit_with(cli::queries::diagnostics::dump_note_shape(&args[2..]))
}
Some("dump-endnote-lines") => {
exit_with(cli::queries::diagnostics::dump_endnote_lines(&args[2..]))
}
Some("dump-pages") => exit_with(cli::queries::page_dump::run(&args[2..])),
Some("dump-extents") => exit_with(cli::queries::diagnostics::dump_extents(&args[2..])),
Some("diag") => exit_with(cli::queries::diagnostics::diag_document(&args[2..])),
Some("search") => exit_with(cli::queries::search::search_document(&args[2..])),
Some("inspect") => exit_with(inspect_command(&args[2..])),
Some("armor") => exit_with(cli::queries::security_inspection::armor_command(&args[2..])),
Some("extract-data") => exit_with(cli::queries::data_extraction::extract_data_command(
&args[2..],
)),
Some("convert") => exit_with(cli::commands::conversion::convert_hwp(&args[2..])),
Some("extract-pages") => exit_with(cli::commands::conversion::extract_pages(&args[2..])),
Some("build-from-ingest") => {
exit_with(cli::commands::generation::build_from_ingest(&args[2..]))
}
Some("scaffold") => exit_with(cli::commands::generation::run_scaffold(&args[2..])),
Some("hwp5-inventory") => exit_with(rhwp::diagnostics::hwp5_inventory::run(&args[2..])),
Some("hwp5-inventory-diff") => {
exit_with(rhwp::diagnostics::hwp5_inventory_diff::run(&args[2..]))
}
Some("hwp5-contract-analyze") => {
exit_with(rhwp::diagnostics::hwp5_contract_analyze::run(&args[2..]))
}
Some("hwp5-ctrl-data-trace") => {
exit_with(rhwp::diagnostics::hwp5_ctrl_data_trace::run(&args[2..]))
}
Some("hwp5-contract-probe") => {
exit_with(rhwp::diagnostics::hwp5_contract_probe::run(&args[2..]))
}
Some("hwp5-table-probe") => exit_with(rhwp::diagnostics::hwp5_table_probe::run(&args[2..])),
Some("hwp5-mel-personnel-probe") => {
exit_with(rhwp::diagnostics::hwp5_mel_personnel_probe::run(&args[2..]))
}
Some("hwp5-borderfill-diagonal-probe") => exit_with(
rhwp::diagnostics::hwp5_borderfill_diagonal_probe::run(&args[2..]),
),
Some("hwp5-first-para-control-probe") => exit_with(
rhwp::diagnostics::hwp5_first_para_control_probe::run(&args[2..]),
),
Some("hwp5-anchor-trace") => {
exit_with(rhwp::diagnostics::hwp5_anchor_trace::run(&args[2..]))
}
Some("hwp5-char-shape-audit") => {
exit_with(rhwp::diagnostics::hwp5_char_shape_audit::run(&args[2..]))
}
Some("hwp5-cell-header-probe") => {
exit_with(rhwp::diagnostics::hwp5_cell_header_probe::run(&args[2..]))
}
Some("dump-records") => exit_with(cli::queries::diagnostics::dump_raw_records(&args[2..])),
Some("test-shape") => exit_with(test_shape_roundtrip(&args[2..])),
Some("test-caption") => exit_with(cli::commands::caption_validation::run(&args[2..])),
Some("gen-table") => exit_with(gen_table(&args[2..])),
Some("gen-pua") => exit_with(gen_pua_test(&args[2..])),
Some("test-field") => exit_with(cli::commands::internal_validation::run(&args[2..])),
Some("ir-diff") => exit_with(cli::queries::ir_comparison::ir_diff(&args[2..])),
Some("ir-sweep") => exit_with(cli::queries::ir_comparison::ir_sweep(&args[2..])),
Some("dump-anchors") => {
exit_with(cli::queries::position_diagnostics::dump_anchors(&args[2..]))
}
Some("dump-carets") => {
exit_with(cli::queries::position_diagnostics::dump_carets(&args[2..]))
}
Some("verify") => exit_with(cli::queries::verification::run(&args[2..])),
Some("hwpx-roundtrip") => rhwp::diagnostics::hwpx_roundtrip_batch::run(&args[2..]),
Some("hwp5-roundtrip") => rhwp::diagnostics::hwp5_roundtrip_batch::run(&args[2..]),
Some("render-diff") => rhwp::diagnostics::render_geom_diff::run(&args[2..]),
Some("layout-anomaly") => exit_with(rhwp::diagnostics::layout_anomaly::run(&args[2..])),
Some("measure-width") => exit_with(rhwp::diagnostics::text_width_probe::run(&args[2..])),
Some("core-pages") => exit_with(rhwp::diagnostics::core_pages_probe::run(&args[2..])),
Some("bench") => exit_with(rhwp::diagnostics::bench::run(&args[2..])),
Some("thumbnail") => exit_with(cli::outputs::preview::extract_thumbnail(&args[2..])),
Some("fields") => exit_with(cli::queries::document_inventory::show_fields(&args[2..])),
Some("explain") => exit_with(cli::queries::explain::explain_document(&args[2..])),
Some("explore") => exit_with(cli::queries::explore::explore_document(&args[2..])),
Some("edit") => exit_with(cli::commands::edit::run(&args[2..])),
Some("run") => exit_with(cli::protocol::cmd_run_plan(&args[2..])),
Some("replay") => exit_with(cli::protocol::cmd_replay(&args[2..])),
Some("audit") => exit_with(cli::protocol::cmd_audit(&args[2..])),
Some("lineage") => exit_with(cli::protocol::cmd_lineage(&args[2..])),
Some("keygen") => exit_with(cli::protocol::cmd_keygen(&args[2..])),
Some("verify-signature") => exit_with(cli::protocol::cmd_verify_signature(&args[2..])),
Some("harness") => exit_with(cli::protocol::cmd_harness(&args[2..])),
Some("harness-status") => exit_with(cli::protocol::cmd_harness_status(&args[2..])),
Some("anchor") => exit_with(cli::protocol::cmd_anchor(&args[2..])),
Some("gate") => exit_with(cli::protocol::cmd_gate(&args[2..])),
Some("bundle") => exit_with(cli::protocol::cmd_bundle(&args[2..])),
Some("disclose") => exit_with(cli::protocol::cmd_disclose(&args[2..])),
Some("settle") => exit_with(cli::protocol::cmd_settle(&args[2..])),
Some("audit-report") => exit_with(cli::protocol::cmd_audit_report(&args[2..])),
Some("recall-scope") => exit_with(cli::protocol::cmd_recall_scope(&args[2..])),
Some("conformance") => exit_with(cli::protocol::cmd_conformance(&args[2..])),
Some("export-plan-schema") => exit_with(cmd_export_plan_schema(&args[2..])),
other => {
let recovery: Option<(String, &str)> = match other {
Some(command) => {
eprintln!("오류: 알 수 없는 명령입니다 - {}", command);
let names = cli::metadata::capabilities::capabilities_command_names();
let hint = cli::metadata::capabilities::closest_name(
command,
names.iter().map(String::as_str),
);
if let Some(hint) = &hint {
eprintln!("힌트: 가장 가까운 명령은 '{hint}' 입니다");
}
hint.map(|h| (h, "요청한 이름이 없음 — 가장 가까운 실존 명령으로 교정"))
}
None => {
eprintln!("오류: 명령을 지정해주세요.");
Some((
"capabilities".to_string(),
"명령이 지정되지 않음 — 실행 가능한 명령 목록·계약은 capabilities 가 자기서술",
))
}
};
eprintln!("rhwp v{}", rhwp::version());
eprintln!("사용법: rhwp <명령> [옵션]");
eprintln!("'rhwp --help'로 자세한 사용법을 확인하세요.");
if let Some((name, why)) = recovery {
cli::metadata::capabilities::eprint_usage_recovery(&name, None, why);
}
process::exit(EXIT_USAGE);
}
}
}
fn tables_json_value(
file_path: &str,
tables: &[rhwp::document_core::queries::table_extract::TableGrid],
) -> serde_json::Value {
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"tableCount": tables.len(),
"tables": tables,
}),
"export-tables",
)
}
fn fields_json_value(file_path: &str, fields: &[serde_json::Value]) -> serde_json::Value {
let names: Vec<String> = fields
.iter()
.filter_map(|f| f["name"].as_str().map(String::from))
.collect();
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"fieldCount": fields.len(),
"fields": fields,
"textSecurity": text_security_value(&names),
}),
"fields",
)
}
fn text_security_value(names: &[String]) -> serde_json::Value {
use rhwp::document_core::text_security as ts;
let mut findings: Vec<serde_json::Value> = Vec::new();
for (_, group) in ts::confusable_collisions(names) {
findings.push(serde_json::json!({
"kind": "confusableFieldName",
"scope": "fieldName",
"names": group,
"note": "이름이 화면상 구별되지 않는 누름틀이 둘 이상입니다 — 이름으로 지목해 채우면 의도와 다른 칸이 채워질 수 있습니다. occurrence 대신 hwp_fields 가 돌려준 바이트를 그대로 쓰거나, 사람 확인을 거치세요.",
}));
}
for name in names {
for risk in ts::scan_identifier(name) {
findings.push(serde_json::json!({
"kind": risk.kind.label(),
"scope": "fieldName",
"names": [name],
"codepoints": risk.codepoints.iter().map(|c| ts::format_codepoint(*c))
.collect::<Vec<_>>(),
"note": risk.kind.describe(),
}));
}
}
if findings.is_empty() {
return serde_json::json!({ "status": "clean" });
}
serde_json::json!({
"status": "warning",
"findingCount": findings.len(),
"findings": findings,
})
}
fn search_json_value(
file_path: &str,
query: &str,
case_sensitive: bool,
matches: &[rhwp::document_core::queries::grep::GrepMatch],
total_match_count: usize,
) -> serde_json::Value {
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"query": query,
"caseSensitive": case_sensitive,
"matchCount": matches.len(),
"totalMatchCount": total_match_count,
"truncated": matches.len() < total_match_count,
"omittedCount": total_match_count.saturating_sub(matches.len()),
"matches": matches,
}),
"search",
)
}
fn truncate_page_texts(
pages: &[(u32, String)],
max_chars: Option<usize>,
) -> (Vec<serde_json::Value>, usize) {
let mut objs = Vec::with_capacity(pages.len());
let mut budget = max_chars;
let mut omitted_total = 0usize;
for (page, text) in pages {
let total = text.chars().count();
let keep = match budget {
Some(remaining) => remaining.min(total),
None => total,
};
if let Some(remaining) = budget.as_mut() {
*remaining -= keep;
}
let omitted = total - keep;
omitted_total += omitted;
let kept: String = if omitted == 0 {
text.clone()
} else {
text.chars().take(keep).collect()
};
let mut obj = serde_json::json!({ "page": page, "text": kept });
if omitted > 0 {
obj["truncated"] = serde_json::json!(true);
obj["omittedCount"] = serde_json::json!(omitted);
}
objs.push(obj);
}
(objs, omitted_total)
}
const TITLE_SCAN_PAGES: u32 = 3;
fn document_title(doc: &rhwp::wasm_api::HwpDocument) -> Option<String> {
for page in 0..doc.page_count().min(TITLE_SCAN_PAGES) {
let Ok(text) = doc.extract_page_text_native(page) else {
continue;
};
if let Some(line) = text.lines().map(str::trim).find(|l| !l.is_empty()) {
return Some(line.to_string());
}
}
None
}
fn info_json_value(
file_path: &str,
file_size: usize,
detected_format: rhwp::parser::FileFormat,
doc: &rhwp::wasm_api::HwpDocument,
) -> serde_json::Value {
let document = doc.document();
let format_str = match detected_format {
rhwp::parser::FileFormat::Hwp => "hwp5",
rhwp::parser::FileFormat::Hwpx => "hwpx",
rhwp::parser::FileFormat::Hwp3 => "hwp3",
rhwp::parser::FileFormat::Hml => "hml",
rhwp::parser::FileFormat::Pdf => "pdf",
rhwp::parser::FileFormat::DrmProtected => "drm-protected",
rhwp::parser::FileFormat::Empty => "empty",
rhwp::parser::FileFormat::Unknown => "unknown",
};
let version = if matches!(
detected_format,
rhwp::parser::FileFormat::Hml | rhwp::parser::FileFormat::Pdf
) {
serde_json::Value::Null
} else {
serde_json::Value::String(format!(
"{}.{}.{}.{}",
document.header.version.major,
document.header.version.minor,
document.header.version.build,
document.header.version.revision,
))
};
let fonts: Vec<String> = document
.doc_info
.font_faces
.iter()
.flatten()
.map(|face| face.name.clone())
.collect();
let para_count: usize = document.sections.iter().map(|s| s.paragraphs.len()).sum();
let last_saved_with = match detected_format {
rhwp::parser::FileFormat::Hwp => {
rhwp::parser::hwp_summary::last_saved_with(&document.extra_streams)
}
rhwp::parser::FileFormat::Hwpx => {
rhwp::parser::hwp_summary::hwpx_last_saved_with(&document.hwpx_aux_entries)
}
_ => None,
}
.map(|save_version| {
serde_json::json!({
"product": save_version.product,
"version": save_version.version,
"confidence": "metadata",
})
});
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"format": format_str,
"sizeBytes": file_size,
"version": version,
"sections": document.sections.len(),
"pageCount": doc.page_count(),
"paraCount": para_count,
"fonts": fonts,
"title": document_title(doc),
"lastSavedWith": last_saved_with,
"printMethod": doc.document().doc_info.print_method,
"printMethodImpliesNup": rhwp::model::document::print_method_implies_nup(
doc.document().doc_info.print_method,
),
"warnings": info_warnings_value(doc),
}),
"info",
)
}
fn info_warnings_value(doc: &rhwp::wasm_api::HwpDocument) -> serde_json::Value {
let Some(metadata) = doc.hml_metadata() else {
return serde_json::Value::Array(Vec::new());
};
serde_json::Value::Array(
metadata
.warnings
.iter()
.map(|w| {
serde_json::json!({
"code": format!("{:?}", w.code),
"xmlPath": w.xml_path,
"message": w.message,
})
})
.collect(),
)
}
fn extract_data_json_value(
file_path: &str,
kind: &str,
items: &[rhwp::document_core::queries::extract_data::DataItem],
total_item_count: usize,
counts: &serde_json::Value,
) -> serde_json::Value {
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"kind": kind,
"itemCount": items.len(),
"totalItemCount": total_item_count,
"truncated": items.len() < total_item_count,
"counts": counts,
"items": items,
}),
"extract-data",
)
}
#[derive(Debug, Default, Clone, Copy)]
struct ConversionVerifyOptions {
verify: bool,
verify_pages: bool,
json: bool,
}
impl ConversionVerifyOptions {
fn enabled(self) -> bool {
self.verify || self.verify_pages
}
}
fn paths_refer_to_same_file(input: &Path, output: &Path) -> bool {
input == output
|| paths_have_same_file_identity(input, output)
|| match (input.canonicalize(), output.canonicalize()) {
(Ok(input), Ok(output)) => input == output,
_ => false,
}
}
#[cfg(unix)]
fn paths_have_same_file_identity(input: &Path, output: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
match (input.metadata(), output.metadata()) {
(Ok(input), Ok(output)) => input.dev() == output.dev() && input.ino() == output.ino(),
_ => false,
}
}
#[cfg(not(unix))]
fn paths_have_same_file_identity(_input: &Path, _output: &Path) -> bool {
false
}
fn validate_internal_positionals(command: &str, args: &[String], max: usize) -> Result<(), i32> {
if let Some(flag) = args.iter().find(|arg| arg.starts_with('-')) {
eprintln!("오류: {command} 은 알 수 없는 옵션을 받지 않습니다 - {flag}");
return Err(EXIT_USAGE);
}
if args.len() > max {
eprintln!("오류: {command} 은 위치 인자를 최대 {max}개만 받습니다.");
return Err(EXIT_USAGE);
}
Ok(())
}
fn test_shape_roundtrip(args: &[String]) -> i32 {
if let Err(code) = validate_internal_positionals("test-shape", args, 2) {
return code;
}
let input = if args.is_empty() {
"saved/g555-s.hwp"
} else {
&args[0]
};
let output = if args.len() > 1 {
&args[1]
} else {
"/tmp/test-shape-out.hwp"
};
let data = match fs::read(input) {
Ok(d) => d,
Err(e) => {
eprintln!("입력 파일 읽기 오류: {}", e);
return EXIT_RUNTIME;
}
};
let mut doc = match rhwp::wasm_api::HwpDocument::from_bytes(&data) {
Ok(d) => d,
Err(e) => {
eprintln!("HWP 파싱 오류: {:?}", e);
return EXIT_RUNTIME;
}
};
let _ = doc.convert_to_editable_native();
let result = doc.create_shape_control_native(
0,
0,
0,
9000,
6750,
0,
0,
false,
"InFrontOfText",
"rectangle",
false,
false,
&[],
);
match &result {
Ok(r) => eprintln!("글상자 생성 성공: {}", r),
Err(e) => {
eprintln!("글상자 생성 실패: {:?}", e);
return EXIT_RUNTIME;
}
}
match doc.export_hwp_native() {
Ok(bytes) => {
if let Err(e) = fs::write(output, &bytes) {
eprintln!("파일 저장 오류: {}", e);
return EXIT_RUNTIME;
}
eprintln!("저장 완료: {} ({}KB)", output, bytes.len() / 1024);
EXIT_OK
}
Err(e) => {
eprintln!("직렬화 오류: {:?}", e);
EXIT_RUNTIME
}
}
}
fn gen_table(args: &[String]) -> i32 {
if let Err(code) = validate_internal_positionals("gen-table", args, 3) {
return code;
}
let rows = match args.first() {
Some(value) => match value.parse::<u16>() {
Ok(value) => value,
Err(_) => {
eprintln!("오류: gen-table 행 수는 0~65535 정수여야 합니다 - {value}");
return EXIT_USAGE;
}
},
None => 1000,
};
let cols = match args.get(1) {
Some(value) => match value.parse::<u16>() {
Ok(value) => value,
Err(_) => {
eprintln!("오류: gen-table 열 수는 0~65535 정수여야 합니다 - {value}");
return EXIT_USAGE;
}
},
None => 6,
};
let output = args
.get(2)
.map(|s| s.as_str())
.unwrap_or("output/gen_table.hwp");
println!("{}행 × {}열 표 생성 중...", rows, cols);
let mut core = rhwp::document_core::DocumentCore::new_empty();
core.create_blank_document_native()
.expect("빈 문서 생성 실패");
let result = core
.create_table_native(0, 0, 0, rows, cols)
.expect("표 생성 실패");
println!(" 표 생성: {}", result);
let table_para_idx: usize = result
.split("\"paraIdx\":")
.nth(1)
.and_then(|s| s.split(&[',', '}'][..]).next())
.and_then(|s| s.trim().parse().ok())
.unwrap_or(1);
println!(" 표 문단 인덱스: {}", table_para_idx);
core.begin_batch_native().expect("배치 시작 실패");
let headers = ["번호", "이름", "부서", "직급", "연락처", "비고"];
for (ci, header) in headers.iter().enumerate().take(cols as usize) {
let _ = core.insert_text_in_cell_native(0, table_para_idx, 0, ci, 0, 0, header);
}
let departments = ["개발팀", "기획팀", "디자인팀", "영업팀", "인사팀", "재무팀"];
let positions = ["사원", "대리", "과장", "차장", "부장"];
for row in 1..rows as usize {
for col in 0..cols as usize {
let cell_idx = row * cols as usize + col;
let text = match col {
0 => format!("{}", row),
1 => format!("홍길동{}", row),
2 => departments[row % departments.len()].to_string(),
3 => positions[row % positions.len()].to_string(),
4 => format!(
"010-{:04}-{:04}",
1000 + row % 9000,
1000 + (row * 7) % 9000
),
5 => {
if row % 3 == 0 {
"특이사항 없음".to_string()
} else {
String::new()
}
}
_ => format!("R{}C{}", row, col),
};
if !text.is_empty() {
let _ =
core.insert_text_in_cell_native(0, table_para_idx, 0, cell_idx, 0, 0, &text);
}
}
if row % 100 == 0 {
println!(" {} / {} 행 완료", row, rows);
}
}
core.end_batch_native().expect("배치 종료 실패");
println!(" 셀 내용 입력 완료");
let bytes = core.export_hwp_native().expect("HWP 내보내기 실패");
let out_path = Path::new(output);
if let Some(parent) = out_path.parent() {
fs::create_dir_all(parent).ok();
}
if let Err(e) = fs::write(out_path, bytes) {
eprintln!("오류: 파일 저장 실패 - {}: {}", output, e);
return EXIT_RUNTIME;
}
println!("저장 완료: {} ({}행 × {}열)", output, rows, cols);
EXIT_OK
}
fn gen_pua_test(args: &[String]) -> i32 {
if let Err(code) = validate_internal_positionals("gen-pua", args, 1) {
return code;
}
let explicit = args.first().map(|s| s.as_str());
if let Some(path) = explicit {
if Path::new(path).exists() {
eprintln!("오류: gen-pua 의 인자는 생성할 **출력** 경로입니다 (입력 파일이 아닙니다).");
eprintln!(" 이미 존재하는 파일을 덮어쓰지 않습니다: {}", path);
eprintln!("사용법: rhwp gen-pua [출력경로] # 기본 output/pua-test.hwp");
return EXIT_USAGE;
}
}
let output = explicit.unwrap_or("output/pua-test.hwp");
println!("PUA 문자 셋트 입력 HWP 문서 생성 중...");
let mut core = rhwp::document_core::DocumentCore::new_empty();
core.create_blank_document_native()
.expect("빈 문서 생성 실패");
let pua_set: &[(u32, &str, &str, &str)] = &[
(0x0F076, "Basic", "mel-001", "❖ U+2756"),
(0x0F09F, "Basic", "biz_plan", "• U+2022"),
(0x0F0A0, "Basic", "synam-001", "▪ U+25AA"),
(0x0F0A7, "Basic", "kps-ai", "▪ U+25AA"),
(0x0F0E8, "Basic", "kps-ai", "(미정의)"),
(0x0F0F2, "Basic", "KTX", "⇩ U+21E9 (의도 정정 후보)"),
(0x0F0FE, "Basic", "k-water-rfp", "☑ U+2611"),
(0x0F53A, "Basic-out", "hwpspec", "(매핑 표 외)"),
(0xF02B1, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B2, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B3, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B4, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B5, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B6, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B7, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B8, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02B9, "Suppl-A", "mel-001", "(매핑 표 외)"),
(0xF02EF, "Suppl-A", "KTX (회귀)", "(매핑 표 외) ★"),
];
println!(" PUA 코드포인트 {} 종 입력", pua_set.len());
core.begin_batch_native().expect("배치 시작 실패");
let title = "[PUA 회귀 검증 — Task #509]";
core.insert_text_native(0, 0, 0, title)
.expect("제목 입력 실패");
for (i, &(cp, area, sample, mapping)) in pua_set.iter().enumerate() {
let pi = i + 1;
core.insert_paragraph_native(0, pi)
.unwrap_or_else(|e| panic!("paragraph 추가 실패 (pi={}): {:?}", pi, e));
let pua_char =
char::from_u32(cp).unwrap_or_else(|| panic!("invalid codepoint U+{:05X}", cp));
let text = format!(
"U+{:05X} ({}, {}, {}): {} ← 한컴 PDF 정답지",
cp, area, sample, mapping, pua_char
);
core.insert_text_native(0, pi, 0, &text)
.unwrap_or_else(|e| panic!("텍스트 입력 실패 (pi={}): {:?}", pi, e));
}
core.end_batch_native().expect("배치 종료 실패");
let bytes = core.export_hwp_native().expect("HWP 내보내기 실패");
let out_path = Path::new(output);
if let Some(parent) = out_path.parent() {
fs::create_dir_all(parent).ok();
}
if let Err(e) = fs::write(out_path, bytes) {
eprintln!("오류: 파일 저장 실패 - {}: {}", output, e);
return EXIT_RUNTIME;
}
println!("저장 완료: {} ({} 종 PUA)", output, pua_set.len());
println!();
println!("다음 단계:");
println!(" 1. 한컴 2022 편집기에서 본 파일 열기 → PDF 출력 (정답지)");
println!(" 2. rhwp export-svg {} → SVG 출력 비교", output);
println!(" 3. 시각 비교로 매핑 정합 확정");
EXIT_OK
}
pub(crate) fn collect_field_records(doc: &rhwp::wasm_api::HwpDocument) -> Vec<serde_json::Value> {
use rhwp::document_core::queries::field_query::NestedEntry;
doc.collect_all_fields()
.iter()
.map(|fi| {
let nested: Vec<serde_json::Value> = fi
.location
.nested_path
.iter()
.map(|e| match e {
NestedEntry::TableCell {
control_index,
cell_index,
para_index,
} => serde_json::json!({
"kind": "tableCell",
"control": control_index,
"cell": cell_index,
"paragraph": para_index,
}),
NestedEntry::TextBox {
control_index,
para_index,
} => serde_json::json!({
"kind": "textBox",
"control": control_index,
"paragraph": para_index,
}),
})
.collect();
serde_json::json!({
"fieldId": fi.field.field_id,
"fieldType": format!("{:?}", fi.field.field_type),
"name": fi.field.field_name().unwrap_or(""),
"guide": fi.field.guide_text().unwrap_or(""),
"memo": fi.field.memo_text().unwrap_or_default(),
"command": fi.field.command,
"value": fi.value,
"editableInForm": fi.field.is_editable_in_form(),
"location": {
"section": fi.location.section_index,
"paragraph": fi.location.para_index,
"nested": nested,
},
})
})
.collect()
}
fn cmd_export_ir_schema(args: &[String]) -> i32 {
let mut out_path: Option<&str> = None;
let mut json_mode = false;
let mut bare = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--json" => json_mode = true,
"--bare" => bare = true,
"-o" | "--out" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.as_str()),
None => {
eprintln!("오류: -o 뒤에 출력 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
other => {
eprintln!("오류: 알 수 없는 옵션입니다 - {}", other);
return EXIT_USAGE;
}
}
i += 1;
}
let payload = if bare {
rhwp::ir_schema::ir_schema()
} else {
provenance::marked(rhwp::ir_schema::envelope(), "export-ir-schema")
};
let text = match serde_json::to_string_pretty(&payload) {
Ok(t) => t,
Err(e) => {
eprintln!("오류: 스키마 직렬화 실패 - {}", e);
return EXIT_RUNTIME;
}
};
if let Some(path) = out_path {
if let Err(e) = fs::write(path, text.as_bytes()) {
eprintln!("오류: 스키마를 쓸 수 없습니다 - {}: {}", path, e);
return EXIT_RUNTIME;
}
if json_mode {
println!(
"{}",
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"irSchemaVersion": rhwp::ir_schema::IR_SCHEMA_VERSION,
"output": path,
"bytes": text.len(),
}),
"export-ir-schema"
)
);
} else {
println!("IR 스키마 저장: {} ({} bytes)", path, text.len());
}
return EXIT_OK;
}
println!("{text}");
EXIT_OK
}
fn cmd_export_plan_schema(args: &[String]) -> i32 {
let mut out_path: Option<&str> = None;
let mut json_mode = false;
let mut bare = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--json" => json_mode = true,
"--bare" => bare = true,
"-o" | "--out" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.as_str()),
None => {
eprintln!("오류: -o 뒤에 출력 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
other => {
eprintln!("오류: 알 수 없는 옵션입니다 - {}", other);
return EXIT_USAGE;
}
}
i += 1;
}
let payload = if bare {
rhwp::plan_schema::plan_schema()
} else {
provenance::marked(rhwp::plan_schema::envelope(), "export-plan-schema")
};
let text = match serde_json::to_string_pretty(&payload) {
Ok(t) => t,
Err(e) => {
eprintln!("오류: 스키마 직렬화 실패 - {}", e);
return EXIT_RUNTIME;
}
};
if let Some(path) = out_path {
if let Err(e) = fs::write(path, text.as_bytes()) {
eprintln!("오류: 스키마를 쓸 수 없습니다 - {}: {}", path, e);
return EXIT_RUNTIME;
}
if json_mode {
println!(
"{}",
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"planSchemaVersion": rhwp::plan_schema::PLAN_SCHEMA_VERSION,
"output": path,
"bytes": text.len(),
}),
"export-plan-schema"
)
);
} else {
println!("계획 스키마 저장: {} ({} bytes)", path, text.len());
}
return EXIT_OK;
}
println!("{text}");
EXIT_OK
}
fn cmd_export_capabilities_schema(args: &[String]) -> i32 {
let mut out_path: Option<&str> = None;
let mut json_mode = false;
let mut bare = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--json" => json_mode = true,
"--bare" => bare = true,
"-o" | "--out" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.as_str()),
None => {
eprintln!("오류: -o 뒤에 출력 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
other => {
eprintln!("오류: 알 수 없는 옵션입니다 - {}", other);
return EXIT_USAGE;
}
}
i += 1;
}
let payload = if bare {
rhwp::capabilities_schema::capabilities_schema()
} else {
provenance::marked(
rhwp::capabilities_schema::envelope(),
"export-capabilities-schema",
)
};
let text = match serde_json::to_string_pretty(&payload) {
Ok(t) => t,
Err(e) => {
eprintln!("오류: 스키마 직렬화 실패 - {}", e);
return EXIT_RUNTIME;
}
};
if let Some(path) = out_path {
if let Err(e) = fs::write(path, text.as_bytes()) {
eprintln!("오류: 스키마를 쓸 수 없습니다 - {}: {}", path, e);
return EXIT_RUNTIME;
}
if json_mode {
println!(
"{}",
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"capabilitiesSchemaVersion":
rhwp::capabilities_schema::CAPABILITIES_SCHEMA_VERSION,
"output": path,
"bytes": text.len(),
}),
"export-capabilities-schema"
)
);
} else {
println!("capabilities 스키마 저장: {} ({} bytes)", path, text.len());
}
return EXIT_OK;
}
println!("{text}");
EXIT_OK
}
fn cmd_export_ontology(args: &[String]) -> i32 {
let mut out_path: Option<&str> = None;
let mut json_mode = false;
let mut bare = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--json" => json_mode = true,
"--bare" => bare = true,
"-o" | "--out" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.as_str()),
None => {
eprintln!("오류: -o 뒤에 출력 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
other => {
eprintln!("오류: 알 수 없는 옵션입니다 - {}", other);
return EXIT_USAGE;
}
}
i += 1;
}
let caps = cli::metadata::capabilities::capabilities_value();
let tools = cli::metadata::mcp::mcp_tool_definitions();
let payload = if bare {
rhwp::ontology::ontology(&caps, &tools)
} else {
provenance::marked(rhwp::ontology::envelope(&caps, &tools), "export-ontology")
};
let text = match serde_json::to_string_pretty(&payload) {
Ok(t) => t,
Err(e) => {
eprintln!("오류: 온톨로지 직렬화 실패 - {}", e);
return EXIT_RUNTIME;
}
};
if let Some(path) = out_path {
if let Err(e) = fs::write(path, text.as_bytes()) {
eprintln!("오류: 온톨로지를 쓸 수 없습니다 - {}: {}", path, e);
return EXIT_RUNTIME;
}
if json_mode {
println!(
"{}",
provenance::marked(
serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"ontologyVersion": rhwp::ontology::ONTOLOGY_VERSION,
"output": path,
"bytes": text.len(),
}),
"export-ontology"
)
);
} else {
println!("온톨로지 저장: {} ({} bytes)", path, text.len());
}
return EXIT_OK;
}
println!("{text}");
EXIT_OK
}
fn agent_manifest_value(bare: bool) -> serde_json::Value {
let mut fields = serde_json::Map::new();
fields.insert(
"capabilities".to_string(),
provenance::marked(
cli::metadata::capabilities::capabilities_value(),
"capabilities",
),
);
fields.insert("irSchema".to_string(), rhwp::ir_schema::ir_schema());
fields.insert(
"provenanceMap".to_string(),
provenance::marked(
provenance::map_json(&rhwp::version()),
"export-provenance-map",
),
);
fields.insert("planSchema".to_string(), rhwp::plan_schema::plan_schema());
fields.insert("missingAxes".to_string(), serde_json::json!([]));
if bare {
return serde_json::Value::Object(fields);
}
let mut envelope = serde_json::Map::new();
envelope.insert(
"schemaVersion".to_string(),
serde_json::json!(ENVELOPE_SCHEMA_VERSION),
);
envelope.extend(fields);
serde_json::Value::Object(envelope)
}
fn cmd_export_agent_manifest(args: &[String]) -> i32 {
let mut json_mode = false;
let mut bare = false;
for arg in args {
match arg.as_str() {
"--json" => json_mode = true,
"--bare" => bare = true,
other => {
eprintln!("알 수 없는 옵션: {other}");
return EXIT_USAGE;
}
}
}
let manifest = provenance::marked(agent_manifest_value(bare), "export-agent-manifest");
if json_mode {
let text = match serde_json::to_string_pretty(&manifest) {
Ok(t) => t,
Err(e) => {
eprintln!("오류: 매니페스트 직렬화 실패 - {}", e);
return EXIT_RUNTIME;
}
};
println!("{text}");
return EXIT_OK;
}
println!("rhwp 에이전트 매니페스트 (capabilities + irSchema + provenanceMap 조립)");
println!();
println!(" capabilities 포함");
println!(" irSchema 포함");
println!(" provenanceMap 포함");
println!(" planSchema 포함");
println!();
println!("기계 계약은 --json 을 쓰세요 (--bare 로 최상위 표지 없이).");
EXIT_OK
}
fn mcp_tool_name_registry() -> Vec<String> {
let mut names: Vec<String> = cli::metadata::mcp::mcp_tool_definitions()
.iter()
.filter_map(|t| t["name"].as_str().map(String::from))
.collect();
names.extend(
agent_profiles::ALL_SESSION_TOOLS
.iter()
.map(|s| s.to_string()),
);
names.sort();
names.dedup();
names
}
fn inspect_command(args: &[String]) -> i32 {
const USAGE: &str =
"사용법: rhwp inspect <hidden-text|injection|unicode|watermark> <파일.hwp|파일.hwpx> [각 축 옵션]";
match args.first().map(|s| s.as_str()) {
Some("hidden-text") => cli::queries::security_inspection::inspect_hidden_text(&args[1..]),
Some("injection") => cli::queries::security_inspection::inspect_injection(&args[1..]),
Some("unicode") => cli::queries::security_inspection::inspect_unicode(&args[1..]),
Some("watermark") => cli::queries::security_inspection::inspect_watermark(&args[1..]),
Some(other) => {
eprintln!("오류: 알 수 없는 inspect 하위 명령입니다 - {other}");
let hint = cli::metadata::capabilities::closest_name(
other,
["hidden-text", "injection", "unicode", "watermark"],
);
if let Some(hint) = &hint {
eprintln!("혹시 이것인가요? inspect {hint}");
}
eprintln!("{USAGE}");
if let Some(hint) = hint {
cli::metadata::capabilities::eprint_usage_recovery(
"inspect",
Some(&hint),
"요청한 이름이 없음 — 가장 가까운 실존 하위 명령으로 교정",
);
}
EXIT_USAGE
}
None => {
eprintln!(
"오류: inspect 하위 명령을 지정해주세요 (hidden-text|injection|unicode|watermark)."
);
eprintln!("{USAGE}");
EXIT_USAGE
}
}
}
fn injection_scan_scopes(include_fields: bool) -> Vec<&'static str> {
let mut scopes = vec![
"body",
"tableCell",
"textBox",
"equation",
"footnote",
"endnote",
"header",
"footer",
"caption",
];
if include_fields {
scopes.extend([
"fieldName",
"fieldGuide",
"fieldCommand",
"hiddenComment",
"fieldMemo",
]);
}
scopes
}
fn display_safe(s: &str) -> String {
s.chars()
.map(|c| match c {
'\u{1b}' => '␛',
'\n' | '\r' => '⏎',
'\t' => '⇥',
c if (c as u32) < 0x20 => '␀',
c => c,
})
.collect()
}
#[cfg(test)]
mod tests {
use crate::cli::outputs::allows_implicit_sibling_resources;
use crate::cli::protocol::{
collect_audit_capsules, replay_scratch_dir, with_replay_input_snapshot,
};
use super::{
cli_output_password, cli_password, set_cli_output_password, set_cli_password,
strip_global_auth_options, strip_utf8_bom, EXIT_USAGE,
};
use rhwp::parser::FileFormat;
#[test]
fn hml_does_not_implicitly_load_sibling_resources() {
assert!(!allows_implicit_sibling_resources(FileFormat::Hml));
assert!(allows_implicit_sibling_resources(FileFormat::Hwp));
assert!(allows_implicit_sibling_resources(FileFormat::Hwpx));
}
#[test]
fn replay_engine_receives_the_hashed_input_snapshot() {
let original =
std::env::temp_dir().join(format!("rhwp-replay-original-{}.hwp", std::process::id()));
std::fs::write(&original, b"original bytes").expect("원본 작성");
let mut plan = serde_json::json!({ "input": original.to_string_lossy() });
let scratch = replay_scratch_dir("unit").expect("전용 임시 폴더");
let scratch_path = scratch.0.clone();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&scratch_path)
.expect("전용 임시 폴더 metadata")
.permissions()
.mode()
& 0o777,
0o700
);
}
let seen = with_replay_input_snapshot(
&mut plan,
b"hashed snapshot",
&scratch.0,
|snapshot_plan| {
std::fs::write(&original, b"changed after hashing").expect("원본 교체");
let snapshot_path = snapshot_plan["input"].as_str().expect("스냅샷 경로");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(snapshot_path)
.expect("입력 스냅샷 metadata")
.permissions()
.mode()
& 0o777,
0o600
);
}
std::fs::read(snapshot_path).expect("스냅샷 읽기")
},
)
.expect("스냅샷 실행");
assert_eq!(seen, b"hashed snapshot");
assert_eq!(plan["input"], original.to_string_lossy().as_ref());
drop(scratch);
assert!(!scratch_path.exists(), "전용 임시 폴더는 RAII 정리");
let _ = std::fs::remove_file(original);
}
#[test]
fn audit_directory_entry_errors_are_not_silently_dropped() {
let entries: [std::io::Result<std::path::PathBuf>; 1] = [Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"denied",
))];
let error = collect_audit_capsules(entries).expect_err("항목 오류는 fail-closed");
assert!(error.contains("폴더 항목 읽기 실패"));
}
#[test]
fn global_password_option_is_removed_from_any_position() {
let args = vec![
"rhwp".to_string(),
"info".to_string(),
"sample.hwp".to_string(),
"--password".to_string(),
"secret".to_string(),
];
set_cli_password(None);
let clean = strip_global_auth_options(args).unwrap();
assert_eq!(clean, ["rhwp", "info", "sample.hwp"]);
assert_eq!(cli_password().as_deref(), Some("secret"));
set_cli_password(None);
}
#[test]
fn password_stdin_ignores_only_a_leading_utf8_bom() {
assert_eq!(strip_utf8_bom("\u{feff}123456\n"), "123456\n");
assert_eq!(strip_utf8_bom("123456\n"), "123456\n");
assert_eq!(
strip_utf8_bom("123456\n\u{feff}next"),
"123456\n\u{feff}next"
);
}
#[test]
fn duplicate_global_password_options_are_rejected() {
let args = vec![
"rhwp".to_string(),
"--password".to_string(),
"first".to_string(),
"info".to_string(),
"sample.hwp".to_string(),
"--password".to_string(),
"second".to_string(),
];
assert!(matches!(
strip_global_auth_options(args),
Err(code) if code == EXIT_USAGE
));
}
#[test]
fn global_output_password_is_removed_without_leaking_into_command_args() {
let args = vec![
"rhwp".to_string(),
"convert".to_string(),
"source.hwp".to_string(),
"output.hwp".to_string(),
"--output-password".to_string(),
"protected".to_string(),
];
set_cli_password(None);
set_cli_output_password(None);
let clean = strip_global_auth_options(args).unwrap();
assert_eq!(clean, ["rhwp", "convert", "source.hwp", "output.hwp"]);
assert_eq!(cli_output_password().as_deref(), Some("protected"));
set_cli_output_password(None);
}
#[test]
fn duplicate_global_output_password_options_are_rejected() {
let args = vec![
"rhwp".to_string(),
"--output-password".to_string(),
"first".to_string(),
"convert".to_string(),
"source.hwp".to_string(),
"output.hwp".to_string(),
"--output-password".to_string(),
"second".to_string(),
];
assert!(matches!(
strip_global_auth_options(args),
Err(code) if code == EXIT_USAGE
));
}
}