Taskcore
Create a symbolic link
Also called make a symlink, create a symlink, ln -s, soft link, readlink.
Make a symbolic link that holds a target path, read the target back, and know that a relative target is read from the directory of the link and that a dangling link still exists.
- Evidence
- Code in 10 languages
Task
Make a symbolic link at the path link that holds the string target, and return the target that the link holds, read back from the link. The target is stored as it is. It need not exist, and a relative target is read from the directory of the link, not from the current directory. So a link sub/link with the target ../a.txt points to a.txt. Report an error when a file, a directory or a link already has the path link, and when the directory of link does not exist.
POSIX says what the call stores: "The string pointed to by path1 shall be treated only as a string and shall not be validated as a pathname." Linux adds: "There is no requirement that the pathname referred to by a symbolic link should exist." A link to a path that does not exist "is said to be a dangling link". The page Hard links and symbolic links tells how links work.
SQL, regular expressions, HTML and CSS do not apply, because they do not make files. The solutions are for Linux and macOS. On Windows, a link needs a privilege or Developer Mode, and a link to a directory is a different kind from a link to a file. See the pitfalls.
Solutions
Each solution makes the link and then reads it back. The order of the two arguments is not the same in each language, so read each call with care.
- Python.
os.symlink(target, link), and thenos.readlink(link).os.symlinkwill "Create a symbolic link pointing to src named dst", so the target comes first, as inln -s. A link that exists givesFileExistsError. - JavaScript and TypeScript (Node.js).
await symlink(target, link)fromnode:fs/promises, and thenawait readlink(link). The third argument "is only used on Windows platforms and can be one of 'dir' , 'file' , or 'junction'". The error codes areEEXISTandENOENT. - Java.
Files.createSymbolicLink(link, Path.of(target)), and thenFiles.readSymbolicLink(link). Here the new link comes first. The target "may be an absolute or relative path and may not exist. When the target is a relative path then file system operations on the resulting link are relative to the path of the link." A link that exists givesFileAlreadyExistsException. - C#.
File.CreateSymbolicLink(link, target), and then theLinkTargetof theFileInfothat it returns. The new link comes first, andpathToTargetis "The path of the target to which the symbolic link points." A link that exists givesIOException: "A file or directory already exists in the location of path". - Go.
os.Symlink(target, link), and thenos.Readlink(link). The target comes first. An error is a*LinkError, which "records an error during a link or symlink or rename system call and the paths that caused it." It matchesfs.ErrExistorfs.ErrNotExistwitherrors.Is. - Rust.
std::os::unix::fs::symlink(target, link), and thenfs::read_link(link). The call "Creates a new symbolic link on the filesystem. The link path will be a symbolic link pointing to the original path." It is in the Unix module, because Windows has two calls,symlink_fileandsymlink_dir. The error kinds areAlreadyExistsandNotFound. - C. POSIX
symlink(target, link), and thenreadlink(link, buf, size). ISO C has no call for links.readlinkgives a count of bytes and does not add a NUL byte: "If the number of bytes in the symbolic link is less than bufsize , the contents of the remainder of buf are unspecified." So the solution adds the NUL byte, and it givesERANGEwhen the target fills the buffer, because the target can be longer. - C++.
std::filesystem::create_symlink(target, link, ec), and thenread_symlink(link, ec). It "Creates a symbolic link link with its target set to target as if by POSIX symlink() : the pathname target may be invalid or non-existing." - Bash.
ln -s -- "$target" "$link", and thenreadlink -- "$link". Whenlinknames a directory,lnmakes the link inside it. See the pitfalls. So the function first checks that no file has the name, with[[ -e $link || -L $link ]]. Another process can make the name between the check andln. The C, Python and other solutions do not have this race, becausesymlinkchecks and makes the link in one call.
Edge cases
The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/errors.jsonl. Each test runs in a new temporary directory that holds the file a.txt and the directory sub, which holds b.txt. Each test checks the result and that the new link is a symbolic link, with lstat or the call of the language.
file-target,directory-targetandlink-in-subdirectory: links toa.txt, tosub, and fromsub/linktob.txt.dangling-target: the targetmissing.txtdoes not exist. The link is made, and reading through it gives no such file.relative-target:sub/linkwith the targeta.txtpoints tosub/a.txt, which does not exist. The result is stilla.txt.parent-target:sub/linkwith the target../a.txtpoints toa.txt. The native tests readalphathrough it.name-with-spacesandnon-ascii-name:my notes.txtandcafé 日本.txt. A shell solution must quote both names.- Errors: a file (
a.txt) and a directory (sub) atlinkgive exists, andnodir/linkgives not-found.
The native tests also check that a dangling link at link gives exists and stays as it was, that an absolute target is stored as it is, and, in Bash, that a directory at link does not get a link inside it.
Pitfalls
- ln -s into a directory. When the last operand of
lnis a directory, POSIX says: "The second synopsis form shall be assumed when the final operand names an existing directory." In that form,ln"shall create a new directory entry for each source_file operand, at a destination path in the existing directory". Soln -s a.txt subgives no error. It makessub/a.txt, and that link points to itself:
This code runs but gives a wrong answer on purpose.
cd "$(mktemp -d)"
printf 'alpha\n' >a.txt
mkdir sub
ln -s a.txt sub
if [ -L sub ]; then echo "sub is a link"; else echo "sub is not a link"; fi
echo "sub/a.txt holds: $(readlink sub/a.txt)"
cat sub/a.txt 2>/dev/null || echo "cat sub/a.txt: fails (a link to itself)"
sub is not a link
sub/a.txt holds: a.txt
cat sub/a.txt: fails (a link to itself)
- A dangling link exists.
os.path.existsfollows a link: it "Returns False for broken symbolic links." So a check withexistsdoes not see a dangling link, andsymlinkthen fails.os.path.lexists"Return True if path refers to an existing path, including broken symbolic links":
This code runs but gives a wrong answer on purpose.
import os
os.symlink("old-target.txt", "link") # a dangling link from an earlier run
if not os.path.exists("link"):
try:
os.symlink("a.txt", "link")
except FileExistsError:
print("exists said no, but symlink gave FileExistsError")
print("lexists:", os.path.lexists("link"))
exists said no, but symlink gave FileExistsError
lexists: True
Do not check first. Call symlink and handle the error, as the solutions do.
- A relative target is read from the link.
os.readlinkgives the string as it is. Python says: "The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using os.path.join(os.path.dirname(path), result)":
import os
os.makedirs("sub")
open("a.txt", "w").close()
os.symlink("../a.txt", "sub/link")
target = os.readlink("sub/link")
print("readlink:", target)
print("from the current directory:", os.path.exists(target))
full = os.path.join(os.path.dirname("sub/link"), target)
print("from the link:", full, os.path.exists(full))
readlink: ../a.txt
from the current directory: False
from the link: sub/../a.txt True
- The order of the arguments. Python, Node.js, Go, Rust, C, C++ and
ln -stake the target first. Java and C# take the new link first. With the wrong order in Java, the call tries to make a link with the name of the target:
This code runs but gives a wrong answer on purpose.
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Files.writeString(Path.of("a.txt"), "alpha\n");
try {
// The order of ln -s: the target, then the link. Java wants the link first.
Files.createSymbolicLink(Path.of("a.txt"), Path.of("link"));
} catch (FileAlreadyExistsException e) {
System.out.println("FileAlreadyExistsException: " + e.getFile());
}
}
}
FileAlreadyExistsException: a.txt
-
Windows needs a privilege. Python says: "When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator." The Windows call has the flag
SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE, and "Developer Mode must first be enabled on the machine before this option will function." A program that makes links must handle this error on Windows. -
A link to a directory on Windows. A Windows link is either for a file or for a directory. C++ says: "Portable code should use (3,4) to create directory symlinks rather than (1,2) , even though there is no distinction on POSIX systems." Rust has
symlink_dir, Node.js has the type'dir', and Python hastarget_is_directory.
Related tasks
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-symbolic-link/.
import os
def make_symlink(target: str, link: str | os.PathLike[str]) -> str:
"""Make a symbolic link at link that holds target, and return the target
that the link holds, read back with os.readlink.
target is stored as it is: it need not exist, and a relative target is
read from the directory of link. The order of the arguments is the order
of os.symlink and of ln -s: first the target, then the new name.
os.symlink raises FileExistsError when link exists, also as a dangling
link, and FileNotFoundError when the directory of link does not exist.
"""
os.symlink(target, link)
return os.readlink(link)
test_make_symlink.py 71 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-symbolic-link/.
import os
from pathlib import Path
import pytest
from make_symlink import make_symlink
# name: (target, link)
CASES = {
"file-target": ("a.txt", "link"),
"directory-target": ("sub", "link"),
"link-in-subdirectory": ("b.txt", "sub/link"),
"dangling-target": ("missing.txt", "link"),
"relative-target": ("a.txt", "sub/link"),
"parent-target": ("../a.txt", "sub/link"),
"name-with-spaces": ("my notes.txt", "my link"),
"non-ascii-name": ("café 日本.txt", "lien 日本"),
}
@pytest.fixture
def tree(tmp_path: Path) -> Path:
(tmp_path / "a.txt").write_bytes(b"alpha\n")
(tmp_path / "sub").mkdir()
(tmp_path / "sub" / "b.txt").write_bytes(b"beta\n")
return tmp_path
@pytest.mark.parametrize("name", CASES)
def test_cases(tree: Path, name: str) -> None:
target, rel = CASES[name]
link = tree / rel
assert make_symlink(target, link) == target
assert link.is_symlink()
@pytest.mark.parametrize("target,rel", [("b.txt", "a.txt"), ("a.txt", "sub")])
def test_exists(tree: Path, target: str, rel: str) -> None:
with pytest.raises(FileExistsError):
make_symlink(target, tree / rel)
assert not (tree / rel).is_symlink()
def test_dangling_link_exists(tree: Path) -> None:
os.symlink("missing.txt", tree / "link")
assert not os.path.exists(tree / "link")
with pytest.raises(FileExistsError):
make_symlink("a.txt", tree / "link")
assert os.readlink(tree / "link") == "missing.txt"
def test_missing_directory(tree: Path) -> None:
with pytest.raises(FileNotFoundError):
make_symlink("a.txt", tree / "nodir" / "link")
def test_link_reads_target(tree: Path) -> None:
make_symlink("a.txt", tree / "link")
assert (tree / "link").read_bytes() == b"alpha\n"
make_symlink("../a.txt", tree / "sub" / "up")
assert (tree / "sub" / "up").read_bytes() == b"alpha\n"
make_symlink("a.txt", tree / "sub" / "here")
assert not (tree / "sub" / "here").exists()
def test_absolute_target(tree: Path) -> None:
target = str(tree / "a.txt")
assert make_symlink(target, tree / "link") == target
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
#include "make_symlink.hpp"
namespace fs = std::filesystem;
namespace files {
fs::path make_symlink(const fs::path& target, const fs::path& link, std::error_code& ec) {
fs::create_symlink(target, link, ec);
if (ec) return {};
return fs::read_symlink(link, ec);
}
} // namespace files
make_symlink.hpp 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
#pragma once
#include <filesystem>
#include <system_error>
namespace files {
// Makes a symbolic link at link that holds target, with
// std::filesystem::create_symlink, and returns the target that the link
// holds, read back with read_symlink. The target is stored as it is: it need
// not exist, and a relative target is read from the directory of link. For a
// link to a directory, portable code uses create_directory_symlink, because
// Windows needs to know; on POSIX the two calls are the same. On an error it
// sets ec and returns an empty path: std::errc::file_exists when link exists,
// also as a dangling link, and std::errc::no_such_file_or_directory when the
// directory of link does not exist.
std::filesystem::path make_symlink(const std::filesystem::path& target,
const std::filesystem::path& link, std::error_code& ec);
} // namespace files
test_make_symlink.cpp 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <string>
#include <system_error>
#include "make_symlink.hpp"
namespace fs = std::filesystem;
namespace {
const fs::path dir = "make_symlink_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_directories(dir / "sub");
std::ofstream(dir / "a.txt", std::ios::binary) << "alpha\n";
std::ofstream(dir / "sub" / "b.txt", std::ios::binary) << "beta\n";
}
} // namespace
int main() {
struct Case {
const char *name, *target, *link;
};
const Case cases[] = {
{"file-target", "a.txt", "link"},
{"directory-target", "sub", "link"},
{"link-in-subdirectory", "b.txt", "sub/link"},
{"dangling-target", "missing.txt", "link"},
{"relative-target", "a.txt", "sub/link"},
{"parent-target", "../a.txt", "sub/link"},
{"name-with-spaces", "my notes.txt", "my link"},
{"non-ascii-name", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac.txt", "lien \xe6\x97\xa5\xe6\x9c\xac"},
};
std::error_code ec;
for (const Case& c : cases) {
fresh();
fs::path link = dir / c.link;
fs::path got = files::make_symlink(c.target, link, ec);
expect(!ec && got == fs::path(c.target), c.name);
expect(fs::is_symlink(link), c.name);
}
fresh();
files::make_symlink("b.txt", dir / "a.txt", ec);
expect(ec == std::errc::file_exists, "file exists");
files::make_symlink("a.txt", dir / "sub", ec);
expect(ec == std::errc::file_exists, "directory exists");
fs::create_symlink("missing.txt", dir / "dangling");
files::make_symlink("a.txt", dir / "dangling", ec);
expect(ec == std::errc::file_exists, "dangling link exists");
expect(fs::read_symlink(dir / "dangling") == "missing.txt", "the dangling link stays");
files::make_symlink("a.txt", dir / "nodir" / "link", ec);
expect(ec == std::errc::no_such_file_or_directory, "missing directory");
files::make_symlink("../a.txt", dir / "sub" / "up", ec);
std::ifstream in(dir / "sub" / "up", std::ios::binary);
std::string data((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
expect(!ec && data == "alpha\n", "link reads target");
fs::remove_all(dir);
if (failures == 0) std::printf("ok\n");
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public final class MakeSymlink {
private MakeSymlink() {}
/**
* Makes a symbolic link at link that holds target, and returns the target that the link holds,
* read back with readSymbolicLink. target is stored as it is: it need not exist, and a relative
* target is read from the directory of link. Files.createSymbolicLink takes the new link first
* and the target second, the other order from ln -s. It throws FileAlreadyExistsException when
* link exists, also as a dangling link, and NoSuchFileException when the directory of link does
* not exist.
*/
public static String makeSymlink(String target, Path link) throws IOException {
Files.createSymbolicLink(link, Path.of(target));
return Files.readSymbolicLink(link).toString();
}
}
MakeSymlinkTest.java 88 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
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 java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
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.BeforeEach;
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 MakeSymlinkTest {
@TempDir Path dir;
@BeforeEach
void tree() throws IOException {
Files.writeString(dir.resolve("a.txt"), "alpha\n");
Files.createDirectory(dir.resolve("sub"));
Files.writeString(dir.resolve("sub/b.txt"), "beta\n");
}
@ParameterizedTest(name = "{0}")
@CsvSource(
delimiter = '|',
value = {
"file-target|a.txt|link",
"directory-target|sub|link",
"link-in-subdirectory|b.txt|sub/link",
"dangling-target|missing.txt|link",
"relative-target|a.txt|sub/link",
"parent-target|../a.txt|sub/link",
"name-with-spaces|my notes.txt|my link",
"non-ascii-name|café 日本.txt|lien 日本",
})
void cases(String name, String target, String rel) throws IOException {
Path link = dir.resolve(rel);
assertEquals(target, MakeSymlink.makeSymlink(target, link));
assertTrue(Files.isSymbolicLink(link));
}
@ParameterizedTest
@CsvSource({"b.txt,a.txt", "a.txt,sub"})
void exists(String target, String rel) {
assertThrows(
FileAlreadyExistsException.class, () -> MakeSymlink.makeSymlink(target, dir.resolve(rel)));
assertFalse(Files.isSymbolicLink(dir.resolve(rel)));
}
@Test
void danglingLinkExists() throws IOException {
Path link = dir.resolve("link");
Files.createSymbolicLink(link, Path.of("missing.txt"));
assertFalse(Files.exists(link));
assertTrue(Files.exists(link, LinkOption.NOFOLLOW_LINKS));
assertThrows(FileAlreadyExistsException.class, () -> MakeSymlink.makeSymlink("a.txt", link));
assertEquals("missing.txt", Files.readSymbolicLink(link).toString());
}
@Test
void missingDirectory() {
assertThrows(
NoSuchFileException.class,
() -> MakeSymlink.makeSymlink("a.txt", dir.resolve("nodir/link")));
}
@Test
void linkReadsTarget() throws IOException {
MakeSymlink.makeSymlink("a.txt", dir.resolve("link"));
assertEquals("alpha\n", Files.readString(dir.resolve("link")));
MakeSymlink.makeSymlink("../a.txt", dir.resolve("sub/up"));
assertEquals("alpha\n", Files.readString(dir.resolve("sub/up")));
}
@Test
void absoluteTarget() throws IOException {
String target = dir.resolve("a.txt").toString();
assertEquals(target, MakeSymlink.makeSymlink(target, dir.resolve("link")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
#define _POSIX_C_SOURCE 200809L
#include "make_symlink.h"
#include <errno.h>
#include <unistd.h>
ssize_t make_symlink(const char *target, const char *link, char *buf, size_t size) {
if (symlink(target, link) != 0) return -1;
if (size == 0) {
errno = ERANGE;
return -1;
}
// readlink does not end the target with a NUL byte. When it fills the
// buffer, the target can be longer, so the code needs one byte more.
ssize_t n = readlink(link, buf, size);
if (n < 0) return -1;
if ((size_t)n == size) {
errno = ERANGE;
return -1;
}
buf[n] = '\0';
return n;
}
make_symlink.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
#ifndef MAKE_SYMLINK_H
#define MAKE_SYMLINK_H
#include <stddef.h>
#include <sys/types.h>
// make_symlink makes a symbolic link at link that holds target, reads the
// target back with readlink into buf, which has size bytes, and ends it with a
// NUL byte. target is stored as it is: it need not exist, and a relative
// target is read from the directory of link. It returns the length of the
// target, or -1 with errno: EEXIST when link exists, also as a dangling link,
// ENOENT when the directory of link does not exist, and ERANGE when buf is too
// small. After ERANGE, the link exists.
ssize_t make_symlink(const char *target, const char *link, char *buf, size_t size);
#endif
test_make_symlink.c 94 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
#define _POSIX_C_SOURCE 200809L
#include "make_symlink.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static const char *dir = "make_symlink_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 write_file(const char *name, const char *data) {
char p[256];
FILE *f = fopen(at(p, name), "wb");
if (f == NULL || fputs(data, f) < 0 || fclose(f) != 0) exit(2);
}
static void fresh(void) {
char p[256];
if (system("rm -rf make_symlink_tree") != 0 || mkdir(dir, 0755) != 0 ||
mkdir(at(p, "sub"), 0755) != 0)
exit(2);
write_file("a.txt", "alpha\n");
write_file("sub/b.txt", "beta\n");
}
int main(void) {
static const struct {
const char *name, *target, *link;
} cases[] = {
{"file-target", "a.txt", "link"},
{"directory-target", "sub", "link"},
{"link-in-subdirectory", "b.txt", "sub/link"},
{"dangling-target", "missing.txt", "link"},
{"relative-target", "a.txt", "sub/link"},
{"parent-target", "../a.txt", "sub/link"},
{"name-with-spaces", "my notes.txt", "my link"},
{"non-ascii-name", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac.txt", "lien \xe6\x97\xa5\xe6\x9c\xac"},
};
char p[256], buf[256];
struct stat st;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
fresh();
ssize_t n = make_symlink(cases[i].target, at(p, cases[i].link), buf, sizeof buf);
expect(n == (ssize_t)strlen(cases[i].target) && strcmp(buf, cases[i].target) == 0,
cases[i].name);
expect(lstat(p, &st) == 0 && S_ISLNK(st.st_mode), cases[i].name);
}
fresh();
errno = 0;
expect(make_symlink("b.txt", at(p, "a.txt"), buf, sizeof buf) == -1 && errno == EEXIST, "file exists");
errno = 0;
expect(make_symlink("a.txt", at(p, "sub"), buf, sizeof buf) == -1 && errno == EEXIST, "directory exists");
if (symlink("missing.txt", at(p, "dangling")) != 0) exit(2);
errno = 0;
expect(make_symlink("a.txt", p, buf, sizeof buf) == -1 && errno == EEXIST, "dangling link exists");
errno = 0;
expect(make_symlink("a.txt", at(p, "nodir/link"), buf, sizeof buf) == -1 && errno == ENOENT, "missing directory");
char small[5];
errno = 0;
expect(make_symlink("long-target.txt", at(p, "small"), small, sizeof small) == -1 && errno == ERANGE, "small buffer");
expect(make_symlink("../a.txt", at(p, "sub/up"), buf, sizeof buf) == 8, "parent link");
FILE *f = fopen(p, "rb");
char data[16] = {0};
expect(f != NULL && fgets(data, sizeof data, f) != NULL && strcmp(data, "alpha\n") == 0, "link reads target");
if (f != NULL) fclose(f);
if (system("rm -rf make_symlink_tree") != 0) return 2;
if (failures == 0) printf("ok\n");
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
public static class MakeSymlink
{
/// <summary>
/// Makes a symbolic link at link that holds target, and returns the
/// target that the link holds, read back with LinkTarget. target is
/// stored as it is: it need not exist, and a relative target is read
/// from the directory of link. File.CreateSymbolicLink takes the new
/// link first and the target second, the other order from ln -s. When
/// link exists, also as a dangling link, it throws IOException, and when
/// the directory of link does not exist, it throws
/// DirectoryNotFoundException.
/// </summary>
public static string Make(string target, string link)
{
var info = File.CreateSymbolicLink(link, target);
return info.LinkTarget ?? throw new IOException($"not a symbolic link: {link}");
}
}
MakeSymlinkTests.cs 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
using Xunit;
public sealed class MakeSymlinkTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("make-symlink-").FullName;
public MakeSymlinkTests()
{
File.WriteAllText(Path.Combine(dir, "a.txt"), "alpha\n");
Directory.CreateDirectory(Path.Combine(dir, "sub"));
File.WriteAllText(Path.Combine(dir, "sub", "b.txt"), "beta\n");
}
public void Dispose() => Directory.Delete(dir, recursive: true);
public static TheoryData<string, string, string> Cases => new()
{
{ "file-target", "a.txt", "link" },
{ "directory-target", "sub", "link" },
{ "link-in-subdirectory", "b.txt", "sub/link" },
{ "dangling-target", "missing.txt", "link" },
{ "relative-target", "a.txt", "sub/link" },
{ "parent-target", "../a.txt", "sub/link" },
{ "name-with-spaces", "my notes.txt", "my link" },
{ "non-ascii-name", "café 日本.txt", "lien 日本" },
};
[Theory]
[MemberData(nameof(Cases))]
public void MakesTheLink(string name, string target, string rel)
{
string link = Path.Combine(dir, rel);
Assert.Equal(target, MakeSymlink.Make(target, link));
Assert.Equal(target, new FileInfo(link).LinkTarget);
Assert.True(name.Length > 0);
}
[Theory]
[InlineData("b.txt", "a.txt")]
[InlineData("a.txt", "sub")]
public void ExistingPathIsAnError(string target, string rel)
{
Assert.ThrowsAny<IOException>(() => MakeSymlink.Make(target, Path.Combine(dir, rel)));
Assert.Null(new FileInfo(Path.Combine(dir, rel)).LinkTarget);
}
[Fact]
public void DanglingLinkExists()
{
string link = Path.Combine(dir, "link");
File.CreateSymbolicLink(link, "missing.txt");
Assert.ThrowsAny<IOException>(() => MakeSymlink.Make("a.txt", link));
Assert.Equal("missing.txt", new FileInfo(link).LinkTarget);
}
[Fact]
public void MissingDirectory()
{
Assert.Throws<DirectoryNotFoundException>(
() => MakeSymlink.Make("a.txt", Path.Combine(dir, "nodir", "link")));
}
[Fact]
public void LinkReadsTarget()
{
MakeSymlink.Make("a.txt", Path.Combine(dir, "link"));
Assert.Equal("alpha\n", File.ReadAllText(Path.Combine(dir, "link")));
MakeSymlink.Make("../a.txt", Path.Combine(dir, "sub", "up"));
Assert.Equal("alpha\n", File.ReadAllText(Path.Combine(dir, "sub", "up")));
}
[Fact]
public void AbsoluteTarget()
{
string target = Path.Combine(dir, "a.txt");
Assert.Equal(target, MakeSymlink.Make(target, Path.Combine(dir, "link")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
import { readlink, symlink } from "node:fs/promises";
/**
* Makes a symbolic link at link that holds target, and returns the target
* that the link holds, read back with readlink. target is stored as it is:
* it need not exist, and a relative target is read from the directory of
* link. The third argument of symlink, the type, is read only on Windows.
* symlink rejects with EEXIST when link exists, also as a dangling link,
* and with ENOENT when the directory of link does not exist.
*/
export async function makeSymlink(target, link) {
await symlink(target, link);
return readlink(link);
}
makeSymlink.test.js 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
import assert from "node:assert/strict";
import { lstat, mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, test } from "node:test";
import { makeSymlink } from "./makeSymlink.js";
const cases = [
["file-target", "a.txt", "link"],
["directory-target", "sub", "link"],
["link-in-subdirectory", "b.txt", "sub/link"],
["dangling-target", "missing.txt", "link"],
["relative-target", "a.txt", "sub/link"],
["parent-target", "../a.txt", "sub/link"],
["name-with-spaces", "my notes.txt", "my link"],
["non-ascii-name", "café 日本.txt", "lien 日本"],
];
let dir;
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), "make-symlink-"));
await writeFile(join(dir, "a.txt"), "alpha\n");
await mkdir(join(dir, "sub"));
await writeFile(join(dir, "sub", "b.txt"), "beta\n");
});
afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
for (const [name, target, rel] of cases) {
test(name, async () => {
assert.equal(await makeSymlink(target, join(dir, rel)), target);
assert.ok((await lstat(join(dir, rel))).isSymbolicLink());
});
}
test("file and directory exist", async () => {
await assert.rejects(makeSymlink("b.txt", join(dir, "a.txt")), { code: "EEXIST" });
await assert.rejects(makeSymlink("a.txt", join(dir, "sub")), { code: "EEXIST" });
});
test("dangling link exists", async () => {
await symlink("missing.txt", join(dir, "link"));
await assert.rejects(makeSymlink("a.txt", join(dir, "link")), { code: "EEXIST" });
assert.equal(await readlink(join(dir, "link")), "missing.txt");
});
test("missing directory", async () => {
await assert.rejects(makeSymlink("a.txt", join(dir, "nodir", "link")), { code: "ENOENT" });
});
test("link reads target", async () => {
await makeSymlink("a.txt", join(dir, "link"));
assert.equal(await readFile(join(dir, "link"), "utf8"), "alpha\n");
await makeSymlink("../a.txt", join(dir, "sub", "up"));
assert.equal(await readFile(join(dir, "sub", "up"), "utf8"), "alpha\n");
});
test("absolute target", async () => {
const target = join(dir, "a.txt");
assert.equal(await makeSymlink(target, join(dir, "link")), target);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
import { readlink, symlink } from "node:fs/promises";
/**
* Makes a symbolic link at link that holds target, and returns the target
* that the link holds, read back with readlink. target is stored as it is:
* it need not exist, and a relative target is read from the directory of
* link. The third argument of symlink, the type, is read only on Windows.
* symlink rejects with EEXIST when link exists, also as a dangling link,
* and with ENOENT when the directory of link does not exist.
*/
export async function makeSymlink(target: string, link: string): Promise<string> {
await symlink(target, link);
return readlink(link);
}
makeSymlink.test.ts 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
import assert from "node:assert/strict";
import { lstat, mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, test } from "node:test";
import { makeSymlink } from "./makeSymlink.ts";
const cases = [
["file-target", "a.txt", "link"],
["directory-target", "sub", "link"],
["link-in-subdirectory", "b.txt", "sub/link"],
["dangling-target", "missing.txt", "link"],
["relative-target", "a.txt", "sub/link"],
["parent-target", "../a.txt", "sub/link"],
["name-with-spaces", "my notes.txt", "my link"],
["non-ascii-name", "café 日本.txt", "lien 日本"],
];
let dir: string;
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), "make-symlink-"));
await writeFile(join(dir, "a.txt"), "alpha\n");
await mkdir(join(dir, "sub"));
await writeFile(join(dir, "sub", "b.txt"), "beta\n");
});
afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});
for (const [name, target, rel] of cases) {
test(name, async () => {
assert.equal(await makeSymlink(target, join(dir, rel)), target);
assert.ok((await lstat(join(dir, rel))).isSymbolicLink());
});
}
test("file and directory exist", async () => {
await assert.rejects(makeSymlink("b.txt", join(dir, "a.txt")), { code: "EEXIST" });
await assert.rejects(makeSymlink("a.txt", join(dir, "sub")), { code: "EEXIST" });
});
test("dangling link exists", async () => {
await symlink("missing.txt", join(dir, "link"));
await assert.rejects(makeSymlink("a.txt", join(dir, "link")), { code: "EEXIST" });
assert.equal(await readlink(join(dir, "link")), "missing.txt");
});
test("missing directory", async () => {
await assert.rejects(makeSymlink("a.txt", join(dir, "nodir", "link")), { code: "ENOENT" });
});
test("link reads target", async () => {
await makeSymlink("a.txt", join(dir, "link"));
assert.equal(await readFile(join(dir, "link"), "utf8"), "alpha\n");
await makeSymlink("../a.txt", join(dir, "sub", "up"));
assert.equal(await readFile(join(dir, "sub", "up"), "utf8"), "alpha\n");
});
test("absolute target", async () => {
const target = join(dir, "a.txt");
assert.equal(await makeSymlink(target, join(dir, "link")), target);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
// Package makesymlink makes a symbolic link and reads its target back.
package makesymlink
import "os"
// MakeSymlink makes a symbolic link at link that holds target, and returns
// the target that the link holds, read back with os.Readlink. target is
// stored as it is: it need not exist, and a relative target is read from the
// directory of link. os.Symlink takes the target first and the new link
// second, as ln -s does. When link exists, also as a dangling link, the error
// matches fs.ErrExist, and when the directory of link does not exist, it
// matches fs.ErrNotExist.
func MakeSymlink(target, link string) (string, error) {
if err := os.Symlink(target, link); err != nil {
return "", err
}
return os.Readlink(link)
}
make_symlink_test.go 100 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
package makesymlink
import (
"errors"
"io/fs"
"os"
"path/filepath"
"testing"
)
func tree(t *testing.T) string {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("alpha\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, "sub"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "sub", "b.txt"), []byte("beta\n"), 0o644); err != nil {
t.Fatal(err)
}
return dir
}
func TestCases(t *testing.T) {
cases := []struct{ name, target, link string }{
{"file-target", "a.txt", "link"},
{"directory-target", "sub", "link"},
{"link-in-subdirectory", "b.txt", "sub/link"},
{"dangling-target", "missing.txt", "link"},
{"relative-target", "a.txt", "sub/link"},
{"parent-target", "../a.txt", "sub/link"},
{"name-with-spaces", "my notes.txt", "my link"},
{"non-ascii-name", "café 日本.txt", "lien 日本"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
link := filepath.Join(tree(t), c.link)
got, err := MakeSymlink(c.target, link)
if err != nil || got != c.target {
t.Fatalf("got %q, %v; want %q", got, err, c.target)
}
fi, err := os.Lstat(link)
if err != nil || fi.Mode().Type() != fs.ModeSymlink {
t.Fatalf("not a symbolic link: %v", err)
}
})
}
}
func TestExists(t *testing.T) {
dir := tree(t)
for _, rel := range []string{"a.txt", "sub"} {
if _, err := MakeSymlink("b.txt", filepath.Join(dir, rel)); !errors.Is(err, fs.ErrExist) {
t.Errorf("%s: got %v, want fs.ErrExist", rel, err)
}
}
}
func TestDanglingLinkExists(t *testing.T) {
link := filepath.Join(tree(t), "link")
if err := os.Symlink("missing.txt", link); err != nil {
t.Fatal(err)
}
if _, err := MakeSymlink("a.txt", link); !errors.Is(err, fs.ErrExist) {
t.Fatalf("got %v, want fs.ErrExist", err)
}
if got, _ := os.Readlink(link); got != "missing.txt" {
t.Fatalf("the link changed to %q", got)
}
}
func TestMissingDirectory(t *testing.T) {
if _, err := MakeSymlink("a.txt", filepath.Join(tree(t), "nodir", "link")); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("got %v, want fs.ErrNotExist", err)
}
}
func TestLinkReadsTarget(t *testing.T) {
dir := tree(t)
if _, err := MakeSymlink("../a.txt", filepath.Join(dir, "sub", "up")); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(dir, "sub", "up"))
if err != nil || string(data) != "alpha\n" {
t.Fatalf("got %q, %v", data, err)
}
}
func TestAbsoluteTarget(t *testing.T) {
dir := tree(t)
target := filepath.Join(dir, "a.txt")
if got, err := MakeSymlink(target, filepath.Join(dir, "link")); err != nil || got != target {
t.Fatalf("got %q, %v", got, err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
//! Make a symbolic link and read its target back.
use std::fs;
use std::io;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
/// Makes a symbolic link at `link` that holds `target`, and returns the
/// target that the link holds, read back with `fs::read_link`. The target is
/// stored as it is: it need not exist, and a relative target is read from the
/// directory of the link. `symlink` is in `std::os::unix::fs`, because
/// Windows has two calls, `symlink_file` and `symlink_dir`. When `link`
/// exists, also as a dangling link, the error kind is `AlreadyExists`, and
/// when the directory of `link` does not exist, it is `NotFound`.
pub fn make_symlink(target: impl AsRef<Path>, link: impl AsRef<Path>) -> io::Result<PathBuf> {
symlink(target, link.as_ref())?;
fs::read_link(link)
}
tests/make_symlink_test.rs 91 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-symbolic-link/.
use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use algo_create_a_symbolic_link::make_symlink;
struct Tree(PathBuf);
impl Tree {
fn new(name: &str) -> Tree {
let dir = std::env::temp_dir().join(format!("make-symlink-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("sub")).unwrap();
fs::write(dir.join("a.txt"), "alpha\n").unwrap();
fs::write(dir.join("sub/b.txt"), "beta\n").unwrap();
Tree(dir)
}
fn path(&self, rel: &str) -> PathBuf {
self.0.join(rel)
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn cases() {
let cases = [
("file-target", "a.txt", "link"),
("directory-target", "sub", "link"),
("link-in-subdirectory", "b.txt", "sub/link"),
("dangling-target", "missing.txt", "link"),
("relative-target", "a.txt", "sub/link"),
("parent-target", "../a.txt", "sub/link"),
("name-with-spaces", "my notes.txt", "my link"),
("non-ascii-name", "café 日本.txt", "lien 日本"),
];
for (name, target, rel) in cases {
let tree = Tree::new(name);
let link = tree.path(rel);
assert_eq!(make_symlink(target, &link).unwrap(), Path::new(target), "{name}");
assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "{name}");
}
}
#[test]
fn exists() {
let tree = Tree::new("exists");
for rel in ["a.txt", "sub"] {
let err = make_symlink("b.txt", tree.path(rel)).unwrap_err();
assert_eq!(err.kind(), ErrorKind::AlreadyExists, "{rel}");
}
}
#[test]
fn dangling_link_exists() {
let tree = Tree::new("dangling");
symlink("missing.txt", tree.path("link")).unwrap();
let err = make_symlink("a.txt", tree.path("link")).unwrap_err();
assert_eq!(err.kind(), ErrorKind::AlreadyExists);
assert_eq!(fs::read_link(tree.path("link")).unwrap(), Path::new("missing.txt"));
}
#[test]
fn missing_directory() {
let tree = Tree::new("missing");
let err = make_symlink("a.txt", tree.path("nodir/link")).unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
}
#[test]
fn link_reads_target() {
let tree = Tree::new("reads");
make_symlink("../a.txt", tree.path("sub/up")).unwrap();
assert_eq!(fs::read_to_string(tree.path("sub/up")).unwrap(), "alpha\n");
}
#[test]
fn absolute_target() {
let tree = Tree::new("absolute");
let target = tree.path("a.txt");
assert_eq!(make_symlink(&target, tree.path("link")).unwrap(), target);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-symbolic-link/.
# make_symlink TARGET LINK
# Makes a symbolic link at LINK that holds TARGET, and prints the target that
# the link holds, read back with readlink. TARGET is stored as it is: it need
# not exist, and a relative target is read from the directory of LINK. When
# LINK names a directory, ln -s makes the link inside that directory, so the
# function checks LINK first. -e follows a link, so -L also checks for a
# dangling link. Another process can make LINK between the check and ln; then
# ln fails, or with a directory it makes the link inside it. The function
# returns status 1 when LINK exists or when ln fails.
make_symlink() {
local target=$1 link=$2
if [[ -e $link || -L $link ]]; then
printf 'make_symlink: %s: File exists\n' "$link" >&2
return 1
fi
ln -s -- "$target" "$link" || return 1
readlink -- "$link"
}
test_make_symlink.bats 76 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-symbolic-link/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/make_symlink.sh"
dir=$BATS_TEST_TMPDIR
printf 'alpha\n' >"$dir/a.txt"
mkdir "$dir/sub"
printf 'beta\n' >"$dir/sub/b.txt"
}
@test "file-target" {
[ "$(make_symlink a.txt "$dir/link")" = a.txt ]
[ -L "$dir/link" ]
}
@test "directory-target" {
[ "$(make_symlink sub "$dir/link")" = sub ]
[ -L "$dir/link" ]
}
@test "link-in-subdirectory" {
[ "$(make_symlink b.txt "$dir/sub/link")" = b.txt ]
}
@test "dangling-target" {
[ "$(make_symlink missing.txt "$dir/link")" = missing.txt ]
[ -L "$dir/link" ]
[ ! -e "$dir/link" ]
}
@test "relative-target" {
[ "$(make_symlink a.txt "$dir/sub/link")" = a.txt ]
[ ! -e "$dir/sub/link" ]
}
@test "parent-target" {
[ "$(make_symlink ../a.txt "$dir/sub/link")" = ../a.txt ]
[ "$(cat "$dir/sub/link")" = alpha ]
}
@test "name-with-spaces" {
[ "$(make_symlink 'my notes.txt' "$dir/my link")" = 'my notes.txt' ]
}
@test "non-ascii-name" {
[ "$(make_symlink 'café 日本.txt' "$dir/lien 日本")" = 'café 日本.txt' ]
}
@test "a file exists" {
run -1 make_symlink b.txt "$dir/a.txt"
[ ! -L "$dir/a.txt" ]
}
@test "a directory exists, and no link is made in it" {
run -1 make_symlink a.txt "$dir/sub"
[ ! -e "$dir/sub/a.txt" ]
[ ! -L "$dir/sub/a.txt" ]
}
@test "a dangling link exists" {
ln -s missing.txt "$dir/link"
run -1 make_symlink a.txt "$dir/link"
[ "$(readlink "$dir/link")" = missing.txt ]
}
@test "missing directory" {
run -1 make_symlink a.txt "$dir/nodir/link"
}
@test "absolute target" {
[ "$(make_symlink "$dir/a.txt" "$dir/link")" = "$dir/a.txt" ]
}
References
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), symlink, symlinkat, DESCRIPTION, ERRORS
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), readlink, readlinkat, DESCRIPTION
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), ln, DESCRIPTION
- Linux manual page, symlink(7), DESCRIPTION
- Windows API reference, CreateSymbolicLinkW function (winbase.h), Parameters (dwFlags), Remarks
- The Python Standard Library, os, Miscellaneous operating system interfaces, os.symlink, os.readlink
- The Python Standard Library, os.path, Common pathname manipulations, os.path.exists, os.path.lexists
- Node.js documentation, File system, fsPromises.symlink(target, path[, type])
- Java SE 25 API, Files, createSymbolicLink, readSymbolicLink
- .NET API reference, File.CreateSymbolicLink(String, String) Method, Parameters, Exceptions
- Go standard library, package os, func Symlink, func Readlink, type LinkError
- The Rust Standard Library, std::os::unix::fs::symlink, Description
- cppreference, std::filesystem::create_symlink, create_directory_symlink, 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag AC2QN9 Edit this page History Report an error Markdown