Directories in Crystal

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

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

require "file_utils"

def check(e)
  raise e if e
end

def main
  # Create a new sub-directory in the current working directory.
  Dir.mkdir("subdir", 0o755)

  # When creating temporary directories, it's good practice to
  # ensure their removal. `FileUtils.rm_rf` will delete a whole
  # directory tree (similarly to `rm -rf`).
  at_exit { FileUtils.rm_rf("subdir") }

  # Helper function to create a new empty file.
  create_empty_file = ->(name : String) do
    File.write(name, "")
  end

  create_empty_file.call("subdir/file1")

  # We can create a hierarchy of directories, including parents
  # with `mkdir_p`. This is similar to the command-line `mkdir -p`.
  Dir.mkdir_p("subdir/parent/child", 0o755)

  create_empty_file.call("subdir/parent/file2")
  create_empty_file.call("subdir/parent/file3")
  create_empty_file.call("subdir/parent/child/file4")

  # `Dir.entries` lists directory contents, returning an array of
  # file and directory names.
  c = Dir.entries("subdir/parent")

  puts "Listing subdir/parent"
  c.each do |entry|
    puts " #{entry} #{File.directory?("subdir/parent/#{entry}")}"
  end

  # `Dir.cd` lets us change the current working directory,
  # similarly to `cd`.
  Dir.cd("subdir/parent/child")

  # Now we'll see the contents of `subdir/parent/child` when
  # listing the current directory.
  c = Dir.entries(".")

  puts "Listing subdir/parent/child"
  c.each do |entry|
    puts " #{entry} #{File.directory?(entry)}"
  end

  # Change back to where we started.
  Dir.cd("../../..")

  # We can also visit a directory recursively, including all its
  # sub-directories. `Dir.walk` yields each file or directory path.
  puts "Visiting subdir"
  Dir.walk("subdir") do |path|
    puts " #{path} #{File.directory?(path)}"
  end
end

main

To run the program, save it as directories.cr and use the Crystal compiler:

$ crystal run directories.cr
Listing subdir/parent
 . true
 .. true
 child true
 file2 false
 file3 false
Listing subdir/parent/child
 . true
 .. true
 file4 false
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 program demonstrates various operations with directories in Crystal:

  1. Creating directories with Dir.mkdir and Dir.mkdir_p
  2. Listing directory contents with Dir.entries
  3. Changing the current working directory with Dir.cd
  4. Walking a directory tree recursively with Dir.walk
  5. Checking if a path is a directory with File.directory?
  6. Creating empty files
  7. Cleaning up temporary directories using at_exit

Crystal’s standard library provides a rich set of tools for working with the file system, making it easy to perform common directory operations.