packer-cn/common/command/template.go

72 lines
1.5 KiB
Go
Raw Normal View History

package command
import (
"errors"
"fmt"
"github.com/mitchellh/packer/packer"
"log"
)
// BuildFilters is a set of options to filter the builds out of a template.
type BuildFilters struct {
Except []string
Only []string
}
// Validate validates the filter settings
func (f *BuildFilters) Validate() error {
if len(f.Except) > 0 && len(f.Only) > 0 {
return errors.New("Only one of '-except' or '-only' may be specified.")
}
return nil
}
// Builds returns the builds out of the given template that pass the
// configured filters.
func (f *BuildFilters) Builds(t *packer.Template, cf *packer.ComponentFinder) ([]packer.Build, error) {
buildNames := t.BuildNames()
builds := make([]packer.Build, 0, len(buildNames))
for _, buildName := range buildNames {
if len(f.Except) > 0 {
found := false
for _, except := range f.Except {
if buildName == except {
found = true
break
}
}
if found {
log.Printf("Skipping build '%s' because specified by -except.", buildName)
continue
}
}
if len(f.Only) > 0 {
found := false
for _, only := range f.Only {
if buildName == only {
found = true
break
}
}
if !found {
log.Printf("Skipping build '%s' because not specified by -only.", buildName)
continue
}
}
log.Printf("Creating build: %s", buildName)
build, err := t.Build(buildName, cf)
if err != nil {
return nil, fmt.Errorf("Failed to create build '%s': \n\n%s", buildName, err)
}
builds = append(builds, build)
}
return builds, nil
}