godo

package module
v1.4.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 3, 2015 License: MIT Imports: 21 Imported by: 4

README

godo

godoc

godo is a task runner and file watcher for golang in the spirit of rake, gulp.

To install

go get -u gopkg.in/godo.v1/cmd/godo

Godofile

godo runs either Gododir/Godofile.go or tasks/Godofile.go.

As an example, create a file Gododir/Godofile.go with this content

package main

import (
	"fmt"
    . "gopkg.in/godo.v1"
)

func tasks(p *Project) {
    Env = `GOPATH=.vendor::$GOPATH`

    p.Task("default", D{"hello", "build"})

    p.Task("hello", func(c *Context) {
        name := c.Args.ZeroString("name", "n")
        if name == "" {
            Bash("echo Hello $USER!")
        } else {
            fmt.Println("Hello", name)
        }
    })

    p.Task("assets?", func() {
        // The "?" tells Godo to run this task ONLY ONCE regardless of
        // how many tasks depend on it. In this case watchify watches
        // on its own.
		Run("watchify public/js/index.js d -o dist/js/app.bundle.js")
    }).Watch("public/**/*.{css,js,html}")

    p.Task("build", D{"views", "assets"}, func() error {
        return Run("GOOS=linux GOARCH=amd64 go build", In{"cmd/server"})
    }).Watch("**/*.go")

    p.Task("server", D{"views", "assets"}, func() {
        // rebuilds and restarts when a watched file changes
        Start("main.go", M{"$in": "cmd/server"})
    }).Watch("server/**/*.go", "cmd/server/*.{go,json}").
       Debounce(3000)

    p.Task("views", func() error {
        return Run("razor templates")
    }).Watch("templates/**/*.go.html")
}

func main() {
    Godo(tasks)
}

To run "server" task from parent dir of tasks/

godo server

To rerun "server" and its dependencies whenever any of their watched files change

godo server --watch

To run the "default" task which runs "hello" and "build"

godo

Task names may add a "?" suffix to execute only once even when watching

// build once regardless of number of dependents
p.Task("assets?", func() {})

Task options

D{} or Dependencies{} - dependent tasks which run before task
W{} or Watches{}      - array of glob file patterns to watch

    /**/   - match zero or more directories
    {a,b}  - match a or b, no spaces
    *      - match any non-separator char
    ?      - match a single non-separator char
    **/    - match any directory, start of pattern only
    /**    - match any in this directory, end of pattern only
    !      - removes files from result set, start of pattern only

Task handlers

func()                  - Simple function handler, don't care about return
func() error            - Simple function handler
func(c *Context)        - Task with context, don't care about return
func(c *Context) error  - Task with context

Any error return in task or its dependencies stops the pipeline and godo exits with status code of 1, except in watch mode.

Task Arguments

Task arguments follow POSIX style flag convention (unlike go's built-in flag package). Any command line arguments succeeding -- are passed to each task. Note, arguments before -- are reserved for godo.

As an example,

p.Task("hello", func(c *Context) {
    // "(none)" is the default value
    msg := c.Args.MayString("(none)", "message", "msg", "m")
    var name string
    if len(c.Args.Leftover() == 1) {
        name = c.Args.Leftover()[0]
    }
    fmt.Println(msg, name)
})

running

# prints "(none)"
godo hello

# prints "Hello dude" using POSIX style flags
godo hello -- dude --message Hello
godo hello -- dude --msg Hello
godo hello -- -m Hello dude

Args functions are categorized as

  • Must* - Argument must be set by user or panic.

c.Args.MustInt("number", "n")


*  `May*` - If argument is not set, default to first value.

    ```go
    // defaults to 100
    c.Args.MayInt(100, "number", "n")
  • Zero* - If argument is not set, default to zero value.

// defaults to 0 c.Args.ZeroInt("number", "n")


## godobin

`godo` compiles `Godofile.go` to `godobin-VERSION` (`godobin-VERSION.exe` on Windows) whenever
`Godofile.go` changes. The binary file is built into the same directory as
`Godofile.go` and should be ignored by adding the path `godobin*` to `.gitignore`.

## Exec functions

All of these functions accept a `map[string]interface{}` or `M` for
options. Option keys that start with `"$"` are reserved for `godo`.
Other fields can be used as context for template.

### Bash

Bash functions uses the bash executable and may not run on all OS.

Run a bash script string. The script can be multiline line with continutation.

```go
Bash(`
    echo -n $USER
    echo some really long \
        command
`)

Bash can use Go templates

Bash(`echo -n {{.name}}`, M{"name": "mario", "$in": "cmd/bar"})

Run a bash script and capture STDOUT and STDERR.

output, err := BashOutput(`echo -n $USER`)
Run

Run go build inside of cmd/app and set environment variables.

Run(`GOOS=linux GOARCH=amd64 go build`, M{"$in": "cmd/app"})

Run can use Go templates

Run(`echo -n {{.name}}`, M{"name": "mario", "$in": "cmd/app"})

Run and capture STDOUT and STDERR

output, err := RunOutput("whoami")
Start

Start an async command. If the executable has suffix ".go" then it will be "go install"ed then executed. Use this for watching a server task.

Start("main.go", M{"$in": "cmd/app"})

Godo tracks the process ID of started processes to restart the app gracefully.

Inside

To run many commands inside a directory, use Inside instead of the $in option. Inside changes the working directory.

Inside("somedir", func() {
    Run("...")
    Bash("...")
})

User Input

To get plain string

user := Prompt("user: ")

To get password

password := PromptPassword("password: ")

Godofile Run-Time Environment

To specify whether to inherit from parent's process environment, set InheritParentEnv. This setting defaults to true

InheritParentEnv = false

To specify the base environment for your tasks, set Env. Separate with whitespace or newlines.

Env = `
    GOPATH=.vendor::$GOPATH
    PG_USER=mario
`

TIP: Set the Env when using a dependency manager like godep

wd, _ := os.Getwd()
ws := path.Join(wd, "Godeps/_workspace")
Env = fmt.Sprintf("GOPATH=%s::$GOPATH", ws)

Functions can add or override environment variables as part of the command string. Note that environment variables are set before the executable similar to a shell; however, the Run and Start functions do not use a shell.

p.Task("build", func() {
    Run("GOOS=linux GOARCH=amd64 go build" )
})

The effective environment for exec functions is: parent (if inherited) <- Env <- func parsed env

Paths should use :: as a cross-platform path list separator. On Windows :: is replaced with ;. On Mac and linux :: is replaced with :.

Documentation

Overview

Package godo is a task runner, file watcher in the spirit of Rake, Gulp ...

To install

go get -u gopkg.in/godo.v1/cmd/godo

As an example, create a file 'tasks/Godofile.go' with this content

package main

import (
    . "gokpkg.in/godo.v1"
)

func Tasks(p *Project) {
    Env = "GOPATH=.vendor:$GOPATH OTHER_VAR=val"

    p.Task("default", D{"hello", "build"})

    p.Task("hello", func() {
        Bash("echo Hello $USER!")
    })

    p.Task("build", W{"**/*.go"}, func() {
        Run("GOOS=linux GOARCH=amd64 go build", In{"cmd/godo"})
    })

    p.Task("server", D{"views"}, W{"**/*.go"}, Debounce(3000), func() {
        // Start recompiles and restarts on changes when watching
        Start("main.go", In{"cmd/server"})
    })
}

func main() {
    Godo(Tasks)
}

To run "views" task from terminal

godo views

To rerun "views" whenever any `*.go.html` file changes

godo views --watch

To run the "default" task which runs "hello" and "views"

godo

Task names may add a "?" suffix to indicate run only once

// run once regardless of number of dependees
p.Task("build?", func() {})

Task options

D{} or Dependencies{} - dependent tasks which run before task
Debounce              - minimum milliseconds before task can run again
W{} or Watches{}      - array of glob file patterns to watch

    /**/   - match zero or more directories
    {a,b}  - match a or b, no spaces
    *      - match any non-separator char
    ?      - match a single non-separator char
    **/    - match any directory, start of pattern only
    /**    - match any this directory, end of pattern only
    !      - removes files from resultset, start of pattern only

Task handlers

func() {}           - Simple function handler
func(c *Context) {} - Handler which accepts the current context

Index

Constants

This section is empty.

Variables

View Source
var DebounceMs int64

DebounceMs is the default time (1500 ms) to debounce task events in watch mode.

Env is the default environment to use for all commands. That is, the effective environment for all commands is the merged set of (parent environment, Env, func specified environment). Whitespace or newline separate key value pairs. $VAR interpolation is allowed.

Env = "GOOS=linux GOARCH=amd64" Env = `

GOOS=linux
GOPATH=./vendor:$GOPATH

`

View Source
var InheritParentEnv bool

InheritParentEnv whether to inherit parent's environment

View Source
var PathListSeparator = "::"

PathListSeparator is a cross-platform path list separator. On Windows, PathListSeparator is replacd by ";". On others, PathListSeparator is replaced by ":"

View Source
var Processes = make(map[string]*os.Process)

Proccesses are the processes spawned by Start()

View Source
var Version = "1.4.5"

Version is the current version

Functions

func Bash added in v1.1.0

func Bash(script string, options ...interface{}) error

Bash executes a bash script (string) with an option to set the working directory.

func BashOutput added in v1.1.0

func BashOutput(script string, options ...interface{}) (string, error)

BashOutput is the same as Bash and it captures stdout and stderr.

func Glob

func Glob(patterns []string) ([]*FileAsset, []*RegexpInfo, error)

Glob returns files and dirctories that match patterns. Patterns must use slashes, even Windows.

Special chars.

/**/   - match zero or more directories
{a,b}  - match a or b, no spaces
*      - match any non-separator char
?      - match a single non-separator char
**/    - match any directory, start of pattern only
/**    - match any this directory, end of pattern only
!      - removes files from resultset, start of pattern only

func Globexp

func Globexp(glob string) *regexp.Regexp

Globexp builds a regular express from from extended glob pattern and then returns a Regexp object from the pattern.

func Godo added in v1.1.0

func Godo(tasksFunc func(*Project))

Godo runs a project of tasks.

func Inside added in v1.1.0

func Inside(dir string, lambda func()) error

Inside temporarily changes the working directory and restores it when lambda finishes.

func Prompt added in v1.4.2

func Prompt(prompt string) string

Prompt prompts user for input with default value.

func PromptPassword added in v1.4.2

func PromptPassword(prompt string) string

PromptPassword prompts user for password input.

func Run

func Run(commandstr string, options ...interface{}) error

Run runs a command with an an option to set the working directory.

func RunOutput added in v1.1.0

func RunOutput(commandstr string, options ...interface{}) (string, error)

RunOutput is same as Run and it captures stdout and stderr.

func SetEnviron added in v1.3.0

func SetEnviron(envstr string, inheritParent bool)

SetEnviron sets the environment for child processes. Note that SetEnviron(Env, InheritParentEnv) is called once automatically.

func Start

func Start(commandstr string, options ...interface{}) error

Start starts an async command. If executable has suffix ".go" then it will be "go install"ed then executed. Use this for watching a server task.

If Start is called with the same command it kills the previous process.

The working directory is optional.

func Usage added in v1.2.0

func Usage(tasks string)

Usage prints a usage screen with task descriptions.

Types

type Context

type Context struct {
	// Task is the currently running task.
	Task *Task

	// FileEvent is an event from the watcher with change details.
	FileEvent *watcher.FileEvent

	// Task command line arguments
	Args minimist.ArgMap
}

Context is the data passed to a task.

func (*Context) AnyFile

func (context *Context) AnyFile() []string

AnyFile returns either a non-DELETe FileEvent file or the WatchGlob patterns which can be used by goa.Load()

type ContextHandlerFunc added in v1.3.2

type ContextHandlerFunc func(*Context) error

ContextHandlerFunc is a Handler adapter.

func (ContextHandlerFunc) Handle added in v1.3.2

func (c ContextHandlerFunc) Handle(ctx *Context) error

Handle implements Handler.

type D

type D Dependencies

D is short for Dependencies option.

type Debounce

type Debounce int64

Debounce is the number of milliseconds before a task can run again.

type Dependencies

type Dependencies []string

Dependencies are tasks which must run before a task.

type FileAsset

type FileAsset struct {
	os.FileInfo
	// Path to asset
	Path string
}

FileAsset contains file information and path from globbing.

type Handler added in v1.3.2

type Handler interface {
	Handle(*Context) error
}

Handler is the interface which all task handlers eventually implement.

type HandlerFunc added in v1.3.2

type HandlerFunc func() error

HandlerFunc is Handler adapter.

func (HandlerFunc) Handle added in v1.3.2

func (f HandlerFunc) Handle(*Context) error

Handle implements Handler.

type In added in v1.1.0

type In []string

In is used by Bash, Run and Start to set the working directory. This is DEPRECATED use M{"$in": "somedir"} instead.

type M

type M map[string]interface{}

M is generic string to interface alias

type Project

type Project struct {
	sync.Mutex
	Tasks     map[string]*Task
	Namespace map[string]*Project
	// contains filtered or unexported fields
}

Project is a container for tasks.

func NewProject

func NewProject(tasksFunc func(*Project)) *Project

NewProject creates am empty project ready for tasks.

func (*Project) Define

func (project *Project) Define(fn func(*Project))

Define defines tasks

func (*Project) Run

func (project *Project) Run(name string) error

Run runs a task by name.

func (*Project) Task

func (project *Project) Task(name string, args ...interface{}) *Task

Task adds a task to the project.

func (*Project) Use

func (project *Project) Use(namespace string, tasksFunc func(*Project))

Use uses another project's task within a namespace.

func (*Project) Watch

func (project *Project) Watch(names []string, isParent bool) bool

Watch watches the Files of a task and reruns the task on a watch event. Any direct dependency is also watched. Returns true if watching.

type RegexpInfo

type RegexpInfo struct {
	*regexp.Regexp
	Negate bool
}

RegexpInfo contains additional info about the Regexp created by a glob pattern.

type Task

type Task struct {
	Name string

	Dependencies []string
	Handler      Handler

	// Watches are the files are watched. On change the task is rerun. For example `**/*.less`
	// Usually Watches and Sources are the same.
	WatchFiles   []*FileAsset
	WatchGlobs   []string
	WatchRegexps []*RegexpInfo

	// computed based on dependencies
	EffectiveWatchRegexps []*RegexpInfo
	EffectiveWatchGlobs   []string

	// Complete indicates whether this task has already ran. This flag is
	// ignored in watch mode.
	Complete bool

	RunOnce bool
	// contains filtered or unexported fields
}

A Task is an operation performed on a user's project directory.

func (*Task) Debounce

func (task *Task) Debounce(ms int64) *Task

Debounce is minimum milliseconds before task can run again

func (*Task) Description

func (task *Task) Description(desc string) *Task

Description sets the description for the task.

func (*Task) Run

func (task *Task) Run()

Run runs all the dependencies of this task and when they have completed, runs this task.

func (*Task) RunWithEvent

func (task *Task) RunWithEvent(logName string, e *watcher.FileEvent) error

RunWithEvent runs this task when triggered from a watch. *e* FileEvent contains information about the file/directory which changed in watch mode.

func (*Task) Watch added in v1.3.1

func (task *Task) Watch(globs ...string) *Task

Watch a set of glob file patterns.

type VoidContextHandlerFunc added in v1.3.2

type VoidContextHandlerFunc func(*Context)

VoidContextHandlerFunc is a Handler adapter.

func (VoidContextHandlerFunc) Handle added in v1.3.2

func (f VoidContextHandlerFunc) Handle(ctx *Context) error

Handle implements Handler.

type VoidHandlerFunc added in v1.3.2

type VoidHandlerFunc func()

VoidHandlerFunc is a Handler adapter.

func (VoidHandlerFunc) Handle added in v1.3.2

func (v VoidHandlerFunc) Handle(*Context) error

Handle implements Handler.

type W

type W Watch

W is short for Watch option.

type Watch

type Watch []string

Watch are the glob file patterns which are watched and trigger rerunning a task on change.

Directories

Path Synopsis
cmd
Package util contains general purpose utility and logging functions.
Package util contains general purpose utility and logging functions.
Package watcher implements filesystem notification,.
Package watcher implements filesystem notification,.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL