File Paths in PureScript

Here’s the translation of the Go code example to PureScript, formatted in Markdown suitable for Hugo:

Our example demonstrates working with file paths in PureScript. The Data.Path.Filename module provides functions to parse and construct file paths in a way that is portable between operating systems.

module Main where

import Prelude

import Data.Path.Filename as Path
import Data.String as String
import Effect (Effect)
import Effect.Console (log)

main :: Effect Unit
main = do
  -- `joinPath` should be used to construct paths in a
  -- portable way. It takes an array of path segments
  -- and constructs a hierarchical path from them.
  let p = Path.joinPath ["dir1", "dir2", "filename"]
  log $ "p: " <> p

  -- You should always use `joinPath` instead of
  -- concatenating "/" or "\" manually. In addition
  -- to providing portability, `joinPath` will also
  -- normalize paths by removing superfluous separators
  -- and directory changes.
  log $ Path.joinPath ["dir1//", "filename"]
  log $ Path.joinPath ["dir1/../dir1", "filename"]

  -- `dirname` and `basename` can be used to split a path to the
  -- directory and the file.
  log $ "dirname(p): " <> Path.dirname p
  log $ "basename(p): " <> Path.basename p

  -- We can check whether a path is absolute.
  log $ show $ Path.isAbsolute "dir/file"
  log $ show $ Path.isAbsolute "/dir/file"

  let filename = "config.json"

  -- Some file names have extensions following a dot. We
  -- can split the extension out of such names with `extname`.
  let ext = Path.extname filename
  log $ show ext

  -- To find the file's name with the extension removed,
  -- use `String.dropRight`.
  log $ String.dropRight (String.length ext) filename

  -- `relativeTo` finds a relative path between a base and a
  -- target. It returns `Nothing` if the target cannot
  -- be made relative to base.
  case Path.relativeTo "a/b" "a/b/t/file" of
    Just rel -> log $ show rel
    Nothing -> log "Cannot make path relative"

  case Path.relativeTo "a/b" "a/c/t/file" of
    Just rel -> log $ show rel
    Nothing -> log "Cannot make path relative"

To run the program, save it as FilePaths.purs and use the PureScript compiler (psc) to compile it, then run it with Node.js:

$ psc FilePaths.purs -o output.js
$ node -e "require('./output.js').main()"
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 example demonstrates how to work with file paths in PureScript, including joining paths, extracting directory and file names, checking for absolute paths, handling file extensions, and finding relative paths. The Data.Path.Filename module provides a set of functions that are similar to the filepath package in other languages, allowing for portable and consistent file path manipulation across different operating systems.