Directories in PureScript

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

Our first program will work with directories in the file system. Here’s the full source code:

module Main where

import Prelude

import Effect (Effect)
import Effect.Console (log)
import Node.FS.Sync as FS
import Node.Path (FilePath)
import Node.Process (cwd)
import Data.Either (Either(..))

main :: Effect Unit
main = do
  -- Create a new sub-directory in the current working directory
  FS.mkdir "subdir"

  -- Helper function to create a new empty file
  let createEmptyFile :: FilePath -> Effect Unit
      createEmptyFile name = FS.writeTextFile FS.UTF8 name ""

  createEmptyFile "subdir/file1"

  -- Create a hierarchy of directories, including parents
  FS.mkdir' "subdir/parent/child" { recursive: true, mode: FS.mkPerms FS.all FS.all FS.all }

  createEmptyFile "subdir/parent/file2"
  createEmptyFile "subdir/parent/file3"
  createEmptyFile "subdir/parent/child/file4"

  -- List directory contents
  contents <- FS.readdir "subdir/parent"
  log "Listing subdir/parent"
  traverse_ (\entry -> log $ " " <> entry) contents

  -- Change the current working directory
  FS.chdir "subdir/parent/child"

  -- List contents of the current directory
  currentContents <- FS.readdir "."
  log "Listing subdir/parent/child"
  traverse_ (\entry -> log $ " " <> entry) currentContents

  -- Change back to the original directory
  FS.chdir "../../.."

  -- Recursively visit a directory
  log "Visiting subdir"
  visitDir "subdir"

visitDir :: FilePath -> Effect Unit
visitDir dir = do
  contents <- FS.readdir dir
  traverse_ (\entry -> do
    let path = dir <> "/" <> entry
    stat <- FS.stat path
    log $ " " <> path <> " " <> show stat.isDirectory
    when stat.isDirectory $ visitDir path
  ) contents

To run the program, save it as Directories.purs and use spago run.

$ spago run
Listing subdir/parent
  child
  file2
  file3
Listing subdir/parent/child
  file4
Visiting subdir
  subdir true
  subdir/file1 false
  subdir/parent true
  subdir/parent/child true
  subdir/parent/child/file4 false
  subdir/parent/file2 false
  subdir/parent/file3 false

This PureScript code demonstrates working with directories:

  1. We use the Node.FS.Sync module for file system operations.
  2. mkdir creates a new directory.
  3. mkdir' creates a directory hierarchy (similar to mkdir -p).
  4. readdir lists directory contents.
  5. chdir changes the current working directory.
  6. We implement a recursive visitDir function to walk through directories.

Note that PureScript, being a functional language, handles effects differently from imperative languages. The Effect monad is used to represent side effects, and we use do notation for sequencing these effects.

Also, error handling in this example is simplified. In a production environment, you’d want to handle potential errors more robustly.