Groovy Pipes

Here’s an example on OS X, using the build-in OS X artifical feline
intelligence simulation program, otherwise known as “cat”.

def cat = 'cat'.execute()

Thread.start { System.out << cat.in }
Thread.start { System.err << cat.err }

cat << "Meow, World!n"

cat.out.close()
cat.waitForOrKill(0)

That is rougly translated to…

// Execute cat.
def cat = 'cat'.execute()

// Direct the output, which is an (in)put buffer, to stdout.
Thread.start { System.out << cat.in }

// Direct the error output, which is also an input buffer, to stderr.
Thread.start { System.err << cat.err }

// Pipe a string value to the executable's stdin.
cat << "Meow, World!n"

// Close the executables stdin.
cat.out.close()

// Wait until the the executable exits before proceeding.
cat.waitForOrKill(0)
[alan@tno ~] groovy cat.groovy
[alan@tno ~] Meow, World!

In Groovy in is out, and out is in, it seems. Awkward for a shell
programmer, so take note.

Here’s one that looks at program output.

'echo Meow, World!'.execute().in.eachLine {
    println ((it =~ /Meow/).replaceFirst('Hello'))
}
[alan@tno ~] groovy echo.groovy
[alan@tno ~] Hello, World!

In Groovy in is out, and out is in, it seems. Awkward for a shell
programmer, so take note.

Here’s one that looks at program output.

'echo Meow, World!'.execute().in.eachLine {
    println ((it =~ /Meow/).replaceFirst('Hello'))
}
[alan@tno ~] groovy echo.groovy
[alan@tno ~] Hello, World!

A universal translator, for cats, in Groovy.

I find there’s little need for fancy Java/Subversion bindings. With
Groovy you can use the well-defined input and output from the
command line utilitites instead.

'svn status'.execute().in.eachLine {
    if (it.charAt(0) == '?') {
        println "Don't forget to add ${it.substring(7)} to Subversion!"
    }
}
[alan@tno ~] groovy status.groovy
[alan@tno ~] Don't forget to add super-secret-diary.txt to Subversion!

Let's put it all together for a cat simulator test case.

<pre><code allow="none">
def cat = 'cat'.execute()

Thread.start {
    cat.in.eachLine {
        if (!(it == "Meow" || it == "Purr")) {
            println "Cats don't say ${it}!"
        }
    }
}

Thread.start { System.err << cat.err }

cat << "Meown"
cat << "Purrn"
cat << "Lasagnan"

cat.out.close()
cat.waitForOrKill(0)
[alan@tno ~] groovy cat.listen.groovy
[alan@tno ~] Cat's don't say Lasagna!

Leave a Reply