team-ljyzipelo

공개
400줄14 KB
1use crate::archive_ui::*;
2use std::{
3 collections::BTreeSet,
4 fs, io,
5 path::{Path, PathBuf},
6};
7
8pub const UNCERTAIN: &str = "저장이 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요.";
9pub const PARTIAL: &str = "일부 파일만 풀렸습니다. 풀린 파일은 풀 위치 폴더에 남아 있습니다.";
10pub const LEFTOVERS: &str =
11 "선택한 파일은 모두 저장했지만 임시 파일을 지우지 못했습니다. 풀 위치 폴더를 확인하세요.";
12pub const SYNC_FAILED: &str =
13 "파일을 디스크에 완전히 저장하지 못했습니다. 풀 위치 폴더를 확인하세요.";
14pub const SYNC_WARNING: &str = "파일을 디스크에 완전히 저장했는지 확인하지 못했습니다.";
15pub const CLEANUP_WARNING: &str =
16 "임시 파일을 지우지 못했습니다. 풀 위치 폴더에 남은 임시 파일이 있을 수 있습니다.";
17pub const INTERNAL: &str = "내부 오류가 발생했습니다. 프로그램을 다시 시작해 주세요";
18pub const FOLDER_ERROR: &str = "풀 위치 폴더를 만들 수 없습니다. 접근 권한을 확인하세요";
19
20pub fn error_text(code: ErrorCode) -> &'static str {
21 match code {
22 ErrorCode::Integrity => "압축파일이 손상됐습니다",
23 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
24 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
25 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
26 ErrorCode::UnsafePath => "파일 경로의 안전성을 확인할 수 없어 중단했습니다",
27 ErrorCode::Conflict => "같은 이름의 파일이 이미 있습니다. 다른 폴더를 선택하세요",
28 ErrorCode::Limit => "처리 한도를 초과했습니다",
29 ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요",
30 ErrorCode::DiskFull => "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요",
31 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
32 ErrorCode::InvalidRequest => "풀 위치와 선택한 항목을 확인하세요",
33 ErrorCode::Protocol | ErrorCode::Internal => INTERNAL,
34 }
35}
36
37pub fn progress_text(stage: Stage, creating: bool) -> &'static str {
38 match stage {
39 Stage::Scan | Stage::Read => "압축파일을 읽는 중",
40 Stage::Decode if creating => "압축하는 중",
41 Stage::Decode => "압축을 푸는 중",
42 Stage::Write => "파일을 저장하는 중",
43 Stage::Verify => "확인하는 중",
44 Stage::Commit => "마무리하는 중",
45 }
46}
47
48pub fn bytes_text(bytes: u64) -> String {
49 for (unit, size) in [("GB", 1_u64 << 30), ("MB", 1 << 20), ("KB", 1 << 10)] {
50 if bytes >= size {
51 return format!("{:.1} {unit}", bytes as f64 / size as f64);
52 }
53 }
54 format!("{bytes} B")
55}
56
57pub fn middle_text(text: &str, max_chars: usize) -> String {
58 let chars = text.chars().collect::<Vec<_>>();
59 if chars.len() <= max_chars || max_chars < 5 {
60 return text.into();
61 }
62 let left = (max_chars - 1) / 2;
63 chars[..left]
64 .iter()
65 .chain(std::iter::once(&'…'))
66 .chain(chars[chars.len() - (max_chars - left - 1)..].iter())
67 .collect()
68}
69
70pub fn default_destination(archive: &Path) -> PathBuf {
71 let name = archive.file_name().unwrap_or_default().to_string_lossy();
72 let lower = name.to_ascii_lowercase();
73 let compound = [".tar.bz2", ".tar.gz", ".tar.xz"]
74 .into_iter()
75 .find(|suffix| lower.ends_with(suffix));
76 let stem = if let Some(suffix) = compound {
77 &name[..name.len() - suffix.len()]
78 } else {
79 name.rsplit_once('.')
80 .map_or(name.as_ref(), |(stem, _)| stem)
81 };
82 archive.with_file_name(if stem.is_empty() {
83 "압축 해제"
84 } else {
85 stem
86 })
87}
88
89pub fn prepare_destination(path: &Path, automatic: bool) -> io::Result<bool> {
90 match fs::symlink_metadata(path) {
91 Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(false),
92 Ok(_) => Err(io::Error::other(FOLDER_ERROR)),
93 Err(error) if error.kind() == io::ErrorKind::NotFound && automatic => {
94 let mut builder = fs::DirBuilder::new();
95 #[cfg(unix)]
96 {
97 use std::os::unix::fs::DirBuilderExt;
98 builder.mode(0o700);
99 }
100 builder.create(path)?;
101 Ok(true)
102 }
103 Err(error) => Err(error),
104 }
105}
106
107pub fn remove_owned_empty(path: &Path) {
108 // 이번 요청에서 만든 폴더만 호출하며 비어 있지 않으면 보존함.
109 let _ = fs::remove_dir(path);
110}
111
112fn requested(entry: &Entry, selection: &Selection) -> bool {
113 match selection {
114 Selection::All => true,
115 Selection::EntryIds(ids) => ids.contains(&entry.id),
116 }
117}
118
119pub fn target_files(
120 entries: &[Entry],
121 selection: &Selection,
122 gzip: Option<&str>,
123) -> Option<BTreeSet<String>> {
124 let mut names = BTreeSet::new();
125 for entry in entries
126 .iter()
127 .filter(|entry| entry.kind == Kind::File && requested(entry, selection))
128 {
129 if !names.insert(gzip.unwrap_or(&entry.name).replace('\\', "/")) {
130 return None;
131 }
132 }
133 Some(names)
134}
135
136pub fn target_directories(entries: &[Entry], selection: &Selection) -> BTreeSet<String> {
137 let mut directories = BTreeSet::new();
138 for entry in entries.iter().filter(|entry| {
139 matches!(entry.kind, Kind::File | Kind::Directory) && requested(entry, selection)
140 }) {
141 let normalized = entry.name.replace('\\', "/");
142 let name = normalized.trim_end_matches('/');
143 if entry.kind == Kind::Directory {
144 directories.insert(name.to_owned());
145 }
146 let mut parent = name;
147 while let Some((directory, _)) = parent.rsplit_once('/') {
148 directories.insert(directory.to_owned());
149 parent = directory;
150 }
151 }
152 directories
153}
154
155pub fn durability_warning(durability: Durability) -> Option<&'static str> {
156 match durability {
157 Durability::Failed => Some(SYNC_FAILED),
158 Durability::Unconfirmed => Some(SYNC_WARNING),
159 _ => None,
160 }
161}
162
163pub fn warnings(
164 terminal: Option<&Terminal>,
165 confirmed: bool,
166 targets: Option<&BTreeSet<String>>,
167 directories: &BTreeSet<String>,
168 outputs: &[(String, Disposition)],
169) -> Vec<&'static str> {
170 let mut result = publication_warnings(terminal, confirmed, targets, directories, outputs);
171 if let Some(warning) = terminal
172 .filter(|_| confirmed)
173 .and_then(|t| durability_warning(t.durability))
174 {
175 result.push(warning);
176 }
177 result
178}
179
180pub fn publication_warnings(
181 terminal: Option<&Terminal>,
182 confirmed: bool,
183 targets: Option<&BTreeSet<String>>,
184 directories: &BTreeSet<String>,
185 outputs: &[(String, Disposition)],
186) -> Vec<&'static str> {
187 let Some(t) = terminal.filter(|_| confirmed) else {
188 return vec![UNCERTAIN];
189 };
190 let created = outputs
191 .iter()
192 .filter(|(_, state)| *state == Disposition::Created)
193 .map(|(name, _)| name.replace('\\', "/"))
194 .collect::<BTreeSet<_>>();
195 let created_reports = outputs
196 .iter()
197 .filter(|(_, state)| *state == Disposition::Created)
198 .count();
199 let uncertain = t.publication == Publication::Uncertain
200 || outputs
201 .iter()
202 .any(|(_, state)| *state == Disposition::CommitUncertain)
203 || created.len() != created_reports
204 || created_reports as u64 != t.created_count
205 || (t.publication == Publication::None && !created.is_empty());
206 let retained = t.retained_partial_count > 0
207 || outputs
208 .iter()
209 .any(|(_, state)| *state == Disposition::PartialRetained);
210 let mut result = Vec::new();
211 let mut all_saved_with_leftovers = false;
212 if uncertain {
213 result.push(UNCERTAIN);
214 } else if let Some(targets) = targets {
215 let files = created
216 .difference(directories)
217 .cloned()
218 .collect::<BTreeSet<_>>();
219 let saved = targets.intersection(&files).count();
220 let unknown = !targets.is_disjoint(directories)
221 || created
222 .iter()
223 .any(|name| !targets.contains(name) && !directories.contains(name));
224 if unknown {
225 result.push(UNCERTAIN);
226 } else if !targets.is_empty() && saved == targets.len() && retained {
227 result.push(LEFTOVERS);
228 all_saved_with_leftovers = true;
229 } else if saved > 0 && saved < targets.len() && t.outcome != Outcome::Completed {
230 result.push(PARTIAL);
231 } else if (saved == 0 && !files.is_empty())
232 || (retained && saved == 0)
233 || (t.outcome == Outcome::Completed && saved != targets.len())
234 {
235 result.push(UNCERTAIN);
236 }
237 } else {
238 result.push(UNCERTAIN);
239 }
240 if (retained || t.cleanup != Cleanup::Complete) && !all_saved_with_leftovers {
241 result.push(CLEANUP_WARNING);
242 }
243 result
244}
245
246pub fn definitely_unsaved(
247 t: Option<&Terminal>,
248 confirmed: bool,
249 outputs: &[(String, Disposition)],
250) -> bool {
251 t.is_some_and(|t| {
252 confirmed
253 && t.publication == Publication::None
254 && t.created_count == 0
255 && t.retained_partial_count == 0
256 && t.cleanup == Cleanup::Complete
257 && outputs
258 .iter()
259 .all(|(_, state)| *state == Disposition::Removed)
260 })
261}
262
263#[derive(Clone)]
264pub struct BrowserEntry {
265 pub path: PathBuf,
266 pub name: String,
267 pub directory: bool,
268 pub link: bool,
269}
270
271pub fn directory_entries(path: &Path) -> io::Result<Vec<BrowserEntry>> {
272 if fs::symlink_metadata(path)?.file_type().is_symlink() {
273 return Err(io::Error::other("링크 폴더는 탐색하지 않음"));
274 }
275 let mut entries = Vec::new();
276 for item in fs::read_dir(path)? {
277 let item = item?;
278 let kind = item.file_type()?;
279 entries.push(BrowserEntry {
280 path: item.path(),
281 name: item.file_name().to_string_lossy().into(),
282 directory: kind.is_dir(),
283 link: kind.is_symlink(),
284 });
285 }
286 entries.sort_by(|a, b| {
287 b.directory
288 .cmp(&a.directory)
289 .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
290 });
291 Ok(entries)
292}
293
294pub fn home_directory() -> PathBuf {
295 std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
296 .map(PathBuf::from)
297 .filter(|p| p.is_absolute())
298 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")))
299}
300
301pub fn shortcuts() -> Vec<(String, PathBuf)> {
302 let home = home_directory();
303 let mut paths = vec![("홈".into(), home.clone())];
304 for (label, candidates) in [
305 ("바탕 화면", ["Desktop", "바탕화면"]),
306 ("문서", ["Documents", "문서"]),
307 ("다운로드", ["Downloads", "다운로드"]),
308 ] {
309 if let Some(path) = candidates
310 .iter()
311 .map(|name| home.join(name))
312 .find(|p| p.is_dir())
313 {
314 paths.push((label.into(), path));
315 }
316 }
317 #[cfg(windows)]
318 for drive in b'A'..=b'Z' {
319 let path = PathBuf::from(format!("{}:\\", drive as char));
320 if path.is_dir() {
321 paths.push((format!("{}:", drive as char), path));
322 }
323 }
324 paths
325}
326
327pub fn folder_command(path: &Path) -> std::process::Command {
328 let mut command = std::process::Command::new(if cfg!(windows) {
329 "explorer"
330 } else {
331 "xdg-open"
332 });
333 command.arg(path);
334 command
335}
336
337pub const UNCONFIRMED_FINISH: &str =
338 "작업이 정상적으로 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요";
339
340pub fn client_error_text(error: &str) -> &'static str {
341 if error.starts_with("작업자 종료 결과를 확인할 수 없습니다") {
342 UNCONFIRMED_FINISH
343 } else {
344 INTERNAL
345 }
346}
347
348pub fn activity_text(model: &Model, creating: bool) -> &'static str {
349 if model.terminal.is_some()
350 || matches!(
351 model.cancel,
352 Some(CancelStatus::TooLate | CancelStatus::Finished)
353 )
354 {
355 "마무리하는 중"
356 } else if model.cancellation_requested() || model.cancel.is_some() {
357 "취소하는 중..."
358 } else if model.challenge.is_some() {
359 "암호를 입력하세요"
360 } else {
361 model
362 .progress
363 .map_or("압축파일을 읽는 중", |(stage, _, _, _)| {
364 progress_text(stage, creating)
365 })
366 }
367}
368
369pub fn valid_output_leaf(name: &str) -> bool {
370 valid_leaf(name) && worker_protocol::archive::valid_name(name, false).is_ok()
371}
372
373pub fn gzip_output_name(archive: &Path) -> String {
374 let file_name = archive
375 .file_name()
376 .and_then(|name| name.to_str())
377 .unwrap_or("");
378 let candidate = file_name
379 .rsplit_once('.')
380 .filter(|(_, suffix)| suffix.eq_ignore_ascii_case("gz"))
381 .map_or(file_name, |(stem, _)| stem);
382 if valid_output_leaf(candidate) {
383 candidate.to_owned()
384 } else {
385 "압축 해제 파일".into()
386 }
387}
388
389pub fn operation_text(text: &str, creating: bool) -> String {
390 if creating {
391 text.replace("풀 위치", "저장 위치")
392 .replace("선택한 항목", "추가한 항목")
393 .replace(
394 "일부 파일만 풀렸습니다. 풀린 파일은",
395 "ZIP 파일이 일부만 저장됐습니다. 저장된 파일은",
396 )
397 } else {
398 text.to_owned()
399 }
400}