team-ljyzipelo

공개
932줄30 KB
1use std::{collections::BTreeSet, path::PathBuf};
2
3#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4pub enum Format {
5 Zip,
6 Tar,
7 Gzip,
8 TarGzip,
9 SevenZip,
10}
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub enum SourceObject {
13 Unix { device: u64, inode: u64 },
14 Windows { volume: u64, file_id: [u8; 16] },
15}
16#[derive(Clone, Debug, Eq, PartialEq)]
17pub struct ListId {
18 pub catalog_version: u16,
19 pub format: Format,
20 pub source_object: SourceObject,
21 pub archive_bytes: u64,
22 pub archive_sha256: [u8; 32],
23}
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub enum Selection {
26 All,
27 EntryIds(Vec<u32>),
28}
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub enum Method {
31 Store,
32 Deflate,
33}
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub enum Start {
36 List {
37 archive: PathBuf,
38 },
39 Extract {
40 archive: PathBuf,
41 destination: PathBuf,
42 selection: Selection,
43 list_id: ListId,
44 gzip_output_name: Option<String>,
45 },
46 CreateZip {
47 sources: Vec<(PathBuf, String)>,
48 output_file: PathBuf,
49 method: Method,
50 aes256: bool,
51 },
52}
53// 암호를 Debug와 로그에서 제외하고 소유 버퍼를 해제 전에 지움.
54pub struct Secret(Vec<u8>);
55impl Secret {
56 pub fn new(text: String) -> Result<Self, &'static str> {
57 let mut bytes = text.into_bytes();
58 if bytes.is_empty() || bytes.len() > 1024 {
59 bytes.fill(0);
60 return Err("암호는 UTF-8 1~1024바이트로 입력하세요");
61 }
62 Ok(Self(bytes))
63 }
64 pub fn as_bytes(&self) -> &[u8] {
65 &self.0
66 }
67}
68impl Drop for Secret {
69 fn drop(&mut self) {
70 self.0.fill(0);
71 }
72}
73#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74pub enum ConflictChoice {
75 Overwrite,
76 Skip,
77 Rename,
78}
79#[derive(Clone, Debug, Eq, PartialEq)]
80pub struct Conflict {
81 pub challenge_id: u64,
82 pub entry_id: u32,
83 pub relative_name: String,
84 pub incoming_size: u64,
85 pub existing_size: u64,
86}
87#[derive(Clone, Debug, Eq, PartialEq)]
88pub struct Resolution {
89 pub entry_id: u32,
90 pub relative_name: String,
91 pub choice: ConflictChoice,
92}
93pub enum Command {
94 Start(Start),
95 Password {
96 challenge_id: u64,
97 secret: Secret,
98 },
99 ConflictReply {
100 challenge_id: u64,
101 choice: ConflictChoice,
102 apply_to_remaining: bool,
103 },
104 Cancel,
105}
106pub struct Request {
107 pub job_id: u64,
108 pub sequence: u64,
109 pub command: Command,
110}
111#[derive(Clone, Copy, Debug, Eq, PartialEq)]
112pub enum Kind {
113 File,
114 Directory,
115 Link,
116 Other,
117}
118#[derive(Clone, Debug, Eq, PartialEq)]
119pub struct Entry {
120 pub id: u32,
121 pub name: String,
122 pub kind: Kind,
123 pub bytes: Option<u64>,
124 pub packed: Option<u64>,
125 pub encrypted: bool,
126}
127#[derive(Clone, Copy, Debug, Eq, PartialEq)]
128pub enum CancelStatus {
129 Requested,
130 AlreadyRequested,
131 TooLate,
132 Finished,
133}
134#[derive(Clone, Copy, Debug, Eq, PartialEq)]
135pub enum Stage {
136 Scan,
137 Read,
138 Decode,
139 Write,
140 Verify,
141 Commit,
142}
143#[derive(Clone, Copy, Debug, Eq, PartialEq)]
144pub enum Outcome {
145 Completed,
146 Failed,
147 Cancelled,
148}
149#[derive(Clone, Copy, Debug, Eq, PartialEq)]
150pub enum ErrorCode {
151 Integrity,
152 UnsupportedFormat,
153 UnsupportedFeature,
154 WrongPassword,
155 UnsafePath,
156 Conflict,
157 Limit,
158 Io,
159 DiskFull,
160 Protocol,
161 Internal,
162 SourceChanged,
163 InvalidRequest,
164}
165#[derive(Clone, Copy, Debug, Eq, PartialEq)]
166pub enum Publication {
167 None,
168 Partial,
169 Complete,
170 Uncertain,
171}
172#[derive(Clone, Copy, Debug, Eq, PartialEq)]
173pub enum Durability {
174 NotApplicable,
175 Synced,
176 Unconfirmed,
177 Failed,
178}
179#[derive(Clone, Copy, Debug, Eq, PartialEq)]
180pub enum Cleanup {
181 Complete,
182 Failed,
183 Unconfirmed,
184}
185#[derive(Clone, Copy, Debug, Eq, PartialEq)]
186pub enum Disposition {
187 Created,
188 PartialRetained,
189 Removed,
190 CommitUncertain,
191}
192#[derive(Clone, Debug)]
193pub struct Terminal {
194 pub outcome: Outcome,
195 pub error: Option<ErrorCode>,
196 pub publication: Publication,
197 pub created_count: u64,
198 pub retained_partial_count: u64,
199 pub durability: Durability,
200 pub cleanup: Cleanup,
201}
202#[derive(Clone, Debug)]
203pub enum Event {
204 Accepted {
205 encryption: bool,
206 },
207 Entry(Entry),
208 ListEnd {
209 entry_count: u32,
210 list_id: ListId,
211 },
212 PasswordRequired {
213 challenge_id: u64,
214 attempt: u32,
215 encrypt: bool,
216 },
217 ConflictRequired(Conflict),
218 ConflictResolved(Resolution),
219 Progress {
220 stage: Stage,
221 processed: u64,
222 total: Option<u64>,
223 completed_entries: u64,
224 },
225 Output {
226 entry_id: Option<u32>,
227 relative_name: String,
228 disposition: Disposition,
229 },
230 CancelAck {
231 request_sequence: u64,
232 status: CancelStatus,
233 },
234 Terminal(Terminal),
235}
236pub enum HostEvent {
237 Fault(String),
238 CleanupComplete,
239 Frame {
240 job_id: u64,
241 sequence: u64,
242 event: Event,
243 },
244 StdoutEof,
245 StderrEof,
246 Exited {
247 success: bool,
248 },
249}
250// 바이트 codec과 프로세스 소유는 작업자 어댑터에서 담당함.
251// 전송 실패 후에도 poll로 양쪽 EOF와 자식 회수 결과를 전달함.
252pub trait Connection {
253 fn send(&mut self, request: Request) -> Result<(), String>;
254 fn poll(&mut self) -> Option<HostEvent>;
255}
256pub trait Factory {
257 fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>;
258}
259pub struct Unavailable;
260impl Factory for Unavailable {
261 fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> {
262 Err("작업자 연결이 아직 준비되지 않았습니다".into())
263 }
264}
265struct Running {
266 id: u64,
267 outgoing: u64,
268 incoming: u64,
269 accepted: bool,
270 start_failed: bool,
271 start: Start,
272 connection: Box<dyn Connection>,
273 entries: Vec<Entry>,
274 list_end: Option<(u32, ListId)>,
275 stdout_eof: bool,
276 transport_closed: bool,
277 stderr_eof: bool,
278 exit: Option<bool>,
279 cancel_sequence: Option<u64>,
280 conflict_ids: BTreeSet<u64>,
281}
282#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
283pub enum Close {
284 #[default]
285 Open,
286 Confirm,
287 Waiting,
288 Review,
289 Allowed,
290}
291#[derive(Default)]
292pub struct Model {
293 running: Option<Running>,
294 next_id: u64,
295 pub archive: Option<PathBuf>,
296 pub entries: Vec<Entry>,
297 pub list_id: Option<ListId>,
298 pub selected: BTreeSet<u32>,
299 pub terminal: Option<Terminal>,
300 pub challenge: Option<(u64, u32, bool)>,
301 pub conflict: Option<Conflict>,
302 pub resolutions: Vec<Resolution>,
303 pub progress: Option<(Stage, u64, Option<u64>, u64)>,
304 pub outputs: Vec<(String, Disposition)>,
305 pub cancel: Option<CancelStatus>,
306 pub error: Option<String>,
307 pub input_error: Option<String>,
308 pub encryption: bool,
309 pub close: Close,
310 pub confirmed: bool,
311}
312impl Model {
313 pub fn busy(&self) -> bool {
314 self.running.is_some()
315 }
316 pub fn cancellation_requested(&self) -> bool {
317 self.running
318 .as_ref()
319 .is_some_and(|run| run.cancel_sequence.is_some())
320 }
321 pub fn job_id(&self) -> Option<u64> {
322 self.running.as_ref().map(|r| r.id)
323 }
324 pub fn can_extract(&self) -> bool {
325 !self.busy()
326 && self.list_id.is_some()
327 && self.archive.is_some()
328 && self.close == Close::Open
329 }
330 pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool {
331 if self.busy() || self.close != Close::Open {
332 return false;
333 }
334 let validation = match &start {
335 Start::List { archive } => archive.is_absolute(),
336 Start::Extract {
337 archive,
338 destination,
339 selection,
340 gzip_output_name,
341 list_id,
342 } => {
343 archive.is_absolute()
344 && destination.is_absolute()
345 && self.archive.as_ref() == Some(archive)
346 && self.list_id.as_ref() == Some(list_id)
347 && match list_id.format {
348 Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)),
349 _ => gzip_output_name.is_none(),
350 }
351 && match selection {
352 Selection::All => true,
353 Selection::EntryIds(ids) => {
354 !ids.is_empty()
355 && ids.iter().collect::<BTreeSet<_>>().len() == ids.len()
356 && ids.iter().all(|id| {
357 self.entries.iter().any(|e| {
358 e.id == *id
359 && matches!(e.kind, Kind::File | Kind::Directory)
360 })
361 })
362 }
363 }
364 }
365 Start::CreateZip {
366 sources,
367 output_file,
368 ..
369 } => {
370 !sources.is_empty()
371 && output_file.is_absolute()
372 && sources
373 .iter()
374 .all(|(p, n)| p.is_absolute() && valid_relative(n))
375 }
376 };
377 if !validation {
378 self.input_error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into());
379 return false;
380 }
381 let Some(id) = self.next_id.checked_add(1) else {
382 self.error = Some("작업 ID 한도에 도달했습니다".into());
383 return false;
384 };
385 let mut connection = match factory.connect(id) {
386 Ok(c) => c,
387 Err(e) => {
388 self.error = Some(e);
389 return false;
390 }
391 };
392 let send_error = connection
393 .send(Request {
394 job_id: id,
395 sequence: 0,
396 command: Command::Start(start.clone()),
397 })
398 .err();
399 let started = send_error.is_none();
400 if let Start::List { archive } = &start
401 && started
402 {
403 self.archive = Some(archive.clone());
404 self.list_id = None;
405 self.entries.clear();
406 self.selected.clear();
407 }
408 self.next_id = id;
409 self.terminal = None;
410 self.challenge = None;
411 self.conflict = None;
412 self.resolutions.clear();
413 self.progress = None;
414 self.outputs.clear();
415 self.cancel = None;
416 self.input_error = None;
417 self.error = send_error;
418 self.confirmed = false;
419 self.running = Some(Running {
420 id,
421 outgoing: 1,
422 incoming: 0,
423 accepted: false,
424 start_failed: !started,
425 start,
426 connection,
427 entries: Vec::new(),
428 list_end: None,
429 stdout_eof: false,
430 transport_closed: false,
431 stderr_eof: false,
432 exit: None,
433 cancel_sequence: None,
434 conflict_ids: BTreeSet::new(),
435 });
436 started
437 }
438 pub fn extract(
439 &mut self,
440 destination: PathBuf,
441 selected_only: bool,
442 gzip_output_name: Option<String>,
443 factory: &mut dyn Factory,
444 ) -> bool {
445 if !self.can_extract() {
446 return false;
447 }
448 self.begin(
449 Start::Extract {
450 archive: self.archive.clone().unwrap(),
451 destination,
452 selection: if selected_only {
453 Selection::EntryIds(self.selected.iter().copied().collect())
454 } else {
455 Selection::All
456 },
457 list_id: self.list_id.clone().unwrap(),
458 gzip_output_name,
459 },
460 factory,
461 )
462 }
463 pub fn password(&mut self, text: String) -> bool {
464 let Some((challenge_id, _, _)) = self.challenge else {
465 return false;
466 };
467 let secret = match Secret::new(text) {
468 Ok(s) => s,
469 Err(e) => {
470 self.input_error = Some(e.into());
471 return false;
472 }
473 };
474 if self
475 .send(Command::Password {
476 challenge_id,
477 secret,
478 })
479 .is_some()
480 {
481 self.challenge = None;
482 self.conflict = None;
483 self.input_error = None;
484 true
485 } else {
486 false
487 }
488 }
489 pub fn resolve_conflict(&mut self, choice: ConflictChoice, apply_to_remaining: bool) -> bool {
490 let Some(conflict) = &self.conflict else {
491 return false;
492 };
493 if self.cancellation_requested() || self.error.is_some() || self.close != Close::Open {
494 return false;
495 }
496 if self
497 .send(Command::ConflictReply {
498 challenge_id: conflict.challenge_id,
499 choice,
500 apply_to_remaining,
501 })
502 .is_some()
503 {
504 self.conflict = None;
505 self.input_error = None;
506 true
507 } else {
508 false
509 }
510 }
511 fn send(&mut self, command: Command) -> Option<u64> {
512 let run = self.running.as_mut()?;
513 if run.start_failed || self.terminal.is_some() || run.exit.is_some() {
514 return None;
515 }
516 let seq = run.outgoing;
517 let Some(next) = seq.checked_add(1) else {
518 self.error = Some("요청 순서 한도 초과".into());
519 return None;
520 };
521 match run.connection.send(Request {
522 job_id: run.id,
523 sequence: seq,
524 command,
525 }) {
526 Ok(()) => {
527 run.outgoing = next;
528 Some(seq)
529 }
530 Err(e) => {
531 self.error = Some(e);
532 None
533 }
534 }
535 }
536 pub fn cancel(&mut self) {
537 if self
538 .running
539 .as_ref()
540 .is_some_and(|r| r.cancel_sequence.is_none())
541 {
542 if let Some(seq) = self.send(Command::Cancel) {
543 self.running.as_mut().unwrap().cancel_sequence = Some(seq);
544 self.challenge = None;
545 self.conflict = None;
546 self.input_error = None;
547 }
548 }
549 }
550 pub fn request_close(&mut self) {
551 if self.close == Close::Open {
552 self.close = if self.busy() {
553 Close::Confirm
554 } else {
555 Close::Review
556 };
557 }
558 }
559 pub fn confirm_close(&mut self) {
560 if self.close == Close::Confirm {
561 self.cancel();
562 self.close = if self.busy() {
563 Close::Waiting
564 } else {
565 Close::Review
566 };
567 }
568 }
569 pub fn keep_open(&mut self) {
570 if self.close != Close::Allowed {
571 self.close = Close::Open;
572 }
573 }
574 pub fn acknowledge_close(&mut self) {
575 if !self.busy() && self.close == Close::Review {
576 self.close = Close::Allowed;
577 }
578 }
579 pub fn poll(&mut self) {
580 for _ in 0..128 {
581 let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else {
582 break;
583 };
584 self.receive(event);
585 }
586 let complete = self.running.as_ref().is_some_and(|r| {
587 r.exit.is_some()
588 && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some()))
589 });
590 if complete {
591 let run = self.running.take().unwrap();
592 self.confirmed =
593 self.terminal.is_some() && run.exit == Some(true) && self.error.is_none();
594 if !self.confirmed {
595 self.error.get_or_insert(
596 "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(),
597 );
598 }
599 if self.confirmed
600 && self
601 .terminal
602 .as_ref()
603 .is_some_and(|t| t.outcome == Outcome::Completed)
604 {
605 if matches!(run.start, Start::List { .. }) {
606 if let Some((count, id)) = run
607 .list_end
608 .filter(|(n, _)| *n as usize == run.entries.len())
609 {
610 let _ = count;
611 self.entries = run.entries;
612 self.list_id = Some(id);
613 } else {
614 self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into());
615 self.confirmed = false;
616 }
617 }
618 }
619 if self
620 .terminal
621 .as_ref()
622 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
623 {
624 self.list_id = None;
625 self.selected.clear();
626 }
627 self.challenge = None;
628 self.conflict = None;
629 self.input_error = None;
630 if matches!(self.close, Close::Waiting | Close::Confirm) {
631 self.close = Close::Review;
632 }
633 }
634 }
635 fn receive(&mut self, host: HostEvent) {
636 let run = self.running.as_mut().unwrap();
637 match host {
638 HostEvent::Fault(message) => self.error = Some(message),
639 HostEvent::CleanupComplete => run.transport_closed = true,
640 HostEvent::StdoutEof => run.stdout_eof = true,
641 HostEvent::StderrEof => run.stderr_eof = true,
642 HostEvent::Exited { success } => run.exit = Some(success),
643 HostEvent::Frame {
644 job_id,
645 sequence,
646 event,
647 } => {
648 if job_id != run.id
649 || sequence != run.incoming
650 || self.terminal.is_some()
651 || run.stdout_eof
652 || sequence >= 1_000_000
653 {
654 self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into());
655 return;
656 }
657 run.incoming += 1;
658 if !run.accepted && !matches!(event, Event::Accepted { .. }) {
659 self.error = Some("작업 승인 응답이 없습니다".into());
660 return;
661 }
662 match event {
663 Event::Accepted { encryption } => {
664 if run.accepted {
665 self.error = Some("작업 승인 중복".into());
666 }
667 run.accepted = true;
668 self.encryption = encryption;
669 }
670 Event::Entry(entry) => {
671 if !matches!(run.start, Start::List { .. })
672 || run.list_end.is_some()
673 || entry.id as usize != run.entries.len()
674 || entry.name.len() > 4096
675 || run.entries.len() >= 100_000
676 {
677 self.error = Some("목록 응답이 유효하지 않습니다".into());
678 } else {
679 run.entries.push(entry);
680 }
681 }
682 Event::ListEnd {
683 entry_count,
684 list_id,
685 } => {
686 if !matches!(run.start, Start::List { .. })
687 || run.list_end.is_some()
688 || list_id.catalog_version != 1
689 {
690 self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
691 } else {
692 run.list_end = Some((entry_count, list_id));
693 }
694 }
695 Event::PasswordRequired {
696 challenge_id,
697 attempt,
698 encrypt,
699 } => {
700 if self.challenge.is_some() || self.conflict.is_some() || challenge_id == 0
701 {
702 self.error = Some("암호 요청이 유효하지 않습니다".into());
703 } else {
704 self.challenge = Some((challenge_id, attempt, encrypt));
705 }
706 }
707 Event::ConflictRequired(conflict) => {
708 let valid_entry = self
709 .entries
710 .iter()
711 .any(|entry| entry.id == conflict.entry_id && entry.kind == Kind::File);
712 if !matches!(run.start, Start::Extract { .. })
713 || !valid_entry
714 || conflict.challenge_id == 0
715 || self.challenge.is_some()
716 || self.conflict.is_some()
717 || run.conflict_ids.len() >= 100_000
718 || !valid_relative(&conflict.relative_name)
719 || conflict.relative_name.len() > 4096
720 || !run.conflict_ids.insert(conflict.challenge_id)
721 {
722 self.error = Some("파일 충돌 요청이 유효하지 않습니다".into());
723 } else if run.cancel_sequence.is_none() {
724 self.conflict = Some(conflict);
725 }
726 }
727 Event::ConflictResolved(resolution) => {
728 if !matches!(run.start, Start::Extract { .. })
729 || !self.entries.iter().any(|entry| {
730 entry.id == resolution.entry_id && entry.kind == Kind::File
731 })
732 || self.resolutions.len() >= 100_000
733 || self
734 .resolutions
735 .iter()
736 .any(|r| r.entry_id == resolution.entry_id)
737 || !valid_relative(&resolution.relative_name)
738 || resolution.relative_name.len() > 4096
739 {
740 self.error = Some("파일 충돌 결과가 유효하지 않습니다".into());
741 } else {
742 self.resolutions.push(resolution);
743 }
744 }
745 Event::Progress {
746 stage,
747 processed,
748 total,
749 completed_entries,
750 } => self.progress = Some((stage, processed, total, completed_entries)),
751 Event::Output {
752 relative_name,
753 disposition,
754 ..
755 } => {
756 if self.outputs.len() < 100_000 && relative_name.len() <= 4096 {
757 self.outputs.push((relative_name, disposition));
758 } else {
759 self.error = Some("출력 보고 한도 초과".into());
760 }
761 }
762 Event::CancelAck {
763 request_sequence,
764 status,
765 } => {
766 if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() {
767 self.cancel = Some(status);
768 } else {
769 self.error = Some("취소 응답이 요청과 일치하지 않습니다".into());
770 }
771 }
772 Event::Terminal(t) => {
773 self.challenge = None;
774 self.conflict = None;
775 self.terminal = Some(t);
776 }
777 }
778 }
779 }
780 }
781 pub fn status(&self) -> String {
782 if let Some(error) = self.error.as_ref().or(self.input_error.as_ref()) {
783 return error.clone();
784 }
785 if self.busy() {
786 if self.terminal.is_some() {
787 return "작업 결과 수신 / 프로세스 종료 확인 중".into();
788 }
789 if self.conflict.is_some() {
790 return "같은 이름의 파일을 처리할 방법을 선택하세요".into();
791 }
792 if self.challenge.is_some() {
793 return "암호를 입력하세요".into();
794 }
795 if let Some(c) = self.cancel {
796 return match c {
797 CancelStatus::Requested | CancelStatus::AlreadyRequested => {
798 "취소 요청 접수 / 최종 결과 대기"
799 }
800 CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기",
801 CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중",
802 }
803 .into();
804 }
805 if self
806 .running
807 .as_ref()
808 .is_some_and(|r| r.cancel_sequence.is_some())
809 {
810 return "취소 요청 전송 / 최종 결과 대기".into();
811 }
812 return "작업 중".into();
813 }
814 match self
815 .terminal
816 .as_ref()
817 .filter(|_| self.confirmed)
818 .map(|t| t.outcome)
819 {
820 Some(Outcome::Completed) => "작업 완료",
821 Some(Outcome::Cancelled) => "작업 취소됨",
822 Some(Outcome::Failed) => "작업 실패",
823 None => "압축파일을 열거나 ZIP 파일을 만드세요",
824 }
825 .into()
826 }
827}
828pub fn valid_leaf(name: &str) -> bool {
829 valid_relative(name) && !name.contains('/') && !name.contains('\\')
830}
831pub fn valid_relative(name: &str) -> bool {
832 !name.is_empty()
833 && !name.contains('\0')
834 && !name.contains(':')
835 && !name.starts_with('/')
836 && !name.starts_with('\\')
837 && name
838 .split(['/', '\\'])
839 .all(|p| !p.is_empty() && p != "." && p != "..")
840}
841
842// 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함.
843pub fn launch_args(
844 args: Vec<std::ffi::OsString>,
845 cwd: PathBuf,
846) -> Result<(bool, Option<PathBuf>), &'static str> {
847 let fixture = args.iter().any(|arg| arg == "--ui-fixture");
848 let paths = args
849 .into_iter()
850 .filter(|arg| arg != "--ui-fixture")
851 .collect::<Vec<_>>();
852 if paths.len() > 1 {
853 return Err("압축파일 하나를 지정하세요");
854 }
855 let path = paths
856 .into_iter()
857 .next()
858 .map(PathBuf::from)
859 .map(|p| if p.is_absolute() { p } else { cwd.join(p) });
860 Ok((fixture, path))
861}
862
863pub fn stage_label(stage: Stage) -> &'static str {
864 match stage {
865 Stage::Scan => "목록 읽는 중",
866 Stage::Read => "파일 읽는 중",
867 Stage::Decode => "압축 푸는 중",
868 Stage::Write => "파일 쓰는 중",
869 Stage::Verify => "검증 중",
870 Stage::Commit => "저장 마무리 중",
871 }
872}
873pub fn disposition_label(disposition: Disposition) -> &'static str {
874 match disposition {
875 Disposition::Created => "생성됨",
876 Disposition::PartialRetained => "일부 파일 남음",
877 Disposition::Removed => "작업 임시 파일 정리됨",
878 Disposition::CommitUncertain => "저장 여부 불확실",
879 }
880}
881pub fn terminal_lines(t: &Terminal) -> Vec<String> {
882 let publication = match t.publication {
883 Publication::None => "게시된 파일 없음",
884 Publication::Partial => "일부 파일 게시됨",
885 Publication::Complete => "파일 게시 완료",
886 Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요",
887 };
888 let durability = match t.durability {
889 Durability::NotApplicable => "동기화 해당 없음",
890 Durability::Synced => "디스크 동기화 완료",
891 Durability::Unconfirmed => "디스크 동기화 미확인",
892 Durability::Failed => "디스크 동기화 실패",
893 };
894 let cleanup = match t.cleanup {
895 Cleanup::Complete => "작업 임시 파일 정리 완료",
896 Cleanup::Failed => "작업 임시 파일 정리 실패",
897 Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인",
898 };
899 let mut lines = vec![
900 publication.into(),
901 format!(
902 "생성 {}개 / 남은 임시 파일 {}개",
903 t.created_count, t.retained_partial_count
904 ),
905 format!("{durability} / {cleanup}"),
906 ];
907 if let Some(error) = t.error {
908 lines.push(
909 match error {
910 ErrorCode::Integrity => "압축파일이 손상됐습니다",
911 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
912 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
913 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
914 ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
915 ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
916 ErrorCode::Limit => "처리 한도를 초과했습니다",
917 ErrorCode::Io => {
918 "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요"
919 }
920 ErrorCode::DiskFull => {
921 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
922 }
923 ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
924 ErrorCode::Internal => "작업자 처리 오류입니다",
925 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
926 ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요",
927 }
928 .into(),
929 );
930 }
931 lines
932}