Task Runners are a way to automate anything you want from the command line using CFML! You write any sort of logic you want, just like you would with bash scripts, Node, or Python, except you can do it with your favorite language. Task Runners come with dozens of helpful utilities for downloading files, interacting with the user, printing formatted text, and interacting with the file system. Task Runners only require CommandBox to be installed and work great inside Docker as well. We'll cover many of the features available including using modules and lifecycle methods!
2. #FreeCFML
● CFML is for templating HTML
● Only usable with a web server
● Must install server
● Only access via HTTP
3. #FreeCFML
● CFML runs anywhere the JVM does
● JSR-223
● Can be used for embedded devices
● Run from the command line
● Outside of a servlet container
● Put it on a Raspberry Pi!
17. Task Runners
● Does (most) everything a custom command does
● It’s a single CFC
● Portable
● No installation
● Easy to distribute
● Can have more than one target (like Ant)
● Replaces other build tools like Ant, Shell, or Grunt
● Doesn’t require any server to be started
18. Task Runner features
● Very little boilerplate
● Pure CLI execution (of CFML)
● Built in parameter handling
● CLI interactivity with user
● ANSI color formatting
● Access to file globbing/watchers/etc
● Can also run commands or native OS binaries
● Easy output helpers
21. Task Runner Anatomy
● Default filename is Task.cfc
● Default method (target) is run()
● But you can call them whatever you want!
CommandBox> task run myTask
CommandBox> task run myTask myTarget
23. Task Runner Parameters
● Named or positional
● Task named params start with :
● Flags work, but need : as well
task run task.cfc run value1 value2
task run :param1=value1 :param2=value2
task run myTask --:force
24. Task Runner Class Hierarchy
─┬ commandbox.system.BaseCommand - Base task for all custom commands
└─┬ commandbox.system.BaseTask - base task for all task runners
└── task - Your custom task runner
25. Task Runner Properties
● wirebox - WireBox injector
● CR - carriage return ( char(10) )
● formatterUtil - Formatter Utility
● fileSystemUtil - File System Utility
● shell - CLI Shell class
● print - Print helper
● logBox - LogBox factory
● logger - LogBox logger named after this CFC
● parser - CLI Parser class
● configService - Config Setting Service
● SystemSettings - System Setting helper
● job - Interactive Job
● thisThread - A reference to the current running java.lang.Thread
● asyncManager - WireBox's AsyncManager class
26. Task Runner Methods
// Returns the AsyncManager class
async()
// Convenience method for getting stuff from WireBox
getInstance( name, dsl, initArguments={}, targetObject='' )
// Retuns current exit code
getExitCode()
// Sets exit code to be returned when task completes
setExitCode( required numeric exitCode )
// Returns the current working directory of the shell
getCWD()
// ask the user a question and wait for response
ask( message, string mask='', string defaultResponse='', keepHistory=false, highlight=true, complete=false )
// Wait until the user's next keystroke amd return the char code
waitForKey( message='' )
// Ask the user a question looking for a yes/no response and return a boolean
confirm( required message )
27. Task Runner Methods
// Intiator for multiselect DSL. (Check "task interactiviy" page in docs)
multiSelect()
// Run another command by name.
runCommand( required command, returnOutput=false )
// Intiator for Command DSL. (Check "running other commands" page in docs)
command( required name )
// Intiator for directory watcher DSL. (Check "Watchers" page in docs)
watch()
// This resolves an absolute or relative path using the rules of the operating system and CLI.
resolvePath( required string path, basePath=shell.pwd() )
// Intiator for globber DSL (check "Using file globs" page in docs)
globber( pattern='' )
// Intiator for PropertyFile DSL (check "property files" page in docs)
propertyFile( propertyFilePath='' )
// Report error in your task. Raises an exception that will not print the stack trace
error( required message, detail='', clearPrintBuffer=false, exitCode=1 )
28. Task Runner Methods
// Returns true if current exit code is not 0.
hasError()
// Open a file or folder externally in the default editor for the user.
openPath( path )
// Open a URL in the user's browser
openURL( theURL, browser='' )
// Set a CommandBox environment variable
setSystemSetting( required string key, string value )
// Retrieve a Java System property or env value by name.
getSystemSetting( required string key, defaultValue )
// Retrieve a Java System property by name.
getSystemProperty( required string key, defaultValue )
// Retrieve an env value by name.
getEnv( required string key, defaultValue )
29. Task Runner Methods
// Call this method periodically in a long-running task to check and see
// if the user has hit Ctrl-C. This method will throw an UserInterruptException
// which you should not catch. It will unroll the stack all the way back to the shell
checkInterrupted( thisThread=variables.thisThread )
// Loads up Java classes into the class loader that loaded the CLI for immediate use.
// (Check "Loading Ad hoc Jars" page in docs)
classLoad( paths )
// Get the current java.lang.Thread object
getCurrentThread()
// Get the current thread name
getThreadName()
30. Task Runner Output
● Use “print” helper
● Chain methods
● Method names are dynamic
print.line( 'I like Spam.' );
print.line();
print.redLine( "..." );
print.blueText( "..." );
38. Task Runner Shell Integration
getCWD() // current working directory
shell.clearScreen()
shell.getTermWidth() // In characters
shell.getTermHeight() // In characters
43. Running other Tasks
// Call “run” target of “task.cfc”
task().run();
// Call “compile” method on “build.cfc”
task( 'build' )
.target( 'compile' )
.run();
// Call “run” method on “mytask.cfc”, passing in args
task( 'mytask' )
.params( path='/my/path', newPath='/my/new/path' )
.run();
44. Downloading Files
property name="progressableDownloader" inject="ProgressableDownloader";
property name="progressBar" inject="ProgressBar";
...
progressableDownloader.download(
'http://site.com/fileToDownload.zip',
'C:/path/to/fileWeDownloaded.zip',
// This callback fires every 1024K of downloaded bytes
function( status ) {
progressBar.update( argumentCollection = status );
}
);
45. Erroring Out
error( "I don't like your tone of voice" );
error(
message="We could not fufill your order",
detail="The ice cream machine is down (again)",
exitCode=666
);
49. Lifecycle Events
● preTask - Before any target in the task
● postTask - After any target in the task
● aroundTask - Wraps execution of any target in the task
● pre<targetName> - Before a specific target (Ex: preRun)
● post<targetName> - After a specific target (Ex: postRun)
● around<targetName> - Wraps execution of a specific target (Ex:
aroundRun)
● onComplete - Fires regardless of exit status
● onSuccess - Fires when task runs without failing exit code or exception
● onFail - Fires if exit code is failing after the action is done.
● onError - fires only if an unhandled exception is thrown and receives
exception object.
● onCancel - Fires when the task is interrupted with Ctrl-C
50. Lifecycle Events
component {
function preTask() {
// Some setup here
}
function run() {
print.line( 'Target is running' );
}
function onComplete() {
// Some cleanup here
}
function onFail(){
log.error( 'There was an issue!' )
}
}
51. Interactive Jobs
● Creates organized output on page when completing
several job steps
● Allows for debug logging which is hidden on
successful execution, but visible when erroring
● Works well with progress bars
● Allows tracking nested operations
● You’re used to seeing this in the output of “server
start” and “install”
52. Interactive Jobs
job.start( 'This is my job to run' );
job.addLog( 'Still going...' );
job.addLog( "Now we're getting somewhere." );
job.addLog( 'Almost done!' );
job.complete();
53. Interactive Jobs
job.start( 'Starting server' );
job.addLog( 'This is the server name' );
job.addWarnLog( "Hey, don't touch that dial" );
job.start( 'Installing CF Engine first' );
job.addLog( 'This was the version used' );
job.addLog( "Yeah, we're done" );
job.complete();
job.addLog( "Aaand, we're back!." );
job.addErrorLog( "I think we're going to crash" );
job.error( "Didn't see that coming" );
54. Property Files
// Create and load property file object
propertyFile( 'myFile.properties' )
.set( 'my.new.property', 'my value' )
.store();
// Get a property
var value = propertyFile( 'myFile.properties' )
.get( 'existing.property' );
// Create one from scratch
propertyFile()
.set( 'brad', 'wood' )
.store( 'myFile.properties' );