Programming Search⌘K

Taskcore

Set file permissions

Also called chmod, change file mode, change file permissions, set file mode.

Set the mode of a file from three or four octal digits, as the chmod command does, and return the new permission bits, with the set-user-ID, set-group-ID and sticky bits.

Task

Set the mode of the file at path to mode, and return the new permission bits of the file as an integer. mode is a string of three or four octal digits, as for the chmod command: 640 is read and write for the owner, read for the group, and nothing for others. The fourth digit, at the left, holds the set-user-ID (4), set-group-ID (2) and sticky (1) bits, so 4755 sets the set-user-ID bit. The result is st_mode & 07777, so 640 gives 416, that is 0o640. Report an error for a mode that is not three or four octal digits, and for a missing file.

An octal mode replaces the whole mode. The POSIX chmod utility says: "For an octal integer mode operand, the file mode bits shall be set absolutely. For each bit set in the octal number, the corresponding file permission bit shown in the following table shall be set; all other file permission bits shall be cleared." The values of the bits are in sys/stat.h: "S_ISUID 04000 Set-user-ID on execution. S_ISGID 02000 Set-group-ID on execution."

The chmod command also takes symbolic modes, such as u+x. This task takes only octal digits, and a symbolic mode is an error. The page File permissions tells what each bit means.

SQL, regular expressions, HTML and CSS do not apply, because they do not change files. On Windows, a file has no Unix mode. The solutions are for Linux and macOS.

Solutions

Each solution checks the mode first, then converts it from base 8, sets it, and reads the mode back. The check must match the whole string, so 640 followed by a newline is an error. Each call follows a symbolic link, so a link changes the mode of its target.

  • Python. os.chmod(path, int(mode, 8)). It does: "Change the mode of path to the numeric mode." The code checks the mode with re.fullmatch. The result is stat.S_IMODE(os.stat(path).st_mode). S_IMODE returns "the portion of the file's mode that can be set by os.chmod()".
  • JavaScript and TypeScript (Node.js). await chmod(path, parseInt(mode, 8)) from node:fs/promises, and then (await stat(path)).mode & 0o7777. The function "Asynchronously changes the permissions of a file." The Node documentation says: "An easier method of constructing the mode is to use a sequence of three octal digits (e.g. 765 )."
  • Java. PosixFilePermission "Defines the bits for use with the permissions attribute", but it has only the nine bits of read, write and execute. It has no set-user-ID bit. So the code uses Files.setAttribute(path, "unix:mode", Integer.parseInt(mode, 8)). The Files documentation shows the unix view only in an example, Files.getAttribute(path, "unix:uid"), and it does not list the attributes of the view. The native tests show that unix:mode works on Linux and macOS.
  • C#. File.SetUnixFileMode(path, (UnixFileMode)Convert.ToInt32(mode, 8)). It "Sets the specified UnixFileMode of the file on the specified path." The values of UnixFileMode are the Unix bits, so the number casts to the enum. The call is not for Windows, so the class has [UnsupportedOSPlatform("windows")]. In .NET, the pattern ^[0-7]{3,4}$ matches 640 with a newline after it, so the code checks each character. A missing file gives FileNotFoundException: "The file cannot be found."
  • Go. os.Chmod(path, m). "Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target." A Go FileMode does not use the Unix values for the three special bits. See the pitfalls. So the code maps 0o4000, 0o2000 and 0o1000 to fs.ModeSetuid, fs.ModeSetgid and fs.ModeSticky, and back.
  • Rust. fs::set_permissions(path, Permissions::from_mode(m)). from_mode "Creates a new instance from the given mode permission bits." It is in the trait std::os::unix::fs::PermissionsExt, which is "Available on Unix only." set_permissions "currently corresponds to the chmod function on Unix".
  • C. POSIX chmod(path, m). ISO C has no call that changes the mode of a file. The code reads each digit itself, because strtol also takes a sign and spaces. A missing file gives ENOENT: "A component of path does not name an existing file or path is an empty string."
  • C++. std::filesystem::permissions(path, perms(m), perm_options::replace, ec). It "Changes access permissions of the file to which p resolves, as if by POSIX fchmodat." With replace, "file permissions are set to exactly prms & std :: filesystem :: perms :: mask".
  • Bash. chmod -- "$mode" "$path". The chmod command takes symbolic modes too, so the function checks the mode first with [[ $mode =~ ^[0-7]{3,4}$ ]]. Then it reads the mode back with stat -L -c %a (GNU), or with stat -L -f %Mp%Lp (macOS).

Edge cases

The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/errors.jsonl. Each test makes the file in a new temporary directory with the mode 0644, sets the mode, and checks the result and the mode of the file.

  • owner-read-write-group-read, owner-only, executable and same-mode: 640, 600, 755 and 644 give 416, 384, 493 and 420.
  • no-permissions: 000 gives 0. The owner can still change the mode again, but cannot read the file. The tests reset the modes before they delete the directory.
  • leading-zero: 0640 gives 416, the same as 640.
  • set-user-id: 4755 gives 2541, that is 0o4755.
  • name-with-spaces and non-ascii-name: my notes.txt and café 日本.txt. A shell solution must quote the name.
  • Errors: a missing file gives not-found. 648 (8 is not an octal digit), 64 and 10640 (two and five digits), u+x (a symbolic mode), the empty string, and 640 with a newline give invalid-mode.

The native tests also check that a symbolic link changes the mode of its target, that a directory takes the mode 700, that an invalid mode does not change the file, and that the umask does not change the result: with the umask 077, the mode 666 gives 0o666.

Pitfalls

  • A decimal number is not a mode. In Python, C and Go, a mode is an integer, and 400 without the 0o or 0 prefix is a decimal number. Decimal 400 is 0o620, so the owner cannot read the file, and the group can write to it:

This code runs but gives a wrong answer on purpose.

import os
import stat
import tempfile

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "a.txt")
    open(path, "w").close()
    os.chmod(path, 400)  # decimal, not 0o400
    print(oct(stat.S_IMODE(os.stat(path).st_mode)))
Output
0o620
  • A mode replaces all the bits. To add one bit, read the mode first. os.chmod(path, stat.S_IXUSR) does not add the execute bit for the owner. It removes all the other bits:

This code runs but gives a wrong answer on purpose.

import os
import stat
import tempfile

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "run.sh")
    open(path, "w").close()
    os.chmod(path, 0o644)
    os.chmod(path, stat.S_IXUSR)
    print(oct(stat.S_IMODE(os.stat(path).st_mode)))
Output
0o100

Use the bitwise OR of the old mode and the new bit:

import os
import stat
import tempfile

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "run.sh")
    open(path, "w").close()
    os.chmod(path, 0o644)
    old = stat.S_IMODE(os.stat(path).st_mode)
    os.chmod(path, old | stat.S_IXUSR)
    print(oct(stat.S_IMODE(os.stat(path).st_mode)))
Output
0o744
  • The special bits of Go are not the Unix bits. Go says: "A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems". So ModeSetuid is a high bit of the uint32, not 0o4000, and os.Chmod drops 0o4000 with no error:

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"os"
	"path/filepath"
	"syscall"
)

func main() {
	dir, err := os.MkdirTemp("", "chmod")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "tool")
	if err := os.WriteFile(path, []byte("#!/bin/sh\n"), 0o644); err != nil {
		panic(err)
	}
	if err := os.Chmod(path, 0o4755); err != nil { // the Unix value of set-user-ID
		panic(err)
	}
	var st syscall.Stat_t
	if err := syscall.Stat(path, &st); err != nil {
		panic(err)
	}
	fmt.Printf("asked for 4755, got %o\n", st.Mode&0o7777)
}
Output
asked for 4755, got 755

Use 0o755 | fs.ModeSetuid, as the Go solution does.

  • The system can ignore the special bits. POSIX says that "Additional implementation-defined restrictions may cause the S_ISUID and S_ISGID bits in mode to be ignored". For a file whose group is not a group of the process, it clears the set-group-ID bit: "bit S_ISGID (set-group-ID on execution) in the file's mode shall be cleared upon successful return from chmod ()." Linux adds: "the S_ISGID bit will be turned off, but this will not cause an error to be returned." So read the mode back, as each solution does, and do not assume that the call set all the bits.

  • A symbolic link changes its target. Each call in the solutions follows a link. Rust warns: "Note that this behavior can lead to privilege escalation vulnerabilities". A program that changes the mode of files in a directory that other users can write to must not follow links.

  • The umask does not apply to an octal mode. The umask clears bits when a program makes a file, but an octal mode sets the bits "absolutely". The chmod utility uses the umask only for a symbolic mode with no who part: systems "do so when who is not specified."

Code

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

set_mode.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/set-file-permissions/.

import os
import re
import stat

_MODE = re.compile(r"[0-7]{3,4}")


def set_mode(path: str | os.PathLike, mode: str) -> int:
    """Sets the mode of the file at path, and returns the new permission bits.

    mode is three or four octal digits, as for the chmod command. re.fullmatch
    checks the whole string, so "640\n" is not valid. os.chmod follows a
    symbolic link and sets the mode as it is: the umask does not apply. The
    result is read back with os.stat, because the system can ignore some bits.
    """
    if not isinstance(mode, str) or not _MODE.fullmatch(mode):
        raise ValueError(f"invalid mode: {mode!r}")
    os.chmod(path, int(mode, 8))
    return stat.S_IMODE(os.stat(path).st_mode)
test_set_mode.py 71 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/set-file-permissions/.

import os
from pathlib import Path

import pytest

from set_mode import set_mode

# name: (path, mode, result)
CASES = {
    "owner-read-write-group-read": ("a.txt", "640", 0o640),
    "owner-only": ("a.txt", "600", 0o600),
    "executable": ("a.txt", "755", 0o755),
    "same-mode": ("a.txt", "644", 0o644),
    "no-permissions": ("a.txt", "000", 0),
    "leading-zero": ("a.txt", "0640", 0o640),
    "set-user-id": ("a.txt", "4755", 0o4755),
    "name-with-spaces": ("my notes.txt", "640", 0o640),
    "non-ascii-name": ("café 日本.txt", "640", 0o640),
}


def new_file(path: Path) -> Path:
    path.write_bytes(b"alpha\n")
    os.chmod(path, 0o644)
    return path


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    rel, mode, result = CASES[name]
    path = new_file(tmp_path / rel)
    assert set_mode(path, mode) == result
    assert os.stat(path).st_mode & 0o7777 == result
    assert result == 0 or path.read_bytes() == b"alpha\n"


@pytest.mark.parametrize("mode", ["648", "64", "10640", "u+x", "", "640\n"])
def test_invalid_mode(tmp_path: Path, mode: str) -> None:
    path = new_file(tmp_path / "a.txt")
    with pytest.raises(ValueError):
        set_mode(path, mode)
    assert os.stat(path).st_mode & 0o7777 == 0o644


def test_missing(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        set_mode(tmp_path / "missing.txt", "640")


def test_symbolic_link_changes_target(tmp_path: Path) -> None:
    target = new_file(tmp_path / "a.txt")
    os.symlink("a.txt", tmp_path / "link")
    assert set_mode(tmp_path / "link", "600") == 0o600
    assert os.stat(target).st_mode & 0o777 == 0o600


def test_directory(tmp_path: Path) -> None:
    (tmp_path / "dir").mkdir()
    assert set_mode(tmp_path / "dir", "700") == 0o700


def test_umask_does_not_apply(tmp_path: Path) -> None:
    path = new_file(tmp_path / "a.txt")
    old = os.umask(0o077)
    try:
        assert set_mode(path, "666") == 0o666
    finally:
        os.umask(old)
set_mode.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

#include "set_mode.hpp"

namespace fs = std::filesystem;

namespace files {

unsigned set_mode(const fs::path& path, std::string_view mode, std::error_code& ec) {
    ec.clear();
    unsigned m = 0;
    bool valid = mode.size() >= 3 && mode.size() <= 4;
    for (char c : mode) {
        valid = valid && c >= '0' && c <= '7';
        m = m * 8 + static_cast<unsigned>(c - '0');
    }
    if (!valid) {
        ec = std::make_error_code(std::errc::invalid_argument);
        return 0;
    }
    fs::permissions(path, static_cast<fs::perms>(m), fs::perm_options::replace, ec);
    if (ec) return 0;
    fs::file_status st = fs::status(path, ec);
    if (ec) return 0;
    return static_cast<unsigned>(st.permissions() & fs::perms::mask);
}

}  // namespace files
set_mode.hpp 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

#pragma once

#include <filesystem>
#include <string_view>
#include <system_error>

namespace files {

// Sets the mode of the file at path to mode, a string of three or four octal
// digits, as for the chmod command, with std::filesystem::permissions, and
// returns the new permission bits (st_mode & 07777). The values of
// std::filesystem::perms are the POSIX bits, so the number casts to perms.
// permissions follows a symbolic link, and the umask does not apply. On an
// error it sets ec and returns 0: std::errc::invalid_argument for a mode that
// is not three or four octal digits, and std::errc::no_such_file_or_directory
// for a missing file.
unsigned set_mode(const std::filesystem::path& path, std::string_view mode, std::error_code& ec);

}  // namespace files
test_set_mode.cpp 101 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

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

#include <sys/stat.h>

#include "set_mode.hpp"

namespace fs = std::filesystem;

namespace {

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

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

void fresh() {
    fs::remove_all(dir);
    fs::create_directory(dir);
}

fs::path new_file(const std::string& name) {
    fs::path p = dir / name;
    std::ofstream(p, std::ios::binary) << "alpha\n";
    fs::permissions(p, static_cast<fs::perms>(0644));
    return p;
}

unsigned mode_of(const fs::path& p) {
    return static_cast<unsigned>(fs::status(p).permissions() & fs::perms::mask);
}

}  // namespace

int main() {
    struct Case {
        const char *name, *rel, *mode;
        unsigned result;
    };
    const Case cases[] = {
        {"owner-read-write-group-read", "a.txt", "640", 0640},
        {"owner-only", "a.txt", "600", 0600},
        {"executable", "a.txt", "755", 0755},
        {"same-mode", "a.txt", "644", 0644},
        {"no-permissions", "a.txt", "000", 0},
        {"leading-zero", "a.txt", "0640", 0640},
        {"set-user-id", "a.txt", "4755", 04755},
        {"name-with-spaces", "my notes.txt", "640", 0640},
        {"non-ascii-name", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac.txt", "640", 0640},
    };
    std::error_code ec;
    for (const Case& c : cases) {
        fresh();
        fs::path p = new_file(c.rel);
        unsigned got = files::set_mode(p, c.mode, ec);
        expect(!ec && got == c.result, c.name);
        expect(mode_of(p) == c.result, c.name);
    }

    fresh();
    fs::path a = new_file("a.txt");
    for (const char* m : {"648", "64", "10640", "u+x", "", "640\n", "+640"}) {
        files::set_mode(a, m, ec);
        expect(ec == std::errc::invalid_argument, std::string("invalid ") + m);
    }
    expect(mode_of(a) == 0644, "invalid modes change nothing");

    files::set_mode(dir / "missing.txt", "640", ec);
    expect(ec == std::errc::no_such_file_or_directory, "missing");

    fresh();
    a = new_file("a.txt");
    fs::create_symlink("a.txt", dir / "link");
    expect(files::set_mode(dir / "link", "600", ec) == 0600 && !ec, "link");
    expect(mode_of(a) == 0600, "link changes the target");

    fresh();
    fs::create_directory(dir / "dir");
    expect(files::set_mode(dir / "dir", "700", ec) == 0700 && !ec, "directory");

    fresh();
    a = new_file("a.txt");
    mode_t old = umask(077);
    expect(files::set_mode(a, "666", ec) == 0666 && !ec, "umask does not apply");
    umask(old);

    fs::remove_all(dir);
    if (failures == 0) std::printf("ok\n");
    return failures == 0 ? 0 : 1;
}
SetMode.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

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

final class SetMode {
  private SetMode() {}

  /**
   * Sets the mode of the file at path, and returns the new permission bits. mode is three or four
   * octal digits, as for the chmod command. String.matches checks the whole string, so "640\n" is
   * not valid. The PosixFilePermission set has no setuid, setgid or sticky bit, so the code sets
   * the attribute "unix:mode", which takes all twelve bits. It follows a symbolic link, and the
   * umask does not apply. A missing file gives NoSuchFileException.
   */
  static int setMode(Path path, String mode) throws IOException {
    if (mode == null || !mode.matches("[0-7]{3,4}")) {
      throw new IllegalArgumentException("invalid mode: " + mode);
    }
    Files.setAttribute(path, "unix:mode", Integer.parseInt(mode, 8));
    return (Integer) Files.getAttribute(path, "unix:mode") & 07777;
  }
}
SetModeTest.java 75 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
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;
import org.junit.jupiter.params.provider.ValueSource;

class SetModeTest {
  @TempDir Path dir;

  private Path newFile(String name) throws IOException {
    Path p = Files.writeString(dir.resolve(name), "alpha\n");
    Files.setPosixFilePermissions(p, PosixFilePermissions.fromString("rw-r--r--"));
    return p;
  }

  private static int mode(Path p) throws IOException {
    return (Integer) Files.getAttribute(p, "unix:mode") & 07777;
  }

  @ParameterizedTest(name = "{0}")
  @CsvSource({
    "owner-read-write-group-read, a.txt, 640, 416",
    "owner-only, a.txt, 600, 384",
    "executable, a.txt, 755, 493",
    "same-mode, a.txt, 644, 420",
    "no-permissions, a.txt, 000, 0",
    "leading-zero, a.txt, 0640, 416",
    "set-user-id, a.txt, 4755, 2541",
    "name-with-spaces, my notes.txt, 640, 416",
    "non-ascii-name, café 日本.txt, 640, 416",
  })
  void cases(String name, String rel, String mode, int result) throws IOException {
    Path p = newFile(rel);
    assertEquals(result, SetMode.setMode(p, mode));
    assertEquals(result, mode(p));
  }

  @ParameterizedTest
  @ValueSource(strings = {"648", "64", "10640", "u+x", "", "640\n"})
  void invalidMode(String mode) throws IOException {
    Path p = newFile("a.txt");
    assertThrows(IllegalArgumentException.class, () -> SetMode.setMode(p, mode));
    assertEquals(0644, mode(p));
  }

  @Test
  void missingFile() {
    assertThrows(NoSuchFileException.class, () -> SetMode.setMode(dir.resolve("missing.txt"), "640"));
  }

  @Test
  void symbolicLinkChangesTarget() throws IOException {
    Path target = newFile("a.txt");
    Path link = Files.createSymbolicLink(dir.resolve("link"), Path.of("a.txt"));
    assertEquals(0600, SetMode.setMode(link, "600"));
    assertEquals(0600, mode(target));
  }

  @Test
  void directory() throws IOException {
    Path d = Files.createDirectory(dir.resolve("dir"));
    assertEquals(0700, SetMode.setMode(d, "700"));
  }
}
set_mode.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

#define _POSIX_C_SOURCE 200809L

#include "set_mode.h"

#include <errno.h>
#include <string.h>
#include <sys/stat.h>

int set_mode(const char *path, const char *mode, mode_t *result) {
    size_t n = mode == NULL ? 0 : strlen(mode);
    if (n < 3 || n > 4) {
        errno = EINVAL;
        return -1;
    }
    // strtol would accept a sign, spaces and a newline, so the code reads
    // each digit itself.
    mode_t m = 0;
    for (size_t i = 0; i < n; i++) {
        if (mode[i] < '0' || mode[i] > '7') {
            errno = EINVAL;
            return -1;
        }
        m = (mode_t)(m * 8 + (mode_t)(mode[i] - '0'));
    }
    struct stat st;
    if (chmod(path, m) != 0 || stat(path, &st) != 0) return -1;
    *result = st.st_mode & 07777;
    return 0;
}
set_mode.h 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

#ifndef SET_MODE_H
#define SET_MODE_H

#include <sys/types.h>

// set_mode sets the mode of the file at path to mode, a string of three or
// four octal digits, as for the chmod command, and stores the new permission
// bits (st_mode & 07777) in *result. chmod follows a symbolic link, and the
// umask does not apply. It returns 0, or -1 with errno: EINVAL for a mode that
// is not three or four octal digits, and ENOENT for a missing file.
int set_mode(const char *path, const char *mode, mode_t *result);

#endif
test_set_mode.c 105 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

#define _POSIX_C_SOURCE 200809L

#include "set_mode.h"

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

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

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

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

static void fresh(void) {
    if (system("chmod -R u+rwx set_mode_tree 2>/dev/null; rm -rf set_mode_tree") != 0 ||
        mkdir(dir, 0755) != 0)
        exit(2);
}

static void new_file(const char *name) {
    char p[256];
    FILE *f = fopen(at(p, name), "wb");
    if (f == NULL || fputs("alpha\n", f) < 0 || fclose(f) != 0 || chmod(p, 0644) != 0) exit(2);
}

static mode_t mode_of(const char *name) {
    char p[256];
    struct stat st;
    if (stat(at(p, name), &st) != 0) exit(2);
    return st.st_mode & 07777;
}

int main(void) {
    static const struct {
        const char *name, *rel, *mode;
        mode_t result;
    } cases[] = {
        {"owner-read-write-group-read", "a.txt", "640", 0640},
        {"owner-only", "a.txt", "600", 0600},
        {"executable", "a.txt", "755", 0755},
        {"same-mode", "a.txt", "644", 0644},
        {"no-permissions", "a.txt", "000", 0},
        {"leading-zero", "a.txt", "0640", 0640},
        {"set-user-id", "a.txt", "4755", 04755},
        {"name-with-spaces", "my notes.txt", "640", 0640},
        {"non-ascii-name", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac.txt", "640", 0640},
    };
    char p[256];
    mode_t got;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        fresh();
        new_file(cases[i].rel);
        int rc = set_mode(at(p, cases[i].rel), cases[i].mode, &got);
        expect(rc == 0 && got == cases[i].result, cases[i].name);
        expect(mode_of(cases[i].rel) == cases[i].result, cases[i].name);
    }

    fresh();
    new_file("a.txt");
    const char *invalid[] = {"648", "64", "10640", "u+x", "", "640\n", "+640", " 640"};
    for (size_t i = 0; i < sizeof invalid / sizeof invalid[0]; i++) {
        errno = 0;
        expect(set_mode(at(p, "a.txt"), invalid[i], &got) == -1 && errno == EINVAL, invalid[i]);
    }
    expect(mode_of("a.txt") == 0644, "invalid modes change nothing");

    errno = 0;
    expect(set_mode(at(p, "missing.txt"), "640", &got) == -1 && errno == ENOENT, "missing");

    fresh();
    new_file("a.txt");
    if (symlink("a.txt", at(p, "link")) != 0) exit(2);
    expect(set_mode(p, "600", &got) == 0 && got == 0600, "link");
    expect(mode_of("a.txt") == 0600, "link changes the target");

    fresh();
    if (mkdir(at(p, "dir"), 0755) != 0) exit(2);
    expect(set_mode(p, "700", &got) == 0 && got == 0700, "directory");

    fresh();
    new_file("a.txt");
    mode_t old = umask(077);
    expect(set_mode(at(p, "a.txt"), "666", &got) == 0 && got == 0666, "umask does not apply");
    umask(old);

    fresh();
    rmdir(dir);
    if (failures == 0) printf("ok\n");
    return failures == 0 ? 0 : 1;
}
SetMode.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

using System.Runtime.Versioning;

// The Unix mode does not exist on Windows, so the class says so, and the
// compiler checks each call site.
[UnsupportedOSPlatform("windows")]
public static class SetMode
{
    /// <summary>
    /// Sets the mode of the file at path, and returns the new permission bits.
    /// mode is three or four octal digits, as for the chmod command. The code
    /// checks each character, because in .NET the pattern ^[0-7]{3,4}$ also
    /// matches "640\n": $ matches before a final newline. The values of
    /// UnixFileMode are the Unix bits, so the number casts to the enum.
    /// File.SetUnixFileMode follows a symbolic link, and the umask does not
    /// apply. A missing file gives FileNotFoundException.
    /// </summary>
    public static int Set(string path, string mode)
    {
        if (mode is null || mode.Length is < 3 or > 4 || !mode.All(c => c is >= '0' and <= '7'))
        {
            throw new ArgumentException($"invalid mode: {mode}", nameof(mode));
        }
        File.SetUnixFileMode(path, (UnixFileMode)Convert.ToInt32(mode, 8));
        return (int)File.GetUnixFileMode(path);
    }
}
SetModeTests.cs 96 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using Xunit;

[UnsupportedOSPlatform("windows")]
public sealed class SetModeTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("set-mode-").FullName;

    public void Dispose()
    {
        foreach (var f in Directory.EnumerateFileSystemEntries(dir))
        {
            if (!Directory.Exists(f)) File.SetUnixFileMode(f, UnixFileMode.UserRead | UnixFileMode.UserWrite);
        }
        Directory.Delete(dir, recursive: true);
    }

    private string NewFile(string name)
    {
        var p = Path.Combine(dir, name);
        File.WriteAllText(p, "alpha\n");
        File.SetUnixFileMode(p, (UnixFileMode)Convert.ToInt32("644", 8));
        return p;
    }

    // name, path, mode, result
    public static TheoryData<string, string, string, int> Cases => new()
    {
        { "owner-read-write-group-read", "a.txt", "640", 416 },
        { "owner-only", "a.txt", "600", 384 },
        { "executable", "a.txt", "755", 493 },
        { "same-mode", "a.txt", "644", 420 },
        { "no-permissions", "a.txt", "000", 0 },
        { "leading-zero", "a.txt", "0640", 416 },
        { "set-user-id", "a.txt", "4755", 2541 },
        { "name-with-spaces", "my notes.txt", "640", 416 },
        { "non-ascii-name", "café 日本.txt", "640", 416 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void SetsTheMode(string name, string rel, string mode, int result)
    {
        Assert.NotEmpty(name);
        var p = NewFile(rel);
        Assert.Equal(result, SetMode.Set(p, mode));
        Assert.Equal(result, (int)File.GetUnixFileMode(p));
    }

    [Theory]
    [InlineData("648")]
    [InlineData("64")]
    [InlineData("10640")]
    [InlineData("u+x")]
    [InlineData("")]
    [InlineData("640\n")]
    public void RejectsAnInvalidMode(string mode)
    {
        var p = NewFile("a.txt");
        Assert.Throws<ArgumentException>(() => SetMode.Set(p, mode));
        Assert.Equal(420, (int)File.GetUnixFileMode(p));
    }

    [Fact]
    public void TheDollarSignOfDotNetMatchesBeforeANewline()
    {
        Assert.Matches(new Regex("^[0-7]{3,4}$"), "640\n");
    }

    [Fact]
    public void MissingFile()
    {
        Assert.Throws<FileNotFoundException>(() => SetMode.Set(Path.Combine(dir, "missing.txt"), "640"));
    }

    [Fact]
    public void ASymbolicLinkChangesTheTarget()
    {
        var target = NewFile("a.txt");
        var link = Path.Combine(dir, "link");
        File.CreateSymbolicLink(link, "a.txt");
        Assert.Equal(384, SetMode.Set(link, "600"));
        Assert.Equal(384, (int)File.GetUnixFileMode(target));
    }

    [Fact]
    public void ADirectory()
    {
        var d = Directory.CreateDirectory(Path.Combine(dir, "dir")).FullName;
        Assert.Equal(448, SetMode.Set(d, "700"));
    }
}
setMode.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

import { chmod, stat } from "node:fs/promises";

/**
 * Sets the mode of the file at path, and returns the new permission bits.
 * mode is three or four octal digits, as for the chmod command. Without the
 * m flag, $ matches only at the end of the string, so "640\n" is not valid.
 * chmod follows a symbolic link and sets the mode as it is: the umask does
 * not apply. The result is read back with stat, because the system can
 * ignore some bits.
 */
export async function setMode(path, mode) {
  if (typeof mode !== "string" || !/^[0-7]{3,4}$/.test(mode)) {
    throw new RangeError(`invalid mode: ${JSON.stringify(mode)}`);
  }
  await chmod(path, parseInt(mode, 8));
  return (await stat(path)).mode & 0o7777;
}
setMode.test.js 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { chmod, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setMode } from "./setMode.js";

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

async function newFile(path) {
  await writeFile(path, "alpha\n");
  await chmod(path, 0o644);
  return path;
}

const cases = [
  ["owner-read-write-group-read", "a.txt", "640", 0o640],
  ["owner-only", "a.txt", "600", 0o600],
  ["executable", "a.txt", "755", 0o755],
  ["same-mode", "a.txt", "644", 0o644],
  ["no-permissions", "a.txt", "000", 0],
  ["leading-zero", "a.txt", "0640", 0o640],
  ["set-user-id", "a.txt", "4755", 0o4755],
  ["name-with-spaces", "my notes.txt", "640", 0o640],
  ["non-ascii-name", "café 日本.txt", "640", 0o640],
];

for (const [name, rel, mode, result] of cases) {
  test(name, () =>
    withDir(async (dir) => {
      const path = await newFile(join(dir, rel));
      assert.equal(await setMode(path, mode), result);
      assert.equal((await stat(path)).mode & 0o7777, result);
    }),
  );
}

test("invalid modes", () =>
  withDir(async (dir) => {
    const path = await newFile(join(dir, "a.txt"));
    for (const mode of ["648", "64", "10640", "u+x", "", "640\n"]) {
      await assert.rejects(setMode(path, mode), RangeError);
    }
    assert.equal((await stat(path)).mode & 0o7777, 0o644);
  }));

test("missing file", () =>
  withDir(async (dir) => {
    await assert.rejects(setMode(join(dir, "missing.txt"), "640"), { code: "ENOENT" });
  }));

test("a symbolic link changes the target", () =>
  withDir(async (dir) => {
    await newFile(join(dir, "a.txt"));
    await symlink("a.txt", join(dir, "link"));
    assert.equal(await setMode(join(dir, "link"), "600"), 0o600);
    assert.equal((await stat(join(dir, "a.txt"))).mode & 0o777, 0o600);
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
  }));

test("a directory", () =>
  withDir(async (dir) => {
    await mkdir(join(dir, "dir"));
    assert.equal(await setMode(join(dir, "dir"), "700"), 0o700);
  }));

test("the umask does not apply", () =>
  withDir(async (dir) => {
    const path = await newFile(join(dir, "a.txt"));
    const old = process.umask(0o077);
    try {
      assert.equal(await setMode(path, "666"), 0o666);
    } finally {
      process.umask(old);
    }
  }));
setMode.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

import { chmod, stat } from "node:fs/promises";

/**
 * Sets the mode of the file at path, and returns the new permission bits.
 * mode is three or four octal digits, as for the chmod command. Without the
 * m flag, $ matches only at the end of the string, so "640\n" is not valid.
 * chmod follows a symbolic link and sets the mode as it is: the umask does
 * not apply. The result is read back with stat, because the system can
 * ignore some bits.
 */
export async function setMode(path: string, mode: string): Promise<number> {
  if (typeof mode !== "string" || !/^[0-7]{3,4}$/.test(mode)) {
    throw new RangeError(`invalid mode: ${JSON.stringify(mode)}`);
  }
  await chmod(path, parseInt(mode, 8));
  return (await stat(path)).mode & 0o7777;
}
setMode.test.ts 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { chmod, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setMode } from "./setMode.ts";

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

async function newFile(path: string): Promise<string> {
  await writeFile(path, "alpha\n");
  await chmod(path, 0o644);
  return path;
}

const cases = [
  ["owner-read-write-group-read", "a.txt", "640", 0o640],
  ["owner-only", "a.txt", "600", 0o600],
  ["executable", "a.txt", "755", 0o755],
  ["same-mode", "a.txt", "644", 0o644],
  ["no-permissions", "a.txt", "000", 0],
  ["leading-zero", "a.txt", "0640", 0o640],
  ["set-user-id", "a.txt", "4755", 0o4755],
  ["name-with-spaces", "my notes.txt", "640", 0o640],
  ["non-ascii-name", "café 日本.txt", "640", 0o640],
] as const;

for (const [name, rel, mode, result] of cases) {
  test(name, () =>
    withDir(async (dir) => {
      const path = await newFile(join(dir, rel));
      assert.equal(await setMode(path, mode), result);
      assert.equal((await stat(path)).mode & 0o7777, result);
    }),
  );
}

test("invalid modes", () =>
  withDir(async (dir) => {
    const path = await newFile(join(dir, "a.txt"));
    for (const mode of ["648", "64", "10640", "u+x", "", "640\n"]) {
      await assert.rejects(setMode(path, mode), RangeError);
    }
    assert.equal((await stat(path)).mode & 0o7777, 0o644);
  }));

test("missing file", () =>
  withDir(async (dir) => {
    await assert.rejects(setMode(join(dir, "missing.txt"), "640"), { code: "ENOENT" });
  }));

test("a symbolic link changes the target", () =>
  withDir(async (dir) => {
    await newFile(join(dir, "a.txt"));
    await symlink("a.txt", join(dir, "link"));
    assert.equal(await setMode(join(dir, "link"), "600"), 0o600);
    assert.equal((await stat(join(dir, "a.txt"))).mode & 0o777, 0o600);
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
  }));

test("a directory", () =>
  withDir(async (dir) => {
    await mkdir(join(dir, "dir"));
    assert.equal(await setMode(join(dir, "dir"), "700"), 0o700);
  }));

test("the umask does not apply", () =>
  withDir(async (dir) => {
    const path = await newFile(join(dir, "a.txt"));
    const old = process.umask(0o077);
    try {
      assert.equal(await setMode(path, "666"), 0o666);
    } finally {
      process.umask(old);
    }
  }));
set_mode.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

// Package setmode sets the permissions of a file.
package setmode

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"regexp"
	"strconv"
)

// ErrInvalidMode is the error for a mode that is not three or four octal digits.
var ErrInvalidMode = errors.New("invalid mode")

// Without the m flag, $ matches only at the end of the text, so "640\n" is not valid.
var modeRE = regexp.MustCompile(`^[0-7]{3,4}$`)

// The Unix bits for setuid, setgid and sticky, and the fs.FileMode bits of Go.
var special = []struct {
	unix uint32
	mode fs.FileMode
}{{0o4000, fs.ModeSetuid}, {0o2000, fs.ModeSetgid}, {0o1000, fs.ModeSticky}}

// SetMode sets the mode of the file at path, and returns the new permission
// bits in the Unix layout (st_mode & 07777). mode is three or four octal
// digits, as for the chmod command. Go keeps setuid, setgid and sticky in its
// own bits, so the code maps them in both directions. os.Chmod follows a
// symbolic link, and the umask does not apply. A missing file gives a
// *fs.PathError with fs.ErrNotExist.
func SetMode(path, mode string) (uint32, error) {
	if !modeRE.MatchString(mode) {
		return 0, fmt.Errorf("set mode %q: %w", mode, ErrInvalidMode)
	}
	n, _ := strconv.ParseUint(mode, 8, 32)
	m := fs.FileMode(n) & fs.ModePerm
	for _, s := range special {
		if uint32(n)&s.unix != 0 {
			m |= s.mode
		}
	}
	if err := os.Chmod(path, m); err != nil {
		return 0, err
	}
	fi, err := os.Stat(path)
	if err != nil {
		return 0, err
	}
	result := uint32(fi.Mode().Perm())
	for _, s := range special {
		if fi.Mode()&s.mode != 0 {
			result |= s.unix
		}
	}
	return result, nil
}
set_mode_test.go 114 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

package setmode

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

func newFile(t *testing.T, name string) string {
	t.Helper()
	p := filepath.Join(t.TempDir(), name)
	if err := os.WriteFile(p, []byte("alpha\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.Chmod(p, 0o644); err != nil {
		t.Fatal(err)
	}
	return p
}

func unixMode(t *testing.T, p string) uint32 {
	t.Helper()
	var st syscall.Stat_t
	if err := syscall.Stat(p, &st); err != nil {
		t.Fatal(err)
	}
	return uint32(st.Mode) & 0o7777
}

func TestCases(t *testing.T) {
	for _, c := range []struct {
		name, rel, mode string
		result          uint32
	}{
		{"owner-read-write-group-read", "a.txt", "640", 0o640},
		{"owner-only", "a.txt", "600", 0o600},
		{"executable", "a.txt", "755", 0o755},
		{"same-mode", "a.txt", "644", 0o644},
		{"no-permissions", "a.txt", "000", 0},
		{"leading-zero", "a.txt", "0640", 0o640},
		{"set-user-id", "a.txt", "4755", 0o4755},
		{"name-with-spaces", "my notes.txt", "640", 0o640},
		{"non-ascii-name", "café 日本.txt", "640", 0o640},
	} {
		t.Run(c.name, func(t *testing.T) {
			p := newFile(t, c.rel)
			got, err := SetMode(p, c.mode)
			if err != nil || got != c.result {
				t.Fatalf("SetMode(%q) = %o, %v; want %o", c.mode, got, err, c.result)
			}
			if m := unixMode(t, p); m != c.result {
				t.Fatalf("stat mode = %o, want %o", m, c.result)
			}
		})
	}
}

func TestInvalidMode(t *testing.T) {
	p := newFile(t, "a.txt")
	for _, mode := range []string{"648", "64", "10640", "u+x", "", "640\n"} {
		if _, err := SetMode(p, mode); !errors.Is(err, ErrInvalidMode) {
			t.Errorf("SetMode(%q) error = %v, want ErrInvalidMode", mode, err)
		}
	}
	if m := unixMode(t, p); m != 0o644 {
		t.Fatalf("mode = %o, want 644", m)
	}
}

func TestMissing(t *testing.T) {
	_, err := SetMode(filepath.Join(t.TempDir(), "missing.txt"), "640")
	if !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("error = %v, want fs.ErrNotExist", err)
	}
}

func TestSymbolicLinkChangesTarget(t *testing.T) {
	p := newFile(t, "a.txt")
	link := filepath.Join(filepath.Dir(p), "link")
	if err := os.Symlink("a.txt", link); err != nil {
		t.Fatal(err)
	}
	if got, err := SetMode(link, "600"); err != nil || got != 0o600 {
		t.Fatalf("SetMode(link) = %o, %v", got, err)
	}
	if m := unixMode(t, p); m != 0o600 {
		t.Fatalf("target mode = %o, want 600", m)
	}
}

func TestDirectory(t *testing.T) {
	d := filepath.Join(t.TempDir(), "dir")
	if err := os.Mkdir(d, 0o755); err != nil {
		t.Fatal(err)
	}
	if got, err := SetMode(d, "700"); err != nil || got != 0o700 {
		t.Fatalf("SetMode(dir) = %o, %v", got, err)
	}
}

func TestUmaskDoesNotApply(t *testing.T) {
	p := newFile(t, "a.txt")
	old := syscall.Umask(0o077)
	defer syscall.Umask(old)
	if got, err := SetMode(p, "666"); err != nil || got != 0o666 {
		t.Fatalf("SetMode = %o, %v; want 666", got, err)
	}
}
set_mode.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

use std::fs;
use std::io::{self, ErrorKind};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;

/// Sets the mode of the file at `path`, and returns the new permission bits
/// (`st_mode & 0o7777`). `mode` is three or four octal digits, as for the
/// chmod command; anything else gives `ErrorKind::InvalidInput`. The portable
/// `Permissions` type has only a read-only flag, so the code uses
/// `PermissionsExt::from_mode`, which is for Unix. `fs::set_permissions`
/// follows a symbolic link, and the umask does not apply. A missing file gives
/// `ErrorKind::NotFound`.
pub fn set_mode(path: impl AsRef<Path>, mode: &str) -> io::Result<u32> {
    let path = path.as_ref();
    let valid = (3..=4).contains(&mode.len()) && mode.bytes().all(|b| (b'0'..=b'7').contains(&b));
    if !valid {
        return Err(io::Error::new(ErrorKind::InvalidInput, format!("invalid mode: {mode:?}")));
    }
    let bits = u32::from_str_radix(mode, 8).map_err(|e| io::Error::new(ErrorKind::InvalidInput, e))?;
    fs::set_permissions(path, fs::Permissions::from_mode(bits))?;
    Ok(fs::metadata(path)?.permissions().mode() & 0o7777)
}
tests/set_mode_test.rs 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/set-file-permissions/.

use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;

use algo_set_file_permissions::set_mode;

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

fn new_file(dir: &PathBuf, name: &str) -> PathBuf {
    let p = dir.join(name);
    fs::write(&p, "alpha\n").unwrap();
    fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
    p
}

fn mode(p: &PathBuf) -> u32 {
    fs::metadata(p).unwrap().permissions().mode() & 0o7777
}

#[test]
fn cases() {
    for (name, rel, m, result) in [
        ("owner-read-write-group-read", "a.txt", "640", 0o640),
        ("owner-only", "a.txt", "600", 0o600),
        ("executable", "a.txt", "755", 0o755),
        ("same-mode", "a.txt", "644", 0o644),
        ("no-permissions", "a.txt", "000", 0),
        ("leading-zero", "a.txt", "0640", 0o640),
        ("set-user-id", "a.txt", "4755", 0o4755),
        ("name-with-spaces", "my notes.txt", "640", 0o640),
        ("non-ascii-name", "café 日本.txt", "640", 0o640),
    ] {
        let dir = new_dir(name);
        let p = new_file(&dir, rel);
        assert_eq!(set_mode(&p, m).unwrap(), result, "{name}");
        assert_eq!(mode(&p), result, "{name}");
        fs::remove_dir_all(&dir).unwrap();
    }
}

#[test]
fn invalid_modes() {
    let dir = new_dir("invalid");
    let p = new_file(&dir, "a.txt");
    for m in ["648", "64", "10640", "u+x", "", "640\n", "+640"] {
        assert_eq!(set_mode(&p, m).unwrap_err().kind(), ErrorKind::InvalidInput, "{m:?}");
    }
    assert_eq!(mode(&p), 0o644);
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn missing_file() {
    let dir = new_dir("missing");
    assert_eq!(set_mode(dir.join("missing.txt"), "640").unwrap_err().kind(), ErrorKind::NotFound);
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn symbolic_link_changes_target() {
    let dir = new_dir("link");
    let target = new_file(&dir, "a.txt");
    std::os::unix::fs::symlink("a.txt", dir.join("link")).unwrap();
    assert_eq!(set_mode(dir.join("link"), "600").unwrap(), 0o600);
    assert_eq!(mode(&target), 0o600);
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn directory() {
    let dir = new_dir("dir");
    let d = dir.join("dir");
    fs::create_dir(&d).unwrap();
    assert_eq!(set_mode(&d, "700").unwrap(), 0o700);
    fs::remove_dir_all(&dir).unwrap();
}
set_mode.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/set-file-permissions/.

# set_mode PATH MODE
# Sets the mode of the file at PATH to MODE, three or four octal digits, and
# prints the new permission bits as octal digits, such as 640. The chmod
# command also takes symbolic modes such as u+x, so the function checks MODE
# first, with a pattern that must match the whole string. POSIX has no stat
# utility, and the options of stat differ between GNU and BSD, so the function
# tries the GNU form and then the BSD form. chmod follows a symbolic link. The
# function returns status 2 for an invalid mode and 1 for a missing file.
set_mode() {
  local path=$1 mode=$2 bits
  if [[ ! $mode =~ ^[0-7]{3,4}$ ]]; then
    printf 'set_mode: invalid mode: %q\n' "$mode" >&2
    return 2
  fi
  chmod -- "$mode" "$path" || return 1
  bits=$(stat -L -c '%a' -- "$path" 2>/dev/null || stat -L -f '%Mp%Lp' -- "$path") || return 1
  printf '%04o\n' "$((8#$bits))" | sed 's/^0\([0-7]\{3\}\)$/\1/'
}
test_set_mode.bats 76 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/set-file-permissions/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/set_mode.sh"
  dir=$BATS_TEST_TMPDIR
  printf 'alpha\n' >"$dir/a.txt"
  chmod 644 "$dir/a.txt"
}

teardown() {
  chmod -R u+rwx "$dir" 2>/dev/null || true
}

@test "owner-read-write-group-read" {
  [ "$(set_mode "$dir/a.txt" 640)" = 640 ]
}

@test "owner-only" {
  [ "$(set_mode "$dir/a.txt" 600)" = 600 ]
}

@test "executable" {
  [ "$(set_mode "$dir/a.txt" 755)" = 755 ]
}

@test "same-mode" {
  [ "$(set_mode "$dir/a.txt" 644)" = 644 ]
}

@test "no-permissions" {
  [ "$(set_mode "$dir/a.txt" 000)" = 000 ]
}

@test "leading-zero" {
  [ "$(set_mode "$dir/a.txt" 0640)" = 640 ]
}

@test "set-user-id" {
  [ "$(set_mode "$dir/a.txt" 4755)" = 4755 ]
}

@test "name-with-spaces" {
  printf 'alpha\n' >"$dir/my notes.txt"
  [ "$(set_mode "$dir/my notes.txt" 640)" = 640 ]
}

@test "non-ascii-name" {
  printf 'alpha\n' >"$dir/café 日本.txt"
  [ "$(set_mode "$dir/café 日本.txt" 640)" = 640 ]
}

@test "invalid modes fail with status 2 and change nothing" {
  for m in 648 64 10640 u+x '' $'640\n' +640; do
    run -2 set_mode "$dir/a.txt" "$m"
  done
  [ "$(set_mode "$dir/a.txt" 644)" = 644 ]
}

@test "missing file fails with status 1" {
  run -1 set_mode "$dir/missing.txt" 640
}

@test "a symbolic link changes the target" {
  ln -s a.txt "$dir/link"
  [ "$(set_mode "$dir/link" 600)" = 600 ]
  [ "$(set_mode "$dir/a.txt" 600)" = 600 ]
}

@test "directory" {
  mkdir "$dir/d"
  [ "$(set_mode "$dir/d" 700)" = 700 ]
}

References

  1. The Open Group Base Specifications Issue 8 (POSIX.1-2024), chmod, fchmodat, DESCRIPTION, ERRORS
  2. The Open Group Base Specifications Issue 8 (POSIX.1-2024), chmod utility, OPERANDS, APPLICATION USAGE
  3. The Open Group Base Specifications Issue 8 (POSIX.1-2024), sys/stat.h, DESCRIPTION, the file mode bits
  4. Linux manual page, chmod(2), DESCRIPTION
  5. The Python Standard Library, os, Miscellaneous operating system interfaces, os.chmod
  6. The Python Standard Library, stat, Interpreting stat() results, stat.S_IMODE
  7. Node.js documentation, File system, fs.chmod(path, mode, callback), File modes
  8. Java SE 25 API, Files, setPosixFilePermissions, getAttribute
  9. Java SE 25 API, PosixFilePermission, Enum description
  10. .NET API reference, File.SetUnixFileMode Method, SetUnixFileMode(String, UnixFileMode), Exceptions
  11. .NET API reference, UnixFileMode Enum, Fields
  12. Go standard library, package os, func Chmod
  13. Go standard library, package io/fs, type FileMode, type FileMode
  14. The Rust Standard Library, std::fs::set_permissions, Platform-specific behavior, Symlinks
  15. The Rust Standard Library, std::os::unix::fs::PermissionsExt, from_mode
  16. cppreference, std::filesystem::permissions, Description

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 (csharp)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