Directories in Groovy

Here’s the translation of the Go code to Groovy, along with explanations in Markdown format suitable for Hugo:

Our first program will demonstrate working with directories in Groovy. Here’s the full source code:

import groovy.io.FileType

// Helper function to check for errors
def check(Closure closure) {
    try {
        closure()
    } catch (Exception e) {
        println "Error: ${e.message}"
        System.exit(1)
    }
}

// Create a new sub-directory in the current working directory
check { new File("subdir").mkdir() }

// When creating temporary directories, it's good practice to delete them afterward
Runtime.runtime.addShutdownHook(new Thread({ new File("subdir").deleteDir() }))

// Helper function to create a new empty file
def createEmptyFile = { String name ->
    check { new File(name).text = '' }
}

createEmptyFile("subdir/file1")

// We can create a hierarchy of directories, including parents
check { new File("subdir/parent/child").mkdirs() }

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

// list directory contents
def parentDir = new File("subdir/parent")
println "Listing subdir/parent"
parentDir.eachFile { file ->
    println " ${file.name} ${file.isDirectory()}"
}

// Change the current working directory
check { System.setProperty("user.dir", new File("subdir/parent/child").absolutePath) }

// Now we'll see the contents of subdir/parent/child when listing the current directory
def currentDir = new File(".")
println "Listing subdir/parent/child"
currentDir.eachFile { file ->
    println " ${file.name} ${file.isDirectory()}"
}

// Change back to where we started
check { System.setProperty("user.dir", new File("../../..").absolutePath) }

// We can also visit a directory recursively, including all its sub-directories
println "Visiting subdir"
new File("subdir").eachFileRecurse(FileType.ANY) { file ->
    println " ${file.path} ${file.isDirectory()}"
}

This Groovy script demonstrates various operations with directories:

  1. We start by creating a new subdirectory.
  2. We use a shutdown hook to ensure the created directory is deleted when the script exits.
  3. We create empty files in different directories.
  4. We list the contents of directories.
  5. We change the current working directory and list its contents.
  6. Finally, we recursively visit all files and directories in the created structure.

To run this script, save it as directories.groovy and execute it using the Groovy command:

$ groovy directories.groovy
Listing subdir/parent
 child true
 file2 false
 file3 false
Listing subdir/parent/child
 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 script demonstrates how to work with directories in Groovy, including creating, listing, and traversing directory structures.