Marcel van Lohuizen | 10fd496 | 2019-04-26 12:14:49 +0200 | [diff] [blame] | 1 | // Copyright 2019 CUE Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // Package task provides a registry for tasks to be used by commands. |
| 16 | package task |
| 17 | |
| 18 | import ( |
| 19 | "context" |
| 20 | "io" |
| 21 | "sync" |
| 22 | |
| 23 | "cuelang.org/go/cue" |
| 24 | ) |
| 25 | |
| 26 | // A Context provides context for running a task. |
| 27 | type Context struct { |
| 28 | Context context.Context |
| 29 | Stdout io.Writer |
| 30 | Stderr io.Writer |
| 31 | } |
| 32 | |
| 33 | // A RunnerFunc creates a Runner. |
| 34 | type RunnerFunc func(v cue.Value) (Runner, error) |
| 35 | |
| 36 | // A Runner defines a command type. |
| 37 | type Runner interface { |
| 38 | // Init is called with the original configuration before any task is run. |
| 39 | // As a result, the configuration may be incomplete, but allows some |
| 40 | // validation before tasks are kicked off. |
| 41 | // Init(v cue.Value) |
| 42 | |
| 43 | // Runner runs given the current value and returns a new value which is to |
| 44 | // be unified with the original result. |
| 45 | Run(ctx *Context, v cue.Value) (results interface{}, err error) |
| 46 | } |
| 47 | |
| 48 | // Register registers a task for cue commands. |
| 49 | func Register(key string, f RunnerFunc) { |
| 50 | runners.Store(key, f) |
| 51 | } |
| 52 | |
| 53 | // Lookup returns the RunnerFunc for a key. |
| 54 | func Lookup(key string) RunnerFunc { |
| 55 | v, ok := runners.Load(key) |
| 56 | if !ok { |
| 57 | return nil |
| 58 | } |
| 59 | return v.(RunnerFunc) |
| 60 | } |
| 61 | |
| 62 | var runners sync.Map |