Skip to content

Instantly share code, notes, and snippets.

@weakpixel
Created March 30, 2022 11:56
Show Gist options
  • Save weakpixel/356f44e8a3d0a74c6e542967ade5eb00 to your computer and use it in GitHub Desktop.
Save weakpixel/356f44e8a3d0a74c6e542967ade5eb00 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclsimple"
)
var (
exampleHCL = `
task "first_task" {
step "mkdir" "build_dir" {
path = "./build/"
}
step "exec" "list_build_dir" {
command = "ls ./build/"
}
}
`
)
func main() {
config := &Config{}
err := hclsimple.Decode("example.hcl", []byte(exampleHCL), nil, config)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, task := range config.Tasks {
fmt.Printf("Task: %s\n", task.Name)
for _, step := range task.Steps {
fmt.Printf(" Step: %s %s\n", step.Type, step.Name)
var runner Runner
switch step.Type {
case "mkdir":
runner = &MkdirStep{}
case "exec":
runner = &ExecStep{}
default:
fmt.Printf("Unknown step type %q\n", step.Type)
os.Exit(1)
}
diags := gohcl.DecodeBody(step.Remain, nil, runner)
if diags.HasErrors() {
fmt.Println(diags)
os.Exit(1)
}
err = runner.Run()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
}
type Config struct {
Tasks []*Task `hcl:"task,block"`
}
type Task struct {
Name string `hcl:"name,label"`
Steps []*Step `hcl:"step,block"`
}
type Step struct {
Type string `hcl:"type,label"`
Name string `hcl:"name,label"`
Remain hcl.Body `hcl:",remain"`
}
type ExecStep struct {
Command string `hcl:"command"`
}
func (s *ExecStep) Run() error {
return nil
}
type MkdirStep struct {
Path string `hcl:"path"`
}
func (s *MkdirStep) Run() error {
return nil
}
type Runner interface {
Run() error
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment