Programming Search⌘K

Taskintro

Rename a file

Also called move a file, rename a file atomically, replace a file atomically, mv.

Give a file a new name, also in another directory, with one rename call that replaces a file at the new name, so that a reader sees the old file or the new file, never a part.

Task

Give the file at path src the new name dst. The new name can be in another directory, but on the same file system. If a file is at dst, replace it. After the call, dst has the data of src, and no entry is at src. If src and dst name the same file, do nothing.

Do it with one rename call of the operating system. On POSIX, that call is atomic: "a directory entry named new shall remain visible to other threads throughout the renaming operation and refer either to the file referred to by new or old before the operation began." So a program that opens dst at any time sees the old file or the new file, never an empty file and never a part of one. This is why programs save a file in two steps: write a temporary file, then rename it over the old file. See the pitfalls.

Report an error, and change nothing, when src is missing, when the directory of dst is missing, when a directory is at dst, and when the two paths are on different file systems. A function that copies the file in the last case is a move, not a rename, and a copy is not atomic.

SQL, regular expressions, HTML and CSS do not apply, because they do not rename files.

Solutions

Each solution calls the rename function of its language. Most of those functions call POSIX rename on Unix. The Linux manual says: "If newpath already exists, it will be atomically replaced, so that there is no point at which another process attempting to access newpath will find it missing." Across file systems, rename fails with EXDEV: "oldpath and newpath are not on the same mounted filesystem."

  • Python. os.replace(src, dst): "If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement)." The code does not use os.rename, because "On Windows, if dst exists a FileExistsError is always raised."
  • JavaScript and TypeScript (Node.js). fsPromises.rename(src, dst). "In the case that newPath already exists, it will be overwritten. If there is a directory at newPath , an error will be raised instead."
  • Java. Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE). With no options, Files.move can copy the file, for example when the target "is on a different FileStore and would require that the file be copied". With ATOMIC_MOVE, "If the move cannot be performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown." For a file at dst, "it is implementation specific if the existing file is replaced or this method fails by throwing an IOException". On Unix it is replaced.
  • Go. os.Rename(src, dst). "If newpath already exists and is not a directory, Rename replaces it. If newpath already exists and is a directory, Rename returns an error." The error is a *os.LinkError, and errors.Is(err, syscall.EXDEV) finds a cross-device error.
  • Rust. std::fs::rename(src, dst) renames "replacing the original file if to already exists. This will not work if the new name is on a different mount point." A cross-device error has the kind ErrorKind::CrossesDevices.
  • C. POSIX rename(src, dst), which returns 0, or -1 with errno. ISO C has rename too, but it does not say what occurs to a file at the new name: "If new_filename exists, the behavior is implementation-defined." POSIX says what occurs, so the code is for POSIX systems.
  • C++. std::filesystem::rename(src, dst, ec) works "as if by the POSIX rename". For a file at dst: "new_p is first deleted, then, without allowing other processes to observe new_p as deleted, the pathname new_p is linked to the file and old_p is unlinked from the file." The function takes a std::error_code&, so it gives no exception.
  • Bash. mv -f -- "$src" "$dst". mv is a rename call only when the two paths are on one file system. When rename fails with EXDEV, mv copies the file and deletes src. So the function first compares the mount points of the two directories, from the last field of df -P, and returns status 1 if they are not the same. mv also moves a file into a directory at dst, so the function returns status 1 for a directory. For the same file, mv gives an error, so the function returns 0 first.

C# is not on this page. File.Move is not one rename call: "This method works across disk volumes", and "Moving the file across disk volumes is equivalent to copying the file and deleting it from the source if the copying was successful." .NET has no option that makes the call fail in place of a copy. The Windows function under it is MoveFileEx. With MOVEFILE_REPLACE_EXISTING, "If a file named lpNewFileName exists, the function replaces its contents with the contents of the lpExistingFileName file". With MOVEFILE_COPY_ALLOWED, "If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions."

On Linux, renameat2 with RENAME_NOREPLACE gives an error if dst exists: "Don't overwrite newpath of the rename. Return an error if newpath already exists." Use it when a file at the new name must not be lost.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each test makes the files in a new temporary directory, calls the function, and checks the content at dst and that no entry is at src.

  • rename and replace-existing: a new name, and a name that has a file. The old data at dst is gone.
  • same-path: src and dst are the same. POSIX says: "If the old argument and the new argument resolve to either the same existing directory entry or different directory entries for the same existing file, rename () shall return successfully and perform no other action." The file stays.
  • empty-file: an empty file replaces a file with text.
  • other-directory: a.txt to sub/a.txt. The directory sub must exist; the rename does not make it.
  • name-with-spaces and non-ascii-name: my notes.txt and café 日本.txt. A shell solution must quote the names.
  • Errors, in cases/errors.jsonl: a missing src and a missing directory of dst give not-found, and a directory at dst gives is-a-directory. POSIX: "If the old argument names a file that is not a directory and the new argument names a directory, or old names a directory and new names a file that is not a directory, or new names a directory that is not empty, rename () shall fail."

The native tests also check that a symbolic link at src is renamed and its target stays; that a program that has the old dst open still reads the old data; and, on Linux, when /dev/shm is on another file system, that a rename to it gives a cross-device error and src stays. The Python test also has threads that read dst while other threads rename new files over it, and each read gets a whole file.

Pitfalls

  • A save that writes in place. Opening a file for writing makes it empty at once. If the program fails before the write, or a reader opens the file during the write, the data is gone or is a part:

This code runs but gives a wrong answer on purpose.

import os
import tempfile


def make_config():
    raise RuntimeError("disk full")  # the program fails before it writes


with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "app.conf")
    with open(path, "w") as f:
        f.write("port = 8080\n")
    try:
        with open(path, "w") as f:  # "w" makes the file empty now
            f.write(make_config())
    except RuntimeError as e:
        print("error:", e)
    print("size:", os.path.getsize(path))
Output
error: disk full
size: 0

Write a temporary file in the same directory, and rename it over the old file. The temporary file must be on the same file system as the old file, so do not put it in /tmp:

import os
import tempfile


def save(path, text):
    dir = os.path.dirname(path)
    fd, tmp = tempfile.mkstemp(dir=dir, prefix=".tmp-")
    try:
        with os.fdopen(fd, "w") as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())  # the data is on the disk
        os.replace(tmp, path)  # one atomic step
    except BaseException:
        os.unlink(tmp)
        raise
    dfd = os.open(dir, os.O_RDONLY)
    try:
        os.fsync(dfd)  # the new name is on the disk
    finally:
        os.close(dfd)


with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "app.conf")
    save(path, "port = 8080\n")
    save(path, "port = 9090\n")
    with open(path) as f:
        print(f.read(), end="")
    print(os.listdir(dir))
Output
port = 9090
['app.conf']
  • A rename that is not on the disk. After a power failure, the new name can be lost, or the new name can point to a file with no data. os.fsync on the file before the rename puts the data on the disk. Then fsync on the directory puts the new name on the disk, because "fsync () does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync () on a file descriptor for the directory is also needed." The block above does both.

  • A move that is a copy. shutil.move, mv, Java Files.move with no options and C# File.Move copy the file when the two paths are on different file systems. For shutil.move: "In case os.rename() fails due to OSError (e.g. the user has write permission to the destination file but not to its parent directory), this method falls back to using copy_function , in which case src is copied to the destination using copy_function and then removed." During the copy, dst is a part of the file, and a failure can leave two files or one part. Use the rename function, and handle the cross-device error: write the temporary file on the file system of dst.

  • A directory at the new name. mv and shutil.move move the file into a directory at dst, with no error:

This code runs but gives a wrong answer on purpose.

dir=$(mktemp -d)
cd "$dir" || exit
printf 'alpha\n' >report.txt
mkdir backup  # a directory with the name the program wants for the file
mv -f report.txt backup
find . -type f
cd / && rm -r "$dir"
Output
./backup/report.txt

The program now looks for backup and finds a directory. The rename functions give an error for this case.

  • A rename that replaces only on Unix. Python os.rename replaces a file at dst on Unix, but "On Windows, if dst exists a FileExistsError is always raised." Code that is correct on Linux then fails on Windows. Use os.replace, which replaces the file on each platform.

  • A reader that has the old file open. A rename changes the name, not the data. A program that opened dst before the rename reads the old file to the end:

import os
import tempfile

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "app.conf")
    new = os.path.join(dir, "app.conf.new")
    with open(path, "w") as f:
        f.write("port = 8080\n")
    with open(new, "w") as f:
        f.write("port = 9090\n")
    with open(path) as reader:  # a reader that opened the old file
        os.replace(new, path)
        print("open reader:", reader.read(), end="")
    with open(path) as f:
        print("new open:", f.read(), end="")
Output
open reader: port = 8080
new open: port = 9090

A server that reads its configuration only at the start must open the file again to see the new data.

Code

The build runs the native tests of each language in a pinned toolchain.

rename_file.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rename-a-file/.

import os


def rename_file(src: str | os.PathLike, dst: str | os.PathLike) -> None:
    """Gives the file at src the name dst, and replaces a file at dst.

    os.replace is one rename call, so it is atomic. os.rename is not used,
    because on Windows it fails when dst exists. shutil.move is not used,
    because across file systems it copies the file, and a copy is not atomic.
    Each error, for example a cross-device error (EXDEV), comes out as an
    OSError.
    """
    os.replace(src, dst)
test_rename_file.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rename-a-file/.

import errno
import os
import threading
from pathlib import Path

import pytest

from rename_file import rename_file

# name: (src, dst, content of src, content of dst or None, content of dst after)
CASES = {
    "rename": ("a.txt", "b.txt", "alpha\n", None, "alpha\n"),
    "replace-existing": ("a.txt", "b.txt", "alpha\n", "beta\n", "alpha\n"),
    "same-path": ("a.txt", "a.txt", "alpha\n", "alpha\n", "alpha\n"),
    "empty-file": ("a.txt", "b.txt", "", "beta\n", ""),
    "other-directory": ("a.txt", "sub/a.txt", "alpha\n", None, "alpha\n"),
    "name-with-spaces": ("my notes.txt", "old notes.txt", "alpha\n", None, "alpha\n"),
    "non-ascii-name": ("a.txt", "café 日本.txt", "alpha\n", None, "alpha\n"),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    src_rel, dst_rel, src_content, dst_content, want = CASES[name]
    src, dst = tmp_path / src_rel, tmp_path / dst_rel
    dst.parent.mkdir(exist_ok=True)
    if dst_content is not None:
        dst.write_text(dst_content, encoding="utf-8")
    src.write_text(src_content, encoding="utf-8")
    rename_file(src, dst)
    assert dst.read_text(encoding="utf-8") == want
    assert src == dst or not os.path.lexists(src)


def test_missing_src(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        rename_file(tmp_path / "a.txt", tmp_path / "b.txt")
    assert not os.path.lexists(tmp_path / "b.txt")


def test_missing_dst_dir(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("alpha\n")
    with pytest.raises(FileNotFoundError):
        rename_file(tmp_path / "a.txt", tmp_path / "no-such-dir" / "b.txt")
    assert (tmp_path / "a.txt").read_text() == "alpha\n"


def test_dst_is_a_directory(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("alpha\n")
    (tmp_path / "dir").mkdir()
    with pytest.raises(OSError):
        rename_file(tmp_path / "a.txt", tmp_path / "dir")
    assert (tmp_path / "dir").is_dir()
    assert (tmp_path / "a.txt").read_text() == "alpha\n"


def test_link(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("alpha\n")
    os.symlink("a.txt", tmp_path / "link")
    rename_file(tmp_path / "link", tmp_path / "new-link")
    assert os.readlink(tmp_path / "new-link") == "a.txt"
    assert not os.path.lexists(tmp_path / "link")
    assert (tmp_path / "a.txt").read_text() == "alpha\n"


def test_open_dst_keeps_old_data(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("alpha\n")
    (tmp_path / "b.txt").write_text("beta\n")
    with open(tmp_path / "b.txt") as old:
        rename_file(tmp_path / "a.txt", tmp_path / "b.txt")
        assert old.read() == "beta\n"
    assert (tmp_path / "b.txt").read_text() == "alpha\n"


def test_readers_see_a_whole_file(tmp_path: Path) -> None:
    dst = tmp_path / "data.txt"
    texts = ["a" * 4096 + "\n", "b" * 4096 + "\n"]
    dst.write_text(texts[0])
    stop = threading.Event()
    seen = set()

    def read() -> None:
        while not stop.is_set():
            seen.add(dst.read_text())

    reader = threading.Thread(target=read)
    reader.start()
    try:
        for i in range(200):
            tmp = tmp_path / "data.txt.tmp"
            tmp.write_text(texts[i % 2])
            rename_file(tmp, dst)
    finally:
        stop.set()
        reader.join()
    assert seen <= set(texts)


def test_cross_device(tmp_path: Path) -> None:
    shm = Path("/dev/shm")
    if not shm.is_dir() or os.stat(shm).st_dev == os.stat(tmp_path).st_dev:
        pytest.skip("no other file system at /dev/shm")
    src = tmp_path / "a.txt"
    src.write_text("alpha\n")
    dst = shm / f"rename-file-{os.getpid()}.txt"
    with pytest.raises(OSError) as err:
        rename_file(src, dst)
    assert err.value.errno == errno.EXDEV
    assert src.read_text() == "alpha\n"
    assert not dst.exists()
rename_file.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

#include "rename_file.hpp"

void rename_file(const std::filesystem::path& src, const std::filesystem::path& dst, std::error_code& ec) {
    // std::filesystem::rename is POSIX rename: one call, atomic, and it does
    // not copy across file systems.
    std::filesystem::rename(src, dst, ec);
}
rename_file.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

#pragma once

#include <filesystem>
#include <system_error>

// Gives the file at src the name dst, and replaces a file at dst, with one
// rename call. Sets ec on an error, for example std::errc::is_a_directory, or
// std::errc::cross_device_link when the paths are on different file systems.
void rename_file(const std::filesystem::path& src, const std::filesystem::path& dst, std::error_code& ec);
test_rename_file.cpp 107 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <optional>
#include <string>
#include <system_error>

#include <sys/stat.h>
#include <unistd.h>

#include "rename_file.hpp"

namespace fs = std::filesystem;

namespace {

const fs::path dir = "rename_file_tree";
int failures = 0;

void put(const fs::path& p, const std::string& text) { std::ofstream(p, std::ios::binary) << text; }

std::string get(const fs::path& p) {
    std::ifstream in(p, std::ios::binary);
    return {std::istreambuf_iterator<char>(in), {}};
}

bool lexists(const fs::path& p) {
    std::error_code ec;
    return fs::exists(fs::symlink_status(p, ec));
}

void expect(bool ok, const char* what) {
    if (!ok) {
        std::fprintf(stderr, "%s\n", what);
        ++failures;
    }
}

void fresh() {
    fs::remove_all(dir);
    fs::create_directories(dir / "sub");
}

void run_case(const char* name, const char* src, const char* dst, const char* src_text,
              std::optional<std::string> dst_text, const char* want) {
    fresh();
    if (dst_text) put(dir / dst, *dst_text);
    put(dir / src, src_text);
    std::error_code ec;
    rename_file(dir / src, dir / dst, ec);
    bool ok = !ec && get(dir / dst) == want && (std::string(src) == dst || !lexists(dir / src));
    if (!ok) {
        std::fprintf(stderr, "%s: %s\n", name, ec.message().c_str());
        ++failures;
    }
}

}  // namespace

int main() {
    run_case("rename", "a.txt", "b.txt", "alpha\n", std::nullopt, "alpha\n");
    run_case("replace-existing", "a.txt", "b.txt", "alpha\n", "beta\n", "alpha\n");
    run_case("same-path", "a.txt", "a.txt", "alpha\n", "alpha\n", "alpha\n");
    run_case("empty-file", "a.txt", "b.txt", "", "beta\n", "");
    run_case("other-directory", "a.txt", "sub/a.txt", "alpha\n", std::nullopt, "alpha\n");
    run_case("name-with-spaces", "my notes.txt", "old notes.txt", "alpha\n", std::nullopt, "alpha\n");
    run_case("non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", std::nullopt, "alpha\n");

    fresh();
    std::error_code ec;
    rename_file(dir / "a.txt", dir / "b.txt", ec);
    expect(ec == std::errc::no_such_file_or_directory, "missing src");
    put(dir / "a.txt", "alpha\n");
    rename_file(dir / "a.txt", dir / "no-such-dir" / "b.txt", ec);
    expect(ec == std::errc::no_such_file_or_directory, "missing dst dir");
    fs::create_directory(dir / "dir");
    rename_file(dir / "a.txt", dir / "dir", ec);
    expect(bool(ec) && fs::is_directory(dir / "dir") && get(dir / "a.txt") == "alpha\n", "dst is a directory");

    fs::create_symlink("a.txt", dir / "link");
    rename_file(dir / "link", dir / "new-link", ec);
    expect(!ec && !lexists(dir / "link") && fs::read_symlink(dir / "new-link") == "a.txt", "link");

    put(dir / "b.txt", "beta\n");
    {
        std::ifstream old(dir / "b.txt", std::ios::binary);
        rename_file(dir / "a.txt", dir / "b.txt", ec);
        std::string data{std::istreambuf_iterator<char>(old), {}};
        expect(!ec && data == "beta\n", "open: old data is gone");
    }
    expect(get(dir / "b.txt") == "alpha\n", "open: dst is not the new file");

    struct stat shm{}, tmp{};
    if (stat("/dev/shm", &shm) == 0 && stat(dir.c_str(), &tmp) == 0 && shm.st_dev != tmp.st_dev) {
        fs::path dst = "/dev/shm/rename-file-" + std::to_string(getpid()) + ".txt";
        rename_file(dir / "b.txt", dst, ec);
        expect(ec == std::errc::cross_device_link && lexists(dir / "b.txt") && !lexists(dst), "cross device");
    }

    fs::remove_all(dir);
    if (failures == 0) std::puts("ok");
    return failures == 0 ? 0 : 1;
}
RenameFile.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public final class RenameFile {
  private RenameFile() {}

  /**
   * Gives the file at src the name dst, and replaces a file at dst.
   *
   * <p>ATOMIC_MOVE makes Files.move one rename call. With no ATOMIC_MOVE, Files.move copies the
   * file and deletes the source when the two paths are on different file systems, and a copy is
   * not atomic. With ATOMIC_MOVE, that case gives AtomicMoveNotSupportedException. On Unix the
   * rename replaces a file at dst.
   */
  public static void rename(Path src, Path dst) throws IOException {
    Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
  }
}
RenameFileTest.java 109 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class RenameFileTest {
  @TempDir Path dir;

  private static String text(String s) {
    return "EMPTY".equals(s) ? "" : s + "\n";
  }

  @ParameterizedTest(name = "{0}")
  @CsvSource(
      delimiter = '|',
      nullValues = "NULL",
      value = {
        "rename | a.txt | b.txt | alpha | NULL | alpha",
        "replace-existing | a.txt | b.txt | alpha | beta | alpha",
        "same-path | a.txt | a.txt | alpha | alpha | alpha",
        "empty-file | a.txt | b.txt | EMPTY | beta | EMPTY",
        "other-directory | a.txt | sub/a.txt | alpha | NULL | alpha",
        "name-with-spaces | my notes.txt | old notes.txt | alpha | NULL | alpha",
        "non-ascii-name | a.txt | café 日本.txt | alpha | NULL | alpha",
      })
  void cases(String name, String srcRel, String dstRel, String srcText, String dstText, String want)
      throws IOException {
    Path src = dir.resolve(srcRel);
    Path dst = dir.resolve(dstRel);
    Files.createDirectories(dst.getParent());
    if (dstText != null) {
      Files.writeString(dst, text(dstText));
    }
    Files.writeString(src, text(srcText));
    RenameFile.rename(src, dst);
    assertEquals(text(want), Files.readString(dst));
    assertTrue(src.equals(dst) || !Files.exists(src, LinkOption.NOFOLLOW_LINKS));
  }

  @Test
  void missingSrc() {
    assertThrows(NoSuchFileException.class, () -> RenameFile.rename(dir.resolve("a.txt"), dir.resolve("b.txt")));
  }

  @Test
  void missingDstDir() throws IOException {
    Path src = Files.writeString(dir.resolve("a.txt"), "alpha\n");
    assertThrows(NoSuchFileException.class, () -> RenameFile.rename(src, dir.resolve("no-such-dir/b.txt")));
    assertEquals("alpha\n", Files.readString(src));
  }

  @Test
  void dstIsADirectory() throws IOException {
    Path src = Files.writeString(dir.resolve("a.txt"), "alpha\n");
    Path sub = Files.createDirectory(dir.resolve("dir"));
    assertThrows(IOException.class, () -> RenameFile.rename(src, sub));
    assertTrue(Files.isDirectory(sub));
    assertEquals("alpha\n", Files.readString(src));
  }

  @Test
  void link() throws IOException {
    Files.writeString(dir.resolve("a.txt"), "alpha\n");
    Files.createSymbolicLink(dir.resolve("link"), Path.of("a.txt"));
    RenameFile.rename(dir.resolve("link"), dir.resolve("new-link"));
    assertEquals(Path.of("a.txt"), Files.readSymbolicLink(dir.resolve("new-link")));
    assertFalse(Files.exists(dir.resolve("link"), LinkOption.NOFOLLOW_LINKS));
  }

  @Test
  void openDstKeepsOldData() throws IOException {
    Path src = Files.writeString(dir.resolve("a.txt"), "alpha\n");
    Path dst = Files.writeString(dir.resolve("b.txt"), "beta\n");
    try (InputStream old = Files.newInputStream(dst)) {
      RenameFile.rename(src, dst);
      assertEquals("beta\n", new String(old.readAllBytes(), StandardCharsets.UTF_8));
    }
    assertEquals("alpha\n", Files.readString(dst));
  }

  @Test
  void crossDevice() throws IOException {
    Path shm = Path.of("/dev/shm");
    assumeTrue(Files.isDirectory(shm));
    assumeTrue(!Files.getFileStore(shm).equals(Files.getFileStore(dir)));
    Path src = Files.writeString(dir.resolve("a.txt"), "alpha\n");
    Path dst = shm.resolve("rename-file-" + ProcessHandle.current().pid() + ".txt");
    assertThrows(AtomicMoveNotSupportedException.class, () -> RenameFile.rename(src, dst));
    assertEquals("alpha\n", Files.readString(src));
    assertFalse(Files.exists(dst));
  }
}
rename_file.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

#include "rename_file.h"

#include <stdio.h>

// ISO C rename does not say what happens when dst exists. POSIX rename
// replaces dst atomically, and this code needs POSIX.
int rename_file(const char *src, const char *dst) {
    return rename(src, dst) == 0 ? 0 : -1;
}
rename_file.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

#ifndef RENAME_FILE_H
#define RENAME_FILE_H

// rename_file gives the file at src the name dst, and replaces a file at dst.
// It returns 0, or -1 with errno from rename, for example ENOENT, EISDIR, or
// EXDEV when the two paths are on different file systems.
int rename_file(const char *src, const char *dst);

#endif
test_rename_file.c 117 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

// symlink, readlink, lstat and getpid are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L

#include "rename_file.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

static const char *dir = "rename_file_tree";
static int failures = 0;

static char *at(char *buf, const char *name) {
    snprintf(buf, 256, "%s/%s", dir, name);
    return buf;
}

static void put(const char *name, const char *text) {
    char p[256];
    FILE *f = fopen(at(p, name), "w");
    if (f == NULL || fputs(text, f) < 0 || fclose(f) != 0) exit(2);
}

static const char *get(const char *name) {
    static char data[64];
    char p[256];
    FILE *f = fopen(at(p, name), "r");
    if (f == NULL) return "(none)";
    size_t n = fread(data, 1, sizeof data - 1, f);
    data[n] = '\0';
    fclose(f);
    return data;
}

static int lexists(const char *name) {
    char p[256];
    struct stat st;
    return lstat(at(p, name), &st) == 0;
}

static void expect(int ok, const char *what) {
    if (!ok) {
        fprintf(stderr, "%s\n", what);
        failures++;
    }
}

static void run_case(const char *name, const char *src, const char *dst, const char *src_text,
                     const char *dst_text, const char *want) {
    char s[256], d[256];
    if (system("rm -rf rename_file_tree") != 0 || mkdir(dir, 0755) != 0) exit(2);
    if (strchr(dst, '/') != NULL && mkdir(at(d, "sub"), 0755) != 0) exit(2);
    if (dst_text != NULL) put(dst, dst_text);
    put(src, src_text);
    if (rename_file(at(s, src), at(d, dst)) != 0 || strcmp(get(dst), want) != 0 ||
        (strcmp(src, dst) != 0 && lexists(src))) {
        fprintf(stderr, "%s: failed\n", name);
        failures++;
    }
}

int main(void) {
    // The cases of cases/basic.jsonl and cases/edge.jsonl.
    run_case("rename", "a.txt", "b.txt", "alpha\n", NULL, "alpha\n");
    run_case("replace-existing", "a.txt", "b.txt", "alpha\n", "beta\n", "alpha\n");
    run_case("same-path", "a.txt", "a.txt", "alpha\n", "alpha\n", "alpha\n");
    run_case("empty-file", "a.txt", "b.txt", "", "beta\n", "");
    run_case("other-directory", "a.txt", "sub/a.txt", "alpha\n", NULL, "alpha\n");
    run_case("name-with-spaces", "my notes.txt", "old notes.txt", "alpha\n", NULL, "alpha\n");
    run_case("non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", NULL, "alpha\n");

    char s[256], d[256];
    if (system("rm -rf rename_file_tree") != 0 || mkdir(dir, 0755) != 0) return 2;
    expect(rename_file(at(s, "a.txt"), at(d, "b.txt")) == -1 && errno == ENOENT, "missing src: no ENOENT");
    put("a.txt", "alpha\n");
    expect(rename_file(at(s, "a.txt"), at(d, "no-such-dir/b.txt")) == -1 && errno == ENOENT,
           "missing dst dir: no ENOENT");
    if (mkdir(at(d, "dir"), 0755) != 0) return 2;
    expect(rename_file(at(s, "a.txt"), at(d, "dir")) == -1 && errno == EISDIR, "dst is a directory: no EISDIR");
    expect(strcmp(get("a.txt"), "alpha\n") == 0, "errors: src is changed");

    // A link is renamed, not its target.
    if (symlink("a.txt", at(s, "link")) != 0) return 2;
    expect(rename_file(at(s, "link"), at(d, "new-link")) == 0 && !lexists("link"), "link: not renamed");
    char target[64] = {0};
    expect(readlink(at(d, "new-link"), target, sizeof target - 1) == 5 && strcmp(target, "a.txt") == 0,
           "link: wrong target");

    // A program that has the old dst open still reads the old data.
    put("b.txt", "beta\n");
    FILE *old = fopen(at(d, "b.txt"), "r");
    if (old == NULL) return 2;
    expect(rename_file(at(s, "a.txt"), at(d, "b.txt")) == 0, "open: rename failed");
    char buf[16] = {0};
    expect(fgets(buf, sizeof buf, old) != NULL && strcmp(buf, "beta\n") == 0, "open: old data is gone");
    fclose(old);
    expect(strcmp(get("b.txt"), "alpha\n") == 0, "open: dst is not the new file");

    // On Linux, /dev/shm is often another file system.
    struct stat shm, tmp;
    if (stat("/dev/shm", &shm) == 0 && stat(dir, &tmp) == 0 && shm.st_dev != tmp.st_dev) {
        char dst[64];
        snprintf(dst, sizeof dst, "/dev/shm/rename-file-%ld.txt", (long)getpid());
        expect(rename_file(at(s, "b.txt"), dst) == -1 && errno == EXDEV, "cross device: no EXDEV");
        expect(lexists("b.txt") && access(dst, F_OK) != 0, "cross device: a file is changed");
    }

    if (system("rm -rf rename_file_tree") != 0) return 2;
    if (failures == 0) printf("ok\n");
    return failures == 0 ? 0 : 1;
}
renameFile.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

import { rename } from "node:fs/promises";

/**
 * Gives the file at src the name dst, and replaces a file at dst. rename is
 * one call of the operating system, so it is atomic. Across file systems it
 * fails with EXDEV and does not copy. Each error is thrown.
 */
export async function renameFile(src, dst) {
  await rename(src, dst);
}
renameFile.test.js 110 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync, statSync } from "node:fs";
import { mkdir, mkdtemp, open, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { renameFile } from "./renameFile.js";

async function withDir(fn) {
  const dir = await mkdtemp(join(tmpdir(), "rename-file-"));
  try {
    await fn(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

function lexists(path) {
  try {
    lstatSync(path);
    return true;
  } catch {
    return false;
  }
}

// name: [src, dst, content of src, content of dst or null, content of dst after]
const cases = {
  rename: ["a.txt", "b.txt", "alpha\n", null, "alpha\n"],
  "replace-existing": ["a.txt", "b.txt", "alpha\n", "beta\n", "alpha\n"],
  "same-path": ["a.txt", "a.txt", "alpha\n", "alpha\n", "alpha\n"],
  "empty-file": ["a.txt", "b.txt", "", "beta\n", ""],
  "other-directory": ["a.txt", "sub/a.txt", "alpha\n", null, "alpha\n"],
  "name-with-spaces": ["my notes.txt", "old notes.txt", "alpha\n", null, "alpha\n"],
  "non-ascii-name": ["a.txt", "café 日本.txt", "alpha\n", null, "alpha\n"],
};

for (const [name, [srcRel, dstRel, srcContent, dstContent, want]] of Object.entries(cases)) {
  test(name, () =>
    withDir(async (dir) => {
      const src = join(dir, srcRel);
      const dst = join(dir, dstRel);
      await mkdir(dirname(dst), { recursive: true });
      if (dstContent !== null) await writeFile(dst, dstContent);
      await writeFile(src, srcContent);
      await renameFile(src, dst);
      assert.equal(await readFile(dst, "utf8"), want);
      assert.equal(src === dst || !lexists(src), true);
    }));
}

test("missing src", () =>
  withDir(async (dir) => {
    await assert.rejects(renameFile(join(dir, "a.txt"), join(dir, "b.txt")), { code: "ENOENT" });
  }));

test("missing dst dir", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await assert.rejects(renameFile(join(dir, "a.txt"), join(dir, "no-such-dir", "b.txt")), { code: "ENOENT" });
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
  }));

test("dst is a directory", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await mkdir(join(dir, "dir"));
    await assert.rejects(renameFile(join(dir, "a.txt"), join(dir, "dir")));
    assert.equal(lstatSync(join(dir, "dir")).isDirectory(), true);
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
  }));

test("link", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await symlink("a.txt", join(dir, "link"));
    await renameFile(join(dir, "link"), join(dir, "new-link"));
    assert.equal(await readlink(join(dir, "new-link")), "a.txt");
    assert.equal(lexists(join(dir, "link")), false);
  }));

test("an open dst keeps the old data", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await writeFile(join(dir, "b.txt"), "beta\n");
    const old = await open(join(dir, "b.txt"));
    try {
      await renameFile(join(dir, "a.txt"), join(dir, "b.txt"));
      assert.equal(await old.readFile("utf8"), "beta\n");
    } finally {
      await old.close();
    }
    assert.equal(await readFile(join(dir, "b.txt"), "utf8"), "alpha\n");
  }));

test("cross device", (t) =>
  withDir(async (dir) => {
    if (!existsSync("/dev/shm") || statSync("/dev/shm").dev === statSync(dir).dev) {
      t.skip("no other file system at /dev/shm");
      return;
    }
    await writeFile(join(dir, "a.txt"), "alpha\n");
    const dst = join("/dev/shm", `rename-file-${process.pid}.txt`);
    await assert.rejects(renameFile(join(dir, "a.txt"), dst), { code: "EXDEV" });
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
    assert.equal(existsSync(dst), false);
  }));
renameFile.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

import { rename } from "node:fs/promises";

/**
 * Gives the file at src the name dst, and replaces a file at dst. rename is
 * one call of the operating system, so it is atomic. Across file systems it
 * fails with EXDEV and does not copy. Each error is thrown.
 */
export async function renameFile(src: string, dst: string): Promise<void> {
  await rename(src, dst);
}
renameFile.test.ts 110 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync, statSync } from "node:fs";
import { mkdir, mkdtemp, open, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { renameFile } from "./renameFile.ts";

async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
  const dir = await mkdtemp(join(tmpdir(), "rename-file-"));
  try {
    await fn(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

function lexists(path: string): boolean {
  try {
    lstatSync(path);
    return true;
  } catch {
    return false;
  }
}

// name: [src, dst, content of src, content of dst or null, content of dst after]
const cases: Record<string, [string, string, string, string | null, string]> = {
  rename: ["a.txt", "b.txt", "alpha\n", null, "alpha\n"],
  "replace-existing": ["a.txt", "b.txt", "alpha\n", "beta\n", "alpha\n"],
  "same-path": ["a.txt", "a.txt", "alpha\n", "alpha\n", "alpha\n"],
  "empty-file": ["a.txt", "b.txt", "", "beta\n", ""],
  "other-directory": ["a.txt", "sub/a.txt", "alpha\n", null, "alpha\n"],
  "name-with-spaces": ["my notes.txt", "old notes.txt", "alpha\n", null, "alpha\n"],
  "non-ascii-name": ["a.txt", "café 日本.txt", "alpha\n", null, "alpha\n"],
};

for (const [name, [srcRel, dstRel, srcContent, dstContent, want]] of Object.entries(cases)) {
  test(name, () =>
    withDir(async (dir) => {
      const src = join(dir, srcRel);
      const dst = join(dir, dstRel);
      await mkdir(dirname(dst), { recursive: true });
      if (dstContent !== null) await writeFile(dst, dstContent);
      await writeFile(src, srcContent);
      await renameFile(src, dst);
      assert.equal(await readFile(dst, "utf8"), want);
      assert.equal(src === dst || !lexists(src), true);
    }));
}

test("missing src", () =>
  withDir(async (dir) => {
    await assert.rejects(renameFile(join(dir, "a.txt"), join(dir, "b.txt")), { code: "ENOENT" });
  }));

test("missing dst dir", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await assert.rejects(renameFile(join(dir, "a.txt"), join(dir, "no-such-dir", "b.txt")), { code: "ENOENT" });
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
  }));

test("dst is a directory", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await mkdir(join(dir, "dir"));
    await assert.rejects(renameFile(join(dir, "a.txt"), join(dir, "dir")));
    assert.equal(lstatSync(join(dir, "dir")).isDirectory(), true);
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
  }));

test("link", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await symlink("a.txt", join(dir, "link"));
    await renameFile(join(dir, "link"), join(dir, "new-link"));
    assert.equal(await readlink(join(dir, "new-link")), "a.txt");
    assert.equal(lexists(join(dir, "link")), false);
  }));

test("an open dst keeps the old data", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await writeFile(join(dir, "b.txt"), "beta\n");
    const old = await open(join(dir, "b.txt"));
    try {
      await renameFile(join(dir, "a.txt"), join(dir, "b.txt"));
      assert.equal(await old.readFile("utf8"), "beta\n");
    } finally {
      await old.close();
    }
    assert.equal(await readFile(join(dir, "b.txt"), "utf8"), "alpha\n");
  }));

test("cross device", (t) =>
  withDir(async (dir) => {
    if (!existsSync("/dev/shm") || statSync("/dev/shm").dev === statSync(dir).dev) {
      t.skip("no other file system at /dev/shm");
      return;
    }
    await writeFile(join(dir, "a.txt"), "alpha\n");
    const dst = join("/dev/shm", `rename-file-${process.pid}.txt`);
    await assert.rejects(renameFile(join(dir, "a.txt"), dst), { code: "EXDEV" });
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
    assert.equal(existsSync(dst), false);
  }));
rename_file.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

// Package renamefile gives a file a new name with one atomic rename call.
package renamefile

import "os"

// RenameFile gives the file at src the name dst, and replaces a file at dst.
// os.Rename is one rename call, so it is atomic. Across file systems it gives
// a *os.LinkError with syscall.EXDEV and does not copy.
func RenameFile(src, dst string) error {
	return os.Rename(src, dst)
}
rename_file_test.go 150 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

package renamefile

import (
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"syscall"
	"testing"
)

func must(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

func read(t *testing.T, path string) string {
	t.Helper()
	b, err := os.ReadFile(path)
	must(t, err)
	return string(b)
}

func lexists(path string) bool {
	_, err := os.Lstat(path)
	return err == nil
}

func ptr(s string) *string { return &s }

func TestCases(t *testing.T) {
	cases := []struct {
		name, src, dst, srcText string
		dstText                 *string
		want                    string
	}{
		{"rename", "a.txt", "b.txt", "alpha\n", nil, "alpha\n"},
		{"replace-existing", "a.txt", "b.txt", "alpha\n", ptr("beta\n"), "alpha\n"},
		{"same-path", "a.txt", "a.txt", "alpha\n", ptr("alpha\n"), "alpha\n"},
		{"empty-file", "a.txt", "b.txt", "", ptr("beta\n"), ""},
		{"other-directory", "a.txt", "sub/a.txt", "alpha\n", nil, "alpha\n"},
		{"name-with-spaces", "my notes.txt", "old notes.txt", "alpha\n", nil, "alpha\n"},
		{"non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", nil, "alpha\n"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			dir := t.TempDir()
			src, dst := filepath.Join(dir, c.src), filepath.Join(dir, c.dst)
			must(t, os.MkdirAll(filepath.Dir(dst), 0o755))
			if c.dstText != nil {
				must(t, os.WriteFile(dst, []byte(*c.dstText), 0o644))
			}
			must(t, os.WriteFile(src, []byte(c.srcText), 0o644))
			must(t, RenameFile(src, dst))
			if got := read(t, dst); got != c.want {
				t.Fatalf("dst = %q, want %q", got, c.want)
			}
			if src != dst && lexists(src) {
				t.Fatal("src is still there")
			}
		})
	}
}

func TestMissingSrc(t *testing.T) {
	dir := t.TempDir()
	if err := RenameFile(filepath.Join(dir, "a.txt"), filepath.Join(dir, "b.txt")); !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("err = %v", err)
	}
}

func TestMissingDstDir(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "a.txt")
	must(t, os.WriteFile(src, []byte("alpha\n"), 0o644))
	if err := RenameFile(src, filepath.Join(dir, "no-such-dir", "b.txt")); !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("err = %v", err)
	}
	if read(t, src) != "alpha\n" {
		t.Fatal("src is changed")
	}
}

func TestDstIsADirectory(t *testing.T) {
	dir := t.TempDir()
	src, sub := filepath.Join(dir, "a.txt"), filepath.Join(dir, "dir")
	must(t, os.WriteFile(src, []byte("alpha\n"), 0o644))
	must(t, os.Mkdir(sub, 0o755))
	if err := RenameFile(src, sub); err == nil {
		t.Fatal("no error")
	}
	if info, err := os.Lstat(sub); err != nil || !info.IsDir() || read(t, src) != "alpha\n" {
		t.Fatal("a file is changed")
	}
}

func TestLink(t *testing.T) {
	dir := t.TempDir()
	must(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("alpha\n"), 0o644))
	must(t, os.Symlink("a.txt", filepath.Join(dir, "link")))
	must(t, RenameFile(filepath.Join(dir, "link"), filepath.Join(dir, "new-link")))
	if target, err := os.Readlink(filepath.Join(dir, "new-link")); err != nil || target != "a.txt" {
		t.Fatalf("target = %q, %v", target, err)
	}
	if lexists(filepath.Join(dir, "link")) {
		t.Fatal("the old link is still there")
	}
}

func TestOpenDstKeepsOldData(t *testing.T) {
	dir := t.TempDir()
	src, dst := filepath.Join(dir, "a.txt"), filepath.Join(dir, "b.txt")
	must(t, os.WriteFile(src, []byte("alpha\n"), 0o644))
	must(t, os.WriteFile(dst, []byte("beta\n"), 0o644))
	old, err := os.Open(dst)
	must(t, err)
	defer old.Close()
	must(t, RenameFile(src, dst))
	if b, _ := io.ReadAll(old); string(b) != "beta\n" {
		t.Fatalf("old = %q", b)
	}
	if read(t, dst) != "alpha\n" {
		t.Fatal("dst is not the new file")
	}
}

func TestCrossDevice(t *testing.T) {
	dir := t.TempDir()
	shm, err1 := os.Stat("/dev/shm")
	tmp, err2 := os.Stat(dir)
	if err1 != nil || err2 != nil || shm.Sys().(*syscall.Stat_t).Dev == tmp.Sys().(*syscall.Stat_t).Dev {
		t.Skip("no other file system at /dev/shm")
	}
	src := filepath.Join(dir, "a.txt")
	must(t, os.WriteFile(src, []byte("alpha\n"), 0o644))
	dst := fmt.Sprintf("/dev/shm/rename-file-%d.txt", os.Getpid())
	if err := RenameFile(src, dst); !errors.Is(err, syscall.EXDEV) {
		t.Fatalf("err = %v", err)
	}
	if read(t, src) != "alpha\n" || lexists(dst) {
		t.Fatal("a file is changed")
	}
}
rename_file.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

use std::fs;
use std::io;
use std::path::Path;

/// Gives the file at `src` the name `dst`, and replaces a file at `dst`.
/// `fs::rename` is one rename call, so it is atomic. Across file systems it
/// gives an error of kind `ErrorKind::CrossesDevices` and does not copy.
pub fn rename_file(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
    fs::rename(src, dst)
}
tests/rename_file_test.rs 108 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rename-a-file/.

use std::fs;
use std::io::{ErrorKind, Read};
use std::os::unix::fs::{symlink, MetadataExt};
use std::path::{Path, PathBuf};

use algo_rename_a_file::rename_file;

/// Returns a new, empty directory for one test.
fn new_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("rename-file-{}-{name}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

fn lexists(path: &Path) -> bool {
    fs::symlink_metadata(path).is_ok()
}

#[test]
fn cases() {
    for (name, src, dst, src_text, dst_text, want) in [
        ("rename", "a.txt", "b.txt", "alpha\n", None, "alpha\n"),
        ("replace-existing", "a.txt", "b.txt", "alpha\n", Some("beta\n"), "alpha\n"),
        ("same-path", "a.txt", "a.txt", "alpha\n", Some("alpha\n"), "alpha\n"),
        ("empty-file", "a.txt", "b.txt", "", Some("beta\n"), ""),
        ("other-directory", "a.txt", "sub/a.txt", "alpha\n", None, "alpha\n"),
        ("name-with-spaces", "my notes.txt", "old notes.txt", "alpha\n", None, "alpha\n"),
        ("non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", None, "alpha\n"),
    ] {
        let dir = new_dir(name);
        let (src, dst) = (dir.join(src), dir.join(dst));
        fs::create_dir_all(dst.parent().unwrap()).unwrap();
        if let Some(t) = dst_text {
            fs::write(&dst, t).unwrap();
        }
        fs::write(&src, src_text).unwrap();
        rename_file(&src, &dst).unwrap();
        assert_eq!(fs::read_to_string(&dst).unwrap(), want, "{name}");
        assert!(src == dst || !lexists(&src), "{name}");
        fs::remove_dir_all(&dir).unwrap();
    }
}

#[test]
fn errors() {
    let dir = new_dir("errors");
    let src = dir.join("a.txt");
    let err = rename_file(&src, dir.join("b.txt")).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
    fs::write(&src, "alpha\n").unwrap();
    let err = rename_file(&src, dir.join("no-such-dir/b.txt")).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
    fs::create_dir(dir.join("dir")).unwrap();
    assert!(rename_file(&src, dir.join("dir")).is_err());
    assert!(dir.join("dir").is_dir());
    assert_eq!(fs::read_to_string(&src).unwrap(), "alpha\n");
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn link() {
    let dir = new_dir("link");
    fs::write(dir.join("a.txt"), "alpha\n").unwrap();
    symlink("a.txt", dir.join("link")).unwrap();
    rename_file(dir.join("link"), dir.join("new-link")).unwrap();
    assert_eq!(fs::read_link(dir.join("new-link")).unwrap(), Path::new("a.txt"));
    assert!(!lexists(&dir.join("link")));
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn open_dst_keeps_old_data() {
    let dir = new_dir("open");
    let (src, dst) = (dir.join("a.txt"), dir.join("b.txt"));
    fs::write(&src, "alpha\n").unwrap();
    fs::write(&dst, "beta\n").unwrap();
    let mut old = fs::File::open(&dst).unwrap();
    rename_file(&src, &dst).unwrap();
    let mut s = String::new();
    old.read_to_string(&mut s).unwrap();
    assert_eq!(s, "beta\n");
    assert_eq!(fs::read_to_string(&dst).unwrap(), "alpha\n");
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn cross_device() {
    let dir = new_dir("cross");
    let shm = Path::new("/dev/shm");
    let other = match (fs::metadata(shm), fs::metadata(&dir)) {
        (Ok(a), Ok(b)) => a.is_dir() && a.dev() != b.dev(),
        _ => false,
    };
    if other {
        let src = dir.join("a.txt");
        fs::write(&src, "alpha\n").unwrap();
        let dst = shm.join(format!("rename-file-{}.txt", std::process::id()));
        let err = rename_file(&src, &dst).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::CrossesDevices);
        assert_eq!(fs::read_to_string(&src).unwrap(), "alpha\n");
        assert!(!lexists(&dst));
    }
    fs::remove_dir_all(&dir).unwrap();
}
rename_file.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rename-a-file/.

# rename_file SRC DST
# Gives the file at SRC the name DST, and replaces a file at DST. mv is a
# rename call when the two paths are on one file system, but mv copies the
# file and deletes SRC when they are not, and a copy is not atomic. So the
# function compares the file systems of the two directories, with df -P, and
# returns status 1 if they are not the same. mv also moves SRC into DST when
# DST is a directory, so the function returns status 1 for a directory at
# DST. -f stops a prompt for a DST that is read-only. -- stops options, so a
# name that starts with - is a file name. If SRC and DST name the same file,
# rename does nothing, but mv gives an error, so the function returns 0.
rename_file() {
  local _fs
  [[ $1 -ef $2 && ! -L $1 && ! -L $2 ]] && return 0
  if [[ -d $2 && ! -L $2 ]]; then
    printf 'rename_file: %s: is a directory\n' "$2" >&2
    return 1
  fi
  if _fs=$(df -P -- "$(dirname -- "$1")" "$(dirname -- "$2")" 2>/dev/null); then
    if [[ $(awk 'NR == 2 { a = $NF } NR == 3 { b = $NF } END { print (a == b) }' <<<"$_fs") != 1 ]]; then
      printf 'rename_file: %s and %s are on different file systems\n' "$1" "$2" >&2
      return 1
    fi
  fi
  mv -f -- "$1" "$2"
}
test_rename_file.bats 104 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rename-a-file/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/rename_file.sh"
  dir=$BATS_TEST_TMPDIR
}

lexists() { [[ -e $1 || -L $1 ]]; }

@test "rename" {
  printf 'alpha\n' >"$dir/a.txt"
  rename_file "$dir/a.txt" "$dir/b.txt"
  [ "$(cat "$dir/b.txt")" = alpha ]
  ! lexists "$dir/a.txt"
}

@test "replace existing" {
  printf 'alpha\n' >"$dir/a.txt"
  printf 'beta\n' >"$dir/b.txt"
  rename_file "$dir/a.txt" "$dir/b.txt"
  [ "$(cat "$dir/b.txt")" = alpha ]
  ! lexists "$dir/a.txt"
}

@test "same path" {
  printf 'alpha\n' >"$dir/a.txt"
  rename_file "$dir/a.txt" "$dir/a.txt"
  [ "$(cat "$dir/a.txt")" = alpha ]
}

@test "empty file" {
  : >"$dir/a.txt"
  printf 'beta\n' >"$dir/b.txt"
  rename_file "$dir/a.txt" "$dir/b.txt"
  [ ! -s "$dir/b.txt" ]
}

@test "other directory" {
  mkdir "$dir/sub"
  printf 'alpha\n' >"$dir/a.txt"
  rename_file "$dir/a.txt" "$dir/sub/a.txt"
  [ "$(cat "$dir/sub/a.txt")" = alpha ]
  ! lexists "$dir/a.txt"
}

@test "names with spaces, non-ASCII and a dash" {
  printf 'alpha\n' >"$dir/my notes.txt"
  rename_file "$dir/my notes.txt" "$dir/café 日本.txt"
  [ "$(cat "$dir/café 日本.txt")" = alpha ]
  cd "$dir"
  rename_file "café 日本.txt" -n
  [ "$(cat -- -n)" = alpha ]
}

@test "read-only dst" {
  printf 'alpha\n' >"$dir/a.txt"
  printf 'beta\n' >"$dir/b.txt"
  chmod 444 "$dir/b.txt"
  rename_file "$dir/a.txt" "$dir/b.txt" </dev/null
  [ "$(cat "$dir/b.txt")" = alpha ]
}

@test "errors" {
  run ! rename_file "$dir/a.txt" "$dir/b.txt"
  printf 'alpha\n' >"$dir/a.txt"
  run ! rename_file "$dir/a.txt" "$dir/no-such-dir/b.txt"
  mkdir "$dir/dir"
  run -1 rename_file "$dir/a.txt" "$dir/dir"
  [ -z "$(ls "$dir/dir")" ]
  [ "$(cat "$dir/a.txt")" = alpha ]
}

@test "link" {
  printf 'alpha\n' >"$dir/a.txt"
  ln -s a.txt "$dir/link"
  rename_file "$dir/link" "$dir/new-link"
  [ -L "$dir/new-link" ]
  ! lexists "$dir/link"
  [ "$(cat "$dir/new-link")" = alpha ]
}

@test "an open dst keeps the old data" {
  printf 'alpha\n' >"$dir/a.txt"
  printf 'beta\n' >"$dir/b.txt"
  exec 3<"$dir/b.txt"
  rename_file "$dir/a.txt" "$dir/b.txt"
  [ "$(cat <&3)" = beta ]
  exec 3<&-
  [ "$(cat "$dir/b.txt")" = alpha ]
}

@test "cross device" {
  [ -d /dev/shm ] || skip "no /dev/shm"
  [ "$(df -P /dev/shm | awk 'NR == 2 { print $NF }')" != "$(df -P "$dir" | awk 'NR == 2 { print $NF }')" ] ||
    skip "/dev/shm is on the same file system"
  printf 'alpha\n' >"$dir/a.txt"
  run -1 rename_file "$dir/a.txt" "/dev/shm/rename-file-$$.txt"
  [ -f "$dir/a.txt" ]
  [ ! -e "/dev/shm/rename-file-$$.txt" ]
}

References

  1. The Python Standard Library, os, Miscellaneous operating system interfaces, os.rename, os.replace, os.fsync
  2. The Python Standard Library, shutil, High-level file operations, shutil.move
  3. Node.js documentation, File system, fsPromises.rename(oldPath, newPath), fs.rename(oldPath, newPath, callback)
  4. Java SE 25 API, Files, move(Path, Path, CopyOption...), ATOMIC_MOVE
  5. .NET API reference, File.Move Method, Remarks
  6. Go standard library, package os, func Rename
  7. The Rust Standard Library, std::fs::rename, Platform-specific behavior
  8. The Open Group Base Specifications Issue 8 (POSIX.1-2024), rename, renameat, DESCRIPTION, ERRORS (EXDEV)
  9. The Open Group Base Specifications Issue 8 (POSIX.1-2024), mv, DESCRIPTION, RATIONALE
  10. The Open Group Base Specifications Issue 8 (POSIX.1-2024), df, OPTIONS (-P)
  11. Linux manual page, rename(2), DESCRIPTION, RENAME_NOREPLACE, ERRORS (EXDEV)
  12. Linux manual page, fsync(2), DESCRIPTION
  13. cppreference, std::filesystem::rename, Description
  14. cppreference, rename (C), Description
  15. Windows API reference, MoveFileExW function (winbase.h), MOVEFILE_REPLACE_EXISTING, MOVEFILE_COPY_ALLOWED

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source