use std::{fs, path::Path, process};
use rhwp::{provenance, schema_registry::ENVELOPE_SCHEMA_VERSION};
use super::runtime::{
edit_output_format, edit_serialize, edit_verify_report, finish_edit_write, EditOutputFormat,
};
use super::tables::{resolve_table_cell, CellResolveError};
use crate::{load_document, EXIT_OK, EXIT_RUNTIME, EXIT_USAGE};
pub(crate) fn recolor_cell_text_black(
document: &mut rhwp::model::document::Document,
sec: usize,
para: usize,
ctrl: usize,
cell_idx: usize,
) -> bool {
use rhwp::model::control::Control;
use rhwp::model::paragraph::CharShapeRef;
let source_id = {
let Some(section) = document.sections.get(sec) else {
return false;
};
let Some(parent) = section.paragraphs.get(para) else {
return false;
};
let Some(Control::Table(table)) = parent.controls.get(ctrl) else {
return false;
};
let Some(cell) = table.cells.get(cell_idx) else {
return false;
};
let Some(paragraph) = cell.paragraphs.first() else {
return false;
};
let Some(shape) = paragraph.char_shapes.first() else {
return false;
};
shape.char_shape_id as usize
};
let Some(base) = document
.doc_info
.char_shapes
.get(source_id)
.or_else(|| document.doc_info.char_shapes.first())
.cloned()
else {
return false;
};
let mut black = base;
black.raw_data = None; black.text_color = 0;
black.italic = false;
black.bold = false;
black.strikethrough = false;
black.underline_type = rhwp::model::style::UnderlineType::None;
let black_id = document
.doc_info
.char_shapes
.iter()
.position(|candidate| candidate == &black)
.map(|idx| idx as u32)
.unwrap_or_else(|| {
let new_id = document.doc_info.char_shapes.len() as u32;
document.doc_info.char_shapes.push(black);
new_id
});
let Some(section) = document.sections.get_mut(sec) else {
return false;
};
let Some(parent) = section.paragraphs.get_mut(para) else {
return false;
};
let Some(Control::Table(table)) = parent.controls.get_mut(ctrl) else {
return false;
};
let Some(cell) = table.cells.get_mut(cell_idx) else {
return false;
};
let Some(cell_para) = cell.paragraphs.get_mut(0) else {
return false;
};
cell_para.char_shapes = vec![CharShapeRef {
start_pos: 0,
char_shape_id: black_id,
}];
true
}
pub(crate) fn measure_cell_overflow(
doc: &rhwp::wasm_api::HwpDocument,
sec: usize,
para: usize,
ctrl: usize,
cell_idx: usize,
text: &str,
) -> Option<(f64, f64, usize)> {
use rhwp::model::control::Control;
use rhwp::renderer::hwpunit_to_px;
if text.is_empty() {
return None;
}
let cell = doc
.document()
.sections
.get(sec)?
.paragraphs
.get(para)?
.controls
.get(ctrl)
.and_then(|c| match c {
Control::Table(t) => t.cells.get(cell_idx),
_ => None,
})?;
let padding = (cell.padding.left + cell.padding.right) as f64;
let usable = hwpunit_to_px(
(cell.width as f64 - padding) as i32,
rhwp::renderer::DEFAULT_DPI,
);
if usable <= 0.0 {
return None;
}
let text_w = estimate_text_width_px(doc, sec, para, ctrl, cell_idx, text);
if text_w <= usable {
return None;
}
let lines = (text_w / usable).ceil() as usize;
Some((usable, text_w, lines))
}
fn estimate_text_width_px(
doc: &rhwp::wasm_api::HwpDocument,
sec: usize,
para: usize,
ctrl: usize,
cell_idx: usize,
text: &str,
) -> f64 {
use rhwp::model::control::Control;
use rhwp::renderer::hwpunit_to_px;
let size_hwpunit = doc
.document()
.sections
.get(sec)
.and_then(|s| s.paragraphs.get(para))
.and_then(|p| p.controls.get(ctrl))
.and_then(|c| match c {
Control::Table(t) => t.cells.get(cell_idx),
_ => None,
})
.and_then(|cell| cell.paragraphs.first())
.and_then(|p| p.char_shapes.first())
.and_then(|cs| {
doc.document()
.doc_info
.char_shapes
.get(cs.char_shape_id as usize)
})
.map(|cs| cs.base_size as f64)
.unwrap_or(1000.0);
let em = hwpunit_to_px(size_hwpunit as i32, rhwp::renderer::DEFAULT_DPI);
text.chars()
.map(|c| if c.is_ascii() { em * 0.5 } else { em })
.sum()
}
const SET_CELL_CONTROL_CHAR_MESSAGE: &str =
"오류: --text 에 줄바꿈·탭은 넣을 수 없습니다 (한 줄 값 기록).";
pub(crate) fn set_cell_control_char_rejection(text: &str) -> Option<&'static str> {
text.chars()
.any(|ch| matches!(ch, '\r' | '\n' | '\t'))
.then_some(SET_CELL_CONTROL_CHAR_MESSAGE)
}
pub(super) fn edit_set_cell(args: &[String]) -> i32 {
let mut file_path: Option<&str> = None;
let mut table_arg: Option<usize> = None;
let mut row_arg: Option<u16> = None;
let mut col_arg: Option<u16> = None;
let mut text_arg: Option<&str> = None;
let mut out_path: Option<String> = None;
let mut dry_run = false;
let mut json_mode = false;
let mut verify_mode = false;
let mut keep_style = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--keep-style" => keep_style = true,
"--table" | "--row" | "--col" => {
let name = args[i].clone();
i += 1;
let Some(v) = args.get(i) else {
eprintln!("오류: {} 뒤에 0 이상의 정수가 필요합니다.", name);
return EXIT_USAGE;
};
match name.as_str() {
"--table" => match v.parse::<usize>() {
Ok(value) => table_arg = Some(value),
Err(_) => {
eprintln!("오류: {} 뒤에 0 이상의 정수가 필요합니다.", name);
return EXIT_USAGE;
}
},
"--row" => match v.parse::<u16>() {
Ok(value) => row_arg = Some(value),
Err(_) => {
eprintln!("오류: {} 뒤에 0 이상 65535 이하의 정수가 필요합니다.", name);
return EXIT_USAGE;
}
},
_ => match v.parse::<u16>() {
Ok(value) => col_arg = Some(value),
Err(_) => {
eprintln!("오류: {} 뒤에 0 이상 65535 이하의 정수가 필요합니다.", name);
return EXIT_USAGE;
}
},
}
}
"--text" => {
i += 1;
match args.get(i) {
Some(v) => text_arg = Some(v),
None => {
eprintln!(
"오류: --text 뒤에 셀에 넣을 문자열이 필요합니다 (비우기는 \"\")."
);
return EXIT_USAGE;
}
}
}
"-o" | "--output" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.clone()),
None => {
eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
"--dry-run" => dry_run = true,
"--json" => json_mode = true,
"--verify" => verify_mode = true,
other if other.starts_with('-') => {
eprintln!("알 수 없는 옵션: {other}");
return EXIT_USAGE;
}
other => {
if file_path.replace(other).is_some() {
eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
return EXIT_USAGE;
}
}
}
i += 1;
}
let (Some(file_path), Some(table_no), Some(row), Some(col), Some(new_text)) =
(file_path, table_arg, row_arg, col_arg, text_arg)
else {
eprintln!(
"사용법: rhwp edit set-cell <파일> --table <번호> --row <행> --col <열> --text <문자열> [-o <출력>] [--keep-style] [--dry-run] [--json]"
);
return EXIT_USAGE;
};
if let Some(message) = set_cell_control_char_rejection(new_text) {
eprintln!("{message}");
return EXIT_USAGE;
}
let bytes = match fs::read(file_path) {
Ok(d) => d,
Err(e) => {
eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
return EXIT_RUNTIME;
}
};
let mut doc = match load_document(&bytes) {
Ok(d) => d,
Err(e) => return e.report(),
};
let (sec, para, ctrl, cell_idx, para_lens, old_text) =
match resolve_table_cell(doc.document(), table_no, row, col) {
Ok(v) => v,
Err(CellResolveError::Usage(msg)) => {
eprintln!("{msg}");
return EXIT_USAGE;
}
Err(CellResolveError::Runtime(msg)) => {
eprintln!("{msg}");
return EXIT_RUNTIME;
}
};
let overflow = measure_cell_overflow(&doc, sec, para, ctrl, cell_idx, &new_text).map(
|(cell_w, text_w, lines)| {
serde_json::json!({
"target": format!("table{}[{},{}]", table_no, row, col),
"text": new_text,
"cellWidthPx": (cell_w * 100.0).round() / 100.0,
"textWidthPx": (text_w * 100.0).round() / 100.0,
"lines": lines,
})
},
);
if !dry_run {
for (pi, len) in para_lens.iter().enumerate() {
if *len == 0 {
continue;
}
if let Err(e) = doc.delete_text_in_cell(
sec as u32,
para as u32,
ctrl as u32,
cell_idx as u32,
pi as u32,
0,
*len as u32,
) {
eprintln!("오류: 셀 비우기 실패(문단 {}) - {:?}", pi, e);
return EXIT_RUNTIME;
}
}
if !new_text.is_empty() {
if let Err(e) = doc.insert_text_in_cell(
sec as u32,
para as u32,
ctrl as u32,
cell_idx as u32,
0,
0,
new_text,
) {
eprintln!("오류: 셀 쓰기 실패 - {:?}", e);
return EXIT_RUNTIME;
}
if !keep_style
&& !recolor_cell_text_black(doc.document_mut(), sec, para, ctrl, cell_idx)
{
eprintln!("경고: 셀 글자색을 검정으로 바꾸지 못했습니다 (상속 스타일 유지).");
}
}
}
let out_format = edit_output_format(&bytes, out_path.as_deref());
let output_path = out_path.unwrap_or_else(|| {
let stem = Path::new(file_path)
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| "output".to_string());
format!("{}_cell.{}", stem, out_format.ext())
});
let mut verify_report = serde_json::Value::Null;
let mut verify_failed = false;
if !dry_run {
let out_bytes = match edit_serialize(&mut doc, out_format) {
Ok(b) => b,
Err(e) => {
eprintln!(
"오류: {} 직렬화 실패 - {}",
out_format.label().to_uppercase(),
e
);
return EXIT_RUNTIME;
}
};
if let Err(e) = fs::write(&output_path, &out_bytes) {
eprintln!("오류: 출력 쓰기 실패 - {}: {}", output_path, e);
return EXIT_RUNTIME;
}
if verify_mode {
let cross = out_format == EditOutputFormat::Hwp
&& rhwp::parser::detect_format(&bytes) == rhwp::parser::FileFormat::Hwpx;
let (report, failed) = edit_verify_report(&doc, &out_bytes, cross);
verify_report = report;
verify_failed = failed;
}
}
let changed_pages = if dry_run {
serde_json::Value::Null
} else {
match doc.pages_covering_paragraphs(&[(sec, para)]) {
Some(pages) => serde_json::json!(pages),
None => serde_json::Value::Null,
}
};
if json_mode {
let mut envelope = serde_json::json!({
"schemaVersion": ENVELOPE_SCHEMA_VERSION,
"source": file_path,
"table": table_no,
"row": row,
"col": col,
"oldText": old_text,
"newText": new_text,
"dryRun": dry_run,
"changedPages": changed_pages,
"keepStyle": keep_style,
"overflow": overflow.clone().map(|o| vec![o]).unwrap_or_default(),
});
if !dry_run {
envelope["output"] = serde_json::Value::String(output_path.clone());
envelope["outputFormat"] = serde_json::Value::String(out_format.label().to_string());
envelope["verify"] = verify_report.clone();
}
println!("{}", provenance::marked(envelope, "edit"));
if verify_failed {
process::exit(3);
}
return EXIT_OK;
}
if dry_run {
println!(
"변경 예정: {} 표{} ({},{}) {:?} → {:?}",
file_path, table_no, row, col, old_text, new_text
);
} else {
println!(
"셀 기록 완료: {} → {} — 표{} ({},{}) {:?} → {:?}",
file_path, output_path, table_no, row, col, old_text, new_text
);
}
if verify_failed {
eprintln!("검증 실패(--verify): 저장본 재파싱 IR 차이 — 상세는 --json 또는 ir-diff");
process::exit(3);
}
EXIT_OK
}
pub(super) fn edit_insert_text_in_cell(args: &[String]) -> i32 {
const USAGE: &str = "사용법: rhwp edit insert-text-in-cell <파일> --table <번호> --row <행> --col <열> --text <문자열> [--offset N] [--cell-para N] [-o <출력>] [--dry-run] [--verify] [--json]";
let mut file_path: Option<&str> = None;
let mut table_arg: Option<usize> = None;
let mut row_arg: Option<u16> = None;
let mut col_arg: Option<u16> = None;
let mut text_arg: Option<&str> = None;
let mut offset_arg: usize = 0;
let mut cell_para_arg: usize = 0;
let mut out_path: Option<String> = None;
let mut dry_run = false;
let mut json_mode = false;
let mut verify_mode = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--table" | "--row" | "--col" | "--offset" | "--cell-para" => {
let name = args[i].clone();
i += 1;
let Some(v) = args.get(i) else {
eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
return EXIT_USAGE;
};
match name.as_str() {
"--table" | "--offset" | "--cell-para" => match v.parse::<usize>() {
Ok(n) => match name.as_str() {
"--table" => table_arg = Some(n),
"--offset" => offset_arg = n,
_ => cell_para_arg = n,
},
Err(_) => {
eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
"--row" => match v.parse::<u16>() {
Ok(n) => row_arg = Some(n),
Err(_) => {
eprintln!("오류: --row 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
_ => match v.parse::<u16>() {
Ok(n) => col_arg = Some(n),
Err(_) => {
eprintln!("오류: --col 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
}
}
"--text" => {
i += 1;
match args.get(i) {
Some(v) if !v.is_empty() => text_arg = Some(v.as_str()),
_ => {
eprintln!("오류: --text 뒤에 넣을 문자열이 필요합니다 (빈 문자열 불가).");
return EXIT_USAGE;
}
}
}
"-o" | "--output" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.clone()),
None => {
eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
"--dry-run" => dry_run = true,
"--json" => json_mode = true,
"--verify" => verify_mode = true,
other if other.starts_with('-') => {
eprintln!("알 수 없는 옵션: {other}");
return EXIT_USAGE;
}
other => {
if file_path.replace(other).is_some() {
eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
return EXIT_USAGE;
}
}
}
i += 1;
}
let (Some(file_path), Some(table_no), Some(row), Some(col), Some(text)) =
(file_path, table_arg, row_arg, col_arg, text_arg)
else {
eprintln!("{USAGE}");
return EXIT_USAGE;
};
let bytes = match fs::read(file_path) {
Ok(d) => d,
Err(e) => {
eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
return EXIT_RUNTIME;
}
};
let mut doc = match load_document(&bytes) {
Ok(d) => d,
Err(e) => return e.report(),
};
let (sec, para, ctrl, cell_idx, para_lens, _old) =
match resolve_table_cell(doc.document(), table_no, row, col) {
Ok(v) => v,
Err(CellResolveError::Usage(msg)) => {
eprintln!("{msg}");
return EXIT_USAGE;
}
Err(CellResolveError::Runtime(msg)) => {
eprintln!("{msg}");
return EXIT_RUNTIME;
}
};
if cell_para_arg >= para_lens.len() {
eprintln!(
"오류: --cell-para 가 범위를 벗어났습니다 (셀 문단 0~{}): {cell_para_arg}",
para_lens.len().saturating_sub(1)
);
return EXIT_USAGE;
}
if offset_arg > para_lens[cell_para_arg] {
eprintln!(
"오류: --offset 이 문단 길이를 넘습니다 (문단 길이 {}): {offset_arg}",
para_lens[cell_para_arg]
);
return EXIT_USAGE;
}
if !dry_run {
if let Err(e) = doc.insert_text_in_cell_native(
sec,
para,
ctrl,
cell_idx,
cell_para_arg,
offset_arg,
text,
) {
eprintln!("오류: 셀 텍스트 삽입 실패 - {e}");
return EXIT_RUNTIME;
}
}
finish_edit_write(
&mut doc,
&bytes,
file_path,
out_path,
"cellins",
dry_run,
json_mode,
verify_mode,
serde_json::json!({
"table": table_no,
"row": row,
"col": col,
"cellPara": cell_para_arg,
"offset": offset_arg,
"text": text
}),
&[(sec, para)],
&format!(
"셀 텍스트 삽입 예정: {file_path} 표 {table_no} ({row},{col}) 문단 {cell_para_arg} 오프셋 {offset_arg}"
),
&format!("셀 텍스트 삽입 완료: {file_path}"),
)
}
pub(super) fn edit_delete_text_in_cell(args: &[String]) -> i32 {
const USAGE: &str = "사용법: rhwp edit delete-text-in-cell <파일> --table <번호> --row <행> --col <열> --count <글자수> [--offset N] [--cell-para N] [-o <출력>] [--dry-run] [--verify] [--json]";
let mut file_path: Option<&str> = None;
let mut table_arg: Option<usize> = None;
let mut row_arg: Option<u16> = None;
let mut col_arg: Option<u16> = None;
let mut count_arg: Option<usize> = None;
let mut offset_arg: usize = 0;
let mut cell_para_arg: usize = 0;
let mut out_path: Option<String> = None;
let mut dry_run = false;
let mut json_mode = false;
let mut verify_mode = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--table" | "--row" | "--col" | "--offset" | "--cell-para" | "--count" => {
let name = args[i].clone();
i += 1;
let Some(v) = args.get(i) else {
eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
return EXIT_USAGE;
};
match name.as_str() {
"--table" | "--offset" | "--cell-para" | "--count" => {
match v.parse::<usize>() {
Ok(n) => match name.as_str() {
"--table" => table_arg = Some(n),
"--offset" => offset_arg = n,
"--count" => {
if n == 0 {
eprintln!("오류: --count 는 1 이상이어야 합니다.");
return EXIT_USAGE;
}
count_arg = Some(n);
}
_ => cell_para_arg = n,
},
Err(_) => {
eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
}
}
"--row" => match v.parse::<u16>() {
Ok(n) => row_arg = Some(n),
Err(_) => {
eprintln!("오류: --row 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
_ => match v.parse::<u16>() {
Ok(n) => col_arg = Some(n),
Err(_) => {
eprintln!("오류: --col 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
}
}
"-o" | "--output" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.clone()),
None => {
eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
"--dry-run" => dry_run = true,
"--json" => json_mode = true,
"--verify" => verify_mode = true,
other if other.starts_with('-') => {
eprintln!("알 수 없는 옵션: {other}");
return EXIT_USAGE;
}
other => {
if file_path.replace(other).is_some() {
eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
return EXIT_USAGE;
}
}
}
i += 1;
}
let (Some(file_path), Some(table_no), Some(row), Some(col), Some(count)) =
(file_path, table_arg, row_arg, col_arg, count_arg)
else {
eprintln!("{USAGE}");
return EXIT_USAGE;
};
let bytes = match fs::read(file_path) {
Ok(d) => d,
Err(e) => {
eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
return EXIT_RUNTIME;
}
};
let mut doc = match load_document(&bytes) {
Ok(d) => d,
Err(e) => return e.report(),
};
let (sec, para, ctrl, cell_idx, para_lens, _old) =
match resolve_table_cell(doc.document(), table_no, row, col) {
Ok(v) => v,
Err(CellResolveError::Usage(msg)) => {
eprintln!("{msg}");
return EXIT_USAGE;
}
Err(CellResolveError::Runtime(msg)) => {
eprintln!("{msg}");
return EXIT_RUNTIME;
}
};
if cell_para_arg >= para_lens.len() {
eprintln!(
"오류: --cell-para 가 범위를 벗어났습니다 (셀 문단 0~{}): {cell_para_arg}",
para_lens.len().saturating_sub(1)
);
return EXIT_USAGE;
}
if offset_arg > para_lens[cell_para_arg] {
eprintln!(
"오류: --offset 이 문단 길이를 넘습니다 (문단 길이 {}): {offset_arg}",
para_lens[cell_para_arg]
);
return EXIT_USAGE;
}
if !dry_run {
if let Err(e) = doc.delete_text_in_cell_native(
sec,
para,
ctrl,
cell_idx,
cell_para_arg,
offset_arg,
count,
) {
eprintln!("오류: 셀 텍스트 삭제 실패 - {e}");
return EXIT_RUNTIME;
}
}
finish_edit_write(
&mut doc,
&bytes,
file_path,
out_path,
"celldel",
dry_run,
json_mode,
verify_mode,
serde_json::json!({
"table": table_no,
"row": row,
"col": col,
"cellPara": cell_para_arg,
"offset": offset_arg,
"count": count
}),
&[(sec, para)],
&format!(
"셀 텍스트 삭제 예정: {file_path} 표 {table_no} ({row},{col}) 문단 {cell_para_arg} 오프셋 {offset_arg} 글자 {count}"
),
&format!("셀 텍스트 삭제 완료: {file_path}"),
)
}
pub(super) fn edit_set_cell_props(args: &[String]) -> i32 {
const USAGE: &str = "사용법: rhwp edit set-cell-props <파일> --table <번호> --row <행> --col <열> --props <JSON> [-o <출력>] [--dry-run] [--verify] [--json]";
let mut file_path: Option<&str> = None;
let mut table_arg: Option<usize> = None;
let mut row_arg: Option<u16> = None;
let mut col_arg: Option<u16> = None;
let mut props: Option<String> = None;
let mut out_path: Option<String> = None;
let mut dry_run = false;
let mut json_mode = false;
let mut verify_mode = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--table" | "--row" | "--col" => {
let name = args[i].clone();
i += 1;
let Some(v) = args.get(i) else {
eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
return EXIT_USAGE;
};
match name.as_str() {
"--table" => match v.parse::<usize>() {
Ok(n) => table_arg = Some(n),
Err(_) => {
eprintln!("오류: --table 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
"--row" => match v.parse::<u16>() {
Ok(n) => row_arg = Some(n),
Err(_) => {
eprintln!("오류: --row 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
_ => match v.parse::<u16>() {
Ok(n) => col_arg = Some(n),
Err(_) => {
eprintln!("오류: --col 뒤에 0 이상의 정수가 필요합니다: {v}");
return EXIT_USAGE;
}
},
}
}
"--props" => {
i += 1;
match args.get(i) {
Some(v) => props = Some(v.clone()),
None => {
eprintln!("오류: --props 뒤에 JSON 문자열이 필요합니다.");
return EXIT_USAGE;
}
}
}
"-o" | "--output" => {
i += 1;
match args.get(i) {
Some(v) => out_path = Some(v.clone()),
None => {
eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
return EXIT_USAGE;
}
}
}
"--dry-run" => dry_run = true,
"--json" => json_mode = true,
"--verify" => verify_mode = true,
other if other.starts_with('-') => {
eprintln!("알 수 없는 옵션: {other}");
return EXIT_USAGE;
}
other => {
if file_path.replace(other).is_some() {
eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
return EXIT_USAGE;
}
}
}
i += 1;
}
let (Some(file_path), Some(table_no), Some(row), Some(col), Some(props)) =
(file_path, table_arg, row_arg, col_arg, props)
else {
eprintln!("{USAGE}");
return EXIT_USAGE;
};
if !matches!(
serde_json::from_str::<serde_json::Value>(&props),
Ok(serde_json::Value::Object(_))
) {
eprintln!("오류: --props 는 JSON 객체여야 합니다.");
return EXIT_USAGE;
}
let bytes = match fs::read(file_path) {
Ok(d) => d,
Err(e) => {
eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
return EXIT_RUNTIME;
}
};
let mut doc = match load_document(&bytes) {
Ok(d) => d,
Err(e) => return e.report(),
};
let (sec, para, ctrl, cell_idx, _para_lens, _old) =
match resolve_table_cell(doc.document(), table_no, row, col) {
Ok(v) => v,
Err(CellResolveError::Usage(msg)) => {
eprintln!("{msg}");
return EXIT_USAGE;
}
Err(CellResolveError::Runtime(msg)) => {
eprintln!("{msg}");
return EXIT_RUNTIME;
}
};
if !dry_run {
if let Err(e) = doc.set_cell_properties_native(sec, para, ctrl, cell_idx, &props) {
eprintln!("오류: 셀 속성 변경 실패 - {e}");
return EXIT_RUNTIME;
}
}
finish_edit_write(
&mut doc,
&bytes,
file_path,
out_path,
"cellprop",
dry_run,
json_mode,
verify_mode,
serde_json::json!({ "table": table_no, "row": row, "col": col }),
&[(sec, para)],
&format!("셀 속성 변경 예정: {file_path} 표 {table_no} ({row},{col})"),
&format!("셀 속성 변경 완료: {file_path}"),
)
}