{"record":{"id":"131769ea631049b9","repo":"astral-sh/ruff","slug":"file-already-exists","errorCode":null,"errorMessage":"File already exists","messagePattern":"File already exists","errorType":"error_code","errorClass":"io::Error","httpStatus":null,"severity":"error","filePath":"crates/ruff_db/src/system/memory_fs.rs","lineNumber":182,"sourceCode":"\n    pub(crate) fn create_new_file(&self, path: &SystemPath) -> Result<()> {\n        let normalized = self.normalize_path(path);\n\n        let mut by_path = self.inner.by_path.write().unwrap();\n        match by_path.entry(normalized) {\n            btree_map::Entry::Vacant(entry) => {\n                let parent = entry.key().parent().map(Utf8Path::to_path_buf);\n                entry.insert(Entry::File(File {\n                    content: Box::default(),\n                    last_modified: file_time_now(),\n                }));\n                if let Some(parent) = parent {\n                    touch_directory(&mut by_path, &parent);\n                }\n\n                Ok(())\n            }\n            btree_map::Entry::Occupied(_) => Err(io::Error::new(\n                io::ErrorKind::AlreadyExists,\n                \"File already exists\",\n            )),\n        }\n    }\n\n    /// Stores a new file in the file system.\n    ///\n    /// The operation overrides the content for an existing file with the same normalized `path`.\n    pub fn write_file(\n        &self,\n        path: impl AsRef<SystemPath>,\n        content: impl AsRef<[u8]>,\n    ) -> Result<()> {\n        let mut by_path = self.inner.by_path.write().unwrap();\n\n        let normalized = self.normalize_path(path.as_ref());\n        let file = get_or_create_file(&mut by_path, &normalized)?;","sourceCodeStart":164,"sourceCodeEnd":200,"githubUrl":"https://github.com/astral-sh/ruff/blob/26f38c119cac42e4d320ba08f09224fdec74af2c/crates/ruff_db/src/system/memory_fs.rs#L164-L200","documentation":"This io::Error (kind AlreadyExists) is raised by the in-memory file system's `create_new_file` when a file already exists at the target path. It mirrors the semantics of `std::fs::OpenOptions::create_new(true)`, which must never overwrite an existing file.","triggerScenarios":"Calling `create_new_file` (or APIs built on it, like exclusive file creation in tests) with a path that already has an entry in the memory FS's `by_path` map.","commonSituations":"Test setups that create fixture files without checking existence, repeated setup of the same memory FS path across subtests, race-like double initialization in tooling using the memory FS.","solutions":["Check existence first with a read/lookup, or remove the existing file before creating","Use a write/overwrite API if replacement is intended instead of exclusive creation","Generate unique paths (e.g. temp-style unique names) for each new file"],"exampleFix":"// before\nfs.create_new_file(path, contents)?; // fails if path exists\n// after\nif fs.read_file(path).is_ok() {\n    fs.remove_file(path)?;\n}\nfs.create_new_file(path, contents)?;","handlingStrategy":"validation","validationCode":"if fs.read_file(path).is_ok() {\n    return Err(io::Error::new(io::ErrorKind::AlreadyExists, \"path exists\"));\n}","typeGuard":"fn path_is_free(fs: &MemoryFileSystem, path: &VfsPath) -> bool {\n    fs.read_file(path).is_err()\n}","tryCatchPattern":"match fs.create_new_file(path, contents) {\n    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => reuse_or_replace(path, contents),\n    Err(e) => return Err(e),\n    Ok(()) => (),\n}","preventionTips":["Use unique/temp-style names for each new memory-FS file","Reset the memory FS between test cases","Decide explicitly between exclusive-create and overwrite APIs"],"tags":["filesystem","memory-fs","conflict"],"backgroundTag":"file-already-exists","analyzedSha":"26f38c119cac42e4d320ba08f09224fdec74af2c","analyzedAt":"2026-09-05T10:32:37.492Z","contentChangedAt":"2026-09-05T10:32:37.492Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}