• Stars
    star
    336
  • Rank 125,564 (Top 3 %)
  • Language
    Shell
  • Created about 8 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Repository for the Taskfile template.

Taskfile

This repository contains the default Taskfile template for getting started in your own projects. A Taskfile is a bash (or zsh etc.) script that follows a specific format. It's called Taskfile, sits in the root of your project (alongside your package.json) and contains the tasks to build your project.

#!/bin/bash
PATH=./node_modules/.bin:$PATH

function install {
    npm install
}

function build {
    webpack
}

function start {
    build # Call task dependency
    python -m SimpleHTTPServer 9000
}

function test {
    mocha test/**/*.js
}

function default {
    # Default task to execute
    start
}

function help {
    echo "$0 <task> <args>"
    echo "Tasks:"
    compgen -A function | cat -n
}

TIMEFORMAT="Task completed in %3lR"
time ${@:-default}

And to run a task:

$ run build
Hash: 31b6167c7c8f2920e0d2
Version: webpack 2.1.0-beta.25
Time: 4664ms
   Asset     Size  Chunks             Chunk Names
index.js  1.96 MB       0  [emitted]  index
    + 353 hidden modules
Task completed in 0m5.008s

Install

To "install", add the following to your .bashrc or .zshrc (or .whateverrc):

# Quick start with the default Taskfile template
alias run-init="curl -so Taskfile https://raw.githubusercontent.com/adriancooney/Taskfile/master/Taskfile.template && chmod +x Taskfile"

# Run your tasks like: run <task>
alias run=./Taskfile

Usage

Open your directory and run run-init to add the default Taskfile template to your project directory:

$ cd my-project
$ run-init

Open the Taskfile and add your tasks. To run tasks, use run:

$ run help
./Taskfile <task> <args>
Tasks:
     1  build
     2  build-all
     3  help
Task completed in 0m0.005s

Techniques

Arguments

Let’s pass some arguments to a task. Arguments are accessible to the task via the $1, $2, $n.. variables. Let’s allow us to specify the port of the HTTP server:

#!/bin/bash

function serve {
  python -m SimpleHTTPServer $1
}

"$@"

And if we run the serve task with a new port:

$ ./Taskfile serve 9090
Serving HTTP on 0.0.0.0 port 9090 ...

Using npm Packages

One of the most powerful things about npm run-scripts (who am I kidding, it’s definitely the most powerful thing) is the ability to use the CLI interfaces for many of the popular packages on npm such as babel or webpack. The way npm achieves this is by extending the search PATH for binaries to include ./node_modules/.bin. We can do this to very easily too by extending the PATH at the top of our Taskfile to include this directory. This will enable us to use our favourite binaries just like we would in an npm run-script:

#!/bin/bash
PATH=./node_modules/.bin:$PATH

function serve {
  python -m SimpleHTTPServer $1
}

function build {
  webpack src/index.js --output-path build/
}

function lint {
  eslint src
}

function test {
  mocha src/**/*.js
}

"$@"

Task Dependencies

Sometimes tasks depend on other tasks to be completed before they can start. To add another task as a dependency, simply call the task's function at the top of the dependant task's function.

#!/bin/bash
PATH=./node_modules/.bin:$PATH

function clean {
  rm -r build dist
}

function build {
  webpack src/index.js --output-path build/
}

function minify {
  uglify build/*.js dist/
}

function deploy {
  clean && build && minify
  scp dist/index.js [email protected]:/top-secret/index.js
}

"$@"

Parallelisation

To run tasks in parallel, you can us Bash’s & operator in conjunction with wait. The following will build the two tasks at the same time and wait until they’re completed before exiting.

#!/bin/bash
PATH=./node_modules/.bin:$PATH

function build {
    echo "beep $1 boop"
    sleep 1
    echo "built $1"
}

function build-all {
    build web & build mobile &
    wait
}

"$@"

And execute the build-all task:

$ run build-all
beep web boop
beep mobile boop
built web
built mobile

Default task

To make a task the default task called when no arguments are passed, we can use bash’s default variable substitution ${VARNAME:-<default value>} to return default if $@ is empty.

#!/bin/bash
PATH=./node_modules/.bin:$PATH

function build {
    echo "beep boop built"
}

function default {
    build
}

"${@:-default}"

Now when we run ./Taskfile, the default function is called.

Runtime Statistics

To add some nice runtime statistics like Gulp so you can keep an eye on build times, we use the built in time and pass if a formatter.

#!/bin/bash
PATH=./node_modules/.bin:$PATH

function build {
    echo "beep boop built"
    sleep 1
}

function default {
    build
}

TIMEFORMAT="Task completed in %3lR"
time ${@:-default}

And if we execute the build task:

$ ./Taskfile build 
beep boop built 
Task completed in 0m1.008s

Help

The final addition I recommend adding to your base Taskfile is the task which emulates, in a much more basic fashion, (with no arguments). It prints out usage and the available tasks in the Taskfile to show us what tasks we have available to ourself.

The compgen -A function is a bash builtin that will list the functions in our Taskfile (i.e. tasks). This is what it looks like when we run the task:

$ ./Taskfile help
./Taskfile <task> <args>
Tasks:
     1  build
     2  default
     3  help
Task completed in 0m0.005s

task: namespace

If you find you need to breakout some code into reusable functions that aren't tasks by themselves and don't want them cluttering your help output, you can introduce a namespace to your task functions. Bash is pretty lenient with it's function names so you could, for example, prefix a task function with task:. Just remember to use that namespace when you're calling other tasks and in your task:$@ entrypoint!

#!/bin/bash
PATH=./node_modules/.bin

function task:build-web {
    build-target web
}

function task:build-desktop {
    build-target desktop
}

function build-target {
    BUILD_TARGET=$1 webpack --production
}

function task:default {
    task:help
}

function task:help {
    echo "$0 <task> <args>"
    echo "Tasks:"

    # We pick out the `task:*` functions
    compgen -A function | sed -En 's/task:(.*)/\1/p' | cat -n
}

TIMEFORMAT="Task completed in %3lR"
time "task:${@:-default}"

Executing tasks

So typing out ./Taskfile every time you want to run a task is a little lousy. just flows through the keyboard so naturally that I wanted something better. The solution for less keystrokes was dead simple: add an alias for run (or task, whatever you fancy) and stick it in your .zshrc. Now, it now looks the part.

$ alias run=./Taskfile
$ run build
beep boop built
Task completed in 0m1.008s

Quickstart

Alongside my run alias, I also added a run-init to my .zshrc to quickly get started with a new Taskfile in a project. It downloads a small Taskfile template to the current directory and makes it executable:

$ alias run-init="curl -so Taskfile https://medium.com/r/?url=https%3A%2F%2Fraw.githubusercontent.com%2Fadriancooney%2FTaskfile%2Fmaster%2FTaskfile.template && chmod +x Taskfile"

$ run-init
$ run build
beep boop built
Task completed in 0m1.008s

Importing from npm

If you've the incredible jq installed (you should, it's so useful), here's a handy oneliner to import your scripts from your package.json into a fresh Taskfile. Copy and paste this into your terminal with your package.json in the working directory:

run-init && (head -n 3 Taskfile && jq -r '.scripts | to_entries[] | "function \(.["key"]) {\n    \(.["value"])\n}\n"' package.json | sed -E 's/npm run ([a-z\:A-Z]+)/\1/g' && tail -n 8 Taskfile) > Taskfile.sh && mv Taskfile.sh Taskfile && chmod +x Taskfile 

And the importer explained:

$ run-init && \ # Download a fresh Taskfile template
    (
        head -n 3 Taskfile && \ # Take the Taskfile template header
        # Extract the scripts using JQ and create bash task functions
        jq -r '.scripts | to_entries[] | "function \(.["key"]) {\n    \(.["value"])\n}\n"' package.json \ 
            | sed -E 's/npm run ([a-z\:A-Z]+)/\1/g' \ # Replace any `npm run <task>` with the task name
        && tail -n 8 Taskfile # Grab the Taskfile template footer
    ) \ # Combine header, body and footer
    > Taskfile.sh && mv Taskfile.sh Taskfile && chmod +x Taskfile # Pipe out to Taskfile

To fix up your npm run-scripts to use the Taskfile, you can also use JQ to do this automatically for you:

jq '.scripts = (.scripts | to_entries | map(.value = "./Taskfile \(.key)") | from_entries)' package.json > package.json.2 && mv package.json.2 package.json

Free Features

  • Conditions and loops. Bash and friends have support for conditions and loops so you can error if parameters aren’t passed or if your build fails.
  • Streaming and piping. Don’t forget, we’re in a shell and you can use all your favourite redirections and piping techniques.
  • All your standard tools like rm and mkdir.
  • Globbing. Shells like zsh can expand globs like **/*.js for you automatically to pass to your tools.
  • Environment variables like NODE_ENV are easily accessible in your Taskfiles.

Considerations

When writing my Taskfile, these are some considerations I found useful:

  • You should try to use tools that you know users will have installed and working on their system. I’m not saying you have to be POSIX.1 compliant but be weary of using tools that aren’t standard (or difficult to install).
  • Keep it pretty. The reason for the Taskfile format is to keep your tasks organised and readable.
  • Don’t completely ditch the package.json. You should proxy the scripts to the Taskfile by calling the Taskfile directory in your package.json like "test": "./Taskfile test". You can still pass arguments to your scripts with the -- special argument and npm run build -- --production if necessary.

Caveats

The only caveat with the Taskfile format is we forgo compatibility with Windows which sucks. Of course, users can install Cygwin but one of most attractive things about the Taskfile format is not having to install external software to run the tasks. Hopefully, [Microsoft’s native bash shell in Windows 10](http://www.howtogeek.com/249966 how-to-install-and-use-the-linux-bash-shell-on-windows-10/) can do work well for us in the future.


Collaboration

The Taskfile format is something I’d love to see become more widespread and it’d be awesome if we could all come together on a standard of sorts. Things like simple syntax highlighting extensions or best practices guide would be awesome to formalise.

More Repositories

1

console.image

The one thing Chrome Dev Tools didn't need.
JavaScript
1,772
star
2

puppeteer-heap-snapshot

API and CLI tool to fetch and query Chome DevTools heap snapshots.
TypeScript
1,346
star
3

voyeur.js

Voyeur is a tiny (1.2kb) Javascript library that lets you traverse and manipulate the DOM the way it should have been.
JavaScript
731
star
4

aristochart

Sophisticated and simplified Javascript 2D line charts.
JavaScript
246
star
5

console.snapshot

An actual useful fork of the console.image. Snapshot the canvas and output it to the console.
JavaScript
164
star
6

node-sfx

Add some sound effects to your node programs.
JavaScript
70
star
7

polytunes

Liberate your music library.
JavaScript
38
star
8

tinyrequire

To the point dependency management.
JavaScript
33
star
9

SKImport

Design and import your SKPhysicsBodys with a fancy editor and loader class.
JavaScript
19
star
10

benchmartian

Run Javascript benchmarks from the CLI.
JavaScript
15
star
11

SKMech

SKMech is a set of handy utilities for SpriteKit.
Objective-C
13
star
12

jQPad

jQPad's official repository
JavaScript
12
star
13

movie-plots

Literal movie plots.
JavaScript
7
star
14

gulp-js1k

Gulp plugin for js1k.
JavaScript
7
star
15

redux-pending

Redux middleware for async actions with pending state.
JavaScript
6
star
16

tw

Teamwork CLI and Node.js API
JavaScript
6
star
17

gulp-cache-money

A gulp caching system that saves to disk.
JavaScript
6
star
18

boh

A simple, smart build tool.
JavaScript
4
star
19

Javascript-Improved

My take on improving some of Javascript's functionality
JavaScript
4
star
20

json.stringify2

A 112% faster implementation of a stripped down native JSON.stringify.
JavaScript
4
star
21

wrestle

A simple REST API testing framework that works in the browser or the command line.
JavaScript
4
star
22

prompt

TypeScript
3
star
23

instate

A application state manager built for React.
JavaScript
3
star
24

bindings

Official bindings for µWebSockets
C++
3
star
25

examist

Final Year Project for NUI Galway CS&IT 2016.
HTML
3
star
26

Image-Filters

Learning image filtering with Javascript's canvas
2
star
27

chat-api-client

Javascript API for Teamwork Chat.
JavaScript
2
star
28

prettyearth-wallpapers

A quick script to download wallpapers all the beautiful places on earth from Google Maps.
JavaScript
2
star
29

chromecoms

Making messaging between content and background scripts manageable.
JavaScript
2
star
30

offlog

A standalone static blog generator in your browser.
JavaScript
1
star
31

history-of-ufc-fighters

http://adriancooney.github.io/history-of-ufc-fighters
JavaScript
1
star
32

Canvas.js

(Yet another) canvas drawing library
JavaScript
1
star
33

spook

HTML 5 Game for CT404.
JavaScript
1
star
34

noodlebox

Javascript toolbox.
JavaScript
1
star
35

When.js

Simple user friendly event managing.
JavaScript
1
star
36

gibingo

TypeScript
1
star
37

HandleDeleteButton

A small library to dynamically handle the iOS keyboard delete/backspace button.
Objective-C
1
star
38

prone

CLI tool to await for services to be up.
JavaScript
1
star
39

ct326-programming

Java
1
star
40

chat-bot-poker

Sprint Planning Poker Chat Bot
JavaScript
1
star
41

koamotive

The Koa Express. A Koa-Express hybrid.
JavaScript
1
star
42

chat-bot

Chat Bots
JavaScript
1
star
43

machine-learning-data-mining

Machine Learning & Data Mining
Jupyter Notebook
1
star
44

Playwrite.js

Writing english to do stuff.
JavaScript
1
star
45

massmural

CT231 project code. Please don't try to break it.
JavaScript
1
star
46

hinge

Hinge - A web server framework for Node.js
JavaScript
1
star