team-ljyzipelo

공개

Merge pull request #147 from Team-LJY/fix/pr144-temp-cleanup-identity

종료 시 교체된 임시 폴더 보존
작성자
LeeJunyoung
작성 시각
커밋
00db1f5c21506a9213d9a32103f332f6b3c7c595
이 시점의 파일 보기

변경된 파일 5개

+501-10
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -16,6 +16,7 @@ mod space;
1616mod split_seven_zip;
1717mod spool;
1818mod streaming;
19추가: pub mod tree_remove;
1920pub mod wire;
2021mod zip_recovery;
2122
추가experiments/rust-archive-worker/src/tree_remove.rs+194-0
@@ -0,0 +1,194 @@
1추가: //! 열어 둔 폴더 핸들에 묶어서 폴더 안의 내용을 지움.
2추가: //! 경로를 다시 해석하지 않으므로 확인한 뒤 경로가 바뀌어도 다른 폴더를 지우지 않음.
3추가:
4추가: use std::fs::File;
5추가: use std::io;
6추가: use std::path::Path;
7추가:
8추가: /// `dir` 핸들이 가리키는 폴더 안의 모든 항목을 지움. 폴더 자체는 지우지 않음.
9추가: /// Linux는 핸들 기준 `unlinkat`으로 지우며 `path`는 쓰지 않음.
10추가: /// Windows는 호출한 쪽이 공유 삭제를 허용하지 않고 `dir`을 열어 두어 폴더 이름이
11추가: /// 바뀌지 않게 한 상태에서만 `path`를 씀.
12추가: pub fn remove_contents(dir: &File, path: &Path) -> io::Result<()> {
13추가: platform::remove_contents(dir, path)
14추가: }
15추가:
16추가: /// `dir` 핸들이 가리키는 폴더가 비어 있는지 확인함. 새로 만든 폴더를 핸들로 잡은 직후 쓰임.
17추가: pub fn is_empty(dir: &File, path: &Path) -> io::Result<bool> {
18추가: platform::is_empty(dir, path)
19추가: }
20추가:
21추가: #[cfg(target_os = "linux")]
22추가: mod platform {
23추가: use std::ffi::{CStr, CString};
24추가: use std::fs::File;
25추가: use std::io;
26추가: use std::os::unix::{
27추가: fs::MetadataExt,
28추가: io::{AsRawFd, FromRawFd},
29추가: };
30추가: use std::path::Path;
31추가:
32추가: #[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
33추가: const NOFOLLOW_DIRECTORY: i32 = 0x8000 | 0x4000;
34추가: #[cfg(not(any(target_arch = "aarch64", target_arch = "arm")))]
35추가: const NOFOLLOW_DIRECTORY: i32 = 0x20000 | 0x10000;
36추가: const CLOEXEC: i32 = 0x80000;
37추가: const AT_REMOVEDIR: i32 = 0x200;
38추가: const ENOENT: i32 = 2;
39추가: const EPERM: i32 = 1;
40추가: const EISDIR: i32 = 21;
41추가: /// 깊게 중첩된 폴더에서 파일 디스크립터가 바닥나지 않게 하는 한도.
42추가: const MAX_DEPTH: usize = 256;
43추가:
44추가: #[repr(C)]
45추가: struct Dirent64 {
46추가: inode: u64,
47추가: offset: i64,
48추가: length: u16,
49추가: kind: u8,
50추가: name: [i8; 256],
51추가: }
52추가:
53추가: unsafe extern "C" {
54추가: fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32;
55추가: fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
56추가: fn fdopendir(fd: i32) -> *mut std::ffi::c_void;
57추가: fn readdir64(stream: *mut std::ffi::c_void) -> *mut Dirent64;
58추가: fn rewinddir(stream: *mut std::ffi::c_void);
59추가: fn closedir(stream: *mut std::ffi::c_void) -> i32;
60추가: }
61추가:
62추가: pub fn remove_contents(dir: &File, _path: &Path) -> io::Result<()> {
63추가: let device = dir.metadata()?.dev();
64추가: remove_children(dir, device, 0)
65추가: }
66추가:
67추가: pub fn is_empty(dir: &File, _path: &Path) -> io::Result<bool> {
68추가: Ok(names(dir)?.is_empty())
69추가: }
70추가:
71추가: fn names(dir: &File) -> io::Result<Vec<CString>> {
72추가: let copy = dir.try_clone()?;
73추가: let fd = std::os::unix::io::IntoRawFd::into_raw_fd(copy);
74추가: // 복제한 디스크립터의 소유권은 폴더 스트림이 가져가며 closedir이 닫음.
75추가: let stream = unsafe { fdopendir(fd) };
76추가: if stream.is_null() {
77추가: let error = io::Error::last_os_error();
78추가: // 스트림을 만들지 못했으므로 복제한 디스크립터를 직접 돌려받아 닫음.
79추가: drop(unsafe { File::from_raw_fd(fd) });
80추가: return Err(error);
81추가: }
82추가: // 복제한 디스크립터는 원본과 읽기 위치를 공유하므로 처음부터 읽음.
83추가: unsafe { rewinddir(stream) };
84추가: let mut found = Vec::new();
85추가: loop {
86추가: let entry = unsafe { readdir64(stream) };
87추가: if entry.is_null() {
88추가: break;
89추가: }
90추가: // 반환된 항목은 다음 readdir64 호출 전까지 유효하며 바로 복사함.
91추가: let name = unsafe { CStr::from_ptr((*entry).name.as_ptr()) };
92추가: let bytes = name.to_bytes();
93추가: if bytes != b"." && bytes != b".." {
94추가: found.push(name.to_owned());
95추가: }
96추가: }
97추가: unsafe { closedir(stream) };
98추가: Ok(found)
99추가: }
100추가:
101추가: fn unlink(dir: &File, name: &CString, flags: i32) -> io::Result<()> {
102추가: // 부모 핸들 기준으로 이름 하나만 지움.
103추가: if unsafe { unlinkat(dir.as_raw_fd(), name.as_ptr(), flags) } == 0 {
104추가: Ok(())
105추가: } else {
106추가: Err(io::Error::last_os_error())
107추가: }
108추가: }
109추가:
110추가: fn open_directory(dir: &File, name: &CString) -> io::Result<File> {
111추가: // 심볼릭 링크를 따르지 않고 폴더만 부모 핸들 기준으로 엶.
112추가: let fd = unsafe {
113추가: openat(
114추가: dir.as_raw_fd(),
115추가: name.as_ptr(),
116추가: NOFOLLOW_DIRECTORY | CLOEXEC,
117추가: )
118추가: };
119추가: if fd < 0 {
120추가: return Err(io::Error::last_os_error());
121추가: }
122추가: Ok(unsafe { File::from_raw_fd(fd) })
123추가: }
124추가:
125추가: fn remove_children(dir: &File, device: u64, depth: usize) -> io::Result<()> {
126추가: let mut failure = None;
127추가: for name in names(dir)? {
128추가: if let Err(error) = remove_entry(dir, &name, device, depth) {
129추가: if error.raw_os_error() != Some(ENOENT) {
130추가: failure.get_or_insert(error);
131추가: }
132추가: }
133추가: }
134추가: failure.map_or(Ok(()), Err)
135추가: }
136추가:
137추가: fn remove_entry(dir: &File, name: &CString, device: u64, depth: usize) -> io::Result<()> {
138추가: match unlink(dir, name, 0) {
139추가: Ok(()) => return Ok(()),
140추가: Err(error) if matches!(error.raw_os_error(), Some(EISDIR | EPERM)) => {}
141추가: Err(error) => return Err(error),
142추가: }
143추가: if depth >= MAX_DEPTH {
144추가: return Err(io::Error::other("폴더가 너무 깊음"));
145추가: }
146추가: let child = match open_directory(dir, name) {
147추가: Ok(child) => child,
148추가: // 그 사이 폴더가 아닌 항목으로 바뀌었으면 항목 자체를 지움.
149추가: Err(_) => return unlink(dir, name, 0),
150추가: };
151추가: // 다른 파일 시스템이 연결된 폴더 안은 지우지 않음.
152추가: if child.metadata()?.dev() != device {
153추가: return Err(io::Error::other("다른 파일 시스템의 폴더"));
154추가: }
155추가: remove_children(&child, device, depth + 1)?;
156추가: drop(child);
157추가: unlink(dir, name, AT_REMOVEDIR)
158추가: }
159추가: }
160추가:
161추가: #[cfg(windows)]
162추가: mod platform {
163추가: use std::fs::{self, File};
164추가: use std::io;
165추가: use std::path::Path;
166추가:
167추가: pub fn is_empty(_dir: &File, path: &Path) -> io::Result<bool> {
168추가: // 호출한 쪽의 핸들이 이름 변경을 막고 있으므로 경로가 같은 폴더를 가리킴.
169추가: Ok(fs::read_dir(path)?.next().is_none())
170추가: }
171추가:
172추가: pub fn remove_contents(_dir: &File, path: &Path) -> io::Result<()> {
173추가: let mut failure = None;
174추가: // 호출한 쪽의 핸들이 폴더 이름 변경을 막고 있으므로 경로가 같은 폴더를 가리킴.
175추가: for entry in fs::read_dir(path)? {
176추가: let result = entry.and_then(|entry| {
177추가: let path = entry.path();
178추가: let kind = fs::symlink_metadata(&path)?.file_type();
179추가: if kind.is_symlink() {
180추가: // 링크는 따라가지 않고 링크 자체만 지움.
181추가: fs::remove_file(&path).or_else(|_| fs::remove_dir(&path))
182추가: } else if kind.is_dir() {
183추가: fs::remove_dir_all(&path)
184추가: } else {
185추가: fs::remove_file(&path)
186추가: }
187추가: });
188추가: if let Err(error) = result {
189추가: failure.get_or_insert(error);
190추가: }
191추가: }
192추가: failure.map_or(Ok(()), Err)
193추가: }
194추가: }
수정experiments/rust-ui-memory-app/src/archive_present.rs+113-5
@@ -503,11 +503,89 @@ fn private_dir(path: &Path) -> io::Result<()> {
503503 builder.create(path)
504504}
505505
506추가: pub struct OpenRoot {
507추가: path: PathBuf,
508추가: handle: fs::File,
509추가: identity: worker_protocol::protocol::SourceObject,
510추가: }
511추가:
512추가: impl OpenRoot {
513추가: fn capture(path: PathBuf) -> io::Result<Self> {
514추가: let handle = open_root_handle(&path)?;
515추가: // 만든 직후에는 비어 있어야 함. 만든 뒤 핸들을 잡기 전에 다른 폴더로 바뀌었다면
516추가: // 사용자 데이터가 들어 있을 수 있으므로 원본으로 기록하지 않음.
517추가: if !worker_protocol::tree_remove::is_empty(&handle, &path)? {
518추가: return Err(io::Error::other("만든 임시 폴더가 아님"));
519추가: }
520추가: let identity = worker_protocol::filesystem::object(&handle)
521추가: .map_err(|_| io::Error::other("임시 폴더 식별 실패"))?;
522추가: Ok(Self {
523추가: path,
524추가: handle,
525추가: identity,
526추가: })
527추가: }
528추가:
529추가: pub fn path(&self) -> &Path {
530추가: &self.path
531추가: }
532추가:
533추가: pub fn is_current(&self) -> bool {
534추가: // 원본 핸들을 유지해 삭제된 inode가 재사용되어도 같다고 판정하지 않음.
535추가: self.handle.metadata().is_ok()
536추가: && open_root_handle(&self.path)
537추가: .ok()
538추가: .and_then(|file| worker_protocol::filesystem::object(&file).ok())
539추가: .is_some_and(|identity| identity == self.identity)
540추가: }
541추가: }
542추가:
543추가: fn open_root_handle(path: &Path) -> io::Result<fs::File> {
544추가: let mut options = fs::OpenOptions::new();
545추가: options.read(true);
546추가: #[cfg(target_os = "linux")]
547추가: {
548추가: use std::os::unix::fs::OpenOptionsExt;
549추가: options.custom_flags(0x20000); // 심볼릭 링크를 따라가지 않음.
550추가: }
551추가: #[cfg(windows)]
552추가: {
553추가: use std::os::windows::fs::OpenOptionsExt;
554추가: // 폴더 자체를 열며 재분석 지점을 따라가지 않음.
555추가: // 삭제 공유를 허용하지 않아 열어 둔 동안 폴더 이름을 바꾸거나 지울 수 없게 함.
556추가: options.share_mode(1 | 2).custom_flags(0x02000000 | 0x00200000);
557추가: }
558추가: let file = options.open(path)?;
559추가: let metadata = file.metadata()?;
560추가: if !metadata.is_dir() || fs::symlink_metadata(path)?.file_type().is_symlink() {
561추가: return Err(io::Error::other("임시 폴더가 아님"));
562추가: }
563추가: #[cfg(windows)]
564추가: {
565추가: use std::os::windows::fs::MetadataExt;
566추가: if metadata.file_attributes() & 0x400 != 0 {
567추가: return Err(io::Error::other("재분석 지점은 임시 폴더로 쓰지 않음"));
568추가: }
569추가: }
570추가: Ok(file)
571추가: }
572추가:
506573/// 압축파일 안 파일을 기본 프로그램으로 열 때 쓸 임시 폴더를 만듦.
507574/// 압축파일과 같은 폴더에 만들고, 그곳에 만들 수 없으면 시스템 임시 폴더를 씀.
508575/// 숨김 폴더로 만들지 않음. snap으로 설치한 Firefox 등은 홈 바로 아래 숨김 폴더와
509576/// 시스템 임시 폴더의 파일을 읽지 못해 열기 요청을 조용히 무시함.
510삭제: pub fn create_open_root(archive: &Path) -> io::Result<PathBuf> {
577추가: pub fn create_open_root(archive: &Path) -> io::Result<OpenRoot> {
578추가: create_open_root_with(archive, |_| {})
579추가: }
580추가:
581추가: /// `create_open_root`와 같고, 폴더를 만든 직후 핸들을 잡기 전에 `after_create`를 실행함.
582추가: /// 만든 뒤 경로가 바뀌는 경우를 시험하려고 둠.
583추가: /// 폴더를 만든 뒤 핸들을 잡기까지의 틈에 경로가 바뀌어도, 핸들로 확인한 폴더가 비어 있지
584추가: /// 않으면 원본으로 쓰지 않고 다른 이름으로 다시 만듦. 바뀐 폴더는 건드리지 않음.
585추가: pub fn create_open_root_with(
586추가: archive: &Path,
587추가: mut after_create: impl FnMut(&Path),
588추가: ) -> io::Result<OpenRoot> {
511589 let name = archive.file_name().unwrap_or_default().to_string_lossy();
512590 let mut error = None;
513591 if let Some(parent) = archive.parent().filter(|p| !p.as_os_str().is_empty()) {
@@ -515,7 +593,18 @@ pub fn create_open_root(archive: &Path) -> io::Result<PathBuf> {
515593 for _ in 0..8 {
516594 let path = unique_folder(&base);
517595 match private_dir(&path) {
518삭제: Ok(()) => return Ok(path),
596추가: Ok(()) => {
597추가: after_create(&path);
598추가: match OpenRoot::capture(path.clone()) {
599추가: Ok(root) => return Ok(root),
600추가: Err(e) => {
601추가: // 비어 있는 폴더만 지워지므로 바뀐 폴더의 내용은 남음.
602추가: let _ = fs::remove_dir(&path);
603추가: error = Some(e);
604추가: continue;
605추가: }
606추가: }
607추가: }
519608 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
520609 Err(e) => {
521610 error = Some(e);
@@ -527,7 +616,10 @@ pub fn create_open_root(archive: &Path) -> io::Result<PathBuf> {
527616 let base = std::env::temp_dir().join(format!("zipelo-{}-{name}", std::process::id()));
528617 let path = unique_folder(&base);
529618 private_dir(&path).map_err(|e| error.unwrap_or(e))?;
530삭제: Ok(path)
619추가: after_create(&path);
620추가: OpenRoot::capture(path.clone()).inspect_err(|_| {
621추가: let _ = fs::remove_dir(&path);
622추가: })
531623}
532624
533625/// 열기용 임시 폴더 이름. 예: `자료.zip (Zipelo 임시)`.
@@ -536,8 +628,24 @@ pub fn open_root_name(archive_name: &str) -> String {
536628}
537629
538630/// 이 앱이 만든 열기용 폴더를 지움. 다른 프로그램이 파일을 쓰고 있으면 남을 수 있음.
539삭제: pub fn remove_open_root(path: &Path) {
540삭제: let _ = fs::remove_dir_all(path);
631추가: pub fn remove_open_root(root: OpenRoot) {
632추가: remove_open_root_with(root, || {});
633추가: }
634추가:
635추가: /// `remove_open_root`와 같고, 정체를 확인한 직후 삭제 전에 `after_check`를 실행함.
636추가: /// 확인과 삭제 사이에 경로가 바뀌는 경우를 시험하려고 둠.
637추가: /// 내용은 만들 때 열어 둔 폴더 핸들에 묶어 지우므로 경로가 바뀌어도 다른 폴더는 건드리지 않음.
638추가: pub fn remove_open_root_with(root: OpenRoot, after_check: impl FnOnce()) {
639추가: if !root.is_current() {
640추가: return;
641추가: }
642추가: after_check();
643추가: let OpenRoot { path, handle, .. } = root;
644추가: let _ = worker_protocol::tree_remove::remove_contents(&handle, &path);
645추가: // Windows는 핸들을 닫아야 폴더를 지울 수 있음.
646추가: drop(handle);
647추가: // 비어 있지 않거나 링크로 바뀐 경로는 지워지지 않으므로 다른 내용이 사라지지 않음.
648추가: let _ = fs::remove_dir(&path);
541649}
542650
543651/// 기본 프로그램으로 열면 실행될 수 있는 파일은 바로 열지 않음.
수정experiments/rust-ui-memory-app/src/archive_screen.rs+6-5
@@ -284,7 +284,7 @@ pub struct ArchiveApp {
284284 /// 마지막 풀기가 기본 프로그램으로 열기였으면 그 항목. 다시 시도할 때 다시 엶.
285285 last_open: Option<u32>,
286286 /// 압축파일별 열기용 임시 폴더. 앱을 닫을 때 지움.
287삭제: open_roots: Vec<(PathBuf, PathBuf)>,
287추가: open_roots: Vec<(PathBuf, present::OpenRoot)>,
288288 open_count: u64,
289289 opener: Opener,
290290 #[cfg(all(feature = "ui-fixture", debug_assertions))]
@@ -410,12 +410,13 @@ impl ArchiveApp {
410410 return false;
411411 };
412412 let root = match self.open_roots.iter().find(|(a, _)| *a == archive) {
413삭제: Some((_, root)) if root.is_dir() => root.clone(),
413추가: Some((_, root)) if root.is_current() => root.path().to_path_buf(),
414414 _ => match present::create_open_root(&archive) {
415415 Ok(root) => {
416416 self.open_roots.retain(|(a, _)| *a != archive);
417삭제: self.open_roots.push((archive, root.clone()));
418삭제: root
417추가: let path = root.path().to_path_buf();
418추가: self.open_roots.push((archive, root));
419추가: path
419420 }
420421 Err(_) => {
421422 self.dismissed = false;
@@ -3658,7 +3659,7 @@ impl Drop for ArchiveApp {
36583659 fn drop(&mut self) {
36593660 self.clear_password();
36603661 for (_, root) in self.open_roots.drain(..) {
3661삭제: present::remove_open_root(&root);
3662추가: present::remove_open_root(root);
36623663 }
36633664 }
36643665}
수정tests/rust-app-ui/presentation.rs+187-0
@@ -1156,3 +1156,190 @@ fn client_protocol_errors_hide_internal_terms_but_preserve_exit_uncertainty() {
11561156 UNCONFIRMED_FINISH
11571157 );
11581158}
1159추가:
1160추가: #[cfg(feature = "ui")]
1161추가: #[cfg(unix)]
1162추가: #[test]
1163추가: fn app_exit_preserves_replaced_open_root() {
1164추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1165추가: let scratch = Folder::new();
1166추가: let mut app = ArchiveApp::new(
1167추가: Box::new(FakeFactory::default()),
1168추가: Some(scratch.0.join("sample.zip")),
1169추가: false,
1170추가: );
1171추가: pump(&mut app.model);
1172추가: assert!(app.open_entry(0));
1173추가: let root = scratch.0.join(open_root_name("sample.zip"));
1174추가: fs::rename(&root, scratch.0.join("original")).unwrap();
1175추가: fs::create_dir(&root).unwrap();
1176추가: let retained = root.join("keep.txt");
1177추가: fs::write(&retained, b"user data").unwrap();
1178추가: drop(app);
1179추가: assert_eq!(fs::read(retained).unwrap(), b"user data");
1180추가: }
1181추가:
1182추가: #[cfg(feature = "ui")]
1183추가: #[test]
1184추가: fn app_exit_removes_original_open_root() {
1185추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1186추가: let scratch = Folder::new();
1187추가: let mut app = ArchiveApp::new(
1188추가: Box::new(FakeFactory::default()),
1189추가: Some(scratch.0.join("sample.zip")),
1190추가: false,
1191추가: );
1192추가: pump(&mut app.model);
1193추가: assert!(app.open_entry(0));
1194추가: let root = scratch.0.join(open_root_name("sample.zip"));
1195추가: fs::write(root.join("opened.txt"), b"temporary").unwrap();
1196추가: drop(app);
1197추가: assert!(!root.exists());
1198추가: }
1199추가:
1200추가: #[cfg(feature = "ui")]
1201추가: #[cfg(windows)]
1202추가: #[test]
1203추가: fn open_root_cannot_be_renamed_while_app_holds_it() {
1204추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1205추가: let scratch = Folder::new();
1206추가: let mut app = ArchiveApp::new(
1207추가: Box::new(FakeFactory::default()),
1208추가: Some(scratch.0.join("sample.zip")),
1209추가: false,
1210추가: );
1211추가: pump(&mut app.model);
1212추가: assert!(app.open_entry(0));
1213추가: let root = scratch.0.join(open_root_name("sample.zip"));
1214추가: // 열어 둔 핸들이 이름 변경을 막아 경로가 다른 폴더로 바뀌지 않음.
1215추가: assert!(fs::rename(&root, scratch.0.join("original")).is_err());
1216추가: drop(app);
1217추가: assert!(!root.exists());
1218추가: }
1219추가:
1220추가: #[cfg(unix)]
1221추가: fn open_root_with_contents(scratch: &Folder) -> (OpenRoot, PathBuf) {
1222추가: let root = create_open_root(&scratch.0.join("sample.zip")).unwrap();
1223추가: let path = root.path().to_path_buf();
1224추가: fs::create_dir_all(path.join("a/b")).unwrap();
1225추가: fs::write(path.join("a/b/deep.txt"), b"temporary").unwrap();
1226추가: fs::write(path.join("top.txt"), b"temporary").unwrap();
1227추가: (root, path)
1228추가: }
1229추가:
1230추가: #[cfg(unix)]
1231추가: #[test]
1232추가: fn removal_is_bound_to_checked_folder_when_replaced_after_check() {
1233추가: let scratch = Folder::new();
1234추가: let (root, path) = open_root_with_contents(&scratch);
1235추가: let original = scratch.0.join("original");
1236추가: remove_open_root_with(root, || {
1237추가: fs::rename(&path, &original).unwrap();
1238추가: fs::create_dir(&path).unwrap();
1239추가: fs::write(path.join("keep.txt"), b"user data").unwrap();
1240추가: });
1241추가: assert_eq!(fs::read(path.join("keep.txt")).unwrap(), b"user data");
1242추가: // 확인한 폴더의 내용만 지움.
1243추가: assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1244추가: }
1245추가:
1246추가: #[cfg(unix)]
1247추가: #[test]
1248추가: fn removal_does_not_follow_link_swapped_in_after_check() {
1249추가: let scratch = Folder::new();
1250추가: let (root, path) = open_root_with_contents(&scratch);
1251추가: let victim = scratch.0.join("victim");
1252추가: fs::create_dir(&victim).unwrap();
1253추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1254추가: let original = scratch.0.join("original");
1255추가: remove_open_root_with(root, || {
1256추가: fs::rename(&path, &original).unwrap();
1257추가: std::os::unix::fs::symlink(&victim, &path).unwrap();
1258추가: });
1259추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1260추가: assert!(fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
1261추가: assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1262추가: }
1263추가:
1264추가: #[cfg(unix)]
1265추가: #[test]
1266추가: fn removal_does_not_follow_links_inside_folder() {
1267추가: let scratch = Folder::new();
1268추가: let (root, path) = open_root_with_contents(&scratch);
1269추가: let victim = scratch.0.join("victim");
1270추가: fs::create_dir(&victim).unwrap();
1271추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1272추가: std::os::unix::fs::symlink(&victim, path.join("a/link")).unwrap();
1273추가: std::os::unix::fs::symlink(victim.join("keep.txt"), path.join("file-link")).unwrap();
1274추가: remove_open_root(root);
1275추가: assert!(!path.exists());
1276추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1277추가: }
1278추가:
1279추가: #[cfg(unix)]
1280추가: #[test]
1281추가: fn removal_of_original_folder_clears_nested_contents() {
1282추가: let scratch = Folder::new();
1283추가: let (root, path) = open_root_with_contents(&scratch);
1284추가: remove_open_root(root);
1285추가: assert!(!path.exists());
1286추가: }
1287추가:
1288추가: #[cfg(unix)]
1289추가: #[test]
1290추가: fn creation_does_not_adopt_folder_replaced_before_handle_is_taken() {
1291추가: let scratch = Folder::new();
1292추가: let archive = scratch.0.join("sample.zip");
1293추가: let swapped = scratch.0.join(open_root_name("sample.zip"));
1294추가: let original = scratch.0.join("original");
1295추가: let mut swaps = 0;
1296추가: let root = create_open_root_with(&archive, |path| {
1297추가: swaps += 1;
1298추가: if swaps == 1 {
1299추가: fs::rename(path, &original).unwrap();
1300추가: fs::create_dir(path).unwrap();
1301추가: fs::write(path.join("keep.txt"), b"user data").unwrap();
1302추가: }
1303추가: })
1304추가: .unwrap();
1305추가: // 바뀐 폴더는 원본으로 기록하지 않고 다른 이름의 새 폴더를 씀.
1306추가: assert_ne!(root.path(), swapped);
1307추가: assert!(root.is_current());
1308추가: remove_open_root(root);
1309추가: assert_eq!(fs::read(swapped.join("keep.txt")).unwrap(), b"user data");
1310추가: }
1311추가:
1312추가: #[cfg(unix)]
1313추가: #[test]
1314추가: fn creation_does_not_adopt_link_replaced_before_handle_is_taken() {
1315추가: let scratch = Folder::new();
1316추가: let archive = scratch.0.join("sample.zip");
1317추가: let link = scratch.0.join(open_root_name("sample.zip"));
1318추가: let victim = scratch.0.join("victim");
1319추가: fs::create_dir(&victim).unwrap();
1320추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1321추가: let mut swaps = 0;
1322추가: let root = create_open_root_with(&archive, |path| {
1323추가: swaps += 1;
1324추가: if swaps == 1 {
1325추가: fs::remove_dir(path).unwrap();
1326추가: std::os::unix::fs::symlink(&victim, path).unwrap();
1327추가: }
1328추가: })
1329추가: .unwrap();
1330추가: assert_ne!(root.path(), link);
1331추가: remove_open_root(root);
1332추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1333추가: assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
1334추가: }
1335추가:
1336추가: #[test]
1337추가: fn creation_of_unchanged_folder_is_empty_and_current() {
1338추가: let scratch = Folder::new();
1339추가: let root = create_open_root(&scratch.0.join("sample.zip")).unwrap();
1340추가: let path = root.path().to_path_buf();
1341추가: assert!(root.is_current());
1342추가: assert_eq!(fs::read_dir(&path).unwrap().count(), 0);
1343추가: remove_open_root(root);
1344추가: assert!(!path.exists());
1345추가: }