File Paths in Chapel

The Path module in Chapel provides functions to parse and construct file paths in a way that is portable between operating systems.

use Path;
use IO;

proc main() {
    // `joinPath` should be used to construct paths in a portable way.
    // It takes any number of arguments and constructs a hierarchical path from them.
    var p = joinPath("dir1", "dir2", "filename");
    writeln("p: ", p);

    // You should always use `joinPath` instead of concatenating
    // separators manually. In addition to providing portability,
    // `joinPath` will also normalize paths by removing superfluous
    // separators and directory changes.
    writeln(joinPath("dir1//", "filename"));
    writeln(joinPath("dir1/../dir1", "filename"));

    // `dirname` and `basename` can be used to split a path to the
    // directory and the file.
    writeln("dirname(p): ", dirname(p));
    writeln("basename(p): ", basename(p));

    // We can check whether a path is absolute.
    writeln(isAbsPath("dir/file"));
    writeln(isAbsPath("/dir/file"));

    var filename = "config.json";

    // Some file names have extensions following a dot. We can split
    // the extension out of such names with `splitExt`.
    var (name, ext) = splitExt(filename);
    writeln(ext);

    // To find the file's name with the extension removed, we can use
    // the `name` part from `splitExt`.
    writeln(name);

    // `relPath` finds a relative path between a base and a target.
    // It returns an empty string if the target cannot be made relative to base.
    var rel = relPath("a/b", "a/b/t/file");
    writeln(rel);

    rel = relPath("a/b", "a/c/t/file");
    writeln(rel);
}

To run the program, save it as file_paths.chpl and use the Chapel compiler:

$ chpl file_paths.chpl -o file_paths
$ ./file_paths
p: dir1/dir2/filename
dir1/filename
dir1/filename
dirname(p): dir1/dir2
basename(p): filename
false
true
.json
config
t/file
../c/t/file

This Chapel code demonstrates the usage of various path-related functions from the Path module, which provide similar functionality to Go’s filepath package. The joinPath function is used for path construction, dirname and basename for path splitting, isAbsPath for checking absolute paths, splitExt for handling file extensions, and relPath for finding relative paths.

Note that Chapel’s path functions may have slightly different names or behaviors compared to Go, but they serve similar purposes in handling file paths in a cross-platform manner.