mirror of
https://github.com/linuxkit/linuxkit.git
synced 2026-04-07 20:17:24 +00:00
switch from flags to cobra (#3884)
Signed-off-by: Avi Deitcher <avi@deitcher.net> Signed-off-by: Avi Deitcher <avi@deitcher.net>
This commit is contained in:
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -13,6 +12,7 @@ import (
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/moby"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const defaultNameForStdin = "moby"
|
||||
@@ -30,193 +30,200 @@ func (f *formatList) Set(value string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Process the build arguments and execute build
|
||||
func build(args []string) {
|
||||
var buildFormats formatList
|
||||
|
||||
outputTypes := moby.OutputTypes()
|
||||
|
||||
buildCmd := flag.NewFlagSet("build", flag.ExitOnError)
|
||||
buildCmd.Usage = func() {
|
||||
fmt.Printf("USAGE: %s build [options] <file>[.yml] | -\n\n", os.Args[0])
|
||||
fmt.Printf("Options:\n")
|
||||
buildCmd.PrintDefaults()
|
||||
}
|
||||
buildName := buildCmd.String("name", "", "Name to use for output files")
|
||||
buildDir := buildCmd.String("dir", "", "Directory for output files, default current directory")
|
||||
buildOutputFile := buildCmd.String("o", "", "File to use for a single output, or '-' for stdout")
|
||||
buildSize := buildCmd.String("size", "1024M", "Size for output image, if supported and fixed size")
|
||||
buildPull := buildCmd.Bool("pull", false, "Always pull images")
|
||||
buildDocker := buildCmd.Bool("docker", false, "Check for images in docker before linuxkit cache")
|
||||
buildDecompressKernel := buildCmd.Bool("decompress-kernel", false, "Decompress the Linux kernel (default false)")
|
||||
buildCmd.Var(&buildFormats, "format", "Formats to create [ "+strings.Join(outputTypes, " ")+" ]")
|
||||
buildArch := buildCmd.String("arch", runtime.GOARCH, "target architecture for which to build")
|
||||
cacheDir := flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
buildCmd.Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
|
||||
if err := buildCmd.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
remArgs := buildCmd.Args()
|
||||
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Println("Please specify a configuration file")
|
||||
buildCmd.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
name := *buildName
|
||||
if name == "" {
|
||||
conf := remArgs[len(remArgs)-1]
|
||||
if conf == "-" {
|
||||
name = defaultNameForStdin
|
||||
} else {
|
||||
name = strings.TrimSuffix(filepath.Base(conf), filepath.Ext(conf))
|
||||
}
|
||||
}
|
||||
|
||||
// There are two types of output, they will probably be split into "build" and "package" later
|
||||
// the basic outputs are tarballs, while the packaged ones are the LinuxKit out formats that
|
||||
// cannot be streamed but we do allow multiple ones to be built.
|
||||
|
||||
if len(buildFormats) == 0 {
|
||||
if *buildOutputFile == "" {
|
||||
buildFormats = formatList{"kernel+initrd"}
|
||||
} else {
|
||||
buildFormats = formatList{"tar"}
|
||||
}
|
||||
}
|
||||
|
||||
log.Debugf("Formats selected: %s", buildFormats.String())
|
||||
|
||||
if len(buildFormats) > 1 {
|
||||
for _, o := range buildFormats {
|
||||
if moby.Streamable(o) {
|
||||
log.Fatalf("Format type %s must be the only format specified", o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(buildFormats) == 1 && moby.Streamable(buildFormats[0]) {
|
||||
if *buildOutputFile == "" {
|
||||
*buildOutputFile = filepath.Join(*buildDir, name+"."+buildFormats[0])
|
||||
// stop the errors in the validation below
|
||||
*buildName = ""
|
||||
*buildDir = ""
|
||||
}
|
||||
} else {
|
||||
err := moby.ValidateFormats(buildFormats, cacheDir.String())
|
||||
if err != nil {
|
||||
log.Errorf("Error parsing formats: %v", err)
|
||||
buildCmd.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
var outputFile *os.File
|
||||
if *buildOutputFile != "" {
|
||||
if len(buildFormats) > 1 {
|
||||
log.Fatal("The -output option can only be specified when generating a single output format")
|
||||
}
|
||||
if *buildName != "" {
|
||||
log.Fatal("The -output option cannot be specified with -name")
|
||||
}
|
||||
if *buildDir != "" {
|
||||
log.Fatal("The -output option cannot be specified with -dir")
|
||||
}
|
||||
if !moby.Streamable(buildFormats[0]) {
|
||||
log.Fatalf("The -output option cannot be specified for build type %s as it cannot be streamed", buildFormats[0])
|
||||
}
|
||||
if *buildOutputFile == "-" {
|
||||
outputFile = os.Stdout
|
||||
} else {
|
||||
var err error
|
||||
outputFile, err = os.Create(*buildOutputFile)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot open output file: %v", err)
|
||||
}
|
||||
defer outputFile.Close()
|
||||
}
|
||||
}
|
||||
|
||||
size, err := getDiskSizeMB(*buildSize)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to parse disk size: %v", err)
|
||||
}
|
||||
|
||||
var m moby.Moby
|
||||
for _, arg := range remArgs {
|
||||
var config []byte
|
||||
if conf := arg; conf == "-" {
|
||||
var err error
|
||||
config, err = io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot read stdin: %v", err)
|
||||
}
|
||||
} else if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
|
||||
buffer := new(bytes.Buffer)
|
||||
response, err := http.Get(arg)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot fetch remote yaml file: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = io.Copy(buffer, response.Body)
|
||||
if err != nil {
|
||||
log.Fatalf("Error reading http body: %v", err)
|
||||
}
|
||||
config = buffer.Bytes()
|
||||
} else {
|
||||
var err error
|
||||
config, err = os.ReadFile(conf)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot open config file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
c, err := moby.NewConfig(config)
|
||||
if err != nil {
|
||||
log.Fatalf("Invalid config: %v", err)
|
||||
}
|
||||
m, err = moby.AppendConfig(m, c)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot append config files: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var tf *os.File
|
||||
var w io.Writer
|
||||
if outputFile != nil {
|
||||
w = outputFile
|
||||
} else {
|
||||
if tf, err = os.CreateTemp("", ""); err != nil {
|
||||
log.Fatalf("Error creating tempfile: %v", err)
|
||||
}
|
||||
defer os.Remove(tf.Name())
|
||||
w = tf
|
||||
}
|
||||
|
||||
// this is a weird interface, but currently only streamable types can have additional files
|
||||
// need to split up the base tarball outputs from the secondary stages
|
||||
var tp string
|
||||
if moby.Streamable(buildFormats[0]) {
|
||||
tp = buildFormats[0]
|
||||
}
|
||||
err = moby.Build(m, w, moby.BuildOpts{Pull: *buildPull, BuilderType: tp, DecompressKernel: *buildDecompressKernel, CacheDir: cacheDir.String(), DockerCache: *buildDocker, Arch: *buildArch})
|
||||
if err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
if outputFile == nil {
|
||||
image := tf.Name()
|
||||
if err := tf.Close(); err != nil {
|
||||
log.Fatalf("Error closing tempfile: %v", err)
|
||||
}
|
||||
|
||||
log.Infof("Create outputs:")
|
||||
err = moby.Formats(filepath.Join(*buildDir, name), image, buildFormats, size, cacheDir.String())
|
||||
if err != nil {
|
||||
log.Fatalf("Error writing outputs: %v", err)
|
||||
}
|
||||
}
|
||||
func (f *formatList) Type() string {
|
||||
return "[]string"
|
||||
}
|
||||
|
||||
func buildCmd() *cobra.Command {
|
||||
|
||||
var (
|
||||
name string
|
||||
dir string
|
||||
outputFile string
|
||||
sizeString string
|
||||
pull bool
|
||||
docker bool
|
||||
decompressKernel bool
|
||||
arch string
|
||||
cacheDir flagOverEnvVarOverDefaultString
|
||||
buildFormats formatList
|
||||
outputTypes = moby.OutputTypes()
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "build",
|
||||
Short: "Build a bootable OS image from a yaml configuration file",
|
||||
Long: `Build a bootable OS image from a yaml configuration file.
|
||||
|
||||
The generated image can be in one of multiple formats which can be run on various platforms.
|
||||
`,
|
||||
Example: ` linuxkit build [options] <file>[.yml]`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if name == "" {
|
||||
conf := args[len(args)-1]
|
||||
if conf == "-" {
|
||||
name = defaultNameForStdin
|
||||
} else {
|
||||
name = strings.TrimSuffix(filepath.Base(conf), filepath.Ext(conf))
|
||||
}
|
||||
}
|
||||
|
||||
// There are two types of output, they will probably be split into "build" and "package" later
|
||||
// the basic outputs are tarballs, while the packaged ones are the LinuxKit out formats that
|
||||
// cannot be streamed but we do allow multiple ones to be built.
|
||||
|
||||
if len(buildFormats) == 0 {
|
||||
if outputFile == "" {
|
||||
buildFormats = formatList{"kernel+initrd"}
|
||||
} else {
|
||||
buildFormats = formatList{"tar"}
|
||||
}
|
||||
}
|
||||
|
||||
log.Debugf("Formats selected: %s", buildFormats.String())
|
||||
|
||||
if len(buildFormats) > 1 {
|
||||
for _, o := range buildFormats {
|
||||
if moby.Streamable(o) {
|
||||
return fmt.Errorf("Format type %s must be the only format specified", o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(buildFormats) == 1 && moby.Streamable(buildFormats[0]) {
|
||||
if outputFile == "" {
|
||||
outputFile = filepath.Join(dir, name+"."+buildFormats[0])
|
||||
// stop the errors in the validation below
|
||||
name = ""
|
||||
dir = ""
|
||||
}
|
||||
} else {
|
||||
err := moby.ValidateFormats(buildFormats, cacheDir.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error parsing formats: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var outfile *os.File
|
||||
if outputFile != "" {
|
||||
if len(buildFormats) > 1 {
|
||||
return fmt.Errorf("The -output option can only be specified when generating a single output format")
|
||||
}
|
||||
if name != "" {
|
||||
return fmt.Errorf("The -output option cannot be specified with -name")
|
||||
}
|
||||
if dir != "" {
|
||||
return fmt.Errorf("The -output option cannot be specified with -dir")
|
||||
}
|
||||
if !moby.Streamable(buildFormats[0]) {
|
||||
return fmt.Errorf("The -output option cannot be specified for build type %s as it cannot be streamed", buildFormats[0])
|
||||
}
|
||||
if outputFile == "-" {
|
||||
outfile = os.Stdout
|
||||
} else {
|
||||
var err error
|
||||
outfile, err = os.Create(outputFile)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot open output file: %v", err)
|
||||
}
|
||||
defer outfile.Close()
|
||||
}
|
||||
}
|
||||
|
||||
size, err := getDiskSizeMB(sizeString)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to parse disk size: %v", err)
|
||||
}
|
||||
|
||||
var m moby.Moby
|
||||
for _, arg := range args {
|
||||
var config []byte
|
||||
if conf := arg; conf == "-" {
|
||||
var err error
|
||||
config, err = io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot read stdin: %v", err)
|
||||
}
|
||||
} else if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
|
||||
buffer := new(bytes.Buffer)
|
||||
response, err := http.Get(arg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot fetch remote yaml file: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = io.Copy(buffer, response.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error reading http body: %v", err)
|
||||
}
|
||||
config = buffer.Bytes()
|
||||
} else {
|
||||
var err error
|
||||
config, err = os.ReadFile(conf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot open config file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
c, err := moby.NewConfig(config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Invalid config: %v", err)
|
||||
}
|
||||
m, err = moby.AppendConfig(m, c)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot append config files: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var tf *os.File
|
||||
var w io.Writer
|
||||
if outfile != nil {
|
||||
w = outfile
|
||||
} else {
|
||||
if tf, err = os.CreateTemp("", ""); err != nil {
|
||||
log.Fatalf("Error creating tempfile: %v", err)
|
||||
}
|
||||
defer os.Remove(tf.Name())
|
||||
w = tf
|
||||
}
|
||||
|
||||
// this is a weird interface, but currently only streamable types can have additional files
|
||||
// need to split up the base tarball outputs from the secondary stages
|
||||
var tp string
|
||||
if moby.Streamable(buildFormats[0]) {
|
||||
tp = buildFormats[0]
|
||||
}
|
||||
err = moby.Build(m, w, moby.BuildOpts{Pull: pull, BuilderType: tp, DecompressKernel: decompressKernel, CacheDir: cacheDir.String(), DockerCache: docker, Arch: arch})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%v", err)
|
||||
}
|
||||
|
||||
if outfile == nil {
|
||||
image := tf.Name()
|
||||
if err := tf.Close(); err != nil {
|
||||
return fmt.Errorf("Error closing tempfile: %v", err)
|
||||
}
|
||||
|
||||
log.Infof("Create outputs:")
|
||||
err = moby.Formats(filepath.Join(dir, name), image, buildFormats, size, cacheDir.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error writing outputs: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&name, "name", "", "Name to use for output files")
|
||||
cmd.Flags().StringVar(&dir, "dir", "", "Directory for output files, default current directory")
|
||||
cmd.Flags().StringVar(&outputFile, "o", "", "File to use for a single output, or '-' for stdout")
|
||||
cmd.Flags().StringVar(&sizeString, "size", "1024M", "Size for output image, if supported and fixed size")
|
||||
cmd.Flags().BoolVar(&pull, "pull", false, "Always pull images")
|
||||
cmd.Flags().BoolVar(&docker, "docker", false, "Check for images in docker before linuxkit cache")
|
||||
cmd.Flags().BoolVar(&decompressKernel, "decompress-kernel", false, "Decompress the Linux kernel (default false)")
|
||||
cmd.Flags().StringVar(&arch, "arch", runtime.GOARCH, "target architecture for which to build")
|
||||
cmd.Flags().VarP(&buildFormats, "format", "f", "Formats to create [ "+strings.Join(outputTypes, " ")+" ]")
|
||||
cacheDir = flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
cmd.Flags().Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,53 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/util"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func cacheUsage() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Printf("USAGE: %s cache command [options]\n\n", invoked)
|
||||
fmt.Printf("Supported commands are\n")
|
||||
// Please keep these in alphabetical order
|
||||
fmt.Printf(" clean\n")
|
||||
fmt.Printf(" export\n")
|
||||
fmt.Printf(" ls\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("'options' are the backend specific options.\n")
|
||||
fmt.Printf("See '%s cache [command] --help' for details.\n\n", invoked)
|
||||
}
|
||||
|
||||
// Process the cache
|
||||
func cache(args []string) {
|
||||
if len(args) < 1 {
|
||||
cacheUsage()
|
||||
os.Exit(1)
|
||||
}
|
||||
switch args[0] {
|
||||
// Please keep cases in alphabetical order
|
||||
case "clean":
|
||||
cacheClean(args[1:])
|
||||
case "rm":
|
||||
cacheRm(args[1:])
|
||||
case "ls":
|
||||
cacheList(args[1:])
|
||||
case "export":
|
||||
cacheExport(args[1:])
|
||||
case "help", "-h", "-help", "--help":
|
||||
cacheUsage()
|
||||
os.Exit(0)
|
||||
default:
|
||||
log.Errorf("No 'cache' command specified.")
|
||||
}
|
||||
}
|
||||
|
||||
func defaultLinuxkitCache() string {
|
||||
lktDir := ".linuxkit"
|
||||
home := util.HomeDir()
|
||||
return filepath.Join(home, lktDir, "cache")
|
||||
}
|
||||
|
||||
func cacheCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "cache",
|
||||
Short: "manage the linuxkit cache",
|
||||
Long: `manage the linuxkit cache.`,
|
||||
}
|
||||
|
||||
cmd.AddCommand(cacheCleanCmd())
|
||||
cmd.AddCommand(cacheRmCmd())
|
||||
cmd.AddCommand(cacheLsCmd())
|
||||
cmd.AddCommand(cacheExportCmd())
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
@@ -9,39 +8,45 @@ import (
|
||||
"github.com/google/go-containerregistry/pkg/v1/remote"
|
||||
cachepkg "github.com/linuxkit/linuxkit/src/cmd/linuxkit/cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func cacheClean(args []string) {
|
||||
flags := flag.NewFlagSet("clean", flag.ExitOnError)
|
||||
func cacheCleanCmd() *cobra.Command {
|
||||
var (
|
||||
publishedOnly bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "clean",
|
||||
Short: "empty the linuxkit cache",
|
||||
Long: `Empty the linuxkit cache.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
// did we limit to published only?
|
||||
if !publishedOnly {
|
||||
if err := os.RemoveAll(cacheDir); err != nil {
|
||||
return fmt.Errorf("Unable to clean cache %s: %v", cacheDir, err)
|
||||
}
|
||||
log.Infof("Cache emptied: %s", cacheDir)
|
||||
return nil
|
||||
}
|
||||
|
||||
cacheDir := flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
flags.Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
publishedOnly := flags.Bool("published-only", false, "Only clean images that linuxkit can confirm at the time of running have been published to the registry")
|
||||
// list all of the images and content in the cache
|
||||
p, err := cachepkg.NewProvider(cacheDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to read a local cache: %v", err)
|
||||
}
|
||||
images, err := p.List()
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading image names: %v", err)
|
||||
}
|
||||
removeImagesFromCache(images, p, publishedOnly)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// did we limit to published only?
|
||||
if !*publishedOnly {
|
||||
if err := os.RemoveAll(cacheDir.String()); err != nil {
|
||||
log.Fatalf("Unable to clean cache %s: %v", cacheDir, err)
|
||||
}
|
||||
log.Infof("Cache emptied: %s", cacheDir)
|
||||
return
|
||||
}
|
||||
cmd.Flags().BoolVar(&publishedOnly, "published-only", false, "Only clean images that linuxkit can confirm at the time of running have been published to the registry")
|
||||
|
||||
// list all of the images and content in the cache
|
||||
p, err := cachepkg.NewProvider(cacheDir.String())
|
||||
if err != nil {
|
||||
log.Fatalf("unable to read a local cache: %v", err)
|
||||
}
|
||||
images, err := p.List()
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("error reading image names: %v", err)
|
||||
}
|
||||
removeImagesFromCache(images, p, *publishedOnly)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// removeImagesFromCache removes images from the cache.
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
@@ -11,77 +9,83 @@ import (
|
||||
cachepkg "github.com/linuxkit/linuxkit/src/cmd/linuxkit/cache"
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/util"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func cacheExport(args []string) {
|
||||
fs := flag.NewFlagSet("export", flag.ExitOnError)
|
||||
func cacheExportCmd() *cobra.Command {
|
||||
var (
|
||||
arch string
|
||||
outputFile string
|
||||
format string
|
||||
tagName string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "export",
|
||||
Short: "export individual images from the linuxkit cache",
|
||||
Long: `Export individual images from the linuxkit cache. Supports exporting into multiple formats.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
names := args
|
||||
name := names[0]
|
||||
fullname := util.ReferenceExpand(name)
|
||||
|
||||
cacheDir := flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
fs.Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
arch := fs.String("arch", runtime.GOARCH, "Architecture to resolve an index to an image, if the provided image name is an index")
|
||||
outfile := fs.String("outfile", "", "Path to file to save output, '-' for stdout")
|
||||
format := fs.String("format", "oci", "export format, one of 'oci', 'filesystem'")
|
||||
tagName := fs.String("name", "", "override the provided image name in the exported tar file; useful only for format=oci")
|
||||
p, err := cachepkg.NewProvider(cacheDir)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to read a local cache: %v", err)
|
||||
}
|
||||
ref, err := reference.Parse(fullname)
|
||||
if err != nil {
|
||||
log.Fatalf("invalid image name %s: %v", name, err)
|
||||
}
|
||||
desc, err := p.FindDescriptor(&ref)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to find image named %s: %v", name, err)
|
||||
}
|
||||
|
||||
if err := fs.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
src := p.NewSource(&ref, arch, desc)
|
||||
var reader io.ReadCloser
|
||||
switch format {
|
||||
case "oci":
|
||||
fullTagName := fullname
|
||||
if tagName != "" {
|
||||
fullTagName = util.ReferenceExpand(tagName)
|
||||
}
|
||||
reader, err = src.V1TarReader(fullTagName)
|
||||
case "filesystem":
|
||||
reader, err = src.TarReader()
|
||||
default:
|
||||
log.Fatalf("requested unknown format %s: %v", name, err)
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalf("error getting reader for image %s: %v", name, err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
// try to write the output file
|
||||
var w io.Writer
|
||||
switch {
|
||||
case outputFile == "":
|
||||
log.Fatal("'outfile' flag is required")
|
||||
case outputFile == "-":
|
||||
w = os.Stdout
|
||||
default:
|
||||
f, err := os.OpenFile(outputFile, os.O_CREATE|os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to open %s: %v", outputFile, err)
|
||||
}
|
||||
defer f.Close()
|
||||
w = f
|
||||
}
|
||||
|
||||
_, err = io.Copy(w, reader)
|
||||
return err
|
||||
},
|
||||
}
|
||||
|
||||
// get the requested images
|
||||
if fs.NArg() < 1 {
|
||||
log.Fatal("At least one image name is required")
|
||||
}
|
||||
names := fs.Args()
|
||||
name := names[0]
|
||||
fullname := util.ReferenceExpand(name)
|
||||
cmd.Flags().StringVar(&arch, "arch", runtime.GOARCH, "Architecture to resolve an index to an image, if the provided image name is an index")
|
||||
cmd.Flags().StringVar(&outputFile, "outfile", "", "Path to file to save output, '-' for stdout")
|
||||
cmd.Flags().StringVar(&format, "format", "oci", "export format, one of 'oci', 'filesystem'")
|
||||
cmd.Flags().StringVar(&tagName, "name", "", "override the provided image name in the exported tar file; useful only for format=oci")
|
||||
|
||||
p, err := cachepkg.NewProvider(cacheDir.String())
|
||||
if err != nil {
|
||||
log.Fatalf("unable to read a local cache: %v", err)
|
||||
}
|
||||
ref, err := reference.Parse(fullname)
|
||||
if err != nil {
|
||||
log.Fatalf("invalid image name %s: %v", name, err)
|
||||
}
|
||||
desc, err := p.FindDescriptor(&ref)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to find image named %s: %v", name, err)
|
||||
}
|
||||
|
||||
src := p.NewSource(&ref, *arch, desc)
|
||||
var reader io.ReadCloser
|
||||
switch *format {
|
||||
case "oci":
|
||||
fullTagName := fullname
|
||||
if *tagName != "" {
|
||||
fullTagName = util.ReferenceExpand(*tagName)
|
||||
}
|
||||
reader, err = src.V1TarReader(fullTagName)
|
||||
case "filesystem":
|
||||
reader, err = src.TarReader()
|
||||
default:
|
||||
log.Fatalf("requested unknown format %s: %v", name, err)
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalf("error getting reader for image %s: %v", name, err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
// try to write the output file
|
||||
var w io.Writer
|
||||
switch {
|
||||
case outfile == nil, *outfile == "":
|
||||
log.Fatal("'outfile' flag is required")
|
||||
case *outfile == "-":
|
||||
w = os.Stdout
|
||||
default:
|
||||
f, err := os.OpenFile(*outfile, os.O_CREATE|os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to open %s: %v", *outfile, err)
|
||||
}
|
||||
defer f.Close()
|
||||
w = f
|
||||
}
|
||||
|
||||
_, _ = io.Copy(w, reader)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,30 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
cachepkg "github.com/linuxkit/linuxkit/src/cmd/linuxkit/cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func cacheList(args []string) {
|
||||
flags := flag.NewFlagSet("list", flag.ExitOnError)
|
||||
|
||||
cacheDir := flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
flags.Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
|
||||
// list all of the images and content in the cache
|
||||
images, err := cachepkg.ListImages(cacheDir.String())
|
||||
if err != nil {
|
||||
log.Fatalf("error reading image names: %v", err)
|
||||
}
|
||||
log.Printf("%-80s %s", "image name", "root manifest hash")
|
||||
for name, hash := range images {
|
||||
log.Printf("%-80s %s", name, hash)
|
||||
func cacheLsCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "ls",
|
||||
Short: "list images in the linuxkit cache",
|
||||
Long: `List images in the linuxkit cache.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
// list all of the images and content in the cache
|
||||
images, err := cachepkg.ListImages(cacheDir)
|
||||
if err != nil {
|
||||
log.Fatalf("error reading image names: %v", err)
|
||||
}
|
||||
log.Printf("%-80s %s", "image name", "root manifest hash")
|
||||
for name, hash := range images {
|
||||
log.Printf("%-80s %s", name, hash)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,48 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
cachepkg "github.com/linuxkit/linuxkit/src/cmd/linuxkit/cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func cacheRm(args []string) {
|
||||
flags := flag.NewFlagSet("rm", flag.ExitOnError)
|
||||
func cacheRmCmd() *cobra.Command {
|
||||
var (
|
||||
publishedOnly bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "rm",
|
||||
Short: "remove individual images from the linuxkit cache",
|
||||
Long: `Remove individual images from the linuxkit cache.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
imageNames := args
|
||||
|
||||
cacheDir := flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
flags.Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
publishedOnly := flags.Bool("published-only", false, "Only remove the specified images if linuxkit can confirm at the time of running have been published to the registry")
|
||||
// did we limit to published only?
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
// list all of the images and content in the cache
|
||||
p, err := cachepkg.NewProvider(cacheDir)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to read a local cache: %v", err)
|
||||
}
|
||||
images := map[string]string{}
|
||||
for _, imageName := range imageNames {
|
||||
desc, err := p.FindRoot(imageName)
|
||||
if err != nil {
|
||||
log.Fatalf("error reading image %s: %v", imageName, err)
|
||||
}
|
||||
dig, err := desc.Digest()
|
||||
if err != nil {
|
||||
log.Fatalf("error reading digest for image %s: %v", imageName, err)
|
||||
}
|
||||
images[imageName] = dig.String()
|
||||
}
|
||||
removeImagesFromCache(images, p, publishedOnly)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
if flags.NArg() == 0 {
|
||||
log.Fatal("Please specify at least one image to remove")
|
||||
}
|
||||
cmd.Flags().BoolVar(&publishedOnly, "published-only", false, "Only clean images that linuxkit can confirm at the time of running have been published to the registry")
|
||||
|
||||
imageNames := flags.Args()
|
||||
|
||||
// did we limit to published only?
|
||||
|
||||
// list all of the images and content in the cache
|
||||
p, err := cachepkg.NewProvider(cacheDir.String())
|
||||
if err != nil {
|
||||
log.Fatalf("unable to read a local cache: %v", err)
|
||||
}
|
||||
images := map[string]string{}
|
||||
for _, imageName := range imageNames {
|
||||
desc, err := p.FindRoot(imageName)
|
||||
if err != nil {
|
||||
log.Fatalf("error reading image %s: %v", imageName, err)
|
||||
}
|
||||
dig, err := desc.Digest()
|
||||
if err != nil {
|
||||
log.Fatalf("error reading digest for image %s: %v", imageName, err)
|
||||
}
|
||||
images[imageName] = dig.String()
|
||||
}
|
||||
removeImagesFromCache(images, p, *publishedOnly)
|
||||
return cmd
|
||||
}
|
||||
|
||||
75
src/cmd/linuxkit/cmd.go
Normal file
75
src/cmd/linuxkit/cmd.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/util"
|
||||
"github.com/spf13/cobra"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
cacheDir string
|
||||
// Config is the global tool configuration
|
||||
Config = GlobalConfig{}
|
||||
)
|
||||
|
||||
// GlobalConfig is the global tool configuration
|
||||
type GlobalConfig struct {
|
||||
Pkg PkgConfig `yaml:"pkg"`
|
||||
}
|
||||
|
||||
// PkgConfig is the config specific to the `pkg` subcommand
|
||||
type PkgConfig struct {
|
||||
}
|
||||
|
||||
func readConfig() {
|
||||
cfgPath := filepath.Join(os.Getenv("HOME"), ".moby", "linuxkit", "config.yml")
|
||||
cfgBytes, err := os.ReadFile(cfgPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return
|
||||
}
|
||||
fmt.Printf("Failed to read %q\n", cfgPath)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := yaml.Unmarshal(cfgBytes, &Config); err != nil {
|
||||
fmt.Printf("Failed to parse %q\n", cfgPath)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func newCmd() *cobra.Command {
|
||||
var (
|
||||
flagQuiet bool
|
||||
flagVerbose bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "linuxkit",
|
||||
DisableAutoGenTag: true,
|
||||
SilenceUsage: true,
|
||||
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
readConfig()
|
||||
|
||||
// Set up logging
|
||||
return util.SetupLogging(flagQuiet, flagVerbose)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.AddCommand(buildCmd()) // apko login
|
||||
cmd.AddCommand(cacheCmd())
|
||||
cmd.AddCommand(metadataCmd())
|
||||
cmd.AddCommand(pkgCmd())
|
||||
cmd.AddCommand(pushCmd())
|
||||
cmd.AddCommand(runCmd())
|
||||
cmd.AddCommand(serveCmd())
|
||||
cmd.AddCommand(versionCmd())
|
||||
|
||||
cmd.PersistentFlags().StringVar(&cacheDir, "cache", defaultLinuxkitCache(), fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
cmd.PersistentFlags().BoolVarP(&flagQuiet, "quiet", "q", false, "Quiet execution")
|
||||
cmd.PersistentFlags().BoolVarP(&flagVerbose, "verbose", "v", false, "Verbose execution")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -98,6 +98,7 @@ require (
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
|
||||
github.com/in-toto/in-toto-golang v0.3.4-0.20220709202702-fa494aaa0add // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/klauspost/compress v1.15.12 // indirect
|
||||
github.com/linuxkit/virtsock v0.0.0-20201010232012-f8cee7dfc7a3 // indirect
|
||||
@@ -117,6 +118,8 @@ require (
|
||||
github.com/prometheus/procfs v0.8.0 // indirect
|
||||
github.com/secure-systems-lab/go-securesystemslib v0.4.0 // indirect
|
||||
github.com/shibumi/go-pathspec v1.3.0 // indirect
|
||||
github.com/spf13/cobra v1.6.1 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/tonistiigi/fsutil v0.0.0-20221114235510-0127568185cf // indirect
|
||||
github.com/tonistiigi/units v0.0.0-20180711220420-6950e57a87ea // indirect
|
||||
github.com/tonistiigi/vt100 v0.0.0-20210615222946-8066bb97264f // indirect
|
||||
|
||||
@@ -467,6 +467,7 @@ github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwc
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/creack/goselect v0.0.0-20180501195510-58854f77ee8d h1:6o8WW5zZ+Ny9sbk69epnAPmBzrBaRnvci+l4+pqleeY=
|
||||
github.com/creack/goselect v0.0.0-20180501195510-58854f77ee8d/go.mod h1:gHrIcH/9UZDn2qgeTUeW5K9eZsVYCH6/60J/FHysWyE=
|
||||
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
|
||||
@@ -921,6 +922,8 @@ github.com/in-toto/in-toto-golang v0.3.4-0.20220709202702-fa494aaa0add h1:DAh7mH
|
||||
github.com/in-toto/in-toto-golang v0.3.4-0.20220709202702-fa494aaa0add/go.mod h1:DQI8vlV6h6qSY/tCOoYKtxjWrkyiNpJ3WTV/WoBllmQ=
|
||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/intel/goresctrl v0.2.0/go.mod h1:+CZdzouYFn5EsxgqAQTEzMfwKwuc0fVdMrT9FCCAVRQ=
|
||||
github.com/ishidawataru/sctp v0.0.0-20191218070446-00ab2ac2db07/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg=
|
||||
github.com/ishidawataru/sctp v0.0.0-20210226210310-f2269e66cdee/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg=
|
||||
@@ -1358,6 +1361,8 @@ github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHN
|
||||
github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo=
|
||||
github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk=
|
||||
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
|
||||
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
|
||||
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
|
||||
github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
|
||||
@@ -1,111 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/util"
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/version"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
"log"
|
||||
)
|
||||
|
||||
// GlobalConfig is the global tool configuration
|
||||
type GlobalConfig struct {
|
||||
Pkg PkgConfig `yaml:"pkg"`
|
||||
}
|
||||
|
||||
// PkgConfig is the config specific to the `pkg` subcommand
|
||||
type PkgConfig struct {
|
||||
}
|
||||
|
||||
var (
|
||||
// Config is the global tool configuration
|
||||
Config = GlobalConfig{}
|
||||
)
|
||||
|
||||
func printVersion() {
|
||||
fmt.Printf("%s version %s\n", filepath.Base(os.Args[0]), version.Version)
|
||||
if version.GitCommit != "" {
|
||||
fmt.Printf("commit: %s\n", version.GitCommit)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func readConfig() {
|
||||
cfgPath := filepath.Join(os.Getenv("HOME"), ".moby", "linuxkit", "config.yml")
|
||||
cfgBytes, err := os.ReadFile(cfgPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return
|
||||
}
|
||||
fmt.Printf("Failed to read %q\n", cfgPath)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := yaml.Unmarshal(cfgBytes, &Config); err != nil {
|
||||
fmt.Printf("Failed to parse %q\n", cfgPath)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Usage = func() {
|
||||
fmt.Printf("USAGE: %s [options] COMMAND\n\n", filepath.Base(os.Args[0]))
|
||||
fmt.Printf("Commands:\n")
|
||||
fmt.Printf(" build Build an image from a YAML file\n")
|
||||
fmt.Printf(" cache Manage the local cache\n")
|
||||
fmt.Printf(" metadata Metadata utilities\n")
|
||||
fmt.Printf(" pkg Package building\n")
|
||||
fmt.Printf(" push Push a VM image to a cloud or image store\n")
|
||||
fmt.Printf(" run Run a VM image on a local hypervisor or remote cloud\n")
|
||||
fmt.Printf(" serve Run a local http server (for iPXE booting)\n")
|
||||
fmt.Printf(" version Print version information\n")
|
||||
fmt.Printf(" help Print this message\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Run '%s COMMAND --help' for more information on the command\n", filepath.Base(os.Args[0]))
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Options:\n")
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
|
||||
readConfig()
|
||||
|
||||
// Set up logging
|
||||
util.AddLoggingFlags(nil)
|
||||
flag.Parse()
|
||||
util.SetupLogging()
|
||||
|
||||
args := flag.Args()
|
||||
if len(args) < 1 {
|
||||
fmt.Printf("Please specify a command.\n\n")
|
||||
flag.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
case "build":
|
||||
build(args[1:])
|
||||
case "cache":
|
||||
cache(args[1:])
|
||||
case "metadata":
|
||||
metadata(args[1:])
|
||||
case "pkg":
|
||||
pkg(args[1:])
|
||||
case "push":
|
||||
push(args[1:])
|
||||
case "run":
|
||||
run(args[1:])
|
||||
case "serve":
|
||||
serve(args[1:])
|
||||
case "version":
|
||||
printVersion()
|
||||
case "help":
|
||||
flag.Usage()
|
||||
default:
|
||||
fmt.Printf("%q is not valid command.\n\n", args[0])
|
||||
flag.Usage()
|
||||
os.Exit(1)
|
||||
if err := newCmd().Execute(); err != nil {
|
||||
log.Fatalf("error during command execution: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/rn/iso9660wrap"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// WriteMetadataISO writes a metadata ISO file in a format usable by pkg/metadata
|
||||
@@ -20,58 +18,35 @@ func WriteMetadataISO(path string, content []byte) error {
|
||||
return iso9660wrap.WriteBuffer(outfh, content, "config")
|
||||
}
|
||||
|
||||
func metadataCreateUsage() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Printf("USAGE: %s metadata create [file.iso] [metadata]\n\n", invoked)
|
||||
func metadataCreateCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "create",
|
||||
Short: "create an ISO with metadata",
|
||||
Long: `Create an ISO file with metadata in it.
|
||||
Provided metadata will be written to '/config' in the ISO.
|
||||
This is compatible with the linuxkit/metadata package.`,
|
||||
Args: cobra.ExactArgs(2),
|
||||
Example: "linuxkit metadata create file.iso \"metadata\"",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
isoImage := args[0]
|
||||
metadata := args[1]
|
||||
|
||||
fmt.Printf("'file.iso' is the file to create.\n")
|
||||
fmt.Printf("'metadata' will be written to '/config' in the ISO.\n")
|
||||
fmt.Printf("This is compatible with the linuxkit/metadata package\n")
|
||||
return WriteMetadataISO(isoImage, []byte(metadata))
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func metadataCreate(args []string) {
|
||||
if len(args) != 2 {
|
||||
metadataCreateUsage()
|
||||
os.Exit(1)
|
||||
}
|
||||
switch args[0] {
|
||||
case "help", "-h", "-help", "--help":
|
||||
metadataCreateUsage()
|
||||
os.Exit(0)
|
||||
func metadataCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "metadata",
|
||||
Short: "manage ISO metadata",
|
||||
Long: `Manage ISO metadata.`,
|
||||
}
|
||||
|
||||
isoImage := args[0]
|
||||
metadata := args[1]
|
||||
cmd.AddCommand(metadataCreateCmd())
|
||||
|
||||
if err := WriteMetadataISO(isoImage, []byte(metadata)); err != nil {
|
||||
log.Fatal("Failed to write user data ISO: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func metadataUsage() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Printf("USAGE: %s metadata COMMAND [options]\n\n", invoked)
|
||||
fmt.Printf("Commands:\n")
|
||||
fmt.Printf(" create Create a metadata ISO\n")
|
||||
}
|
||||
|
||||
func metadata(args []string) {
|
||||
if len(args) < 1 {
|
||||
metadataUsage()
|
||||
os.Exit(1)
|
||||
}
|
||||
switch args[0] {
|
||||
case "help", "-h", "-help", "--help":
|
||||
metadataUsage()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
case "create":
|
||||
metadataCreate(args[1:])
|
||||
default:
|
||||
fmt.Printf("%q is not a valid metadata command.\n\n", args[0])
|
||||
metadataUsage()
|
||||
os.Exit(1)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -127,9 +127,9 @@ func outputLinuxKit(format string, filename string, kernel []byte, initrd []byte
|
||||
}
|
||||
commandLine := []string{
|
||||
"-q", "run", "qemu",
|
||||
"-disk", fmt.Sprintf("%s,size=%s,format=%s", filename, sizeString, format),
|
||||
"-disk", fmt.Sprintf("%s,format=raw", tardisk),
|
||||
"-kernel", imageFilename("mkimage"),
|
||||
"--disk", fmt.Sprintf("%s,size=%s,format=%s", filename, sizeString, format),
|
||||
"--disk", fmt.Sprintf("%s,format=raw", tardisk),
|
||||
"--kernel", imageFilename("mkimage"),
|
||||
}
|
||||
log.Debugf("run %s: %v", linuxkit, commandLine)
|
||||
cmd := exec.Command(linuxkit, commandLine...)
|
||||
|
||||
@@ -1,46 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"errors"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/pkglib"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func pkgUsage() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Printf("USAGE: %s pkg [subcommand] [options] [prefix]\n\n", invoked)
|
||||
var pkglibConfig pkglib.PkglibConfig
|
||||
|
||||
fmt.Printf("'subcommand' is one of:\n")
|
||||
fmt.Printf(" build\n")
|
||||
fmt.Printf(" builder\n")
|
||||
fmt.Printf(" push\n")
|
||||
fmt.Printf(" show-tag\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("'options' are the command specific options.\n")
|
||||
fmt.Printf("See '%s pkg [command] --help' for details.\n\n", invoked)
|
||||
}
|
||||
func pkgCmd() *cobra.Command {
|
||||
var (
|
||||
argDisableCache bool
|
||||
argEnableCache bool
|
||||
argNoNetwork bool
|
||||
argNetwork bool
|
||||
argOrg string
|
||||
buildYML string
|
||||
hash string
|
||||
hashCommit string
|
||||
hashPath string
|
||||
dirty bool
|
||||
devMode bool
|
||||
)
|
||||
|
||||
func pkg(args []string) {
|
||||
if len(args) < 1 {
|
||||
pkgUsage()
|
||||
os.Exit(1)
|
||||
cmd := &cobra.Command{
|
||||
Use: "pkg",
|
||||
Short: "package building and pushing",
|
||||
Long: `Package building and pushing.`,
|
||||
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
pkglibConfig = pkglib.PkglibConfig{
|
||||
BuildYML: buildYML,
|
||||
Hash: hash,
|
||||
HashCommit: hashCommit,
|
||||
HashPath: hashPath,
|
||||
Dirty: dirty,
|
||||
Dev: devMode,
|
||||
}
|
||||
if cmd.Flags().Changed("disable-cache") && cmd.Flags().Changed("enable-cache") {
|
||||
return errors.New("cannot set but disable-cache and enable-cache")
|
||||
}
|
||||
|
||||
if cmd.Flags().Changed("nonetwork") && cmd.Flags().Changed("network") {
|
||||
return errors.New("cannot set but nonetwork and network")
|
||||
}
|
||||
|
||||
// these should be set only for overrides
|
||||
if cmd.Flags().Changed("disable-cache") {
|
||||
pkglibConfig.DisableCache = &argDisableCache
|
||||
}
|
||||
if cmd.Flags().Changed("enable-cache") {
|
||||
val := !argEnableCache
|
||||
pkglibConfig.DisableCache = &val
|
||||
}
|
||||
if cmd.Flags().Changed("nonetwork") {
|
||||
val := !argNoNetwork
|
||||
pkglibConfig.Network = &val
|
||||
}
|
||||
if cmd.Flags().Changed("network") {
|
||||
pkglibConfig.Network = &argNetwork
|
||||
}
|
||||
if cmd.Flags().Changed("org") {
|
||||
pkglibConfig.Org = &argOrg
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
case "build":
|
||||
pkgBuild(args[1:])
|
||||
case "builder":
|
||||
pkgBuilder(args[1:])
|
||||
case "push":
|
||||
pkgPush(args[1:])
|
||||
case "show-tag":
|
||||
pkgShowTag(args[1:])
|
||||
case "manifest":
|
||||
pkgManifest(args[1:])
|
||||
case "index":
|
||||
pkgIndex(args[1:])
|
||||
default:
|
||||
fmt.Printf("Unknown subcommand %q\n\n", args[0])
|
||||
pkgUsage()
|
||||
}
|
||||
cmd.AddCommand(pkgBuildCmd())
|
||||
cmd.AddCommand(pkgBuilderCmd())
|
||||
cmd.AddCommand(pkgPushCmd())
|
||||
cmd.AddCommand(pkgShowTagCmd())
|
||||
cmd.AddCommand(pkgManifestCmd())
|
||||
|
||||
// These override fields in pkgInfo default below, bools are in both forms to allow user overrides in either direction.
|
||||
// These will apply to all packages built.
|
||||
piBase := pkglib.NewPkgInfo()
|
||||
cmd.PersistentFlags().BoolVar(&argDisableCache, "disable-cache", piBase.DisableCache, "Disable build cache")
|
||||
cmd.PersistentFlags().BoolVar(&argEnableCache, "enable-cache", !piBase.DisableCache, "Enable build cache")
|
||||
cmd.PersistentFlags().BoolVar(&argNoNetwork, "nonetwork", !piBase.Network, "Disallow network use during build")
|
||||
cmd.PersistentFlags().BoolVar(&argNetwork, "network", piBase.Network, "Allow network use during build")
|
||||
|
||||
cmd.PersistentFlags().StringVar(&argOrg, "org", piBase.Org, "Override the hub org")
|
||||
cmd.PersistentFlags().StringVar(&buildYML, "build-yml", "build.yml", "Override the name of the yml file")
|
||||
cmd.PersistentFlags().StringVar(&hash, "hash", "", "Override the image hash (default is to query git for the package's tree-sh)")
|
||||
cmd.PersistentFlags().StringVar(&hashCommit, "hash-commit", "HEAD", "Override the git commit to use for the hash")
|
||||
cmd.PersistentFlags().StringVar(&hashPath, "hash-path", "", "Override the directory to use for the image hash, must be a parent of the package dir (default is to use the package dir)")
|
||||
cmd.PersistentFlags().BoolVar(&dirty, "force-dirty", false, "Force the pkg(s) to be considered dirty")
|
||||
cmd.PersistentFlags().BoolVar(&devMode, "dev", false, "Force org and hash to $USER and \"dev\" respectively")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/pkglib"
|
||||
imagespec "github.com/opencontainers/image-spec/specs-go/v1"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -17,199 +17,199 @@ const (
|
||||
defaultBuilderImage = "moby/buildkit:v0.11.0-rc2"
|
||||
)
|
||||
|
||||
func pkgBuild(args []string) {
|
||||
pkgBuildPush(args, false)
|
||||
}
|
||||
|
||||
func pkgBuildPush(args []string, withPush bool) {
|
||||
flags := flag.NewFlagSet("pkg build", flag.ExitOnError)
|
||||
flags.Usage = func() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
name := "build"
|
||||
if withPush {
|
||||
name = "push"
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "USAGE: %s pkg %s [options] path\n\n", name, invoked)
|
||||
fmt.Fprintf(os.Stderr, "'path' specifies the path to the package source directory.\n")
|
||||
fmt.Fprintf(os.Stderr, "\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
|
||||
force := flags.Bool("force", false, "Force rebuild even if image is in local cache")
|
||||
pull := flags.Bool("pull", false, "Pull image if in registry but not in local cache; conflicts with --force")
|
||||
ignoreCache := flags.Bool("ignore-cached", false, "Ignore cached intermediate images, always pulling from registry")
|
||||
docker := flags.Bool("docker", false, "Store the built image in the docker image cache instead of the default linuxkit cache")
|
||||
platforms := flags.String("platforms", "", "Which platforms to build for, defaults to all of those for which the package can be built")
|
||||
skipPlatforms := flags.String("skip-platforms", "", "Platforms that should be skipped, even if present in build.yml")
|
||||
builders := flags.String("builders", "", "Which builders to use for which platforms, e.g. linux/arm64=docker-context-arm64, overrides defaults and environment variables, see https://github.com/linuxkit/linuxkit/blob/master/docs/packages.md#Providing-native-builder-nodes")
|
||||
builderImage := flags.String("builder-image", defaultBuilderImage, "buildkit builder container image to use")
|
||||
builderRestart := flags.Bool("builder-restart", false, "force restarting builder, even if container with correct name and image exists")
|
||||
cacheDir := flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
flags.Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
|
||||
// some logic clarification:
|
||||
// pkg build - builds unless is in cache or published in registry
|
||||
// pkg build --pull - builds unless is in cache or published in registry; pulls from registry if not in cache
|
||||
// pkg build --force - always builds even if is in cache or published in registry
|
||||
// pkg build --force --pull - always builds even if is in cache or published in registry; --pull ignored
|
||||
// pkg push - always builds unless is in cache
|
||||
// pkg push --force - always builds even if is in cache
|
||||
// pkg push --nobuild - skips build; if not in cache, fails
|
||||
// pkg push --nobuild --force - nonsensical
|
||||
// some logic clarification:
|
||||
// pkg build - builds unless is in cache or published in registry
|
||||
// pkg build --pull - builds unless is in cache or published in registry; pulls from registry if not in cache
|
||||
// pkg build --force - always builds even if is in cache or published in registry
|
||||
// pkg build --force --pull - always builds even if is in cache or published in registry; --pull ignored
|
||||
// pkg push - always builds unless is in cache
|
||||
// pkg push --force - always builds even if is in cache
|
||||
// pkg push --nobuild - skips build; if not in cache, fails
|
||||
// pkg push --nobuild --force - nonsensical
|
||||
|
||||
// addCmdRunPkgBuildPush adds the RunE function and flags to a cobra.Command
|
||||
// for "pkg build" or "pkg push".
|
||||
func addCmdRunPkgBuildPush(cmd *cobra.Command, withPush bool) *cobra.Command {
|
||||
var (
|
||||
release *string
|
||||
nobuild, manifest *bool
|
||||
nobuildRef = false
|
||||
force bool
|
||||
pull bool
|
||||
ignoreCache bool
|
||||
docker bool
|
||||
platforms string
|
||||
skipPlatforms string
|
||||
builders string
|
||||
builderImage string
|
||||
builderRestart bool
|
||||
release string
|
||||
nobuild bool
|
||||
manifest bool
|
||||
cacheDir = flagOverEnvVarOverDefaultString{def: defaultLinuxkitCache(), envVar: envVarCacheDir}
|
||||
)
|
||||
nobuild = &nobuildRef
|
||||
if withPush {
|
||||
release = flags.String("release", "", "Release the given version")
|
||||
nobuild = flags.Bool("nobuild", false, "Skip building the image before pushing, conflicts with -force")
|
||||
manifest = flags.Bool("manifest", true, "Create and push multi-arch manifest")
|
||||
}
|
||||
|
||||
pkgs, err := pkglib.NewFromCLI(flags, args...)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if *nobuild && *force {
|
||||
fmt.Fprint(os.Stderr, "flags -force and -nobuild conflict")
|
||||
os.Exit(1)
|
||||
}
|
||||
if *pull && *force {
|
||||
fmt.Fprint(os.Stderr, "flags -force and -pull conflict")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var opts []pkglib.BuildOpt
|
||||
if *force {
|
||||
opts = append(opts, pkglib.WithBuildForce())
|
||||
}
|
||||
if *ignoreCache {
|
||||
opts = append(opts, pkglib.WithBuildIgnoreCache())
|
||||
}
|
||||
if *pull {
|
||||
opts = append(opts, pkglib.WithBuildPull())
|
||||
}
|
||||
|
||||
opts = append(opts, pkglib.WithBuildCacheDir(cacheDir.String()))
|
||||
|
||||
if withPush {
|
||||
opts = append(opts, pkglib.WithBuildPush())
|
||||
if *nobuild {
|
||||
opts = append(opts, pkglib.WithBuildSkip())
|
||||
cmd.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
pkgs, err := pkglib.NewFromConfig(pkglibConfig, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *release != "" {
|
||||
opts = append(opts, pkglib.WithRelease(*release))
|
||||
}
|
||||
if *manifest {
|
||||
opts = append(opts, pkglib.WithBuildManifest())
|
||||
}
|
||||
}
|
||||
if *docker {
|
||||
opts = append(opts, pkglib.WithBuildTargetDockerCache())
|
||||
}
|
||||
|
||||
// skipPlatformsMap contains platforms that should be skipped
|
||||
skipPlatformsMap := make(map[string]bool)
|
||||
if *skipPlatforms != "" {
|
||||
for _, platform := range strings.Split(*skipPlatforms, ",") {
|
||||
parts := strings.SplitN(platform, "/", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[0] != "linux" || parts[1] == "" {
|
||||
fmt.Fprintf(os.Stderr, "invalid target platform specification '%s'\n", platform)
|
||||
os.Exit(1)
|
||||
if nobuild && force {
|
||||
return errors.New("flags -force and -nobuild conflict")
|
||||
}
|
||||
if pull && force {
|
||||
return errors.New("flags -force and -pull conflict")
|
||||
}
|
||||
|
||||
var opts []pkglib.BuildOpt
|
||||
if force {
|
||||
opts = append(opts, pkglib.WithBuildForce())
|
||||
}
|
||||
if ignoreCache {
|
||||
opts = append(opts, pkglib.WithBuildIgnoreCache())
|
||||
}
|
||||
if pull {
|
||||
opts = append(opts, pkglib.WithBuildPull())
|
||||
}
|
||||
|
||||
opts = append(opts, pkglib.WithBuildCacheDir(cacheDir.String()))
|
||||
|
||||
if withPush {
|
||||
opts = append(opts, pkglib.WithBuildPush())
|
||||
if nobuild {
|
||||
opts = append(opts, pkglib.WithBuildSkip())
|
||||
}
|
||||
skipPlatformsMap[strings.Trim(parts[1], " ")] = true
|
||||
}
|
||||
}
|
||||
// if requested specific platforms, build those. If not, then we will
|
||||
// retrieve the defaults in the loop over each package.
|
||||
var plats []imagespec.Platform
|
||||
// don't allow the use of --skip-platforms with --platforms
|
||||
if *platforms != "" && *skipPlatforms != "" {
|
||||
fmt.Fprintln(os.Stderr, "--skip-platforms and --platforms may not be used together")
|
||||
os.Exit(1)
|
||||
}
|
||||
// process the platforms if provided
|
||||
if *platforms != "" {
|
||||
for _, p := range strings.Split(*platforms, ",") {
|
||||
parts := strings.SplitN(p, "/", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
fmt.Fprintf(os.Stderr, "invalid target platform specification '%s'\n", p)
|
||||
os.Exit(1)
|
||||
if release != "" {
|
||||
opts = append(opts, pkglib.WithRelease(release))
|
||||
}
|
||||
if manifest {
|
||||
opts = append(opts, pkglib.WithBuildManifest())
|
||||
}
|
||||
plats = append(plats, imagespec.Platform{OS: parts[0], Architecture: parts[1]})
|
||||
}
|
||||
}
|
||||
if docker {
|
||||
opts = append(opts, pkglib.WithBuildTargetDockerCache())
|
||||
}
|
||||
|
||||
// build the builders map
|
||||
buildersMap := map[string]string{}
|
||||
// look for builders env var
|
||||
buildersMap, err = buildPlatformBuildersMap(os.Getenv(buildersEnvVar), buildersMap)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s in environment variable %s\n", err.Error(), buildersEnvVar)
|
||||
os.Exit(1)
|
||||
}
|
||||
// any CLI options override env var
|
||||
buildersMap, err = buildPlatformBuildersMap(*builders, buildersMap)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s in --builders flag\n", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
opts = append(opts, pkglib.WithBuildBuilders(buildersMap))
|
||||
opts = append(opts, pkglib.WithBuildBuilderImage(*builderImage))
|
||||
opts = append(opts, pkglib.WithBuildBuilderRestart(*builderRestart))
|
||||
|
||||
for _, p := range pkgs {
|
||||
// things we need our own copies of
|
||||
var (
|
||||
pkgOpts = make([]pkglib.BuildOpt, len(opts))
|
||||
pkgPlats = make([]imagespec.Platform, len(plats))
|
||||
)
|
||||
copy(pkgOpts, opts)
|
||||
copy(pkgPlats, plats)
|
||||
// unless overridden, platforms are specific to a package, so this needs to be inside the for loop
|
||||
if len(pkgPlats) == 0 {
|
||||
for _, a := range p.Arches() {
|
||||
if _, ok := skipPlatformsMap[a]; ok {
|
||||
continue
|
||||
// skipPlatformsMap contains platforms that should be skipped
|
||||
skipPlatformsMap := make(map[string]bool)
|
||||
if skipPlatforms != "" {
|
||||
for _, platform := range strings.Split(skipPlatforms, ",") {
|
||||
parts := strings.SplitN(platform, "/", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[0] != "linux" || parts[1] == "" {
|
||||
return fmt.Errorf("invalid target platform specification '%s'\n", platform)
|
||||
}
|
||||
pkgPlats = append(pkgPlats, imagespec.Platform{OS: "linux", Architecture: a})
|
||||
skipPlatformsMap[strings.Trim(parts[1], " ")] = true
|
||||
}
|
||||
}
|
||||
// if requested specific platforms, build those. If not, then we will
|
||||
// retrieve the defaults in the loop over each package.
|
||||
var plats []imagespec.Platform
|
||||
// don't allow the use of --skip-platforms with --platforms
|
||||
if platforms != "" && skipPlatforms != "" {
|
||||
return errors.New("--skip-platforms and --platforms may not be used together")
|
||||
}
|
||||
// process the platforms if provided
|
||||
if platforms != "" {
|
||||
for _, p := range strings.Split(platforms, ",") {
|
||||
parts := strings.SplitN(p, "/", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
fmt.Fprintf(os.Stderr, "invalid target platform specification '%s'\n", p)
|
||||
os.Exit(1)
|
||||
}
|
||||
plats = append(plats, imagespec.Platform{OS: parts[0], Architecture: parts[1]})
|
||||
}
|
||||
}
|
||||
|
||||
// if there are no platforms to build for, do nothing.
|
||||
// note that this is *not* an error; we simply skip it
|
||||
if len(pkgPlats) == 0 {
|
||||
fmt.Printf("Skipping %s with no architectures to build\n", p.Tag())
|
||||
continue
|
||||
// build the builders map
|
||||
buildersMap := map[string]string{}
|
||||
// look for builders env var
|
||||
buildersMap, err = buildPlatformBuildersMap(os.Getenv(buildersEnvVar), buildersMap)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error in environment variable %s: %w\n", buildersEnvVar, err)
|
||||
}
|
||||
|
||||
pkgOpts = append(pkgOpts, pkglib.WithBuildPlatforms(pkgPlats...))
|
||||
|
||||
var msg, action string
|
||||
switch {
|
||||
case !withPush:
|
||||
msg = fmt.Sprintf("Building %q", p.Tag())
|
||||
action = "building"
|
||||
case *nobuild:
|
||||
msg = fmt.Sprintf("Pushing %q without building", p.Tag())
|
||||
action = "building and pushing"
|
||||
default:
|
||||
msg = fmt.Sprintf("Building and pushing %q", p.Tag())
|
||||
action = "building and pushing"
|
||||
// any CLI options override env var
|
||||
buildersMap, err = buildPlatformBuildersMap(builders, buildersMap)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error in --builders flag: %w\n", err)
|
||||
}
|
||||
opts = append(opts, pkglib.WithBuildBuilders(buildersMap))
|
||||
opts = append(opts, pkglib.WithBuildBuilderImage(builderImage))
|
||||
opts = append(opts, pkglib.WithBuildBuilderRestart(builderRestart))
|
||||
|
||||
fmt.Println(msg)
|
||||
for _, p := range pkgs {
|
||||
// things we need our own copies of
|
||||
var (
|
||||
pkgOpts = make([]pkglib.BuildOpt, len(opts))
|
||||
pkgPlats = make([]imagespec.Platform, len(plats))
|
||||
)
|
||||
copy(pkgOpts, opts)
|
||||
copy(pkgPlats, plats)
|
||||
// unless overridden, platforms are specific to a package, so this needs to be inside the for loop
|
||||
if len(pkgPlats) == 0 {
|
||||
for _, a := range p.Arches() {
|
||||
if _, ok := skipPlatformsMap[a]; ok {
|
||||
continue
|
||||
}
|
||||
pkgPlats = append(pkgPlats, imagespec.Platform{OS: "linux", Architecture: a})
|
||||
}
|
||||
}
|
||||
|
||||
if err := p.Build(pkgOpts...); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error %s %q: %v\n", action, p.Tag(), err)
|
||||
os.Exit(1)
|
||||
// if there are no platforms to build for, do nothing.
|
||||
// note that this is *not* an error; we simply skip it
|
||||
if len(pkgPlats) == 0 {
|
||||
fmt.Printf("Skipping %s with no architectures to build\n", p.Tag())
|
||||
continue
|
||||
}
|
||||
|
||||
pkgOpts = append(pkgOpts, pkglib.WithBuildPlatforms(pkgPlats...))
|
||||
|
||||
var msg, action string
|
||||
switch {
|
||||
case !withPush:
|
||||
msg = fmt.Sprintf("Building %q", p.Tag())
|
||||
action = "building"
|
||||
case nobuild:
|
||||
msg = fmt.Sprintf("Pushing %q without building", p.Tag())
|
||||
action = "building and pushing"
|
||||
default:
|
||||
msg = fmt.Sprintf("Building and pushing %q", p.Tag())
|
||||
action = "building and pushing"
|
||||
}
|
||||
|
||||
fmt.Println(msg)
|
||||
|
||||
if err := p.Build(pkgOpts...); err != nil {
|
||||
return fmt.Errorf("error %s %q: %w", action, p.Tag(), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
cmd.Flags().BoolVar(&force, "force", false, "Force rebuild even if image is in local cache")
|
||||
cmd.Flags().BoolVar(&pull, "pull", false, "Pull image if in registry but not in local cache; conflicts with --force")
|
||||
cmd.Flags().BoolVar(&ignoreCache, "ignore-cached", false, "Ignore cached intermediate images, always pulling from registry")
|
||||
cmd.Flags().BoolVar(&docker, "docker", false, "Store the built image in the docker image cache instead of the default linuxkit cache")
|
||||
cmd.Flags().StringVar(&platforms, "platforms", "", "Which platforms to build for, defaults to all of those for which the package can be built")
|
||||
cmd.Flags().StringVar(&skipPlatforms, "skip-platforms", "", "Platforms that should be skipped, even if present in build.yml")
|
||||
cmd.Flags().StringVar(&builders, "builders", "", "Which builders to use for which platforms, e.g. linux/arm64=docker-context-arm64, overrides defaults and environment variables, see https://github.com/linuxkit/linuxkit/blob/master/docs/packages.md#Providing-native-builder-nodes")
|
||||
cmd.Flags().StringVar(&builderImage, "builder-image", defaultBuilderImage, "buildkit builder container image to use")
|
||||
cmd.Flags().BoolVar(&builderRestart, "builder-restart", false, "force restarting builder, even if container with correct name and image exists")
|
||||
cmd.Flags().Var(&cacheDir, "cache", fmt.Sprintf("Directory for caching and finding cached image, overrides env var %s", envVarCacheDir))
|
||||
cmd.Flags().StringVar(&release, "release", "", "Release the given version")
|
||||
cmd.Flags().BoolVar(&nobuild, "nobuild", false, "Skip building the image before pushing, conflicts with -force")
|
||||
cmd.Flags().BoolVar(&manifest, "manifest", true, "Create and push multi-arch manifest")
|
||||
|
||||
return cmd
|
||||
}
|
||||
func pkgBuildCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "build",
|
||||
Short: "build an OCI package from a directory with a yaml configuration file",
|
||||
Long: `Build an OCI package from a directory with a yaml configuration file.
|
||||
'path' specifies the path to the package source directory.
|
||||
`,
|
||||
Example: ` linuxkit pkg build [options] pkg/dir/`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
}
|
||||
return addCmdRunPkgBuildPush(cmd, false)
|
||||
}
|
||||
|
||||
func buildPlatformBuildersMap(inputs string, existing map[string]string) (map[string]string, error) {
|
||||
|
||||
@@ -1,84 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/pkglib"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func pkgBuilderUsage() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Printf("USAGE: %s builder command [options]\n\n", invoked)
|
||||
fmt.Printf("Supported commands are\n")
|
||||
// Please keep these in alphabetical order
|
||||
fmt.Printf(" du\n")
|
||||
fmt.Printf(" prune\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("'options' are the backend specific options.\n")
|
||||
fmt.Printf("See '%s builder [command] --help' for details.\n\n", invoked)
|
||||
}
|
||||
func pkgBuilderCmd() *cobra.Command {
|
||||
var (
|
||||
builders string
|
||||
platforms string
|
||||
builderImage string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "builder",
|
||||
Short: "manage the pkg builder",
|
||||
Long: `Manage the pkg builder. This normally is a container.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
command := args[0]
|
||||
verbose := cmd.Flags().Lookup("verbose").Value.String() == "true"
|
||||
// build the builders map
|
||||
buildersMap := make(map[string]string)
|
||||
// look for builders env var
|
||||
buildersMap, err := buildPlatformBuildersMap(os.Getenv(buildersEnvVar), buildersMap)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid environment variable %s: %w", buildersEnvVar, err)
|
||||
}
|
||||
// any CLI options override env var
|
||||
buildersMap, err = buildPlatformBuildersMap(builders, buildersMap)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid --builders flag: %w", err)
|
||||
}
|
||||
|
||||
// Process the builder
|
||||
func pkgBuilder(args []string) {
|
||||
if len(args) < 1 {
|
||||
pkgBuilderUsage()
|
||||
os.Exit(1)
|
||||
}
|
||||
switch args[0] {
|
||||
// Please keep cases in alphabetical order
|
||||
case "du":
|
||||
pkgBuilderCommands(args[0], args[1:])
|
||||
case "prune":
|
||||
pkgBuilderCommands(args[0], args[1:])
|
||||
case "help", "-h", "-help", "--help":
|
||||
pkgBuilderUsage()
|
||||
os.Exit(0)
|
||||
default:
|
||||
log.Errorf("No 'builder' command specified.")
|
||||
}
|
||||
}
|
||||
|
||||
func pkgBuilderCommands(command string, args []string) {
|
||||
flags := flag.NewFlagSet(command, flag.ExitOnError)
|
||||
builders := flags.String("builders", "", "Which builders to use for which platforms, e.g. linux/arm64=docker-context-arm64, overrides defaults and environment variables, see https://github.com/linuxkit/linuxkit/blob/master/docs/packages.md#Providing-native-builder-nodes")
|
||||
platforms := flags.String("platforms", fmt.Sprintf("linux/%s", runtime.GOARCH), "Which platforms we built images for")
|
||||
builderImage := flags.String("builder-image", defaultBuilderImage, "buildkit builder container image to use")
|
||||
verbose := flags.Bool("v", false, "Verbose output")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
// build the builders map
|
||||
buildersMap := make(map[string]string)
|
||||
// look for builders env var
|
||||
buildersMap, err := buildPlatformBuildersMap(os.Getenv(buildersEnvVar), buildersMap)
|
||||
if err != nil {
|
||||
log.Fatalf("%s in environment variable %s\n", err.Error(), buildersEnvVar)
|
||||
}
|
||||
// any CLI options override env var
|
||||
buildersMap, err = buildPlatformBuildersMap(*builders, buildersMap)
|
||||
if err != nil {
|
||||
log.Fatalf("%s in --builders flag\n", err.Error())
|
||||
platformsToClean := strings.Split(platforms, ",")
|
||||
switch command {
|
||||
case "du":
|
||||
if err := pkglib.DiskUsage(buildersMap, builderImage, platformsToClean, verbose); err != nil {
|
||||
return fmt.Errorf("Unable to print disk usage of builder: %w", err)
|
||||
}
|
||||
case "prune":
|
||||
if err := pkglib.PruneBuilder(buildersMap, builderImage, platformsToClean, verbose); err != nil {
|
||||
return fmt.Errorf("Unable to prune builder: %w", err)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected command %s", command)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
platformsToClean := strings.Split(*platforms, ",")
|
||||
switch command {
|
||||
case "du":
|
||||
if err := pkglib.DiskUsage(buildersMap, *builderImage, platformsToClean, *verbose); err != nil {
|
||||
log.Fatalf("Unable to print disk usage of builder: %v", err)
|
||||
}
|
||||
case "prune":
|
||||
if err := pkglib.PruneBuilder(buildersMap, *builderImage, platformsToClean, *verbose); err != nil {
|
||||
log.Fatalf("Unable to prune builder: %v", err)
|
||||
}
|
||||
default:
|
||||
log.Errorf("unexpected command %s", command)
|
||||
pkgBuilderUsage()
|
||||
os.Exit(1)
|
||||
}
|
||||
cmd.PersistentFlags().StringVar(&builders, "builders", "", "Which builders to use for which platforms, e.g. linux/arm64=docker-context-arm64, overrides defaults and environment variables, see https://github.com/linuxkit/linuxkit/blob/master/docs/packages.md#Providing-native-builder-nodes")
|
||||
cmd.PersistentFlags().StringVar(&platforms, "platforms", fmt.Sprintf("linux/%s", runtime.GOARCH), "Which platforms we built images for")
|
||||
cmd.PersistentFlags().StringVar(&builderImage, "builder-image", defaultBuilderImage, "buildkit builder container image to use")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,50 +1,47 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/pkglib"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func pkgManifest(args []string) {
|
||||
pkgIndex(args)
|
||||
}
|
||||
func pkgIndex(args []string) {
|
||||
flags := flag.NewFlagSet("pkg manifest", flag.ExitOnError)
|
||||
flags.Usage = func() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
name := "manifest"
|
||||
fmt.Fprintf(os.Stderr, "USAGE: %s pkg %s [options] path\n\n", name, invoked)
|
||||
fmt.Fprintf(os.Stderr, "'path' specifies the path to the package source directory.\n")
|
||||
fmt.Fprintf(os.Stderr, "\n")
|
||||
fmt.Fprintf(os.Stderr, "Updates the manifest in the registry for the given path based on all known platforms. If none found, no manifest created.\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
release := flags.String("release", "", "Release the given version")
|
||||
|
||||
pkgs, err := pkglib.NewFromCLI(flags, args...)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var opts []pkglib.BuildOpt
|
||||
if *release != "" {
|
||||
opts = append(opts, pkglib.WithRelease(*release))
|
||||
}
|
||||
|
||||
for _, p := range pkgs {
|
||||
msg := fmt.Sprintf("Updating index for %q", p.Tag())
|
||||
action := "building and pushing"
|
||||
|
||||
fmt.Println(msg)
|
||||
|
||||
if err := p.Index(opts...); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error %s %q: %v\n", action, p.Tag(), err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func pkgManifestCmd() *cobra.Command {
|
||||
var release string
|
||||
cmd := &cobra.Command{
|
||||
Use: "manifest",
|
||||
Short: "update manifest in the registry for the given path based on all known platforms",
|
||||
Long: `Updates the manifest in the registry for the given path based on all known platforms. If none found, no manifest created.
|
||||
'path' specifies the path to the package source directory.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Aliases: []string{"index"},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
pkgs, err := pkglib.NewFromConfig(pkglibConfig, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var opts []pkglib.BuildOpt
|
||||
if release != "" {
|
||||
opts = append(opts, pkglib.WithRelease(release))
|
||||
}
|
||||
|
||||
for _, p := range pkgs {
|
||||
msg := fmt.Sprintf("Updating index for %q", p.Tag())
|
||||
action := "building and pushing"
|
||||
|
||||
fmt.Println(msg)
|
||||
|
||||
if err := p.Index(opts...); err != nil {
|
||||
return fmt.Errorf("error %s %q: %w", action, p.Tag(), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&release, "release", "", "Release the given version")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
package main
|
||||
|
||||
func pkgPush(args []string) {
|
||||
pkgBuildPush(args, true)
|
||||
import "github.com/spf13/cobra"
|
||||
|
||||
func pkgPushCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "push",
|
||||
Short: "build and push an OCI package from a directory with a yaml configuration file",
|
||||
Long: `Build and push an OCI package from a directory with a yaml configuration file.
|
||||
'path' specifies the path to the package source directory.
|
||||
|
||||
The package may or may not be built first, depending on options
|
||||
`,
|
||||
Example: ` linuxkit pkg push [options] pkg/dir/`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
}
|
||||
return addCmdRunPkgBuildPush(cmd, true)
|
||||
}
|
||||
|
||||
@@ -1,35 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/linuxkit/linuxkit/src/cmd/linuxkit/pkglib"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func pkgShowTag(args []string) {
|
||||
flags := flag.NewFlagSet("pkg show-tag", flag.ExitOnError)
|
||||
flags.Usage = func() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Fprintf(os.Stderr, "USAGE: %s pkg show-tag [options] path\n\n", invoked)
|
||||
fmt.Fprintf(os.Stderr, "'path' specifies the path to the package source directory.\n")
|
||||
fmt.Fprintf(os.Stderr, "\n")
|
||||
flags.PrintDefaults()
|
||||
func pkgShowTagCmd() *cobra.Command {
|
||||
var canonical bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "show-tag",
|
||||
Short: "show the tag for a package based on its source directory",
|
||||
Long: `Show the tag for a package based on its source directory.
|
||||
'path' specifies the path to the package source directory.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
pkgs, err := pkglib.NewFromConfig(pkglibConfig, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, p := range pkgs {
|
||||
tag := p.Tag()
|
||||
if canonical {
|
||||
tag = p.FullTag()
|
||||
}
|
||||
fmt.Println(tag)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
canonical := flags.Bool("canonical", false, "Show canonical name, e.g. docker.io/linuxkit/foo:1234, instead of the default, e.g. linuxkit/foo:1234")
|
||||
cmd.Flags().BoolVar(&canonical, "canonical", false, "Show canonical name, e.g. docker.io/linuxkit/foo:1234, instead of the default, e.g. linuxkit/foo:1234")
|
||||
|
||||
pkgs, err := pkglib.NewFromCLI(flags, args...)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
for _, p := range pkgs {
|
||||
tag := p.Tag()
|
||||
if *canonical {
|
||||
tag = p.FullTag()
|
||||
}
|
||||
fmt.Println(tag)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -564,7 +564,7 @@ type buildCtx struct {
|
||||
|
||||
// Reader gets an io.Reader by iterating over the sources, tarring up the content after rewriting the paths.
|
||||
// It assumes that sources is sane, ie is well formed and the first part is an absolute path
|
||||
// and that it exists. NewFromCLI() ensures that.
|
||||
// and that it exists.
|
||||
func (c *buildCtx) Reader() io.ReadCloser {
|
||||
r, w := io.Pipe()
|
||||
tw := tar.NewWriter(w)
|
||||
|
||||
@@ -2,7 +2,6 @@ package pkglib
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
@@ -36,6 +35,32 @@ type pkgInfo struct {
|
||||
} `yaml:"depends"`
|
||||
}
|
||||
|
||||
// PkglibConfig contains the configuration for the pkglib package.
|
||||
// It is used to override the default behaviour of the package.
|
||||
// Fields that are pointers are so that the caller can leave it as nil
|
||||
// for "use whatever default pkglib has", while non-nil means "explicitly override".
|
||||
type PkglibConfig struct {
|
||||
DisableCache *bool
|
||||
Network *bool
|
||||
Org *string
|
||||
BuildYML string
|
||||
Hash string
|
||||
HashCommit string
|
||||
HashPath string
|
||||
Dirty bool
|
||||
Dev bool
|
||||
}
|
||||
|
||||
func NewPkgInfo() pkgInfo {
|
||||
return pkgInfo{
|
||||
Org: "linuxkit",
|
||||
Arches: []string{"amd64", "arm64", "s390x"},
|
||||
GitRepo: "https://github.com/linuxkit/linuxkit",
|
||||
Network: false,
|
||||
DisableCache: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Specifies the source directory for a package and their destination in the build context.
|
||||
type pkgSource struct {
|
||||
src string
|
||||
@@ -65,16 +90,10 @@ type Pkg struct {
|
||||
git *git
|
||||
}
|
||||
|
||||
// NewFromCLI creates a range of Pkg from a set of CLI arguments. Calls fs.Parse()
|
||||
func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
// NewFromConfig creates a range of Pkg from a PkglibConfig and paths to packages.
|
||||
func NewFromConfig(cfg PkglibConfig, args ...string) ([]Pkg, error) {
|
||||
// Defaults
|
||||
piBase := pkgInfo{
|
||||
Org: "linuxkit",
|
||||
Arches: []string{"amd64", "arm64", "s390x"},
|
||||
GitRepo: "https://github.com/linuxkit/linuxkit",
|
||||
Network: false,
|
||||
DisableCache: false,
|
||||
}
|
||||
piBase := NewPkgInfo()
|
||||
|
||||
// TODO(ijc) look for "$(git rev-parse --show-toplevel)/.build-defaults.yml"?
|
||||
|
||||
@@ -83,49 +102,23 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
|
||||
// These override fields in pi below, bools are in both forms to allow user overrides in either direction.
|
||||
// These will apply to all packages built.
|
||||
argDisableCache := fs.Bool("disable-cache", piBase.DisableCache, "Disable build cache")
|
||||
argEnableCache := fs.Bool("enable-cache", !piBase.DisableCache, "Enable build cache")
|
||||
argNoNetwork := fs.Bool("nonetwork", !piBase.Network, "Disallow network use during build")
|
||||
argNetwork := fs.Bool("network", piBase.Network, "Allow network use during build")
|
||||
|
||||
argOrg := fs.String("org", piBase.Org, "Override the hub org")
|
||||
|
||||
// Other arguments
|
||||
var buildYML, hash, hashCommit, hashPath string
|
||||
var dirty, devMode bool
|
||||
|
||||
fs.StringVar(&buildYML, "build-yml", "build.yml", "Override the name of the yml file")
|
||||
fs.StringVar(&hash, "hash", "", "Override the image hash (default is to query git for the package's tree-sh)")
|
||||
fs.StringVar(&hashCommit, "hash-commit", "HEAD", "Override the git commit to use for the hash")
|
||||
fs.StringVar(&hashPath, "hash-path", "", "Override the directory to use for the image hash, must be a parent of the package dir (default is to use the package dir)")
|
||||
fs.BoolVar(&dirty, "force-dirty", false, "Force the pkg(s) to be considered dirty")
|
||||
fs.BoolVar(&devMode, "dev", false, "Force org and hash to $USER and \"dev\" respectively")
|
||||
|
||||
util.AddLoggingFlags(fs)
|
||||
|
||||
_ = fs.Parse(args)
|
||||
|
||||
util.SetupLogging()
|
||||
|
||||
if fs.NArg() < 1 {
|
||||
return nil, fmt.Errorf("At least one pkg directory is required")
|
||||
}
|
||||
|
||||
var pkgs []Pkg
|
||||
for _, pkg := range fs.Args() {
|
||||
for _, pkg := range args {
|
||||
var (
|
||||
pkgHashPath string
|
||||
pkgHash = hash
|
||||
pkgHash = cfg.Hash
|
||||
)
|
||||
pkgPath, err := filepath.Abs(pkg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if hashPath == "" {
|
||||
if cfg.HashPath == "" {
|
||||
pkgHashPath = pkgPath
|
||||
} else {
|
||||
pkgHashPath, err = filepath.Abs(hashPath)
|
||||
pkgHashPath, err = filepath.Abs(cfg.HashPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -147,7 +140,7 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
b, err := os.ReadFile(filepath.Join(pkgPath, buildYML))
|
||||
b, err := os.ReadFile(filepath.Join(pkgPath, cfg.BuildYML))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -165,7 +158,7 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if devMode {
|
||||
if cfg.Dev {
|
||||
// If --org is also used then this will be overwritten
|
||||
// by argOrg when we iterate over the provided options
|
||||
// in the fs.Visit block below.
|
||||
@@ -179,21 +172,15 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
// apart from Visit which iterates over only those which were
|
||||
// set. This must be run here, rather than earlier, because we need to
|
||||
// have read it from the build.yml file first, then override based on CLI.
|
||||
fs.Visit(func(f *flag.Flag) {
|
||||
switch f.Name {
|
||||
case "disable-cache":
|
||||
pi.DisableCache = *argDisableCache
|
||||
case "enable-cache":
|
||||
pi.DisableCache = !*argEnableCache
|
||||
case "network":
|
||||
pi.Network = *argNetwork
|
||||
case "nonetwork":
|
||||
pi.Network = !*argNoNetwork
|
||||
case "org":
|
||||
pi.Org = *argOrg
|
||||
}
|
||||
})
|
||||
|
||||
if cfg.DisableCache != nil {
|
||||
pi.DisableCache = *cfg.DisableCache
|
||||
}
|
||||
if cfg.Network != nil {
|
||||
pi.Network = *cfg.Network
|
||||
}
|
||||
if cfg.Org != nil {
|
||||
pi.Org = *cfg.Org
|
||||
}
|
||||
var srcHashes string
|
||||
sources := []pkgSource{{src: pkgPath, dst: "/"}}
|
||||
|
||||
@@ -216,7 +203,7 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
if g == nil {
|
||||
return nil, fmt.Errorf("Source %s not in a git repository", srcPath)
|
||||
}
|
||||
h, err := g.treeHash(srcPath, hashCommit)
|
||||
h, err := g.treeHash(srcPath, cfg.HashCommit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -230,16 +217,17 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var dirty bool
|
||||
if git != nil {
|
||||
gitDirty, err := git.isDirty(pkgHashPath, hashCommit)
|
||||
gitDirty, err := git.isDirty(pkgHashPath, cfg.HashCommit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dirty = dirty || gitDirty
|
||||
dirty = cfg.Dirty || gitDirty
|
||||
|
||||
if pkgHash == "" {
|
||||
if pkgHash, err = git.treeHash(pkgHashPath, hashCommit); err != nil {
|
||||
if pkgHash, err = git.treeHash(pkgHashPath, cfg.HashCommit); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -266,7 +254,7 @@ func NewFromCLI(fs *flag.FlagSet, args ...string) ([]Pkg, error) {
|
||||
image: pi.Image,
|
||||
org: pi.Org,
|
||||
hash: pkgHash,
|
||||
commitHash: hashCommit,
|
||||
commitHash: cfg.HashCommit,
|
||||
arches: pi.Arches,
|
||||
sources: sources,
|
||||
gitRepo: pi.GitRepo,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package pkglib
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
@@ -21,66 +23,84 @@ func dummyPackage(t *testing.T, tmpDir, yml string) string {
|
||||
return d
|
||||
}
|
||||
|
||||
func testBool(t *testing.T, key string, inv bool, forceOn, forceOff string, get func(p Pkg) bool) {
|
||||
// testGetBoolPkg given a combination of field, fileKey, fileSetting and override setting,
|
||||
// create a Pkg that reflects it.
|
||||
func testGetBoolPkg(t *testing.T, fileKey, cfgKey string, fileSetting, cfgSetting *bool) Pkg {
|
||||
// create a git-enabled temporary working directory
|
||||
cwd, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
|
||||
tmpDir := filepath.Join(cwd, t.Name())
|
||||
err = os.Mkdir(tmpDir, 0755)
|
||||
tmpdirBase := path.Join(cwd, "testdatadir")
|
||||
err = os.MkdirAll(tmpdirBase, 0755)
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
check := func(pkgDir, override string, f func(t *testing.T, p Pkg)) func(t *testing.T) {
|
||||
return func(t *testing.T) {
|
||||
flags := flag.NewFlagSet(t.Name(), flag.ExitOnError)
|
||||
args := []string{"-hash-path=" + cwd}
|
||||
if override != "" {
|
||||
args = append(args, override)
|
||||
}
|
||||
args = append(args, pkgDir)
|
||||
pkgs, err := NewFromCLI(flags, args...)
|
||||
require.NoError(t, err)
|
||||
pkg := pkgs[0]
|
||||
t.Logf("override %q produced %t", override, get(pkg))
|
||||
f(t, pkg)
|
||||
}
|
||||
tmpDir, err := os.MkdirTemp(tmpdirBase, "pkglib_test")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(tmpdirBase)
|
||||
var value string
|
||||
if fileSetting != nil {
|
||||
value = fmt.Sprintf("%s: %v\n", fileKey, *fileSetting)
|
||||
}
|
||||
|
||||
setting := func(name, cfg string, def bool) {
|
||||
var value string
|
||||
if cfg != "" {
|
||||
value = key + ": " + cfg + "\n"
|
||||
}
|
||||
pkgDir := dummyPackage(t, tmpDir, `
|
||||
pkgDir := dummyPackage(t, tmpDir, `
|
||||
image: dummy
|
||||
`+value)
|
||||
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Run("None", check(pkgDir, "", func(t *testing.T, p Pkg) {
|
||||
assert.Equal(t, def, get(p))
|
||||
}))
|
||||
t.Run("ForceOn", check(pkgDir, forceOn, func(t *testing.T, p Pkg) {
|
||||
assert.True(t, get(p))
|
||||
}))
|
||||
t.Run("ForceOff", check(pkgDir, forceOff, func(t *testing.T, p Pkg) {
|
||||
assert.False(t, get(p))
|
||||
}))
|
||||
cfg := PkglibConfig{
|
||||
HashPath: cwd,
|
||||
BuildYML: "build.yml",
|
||||
HashCommit: "HEAD",
|
||||
}
|
||||
if cfgSetting != nil {
|
||||
cfgField := reflect.ValueOf(&cfg).Elem().FieldByName(cfgKey)
|
||||
cfgField.Set(reflect.ValueOf(cfgSetting))
|
||||
}
|
||||
pkgs, err := NewFromConfig(cfg, pkgDir)
|
||||
require.NoError(t, err)
|
||||
return pkgs[0]
|
||||
}
|
||||
|
||||
func TestBoolSettings(t *testing.T) {
|
||||
// this is false, because the default is to disable network. The option "Network"
|
||||
// is aligned with the value p.network
|
||||
var (
|
||||
trueVal = true
|
||||
falseVal = false
|
||||
)
|
||||
tests := []struct {
|
||||
testName string
|
||||
cfgKey string
|
||||
fileKey string
|
||||
fileSetting *bool
|
||||
cfgSetting *bool
|
||||
pkgField string
|
||||
expectation bool
|
||||
}{
|
||||
{"Network/Default/None", "Network", "network", nil, nil, "network", false},
|
||||
{"Network/Default/ForceOn", "Network", "network", nil, &trueVal, "network", true},
|
||||
{"Network/Default/ForceOff", "Network", "network", nil, &falseVal, "network", false},
|
||||
{"Network/SetTrue/None", "Network", "network", &trueVal, nil, "network", true},
|
||||
{"Network/SetTrue/ForceOn", "Network", "network", &trueVal, &trueVal, "network", true},
|
||||
{"Network/SetTrue/ForceOff", "Network", "network", &trueVal, &falseVal, "network", false},
|
||||
{"Network/SetFalse/None", "Network", "network", &falseVal, nil, "network", false},
|
||||
{"Network/SetFalse/ForceOn", "Network", "network", &falseVal, &trueVal, "network", true},
|
||||
{"Network/SetFalse/ForceOff", "Network", "network", &falseVal, &falseVal, "network", false},
|
||||
{"Cache/Default/None", "DisableCache", "disable-cache", nil, nil, "cache", true},
|
||||
{"Cache/Default/ForceOn", "DisableCache", "disable-cache", nil, &trueVal, "cache", false},
|
||||
{"Cache/Default/ForceOff", "DisableCache", "disable-cache", nil, &falseVal, "cache", true},
|
||||
{"Cache/SetTrue/None", "DisableCache", "disable-cache", &trueVal, nil, "cache", false},
|
||||
{"Cache/SetTrue/ForceOn", "DisableCache", "disable-cache", &trueVal, &trueVal, "cache", false},
|
||||
{"Cache/SetTrue/ForceOff", "DisableCache", "disable-cache", &trueVal, &falseVal, "cache", true},
|
||||
{"Cache/SetFalse/None", "DisableCache", "disable-cache", &falseVal, nil, "cache", true},
|
||||
{"Cache/SetFalse/ForceOn", "DisableCache", "disable-cache", &falseVal, &trueVal, "cache", false},
|
||||
{"Cache/SetFalse/ForceOff", "DisableCache", "disable-cache", &falseVal, &falseVal, "cache", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.testName, func(t *testing.T) {
|
||||
pkg := testGetBoolPkg(t, tt.fileKey, tt.cfgKey, tt.fileSetting, tt.cfgSetting)
|
||||
returned := reflect.ValueOf(&pkg).Elem().FieldByName(tt.pkgField)
|
||||
|
||||
t.Logf("override field %s value %v produced %t", tt.cfgKey, tt.cfgSetting, returned.Bool())
|
||||
assert.Equal(t, tt.expectation, returned.Bool())
|
||||
})
|
||||
}
|
||||
|
||||
// `inv` indicates that the sense of the boolean in
|
||||
// `build.yml` is inverted, booleans default to false.
|
||||
setting("Default", "", inv)
|
||||
setting("SetTrue", "true", !inv)
|
||||
setting("SetFalse", "false", inv)
|
||||
}
|
||||
|
||||
func TestNetwork(t *testing.T) {
|
||||
testBool(t, "network", false, "-network", "-nonetwork", func(p Pkg) bool { return p.network })
|
||||
}
|
||||
|
||||
func TestCache(t *testing.T) {
|
||||
testBool(t, "disable-cache", true, "-enable-cache", "-disable-cache", func(p Pkg) bool { return p.cache })
|
||||
}
|
||||
|
||||
func testBadBuildYML(t *testing.T, build, expect string) {
|
||||
@@ -93,9 +113,11 @@ func testBadBuildYML(t *testing.T, build, expect string) {
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
pkgDir := dummyPackage(t, tmpDir, build)
|
||||
flags := flag.NewFlagSet(t.Name(), flag.ExitOnError)
|
||||
args := []string{"-hash-path=" + cwd, pkgDir}
|
||||
_, err = NewFromCLI(flags, args...)
|
||||
_, err = NewFromConfig(PkglibConfig{
|
||||
HashPath: cwd,
|
||||
BuildYML: "build.yml",
|
||||
HashCommit: "HEAD",
|
||||
}, pkgDir)
|
||||
require.Error(t, err)
|
||||
assert.Regexp(t, regexp.MustCompile(expect), err.Error())
|
||||
}
|
||||
|
||||
@@ -1,58 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func pushUsage() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Printf("USAGE: %s push [backend] [options] [prefix]\n\n", invoked)
|
||||
fmt.Printf("'backend' specifies the push backend.\n")
|
||||
fmt.Printf("Supported backends are\n")
|
||||
// Please keep these in alphabetical order
|
||||
fmt.Printf(" aws\n")
|
||||
fmt.Printf(" azure\n")
|
||||
fmt.Printf(" gcp\n")
|
||||
fmt.Printf(" openstack\n")
|
||||
fmt.Printf(" packet\n")
|
||||
fmt.Printf(" scaleway\n")
|
||||
fmt.Printf(" vcenter\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("'options' are the backend specific options.\n")
|
||||
fmt.Printf("See '%s push [backend] --help' for details.\n\n", invoked)
|
||||
fmt.Printf("'prefix' specifies the path to the VM image.\n")
|
||||
}
|
||||
func pushCmd() *cobra.Command {
|
||||
|
||||
func push(args []string) {
|
||||
if len(args) < 1 {
|
||||
pushUsage()
|
||||
os.Exit(1)
|
||||
cmd := &cobra.Command{
|
||||
Use: "push",
|
||||
Short: "push a VM image to a cloud provider",
|
||||
Long: `Push a VM image to a cloud provider.`,
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
// Please keep cases in alphabetical order
|
||||
case "aws":
|
||||
pushAWS(args[1:])
|
||||
case "azure":
|
||||
pushAzure(args[1:])
|
||||
case "gcp":
|
||||
pushGcp(args[1:])
|
||||
case "openstack":
|
||||
pushOpenstack(args[1:])
|
||||
case "packet":
|
||||
pushPacket(args[1:])
|
||||
case "scaleway":
|
||||
pushScaleway(args[1:])
|
||||
case "vcenter":
|
||||
pushVCenter(args[1:])
|
||||
case "help", "-h", "-help", "--help":
|
||||
pushUsage()
|
||||
os.Exit(0)
|
||||
default:
|
||||
log.Errorf("No 'push' backend specified.")
|
||||
}
|
||||
cmd.AddCommand(pushAWSCmd())
|
||||
cmd.AddCommand(pushAzureCmd())
|
||||
cmd.AddCommand(pushGCPCmd())
|
||||
cmd.AddCommand(pushOpenstackCmd())
|
||||
cmd.AddCommand(pushPacketCmd())
|
||||
cmd.AddCommand(pushScalewayCmd())
|
||||
cmd.AddCommand(pushVCenterCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -14,174 +13,181 @@ import (
|
||||
"github.com/aws/aws-sdk-go/service/ec2"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const timeoutVar = "LINUXKIT_UPLOAD_TIMEOUT"
|
||||
|
||||
func pushAWS(args []string) {
|
||||
flags := flag.NewFlagSet("aws", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s push aws [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' specifies the full path of an AWS image. It will be uploaded to S3 and an AMI will be created from it.\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
timeoutFlag := flags.Int("timeout", 0, "Upload timeout in seconds")
|
||||
bucketFlag := flags.String("bucket", "", "S3 Bucket to upload to. *Required*")
|
||||
nameFlag := flags.String("img-name", "", "Overrides the name used to identify the file in Amazon S3 and the VM image. Defaults to the base of 'path' with the file extension removed.")
|
||||
enaFlag := flags.Bool("ena", false, "Enable ENA networking")
|
||||
sriovNetFlag := flags.String("sriov", "", "SRIOV network support, set to 'simple' to enable 82599 VF networking")
|
||||
uefiFlag := flags.Bool("uefi", false, "Enable uefi boot mode.")
|
||||
tpmFlag := flags.Bool("tpm", false, "Enable tpm device.")
|
||||
func pushAWSCmd() *cobra.Command {
|
||||
var (
|
||||
timeoutFlag int
|
||||
bucketFlag string
|
||||
nameFlag string
|
||||
ena bool
|
||||
sriovNet string
|
||||
uefi bool
|
||||
tpm bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "aws",
|
||||
Short: "push image to AWS",
|
||||
Long: `Push image to AWS.
|
||||
Single argument specifies the full path of an AWS image. It will be uploaded to S3 and an AMI will be created from it.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
timeout := getIntValue(timeoutVar, timeoutFlag, 600)
|
||||
bucket := getStringValue(bucketVar, bucketFlag, "")
|
||||
name := getStringValue(nameVar, nameFlag, "")
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the path to the image to push\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
|
||||
timeout := getIntValue(timeoutVar, *timeoutFlag, 600)
|
||||
bucket := getStringValue(bucketVar, *bucketFlag, "")
|
||||
name := getStringValue(nameVar, *nameFlag, "")
|
||||
if *sriovNetFlag == "" {
|
||||
sriovNetFlag = nil
|
||||
}
|
||||
|
||||
if !*uefiFlag && *tpmFlag {
|
||||
log.Fatal("Cannot use tpm without uefi mode")
|
||||
}
|
||||
|
||||
sess := session.Must(session.NewSession())
|
||||
storage := s3.New(sess)
|
||||
|
||||
ctx, cancelFn := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancelFn()
|
||||
|
||||
if bucket == "" {
|
||||
log.Fatalf("Please provide the bucket to use")
|
||||
}
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
log.Fatalf("Error opening file: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(path, filepath.Ext(path))
|
||||
name = filepath.Base(name)
|
||||
}
|
||||
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
log.Fatalf("Error reading file information: %v", err)
|
||||
}
|
||||
|
||||
dst := name + filepath.Ext(path)
|
||||
putParams := &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(dst),
|
||||
Body: f,
|
||||
ContentLength: aws.Int64(fi.Size()),
|
||||
ContentType: aws.String("application/octet-stream"),
|
||||
}
|
||||
log.Debugf("PutObject:\n%v", putParams)
|
||||
|
||||
_, err = storage.PutObjectWithContext(ctx, putParams)
|
||||
if err != nil {
|
||||
log.Fatalf("Error uploading to S3: %v", err)
|
||||
}
|
||||
|
||||
compute := ec2.New(sess)
|
||||
|
||||
importParams := &ec2.ImportSnapshotInput{
|
||||
Description: aws.String(fmt.Sprintf("LinuxKit: %s", name)),
|
||||
DiskContainer: &ec2.SnapshotDiskContainer{
|
||||
Description: aws.String(fmt.Sprintf("LinuxKit: %s disk", name)),
|
||||
Format: aws.String("raw"),
|
||||
UserBucket: &ec2.UserBucket{
|
||||
S3Bucket: aws.String(bucket),
|
||||
S3Key: aws.String(dst),
|
||||
},
|
||||
},
|
||||
}
|
||||
log.Debugf("ImportSnapshot:\n%v", importParams)
|
||||
|
||||
resp, err := compute.ImportSnapshot(importParams)
|
||||
if err != nil {
|
||||
log.Fatalf("Error importing snapshot: %v", err)
|
||||
}
|
||||
|
||||
var snapshotID *string
|
||||
for {
|
||||
describeParams := &ec2.DescribeImportSnapshotTasksInput{
|
||||
ImportTaskIds: []*string{
|
||||
resp.ImportTaskId,
|
||||
},
|
||||
}
|
||||
log.Debugf("DescribeImportSnapshotTask:\n%v", describeParams)
|
||||
status, err := compute.DescribeImportSnapshotTasks(describeParams)
|
||||
if err != nil {
|
||||
log.Fatalf("Error getting import snapshot status: %v", err)
|
||||
}
|
||||
if len(status.ImportSnapshotTasks) == 0 {
|
||||
log.Fatalf("Unable to get import snapshot task status")
|
||||
}
|
||||
if *status.ImportSnapshotTasks[0].SnapshotTaskDetail.Status != "completed" {
|
||||
progress := "0"
|
||||
if status.ImportSnapshotTasks[0].SnapshotTaskDetail.Progress != nil {
|
||||
progress = *status.ImportSnapshotTasks[0].SnapshotTaskDetail.Progress
|
||||
var sriovNetFlag *string
|
||||
if sriovNet != "" {
|
||||
*sriovNetFlag = sriovNet
|
||||
}
|
||||
log.Debugf("Task %s is %s%% complete. Waiting 60 seconds...\n", *resp.ImportTaskId, progress)
|
||||
time.Sleep(60 * time.Second)
|
||||
continue
|
||||
}
|
||||
snapshotID = status.ImportSnapshotTasks[0].SnapshotTaskDetail.SnapshotId
|
||||
break
|
||||
}
|
||||
|
||||
if snapshotID == nil {
|
||||
log.Fatalf("SnapshotID unavailable after import completed")
|
||||
} else {
|
||||
log.Debugf("SnapshotID: %s", *snapshotID)
|
||||
}
|
||||
if !uefi && tpm {
|
||||
return fmt.Errorf("Cannot use tpm without uefi mode")
|
||||
}
|
||||
|
||||
regParams := &ec2.RegisterImageInput{
|
||||
Name: aws.String(name), // Required
|
||||
Architecture: aws.String("x86_64"),
|
||||
BlockDeviceMappings: []*ec2.BlockDeviceMapping{
|
||||
{
|
||||
DeviceName: aws.String("/dev/sda1"),
|
||||
Ebs: &ec2.EbsBlockDevice{
|
||||
DeleteOnTermination: aws.Bool(true),
|
||||
SnapshotId: snapshotID,
|
||||
VolumeType: aws.String("standard"),
|
||||
sess := session.Must(session.NewSession())
|
||||
storage := s3.New(sess)
|
||||
|
||||
ctx, cancelFn := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancelFn()
|
||||
|
||||
if bucket == "" {
|
||||
return fmt.Errorf("Please provide the bucket to use")
|
||||
}
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error opening file: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(path, filepath.Ext(path))
|
||||
name = filepath.Base(name)
|
||||
}
|
||||
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error reading file information: %v", err)
|
||||
}
|
||||
|
||||
dst := name + filepath.Ext(path)
|
||||
putParams := &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(dst),
|
||||
Body: f,
|
||||
ContentLength: aws.Int64(fi.Size()),
|
||||
ContentType: aws.String("application/octet-stream"),
|
||||
}
|
||||
log.Debugf("PutObject:\n%v", putParams)
|
||||
|
||||
_, err = storage.PutObjectWithContext(ctx, putParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error uploading to S3: %v", err)
|
||||
}
|
||||
|
||||
compute := ec2.New(sess)
|
||||
|
||||
importParams := &ec2.ImportSnapshotInput{
|
||||
Description: aws.String(fmt.Sprintf("LinuxKit: %s", name)),
|
||||
DiskContainer: &ec2.SnapshotDiskContainer{
|
||||
Description: aws.String(fmt.Sprintf("LinuxKit: %s disk", name)),
|
||||
Format: aws.String("raw"),
|
||||
UserBucket: &ec2.UserBucket{
|
||||
S3Bucket: aws.String(bucket),
|
||||
S3Key: aws.String(dst),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
log.Debugf("ImportSnapshot:\n%v", importParams)
|
||||
|
||||
resp, err := compute.ImportSnapshot(importParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error importing snapshot: %v", err)
|
||||
}
|
||||
|
||||
var snapshotID *string
|
||||
for {
|
||||
describeParams := &ec2.DescribeImportSnapshotTasksInput{
|
||||
ImportTaskIds: []*string{
|
||||
resp.ImportTaskId,
|
||||
},
|
||||
}
|
||||
log.Debugf("DescribeImportSnapshotTask:\n%v", describeParams)
|
||||
status, err := compute.DescribeImportSnapshotTasks(describeParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting import snapshot status: %v", err)
|
||||
}
|
||||
if len(status.ImportSnapshotTasks) == 0 {
|
||||
return fmt.Errorf("Unable to get import snapshot task status")
|
||||
}
|
||||
if *status.ImportSnapshotTasks[0].SnapshotTaskDetail.Status != "completed" {
|
||||
progress := "0"
|
||||
if status.ImportSnapshotTasks[0].SnapshotTaskDetail.Progress != nil {
|
||||
progress = *status.ImportSnapshotTasks[0].SnapshotTaskDetail.Progress
|
||||
}
|
||||
log.Debugf("Task %s is %s%% complete. Waiting 60 seconds...\n", *resp.ImportTaskId, progress)
|
||||
time.Sleep(60 * time.Second)
|
||||
continue
|
||||
}
|
||||
snapshotID = status.ImportSnapshotTasks[0].SnapshotTaskDetail.SnapshotId
|
||||
break
|
||||
}
|
||||
|
||||
if snapshotID == nil {
|
||||
return fmt.Errorf("SnapshotID unavailable after import completed")
|
||||
} else {
|
||||
log.Debugf("SnapshotID: %s", *snapshotID)
|
||||
}
|
||||
|
||||
regParams := &ec2.RegisterImageInput{
|
||||
Name: aws.String(name), // Required
|
||||
Architecture: aws.String("x86_64"),
|
||||
BlockDeviceMappings: []*ec2.BlockDeviceMapping{
|
||||
{
|
||||
DeviceName: aws.String("/dev/sda1"),
|
||||
Ebs: &ec2.EbsBlockDevice{
|
||||
DeleteOnTermination: aws.Bool(true),
|
||||
SnapshotId: snapshotID,
|
||||
VolumeType: aws.String("standard"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Description: aws.String(fmt.Sprintf("LinuxKit: %s image", name)),
|
||||
RootDeviceName: aws.String("/dev/sda1"),
|
||||
VirtualizationType: aws.String("hvm"),
|
||||
EnaSupport: &ena,
|
||||
SriovNetSupport: sriovNetFlag,
|
||||
}
|
||||
if uefi {
|
||||
regParams.BootMode = aws.String("uefi")
|
||||
if tpm {
|
||||
regParams.TpmSupport = aws.String("v2.0")
|
||||
}
|
||||
}
|
||||
log.Debugf("RegisterImage:\n%v", regParams)
|
||||
regResp, err := compute.RegisterImage(regParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error registering the image: %s; %v", name, err)
|
||||
}
|
||||
log.Infof("Created AMI: %s", *regResp.ImageId)
|
||||
return nil
|
||||
},
|
||||
Description: aws.String(fmt.Sprintf("LinuxKit: %s image", name)),
|
||||
RootDeviceName: aws.String("/dev/sda1"),
|
||||
VirtualizationType: aws.String("hvm"),
|
||||
EnaSupport: enaFlag,
|
||||
SriovNetSupport: sriovNetFlag,
|
||||
}
|
||||
if *uefiFlag {
|
||||
regParams.BootMode = aws.String("uefi")
|
||||
if *tpmFlag {
|
||||
regParams.TpmSupport = aws.String("v2.0")
|
||||
}
|
||||
}
|
||||
log.Debugf("RegisterImage:\n%v", regParams)
|
||||
regResp, err := compute.RegisterImage(regParams)
|
||||
if err != nil {
|
||||
log.Fatalf("Error registering the image: %s; %v", name, err)
|
||||
}
|
||||
log.Infof("Created AMI: %s", *regResp.ImageId)
|
||||
|
||||
cmd.Flags().IntVar(&timeoutFlag, "timeout", 0, "Upload timeout in seconds")
|
||||
cmd.Flags().StringVar(&bucketFlag, "bucket", "", "S3 Bucket to upload to. *Required*")
|
||||
cmd.Flags().StringVar(&nameFlag, "img-name", "", "Overrides the name used to identify the file in Amazon S3 and the VM image. Defaults to the base of 'path' with the file extension removed.")
|
||||
cmd.Flags().BoolVar(&ena, "ena", false, "Enable ENA networking")
|
||||
cmd.Flags().StringVar(&sriovNet, "sriov", "", "SRIOV network support, set to 'simple' to enable 82599 VF networking")
|
||||
cmd.Flags().BoolVar(&uefi, "uefi", false, "Enable uefi boot mode.")
|
||||
cmd.Flags().BoolVar(&tpm, "tpm", false, "Enable tpm device.")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,47 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func pushAzure(args []string) {
|
||||
flags := flag.NewFlagSet("azure", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s push azure [options] path\n\n", invoked)
|
||||
fmt.Printf("Push a disk image to Azure\n")
|
||||
fmt.Printf("'path' specifies the path to a VHD. It will be uploaded to an Azure Storage Account.\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
func pushAzureCmd() *cobra.Command {
|
||||
var (
|
||||
resourceGroup string
|
||||
accountName string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "azure",
|
||||
Short: "push image to Azure",
|
||||
Long: `Push image to Azure.
|
||||
First argument specifies the path to a VHD. It will be uploaded to an Azure Storage Account.
|
||||
Relies on the following environment variables:
|
||||
|
||||
AZURE_SUBSCRIPTION_ID
|
||||
AZURE_TENANT_ID
|
||||
AZURE_CLIENT_ID
|
||||
AZURE_CLIENT_SECRET
|
||||
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
|
||||
subscriptionID := getEnvVarOrExit("AZURE_SUBSCRIPTION_ID")
|
||||
tenantID := getEnvVarOrExit("AZURE_TENANT_ID")
|
||||
|
||||
clientID := getEnvVarOrExit("AZURE_CLIENT_ID")
|
||||
clientSecret := getEnvVarOrExit("AZURE_CLIENT_SECRET")
|
||||
|
||||
initializeAzureClients(subscriptionID, tenantID, clientID, clientSecret)
|
||||
|
||||
uploadVMImage(resourceGroup, accountName, path)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
resourceGroup := flags.String("resource-group", "", "Name of resource group to be used for VM")
|
||||
accountName := flags.String("storage-account", "", "Name of the storage account")
|
||||
cmd.Flags().StringVar(&resourceGroup, "resource-group", "", "Name of resource group to be used for VM")
|
||||
cmd.Flags().StringVar(&accountName, "storage-account", "", "Name of the storage account")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the path to the image to push\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
|
||||
subscriptionID := getEnvVarOrExit("AZURE_SUBSCRIPTION_ID")
|
||||
tenantID := getEnvVarOrExit("AZURE_TENANT_ID")
|
||||
|
||||
clientID := getEnvVarOrExit("AZURE_CLIENT_ID")
|
||||
clientSecret := getEnvVarOrExit("AZURE_CLIENT_SECRET")
|
||||
|
||||
initializeAzureClients(subscriptionID, tenantID, clientID, clientSecret)
|
||||
|
||||
uploadVMImage(*resourceGroup, *accountName, path)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,73 +1,78 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func pushGcp(args []string) {
|
||||
flags := flag.NewFlagSet("gcp", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s push gcp [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' is the full path to a GCP image. It will be uploaded to GCS and GCP VM image will be created from it.\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
keysFlag := flags.String("keys", "", "Path to Service Account JSON key file")
|
||||
projectFlag := flags.String("project", "", "GCP Project Name")
|
||||
bucketFlag := flags.String("bucket", "", "GCS Bucket to upload to. *Required*")
|
||||
publicFlag := flags.Bool("public", false, "Select if file on GCS should be public. *Optional*")
|
||||
familyFlag := flags.String("family", "", "GCP Image Family. A group of images where the family name points to the most recent image. *Optional*")
|
||||
nameFlag := flags.String("img-name", "", "Overrides the name used to identify the file in Google Storage and the VM image. Defaults to the base of 'path' with the '.img.tar.gz' suffix removed")
|
||||
nestedVirt := flags.Bool("nested-virt", false, "Enabled nested virtualization for the image")
|
||||
uefiCompatible := flags.Bool("uefi-compatible", false, "Enable UEFI_COMPATIBLE feature for the image, required to enable vTPM.")
|
||||
func pushGCPCmd() *cobra.Command {
|
||||
var (
|
||||
keysFlag string
|
||||
projectFlag string
|
||||
bucketFlag string
|
||||
publicFlag bool
|
||||
familyFlag string
|
||||
nameFlag string
|
||||
nestedVirt bool
|
||||
uefi bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "gcp",
|
||||
Short: "push image to GCP",
|
||||
Long: `Push image to GCP.
|
||||
First argument specifies the path to a disk file.
|
||||
It will be uploaded to GCS and GCP VM image will be created from it.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
keys := getStringValue(keysVar, keysFlag, "")
|
||||
project := getStringValue(projectVar, projectFlag, "")
|
||||
bucket := getStringValue(bucketVar, bucketFlag, "")
|
||||
public := getBoolValue(publicVar, publicFlag)
|
||||
family := getStringValue(familyVar, familyFlag, "")
|
||||
name := getStringValue(nameVar, nameFlag, "")
|
||||
|
||||
const suffix = ".img.tar.gz"
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(path, suffix)
|
||||
name = filepath.Base(name)
|
||||
}
|
||||
|
||||
client, err := NewGCPClient(keys, project)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to connect to GCP: %v", err)
|
||||
}
|
||||
|
||||
if bucket == "" {
|
||||
return fmt.Errorf("Please specify the bucket to use")
|
||||
}
|
||||
|
||||
err = client.UploadFile(path, name+suffix, bucket, public)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error copying to Google Storage: %v", err)
|
||||
}
|
||||
err = client.CreateImage(name, "https://storage.googleapis.com/"+bucket+"/"+name+suffix, family, nestedVirt, uefi, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating Google Compute Image: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the path to the image to push\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
cmd.Flags().StringVar(&keysFlag, "keys", "", "Path to Service Account JSON key file")
|
||||
cmd.Flags().StringVar(&projectFlag, "project", "", "GCP Project Name")
|
||||
cmd.Flags().StringVar(&bucketFlag, "bucket", "", "GCS Bucket to upload to. *Required*")
|
||||
cmd.Flags().BoolVar(&publicFlag, "public", false, "Select if file on GCS should be public. *Optional*")
|
||||
cmd.Flags().StringVar(&familyFlag, "family", "", "GCP Image Family. A group of images where the family name points to the most recent image. *Optional*")
|
||||
cmd.Flags().StringVar(&nameFlag, "img-name", "", "Overrides the name used to identify the file in Google Storage and the VM image. Defaults to the base of 'path' with the '.img.tar.gz' suffix removed")
|
||||
cmd.Flags().BoolVar(&nestedVirt, "nested-virt", false, "Enabled nested virtualization for the image")
|
||||
cmd.Flags().BoolVar(&uefi, "uefi-compatible", false, "Enable UEFI_COMPATIBLE feature for the image, required to enable vTPM.")
|
||||
|
||||
keys := getStringValue(keysVar, *keysFlag, "")
|
||||
project := getStringValue(projectVar, *projectFlag, "")
|
||||
bucket := getStringValue(bucketVar, *bucketFlag, "")
|
||||
public := getBoolValue(publicVar, *publicFlag)
|
||||
family := getStringValue(familyVar, *familyFlag, "")
|
||||
name := getStringValue(nameVar, *nameFlag, "")
|
||||
|
||||
const suffix = ".img.tar.gz"
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(path, suffix)
|
||||
name = filepath.Base(name)
|
||||
}
|
||||
|
||||
client, err := NewGCPClient(keys, project)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to connect to GCP: %v", err)
|
||||
}
|
||||
|
||||
if bucket == "" {
|
||||
log.Fatalf("Please specify the bucket to use")
|
||||
}
|
||||
|
||||
err = client.UploadFile(path, name+suffix, bucket, public)
|
||||
if err != nil {
|
||||
log.Fatalf("Error copying to Google Storage: %v", err)
|
||||
}
|
||||
err = client.CreateImage(name, "https://storage.googleapis.com/"+bucket+"/"+name+suffix, family, *nestedVirt, *uefiCompatible, true)
|
||||
if err != nil {
|
||||
log.Fatalf("Error creating Google Compute Image: %v", err)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
@@ -12,44 +11,11 @@ import (
|
||||
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/imagedata"
|
||||
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
|
||||
"github.com/gophercloud/utils/openstack/clientconfig"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func pushOpenstack(args []string) {
|
||||
flags := flag.NewFlagSet("openstack", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s push openstack [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' is the full path to an image that will be uploaded to an OpenStack Image store (Glance)\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
imageName := flags.String("img-name", "", "A unique name for the image, if blank the filename will be used")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the path to the image to push\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
filePath := remArgs[0]
|
||||
// Check that the file both exists, and can be read
|
||||
checkFile(filePath)
|
||||
|
||||
client, err := clientconfig.NewServiceClient("image", nil)
|
||||
if err != nil {
|
||||
log.Fatalf("Error connecting to your OpenStack cloud: %s", err)
|
||||
}
|
||||
|
||||
createOpenStackImage(filePath, *imageName, client)
|
||||
}
|
||||
|
||||
func createOpenStackImage(filePath string, imageName string, client *gophercloud.ServiceClient) {
|
||||
// Image formats that are supported by both LinuxKit and OpenStack Glance V2
|
||||
formats := []string{"ami", "vhd", "vhdx", "vmdk", "raw", "qcow2", "iso"}
|
||||
@@ -103,3 +69,35 @@ func createOpenStackImage(filePath string, imageName string, client *gophercloud
|
||||
fmt.Println(image.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func pushOpenstackCmd() *cobra.Command {
|
||||
var (
|
||||
imageName string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "openstack",
|
||||
Short: "push image to OpenStack Image store (Glance)",
|
||||
Long: `Push image to OpenStack Image store (Glance).
|
||||
First argument specifies the path to a disk file.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
|
||||
// Check that the file both exists, and can be read
|
||||
checkFile(path)
|
||||
|
||||
client, err := clientconfig.NewServiceClient("image", nil)
|
||||
if err != nil {
|
||||
log.Fatalf("Error connecting to your OpenStack cloud: %s", err)
|
||||
}
|
||||
|
||||
createOpenStackImage(path, imageName, client)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&imageName, "img-name", "", "A unique name for the image, if blank the filename will be used")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
@@ -12,6 +11,7 @@ import (
|
||||
// drop-in 100% compatible replacement and 17% faster than compress/gzip.
|
||||
gzip "github.com/klauspost/pgzip"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -28,70 +28,77 @@ func init() {
|
||||
}
|
||||
}
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func pushPacket(args []string) {
|
||||
flags := flag.NewFlagSet("packet", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s push packet [options] [name]\n\n", invoked)
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
baseURLFlag := flags.String("base-url", "", "Base URL that the kernel, initrd and iPXE script are served from (or "+packetBaseURL+")")
|
||||
nameFlag := flags.String("img-name", "", "Overrides the prefix used to identify the files. Defaults to [name] (or "+packetNameVar+")")
|
||||
archFlag := flags.String("arch", packetDefaultArch, "Image architecture (x86_64 or aarch64)")
|
||||
decompressFlag := flags.Bool("decompress", packetDefaultDecompress, "Decompress kernel/initrd before pushing")
|
||||
dstFlag := flags.String("destination", "", "URL where to push the image to. Currently only 'file' is supported as a scheme (which is also the default if omitted)")
|
||||
func pushPacketCmd() *cobra.Command {
|
||||
var (
|
||||
baseURLFlag string
|
||||
nameFlag string
|
||||
arch string
|
||||
dst string
|
||||
decompress bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "packet",
|
||||
Short: "push image to Equinix Metal / Packet",
|
||||
Long: `Push image to Equinix Metal / Packet.
|
||||
Single argument is the prefix to use for the image, defualts to "packet".
|
||||
`,
|
||||
Example: "linuxkit push packet [options] [name]",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
prefix := "packet"
|
||||
if len(args) > 0 {
|
||||
prefix = args[0]
|
||||
}
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
baseURL := getStringValue(packetBaseURL, baseURLFlag, "")
|
||||
if baseURL == "" {
|
||||
return fmt.Errorf("Need to specify a value for --base-url from where the kernel, initrd and iPXE script will be loaded from.")
|
||||
}
|
||||
|
||||
if dst == "" {
|
||||
return fmt.Errorf("Need to specify the destination where to push to.")
|
||||
}
|
||||
|
||||
name := getStringValue(packetNameVar, nameFlag, prefix)
|
||||
|
||||
if _, err := os.Stat(fmt.Sprintf("%s-kernel", name)); os.IsNotExist(err) {
|
||||
return fmt.Errorf("kernel file does not exist: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(fmt.Sprintf("%s-initrd.img", name)); os.IsNotExist(err) {
|
||||
return fmt.Errorf("initrd file does not exist: %v", err)
|
||||
}
|
||||
|
||||
// Read kernel command line
|
||||
var cmdline string
|
||||
if c, err := os.ReadFile(prefix + "-cmdline"); err != nil {
|
||||
return fmt.Errorf("Cannot open cmdline file: %v", err)
|
||||
} else {
|
||||
cmdline = string(c)
|
||||
}
|
||||
|
||||
ipxeScript := packetIPXEScript(name, baseURL, cmdline, arch)
|
||||
|
||||
// Parse the destination
|
||||
dst, err := url.Parse(dst)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot parse destination: %v", err)
|
||||
}
|
||||
switch dst.Scheme {
|
||||
case "", "file":
|
||||
packetPushFile(dst, decompress, name, cmdline, ipxeScript)
|
||||
default:
|
||||
return fmt.Errorf("Unknown destination format: %s", dst.Scheme)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
prefix := "packet"
|
||||
if len(remArgs) > 0 {
|
||||
prefix = remArgs[0]
|
||||
}
|
||||
cmd.Flags().StringVar(&baseURLFlag, "base-url", "", "Base URL that the kernel, initrd and iPXE script are served from (or "+packetBaseURL+")")
|
||||
cmd.Flags().StringVar(&nameFlag, "img-name", "", "Overrides the prefix used to identify the files. Defaults to [name] (or "+packetNameVar+")")
|
||||
cmd.Flags().StringVar(&arch, "arch", packetDefaultArch, "Image architecture (x86_64 or aarch64)")
|
||||
cmd.Flags().BoolVar(&decompress, "decompress", packetDefaultDecompress, "Decompress kernel/initrd before pushing")
|
||||
cmd.Flags().StringVar(&dst, "destination", "", "URL where to push the image to. Currently only 'file' is supported as a scheme (which is also the default if omitted)")
|
||||
|
||||
baseURL := getStringValue(packetBaseURL, *baseURLFlag, "")
|
||||
if baseURL == "" {
|
||||
log.Fatal("Need to specify a value for --base-url from where the kernel, initrd and iPXE script will be loaded from.")
|
||||
}
|
||||
|
||||
if *dstFlag == "" {
|
||||
log.Fatal("Need to specify the destination where to push to.")
|
||||
}
|
||||
|
||||
name := getStringValue(packetNameVar, *nameFlag, prefix)
|
||||
|
||||
if _, err := os.Stat(fmt.Sprintf("%s-kernel", name)); os.IsNotExist(err) {
|
||||
log.Fatalf("kernel file does not exist: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(fmt.Sprintf("%s-initrd.img", name)); os.IsNotExist(err) {
|
||||
log.Fatalf("initrd file does not exist: %v", err)
|
||||
}
|
||||
|
||||
// Read kernel command line
|
||||
var cmdline string
|
||||
if c, err := os.ReadFile(prefix + "-cmdline"); err != nil {
|
||||
log.Fatalf("Cannot open cmdline file: %v", err)
|
||||
} else {
|
||||
cmdline = string(c)
|
||||
}
|
||||
|
||||
ipxeScript := packetIPXEScript(name, baseURL, cmdline, *archFlag)
|
||||
|
||||
// Parse the destination
|
||||
dst, err := url.Parse(*dstFlag)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot parse destination: %v", err)
|
||||
}
|
||||
switch dst.Scheme {
|
||||
case "", "file":
|
||||
packetPushFile(dst, *decompressFlag, name, cmdline, ipxeScript)
|
||||
default:
|
||||
log.Fatalf("Unknown destination format: %s", dst.Scheme)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func packetPushFile(dst *url.URL, decompress bool, name, cmdline, ipxeScript string) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
@@ -9,116 +8,124 @@ import (
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const defaultScalewayVolumeSize = 10 // GB
|
||||
|
||||
func pushScaleway(args []string) {
|
||||
flags := flag.NewFlagSet("scaleway", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s push scaleway [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' is the full path to an EFI ISO image. It will be copied to a new Scaleway instance in order to create a Scaeway image out of it.\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
nameFlag := flags.String("img-name", "", "Overrides the name used to identify the image name in Scaleway's images. Defaults to the base of 'path' with the '.iso' suffix removed")
|
||||
accessKeyFlag := flags.String("access-key", "", "Access Key to connect to Scaleway API")
|
||||
secretKeyFlag := flags.String("secret-key", "", "Secret Key to connect to Scaleway API")
|
||||
sshKeyFlag := flags.String("ssh-key", os.Getenv("HOME")+"/.ssh/id_rsa", "SSH key file")
|
||||
instanceIDFlag := flags.String("instance-id", "", "Instance ID of a running Scaleway instance, with a second volume.")
|
||||
deviceNameFlag := flags.String("device-name", "/dev/vdb", "Device name on which the image will be copied")
|
||||
volumeSizeFlag := flags.Int("volume-size", 0, "Size of the volume to use (in GB). Defaults to size of the ISO file rounded up to GB")
|
||||
zoneFlag := flags.String("zone", defaultScalewayZone, "Select Scaleway zone")
|
||||
organizationIDFlag := flags.String("organization-id", "", "Select Scaleway's organization ID")
|
||||
noCleanFlag := flags.Bool("no-clean", false, "Do not remove temporary instance and volumes")
|
||||
func pushScalewayCmd() *cobra.Command {
|
||||
var (
|
||||
nameFlag string
|
||||
accessKeyFlag string
|
||||
secretKeyFlag string
|
||||
sshKeyFlag string
|
||||
instanceIDFlag string
|
||||
deviceNameFlag string
|
||||
volumeSizeFlag int
|
||||
zoneFlag string
|
||||
organizationIDFlag string
|
||||
noCleanFlag bool
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "scaleway",
|
||||
Short: "push image to Scaleway",
|
||||
Long: `Push image to Scaleway.
|
||||
First argument specifies the path to an EFI ISO image. It will be copied to a new Scaleway instance in order to create a Scaeway image out of it.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
name := getStringValue(scalewayNameVar, nameFlag, "")
|
||||
accessKey := getStringValue(accessKeyVar, accessKeyFlag, "")
|
||||
secretKey := getStringValue(secretKeyVar, secretKeyFlag, "")
|
||||
sshKeyFile := getStringValue(sshKeyVar, sshKeyFlag, "")
|
||||
instanceID := getStringValue(instanceIDVar, instanceIDFlag, "")
|
||||
deviceName := getStringValue(deviceNameVar, deviceNameFlag, "")
|
||||
volumeSize := getIntValue(volumeSizeVar, volumeSizeFlag, 0)
|
||||
zone := getStringValue(zoneVar, zoneFlag, defaultScalewayZone)
|
||||
organizationID := getStringValue(organizationIDVar, organizationIDFlag, "")
|
||||
|
||||
const suffix = ".iso"
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(path, suffix)
|
||||
name = filepath.Base(name)
|
||||
}
|
||||
|
||||
client, err := NewScalewayClient(accessKey, secretKey, zone, organizationID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to connect to Scaleway: %v", err)
|
||||
}
|
||||
|
||||
// if volume size not set, try to calculate it from file size
|
||||
if volumeSize == 0 {
|
||||
if fi, err := os.Stat(path); err == nil {
|
||||
volumeSize = int(math.Ceil(float64(fi.Size()) / 1000000000)) // / 1 GB
|
||||
} else {
|
||||
// fallback to default
|
||||
log.Warnf("Unable to calculate volume size, using default of %d GB: %v", defaultScalewayVolumeSize, err)
|
||||
volumeSize = defaultScalewayVolumeSize
|
||||
}
|
||||
}
|
||||
|
||||
// if no instanceID is provided, we create the instance
|
||||
if instanceID == "" {
|
||||
instanceID, err = client.CreateInstance(volumeSize)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating a Scaleway instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.BootInstanceAndWait(instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error booting instance: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
volumeID, err := client.GetSecondVolumeID(instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error retrieving second volume ID: %v", err)
|
||||
}
|
||||
|
||||
err = client.CopyImageToInstance(instanceID, path, sshKeyFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error copying ISO file to Scaleway's instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.WriteImageToVolume(instanceID, deviceName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error writing ISO file to additional volume: %v", err)
|
||||
}
|
||||
|
||||
err = client.TerminateInstance(instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error terminating Scaleway's instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.CreateScalewayImage(instanceID, volumeID, name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating Scaleway image: %v", err)
|
||||
}
|
||||
|
||||
if !noCleanFlag {
|
||||
err = client.DeleteInstanceAndVolumes(instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error deleting Scaleway instance and volumes: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the path to the image to push\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
cmd.Flags().StringVar(&nameFlag, "img-name", "", "Overrides the name used to identify the image name in Scaleway's images. Defaults to the base of 'path' with the '.iso' suffix removed")
|
||||
cmd.Flags().StringVar(&accessKeyFlag, "access-key", "", "Access Key to connect to Scaleway API")
|
||||
cmd.Flags().StringVar(&secretKeyFlag, "secret-key", "", "Secret Key to connect to Scaleway API")
|
||||
cmd.Flags().StringVar(&sshKeyFlag, "ssh-key", os.Getenv("HOME")+"/.ssh/id_rsa", "SSH key file")
|
||||
cmd.Flags().StringVar(&instanceIDFlag, "instance-id", "", "Instance ID of a running Scaleway instance, with a second volume.")
|
||||
cmd.Flags().StringVar(&deviceNameFlag, "device-name", "/dev/vdb", "Device name on which the image will be copied")
|
||||
cmd.Flags().IntVar(&volumeSizeFlag, "volume-size", 0, "Size of the volume to use (in GB). Defaults to size of the ISO file rounded up to GB")
|
||||
cmd.Flags().StringVar(&zoneFlag, "zone", defaultScalewayZone, "Select Scaleway zone")
|
||||
cmd.Flags().StringVar(&organizationIDFlag, "organization-id", "", "Select Scaleway's organization ID")
|
||||
cmd.Flags().BoolVar(&noCleanFlag, "no-clean", false, "Do not remove temporary instance and volumes")
|
||||
|
||||
name := getStringValue(scalewayNameVar, *nameFlag, "")
|
||||
accessKey := getStringValue(accessKeyVar, *accessKeyFlag, "")
|
||||
secretKey := getStringValue(secretKeyVar, *secretKeyFlag, "")
|
||||
sshKeyFile := getStringValue(sshKeyVar, *sshKeyFlag, "")
|
||||
instanceID := getStringValue(instanceIDVar, *instanceIDFlag, "")
|
||||
deviceName := getStringValue(deviceNameVar, *deviceNameFlag, "")
|
||||
volumeSize := getIntValue(volumeSizeVar, *volumeSizeFlag, 0)
|
||||
zone := getStringValue(zoneVar, *zoneFlag, defaultScalewayZone)
|
||||
organizationID := getStringValue(organizationIDVar, *organizationIDFlag, "")
|
||||
|
||||
const suffix = ".iso"
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(path, suffix)
|
||||
name = filepath.Base(name)
|
||||
}
|
||||
|
||||
client, err := NewScalewayClient(accessKey, secretKey, zone, organizationID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to connect to Scaleway: %v", err)
|
||||
}
|
||||
|
||||
// if volume size not set, try to calculate it from file size
|
||||
if volumeSize == 0 {
|
||||
if fi, err := os.Stat(path); err == nil {
|
||||
volumeSize = int(math.Ceil(float64(fi.Size()) / 1000000000)) // / 1 GB
|
||||
} else {
|
||||
// fallback to default
|
||||
log.Warnf("Unable to calculate volume size, using default of %d GB: %v", defaultScalewayVolumeSize, err)
|
||||
volumeSize = defaultScalewayVolumeSize
|
||||
}
|
||||
}
|
||||
|
||||
// if no instanceID is provided, we create the instance
|
||||
if instanceID == "" {
|
||||
instanceID, err = client.CreateInstance(volumeSize)
|
||||
if err != nil {
|
||||
log.Fatalf("Error creating a Scaleway instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.BootInstanceAndWait(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Error booting instance: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
volumeID, err := client.GetSecondVolumeID(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Error retrieving second volume ID: %v", err)
|
||||
}
|
||||
|
||||
err = client.CopyImageToInstance(instanceID, path, sshKeyFile)
|
||||
if err != nil {
|
||||
log.Fatalf("Error copying ISO file to Scaleway's instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.WriteImageToVolume(instanceID, deviceName)
|
||||
if err != nil {
|
||||
log.Fatalf("Error writing ISO file to additional volume: %v", err)
|
||||
}
|
||||
|
||||
err = client.TerminateInstance(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Error terminating Scaleway's instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.CreateScalewayImage(instanceID, volumeID, name)
|
||||
if err != nil {
|
||||
log.Fatalf("Error creating Scaleway image: %v", err)
|
||||
}
|
||||
|
||||
if !*noCleanFlag {
|
||||
err = client.DeleteInstanceAndVolumes(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Error deleting Scaleway instance and volumes: %v", err)
|
||||
}
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -2,73 +2,77 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/vmware/govmomi"
|
||||
"github.com/vmware/govmomi/object"
|
||||
"github.com/vmware/govmomi/vim25/soap"
|
||||
)
|
||||
|
||||
// Process the push arguments and execute push
|
||||
func pushVCenter(args []string) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
func pushVCenterCmd() *cobra.Command {
|
||||
var (
|
||||
url string
|
||||
datacenter string
|
||||
datastore string
|
||||
hostname string
|
||||
folder string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "vcenter",
|
||||
Short: "push image to Azure",
|
||||
Long: `Push image to Azure.
|
||||
First argument specifies the full path of an ISO image. It will be pushed to a vCenter cluster.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
filepath := args[0]
|
||||
|
||||
var newVM vmConfig
|
||||
newVM := vmConfig{
|
||||
vCenterURL: &url,
|
||||
dcName: &datacenter,
|
||||
dsName: &datastore,
|
||||
vSphereHost: &hostname,
|
||||
path: &filepath,
|
||||
vmFolder: &folder,
|
||||
}
|
||||
|
||||
flags := flag.NewFlagSet("vCenter", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s push vcenter [options] path \n\n", invoked)
|
||||
fmt.Printf("'path' specifies the full path of an ISO image. It will be pushed to a vCenter cluster.\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
// Ensure an iso has been passed to the vCenter push Command
|
||||
if !strings.HasSuffix(*newVM.path, ".iso") {
|
||||
log.Fatalln("Please specify an '.iso' file")
|
||||
}
|
||||
|
||||
// Test any passed in files before uploading image
|
||||
checkFile(*newVM.path)
|
||||
|
||||
// Connect to VMware vCenter and return the values needed to upload image
|
||||
c, dss, _, _, _, _ := vCenterConnect(ctx, newVM)
|
||||
|
||||
// Create a folder from the uploaded image name if needed
|
||||
if *newVM.vmFolder == "" {
|
||||
*newVM.vmFolder = strings.TrimSuffix(path.Base(*newVM.path), ".iso")
|
||||
}
|
||||
|
||||
// The CreateFolder method isn't necessary as the *newVM.vmname will be created automatically
|
||||
uploadFile(c, newVM, dss)
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
newVM.vCenterURL = flags.String("url", os.Getenv("VCURL"), "URL of VMware vCenter in the format of https://username:password@VCaddress/sdk")
|
||||
newVM.dcName = flags.String("datacenter", os.Getenv("VCDATACENTER"), "The name of the DataCenter to host the image")
|
||||
newVM.dsName = flags.String("datastore", os.Getenv("VCDATASTORE"), "The name of the DataStore to host the image")
|
||||
newVM.vSphereHost = flags.String("hostname", os.Getenv("VCHOST"), "The server that will host the image")
|
||||
newVM.path = flags.String("path", "", "Path to a specific image")
|
||||
cmd.Flags().StringVar(&url, "url", os.Getenv("VCURL"), "URL of VMware vCenter in the format of https://username:password@VCaddress/sdk")
|
||||
cmd.Flags().StringVar(&datacenter, "datacenter", os.Getenv("VCDATACENTER"), "The name of the DataCenter to host the image")
|
||||
cmd.Flags().StringVar(&datastore, "datastore", os.Getenv("VCDATASTORE"), "The name of the DataStore to host the image")
|
||||
cmd.Flags().StringVar(&hostname, "hostname", os.Getenv("VCHOST"), "The server that will host the image")
|
||||
cmd.Flags().StringVar(&folder, "folder", "", "A folder on the datastore to push the image too")
|
||||
|
||||
newVM.vmFolder = flags.String("folder", "", "A folder on the datastore to push the image too")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatalln("Unable to parse args")
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the path to the image to push\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
*newVM.path = remArgs[0]
|
||||
|
||||
// Ensure an iso has been passed to the vCenter push Command
|
||||
if !strings.HasSuffix(*newVM.path, ".iso") {
|
||||
log.Fatalln("Please specify an '.iso' file")
|
||||
}
|
||||
|
||||
// Test any passed in files before uploading image
|
||||
checkFile(*newVM.path)
|
||||
|
||||
// Connect to VMware vCenter and return the values needed to upload image
|
||||
c, dss, _, _, _, _ := vCenterConnect(ctx, newVM)
|
||||
|
||||
// Create a folder from the uploaded image name if needed
|
||||
if *newVM.vmFolder == "" {
|
||||
*newVM.vmFolder = strings.TrimSuffix(path.Base(*newVM.path), ".iso")
|
||||
}
|
||||
|
||||
// The CreateFolder method isn't necessary as the *newVM.vmname will be created automatically
|
||||
uploadFile(c, newVM, dss)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func checkFile(file string) {
|
||||
|
||||
@@ -2,88 +2,72 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func runUsage() {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
fmt.Printf("USAGE: %s run [backend] [options] [prefix]\n\n", invoked)
|
||||
var (
|
||||
cpus int
|
||||
mem int
|
||||
disks Disks
|
||||
)
|
||||
|
||||
fmt.Printf("'backend' specifies the run backend.\n")
|
||||
fmt.Printf("If not specified the platform specific default will be used\n")
|
||||
fmt.Printf("Supported backends are (default platform in brackets):\n")
|
||||
// Please keep these in alphabetical order
|
||||
fmt.Printf(" aws\n")
|
||||
fmt.Printf(" azure\n")
|
||||
fmt.Printf(" gcp\n")
|
||||
fmt.Printf(" virtualization [macOS]\n")
|
||||
fmt.Printf(" hyperkit\n")
|
||||
fmt.Printf(" hyperv [Windows]\n")
|
||||
fmt.Printf(" openstack\n")
|
||||
fmt.Printf(" packet\n")
|
||||
fmt.Printf(" qemu [linux]\n")
|
||||
fmt.Printf(" scaleway\n")
|
||||
fmt.Printf(" vbox\n")
|
||||
fmt.Printf(" vcenter\n")
|
||||
fmt.Printf(" vmware\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("'options' are the backend specific options.\n")
|
||||
fmt.Printf("See '%s run [backend] --help' for details.\n\n", invoked)
|
||||
fmt.Printf("'prefix' specifies the path to the VM image.\n")
|
||||
fmt.Printf("It defaults to './image'.\n")
|
||||
}
|
||||
func runCmd() *cobra.Command {
|
||||
|
||||
func run(args []string) {
|
||||
if len(args) < 1 {
|
||||
runUsage()
|
||||
os.Exit(1)
|
||||
cmd := &cobra.Command{
|
||||
Use: "run",
|
||||
Short: "run a VM image",
|
||||
Long: `Run a VM image.
|
||||
|
||||
'backend' specifies the run backend.
|
||||
If the backend is not specified, the platform specific default will be used.
|
||||
|
||||
'prefix' specifies the path to the image.
|
||||
If the image is not specified, the default is './image'.
|
||||
`,
|
||||
Example: `run [options] [backend] [prefix]`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var target string
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
target = "virtualization"
|
||||
case "linux":
|
||||
target = "qemu"
|
||||
case "windows":
|
||||
target = "hyperv"
|
||||
default:
|
||||
return fmt.Errorf("there currently is no default 'run' backend for your platform.")
|
||||
}
|
||||
children := cmd.Commands()
|
||||
for _, child := range children {
|
||||
if child.Name() == target {
|
||||
return child.RunE(cmd, args)
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("could not find default for your platform: %s", target)
|
||||
},
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
// Please keep cases in alphabetical order
|
||||
case "aws":
|
||||
runAWS(args[1:])
|
||||
case "azure":
|
||||
runAzure(args[1:])
|
||||
case "gcp":
|
||||
runGcp(args[1:])
|
||||
case "help", "-h", "-help", "--help":
|
||||
runUsage()
|
||||
os.Exit(0)
|
||||
case "hyperkit":
|
||||
runHyperKit(args[1:])
|
||||
case "virtualization":
|
||||
runVirtualizationFramework(args[1:])
|
||||
case "hyperv":
|
||||
runHyperV(args[1:])
|
||||
case "openstack":
|
||||
runOpenStack(args[1:])
|
||||
case "packet":
|
||||
runPacket(args[1:])
|
||||
case "qemu":
|
||||
runQemu(args[1:])
|
||||
case "scaleway":
|
||||
runScaleway(args[1:])
|
||||
case "vmware":
|
||||
runVMware(args[1:])
|
||||
case "vbox":
|
||||
runVbox(args[1:])
|
||||
case "vcenter":
|
||||
runVcenter(args[1:])
|
||||
default:
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
runVirtualizationFramework(args)
|
||||
case "linux":
|
||||
runQemu(args)
|
||||
case "windows":
|
||||
runHyperV(args)
|
||||
default:
|
||||
log.Errorf("There currently is no default 'run' backend for your platform.")
|
||||
}
|
||||
}
|
||||
cmd.AddCommand(runAWSCmd())
|
||||
cmd.AddCommand(runAzureCmd())
|
||||
cmd.AddCommand(runGCPCmd())
|
||||
cmd.AddCommand(runHyperkitCmd())
|
||||
cmd.AddCommand(runVirtualizationFrameworkCmd())
|
||||
cmd.AddCommand(runHyperVCmd())
|
||||
cmd.AddCommand(runOpenStackCmd())
|
||||
cmd.AddCommand(runPacketCmd())
|
||||
cmd.AddCommand(runQEMUCmd())
|
||||
cmd.AddCommand(runScalewayCmd())
|
||||
cmd.AddCommand(runVMWareCmd())
|
||||
cmd.AddCommand(runVBoxCmd())
|
||||
cmd.AddCommand(runVCenterCmd())
|
||||
|
||||
cmd.PersistentFlags().IntVar(&cpus, "cpus", 1, "Number of CPUs")
|
||||
cmd.PersistentFlags().IntVar(&mem, "mem", 1024, "Amount of memory in MB")
|
||||
cmd.PersistentFlags().Var(&disks, "disk", "Disk config. [file=]path[,size=1G]")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -2,15 +2,14 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/ec2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -25,188 +24,191 @@ const (
|
||||
awsZoneVar = "AWS_ZONE" // non-standard
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runAWS(args []string) {
|
||||
flags := flag.NewFlagSet("aws", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run aws [options] [name]\n\n", invoked)
|
||||
fmt.Printf("'name' is the name of an AWS image that has already been\n")
|
||||
fmt.Printf(" uploaded using 'linuxkit push'\n\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
machineFlag := flags.String("machine", defaultAWSMachine, "AWS Machine Type")
|
||||
diskSizeFlag := flags.Int("disk-size", 0, "Size of system disk in GB")
|
||||
diskTypeFlag := flags.String("disk-type", defaultAWSDiskType, "AWS Disk Type")
|
||||
zoneFlag := flags.String("zone", defaultAWSZone, "AWS Availability Zone")
|
||||
sgFlag := flags.String("security-group", "", "Security Group ID")
|
||||
func runAWSCmd() *cobra.Command {
|
||||
var (
|
||||
machineFlag string
|
||||
diskSizeFlag int
|
||||
diskTypeFlag string
|
||||
zoneFlag string
|
||||
sgFlag string
|
||||
|
||||
data := flags.String("data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
dataPath := flags.String("data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
data string
|
||||
dataPath string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "aws",
|
||||
Short: "launch an AWS ec2 instance using an existing image",
|
||||
Long: `Launch an AWS ec2 instance using an existing image.
|
||||
'name' is the name of an AWS image that has already been uploaded to S3.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
name := args[0]
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
if data != "" && dataPath != "" {
|
||||
log.Fatal("Cannot specify both -data and -data-file")
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the name of the image to boot\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
name := remArgs[0]
|
||||
if dataPath != "" {
|
||||
dataB, err := os.ReadFile(dataPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to read metadata file: %v", err)
|
||||
}
|
||||
data = string(dataB)
|
||||
}
|
||||
// data must be base64 encoded
|
||||
data = base64.StdEncoding.EncodeToString([]byte(data))
|
||||
|
||||
if *data != "" && *dataPath != "" {
|
||||
log.Fatal("Cannot specify both -data and -data-file")
|
||||
}
|
||||
machine := getStringValue(awsMachineVar, machineFlag, defaultAWSMachine)
|
||||
diskSize := getIntValue(awsDiskSizeVar, diskSizeFlag, defaultAWSDiskSize)
|
||||
diskType := getStringValue(awsDiskTypeVar, diskTypeFlag, defaultAWSDiskType)
|
||||
zone := os.Getenv("AWS_REGION") + getStringValue(awsZoneVar, zoneFlag, defaultAWSZone)
|
||||
|
||||
if *dataPath != "" {
|
||||
dataB, err := os.ReadFile(*dataPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to read metadata file: %v", err)
|
||||
}
|
||||
*data = string(dataB)
|
||||
}
|
||||
// data must be base64 encoded
|
||||
*data = base64.StdEncoding.EncodeToString([]byte(*data))
|
||||
sess := session.Must(session.NewSession())
|
||||
compute := ec2.New(sess)
|
||||
|
||||
machine := getStringValue(awsMachineVar, *machineFlag, defaultAWSMachine)
|
||||
diskSize := getIntValue(awsDiskSizeVar, *diskSizeFlag, defaultAWSDiskSize)
|
||||
diskType := getStringValue(awsDiskTypeVar, *diskTypeFlag, defaultAWSDiskType)
|
||||
zone := os.Getenv("AWS_REGION") + getStringValue(awsZoneVar, *zoneFlag, defaultAWSZone)
|
||||
|
||||
sess := session.Must(session.NewSession())
|
||||
compute := ec2.New(sess)
|
||||
|
||||
// 1. Find AMI
|
||||
filter := &ec2.DescribeImagesInput{
|
||||
Filters: []*ec2.Filter{
|
||||
{
|
||||
Name: aws.String("name"),
|
||||
Values: []*string{aws.String(name)},
|
||||
},
|
||||
},
|
||||
}
|
||||
results, err := compute.DescribeImages(filter)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to describe images: %s", err)
|
||||
}
|
||||
if len(results.Images) < 1 {
|
||||
log.Fatalf("Unable to find image with name %s", name)
|
||||
}
|
||||
if len(results.Images) > 1 {
|
||||
log.Warnf("Found multiple images with the same name, using the first one")
|
||||
}
|
||||
imageID := results.Images[0].ImageId
|
||||
|
||||
// 2. Create Instance
|
||||
params := &ec2.RunInstancesInput{
|
||||
ImageId: imageID,
|
||||
InstanceType: aws.String(machine),
|
||||
MinCount: aws.Int64(1),
|
||||
MaxCount: aws.Int64(1),
|
||||
Placement: &ec2.Placement{
|
||||
AvailabilityZone: aws.String(zone),
|
||||
},
|
||||
SecurityGroupIds: []*string{sgFlag},
|
||||
UserData: data,
|
||||
}
|
||||
runResult, err := compute.RunInstances(params)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to run instance: %s", err)
|
||||
|
||||
}
|
||||
instanceID := runResult.Instances[0].InstanceId
|
||||
log.Infof("Created instance %s", *instanceID)
|
||||
|
||||
instanceFilter := &ec2.DescribeInstancesInput{
|
||||
Filters: []*ec2.Filter{
|
||||
{
|
||||
Name: aws.String("instance-id"),
|
||||
Values: []*string{instanceID},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err = compute.WaitUntilInstanceRunning(instanceFilter); err != nil {
|
||||
log.Fatalf("Error waiting for instance to start: %s", err)
|
||||
}
|
||||
log.Infof("Instance %s is running", *instanceID)
|
||||
|
||||
if diskSize > 0 {
|
||||
// 3. Create EBS Volume
|
||||
diskParams := &ec2.CreateVolumeInput{
|
||||
AvailabilityZone: aws.String(zone),
|
||||
Size: aws.Int64(int64(diskSize)),
|
||||
VolumeType: aws.String(diskType),
|
||||
}
|
||||
log.Debugf("CreateVolume:\n%v\n", diskParams)
|
||||
|
||||
volume, err := compute.CreateVolume(diskParams)
|
||||
if err != nil {
|
||||
log.Fatalf("Error creating volume: %s", err)
|
||||
}
|
||||
|
||||
waitVol := &ec2.DescribeVolumesInput{
|
||||
Filters: []*ec2.Filter{
|
||||
{
|
||||
Name: aws.String("volume-id"),
|
||||
Values: []*string{volume.VolumeId},
|
||||
// 1. Find AMI
|
||||
filter := &ec2.DescribeImagesInput{
|
||||
Filters: []*ec2.Filter{
|
||||
{
|
||||
Name: aws.String("name"),
|
||||
Values: []*string{aws.String(name)},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
results, err := compute.DescribeImages(filter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to describe images: %s", err)
|
||||
}
|
||||
if len(results.Images) < 1 {
|
||||
return fmt.Errorf("Unable to find image with name %s", name)
|
||||
}
|
||||
if len(results.Images) > 1 {
|
||||
log.Warnf("Found multiple images with the same name, using the first one")
|
||||
}
|
||||
imageID := results.Images[0].ImageId
|
||||
|
||||
log.Infof("Waiting for volume %s to be available", *volume.VolumeId)
|
||||
// 2. Create Instance
|
||||
params := &ec2.RunInstancesInput{
|
||||
ImageId: imageID,
|
||||
InstanceType: aws.String(machine),
|
||||
MinCount: aws.Int64(1),
|
||||
MaxCount: aws.Int64(1),
|
||||
Placement: &ec2.Placement{
|
||||
AvailabilityZone: aws.String(zone),
|
||||
},
|
||||
SecurityGroupIds: []*string{&sgFlag},
|
||||
UserData: &data,
|
||||
}
|
||||
runResult, err := compute.RunInstances(params)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to run instance: %s", err)
|
||||
|
||||
if err := compute.WaitUntilVolumeAvailable(waitVol); err != nil {
|
||||
log.Fatalf("Error waiting for volume to be available: %s", err)
|
||||
}
|
||||
}
|
||||
instanceID := runResult.Instances[0].InstanceId
|
||||
log.Infof("Created instance %s", *instanceID)
|
||||
|
||||
log.Infof("Attaching volume %s to instance %s", *volume.VolumeId, *instanceID)
|
||||
volParams := &ec2.AttachVolumeInput{
|
||||
Device: aws.String("/dev/sda2"),
|
||||
InstanceId: instanceID,
|
||||
VolumeId: volume.VolumeId,
|
||||
}
|
||||
_, err = compute.AttachVolume(volParams)
|
||||
if err != nil {
|
||||
log.Fatalf("Error attaching volume to instance: %s", err)
|
||||
}
|
||||
instanceFilter := &ec2.DescribeInstancesInput{
|
||||
Filters: []*ec2.Filter{
|
||||
{
|
||||
Name: aws.String("instance-id"),
|
||||
Values: []*string{instanceID},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err = compute.WaitUntilInstanceRunning(instanceFilter); err != nil {
|
||||
return fmt.Errorf("Error waiting for instance to start: %s", err)
|
||||
}
|
||||
log.Infof("Instance %s is running", *instanceID)
|
||||
|
||||
if diskSize > 0 {
|
||||
// 3. Create EBS Volume
|
||||
diskParams := &ec2.CreateVolumeInput{
|
||||
AvailabilityZone: aws.String(zone),
|
||||
Size: aws.Int64(int64(diskSize)),
|
||||
VolumeType: aws.String(diskType),
|
||||
}
|
||||
log.Debugf("CreateVolume:\n%v\n", diskParams)
|
||||
|
||||
volume, err := compute.CreateVolume(diskParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating volume: %s", err)
|
||||
}
|
||||
|
||||
waitVol := &ec2.DescribeVolumesInput{
|
||||
Filters: []*ec2.Filter{
|
||||
{
|
||||
Name: aws.String("volume-id"),
|
||||
Values: []*string{volume.VolumeId},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
log.Infof("Waiting for volume %s to be available", *volume.VolumeId)
|
||||
|
||||
if err := compute.WaitUntilVolumeAvailable(waitVol); err != nil {
|
||||
return fmt.Errorf("Error waiting for volume to be available: %s", err)
|
||||
}
|
||||
|
||||
log.Infof("Attaching volume %s to instance %s", *volume.VolumeId, *instanceID)
|
||||
volParams := &ec2.AttachVolumeInput{
|
||||
Device: aws.String("/dev/sda2"),
|
||||
InstanceId: instanceID,
|
||||
VolumeId: volume.VolumeId,
|
||||
}
|
||||
_, err = compute.AttachVolume(volParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error attaching volume to instance: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Warnf("AWS doesn't stream serial console output.\n Please use the AWS Management Console to obtain this output \n Console output will be displayed when the instance has been stopped.")
|
||||
log.Warn("Waiting for instance to stop...")
|
||||
|
||||
if err = compute.WaitUntilInstanceStopped(instanceFilter); err != nil {
|
||||
return fmt.Errorf("Error waiting for instance to stop: %s", err)
|
||||
}
|
||||
|
||||
consoleParams := &ec2.GetConsoleOutputInput{
|
||||
InstanceId: instanceID,
|
||||
}
|
||||
output, err := compute.GetConsoleOutput(consoleParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting output from instance %s: %s", *instanceID, err)
|
||||
}
|
||||
|
||||
if output.Output == nil {
|
||||
log.Warn("No Console Output found")
|
||||
} else {
|
||||
out, err := base64.StdEncoding.DecodeString(*output.Output)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error decoding output: %s", err)
|
||||
}
|
||||
fmt.Printf(string(out) + "\n")
|
||||
}
|
||||
log.Infof("Terminating instance %s", *instanceID)
|
||||
terminateParams := &ec2.TerminateInstancesInput{
|
||||
InstanceIds: []*string{instanceID},
|
||||
}
|
||||
if _, err := compute.TerminateInstances(terminateParams); err != nil {
|
||||
return fmt.Errorf("Error terminating instance %s", *instanceID)
|
||||
}
|
||||
if err = compute.WaitUntilInstanceTerminated(instanceFilter); err != nil {
|
||||
return fmt.Errorf("Error waiting for instance to terminate: %s", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
log.Warnf("AWS doesn't stream serial console output.\n Please use the AWS Management Console to obtain this output \n Console output will be displayed when the instance has been stopped.")
|
||||
log.Warn("Waiting for instance to stop...")
|
||||
cmd.Flags().StringVar(&machineFlag, "machine", defaultAWSMachine, "AWS Machine Type")
|
||||
cmd.Flags().IntVar(&diskSizeFlag, "disk-size", 0, "Size of system disk in GB")
|
||||
cmd.Flags().StringVar(&diskTypeFlag, "disk-type", defaultAWSDiskType, "AWS Disk Type")
|
||||
cmd.Flags().StringVar(&zoneFlag, "zone", defaultAWSZone, "AWS Availability Zone")
|
||||
cmd.Flags().StringVar(&sgFlag, "security-group", "", "Security Group ID")
|
||||
cmd.Flags().StringVar(&data, "data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
cmd.Flags().StringVar(&dataPath, "data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
|
||||
if err = compute.WaitUntilInstanceStopped(instanceFilter); err != nil {
|
||||
log.Fatalf("Error waiting for instance to stop: %s", err)
|
||||
}
|
||||
|
||||
consoleParams := &ec2.GetConsoleOutputInput{
|
||||
InstanceId: instanceID,
|
||||
}
|
||||
output, err := compute.GetConsoleOutput(consoleParams)
|
||||
if err != nil {
|
||||
log.Fatalf("Error getting output from instance %s: %s", *instanceID, err)
|
||||
}
|
||||
|
||||
if output.Output == nil {
|
||||
log.Warn("No Console Output found")
|
||||
} else {
|
||||
out, err := base64.StdEncoding.DecodeString(*output.Output)
|
||||
if err != nil {
|
||||
log.Fatalf("Error decoding output: %s", err)
|
||||
}
|
||||
fmt.Printf(string(out) + "\n")
|
||||
}
|
||||
log.Infof("Terminating instance %s", *instanceID)
|
||||
terminateParams := &ec2.TerminateInstancesInput{
|
||||
InstanceIds: []*string{instanceID},
|
||||
}
|
||||
if _, err := compute.TerminateInstances(terminateParams); err != nil {
|
||||
log.Fatalf("Error terminating instance %s", *instanceID)
|
||||
}
|
||||
if err = compute.WaitUntilInstanceTerminated(instanceFilter); err != nil {
|
||||
log.Fatalf("Error waiting for instance to terminate: %s", err)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// This program requires that the following environment vars are set:
|
||||
@@ -19,61 +17,68 @@ import (
|
||||
|
||||
const defaultStorageAccountName = "linuxkit"
|
||||
|
||||
func runAzure(args []string) {
|
||||
flags := flag.NewFlagSet("azure", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run azure [options] imagePath\n\n", invoked)
|
||||
fmt.Printf("'imagePath' specifies the path (absolute or relative) of a\n")
|
||||
fmt.Printf("VHD image be used as the OS image for the VM\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
func runAzureCmd() *cobra.Command {
|
||||
var (
|
||||
resourceGroupName string
|
||||
location string
|
||||
accountName string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "azure",
|
||||
Short: "launch an Azure instance using an existing image",
|
||||
Long: `Launch an Azure instance using an existing image.
|
||||
'imagePath' specifies the path (absolute or relative) of a VHD image to be used as the OS image for the VM.
|
||||
|
||||
Relies on the following environment variables:
|
||||
|
||||
AZURE_SUBSCRIPTION_ID
|
||||
AZURE_TENANT_ID
|
||||
AZURE_CLIENT_ID
|
||||
AZURE_CLIENT_SECRET
|
||||
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run azure [options] imagePath",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
imagePath := args[0]
|
||||
subscriptionID := getEnvVarOrExit("AZURE_SUBSCRIPTION_ID")
|
||||
tenantID := getEnvVarOrExit("AZURE_TENANT_ID")
|
||||
|
||||
clientID := getEnvVarOrExit("AZURE_CLIENT_ID")
|
||||
clientSecret := getEnvVarOrExit("AZURE_CLIENT_SECRET")
|
||||
|
||||
rand.Seed(time.Now().UTC().UnixNano())
|
||||
virtualNetworkName := fmt.Sprintf("linuxkitvirtualnetwork%d", rand.Intn(1000))
|
||||
subnetName := fmt.Sprintf("linuxkitsubnet%d", rand.Intn(1000))
|
||||
publicIPAddressName := fmt.Sprintf("publicip%d", rand.Intn(1000))
|
||||
networkInterfaceName := fmt.Sprintf("networkinterface%d", rand.Intn(1000))
|
||||
virtualMachineName := fmt.Sprintf("linuxkitvm%d", rand.Intn(1000))
|
||||
|
||||
initializeAzureClients(subscriptionID, tenantID, clientID, clientSecret)
|
||||
|
||||
group := createResourceGroup(resourceGroupName, location)
|
||||
createStorageAccount(accountName, location, *group)
|
||||
uploadVMImage(*group.Name, accountName, imagePath)
|
||||
createVirtualNetwork(*group, virtualNetworkName, location)
|
||||
subnet := createSubnet(*group, virtualNetworkName, subnetName)
|
||||
publicIPAddress := createPublicIPAddress(*group, publicIPAddressName, location)
|
||||
networkInterface := createNetworkInterface(*group, networkInterfaceName, *publicIPAddress, *subnet, location)
|
||||
go createVirtualMachine(*group, accountName, virtualMachineName, *networkInterface, *publicIPAddress, location)
|
||||
|
||||
fmt.Printf("\nStarted deployment of virtual machine %s in resource group %s", virtualMachineName, *group.Name)
|
||||
|
||||
time.Sleep(time.Second * 5)
|
||||
|
||||
fmt.Printf("\nNOTE: Since you created a minimal VM without the Azure Linux Agent, the portal will notify you that the deployment failed. After around 50 seconds try connecting to the VM")
|
||||
fmt.Printf("\nssh -i path-to-key root@%s\n", *publicIPAddress.DNSSettings.Fqdn)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
resourceGroupName := flags.String("resourceGroupName", "", "Name of resource group to be used for VM")
|
||||
location := flags.String("location", "westus", "Location of the VM")
|
||||
accountName := flags.String("accountName", defaultStorageAccountName, "Name of the storage account")
|
||||
cmd.Flags().StringVar(&resourceGroupName, "resourceGroupName", "", "Name of resource group to be used for VM")
|
||||
cmd.Flags().StringVar(&location, "location", "westus", "Location of the VM")
|
||||
cmd.Flags().StringVar(&accountName, "accountName", defaultStorageAccountName, "Name of the storage account")
|
||||
|
||||
subscriptionID := getEnvVarOrExit("AZURE_SUBSCRIPTION_ID")
|
||||
tenantID := getEnvVarOrExit("AZURE_TENANT_ID")
|
||||
|
||||
clientID := getEnvVarOrExit("AZURE_CLIENT_ID")
|
||||
clientSecret := getEnvVarOrExit("AZURE_CLIENT_SECRET")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatalf("Unable to parse args: %s", err.Error())
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the image to run\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
imagePath := remArgs[0]
|
||||
|
||||
rand.Seed(time.Now().UTC().UnixNano())
|
||||
virtualNetworkName := fmt.Sprintf("linuxkitvirtualnetwork%d", rand.Intn(1000))
|
||||
subnetName := fmt.Sprintf("linuxkitsubnet%d", rand.Intn(1000))
|
||||
publicIPAddressName := fmt.Sprintf("publicip%d", rand.Intn(1000))
|
||||
networkInterfaceName := fmt.Sprintf("networkinterface%d", rand.Intn(1000))
|
||||
virtualMachineName := fmt.Sprintf("linuxkitvm%d", rand.Intn(1000))
|
||||
|
||||
initializeAzureClients(subscriptionID, tenantID, clientID, clientSecret)
|
||||
|
||||
group := createResourceGroup(*resourceGroupName, *location)
|
||||
createStorageAccount(*accountName, *location, *group)
|
||||
uploadVMImage(*group.Name, *accountName, imagePath)
|
||||
createVirtualNetwork(*group, virtualNetworkName, *location)
|
||||
subnet := createSubnet(*group, virtualNetworkName, subnetName)
|
||||
publicIPAddress := createPublicIPAddress(*group, publicIPAddressName, *location)
|
||||
networkInterface := createNetworkInterface(*group, networkInterfaceName, *publicIPAddress, *subnet, *location)
|
||||
go createVirtualMachine(*group, *accountName, virtualMachineName, *networkInterface, *publicIPAddress, *location)
|
||||
|
||||
fmt.Printf("\nStarted deployment of virtual machine %s in resource group %s", virtualMachineName, *group.Name)
|
||||
|
||||
time.Sleep(time.Second * 5)
|
||||
|
||||
fmt.Printf("\nNOTE: Since you created a minimal VM without the Azure Linux Agent, the portal will notify you that the deployment failed. After around 50 seconds try connecting to the VM")
|
||||
fmt.Printf("\nssh -i path-to-key root@%s\n", *publicIPAddress.DNSSettings.Fqdn)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -23,81 +22,87 @@ const (
|
||||
nameVar = "CLOUDSDK_IMAGE_NAME" // non-standard
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runGcp(args []string) {
|
||||
flags := flag.NewFlagSet("gcp", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run gcp [options] [image]\n\n", invoked)
|
||||
fmt.Printf("'image' specifies either the name of an already uploaded\n")
|
||||
fmt.Printf("GCP image or the full path to a image file which will be\n")
|
||||
fmt.Printf("uploaded before it is run.\n\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
name := flags.String("name", "", "Machine name")
|
||||
zoneFlag := flags.String("zone", defaultZone, "GCP Zone")
|
||||
machineFlag := flags.String("machine", defaultMachine, "GCP Machine Type")
|
||||
keysFlag := flags.String("keys", "", "Path to Service Account JSON key file")
|
||||
projectFlag := flags.String("project", "", "GCP Project Name")
|
||||
var disks Disks
|
||||
flags.Var(&disks, "disk", "Disk config, may be repeated. [file=]diskName[,size=1G]")
|
||||
func runGCPCmd() *cobra.Command {
|
||||
var (
|
||||
name string
|
||||
zoneFlag string
|
||||
machineFlag string
|
||||
keysFlag string
|
||||
projectFlag string
|
||||
skipCleanup bool
|
||||
nestedVirt bool
|
||||
vTPM bool
|
||||
data string
|
||||
dataPath string
|
||||
)
|
||||
|
||||
skipCleanup := flags.Bool("skip-cleanup", false, "Don't remove images or VMs")
|
||||
nestedVirt := flags.Bool("nested-virt", false, "Enabled nested virtualization")
|
||||
vTPM := flags.Bool("vtpm", false, "Enable vTPM device")
|
||||
cmd := &cobra.Command{
|
||||
Use: "gcp",
|
||||
Short: "launch a GCP instance",
|
||||
Long: `Launch a GCP instance.
|
||||
'image' specifies either the name of an already uploaded GCP image,
|
||||
or the full path to a image file which will be uploaded before it is run.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run gcp [options] [image]",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
image := args[0]
|
||||
|
||||
data := flags.String("data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
dataPath := flags.String("data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
if data != "" && dataPath != "" {
|
||||
return errors.New("Cannot specify both -data and -data-file")
|
||||
}
|
||||
|
||||
if *data != "" && *dataPath != "" {
|
||||
log.Fatal("Cannot specify both -data and -data-file")
|
||||
if name == "" {
|
||||
name = image
|
||||
}
|
||||
|
||||
if dataPath != "" {
|
||||
dataB, err := os.ReadFile(dataPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to read metadata file: %v", err)
|
||||
}
|
||||
data = string(dataB)
|
||||
}
|
||||
|
||||
zone := getStringValue(zoneVar, zoneFlag, defaultZone)
|
||||
machine := getStringValue(machineVar, machineFlag, defaultMachine)
|
||||
keys := getStringValue(keysVar, keysFlag, "")
|
||||
project := getStringValue(projectVar, projectFlag, "")
|
||||
|
||||
client, err := NewGCPClient(keys, project)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to connect to GCP: %v", err)
|
||||
}
|
||||
|
||||
if err = client.CreateInstance(name, image, zone, machine, disks, &data, nestedVirt, vTPM, true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = client.ConnectToInstanceSerialPort(name, zone); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !skipCleanup {
|
||||
if err = client.DeleteInstance(name, zone, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
cmd.Flags().StringVar(&name, "name", "", "Machine name")
|
||||
cmd.Flags().StringVar(&zoneFlag, "zone", defaultZone, "GCP Zone")
|
||||
cmd.Flags().StringVar(&machineFlag, "machine", defaultMachine, "GCP Machine Type")
|
||||
cmd.Flags().StringVar(&keysFlag, "keys", "", "Path to Service Account JSON key file")
|
||||
cmd.Flags().StringVar(&projectFlag, "project", "", "GCP Project Name")
|
||||
cmd.Flags().BoolVar(&skipCleanup, "skip-cleanup", false, "Don't remove images or VMs")
|
||||
cmd.Flags().BoolVar(&nestedVirt, "nested-virt", false, "Enabled nested virtualization")
|
||||
cmd.Flags().BoolVar(&vTPM, "vtpm", false, "Enable vTPM device")
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the name of the image to boot\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
image := remArgs[0]
|
||||
if *name == "" {
|
||||
*name = image
|
||||
}
|
||||
cmd.Flags().StringVar(&data, "data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
cmd.Flags().StringVar(&dataPath, "data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
|
||||
if *dataPath != "" {
|
||||
dataB, err := os.ReadFile(*dataPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to read metadata file: %v", err)
|
||||
}
|
||||
*data = string(dataB)
|
||||
}
|
||||
|
||||
zone := getStringValue(zoneVar, *zoneFlag, defaultZone)
|
||||
machine := getStringValue(machineVar, *machineFlag, defaultMachine)
|
||||
keys := getStringValue(keysVar, *keysFlag, "")
|
||||
project := getStringValue(projectVar, *projectFlag, "")
|
||||
|
||||
client, err := NewGCPClient(keys, project)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to connect to GCP: %v", err)
|
||||
}
|
||||
|
||||
if err = client.CreateInstance(*name, image, zone, machine, disks, data, *nestedVirt, *vTPM, true); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if err = client.ConnectToInstanceSerialPort(*name, zone); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if !*skipCleanup {
|
||||
if err = client.DeleteInstance(*name, zone, true); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/moby/vpnkit/go/pkg/vmnet"
|
||||
"github.com/moby/vpnkit/go/pkg/vpnkit"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -30,320 +31,327 @@ func init() {
|
||||
hyperkit.SetLogger(log.StandardLogger())
|
||||
}
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runHyperKit(args []string) {
|
||||
flags := flag.NewFlagSet("hyperkit", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run hyperkit [options] prefix\n\n", invoked)
|
||||
fmt.Printf("'prefix' specifies the path to the VM image.\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Options:\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
hyperkitPath := flags.String("hyperkit", "", "Path to hyperkit binary (if not in default location)")
|
||||
cpus := flags.Int("cpus", 1, "Number of CPUs")
|
||||
mem := flags.Int("mem", 1024, "Amount of memory in MB")
|
||||
var disks Disks
|
||||
flags.Var(&disks, "disk", "Disk config. [file=]path[,size=1G]")
|
||||
data := flags.String("data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
dataPath := flags.String("data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
func runHyperkitCmd() *cobra.Command {
|
||||
var (
|
||||
hyperkitPath string
|
||||
data string
|
||||
dataPath string
|
||||
ipStr string
|
||||
state string
|
||||
vsockports string
|
||||
networking string
|
||||
vpnkitUUID string
|
||||
vpnkitPath string
|
||||
uefiBoot bool
|
||||
isoBoot bool
|
||||
squashFSBoot bool
|
||||
kernelBoot bool
|
||||
consoleToFile bool
|
||||
fw string
|
||||
publishFlags multipleFlag
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "hyperkit",
|
||||
Short: "launch a VM using hyperkit",
|
||||
Long: `Launch a VM using hyperkit.
|
||||
'prefix' specifies the path to the VM image.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run hyperkit [options] prefix",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
|
||||
if *data != "" && *dataPath != "" {
|
||||
log.Fatal("Cannot specify both -data and -data-file")
|
||||
if data != "" && dataPath != "" {
|
||||
return errors.New("Cannot specify both -data and -data-file")
|
||||
}
|
||||
|
||||
prefix := path
|
||||
|
||||
_, err := os.Stat(path + "-kernel")
|
||||
statKernel := err == nil
|
||||
|
||||
var isoPaths []string
|
||||
|
||||
switch {
|
||||
case squashFSBoot:
|
||||
if kernelBoot || isoBoot {
|
||||
return fmt.Errorf("Please specify only one boot method")
|
||||
}
|
||||
if !statKernel {
|
||||
return fmt.Errorf("Booting a SquashFS root filesystem requires a kernel at %s", path+"-kernel")
|
||||
}
|
||||
_, err = os.Stat(path + "-squashfs.img")
|
||||
statSquashFS := err == nil
|
||||
if !statSquashFS {
|
||||
return fmt.Errorf("Cannot find SquashFS image (%s): %v", path+"-squashfs.img", err)
|
||||
}
|
||||
case isoBoot:
|
||||
if kernelBoot {
|
||||
return fmt.Errorf("Please specify only one boot method")
|
||||
}
|
||||
if !uefiBoot {
|
||||
return fmt.Errorf("Hyperkit requires --uefi to be set to boot an ISO")
|
||||
}
|
||||
// We used to auto-detect ISO boot. For backwards compat, append .iso if not present
|
||||
isoPath := path
|
||||
if !strings.HasSuffix(isoPath, ".iso") {
|
||||
isoPath += ".iso"
|
||||
}
|
||||
_, err = os.Stat(isoPath)
|
||||
statISO := err == nil
|
||||
if !statISO {
|
||||
return fmt.Errorf("Cannot find ISO image (%s): %v", isoPath, err)
|
||||
}
|
||||
prefix = strings.TrimSuffix(path, ".iso")
|
||||
isoPaths = append(isoPaths, isoPath)
|
||||
default:
|
||||
// Default to kernel+initrd
|
||||
if !statKernel {
|
||||
return fmt.Errorf("Cannot find kernel file: %s", path+"-kernel")
|
||||
}
|
||||
_, err = os.Stat(path + "-initrd.img")
|
||||
statInitrd := err == nil
|
||||
if !statInitrd {
|
||||
return fmt.Errorf("Cannot find initrd file (%s): %v", path+"-initrd.img", err)
|
||||
}
|
||||
kernelBoot = true
|
||||
}
|
||||
|
||||
if uefiBoot {
|
||||
_, err := os.Stat(fw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot open UEFI firmware file (%s): %v", fw, err)
|
||||
}
|
||||
}
|
||||
|
||||
if state == "" {
|
||||
state = prefix + "-state"
|
||||
}
|
||||
if err := os.MkdirAll(state, 0755); err != nil {
|
||||
return fmt.Errorf("Could not create state directory: %v", err)
|
||||
}
|
||||
|
||||
metadataPaths, err := CreateMetadataISO(state, data, dataPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%v", err)
|
||||
}
|
||||
isoPaths = append(isoPaths, metadataPaths...)
|
||||
|
||||
// Create UUID for VPNKit or reuse an existing one from state dir. IP addresses are
|
||||
// assigned to the UUID, so to get the same IP we have to store the initial UUID. If
|
||||
// has specified a VPNKit UUID the file is ignored.
|
||||
if vpnkitUUID == "" {
|
||||
vpnkitUUIDFile := filepath.Join(state, "vpnkit.uuid")
|
||||
if _, err := os.Stat(vpnkitUUIDFile); os.IsNotExist(err) {
|
||||
vpnkitUUID = uuid.New().String()
|
||||
if err := os.WriteFile(vpnkitUUIDFile, []byte(vpnkitUUID), 0600); err != nil {
|
||||
return fmt.Errorf("Unable to write to %s: %v", vpnkitUUIDFile, err)
|
||||
}
|
||||
} else {
|
||||
uuidBytes, err := os.ReadFile(vpnkitUUIDFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to read VPNKit UUID from %s: %v", vpnkitUUIDFile, err)
|
||||
}
|
||||
if tmp, err := uuid.ParseBytes(uuidBytes); err != nil {
|
||||
return fmt.Errorf("Unable to parse VPNKit UUID from %s: %v", vpnkitUUIDFile, err)
|
||||
} else {
|
||||
vpnkitUUID = tmp.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate new UUID, otherwise /sys/class/dmi/id/product_uuid is identical on all VMs
|
||||
vmUUID := uuid.New().String()
|
||||
|
||||
// Run
|
||||
var cmdline string
|
||||
if kernelBoot || squashFSBoot {
|
||||
cmdlineBytes, err := os.ReadFile(prefix + "-cmdline")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot open cmdline file: %v", err)
|
||||
}
|
||||
cmdline = string(cmdlineBytes)
|
||||
}
|
||||
|
||||
// Create new HyperKit instance (w/o networking for now)
|
||||
h, err := hyperkit.New(hyperkitPath, "", state)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating hyperkit: %w", err)
|
||||
}
|
||||
|
||||
if consoleToFile {
|
||||
h.Console = hyperkit.ConsoleFile
|
||||
}
|
||||
|
||||
h.UUID = vmUUID
|
||||
h.ISOImages = isoPaths
|
||||
h.VSock = true
|
||||
h.CPUs = cpus
|
||||
h.Memory = mem
|
||||
|
||||
switch {
|
||||
case kernelBoot:
|
||||
h.Kernel = prefix + "-kernel"
|
||||
h.Initrd = prefix + "-initrd.img"
|
||||
case squashFSBoot:
|
||||
h.Kernel = prefix + "-kernel"
|
||||
// Make sure the SquashFS image is the first disk, raw, and virtio
|
||||
var rootDisk hyperkit.RawDisk
|
||||
rootDisk.Path = prefix + "-squashfs.img"
|
||||
rootDisk.Trim = false // This happens to select 'virtio-blk'
|
||||
h.Disks = append(h.Disks, &rootDisk)
|
||||
cmdline = cmdline + " root=/dev/vda"
|
||||
default:
|
||||
h.Bootrom = fw
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = filepath.Join(state, "disk"+id+".raw")
|
||||
}
|
||||
if d.Path == "" {
|
||||
return fmt.Errorf("disk specified with no size or name")
|
||||
}
|
||||
hd, err := hyperkit.NewDisk(d.Path, d.Size)
|
||||
if err != nil {
|
||||
return fmt.Errorf("NewDisk failed: %v", err)
|
||||
}
|
||||
h.Disks = append(h.Disks, hd)
|
||||
}
|
||||
|
||||
if h.VSockPorts, err = stringToIntArray(vsockports, ","); err != nil {
|
||||
return fmt.Errorf("Unable to parse vsock-ports: %w", err)
|
||||
}
|
||||
|
||||
// Select network mode
|
||||
var vpnkitProcess *os.Process
|
||||
var vpnkitPortSocket string
|
||||
if networking == "" || networking == "default" {
|
||||
dflt := hyperkitNetworkingDefault
|
||||
networking = dflt
|
||||
}
|
||||
netMode := strings.SplitN(networking, ",", 3)
|
||||
switch netMode[0] {
|
||||
case hyperkitNetworkingDockerForMac:
|
||||
oldEthSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/s50")
|
||||
oldPortSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/s51")
|
||||
newEthSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/vpnkit.eth.sock")
|
||||
newPortSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/vpnkit.port.sock")
|
||||
_, err := os.Stat(oldEthSock)
|
||||
if err == nil {
|
||||
h.VPNKitSock = oldEthSock
|
||||
vpnkitPortSocket = oldPortSock
|
||||
} else {
|
||||
_, err = os.Stat(newEthSock)
|
||||
if err != nil {
|
||||
return errors.New("Cannot find Docker for Mac network sockets. Install Docker or use a different network mode.")
|
||||
}
|
||||
h.VPNKitSock = newEthSock
|
||||
vpnkitPortSocket = newPortSock
|
||||
}
|
||||
case hyperkitNetworkingVPNKit:
|
||||
if len(netMode) > 1 {
|
||||
// Socket path specified, try to use existing VPNKit instance
|
||||
h.VPNKitSock = netMode[1]
|
||||
if len(netMode) > 2 {
|
||||
vpnkitPortSocket = netMode[2]
|
||||
}
|
||||
// The guest will use this 9P mount to configure which ports to forward
|
||||
h.Sockets9P = []hyperkit.Socket9P{{Path: vpnkitPortSocket, Tag: "port"}}
|
||||
// VSOCK port 62373 is used to pass traffic from host->guest
|
||||
h.VSockPorts = append(h.VSockPorts, 62373)
|
||||
} else {
|
||||
// Start new VPNKit instance
|
||||
h.VPNKitSock = filepath.Join(state, "vpnkit_eth.sock")
|
||||
vpnkitPortSocket = filepath.Join(state, "vpnkit_port.sock")
|
||||
vsockSocket := filepath.Join(state, "connect")
|
||||
vpnkitProcess, err = launchVPNKit(vpnkitPath, h.VPNKitSock, vsockSocket, vpnkitPortSocket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to start vpnkit: %w", err)
|
||||
}
|
||||
defer shutdownVPNKit(vpnkitProcess)
|
||||
log.RegisterExitHandler(func() {
|
||||
shutdownVPNKit(vpnkitProcess)
|
||||
})
|
||||
// The guest will use this 9P mount to configure which ports to forward
|
||||
h.Sockets9P = []hyperkit.Socket9P{{Path: vpnkitPortSocket, Tag: "port"}}
|
||||
// VSOCK port 62373 is used to pass traffic from host->guest
|
||||
h.VSockPorts = append(h.VSockPorts, 62373)
|
||||
}
|
||||
case hyperkitNetworkingVMNet:
|
||||
h.VPNKitSock = ""
|
||||
h.VMNet = true
|
||||
case hyperkitNetworkingNone:
|
||||
h.VPNKitSock = ""
|
||||
default:
|
||||
return fmt.Errorf("Invalid networking mode: %s", netMode[0])
|
||||
}
|
||||
|
||||
h.VPNKitUUID = vpnkitUUID
|
||||
if ipStr != "" {
|
||||
if ip := net.ParseIP(ipStr); len(ip) > 0 && ip.To4() != nil {
|
||||
h.VPNKitPreferredIPv4 = ip.String()
|
||||
} else {
|
||||
return fmt.Errorf("Unable to parse IPv4 address: %v", ipStr)
|
||||
}
|
||||
}
|
||||
|
||||
// Publish ports if requested and VPNKit is used
|
||||
if len(publishFlags) != 0 {
|
||||
switch netMode[0] {
|
||||
case hyperkitNetworkingDockerForMac, hyperkitNetworkingVPNKit:
|
||||
if vpnkitPortSocket == "" {
|
||||
return fmt.Errorf("The VPNKit Port socket path is required to publish ports")
|
||||
}
|
||||
f, err := vpnkitPublishPorts(h, publishFlags, vpnkitPortSocket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Publish ports failed with: %v", err)
|
||||
}
|
||||
defer f()
|
||||
log.RegisterExitHandler(f)
|
||||
default:
|
||||
return fmt.Errorf("Port publishing requires %q or %q networking mode", hyperkitNetworkingDockerForMac, hyperkitNetworkingVPNKit)
|
||||
}
|
||||
}
|
||||
|
||||
err = h.Run(cmdline)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot run hyperkit: %v", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
ipStr := flags.String("ip", "", "Preferred IPv4 address for the VM.")
|
||||
state := flags.String("state", "", "Path to directory to keep VM state in")
|
||||
vsockports := flags.String("vsock-ports", "", "List of vsock ports to forward from the guest on startup (comma separated). A unix domain socket for each port will be created in the state directory")
|
||||
networking := flags.String("networking", hyperkitNetworkingDefault, "Networking mode. Valid options are 'default', 'docker-for-mac', 'vpnkit[,eth-socket-path[,port-socket-path]]', 'vmnet' and 'none'. 'docker-for-mac' connects to the network used by Docker for Mac. 'vpnkit' connects to the VPNKit socket(s) specified. If no socket path is provided a new VPNKit instance will be started and 'vpnkit_eth.sock' and 'vpnkit_port.sock' will be created in the state directory. 'port-socket-path' is only needed if you want to publish ports on localhost using an existing VPNKit instance. 'vmnet' uses the Apple vmnet framework, requires root/sudo. 'none' disables networking.`")
|
||||
cmd.Flags().StringVar(&hyperkitPath, "hyperkit", "", "Path to hyperkit binary (if not in default location)")
|
||||
cmd.Flags().StringVar(&data, "data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
cmd.Flags().StringVar(&dataPath, "data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
cmd.Flags().StringVar(&ipStr, "ip", "", "Preferred IPv4 address for the VM.")
|
||||
cmd.Flags().StringVar(&state, "state", "", "Path to directory to keep VM state in")
|
||||
cmd.Flags().StringVar(&vsockports, "vsock-ports", "", "List of vsock ports to forward from the guest on startup (comma separated). A unix domain socket for each port will be created in the state directory")
|
||||
cmd.Flags().StringVar(&networking, "networking", hyperkitNetworkingDefault, "Networking mode. Valid options are 'default', 'docker-for-mac', 'vpnkit[,eth-socket-path[,port-socket-path]]', 'vmnet' and 'none'. 'docker-for-mac' connects to the network used by Docker for Mac. 'vpnkit' connects to the VPNKit socket(s) specified. If no socket path is provided a new VPNKit instance will be started and 'vpnkit_eth.sock' and 'vpnkit_port.sock' will be created in the state directory. 'port-socket-path' is only needed if you want to publish ports on localhost using an existing VPNKit instance. 'vmnet' uses the Apple vmnet framework, requires root/sudo. 'none' disables networking.`")
|
||||
|
||||
vpnkitUUID := flags.String("vpnkit-uuid", "", "Optional UUID used to identify the VPNKit connection. Overrides 'vpnkit.uuid' in the state directory.")
|
||||
vpnkitPath := flags.String("vpnkit", "", "Path to vpnkit binary")
|
||||
publishFlags := multipleFlag{}
|
||||
flags.Var(&publishFlags, "publish", "Publish a vm's port(s) to the host (default [])")
|
||||
cmd.Flags().StringVar(&vpnkitUUID, "vpnkit-uuid", "", "Optional UUID used to identify the VPNKit connection. Overrides 'vpnkit.uuid' in the state directory.")
|
||||
cmd.Flags().StringVar(&vpnkitPath, "vpnkit", "", "Path to vpnkit binary")
|
||||
cmd.Flags().Var(&publishFlags, "publish", "Publish a vm's port(s) to the host (default [])")
|
||||
|
||||
// Boot type; we try to determine automatically
|
||||
uefiBoot := flags.Bool("uefi", false, "Use UEFI boot")
|
||||
isoBoot := flags.Bool("iso", false, "Boot image is an ISO")
|
||||
squashFSBoot := flags.Bool("squashfs", false, "Boot image is a kernel+squashfs+cmdline")
|
||||
kernelBoot := flags.Bool("kernel", false, "Boot image is kernel+initrd+cmdline 'path'-kernel/-initrd/-cmdline")
|
||||
cmd.Flags().BoolVar(&uefiBoot, "uefi", false, "Use UEFI boot")
|
||||
cmd.Flags().BoolVar(&isoBoot, "iso", false, "Boot image is an ISO")
|
||||
cmd.Flags().BoolVar(&squashFSBoot, "squashfs", false, "Boot image is a kernel+squashfs+cmdline")
|
||||
cmd.Flags().BoolVar(&kernelBoot, "kernel", false, "Boot image is kernel+initrd+cmdline 'path'-kernel/-initrd/-cmdline")
|
||||
|
||||
// Hyperkit settings
|
||||
consoleToFile := flags.Bool("console-file", false, "Output the console to a tty file")
|
||||
cmd.Flags().BoolVar(&consoleToFile, "console-file", false, "Output the console to a tty file")
|
||||
|
||||
// Paths and settings for UEFI firmware
|
||||
// Note, the default uses the firmware shipped with Docker for Mac
|
||||
fw := flags.String("fw", "/Applications/Docker.app/Contents/Resources/uefi/UEFI.fd", "Path to OVMF firmware for UEFI boot")
|
||||
cmd.Flags().StringVar(&fw, "fw", "/Applications/Docker.app/Contents/Resources/uefi/UEFI.fd", "Path to OVMF firmware for UEFI boot")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Println("Please specify the prefix to the image to boot")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
prefix := path
|
||||
|
||||
_, err := os.Stat(path + "-kernel")
|
||||
statKernel := err == nil
|
||||
|
||||
var isoPaths []string
|
||||
|
||||
switch {
|
||||
case *squashFSBoot:
|
||||
if *kernelBoot || *isoBoot {
|
||||
log.Fatalf("Please specify only one boot method")
|
||||
}
|
||||
if !statKernel {
|
||||
log.Fatalf("Booting a SquashFS root filesystem requires a kernel at %s", path+"-kernel")
|
||||
}
|
||||
_, err = os.Stat(path + "-squashfs.img")
|
||||
statSquashFS := err == nil
|
||||
if !statSquashFS {
|
||||
log.Fatalf("Cannot find SquashFS image (%s): %v", path+"-squashfs.img", err)
|
||||
}
|
||||
case *isoBoot:
|
||||
if *kernelBoot {
|
||||
log.Fatalf("Please specify only one boot method")
|
||||
}
|
||||
if !*uefiBoot {
|
||||
log.Fatalf("Hyperkit requires --uefi to be set to boot an ISO")
|
||||
}
|
||||
// We used to auto-detect ISO boot. For backwards compat, append .iso if not present
|
||||
isoPath := path
|
||||
if !strings.HasSuffix(isoPath, ".iso") {
|
||||
isoPath += ".iso"
|
||||
}
|
||||
_, err = os.Stat(isoPath)
|
||||
statISO := err == nil
|
||||
if !statISO {
|
||||
log.Fatalf("Cannot find ISO image (%s): %v", isoPath, err)
|
||||
}
|
||||
prefix = strings.TrimSuffix(path, ".iso")
|
||||
isoPaths = append(isoPaths, isoPath)
|
||||
default:
|
||||
// Default to kernel+initrd
|
||||
if !statKernel {
|
||||
log.Fatalf("Cannot find kernel file: %s", path+"-kernel")
|
||||
}
|
||||
_, err = os.Stat(path + "-initrd.img")
|
||||
statInitrd := err == nil
|
||||
if !statInitrd {
|
||||
log.Fatalf("Cannot find initrd file (%s): %v", path+"-initrd.img", err)
|
||||
}
|
||||
*kernelBoot = true
|
||||
}
|
||||
|
||||
if *uefiBoot {
|
||||
_, err := os.Stat(*fw)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot open UEFI firmware file (%s): %v", *fw, err)
|
||||
}
|
||||
}
|
||||
|
||||
if *state == "" {
|
||||
*state = prefix + "-state"
|
||||
}
|
||||
if err := os.MkdirAll(*state, 0755); err != nil {
|
||||
log.Fatalf("Could not create state directory: %v", err)
|
||||
}
|
||||
|
||||
metadataPaths, err := CreateMetadataISO(*state, *data, *dataPath)
|
||||
if err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
isoPaths = append(isoPaths, metadataPaths...)
|
||||
|
||||
// Create UUID for VPNKit or reuse an existing one from state dir. IP addresses are
|
||||
// assigned to the UUID, so to get the same IP we have to store the initial UUID. If
|
||||
// has specified a VPNKit UUID the file is ignored.
|
||||
if *vpnkitUUID == "" {
|
||||
vpnkitUUIDFile := filepath.Join(*state, "vpnkit.uuid")
|
||||
if _, err := os.Stat(vpnkitUUIDFile); os.IsNotExist(err) {
|
||||
*vpnkitUUID = uuid.New().String()
|
||||
if err := os.WriteFile(vpnkitUUIDFile, []byte(*vpnkitUUID), 0600); err != nil {
|
||||
log.Fatalf("Unable to write to %s: %v", vpnkitUUIDFile, err)
|
||||
}
|
||||
} else {
|
||||
uuidBytes, err := os.ReadFile(vpnkitUUIDFile)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to read VPNKit UUID from %s: %v", vpnkitUUIDFile, err)
|
||||
}
|
||||
if tmp, err := uuid.ParseBytes(uuidBytes); err != nil {
|
||||
log.Fatalf("Unable to parse VPNKit UUID from %s: %v", vpnkitUUIDFile, err)
|
||||
} else {
|
||||
*vpnkitUUID = tmp.String()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Generate new UUID, otherwise /sys/class/dmi/id/product_uuid is identical on all VMs
|
||||
vmUUID := uuid.New().String()
|
||||
|
||||
// Run
|
||||
var cmdline string
|
||||
if *kernelBoot || *squashFSBoot {
|
||||
cmdlineBytes, err := os.ReadFile(prefix + "-cmdline")
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot open cmdline file: %v", err)
|
||||
}
|
||||
cmdline = string(cmdlineBytes)
|
||||
}
|
||||
|
||||
// Create new HyperKit instance (w/o networking for now)
|
||||
h, err := hyperkit.New(*hyperkitPath, "", *state)
|
||||
if err != nil {
|
||||
log.Fatalln("Error creating hyperkit: ", err)
|
||||
}
|
||||
|
||||
if *consoleToFile {
|
||||
h.Console = hyperkit.ConsoleFile
|
||||
}
|
||||
|
||||
h.UUID = vmUUID
|
||||
h.ISOImages = isoPaths
|
||||
h.VSock = true
|
||||
h.CPUs = *cpus
|
||||
h.Memory = *mem
|
||||
|
||||
switch {
|
||||
case *kernelBoot:
|
||||
h.Kernel = prefix + "-kernel"
|
||||
h.Initrd = prefix + "-initrd.img"
|
||||
case *squashFSBoot:
|
||||
h.Kernel = prefix + "-kernel"
|
||||
// Make sure the SquashFS image is the first disk, raw, and virtio
|
||||
var rootDisk hyperkit.RawDisk
|
||||
rootDisk.Path = prefix + "-squashfs.img"
|
||||
rootDisk.Trim = false // This happens to select 'virtio-blk'
|
||||
h.Disks = append(h.Disks, &rootDisk)
|
||||
cmdline = cmdline + " root=/dev/vda"
|
||||
default:
|
||||
h.Bootrom = *fw
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = filepath.Join(*state, "disk"+id+".raw")
|
||||
}
|
||||
if d.Path == "" {
|
||||
log.Fatalf("disk specified with no size or name")
|
||||
}
|
||||
hd, err := hyperkit.NewDisk(d.Path, d.Size)
|
||||
if err != nil {
|
||||
log.Fatalf("NewDisk failed: %v", err)
|
||||
}
|
||||
h.Disks = append(h.Disks, hd)
|
||||
}
|
||||
|
||||
if h.VSockPorts, err = stringToIntArray(*vsockports, ","); err != nil {
|
||||
log.Fatalln("Unable to parse vsock-ports: ", err)
|
||||
}
|
||||
|
||||
// Select network mode
|
||||
var vpnkitProcess *os.Process
|
||||
var vpnkitPortSocket string
|
||||
if *networking == "" || *networking == "default" {
|
||||
dflt := hyperkitNetworkingDefault
|
||||
networking = &dflt
|
||||
}
|
||||
netMode := strings.SplitN(*networking, ",", 3)
|
||||
switch netMode[0] {
|
||||
case hyperkitNetworkingDockerForMac:
|
||||
oldEthSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/s50")
|
||||
oldPortSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/s51")
|
||||
newEthSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/vpnkit.eth.sock")
|
||||
newPortSock := filepath.Join(os.Getenv("HOME"), "Library/Containers/com.docker.docker/Data/vpnkit.port.sock")
|
||||
_, err := os.Stat(oldEthSock)
|
||||
if err == nil {
|
||||
h.VPNKitSock = oldEthSock
|
||||
vpnkitPortSocket = oldPortSock
|
||||
} else {
|
||||
_, err = os.Stat(newEthSock)
|
||||
if err != nil {
|
||||
log.Fatalln("Cannot find Docker for Mac network sockets. Install Docker or use a different network mode.")
|
||||
}
|
||||
h.VPNKitSock = newEthSock
|
||||
vpnkitPortSocket = newPortSock
|
||||
}
|
||||
case hyperkitNetworkingVPNKit:
|
||||
if len(netMode) > 1 {
|
||||
// Socket path specified, try to use existing VPNKit instance
|
||||
h.VPNKitSock = netMode[1]
|
||||
if len(netMode) > 2 {
|
||||
vpnkitPortSocket = netMode[2]
|
||||
}
|
||||
// The guest will use this 9P mount to configure which ports to forward
|
||||
h.Sockets9P = []hyperkit.Socket9P{{Path: vpnkitPortSocket, Tag: "port"}}
|
||||
// VSOCK port 62373 is used to pass traffic from host->guest
|
||||
h.VSockPorts = append(h.VSockPorts, 62373)
|
||||
} else {
|
||||
// Start new VPNKit instance
|
||||
h.VPNKitSock = filepath.Join(*state, "vpnkit_eth.sock")
|
||||
vpnkitPortSocket = filepath.Join(*state, "vpnkit_port.sock")
|
||||
vsockSocket := filepath.Join(*state, "connect")
|
||||
vpnkitProcess, err = launchVPNKit(*vpnkitPath, h.VPNKitSock, vsockSocket, vpnkitPortSocket)
|
||||
if err != nil {
|
||||
log.Fatalln("Unable to start vpnkit: ", err)
|
||||
}
|
||||
defer shutdownVPNKit(vpnkitProcess)
|
||||
log.RegisterExitHandler(func() {
|
||||
shutdownVPNKit(vpnkitProcess)
|
||||
})
|
||||
// The guest will use this 9P mount to configure which ports to forward
|
||||
h.Sockets9P = []hyperkit.Socket9P{{Path: vpnkitPortSocket, Tag: "port"}}
|
||||
// VSOCK port 62373 is used to pass traffic from host->guest
|
||||
h.VSockPorts = append(h.VSockPorts, 62373)
|
||||
}
|
||||
case hyperkitNetworkingVMNet:
|
||||
h.VPNKitSock = ""
|
||||
h.VMNet = true
|
||||
case hyperkitNetworkingNone:
|
||||
h.VPNKitSock = ""
|
||||
default:
|
||||
log.Fatalf("Invalid networking mode: %s", netMode[0])
|
||||
}
|
||||
|
||||
h.VPNKitUUID = *vpnkitUUID
|
||||
if *ipStr != "" {
|
||||
if ip := net.ParseIP(*ipStr); len(ip) > 0 && ip.To4() != nil {
|
||||
h.VPNKitPreferredIPv4 = ip.String()
|
||||
} else {
|
||||
log.Fatalf("Unable to parse IPv4 address: %v", *ipStr)
|
||||
}
|
||||
}
|
||||
|
||||
// Publish ports if requested and VPNKit is used
|
||||
if len(publishFlags) != 0 {
|
||||
switch netMode[0] {
|
||||
case hyperkitNetworkingDockerForMac, hyperkitNetworkingVPNKit:
|
||||
if vpnkitPortSocket == "" {
|
||||
log.Fatalf("The VPNKit Port socket path is required to publish ports")
|
||||
}
|
||||
f, err := vpnkitPublishPorts(h, publishFlags, vpnkitPortSocket)
|
||||
if err != nil {
|
||||
log.Fatalf("Publish ports failed with: %v", err)
|
||||
}
|
||||
defer f()
|
||||
log.RegisterExitHandler(f)
|
||||
default:
|
||||
log.Fatalf("Port publishing requires %q or %q networking mode", hyperkitNetworkingDockerForMac, hyperkitNetworkingVPNKit)
|
||||
}
|
||||
}
|
||||
|
||||
err = h.Run(cmdline)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot run hyperkit: %v", err)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func shutdownVPNKit(process *os.Process) {
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -11,169 +10,165 @@ import (
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runHyperV(args []string) {
|
||||
flags := flag.NewFlagSet("hyperv", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run hyperv [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' specifies the path to a EFI ISO file.\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Options:\n")
|
||||
flags.PrintDefaults()
|
||||
func runHyperVCmd() *cobra.Command {
|
||||
var (
|
||||
vmName string
|
||||
keep bool
|
||||
switchName string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "hyperv",
|
||||
Short: "launch a VM in Hyper-V",
|
||||
Long: `Launch a VM in Hyper-V.
|
||||
'path' specifies the path to a EFI ISO file.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run hyperv [options] path",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
isoPath := args[0]
|
||||
// Sanity checks. Errors out on failure
|
||||
hypervChecks()
|
||||
|
||||
vmSwitch, err := hypervGetSwitch(switchName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Debugf("Using switch: %s", vmSwitch)
|
||||
|
||||
if vmName == "" {
|
||||
vmName = filepath.Base(isoPath)
|
||||
vmName = strings.TrimSuffix(vmName, ".iso")
|
||||
// Also strip -efi in case it is present
|
||||
vmName = strings.TrimSuffix(vmName, "-efi")
|
||||
}
|
||||
|
||||
log.Infof("Creating VM: %s", vmName)
|
||||
_, out, err := poshCmd("New-VM", "-Name", fmt.Sprintf("'%s'", vmName),
|
||||
"-Generation", "2",
|
||||
"-NoVHD",
|
||||
"-SwitchName", fmt.Sprintf("'%s'", vmSwitch))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create new VM: %w\n%s", err, out)
|
||||
}
|
||||
log.Infof("Configure VM: %s", vmName)
|
||||
_, out, err = poshCmd("Set-VM", "-Name", fmt.Sprintf("'%s'", vmName),
|
||||
"-AutomaticStartAction", "Nothing",
|
||||
"-AutomaticStopAction", "ShutDown",
|
||||
"-CheckpointType", "Disabled",
|
||||
"-MemoryStartupBytes", fmt.Sprintf("%dMB", mem),
|
||||
"-StaticMemory",
|
||||
"-ProcessorCount", fmt.Sprintf("%d", cpus))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to configure new VM: %w\n%s", err, out)
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = vmName + "-disk" + id + ".vhdx"
|
||||
}
|
||||
if d.Path == "" {
|
||||
return fmt.Errorf("disk specified with no size or name")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(d.Path); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
log.Infof("Creating new disk %s %dMB", d.Path, d.Size)
|
||||
_, out, err = poshCmd("New-VHD",
|
||||
"-Path", fmt.Sprintf("'%s'", d.Path),
|
||||
"-SizeBytes", fmt.Sprintf("%dMB", d.Size),
|
||||
"-Dynamic")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create VHD %s: %w\n%s", d.Path, err, out)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("Problem accessing disk %s. %w", d.Path, err)
|
||||
}
|
||||
} else {
|
||||
log.Infof("Using existing disk %s", d.Path)
|
||||
}
|
||||
|
||||
_, out, err = poshCmd("Add-VMHardDiskDrive",
|
||||
"-VMName", fmt.Sprintf("'%s'", vmName),
|
||||
"-Path", fmt.Sprintf("'%s'", d.Path))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to add VHD %s: %w\n%s", d.Path, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("Setting up boot from ISO")
|
||||
_, out, err = poshCmd("Add-VMDvdDrive",
|
||||
"-VMName", fmt.Sprintf("'%s'", vmName),
|
||||
"-Path", fmt.Sprintf("'%s'", isoPath))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed add DVD: %w\n%s", err, out)
|
||||
}
|
||||
_, out, err = poshCmd(
|
||||
fmt.Sprintf("$cdrom = Get-VMDvdDrive -vmname '%s';", vmName),
|
||||
"Set-VMFirmware", "-VMName", fmt.Sprintf("'%s'", vmName),
|
||||
"-EnableSecureBoot", "Off",
|
||||
"-FirstBootDevice", "$cdrom")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed set DVD as boot device: %w\n%s", err, out)
|
||||
}
|
||||
|
||||
log.Info("Set up COM port")
|
||||
_, out, err = poshCmd("Set-VMComPort",
|
||||
"-VMName", fmt.Sprintf("'%s'", vmName),
|
||||
"-number", "1",
|
||||
"-Path", fmt.Sprintf(`\\.\pipe\%s-com1`, vmName))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed set up COM port: %w\n%s", err, out)
|
||||
}
|
||||
|
||||
log.Info("Start the VM")
|
||||
_, out, err = poshCmd("Start-VM", "-Name", fmt.Sprintf("'%s'", vmName))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed start the VM: %w\n%s", err, out)
|
||||
}
|
||||
|
||||
err = hypervStartConsole(vmName)
|
||||
if err != nil {
|
||||
log.Infof("Console returned: %v\n", err)
|
||||
}
|
||||
hypervRestoreConsole()
|
||||
|
||||
if keep {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Info("Stop the VM")
|
||||
_, out, err = poshCmd("Stop-VM",
|
||||
"-Name", fmt.Sprintf("'%s'", vmName), "-Force")
|
||||
if err != nil {
|
||||
// Don't error out, could get an error if VM is already stopped
|
||||
log.Infof("Stop-VM error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
log.Info("Remove the VM")
|
||||
_, out, err = poshCmd("Remove-VM",
|
||||
"-Name", fmt.Sprintf("'%s'", vmName), "-Force")
|
||||
if err != nil {
|
||||
log.Infof("Remove-VM error: %v\n%s", err, out)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
//nolint:staticcheck // I honestly have no idea why this is complaining, as this does get called on
|
||||
// L159, but anything to get the linter to stop complaining.
|
||||
keep := flags.Bool("keep", false, "Keep the VM after finishing")
|
||||
vmName := flags.String("name", "", "Name of the Hyper-V VM")
|
||||
cpus := flags.Int("cpus", 1, "Number of CPUs")
|
||||
mem := flags.Int("mem", 1024, "Amount of memory in MB")
|
||||
var disks Disks
|
||||
flags.Var(&disks, "disk", "Disk config. [file=]path[,size=1G]")
|
||||
cmd.Flags().BoolVar(&keep, "keep", false, "Keep the VM after finishing")
|
||||
cmd.Flags().StringVar(&vmName, "name", "", "Name of the Hyper-V VM")
|
||||
cmd.Flags().StringVar(&switchName, "switch", "", "Which Hyper-V switch to attache the VM to. If left empty, either 'Default Switch' or the first external switch found is used.")
|
||||
|
||||
switchName := flags.String("switch", "", "Which Hyper-V switch to attache the VM to. If left empty, either 'Default Switch' or the first external switch found is used.")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Println("Please specify the path to the ISO image to boot")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
isoPath := remArgs[0]
|
||||
|
||||
// Sanity checks. Errors out on failure
|
||||
hypervChecks()
|
||||
|
||||
vmSwitch, err := hypervGetSwitch(*switchName)
|
||||
if err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
log.Debugf("Using switch: %s", vmSwitch)
|
||||
|
||||
if *vmName == "" {
|
||||
*vmName = filepath.Base(isoPath)
|
||||
*vmName = strings.TrimSuffix(*vmName, ".iso")
|
||||
// Also strip -efi in case it is present
|
||||
*vmName = strings.TrimSuffix(*vmName, "-efi")
|
||||
}
|
||||
|
||||
log.Infof("Creating VM: %s", *vmName)
|
||||
_, out, err := poshCmd("New-VM", "-Name", fmt.Sprintf("'%s'", *vmName),
|
||||
"-Generation", "2",
|
||||
"-NoVHD",
|
||||
"-SwitchName", fmt.Sprintf("'%s'", vmSwitch))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to create new VM: %v\n%s", err, out)
|
||||
}
|
||||
log.Infof("Configure VM: %s", *vmName)
|
||||
_, out, err = poshCmd("Set-VM", "-Name", fmt.Sprintf("'%s'", *vmName),
|
||||
"-AutomaticStartAction", "Nothing",
|
||||
"-AutomaticStopAction", "ShutDown",
|
||||
"-CheckpointType", "Disabled",
|
||||
"-MemoryStartupBytes", fmt.Sprintf("%dMB", *mem),
|
||||
"-StaticMemory",
|
||||
"-ProcessorCount", fmt.Sprintf("%d", *cpus))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to configure new VM: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = *vmName + "-disk" + id + ".vhdx"
|
||||
}
|
||||
if d.Path == "" {
|
||||
log.Fatalf("disk specified with no size or name")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(d.Path); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
log.Infof("Creating new disk %s %dMB", d.Path, d.Size)
|
||||
_, out, err = poshCmd("New-VHD",
|
||||
"-Path", fmt.Sprintf("'%s'", d.Path),
|
||||
"-SizeBytes", fmt.Sprintf("%dMB", d.Size),
|
||||
"-Dynamic")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to create VHD %s: %v\n%s", d.Path, err, out)
|
||||
}
|
||||
} else {
|
||||
log.Fatalf("Problem accessing disk %s. %v", d.Path, err)
|
||||
}
|
||||
} else {
|
||||
log.Infof("Using existing disk %s", d.Path)
|
||||
}
|
||||
|
||||
_, out, err = poshCmd("Add-VMHardDiskDrive",
|
||||
"-VMName", fmt.Sprintf("'%s'", *vmName),
|
||||
"-Path", fmt.Sprintf("'%s'", d.Path))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to add VHD %s: %v\n%s", d.Path, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("Setting up boot from ISO")
|
||||
_, out, err = poshCmd("Add-VMDvdDrive",
|
||||
"-VMName", fmt.Sprintf("'%s'", *vmName),
|
||||
"-Path", fmt.Sprintf("'%s'", isoPath))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed add DVD: %v\n%s", err, out)
|
||||
}
|
||||
_, out, err = poshCmd(
|
||||
fmt.Sprintf("$cdrom = Get-VMDvdDrive -vmname '%s';", *vmName),
|
||||
"Set-VMFirmware", "-VMName", fmt.Sprintf("'%s'", *vmName),
|
||||
"-EnableSecureBoot", "Off",
|
||||
"-FirstBootDevice", "$cdrom")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed set DVD as boot device: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
log.Info("Set up COM port")
|
||||
_, out, err = poshCmd("Set-VMComPort",
|
||||
"-VMName", fmt.Sprintf("'%s'", *vmName),
|
||||
"-number", "1",
|
||||
"-Path", fmt.Sprintf(`\\.\pipe\%s-com1`, *vmName))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed set up COM port: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
log.Info("Start the VM")
|
||||
_, out, err = poshCmd("Start-VM", "-Name", fmt.Sprintf("'%s'", *vmName))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed start the VM: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
err = hypervStartConsole(*vmName)
|
||||
if err != nil {
|
||||
log.Infof("Console returned: %v\n", err)
|
||||
}
|
||||
hypervRestoreConsole()
|
||||
|
||||
if *keep {
|
||||
return
|
||||
}
|
||||
|
||||
log.Info("Stop the VM")
|
||||
_, out, err = poshCmd("Stop-VM",
|
||||
"-Name", fmt.Sprintf("'%s'", *vmName), "-Force")
|
||||
if err != nil {
|
||||
// Don't error out, could get an error if VM is already stopped
|
||||
log.Infof("Stop-VM error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
log.Info("Remove the VM")
|
||||
_, out, err = poshCmd("Remove-VM",
|
||||
"-Name", fmt.Sprintf("'%s'", *vmName), "-Force")
|
||||
if err != nil {
|
||||
log.Infof("Remove-VM error: %v\n%s", err, out)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
var powershell string
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs"
|
||||
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
|
||||
"github.com/gophercloud/utils/openstack/clientconfig"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -18,72 +16,73 @@ const (
|
||||
defaultOSFlavor = "m1.tiny"
|
||||
)
|
||||
|
||||
func runOpenStack(args []string) {
|
||||
flags := flag.NewFlagSet("openstack", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run openstack [options] [name]\n\n", invoked)
|
||||
fmt.Printf("'name' is the name of an OpenStack image that has already been\n")
|
||||
fmt.Printf(" uploaded using 'linuxkit push'\n\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
flavorName := flags.String("flavor", defaultOSFlavor, "Instance size (flavor)")
|
||||
instanceName := flags.String("instancename", "", "Name of instance. Defaults to the name of the image if not specified")
|
||||
networkID := flags.String("network", "", "The ID of the network to attach the instance to")
|
||||
secGroups := flags.String("sec-groups", "default", "Security Group names separated by comma")
|
||||
keyName := flags.String("keyname", "", "The name of the SSH keypair to associate with the instance")
|
||||
func runOpenStackCmd() *cobra.Command {
|
||||
var (
|
||||
flavorName string
|
||||
instanceName string
|
||||
networkID string
|
||||
secGroups string
|
||||
keyName string
|
||||
)
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
cmd := &cobra.Command{
|
||||
Use: "openstack",
|
||||
Short: "launch an openstack instance using an existing image",
|
||||
Long: `Launch an openstack instance using an existing image.
|
||||
'name' is the name of an OpenStack image that has already been uploaded using 'linuxkit push'.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run openstack [options] [name]",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
name := args[0]
|
||||
if instanceName == "" {
|
||||
instanceName = name
|
||||
}
|
||||
|
||||
client, err := clientconfig.NewServiceClient("compute", nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to create Compute client, %s", err)
|
||||
}
|
||||
|
||||
network := servers.Network{
|
||||
UUID: networkID,
|
||||
}
|
||||
|
||||
var serverOpts servers.CreateOptsBuilder
|
||||
|
||||
serverOpts = &servers.CreateOpts{
|
||||
FlavorName: flavorName,
|
||||
ImageName: name,
|
||||
Name: instanceName,
|
||||
Networks: []servers.Network{network},
|
||||
ServiceClient: client,
|
||||
SecurityGroups: strings.Split(secGroups, ","),
|
||||
}
|
||||
|
||||
if keyName != "" {
|
||||
serverOpts = &keypairs.CreateOptsExt{
|
||||
CreateOptsBuilder: serverOpts,
|
||||
KeyName: keyName,
|
||||
}
|
||||
}
|
||||
|
||||
server, err := servers.Create(client, serverOpts).Extract()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to create server: %w", err)
|
||||
}
|
||||
|
||||
_ = servers.WaitForStatus(client, server.ID, "ACTIVE", 600)
|
||||
log.Infof("Server created, UUID is %s", server.ID)
|
||||
fmt.Println(server.ID)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the name of the image to boot\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
name := remArgs[0]
|
||||
|
||||
if *instanceName == "" {
|
||||
*instanceName = name
|
||||
}
|
||||
|
||||
client, err := clientconfig.NewServiceClient("compute", nil)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Compute client, %s", err)
|
||||
}
|
||||
|
||||
network := servers.Network{
|
||||
UUID: *networkID,
|
||||
}
|
||||
|
||||
var serverOpts servers.CreateOptsBuilder
|
||||
|
||||
serverOpts = &servers.CreateOpts{
|
||||
FlavorName: *flavorName,
|
||||
ImageName: name,
|
||||
Name: *instanceName,
|
||||
Networks: []servers.Network{network},
|
||||
ServiceClient: client,
|
||||
SecurityGroups: strings.Split(*secGroups, ","),
|
||||
}
|
||||
|
||||
if *keyName != "" {
|
||||
serverOpts = &keypairs.CreateOptsExt{
|
||||
CreateOptsBuilder: serverOpts,
|
||||
KeyName: *keyName,
|
||||
}
|
||||
}
|
||||
|
||||
server, err := servers.Create(client, serverOpts).Extract()
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create server: %s", err)
|
||||
}
|
||||
|
||||
_ = servers.WaitForStatus(client, server.ID, "ACTIVE", 600)
|
||||
log.Infof("Server created, UUID is %s", server.ID)
|
||||
fmt.Println(server.ID)
|
||||
cmd.Flags().StringVar(&flavorName, "flavor", defaultOSFlavor, "Instance size (flavor)")
|
||||
cmd.Flags().StringVar(&instanceName, "instancename", "", "Name of instance. Defaults to the name of the image if not specified")
|
||||
cmd.Flags().StringVar(&networkID, "network", "", "The ID of the network to attach the instance to")
|
||||
cmd.Flags().StringVar(&secGroups, "sec-groups", "default", "Security Group names separated by comma")
|
||||
cmd.Flags().StringVar(&keyName, "keyname", "", "The name of the SSH keypair to associate with the instance")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
"github.com/packethost/packngo"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/crypto/ssh/agent"
|
||||
"golang.org/x/term"
|
||||
@@ -46,202 +47,217 @@ func init() {
|
||||
}
|
||||
}
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runPacket(args []string) {
|
||||
flags := flag.NewFlagSet("packet", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run packet [options] [name]\n\n", invoked)
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
baseURLFlag := flags.String("base-url", "", "Base URL that the kernel, initrd and iPXE script are served from (or "+packetBaseURL+")")
|
||||
zoneFlag := flags.String("zone", packetDefaultZone, "Packet Zone (or "+packetZoneVar+")")
|
||||
machineFlag := flags.String("machine", packetDefaultMachine, "Packet Machine Type (or "+packetMachineVar+")")
|
||||
apiKeyFlag := flags.String("api-key", "", "Packet API key (or "+packetAPIKeyVar+")")
|
||||
projectFlag := flags.String("project-id", "", "Packet Project ID (or "+packetProjectIDVar+")")
|
||||
deviceFlag := flags.String("device", "", "The ID of an existing device")
|
||||
hostNameFlag := flags.String("hostname", packetDefaultHostname, "Hostname of new instance (or "+packetHostnameVar+")")
|
||||
nameFlag := flags.String("img-name", "", "Overrides the prefix used to identify the files. Defaults to [name] (or "+packetNameVar+")")
|
||||
alwaysPXE := flags.Bool("always-pxe", true, "Reboot from PXE every time.")
|
||||
serveFlag := flags.String("serve", "", "Serve local files via the http port specified, e.g. ':8080'.")
|
||||
consoleFlag := flags.Bool("console", true, "Provide interactive access on the console.")
|
||||
keepFlag := flags.Bool("keep", false, "Keep the machine after exiting/poweroff.")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
func runPacketCmd() *cobra.Command {
|
||||
var (
|
||||
baseURLFlag string
|
||||
zoneFlag string
|
||||
machineFlag string
|
||||
apiKeyFlag string
|
||||
projectFlag string
|
||||
deviceFlag string
|
||||
hostNameFlag string
|
||||
nameFlag string
|
||||
alwaysPXE bool
|
||||
serveFlag string
|
||||
consoleFlag bool
|
||||
keepFlag bool
|
||||
)
|
||||
|
||||
remArgs := flags.Args()
|
||||
prefix := "packet"
|
||||
if len(remArgs) > 0 {
|
||||
prefix = remArgs[0]
|
||||
}
|
||||
|
||||
url := getStringValue(packetBaseURL, *baseURLFlag, "")
|
||||
if url == "" {
|
||||
log.Fatalf("Need to specify a value for --base-url where the images are hosted. This URL should contain <url>/%s-kernel, <url>/%s-initrd.img and <url>/%s-packet.ipxe", prefix, prefix, prefix)
|
||||
}
|
||||
facility := getStringValue(packetZoneVar, *zoneFlag, "")
|
||||
plan := getStringValue(packetMachineVar, *machineFlag, defaultMachine)
|
||||
apiKey := getStringValue(packetAPIKeyVar, *apiKeyFlag, "")
|
||||
if apiKey == "" {
|
||||
log.Fatal("Must specify a Packet.net API key with --api-key")
|
||||
}
|
||||
projectID := getStringValue(packetProjectIDVar, *projectFlag, "")
|
||||
if projectID == "" {
|
||||
log.Fatal("Must specify a Packet.net Project ID with --project-id")
|
||||
}
|
||||
hostname := getStringValue(packetHostnameVar, *hostNameFlag, "")
|
||||
name := getStringValue(packetNameVar, *nameFlag, prefix)
|
||||
osType := "custom_ipxe"
|
||||
billing := "hourly"
|
||||
|
||||
if !*keepFlag && !*consoleFlag {
|
||||
log.Fatalf("Combination of keep=%t and console=%t makes little sense", *keepFlag, *consoleFlag)
|
||||
}
|
||||
|
||||
ipxeScriptName := fmt.Sprintf("%s-packet.ipxe", name)
|
||||
|
||||
// Serve files with a local http server
|
||||
var httpServer *http.Server
|
||||
if *serveFlag != "" {
|
||||
// Read kernel command line
|
||||
var cmdline string
|
||||
if c, err := os.ReadFile(prefix + "-cmdline"); err != nil {
|
||||
log.Fatalf("Cannot open cmdline file: %v", err)
|
||||
} else {
|
||||
cmdline = string(c)
|
||||
}
|
||||
|
||||
ipxeScript := packetIPXEScript(name, url, cmdline, packetMachineToArch(*machineFlag))
|
||||
log.Debugf("Using iPXE script:\n%s\n", ipxeScript)
|
||||
|
||||
// Two handlers, one for the iPXE script and one for the kernel/initrd files
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc(fmt.Sprintf("/%s", ipxeScriptName),
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, ipxeScript)
|
||||
})
|
||||
fs := serveFiles{[]string{fmt.Sprintf("%s-kernel", name), fmt.Sprintf("%s-initrd.img", name)}}
|
||||
mux.Handle("/", http.FileServer(fs))
|
||||
httpServer = &http.Server{Addr: *serveFlag, Handler: mux}
|
||||
go func() {
|
||||
log.Debugf("Listening on http://%s\n", *serveFlag)
|
||||
if err := httpServer.ListenAndServe(); err != nil {
|
||||
log.Infof("http server exited with: %v", err)
|
||||
cmd := &cobra.Command{
|
||||
Use: "packet",
|
||||
Short: "launch an Equinix Metal (Packet) device",
|
||||
Long: `Launch an Equinix Metal (Packet) device.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run packet [options] name",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
prefix := "packet"
|
||||
if len(args) > 0 {
|
||||
prefix = args[0]
|
||||
}
|
||||
}()
|
||||
url := getStringValue(packetBaseURL, baseURLFlag, "")
|
||||
if url == "" {
|
||||
return fmt.Errorf("Need to specify a value for --base-url where the images are hosted. This URL should contain <url>/%s-kernel, <url>/%s-initrd.img and <url>/%s-packet.ipxe", prefix, prefix, prefix)
|
||||
}
|
||||
facility := getStringValue(packetZoneVar, zoneFlag, "")
|
||||
plan := getStringValue(packetMachineVar, machineFlag, defaultMachine)
|
||||
apiKey := getStringValue(packetAPIKeyVar, apiKeyFlag, "")
|
||||
if apiKey == "" {
|
||||
return errors.New("Must specify a Packet.net API key with --api-key")
|
||||
}
|
||||
projectID := getStringValue(packetProjectIDVar, projectFlag, "")
|
||||
if projectID == "" {
|
||||
return errors.New("Must specify a Packet.net Project ID with --project-id")
|
||||
}
|
||||
hostname := getStringValue(packetHostnameVar, hostNameFlag, "")
|
||||
name := getStringValue(packetNameVar, nameFlag, prefix)
|
||||
osType := "custom_ipxe"
|
||||
billing := "hourly"
|
||||
|
||||
if !keepFlag && !consoleFlag {
|
||||
return fmt.Errorf("Combination of keep=%t and console=%t makes little sense", keepFlag, consoleFlag)
|
||||
}
|
||||
|
||||
ipxeScriptName := fmt.Sprintf("%s-packet.ipxe", name)
|
||||
|
||||
// Serve files with a local http server
|
||||
var httpServer *http.Server
|
||||
if serveFlag != "" {
|
||||
// Read kernel command line
|
||||
var cmdline string
|
||||
if c, err := os.ReadFile(prefix + "-cmdline"); err != nil {
|
||||
return fmt.Errorf("Cannot open cmdline file: %v", err)
|
||||
} else {
|
||||
cmdline = string(c)
|
||||
}
|
||||
|
||||
ipxeScript := packetIPXEScript(name, url, cmdline, packetMachineToArch(machineFlag))
|
||||
log.Debugf("Using iPXE script:\n%s\n", ipxeScript)
|
||||
|
||||
// Two handlers, one for the iPXE script and one for the kernel/initrd files
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc(fmt.Sprintf("/%s", ipxeScriptName),
|
||||
func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, ipxeScript)
|
||||
})
|
||||
fs := serveFiles{[]string{fmt.Sprintf("%s-kernel", name), fmt.Sprintf("%s-initrd.img", name)}}
|
||||
mux.Handle("/", http.FileServer(fs))
|
||||
httpServer = &http.Server{Addr: serveFlag, Handler: mux}
|
||||
go func() {
|
||||
log.Debugf("Listening on http://%s\n", serveFlag)
|
||||
if err := httpServer.ListenAndServe(); err != nil {
|
||||
log.Infof("http server exited with: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Make sure the URLs work
|
||||
ipxeURL := fmt.Sprintf("%s/%s", url, ipxeScriptName)
|
||||
initrdURL := fmt.Sprintf("%s/%s-initrd.img", url, name)
|
||||
kernelURL := fmt.Sprintf("%s/%s-kernel", url, name)
|
||||
log.Infof("Validating URL: %s", ipxeURL)
|
||||
if err := validateHTTPURL(ipxeURL); err != nil {
|
||||
return fmt.Errorf("Invalid iPXE URL %s: %v", ipxeURL, err)
|
||||
}
|
||||
log.Infof("Validating URL: %s", kernelURL)
|
||||
if err := validateHTTPURL(kernelURL); err != nil {
|
||||
return fmt.Errorf("Invalid kernel URL %s: %v", kernelURL, err)
|
||||
}
|
||||
log.Infof("Validating URL: %s", initrdURL)
|
||||
if err := validateHTTPURL(initrdURL); err != nil {
|
||||
return fmt.Errorf("Invalid initrd URL %s: %v", initrdURL, err)
|
||||
}
|
||||
|
||||
client := packngo.NewClient("", apiKey, nil)
|
||||
var tags []string
|
||||
|
||||
var dev *packngo.Device
|
||||
var err error
|
||||
if deviceFlag != "" {
|
||||
dev, _, err = client.Devices.Get(deviceFlag)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Getting info for device %s failed: %v", deviceFlag, err)
|
||||
}
|
||||
b, err := json.MarshalIndent(dev, "", " ")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Debugf("%s\n", string(b))
|
||||
|
||||
req := packngo.DeviceUpdateRequest{
|
||||
Hostname: hostname,
|
||||
Locked: dev.Locked,
|
||||
Tags: dev.Tags,
|
||||
IPXEScriptURL: ipxeURL,
|
||||
AlwaysPXE: alwaysPXE,
|
||||
}
|
||||
dev, _, err = client.Devices.Update(deviceFlag, &req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Update device %s failed: %v", deviceFlag, err)
|
||||
}
|
||||
if _, err := client.Devices.Reboot(deviceFlag); err != nil {
|
||||
return fmt.Errorf("Rebooting device %s failed: %v", deviceFlag, err)
|
||||
}
|
||||
} else {
|
||||
// Create a new device
|
||||
req := packngo.DeviceCreateRequest{
|
||||
Hostname: hostname,
|
||||
Plan: plan,
|
||||
Facility: facility,
|
||||
OS: osType,
|
||||
BillingCycle: billing,
|
||||
ProjectID: projectID,
|
||||
Tags: tags,
|
||||
IPXEScriptURL: ipxeURL,
|
||||
AlwaysPXE: alwaysPXE,
|
||||
}
|
||||
dev, _, err = client.Devices.Create(&req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Creating device failed: %w", err)
|
||||
}
|
||||
}
|
||||
b, err := json.MarshalIndent(dev, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Debugf("%s\n", string(b))
|
||||
|
||||
log.Printf("Booting %s...", dev.ID)
|
||||
|
||||
sshHost := "sos." + dev.Facility.Code + ".packet.net"
|
||||
if consoleFlag {
|
||||
// Connect to the serial console
|
||||
if err := packetSOS(dev.ID, sshHost); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
log.Printf("Access the console with: ssh %s@%s", dev.ID, sshHost)
|
||||
|
||||
// if the serve option is present, wait till 'ctrl-c' is hit.
|
||||
// Otherwise we wouldn't serve the files
|
||||
if serveFlag != "" {
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt)
|
||||
log.Printf("Hit ctrl-c to stop http server")
|
||||
<-stop
|
||||
}
|
||||
}
|
||||
|
||||
// Stop the http server before exiting
|
||||
if serveFlag != "" {
|
||||
log.Debugf("Shutting down http server...")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = httpServer.Shutdown(ctx)
|
||||
}
|
||||
|
||||
if keepFlag {
|
||||
log.Printf("The machine is kept...")
|
||||
log.Printf("Device ID: %s", dev.ID)
|
||||
log.Printf("Serial: ssh %s@%s", dev.ID, sshHost)
|
||||
} else {
|
||||
if _, err := client.Devices.Delete(dev.ID); err != nil {
|
||||
return fmt.Errorf("Unable to delete device: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// Make sure the URLs work
|
||||
ipxeURL := fmt.Sprintf("%s/%s", url, ipxeScriptName)
|
||||
initrdURL := fmt.Sprintf("%s/%s-initrd.img", url, name)
|
||||
kernelURL := fmt.Sprintf("%s/%s-kernel", url, name)
|
||||
log.Infof("Validating URL: %s", ipxeURL)
|
||||
if err := validateHTTPURL(ipxeURL); err != nil {
|
||||
log.Fatalf("Invalid iPXE URL %s: %v", ipxeURL, err)
|
||||
}
|
||||
log.Infof("Validating URL: %s", kernelURL)
|
||||
if err := validateHTTPURL(kernelURL); err != nil {
|
||||
log.Fatalf("Invalid kernel URL %s: %v", kernelURL, err)
|
||||
}
|
||||
log.Infof("Validating URL: %s", initrdURL)
|
||||
if err := validateHTTPURL(initrdURL); err != nil {
|
||||
log.Fatalf("Invalid initrd URL %s: %v", initrdURL, err)
|
||||
}
|
||||
cmd.Flags().StringVar(&baseURLFlag, "base-url", "", "Base URL that the kernel, initrd and iPXE script are served from (or "+packetBaseURL+")")
|
||||
cmd.Flags().StringVar(&zoneFlag, "zone", packetDefaultZone, "Packet Zone (or "+packetZoneVar+")")
|
||||
cmd.Flags().StringVar(&machineFlag, "machine", packetDefaultMachine, "Packet Machine Type (or "+packetMachineVar+")")
|
||||
cmd.Flags().StringVar(&apiKeyFlag, "api-key", "", "Packet API key (or "+packetAPIKeyVar+")")
|
||||
cmd.Flags().StringVar(&projectFlag, "project-id", "", "Packet Project ID (or "+packetProjectIDVar+")")
|
||||
cmd.Flags().StringVar(&deviceFlag, "device", "", "The ID of an existing device")
|
||||
cmd.Flags().StringVar(&hostNameFlag, "hostname", packetDefaultHostname, "Hostname of new instance (or "+packetHostnameVar+")")
|
||||
cmd.Flags().StringVar(&nameFlag, "img-name", "", "Overrides the prefix used to identify the files. Defaults to [name] (or "+packetNameVar+")")
|
||||
cmd.Flags().BoolVar(&alwaysPXE, "always-pxe", true, "Reboot from PXE every time.")
|
||||
cmd.Flags().StringVar(&serveFlag, "serve", "", "Serve local files via the http port specified, e.g. ':8080'.")
|
||||
cmd.Flags().BoolVar(&consoleFlag, "console", true, "Provide interactive access on the console.")
|
||||
cmd.Flags().BoolVar(&keepFlag, "keep", false, "Keep the machine after exiting/poweroff.")
|
||||
|
||||
client := packngo.NewClient("", apiKey, nil)
|
||||
var tags []string
|
||||
|
||||
var dev *packngo.Device
|
||||
var err error
|
||||
if *deviceFlag != "" {
|
||||
dev, _, err = client.Devices.Get(*deviceFlag)
|
||||
if err != nil {
|
||||
log.Fatalf("Getting info for device %s failed: %v", *deviceFlag, err)
|
||||
}
|
||||
b, err := json.MarshalIndent(dev, "", " ")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Debugf("%s\n", string(b))
|
||||
|
||||
req := packngo.DeviceUpdateRequest{
|
||||
Hostname: hostname,
|
||||
Locked: dev.Locked,
|
||||
Tags: dev.Tags,
|
||||
IPXEScriptURL: ipxeURL,
|
||||
AlwaysPXE: *alwaysPXE,
|
||||
}
|
||||
dev, _, err = client.Devices.Update(*deviceFlag, &req)
|
||||
if err != nil {
|
||||
log.Fatalf("Update device %s failed: %v", *deviceFlag, err)
|
||||
}
|
||||
if _, err := client.Devices.Reboot(*deviceFlag); err != nil {
|
||||
log.Fatalf("Rebooting device %s failed: %v", *deviceFlag, err)
|
||||
}
|
||||
} else {
|
||||
// Create a new device
|
||||
req := packngo.DeviceCreateRequest{
|
||||
Hostname: hostname,
|
||||
Plan: plan,
|
||||
Facility: facility,
|
||||
OS: osType,
|
||||
BillingCycle: billing,
|
||||
ProjectID: projectID,
|
||||
Tags: tags,
|
||||
IPXEScriptURL: ipxeURL,
|
||||
AlwaysPXE: *alwaysPXE,
|
||||
}
|
||||
dev, _, err = client.Devices.Create(&req)
|
||||
if err != nil {
|
||||
log.Fatalf("Creating device failed: %v", err)
|
||||
}
|
||||
}
|
||||
b, err := json.MarshalIndent(dev, "", " ")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Debugf("%s\n", string(b))
|
||||
|
||||
log.Printf("Booting %s...", dev.ID)
|
||||
|
||||
sshHost := "sos." + dev.Facility.Code + ".packet.net"
|
||||
if *consoleFlag {
|
||||
// Connect to the serial console
|
||||
if err := packetSOS(dev.ID, sshHost); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("Access the console with: ssh %s@%s", dev.ID, sshHost)
|
||||
|
||||
// if the serve option is present, wait till 'ctrl-c' is hit.
|
||||
// Otherwise we wouldn't serve the files
|
||||
if *serveFlag != "" {
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt)
|
||||
log.Printf("Hit ctrl-c to stop http server")
|
||||
<-stop
|
||||
}
|
||||
}
|
||||
|
||||
// Stop the http server before exiting
|
||||
if *serveFlag != "" {
|
||||
log.Debugf("Shutting down http server...")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = httpServer.Shutdown(ctx)
|
||||
}
|
||||
|
||||
if *keepFlag {
|
||||
log.Printf("The machine is kept...")
|
||||
log.Printf("Device ID: %s", dev.ID)
|
||||
log.Printf("Serial: ssh %s@%s", dev.ID, sshHost)
|
||||
} else {
|
||||
if _, err := client.Devices.Delete(dev.ID); err != nil {
|
||||
log.Fatalf("Unable to delete device: %v", err)
|
||||
}
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Convert machine type to architecture
|
||||
|
||||
@@ -2,7 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"flag"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -116,233 +117,241 @@ func generateMAC() net.HardwareAddr {
|
||||
return mac
|
||||
}
|
||||
|
||||
func runQemu(args []string) {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags := flag.NewFlagSet("qemu", flag.ExitOnError)
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run qemu [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' specifies the path to the VM image.\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Options:\n")
|
||||
flags.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("If not running as root note that '-networking bridge,br0' requires a\n")
|
||||
fmt.Printf("setuid network helper and appropriate host configuration, see\n")
|
||||
fmt.Printf("http://wiki.qemu.org/Features/HelperNetworking.\n")
|
||||
func runQEMUCmd() *cobra.Command {
|
||||
var (
|
||||
enableGUI bool
|
||||
uefiBoot bool
|
||||
isoBoot bool
|
||||
squashFSBoot bool
|
||||
kernelBoot bool
|
||||
state string
|
||||
data string
|
||||
dataPath string
|
||||
fw string
|
||||
accel string
|
||||
arch string
|
||||
qemuCmd string
|
||||
qemuDetached bool
|
||||
networking string
|
||||
usbEnabled bool
|
||||
deviceFlags multipleFlag
|
||||
publishFlags multipleFlag
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "qemu",
|
||||
Short: "launch a VM using qemu",
|
||||
Long: `Launch a VM using qemu.
|
||||
'path' specifies the path to the VM image.
|
||||
|
||||
If not running as root note that '-networking bridge,br0' requires a
|
||||
setuid network helper and appropriate host configuration, see
|
||||
http://wiki.qemu.org/Features/HelperNetworking.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run qemu [options] path",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
|
||||
if data != "" && dataPath != "" {
|
||||
return errors.New("Cannot specify both -data and -data-file")
|
||||
}
|
||||
|
||||
// Generate UUID, so that /sys/class/dmi/id/product_uuid is populated
|
||||
vmUUID := uuid.New()
|
||||
|
||||
// These envvars override the corresponding command line
|
||||
// options. So this must remain after the `flags.Parse` above.
|
||||
accel = getStringValue("LINUXKIT_QEMU_ACCEL", accel, "")
|
||||
|
||||
prefix := path
|
||||
|
||||
_, err := os.Stat(path)
|
||||
stat := err == nil
|
||||
|
||||
// if the path does not exist, must be trying to do a kernel+initrd or kernel+squashfs boot
|
||||
if !stat {
|
||||
_, err = os.Stat(path + "-kernel")
|
||||
statKernel := err == nil
|
||||
if statKernel {
|
||||
_, err = os.Stat(path + "-squashfs.img")
|
||||
statSquashFS := err == nil
|
||||
if statSquashFS {
|
||||
squashFSBoot = true
|
||||
} else {
|
||||
kernelBoot = true
|
||||
}
|
||||
}
|
||||
// we will error out later if neither found
|
||||
} else {
|
||||
// if path ends in .iso they meant an ISO
|
||||
if strings.HasSuffix(path, ".iso") {
|
||||
isoBoot = true
|
||||
prefix = strings.TrimSuffix(path, ".iso")
|
||||
}
|
||||
}
|
||||
|
||||
if state == "" {
|
||||
state = prefix + "-state"
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(state, 0755); err != nil {
|
||||
return fmt.Errorf("Could not create state directory: %w", err)
|
||||
}
|
||||
|
||||
var isoPaths []string
|
||||
|
||||
if isoBoot {
|
||||
isoPaths = append(isoPaths, path)
|
||||
}
|
||||
|
||||
metadataPaths, err := CreateMetadataISO(state, data, dataPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
isoPaths = append(isoPaths, metadataPaths...)
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Format == "" {
|
||||
d.Format = "qcow2"
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = filepath.Join(state, "disk"+id+".img")
|
||||
}
|
||||
if d.Path == "" {
|
||||
return fmt.Errorf("disk specified with no size or name")
|
||||
}
|
||||
disks[i] = d
|
||||
}
|
||||
|
||||
// user not trying to boot off ISO or kernel+initrd, so assume booting from a disk image or kernel+squashfs
|
||||
if !kernelBoot && !isoBoot {
|
||||
var diskPath string
|
||||
if squashFSBoot {
|
||||
diskPath = path + "-squashfs.img"
|
||||
} else {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
log.Fatalf("Boot disk image %s does not exist", path)
|
||||
}
|
||||
diskPath = path
|
||||
}
|
||||
// currently no way to set format, but autodetect probably works
|
||||
d := Disks{DiskConfig{Path: diskPath}}
|
||||
disks = append(d, disks...)
|
||||
}
|
||||
|
||||
if networking == "" || networking == "default" {
|
||||
networking = qemuNetworkingDefault
|
||||
}
|
||||
netMode := strings.SplitN(networking, ",", 2)
|
||||
|
||||
var netdevConfig string
|
||||
switch netMode[0] {
|
||||
case qemuNetworkingUser:
|
||||
netdevConfig = "user,id=t0"
|
||||
case qemuNetworkingTap:
|
||||
if len(netMode) != 2 {
|
||||
return fmt.Errorf("Not enough arguments for %q networking mode", qemuNetworkingTap)
|
||||
}
|
||||
if len(publishFlags) != 0 {
|
||||
return fmt.Errorf("Port publishing requires %q networking mode", qemuNetworkingUser)
|
||||
}
|
||||
netdevConfig = fmt.Sprintf("tap,id=t0,ifname=%s,script=no,downscript=no", netMode[1])
|
||||
case qemuNetworkingBridge:
|
||||
if len(netMode) != 2 {
|
||||
return fmt.Errorf("Not enough arguments for %q networking mode", qemuNetworkingBridge)
|
||||
}
|
||||
if len(publishFlags) != 0 {
|
||||
return fmt.Errorf("Port publishing requires %q networking mode", qemuNetworkingUser)
|
||||
}
|
||||
netdevConfig = fmt.Sprintf("bridge,id=t0,br=%s", netMode[1])
|
||||
case qemuNetworkingNone:
|
||||
if len(publishFlags) != 0 {
|
||||
return fmt.Errorf("Port publishing requires %q networking mode", qemuNetworkingUser)
|
||||
}
|
||||
netdevConfig = ""
|
||||
default:
|
||||
return fmt.Errorf("Invalid networking mode: %s", netMode[0])
|
||||
}
|
||||
|
||||
config := QemuConfig{
|
||||
Path: path,
|
||||
ISOBoot: isoBoot,
|
||||
UEFI: uefiBoot,
|
||||
SquashFS: squashFSBoot,
|
||||
Kernel: kernelBoot,
|
||||
GUI: enableGUI,
|
||||
Disks: disks,
|
||||
ISOImages: isoPaths,
|
||||
StatePath: state,
|
||||
FWPath: fw,
|
||||
Arch: arch,
|
||||
CPUs: fmt.Sprintf("%d", cpus),
|
||||
Memory: fmt.Sprintf("%d", mem),
|
||||
Accel: accel,
|
||||
Detached: qemuDetached,
|
||||
QemuBinPath: qemuCmd,
|
||||
PublishedPorts: publishFlags,
|
||||
NetdevConfig: netdevConfig,
|
||||
UUID: vmUUID,
|
||||
USB: usbEnabled,
|
||||
Devices: deviceFlags,
|
||||
}
|
||||
|
||||
config, err = discoverBinaries(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = runQemuLocal(config); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// Display flags
|
||||
enableGUI := flags.Bool("gui", false, "Set qemu to use video output instead of stdio")
|
||||
cmd.Flags().BoolVar(&enableGUI, "gui", false, "Set qemu to use video output instead of stdio")
|
||||
|
||||
// Boot type; we try to determine automatically
|
||||
uefiBoot := flags.Bool("uefi", false, "Use UEFI boot")
|
||||
isoBoot := flags.Bool("iso", false, "Boot image is an ISO")
|
||||
squashFSBoot := flags.Bool("squashfs", false, "Boot image is a kernel+squashfs+cmdline")
|
||||
kernelBoot := flags.Bool("kernel", false, "Boot image is kernel+initrd+cmdline 'path'-kernel/-initrd/-cmdline")
|
||||
cmd.Flags().BoolVar(&uefiBoot, "uefi", false, "Use UEFI boot")
|
||||
cmd.Flags().BoolVar(&isoBoot, "iso", false, "Boot image is an ISO")
|
||||
cmd.Flags().BoolVar(&squashFSBoot, "squashfs", false, "Boot image is a kernel+squashfs+cmdline")
|
||||
cmd.Flags().BoolVar(&kernelBoot, "kernel", false, "Boot image is kernel+initrd+cmdline 'path'-kernel/-initrd/-cmdline")
|
||||
|
||||
// State flags
|
||||
state := flags.String("state", "", "Path to directory to keep VM state in")
|
||||
cmd.Flags().StringVar(&state, "state", "", "Path to directory to keep VM state in")
|
||||
|
||||
// Paths and settings for disks
|
||||
var disks Disks
|
||||
flags.Var(&disks, "disk", "Disk config, may be repeated. [file=]path[,size=1G][,format=qcow2]")
|
||||
data := flags.String("data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
dataPath := flags.String("data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
|
||||
if *data != "" && *dataPath != "" {
|
||||
log.Fatal("Cannot specify both -data and -data-file")
|
||||
}
|
||||
cmd.Flags().StringVar(&data, "data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
cmd.Flags().StringVar(&dataPath, "data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
|
||||
// Paths and settings for UEFI firware
|
||||
// Note, we do not use defaultFWPath here as we have a special case for containerised execution
|
||||
fw := flags.String("fw", "", "Path to OVMF firmware for UEFI boot")
|
||||
cmd.Flags().StringVar(&fw, "fw", "", "Path to OVMF firmware for UEFI boot")
|
||||
|
||||
// VM configuration
|
||||
accel := flags.String("accel", defaultAccel, "Choose acceleration mode. Use 'tcg' to disable it.")
|
||||
arch := flags.String("arch", defaultArch, "Type of architecture to use, e.g. x86_64, aarch64, s390x")
|
||||
cpus := flags.String("cpus", "1", "Number of CPUs")
|
||||
mem := flags.String("mem", "1024", "Amount of memory in MB")
|
||||
cmd.Flags().StringVar(&accel, "accel", defaultAccel, "Choose acceleration mode. Use 'tcg' to disable it.")
|
||||
cmd.Flags().StringVar(&arch, "arch", defaultArch, "Type of architecture to use, e.g. x86_64, aarch64, s390x")
|
||||
|
||||
// Backend configuration
|
||||
qemuCmd := flags.String("qemu", "", "Path to the qemu binary (otherwise look in $PATH)")
|
||||
qemuDetached := flags.Bool("detached", false, "Set qemu container to run in the background")
|
||||
|
||||
// Generate UUID, so that /sys/class/dmi/id/product_uuid is populated
|
||||
vmUUID := uuid.New()
|
||||
cmd.Flags().StringVar(&qemuCmd, "qemu", "", "Path to the qemu binary (otherwise look in $PATH)")
|
||||
cmd.Flags().BoolVar(&qemuDetached, "detached", false, "Set qemu container to run in the background")
|
||||
|
||||
// Networking
|
||||
networking := flags.String("networking", qemuNetworkingDefault, "Networking mode. Valid options are 'default', 'user', 'bridge[,name]', tap[,name] and 'none'. 'user' uses QEMUs userspace networking. 'bridge' connects to a preexisting bridge. 'tap' uses a prexisting tap device. 'none' disables networking.`")
|
||||
cmd.Flags().StringVar(&networking, "networking", qemuNetworkingDefault, "Networking mode. Valid options are 'default', 'user', 'bridge[,name]', tap[,name] and 'none'. 'user' uses QEMUs userspace networking. 'bridge' connects to a preexisting bridge. 'tap' uses a prexisting tap device. 'none' disables networking.`")
|
||||
|
||||
publishFlags := multipleFlag{}
|
||||
flags.Var(&publishFlags, "publish", "Publish a vm's port(s) to the host (default [])")
|
||||
cmd.Flags().Var(&publishFlags, "publish", "Publish a vm's port(s) to the host (default [])")
|
||||
|
||||
// USB devices
|
||||
usbEnabled := flags.Bool("usb", false, "Enable USB controller")
|
||||
deviceFlags := multipleFlag{}
|
||||
flags.Var(&deviceFlags, "device", "Add USB host device(s). Format driver[,prop=value][,...] -- add device, like -device on the qemu command line.")
|
||||
cmd.Flags().BoolVar(&usbEnabled, "usb", false, "Enable USB controller")
|
||||
cmd.Flags().Var(&deviceFlags, "device", "Add USB host device(s). Format driver[,prop=value][,...] -- add device, like -device on the qemu command line.")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
remArgs := flags.Args()
|
||||
|
||||
// These envvars override the corresponding command line
|
||||
// options. So this must remain after the `flags.Parse` above.
|
||||
*accel = getStringValue("LINUXKIT_QEMU_ACCEL", *accel, "")
|
||||
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Println("Please specify the path to the image to boot")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
prefix := path
|
||||
|
||||
_, err := os.Stat(path)
|
||||
stat := err == nil
|
||||
|
||||
// if the path does not exist, must be trying to do a kernel+initrd or kernel+squashfs boot
|
||||
if !stat {
|
||||
_, err = os.Stat(path + "-kernel")
|
||||
statKernel := err == nil
|
||||
if statKernel {
|
||||
_, err = os.Stat(path + "-squashfs.img")
|
||||
statSquashFS := err == nil
|
||||
if statSquashFS {
|
||||
*squashFSBoot = true
|
||||
} else {
|
||||
*kernelBoot = true
|
||||
}
|
||||
}
|
||||
// we will error out later if neither found
|
||||
} else {
|
||||
// if path ends in .iso they meant an ISO
|
||||
if strings.HasSuffix(path, ".iso") {
|
||||
*isoBoot = true
|
||||
prefix = strings.TrimSuffix(path, ".iso")
|
||||
}
|
||||
}
|
||||
|
||||
if *state == "" {
|
||||
*state = prefix + "-state"
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(*state, 0755); err != nil {
|
||||
log.Fatalf("Could not create state directory: %v", err)
|
||||
}
|
||||
|
||||
var isoPaths []string
|
||||
|
||||
if *isoBoot {
|
||||
isoPaths = append(isoPaths, path)
|
||||
}
|
||||
|
||||
metadataPaths, err := CreateMetadataISO(*state, *data, *dataPath)
|
||||
if err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
isoPaths = append(isoPaths, metadataPaths...)
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Format == "" {
|
||||
d.Format = "qcow2"
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = filepath.Join(*state, "disk"+id+".img")
|
||||
}
|
||||
if d.Path == "" {
|
||||
log.Fatalf("disk specified with no size or name")
|
||||
}
|
||||
disks[i] = d
|
||||
}
|
||||
|
||||
// user not trying to boot off ISO or kernel+initrd, so assume booting from a disk image or kernel+squashfs
|
||||
if !*kernelBoot && !*isoBoot {
|
||||
var diskPath string
|
||||
if *squashFSBoot {
|
||||
diskPath = path + "-squashfs.img"
|
||||
} else {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
log.Fatalf("Boot disk image %s does not exist", path)
|
||||
}
|
||||
diskPath = path
|
||||
}
|
||||
// currently no way to set format, but autodetect probably works
|
||||
d := Disks{DiskConfig{Path: diskPath}}
|
||||
disks = append(d, disks...)
|
||||
}
|
||||
|
||||
if *networking == "" || *networking == "default" {
|
||||
dflt := qemuNetworkingDefault
|
||||
networking = &dflt
|
||||
}
|
||||
netMode := strings.SplitN(*networking, ",", 2)
|
||||
|
||||
var netdevConfig string
|
||||
switch netMode[0] {
|
||||
case qemuNetworkingUser:
|
||||
netdevConfig = "user,id=t0"
|
||||
case qemuNetworkingTap:
|
||||
if len(netMode) != 2 {
|
||||
log.Fatalf("Not enough arguments for %q networking mode", qemuNetworkingTap)
|
||||
}
|
||||
if len(publishFlags) != 0 {
|
||||
log.Fatalf("Port publishing requires %q networking mode", qemuNetworkingUser)
|
||||
}
|
||||
netdevConfig = fmt.Sprintf("tap,id=t0,ifname=%s,script=no,downscript=no", netMode[1])
|
||||
case qemuNetworkingBridge:
|
||||
if len(netMode) != 2 {
|
||||
log.Fatalf("Not enough arguments for %q networking mode", qemuNetworkingBridge)
|
||||
}
|
||||
if len(publishFlags) != 0 {
|
||||
log.Fatalf("Port publishing requires %q networking mode", qemuNetworkingUser)
|
||||
}
|
||||
netdevConfig = fmt.Sprintf("bridge,id=t0,br=%s", netMode[1])
|
||||
case qemuNetworkingNone:
|
||||
if len(publishFlags) != 0 {
|
||||
log.Fatalf("Port publishing requires %q networking mode", qemuNetworkingUser)
|
||||
}
|
||||
netdevConfig = ""
|
||||
default:
|
||||
log.Fatalf("Invalid networking mode: %s", netMode[0])
|
||||
}
|
||||
|
||||
config := QemuConfig{
|
||||
Path: path,
|
||||
ISOBoot: *isoBoot,
|
||||
UEFI: *uefiBoot,
|
||||
SquashFS: *squashFSBoot,
|
||||
Kernel: *kernelBoot,
|
||||
GUI: *enableGUI,
|
||||
Disks: disks,
|
||||
ISOImages: isoPaths,
|
||||
StatePath: *state,
|
||||
FWPath: *fw,
|
||||
Arch: *arch,
|
||||
CPUs: *cpus,
|
||||
Memory: *mem,
|
||||
Accel: *accel,
|
||||
Detached: *qemuDetached,
|
||||
QemuBinPath: *qemuCmd,
|
||||
PublishedPorts: publishFlags,
|
||||
NetdevConfig: netdevConfig,
|
||||
UUID: vmUUID,
|
||||
USB: *usbEnabled,
|
||||
Devices: deviceFlags,
|
||||
}
|
||||
|
||||
config, err = discoverBinaries(config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if err = runQemuLocal(config); err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runQemuLocal(config QemuConfig) error {
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -26,76 +22,82 @@ const (
|
||||
instanceTypeVar = "SCW_RUN_TYPE" // non-standard
|
||||
)
|
||||
|
||||
func runScaleway(args []string) {
|
||||
flags := flag.NewFlagSet("scaleway", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run scaleway [options] [name]\n\n", invoked)
|
||||
fmt.Printf("'name' is the name of a Scaleway image that has already \n")
|
||||
fmt.Printf("been uploaded using 'linuxkit push'\n\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
instanceTypeFlag := flags.String("instance-type", defaultScalewayInstanceType, "Scaleway instance type")
|
||||
instanceNameFlag := flags.String("instance-name", "linuxkit", "Name of the create instance, default to the image name")
|
||||
accessKeyFlag := flags.String("access-key", "", "Access Key to connect to Scaleway API")
|
||||
secretKeyFlag := flags.String("secret-key", "", "Secret Key to connect to Scaleway API")
|
||||
zoneFlag := flags.String("zone", defaultScalewayZone, "Select Scaleway zone")
|
||||
organizationIDFlag := flags.String("organization-id", "", "Select Scaleway's organization ID")
|
||||
cleanFlag := flags.Bool("clean", false, "Remove instance")
|
||||
noAttachFlag := flags.Bool("no-attach", false, "Don't attach to serial port, you will have to connect to instance manually")
|
||||
func runScalewayCmd() *cobra.Command {
|
||||
var (
|
||||
instanceTypeFlag string
|
||||
instanceNameFlag string
|
||||
accessKeyFlag string
|
||||
secretKeyFlag string
|
||||
zoneFlag string
|
||||
organizationIDFlag string
|
||||
cleanFlag bool
|
||||
noAttachFlag bool
|
||||
)
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
cmd := &cobra.Command{
|
||||
Use: "scaleway",
|
||||
Short: "launch a scaleway instance",
|
||||
Long: `Launch an Scaleway instance using an existing image.
|
||||
'name' is the name of a Scaleway image that has already been uploaded using 'linuxkit push'.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run scaleway [options] [name]",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
name := args[0]
|
||||
|
||||
instanceType := getStringValue(instanceTypeVar, instanceTypeFlag, defaultScalewayInstanceType)
|
||||
instanceName := getStringValue("", instanceNameFlag, name)
|
||||
accessKey := getStringValue(accessKeyVar, accessKeyFlag, "")
|
||||
secretKey := getStringValue(secretKeyVar, secretKeyFlag, "")
|
||||
zone := getStringValue(scwZoneVar, zoneFlag, defaultScalewayZone)
|
||||
organizationID := getStringValue(organizationIDVar, organizationIDFlag, "")
|
||||
|
||||
client, err := NewScalewayClient(accessKey, secretKey, zone, organizationID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to connect to Scaleway: %v", err)
|
||||
}
|
||||
|
||||
instanceID, err := client.CreateLinuxkitInstance(instanceName, name, instanceType)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Scaleway instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.BootInstance(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to boot Scaleway instance: %v", err)
|
||||
}
|
||||
|
||||
if !noAttachFlag {
|
||||
err = client.ConnectSerialPort(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to connect to serial port: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if cleanFlag {
|
||||
err = client.TerminateInstance(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to stop instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.DeleteInstanceAndVolumes(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to delete instance: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the name of the image to boot\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
name := remArgs[0]
|
||||
|
||||
instanceType := getStringValue(instanceTypeVar, *instanceTypeFlag, defaultScalewayInstanceType)
|
||||
instanceName := getStringValue("", *instanceNameFlag, name)
|
||||
accessKey := getStringValue(accessKeyVar, *accessKeyFlag, "")
|
||||
secretKey := getStringValue(secretKeyVar, *secretKeyFlag, "")
|
||||
zone := getStringValue(scwZoneVar, *zoneFlag, defaultScalewayZone)
|
||||
organizationID := getStringValue(organizationIDVar, *organizationIDFlag, "")
|
||||
|
||||
client, err := NewScalewayClient(accessKey, secretKey, zone, organizationID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to connect to Scaleway: %v", err)
|
||||
}
|
||||
|
||||
instanceID, err := client.CreateLinuxkitInstance(instanceName, name, instanceType)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create Scaleway instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.BootInstance(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to boot Scaleway instance: %v", err)
|
||||
}
|
||||
|
||||
if !*noAttachFlag {
|
||||
err = client.ConnectSerialPort(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to connect to serial port: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if *cleanFlag {
|
||||
err = client.TerminateInstance(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to stop instance: %v", err)
|
||||
}
|
||||
|
||||
err = client.DeleteInstanceAndVolumes(instanceID)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to delete instance: %v", err)
|
||||
}
|
||||
}
|
||||
cmd.Flags().StringVar(&instanceTypeFlag, "instance-type", defaultScalewayInstanceType, "Scaleway instance type")
|
||||
cmd.Flags().StringVar(&instanceNameFlag, "instance-name", "linuxkit", "Name of the create instance, default to the image name")
|
||||
cmd.Flags().StringVar(&accessKeyFlag, "access-key", "", "Access Key to connect to Scaleway API")
|
||||
cmd.Flags().StringVar(&secretKeyFlag, "secret-key", "", "Secret Key to connect to Scaleway API")
|
||||
cmd.Flags().StringVar(&zoneFlag, "zone", defaultScalewayZone, "Select Scaleway zone")
|
||||
cmd.Flags().StringVar(&organizationIDFlag, "organization-id", "", "Select Scaleway's organization ID")
|
||||
cmd.Flags().BoolVar(&cleanFlag, "clean", false, "Remove instance")
|
||||
cmd.Flags().BoolVar(&noAttachFlag, "no-attach", false, "Don't attach to serial port, you will have to connect to instance manually")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// VBNetwork is the config for a Virtual Box network
|
||||
@@ -30,6 +30,10 @@ func (l *VBNetworks) String() string {
|
||||
return fmt.Sprint(*l)
|
||||
}
|
||||
|
||||
func (l *VBNetworks) Type() string {
|
||||
return "[]VBNetwork"
|
||||
}
|
||||
|
||||
// Set is used by flag to configure value from CLI
|
||||
func (l *VBNetworks) Set(value string) error {
|
||||
d := VBNetwork{}
|
||||
@@ -54,269 +58,266 @@ func (l *VBNetworks) Set(value string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func runVbox(args []string) {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags := flag.NewFlagSet("vbox", flag.ExitOnError)
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run vbox [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' specifies the path to the VM image.\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Options:\n")
|
||||
flags.PrintDefaults()
|
||||
fmt.Printf("\n")
|
||||
func runVBoxCmd() *cobra.Command {
|
||||
var (
|
||||
enableGUI bool
|
||||
vboxmanageFlag string
|
||||
keep bool
|
||||
vmName string
|
||||
state string
|
||||
isoBoot bool
|
||||
uefiBoot bool
|
||||
networks VBNetworks
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "vbox",
|
||||
Short: "launch a vbox VM using an existing image",
|
||||
Long: `Launch a vbox VM using an existing image.
|
||||
'path' specifies the path to the VM image.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run vbox [options] path",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
path := args[0]
|
||||
if runtime.GOOS == "windows" {
|
||||
return fmt.Errorf("TODO: Windows is not yet supported")
|
||||
}
|
||||
|
||||
if strings.HasSuffix(path, ".iso") {
|
||||
isoBoot = true
|
||||
}
|
||||
|
||||
vboxmanage, err := exec.LookPath(vboxmanageFlag)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot find management binary %s: %v", vboxmanageFlag, err)
|
||||
}
|
||||
|
||||
name := vmName
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
|
||||
}
|
||||
|
||||
if state == "" {
|
||||
prefix := strings.TrimSuffix(path, filepath.Ext(path))
|
||||
state = prefix + "-state"
|
||||
}
|
||||
if err := os.MkdirAll(state, 0755); err != nil {
|
||||
return fmt.Errorf("Could not create state directory: %v", err)
|
||||
}
|
||||
|
||||
// remove machine in case it already exists
|
||||
cleanup(vboxmanage, name, false)
|
||||
|
||||
_, out, err := manage(vboxmanage, "createvm", "--name", name, "--register")
|
||||
if err != nil {
|
||||
return fmt.Errorf("createvm error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--acpi", "on")
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --acpi error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--memory", fmt.Sprintf("%d", mem))
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --memory error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--cpus", fmt.Sprintf("%d", cpus))
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --cpus error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
firmware := "bios"
|
||||
if uefiBoot {
|
||||
firmware = "efi"
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--firmware", firmware)
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --firmware error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// set up serial console
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--uart1", "0x3F8", "4")
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --uart error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
var consolePath string
|
||||
if runtime.GOOS == "windows" {
|
||||
// TODO use a named pipe on Windows
|
||||
} else {
|
||||
consolePath = filepath.Join(state, "console")
|
||||
consolePath, err = filepath.Abs(consolePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Bad path: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--uartmode1", "client", consolePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --uartmode error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "storagectl", name, "--name", "IDE Controller", "--add", "ide")
|
||||
if err != nil {
|
||||
return fmt.Errorf("storagectl error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
if isoBoot {
|
||||
_, out, err = manage(vboxmanage, "storageattach", name, "--storagectl", "IDE Controller", "--port", "1", "--device", "0", "--type", "dvddrive", "--medium", path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("storageattach error: %v\n%s", err, out)
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--boot1", "dvd")
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --boot error: %v\n%s", err, out)
|
||||
}
|
||||
} else {
|
||||
_, out, err = manage(vboxmanage, "storageattach", name, "--storagectl", "IDE Controller", "--port", "1", "--device", "0", "--type", "hdd", "--medium", path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("storageattach error: %v\n%s", err, out)
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--boot1", "disk")
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --boot error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
if len(disks) > 0 {
|
||||
_, out, err = manage(vboxmanage, "storagectl", name, "--name", "SATA", "--add", "sata")
|
||||
if err != nil {
|
||||
return fmt.Errorf("storagectl error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := strconv.Itoa(i)
|
||||
if d.Size != 0 && d.Format == "" {
|
||||
d.Format = "raw"
|
||||
}
|
||||
if d.Format != "raw" && d.Path == "" {
|
||||
log.Fatal("vbox currently can only create raw disks")
|
||||
}
|
||||
if d.Path == "" && d.Size == 0 {
|
||||
log.Fatal("please specify an existing disk file or a size")
|
||||
}
|
||||
if d.Path == "" {
|
||||
d.Path = filepath.Join(state, "disk"+id+".img")
|
||||
if err := os.Truncate(d.Path, int64(d.Size)*int64(1048576)); err != nil {
|
||||
return fmt.Errorf("Cannot create disk: %v", err)
|
||||
}
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "storageattach", name, "--storagectl", "SATA", "--port", "0", "--device", id, "--type", "hdd", "--medium", d.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("storageattach error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
for i, d := range networks {
|
||||
nic := i + 1
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--nictype%d", nic), "virtio")
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --nictype error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--nic%d", nic), d.Type)
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --nic error: %v\n%s", err, out)
|
||||
}
|
||||
if d.Type == "hostonly" {
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--hostonlyadapter%d", nic), d.Adapter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --hostonlyadapter error: %v\n%s", err, out)
|
||||
}
|
||||
} else if d.Type == "bridged" {
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--bridgeadapter%d", nic), d.Adapter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --bridgeadapter error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--cableconnected%d", nic), "on")
|
||||
if err != nil {
|
||||
return fmt.Errorf("modifyvm --cableconnected error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// create socket
|
||||
_ = os.Remove(consolePath)
|
||||
ln, err := net.Listen("unix", consolePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Cannot listen on console socket %s: %v", consolePath, err)
|
||||
}
|
||||
|
||||
var vmType string
|
||||
if enableGUI {
|
||||
vmType = "gui"
|
||||
} else {
|
||||
vmType = "headless"
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "startvm", name, "--type", vmType)
|
||||
if err != nil {
|
||||
return fmt.Errorf("startvm error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt)
|
||||
go func() {
|
||||
<-c
|
||||
cleanup(vboxmanage, name, keep)
|
||||
os.Exit(1)
|
||||
}()
|
||||
|
||||
socket, err := ln.Accept()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Accept error: %v", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
if _, err := io.Copy(socket, os.Stdin); err != nil {
|
||||
cleanup(vboxmanage, name, keep)
|
||||
log.Fatalf("Copy error: %v", err)
|
||||
}
|
||||
cleanup(vboxmanage, name, keep)
|
||||
os.Exit(0)
|
||||
}()
|
||||
go func() {
|
||||
if _, err := io.Copy(os.Stdout, socket); err != nil {
|
||||
cleanup(vboxmanage, name, keep)
|
||||
log.Fatalf("Copy error: %v", err)
|
||||
}
|
||||
cleanup(vboxmanage, name, keep)
|
||||
os.Exit(0)
|
||||
}()
|
||||
// wait forever
|
||||
select {}
|
||||
},
|
||||
}
|
||||
|
||||
// Display flags
|
||||
enableGUI := flags.Bool("gui", false, "Show the VM GUI")
|
||||
cmd.Flags().BoolVar(&enableGUI, "gui", false, "Show the VM GUI")
|
||||
|
||||
// vbox options
|
||||
vboxmanageFlag := flags.String("vboxmanage", "VBoxManage", "VBoxManage binary to use")
|
||||
keep := flags.Bool("keep", false, "Keep the VM after finishing")
|
||||
vmName := flags.String("name", "", "Name of the Virtualbox VM")
|
||||
state := flags.String("state", "", "Path to directory to keep VM state in")
|
||||
cmd.Flags().StringVar(&vboxmanageFlag, "vboxmanage", "VBoxManage", "VBoxManage binary to use")
|
||||
cmd.Flags().BoolVar(&keep, "keep", false, "Keep the VM after finishing")
|
||||
cmd.Flags().StringVar(&vmName, "name", "", "Name of the Virtualbox VM")
|
||||
cmd.Flags().StringVar(&state, "state", "", "Path to directory to keep VM state in")
|
||||
|
||||
// Paths and settings for disks
|
||||
var disks Disks
|
||||
flags.Var(&disks, "disk", "Disk config, may be repeated. [file=]path[,size=1G][,format=raw]")
|
||||
|
||||
// VM configuration
|
||||
cpus := flags.String("cpus", "1", "Number of CPUs")
|
||||
mem := flags.String("mem", "1024", "Amount of memory in MB")
|
||||
|
||||
// booting config
|
||||
isoBoot := flags.Bool("iso", false, "Boot image is an ISO")
|
||||
uefiBoot := flags.Bool("uefi", false, "Use UEFI boot")
|
||||
cmd.Flags().BoolVar(&isoBoot, "iso", false, "Boot image is an ISO")
|
||||
cmd.Flags().BoolVar(&uefiBoot, "uefi", false, "Use UEFI boot")
|
||||
|
||||
// networking
|
||||
var networks VBNetworks
|
||||
flags.Var(&networks, "networking", "Network config, may be repeated. [type=](null|nat|bridged|intnet|hostonly|generic|natnetwork[<devicename>])[,[bridge|host]adapter=<interface>]")
|
||||
cmd.Flags().Var(&networks, "networking", "Network config, may be repeated. [type=](null|nat|bridged|intnet|hostonly|generic|natnetwork[<devicename>])[,[bridge|host]adapter=<interface>]")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
remArgs := flags.Args()
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
log.Fatalf("TODO: Windows is not yet supported")
|
||||
}
|
||||
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Println("Please specify the path to the image to boot")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
|
||||
if strings.HasSuffix(path, ".iso") {
|
||||
*isoBoot = true
|
||||
}
|
||||
|
||||
vboxmanage, err := exec.LookPath(*vboxmanageFlag)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot find management binary %s: %v", *vboxmanageFlag, err)
|
||||
}
|
||||
|
||||
name := *vmName
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
|
||||
}
|
||||
|
||||
if *state == "" {
|
||||
prefix := strings.TrimSuffix(path, filepath.Ext(path))
|
||||
*state = prefix + "-state"
|
||||
}
|
||||
if err := os.MkdirAll(*state, 0755); err != nil {
|
||||
log.Fatalf("Could not create state directory: %v", err)
|
||||
}
|
||||
|
||||
// remove machine in case it already exists
|
||||
cleanup(vboxmanage, name, false)
|
||||
|
||||
_, out, err := manage(vboxmanage, "createvm", "--name", name, "--register")
|
||||
if err != nil {
|
||||
log.Fatalf("createvm error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--acpi", "on")
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --acpi error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--memory", *mem)
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --memory error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--cpus", *cpus)
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --cpus error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
firmware := "bios"
|
||||
if *uefiBoot {
|
||||
firmware = "efi"
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--firmware", firmware)
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --firmware error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// set up serial console
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--uart1", "0x3F8", "4")
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --uart error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
var consolePath string
|
||||
if runtime.GOOS == "windows" {
|
||||
// TODO use a named pipe on Windows
|
||||
} else {
|
||||
consolePath = filepath.Join(*state, "console")
|
||||
consolePath, err = filepath.Abs(consolePath)
|
||||
if err != nil {
|
||||
log.Fatalf("Bad path: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--uartmode1", "client", consolePath)
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --uartmode error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "storagectl", name, "--name", "IDE Controller", "--add", "ide")
|
||||
if err != nil {
|
||||
log.Fatalf("storagectl error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
if *isoBoot {
|
||||
_, out, err = manage(vboxmanage, "storageattach", name, "--storagectl", "IDE Controller", "--port", "1", "--device", "0", "--type", "dvddrive", "--medium", path)
|
||||
if err != nil {
|
||||
log.Fatalf("storageattach error: %v\n%s", err, out)
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--boot1", "dvd")
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --boot error: %v\n%s", err, out)
|
||||
}
|
||||
} else {
|
||||
_, out, err = manage(vboxmanage, "storageattach", name, "--storagectl", "IDE Controller", "--port", "1", "--device", "0", "--type", "hdd", "--medium", path)
|
||||
if err != nil {
|
||||
log.Fatalf("storageattach error: %v\n%s", err, out)
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, "--boot1", "disk")
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --boot error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
if len(disks) > 0 {
|
||||
_, out, err = manage(vboxmanage, "storagectl", name, "--name", "SATA", "--add", "sata")
|
||||
if err != nil {
|
||||
log.Fatalf("storagectl error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := strconv.Itoa(i)
|
||||
if d.Size != 0 && d.Format == "" {
|
||||
d.Format = "raw"
|
||||
}
|
||||
if d.Format != "raw" && d.Path == "" {
|
||||
log.Fatal("vbox currently can only create raw disks")
|
||||
}
|
||||
if d.Path == "" && d.Size == 0 {
|
||||
log.Fatal("please specify an existing disk file or a size")
|
||||
}
|
||||
if d.Path == "" {
|
||||
d.Path = filepath.Join(*state, "disk"+id+".img")
|
||||
if err := os.Truncate(d.Path, int64(d.Size)*int64(1048576)); err != nil {
|
||||
log.Fatalf("Cannot create disk: %v", err)
|
||||
}
|
||||
}
|
||||
_, out, err = manage(vboxmanage, "storageattach", name, "--storagectl", "SATA", "--port", "0", "--device", id, "--type", "hdd", "--medium", d.Path)
|
||||
if err != nil {
|
||||
log.Fatalf("storageattach error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
for i, d := range networks {
|
||||
nic := i + 1
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--nictype%d", nic), "virtio")
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --nictype error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--nic%d", nic), d.Type)
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --nic error: %v\n%s", err, out)
|
||||
}
|
||||
if d.Type == "hostonly" {
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--hostonlyadapter%d", nic), d.Adapter)
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --hostonlyadapter error: %v\n%s", err, out)
|
||||
}
|
||||
} else if d.Type == "bridged" {
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--bridgeadapter%d", nic), d.Adapter)
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --bridgeadapter error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "modifyvm", name, fmt.Sprintf("--cableconnected%d", nic), "on")
|
||||
if err != nil {
|
||||
log.Fatalf("modifyvm --cableconnected error: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// create socket
|
||||
_ = os.Remove(consolePath)
|
||||
ln, err := net.Listen("unix", consolePath)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot listen on console socket %s: %v", consolePath, err)
|
||||
}
|
||||
|
||||
var vmType string
|
||||
if *enableGUI {
|
||||
vmType = "gui"
|
||||
} else {
|
||||
vmType = "headless"
|
||||
}
|
||||
|
||||
_, out, err = manage(vboxmanage, "startvm", name, "--type", vmType)
|
||||
if err != nil {
|
||||
log.Fatalf("startvm error: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt)
|
||||
go func() {
|
||||
<-c
|
||||
cleanup(vboxmanage, name, *keep)
|
||||
os.Exit(1)
|
||||
}()
|
||||
|
||||
socket, err := ln.Accept()
|
||||
if err != nil {
|
||||
log.Fatalf("Accept error: %v", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
if _, err := io.Copy(socket, os.Stdin); err != nil {
|
||||
cleanup(vboxmanage, name, *keep)
|
||||
log.Fatalf("Copy error: %v", err)
|
||||
}
|
||||
cleanup(vboxmanage, name, *keep)
|
||||
os.Exit(0)
|
||||
}()
|
||||
go func() {
|
||||
if _, err := io.Copy(os.Stdout, socket); err != nil {
|
||||
cleanup(vboxmanage, name, *keep)
|
||||
log.Fatalf("Copy error: %v", err)
|
||||
}
|
||||
cleanup(vboxmanage, name, *keep)
|
||||
os.Exit(0)
|
||||
}()
|
||||
// wait forever
|
||||
select {}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func cleanup(vboxmanage string, name string, keep bool) {
|
||||
|
||||
@@ -2,15 +2,15 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/vmware/govmomi"
|
||||
"github.com/vmware/govmomi/find"
|
||||
"github.com/vmware/govmomi/object"
|
||||
@@ -36,123 +36,140 @@ type vmConfig struct {
|
||||
guestIP *bool
|
||||
}
|
||||
|
||||
func runVcenter(args []string) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
func runVCenterCmd() *cobra.Command {
|
||||
var (
|
||||
vCenterURL string
|
||||
dcName string
|
||||
dsName string
|
||||
networkName string
|
||||
vSphereHost string
|
||||
vmFolder string
|
||||
vmPath string
|
||||
persistent string
|
||||
poweron bool
|
||||
guestIP bool
|
||||
)
|
||||
|
||||
var newVM vmConfig
|
||||
cmd := &cobra.Command{
|
||||
Use: "vcenter",
|
||||
Short: "launch a VCenter instance using an existing image",
|
||||
Long: `Launch a VCenter instance using an existing image.
|
||||
'path' specifies the full path of an image to run.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run vcenter [options] path",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
imagePath := args[0]
|
||||
if guestIP && !poweron {
|
||||
return errors.New("The waitForIP flag can not be used without the powerOn flag")
|
||||
}
|
||||
// Ensure an iso has been passed to the vCenter run Command
|
||||
if strings.HasSuffix(vmPath, ".iso") {
|
||||
// Allow alternative names for new virtual machines being created in vCenter
|
||||
if vmFolder == "" {
|
||||
vmFolder = strings.TrimSuffix(path.Base(vmPath), ".iso")
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("Please pass an \".iso\" file as the path")
|
||||
}
|
||||
|
||||
flags := flag.NewFlagSet("vCenter", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
mem64 := int64(mem)
|
||||
newVM := vmConfig{
|
||||
vCenterURL: &vCenterURL,
|
||||
dcName: &dcName,
|
||||
dsName: &dsName,
|
||||
networkName: &networkName,
|
||||
vSphereHost: &vSphereHost,
|
||||
vmFolder: &vmFolder,
|
||||
path: &vmPath,
|
||||
persistent: &persistent,
|
||||
mem: &mem64,
|
||||
vCpus: &cpus,
|
||||
poweron: &poweron,
|
||||
guestIP: &guestIP,
|
||||
}
|
||||
newVM.path = &imagePath
|
||||
|
||||
newVM.vCenterURL = flags.String("url", os.Getenv("VCURL"), "URL of VMware vCenter in the format of https://username:password@VCaddress/sdk")
|
||||
newVM.dcName = flags.String("datacenter", os.Getenv("VCDATACENTER"), "The name of the Datacenter to host the VM")
|
||||
newVM.dsName = flags.String("datastore", os.Getenv("VCDATASTORE"), "The name of the DataStore to host the VM")
|
||||
newVM.networkName = flags.String("network", os.Getenv("VCNETWORK"), "The network label the VM will use")
|
||||
newVM.vSphereHost = flags.String("hostname", os.Getenv("VCHOST"), "The server that will run the VM")
|
||||
// Connect to VMware vCenter and return the default and found values needed for a new VM
|
||||
c, dss, folders, hs, net, rp := vCenterConnect(ctx, newVM)
|
||||
|
||||
newVM.vmFolder = flags.String("vmfolder", "", "Specify a name/folder for the virtual machine to reside in")
|
||||
newVM.path = flags.String("path", "", "Path to a specific image")
|
||||
newVM.persistent = flags.String("persistentSize", "", "Size in MB of persistent storage to allocate to the VM")
|
||||
newVM.mem = flags.Int64("mem", 1024, "Size in MB of memory to allocate to the VM")
|
||||
newVM.vCpus = flags.Int("cpus", 1, "Amount of vCPUs to allocate to the VM")
|
||||
newVM.poweron = flags.Bool("powerOn", false, "Power On the new VM once it has been created")
|
||||
newVM.guestIP = flags.Bool("waitForIP", false, "LinuxKit will wait for the VM to power on and return the guest IP, requires open-vm-tools and the -powerOn flag to be set")
|
||||
log.Infof("Creating new LinuxKit Virtual Machine")
|
||||
spec := types.VirtualMachineConfigSpec{
|
||||
Name: *newVM.vmFolder,
|
||||
GuestId: "otherLinux64Guest",
|
||||
Files: &types.VirtualMachineFileInfo{VmPathName: fmt.Sprintf("[%s]", dss.Name())},
|
||||
NumCPUs: int32(*newVM.vCpus),
|
||||
MemoryMB: *newVM.mem,
|
||||
}
|
||||
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run vcenter [options] path\n\n", invoked)
|
||||
fmt.Printf("'path' specifies the full path of an image to run\n")
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
scsi, err := object.SCSIControllerTypes().CreateSCSIController("pvscsi")
|
||||
if err != nil {
|
||||
return errors.New("Error creating pvscsi controller as part of new VM")
|
||||
}
|
||||
|
||||
spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{
|
||||
Operation: types.VirtualDeviceConfigSpecOperationAdd,
|
||||
Device: scsi,
|
||||
})
|
||||
|
||||
task, err := folders.VmFolder.CreateVM(ctx, spec, rp, hs)
|
||||
if err != nil {
|
||||
return errors.New("Creating new VM failed, more detail can be found in vCenter tasks")
|
||||
}
|
||||
|
||||
info, err := task.WaitForResult(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Creating new VM failed\n%w", err)
|
||||
}
|
||||
|
||||
// Retrieve the new VM
|
||||
vm := object.NewVirtualMachine(c.Client, info.Result.(types.ManagedObjectReference))
|
||||
|
||||
addISO(ctx, newVM, vm, dss)
|
||||
|
||||
if *newVM.persistent != "" {
|
||||
newVM.persistentSz, err = getDiskSizeMB(*newVM.persistent)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't parse disk-size %s: %v", *newVM.persistent, err)
|
||||
}
|
||||
addVMDK(ctx, vm, dss, newVM)
|
||||
}
|
||||
|
||||
if *newVM.networkName != "" {
|
||||
addNIC(ctx, vm, net)
|
||||
}
|
||||
|
||||
if *newVM.poweron {
|
||||
log.Infoln("Powering on LinuxKit VM")
|
||||
powerOnVM(ctx, vm)
|
||||
}
|
||||
|
||||
if *newVM.guestIP {
|
||||
log.Infof("Waiting for OpenVM Tools to come online")
|
||||
guestIP, err := getVMToolsIP(ctx, vm)
|
||||
if err != nil {
|
||||
log.Errorf("%v", err)
|
||||
}
|
||||
log.Infof("Guest IP Address: %s", guestIP)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatalln("Unable to parse args")
|
||||
}
|
||||
cmd.Flags().StringVar(&vCenterURL, "url", os.Getenv("VCURL"), "URL of VMware vCenter in the format of https://username:password@VCaddress/sdk")
|
||||
cmd.Flags().StringVar(&dcName, "datacenter", os.Getenv("VCDATACENTER"), "The name of the Datacenter to host the VM")
|
||||
cmd.Flags().StringVar(&dsName, "datastore", os.Getenv("VCDATASTORE"), "The name of the DataStore to host the VM")
|
||||
cmd.Flags().StringVar(&networkName, "network", os.Getenv("VCNETWORK"), "The network label the VM will use")
|
||||
cmd.Flags().StringVar(&vSphereHost, "hostname", os.Getenv("VCHOST"), "The server that will run the VM")
|
||||
cmd.Flags().StringVar(&vmFolder, "vmfolder", "", "Specify a name/folder for the virtual machine to reside in")
|
||||
cmd.Flags().StringVar(&vmPath, "path", "", "Path to a specific image")
|
||||
cmd.Flags().StringVar(&persistent, "persistentSize", "", "Size in MB of persistent storage to allocate to the VM")
|
||||
cmd.Flags().BoolVar(&poweron, "powerOn", false, "Power On the new VM once it has been created")
|
||||
cmd.Flags().BoolVar(&guestIP, "waitForIP", false, "LinuxKit will wait for the VM to power on and return the guest IP, requires open-vm-tools and the -powerOn flag to be set")
|
||||
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Printf("Please specify the path to the image to run\n")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
*newVM.path = remArgs[0]
|
||||
|
||||
if *newVM.guestIP && !*newVM.poweron {
|
||||
log.Fatalln("The waitForIP flag can not be used without the powerOn flag")
|
||||
}
|
||||
// Ensure an iso has been passed to the vCenter run Command
|
||||
if strings.HasSuffix(*newVM.path, ".iso") {
|
||||
// Allow alternative names for new virtual machines being created in vCenter
|
||||
if *newVM.vmFolder == "" {
|
||||
*newVM.vmFolder = strings.TrimSuffix(path.Base(*newVM.path), ".iso")
|
||||
}
|
||||
} else {
|
||||
log.Fatalln("Please pass an \".iso\" file as the path")
|
||||
}
|
||||
|
||||
// Connect to VMware vCenter and return the default and found values needed for a new VM
|
||||
c, dss, folders, hs, net, rp := vCenterConnect(ctx, newVM)
|
||||
|
||||
log.Infof("Creating new LinuxKit Virtual Machine")
|
||||
spec := types.VirtualMachineConfigSpec{
|
||||
Name: *newVM.vmFolder,
|
||||
GuestId: "otherLinux64Guest",
|
||||
Files: &types.VirtualMachineFileInfo{VmPathName: fmt.Sprintf("[%s]", dss.Name())},
|
||||
NumCPUs: int32(*newVM.vCpus),
|
||||
MemoryMB: *newVM.mem,
|
||||
}
|
||||
|
||||
scsi, err := object.SCSIControllerTypes().CreateSCSIController("pvscsi")
|
||||
if err != nil {
|
||||
log.Fatalln("Error creating pvscsi controller as part of new VM")
|
||||
}
|
||||
|
||||
spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{
|
||||
Operation: types.VirtualDeviceConfigSpecOperationAdd,
|
||||
Device: scsi,
|
||||
})
|
||||
|
||||
task, err := folders.VmFolder.CreateVM(ctx, spec, rp, hs)
|
||||
if err != nil {
|
||||
log.Fatalln("Creating new VM failed, more detail can be found in vCenter tasks")
|
||||
}
|
||||
|
||||
info, err := task.WaitForResult(ctx, nil)
|
||||
if err != nil {
|
||||
log.Fatalf("Creating new VM failed\n%v", err)
|
||||
}
|
||||
|
||||
// Retrieve the new VM
|
||||
vm := object.NewVirtualMachine(c.Client, info.Result.(types.ManagedObjectReference))
|
||||
|
||||
addISO(ctx, newVM, vm, dss)
|
||||
|
||||
if *newVM.persistent != "" {
|
||||
newVM.persistentSz, err = getDiskSizeMB(*newVM.persistent)
|
||||
if err != nil {
|
||||
log.Fatalf("Couldn't parse disk-size %s: %v", *newVM.persistent, err)
|
||||
}
|
||||
addVMDK(ctx, vm, dss, newVM)
|
||||
}
|
||||
|
||||
if *newVM.networkName != "" {
|
||||
addNIC(ctx, vm, net)
|
||||
}
|
||||
|
||||
if *newVM.poweron {
|
||||
log.Infoln("Powering on LinuxKit VM")
|
||||
powerOnVM(ctx, vm)
|
||||
}
|
||||
|
||||
if *newVM.guestIP {
|
||||
log.Infof("Waiting for OpenVM Tools to come online")
|
||||
guestIP, err := getVMToolsIP(ctx, vm)
|
||||
if err != nil {
|
||||
log.Errorf("%v", err)
|
||||
}
|
||||
log.Infof("Guest IP Address: %s", guestIP)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func getVMToolsIP(ctx context.Context, vm *object.VirtualMachine) (string, error) {
|
||||
|
||||
@@ -1,13 +1,68 @@
|
||||
//go:build !darwin
|
||||
// +build !darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runVirtualizationFramework(args []string) {
|
||||
log.Fatal("virtualization framework is available only on macOS")
|
||||
const (
|
||||
virtualizationNetworkingNone string = "none"
|
||||
virtualizationNetworkingDockerForMac = "docker-for-mac"
|
||||
virtualizationNetworkingVPNKit = "vpnkit"
|
||||
virtualizationNetworkingVMNet = "vmnet"
|
||||
virtualizationNetworkingDefault = virtualizationNetworkingVMNet
|
||||
virtualizationFrameworkConsole = "console=hvc0"
|
||||
)
|
||||
|
||||
type virtualizationFramwworkConfig struct {
|
||||
cpus uint
|
||||
mem uint64
|
||||
disks Disks
|
||||
data string
|
||||
dataPath string
|
||||
state string
|
||||
networking string
|
||||
kernelBoot bool
|
||||
}
|
||||
|
||||
func runVirtualizationFrameworkCmd() *cobra.Command {
|
||||
var (
|
||||
data string
|
||||
dataPath string
|
||||
state string
|
||||
networking string
|
||||
kernelBoot bool
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "virtualization",
|
||||
Short: "launch a VM using the macOS virtualization framework",
|
||||
Long: `Launch a VM using the macOS virtualization framework.
|
||||
'prefix' specifies the path to the VM image.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run virtualization [options] prefix",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cfg := virtualizationFramwworkConfig{
|
||||
cpus: uint(cpus),
|
||||
mem: uint64(mem) * 1024 * 1024,
|
||||
disks: disks,
|
||||
data: data,
|
||||
dataPath: dataPath,
|
||||
state: state,
|
||||
networking: networking,
|
||||
kernelBoot: kernelBoot,
|
||||
}
|
||||
return runVirtualizationFramework(cfg, args[0])
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&data, "data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
cmd.Flags().StringVar(&dataPath, "data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
|
||||
cmd.Flags().StringVar(&state, "state", "", "Path to directory to keep VM state in")
|
||||
cmd.Flags().StringVar(&networking, "networking", virtualizationNetworkingDefault, "Networking mode. Valid options are 'default', 'vmnet' and 'none'. 'vmnet' uses the Apple vmnet framework. 'none' disables networking.`")
|
||||
|
||||
cmd.Flags().BoolVar(&kernelBoot, "kernel", false, "Boot image is kernel+initrd+cmdline 'path'-kernel/-initrd/-cmdline")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runVirtualizationFramework(args []string) {
|
||||
log.Fatal("This build of linuxkit was compiled without virtualization framework capabilities. " +
|
||||
func runVirtualizationFramework(cfg virtualizationFramwworkConfig, image string) error {
|
||||
return errors.New("This build of linuxkit was compiled without virtualization framework capabilities. " +
|
||||
"To perform 'linuxkit run' on macOS, please use a version of linuxkit compiled with virtualization framework.")
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ package main
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"flag"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -22,53 +22,12 @@ import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const (
|
||||
virtualizationNetworkingNone string = "none"
|
||||
virtualizationNetworkingDockerForMac = "docker-for-mac"
|
||||
virtualizationNetworkingVPNKit = "vpnkit"
|
||||
virtualizationNetworkingVMNet = "vmnet"
|
||||
virtualizationNetworkingDefault = virtualizationNetworkingVMNet
|
||||
virtualizationFrameworkConsole = "console=hvc0"
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runVirtualizationFramework(args []string) {
|
||||
flags := flag.NewFlagSet("virtualization", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run virtualization [options] prefix\n\n", invoked)
|
||||
fmt.Printf("'prefix' specifies the path to the VM image.\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Options:\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
cpus := flags.Uint("cpus", 1, "Number of CPUs")
|
||||
mem := flags.Uint64("mem", 1024, "Amount of memory in MB")
|
||||
memBytes := *mem * 1024 * 1024
|
||||
var disks Disks
|
||||
flags.Var(&disks, "disk", "Disk config. [file=]path[,size=1G]")
|
||||
data := flags.String("data", "", "String of metadata to pass to VM; error to specify both -data and -data-file")
|
||||
dataPath := flags.String("data-file", "", "Path to file containing metadata to pass to VM; error to specify both -data and -data-file")
|
||||
|
||||
if *data != "" && *dataPath != "" {
|
||||
log.Fatal("Cannot specify both -data and -data-file")
|
||||
func runVirtualizationFramework(cfg virtualizationFramwworkConfig, path string) error {
|
||||
if cfg.data != "" && cfg.dataPath != "" {
|
||||
return errors.New("Cannot specify both -data and -data-file")
|
||||
}
|
||||
|
||||
state := flags.String("state", "", "Path to directory to keep VM state in")
|
||||
networking := flags.String("networking", virtualizationNetworkingDefault, "Networking mode. Valid options are 'default', 'vmnet' and 'none'. 'vmnet' uses the Apple vmnet framework. 'none' disables networking.`")
|
||||
|
||||
kernelBoot := flags.Bool("kernel", false, "Boot image is kernel+initrd+cmdline 'path'-kernel/-initrd/-cmdline")
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
remArgs := flags.Args()
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Println("Please specify the prefix to the image to boot")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
path := remArgs[0]
|
||||
prefix := path
|
||||
|
||||
_, err := os.Stat(path + "-kernel")
|
||||
@@ -78,18 +37,18 @@ func runVirtualizationFramework(args []string) {
|
||||
|
||||
// Default to kernel+initrd
|
||||
if !statKernel {
|
||||
log.Fatalf("Cannot find kernel file: %s", path+"-kernel")
|
||||
return fmt.Errorf("Cannot find kernel file: %s", path+"-kernel")
|
||||
}
|
||||
_, err = os.Stat(path + "-initrd.img")
|
||||
statInitrd := err == nil
|
||||
if !statInitrd {
|
||||
log.Fatalf("Cannot find initrd file (%s): %v", path+"-initrd.img", err)
|
||||
return fmt.Errorf("Cannot find initrd file (%s): %w", path+"-initrd.img", err)
|
||||
}
|
||||
*kernelBoot = true
|
||||
cfg.kernelBoot = true
|
||||
|
||||
metadataPaths, err := CreateMetadataISO(*state, *data, *dataPath)
|
||||
metadataPaths, err := CreateMetadataISO(cfg.state, cfg.data, cfg.dataPath)
|
||||
if err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
return fmt.Errorf("%w", err)
|
||||
}
|
||||
isoPaths = append(isoPaths, metadataPaths...)
|
||||
|
||||
@@ -100,7 +59,7 @@ func runVirtualizationFramework(args []string) {
|
||||
|
||||
cmdlineBytes, err := os.ReadFile(prefix + "-cmdline")
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot open cmdline file: %v", err)
|
||||
return fmt.Errorf("Cannot open cmdline file: %v", err)
|
||||
}
|
||||
// must have hvc0 as console for vf
|
||||
kernelCommandLineArguments := strings.Split(string(cmdlineBytes), " ")
|
||||
@@ -119,7 +78,7 @@ func runVirtualizationFramework(args []string) {
|
||||
// need to check if it is gzipped, and, if so, gunzip it
|
||||
filetype, err := checkFileType(vmlinuz)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to check kernel file type at %s: %v", vmlinuz, err)
|
||||
return fmt.Errorf("unable to check kernel file type at %s: %v", vmlinuz, err)
|
||||
}
|
||||
|
||||
if filetype == "application/x-gzip" {
|
||||
@@ -127,23 +86,23 @@ func runVirtualizationFramework(args []string) {
|
||||
// gzipped kernel, we load it into memory, unzip it, and pass it
|
||||
f, err := os.Open(vmlinuz)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to read kernel file %s: %v", vmlinuz, err)
|
||||
return fmt.Errorf("unable to read kernel file %s: %v", vmlinuz, err)
|
||||
}
|
||||
defer f.Close()
|
||||
r, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to read from file %s: %v", vmlinuz, err)
|
||||
return fmt.Errorf("unable to read from file %s: %v", vmlinuz, err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
writer, err := os.Create(vmlinuzUncompressed)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to create decompressed kernel file %s: %v", vmlinuzUncompressed, err)
|
||||
return fmt.Errorf("unable to create decompressed kernel file %s: %v", vmlinuzUncompressed, err)
|
||||
}
|
||||
defer writer.Close()
|
||||
|
||||
if _, err = io.Copy(writer, r); err != nil {
|
||||
log.Fatalf("unable to decompress kernel file to %s: %v", vmlinuzUncompressed, err)
|
||||
return fmt.Errorf("unable to decompress kernel file to %s: %v", vmlinuzUncompressed, err)
|
||||
}
|
||||
vmlinuzFile = vmlinuzUncompressed
|
||||
}
|
||||
@@ -153,27 +112,27 @@ func runVirtualizationFramework(args []string) {
|
||||
vz.WithInitrd(initrd),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to create bootloader: %v", err)
|
||||
return fmt.Errorf("unable to create bootloader: %v", err)
|
||||
}
|
||||
|
||||
config, err := vz.NewVirtualMachineConfiguration(
|
||||
bootLoader,
|
||||
*cpus,
|
||||
memBytes,
|
||||
cfg.cpus,
|
||||
cfg.mem,
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to create VM config: %v", err)
|
||||
return fmt.Errorf("unable to create VM config: %v", err)
|
||||
}
|
||||
|
||||
// console
|
||||
stdin, stdout := os.Stdin, os.Stdout
|
||||
serialPortAttachment, err := vz.NewFileHandleSerialPortAttachment(stdin, stdout)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to create serial port attachment: %v", err)
|
||||
return fmt.Errorf("unable to create serial port attachment: %v", err)
|
||||
}
|
||||
consoleConfig, err := vz.NewVirtioConsoleDeviceSerialPortConfiguration(serialPortAttachment)
|
||||
if err != nil {
|
||||
log.Fatalf("unable to create console config: %v", err)
|
||||
return fmt.Errorf("unable to create console config: %v", err)
|
||||
}
|
||||
config.SetSerialPortsVirtualMachineConfiguration([]*vz.VirtioConsoleDeviceSerialPortConfiguration{
|
||||
consoleConfig,
|
||||
@@ -183,39 +142,38 @@ func runVirtualizationFramework(args []string) {
|
||||
// network
|
||||
// Select network mode
|
||||
// for now, we only support vmnet and none, but hoping to have more in the future
|
||||
if *networking == "" || *networking == "default" {
|
||||
dflt := virtualizationNetworkingDefault
|
||||
networking = &dflt
|
||||
if cfg.networking == "" || cfg.networking == "default" {
|
||||
cfg.networking = virtualizationNetworkingDefault
|
||||
}
|
||||
netMode := strings.SplitN(*networking, ",", 3)
|
||||
netMode := strings.SplitN(cfg.networking, ",", 3)
|
||||
switch netMode[0] {
|
||||
|
||||
case virtualizationNetworkingVMNet:
|
||||
natAttachment, err := vz.NewNATNetworkDeviceAttachment()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create NAT network device attachment: %v", err)
|
||||
return fmt.Errorf("Could not create NAT network device attachment: %v", err)
|
||||
}
|
||||
networkConfig, err := vz.NewVirtioNetworkDeviceConfiguration(natAttachment)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create virtio network device configuration: %v", err)
|
||||
return fmt.Errorf("Could not create virtio network device configuration: %v", err)
|
||||
}
|
||||
config.SetNetworkDevicesVirtualMachineConfiguration([]*vz.VirtioNetworkDeviceConfiguration{
|
||||
networkConfig,
|
||||
})
|
||||
macAddress, err := vz.NewRandomLocallyAdministeredMACAddress()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create random MAC address: %v", err)
|
||||
return fmt.Errorf("Could not create random MAC address: %v", err)
|
||||
}
|
||||
networkConfig.SetMACAddress(macAddress)
|
||||
case virtualizationNetworkingNone:
|
||||
default:
|
||||
log.Fatalf("Invalid networking mode: %s", netMode[0])
|
||||
return fmt.Errorf("Invalid networking mode: %s", netMode[0])
|
||||
}
|
||||
|
||||
// entropy
|
||||
entropyConfig, err := vz.NewVirtioEntropyDeviceConfiguration()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create virtio entropy device configuration: %v", err)
|
||||
return fmt.Errorf("Could not create virtio entropy device configuration: %v", err)
|
||||
}
|
||||
|
||||
config.SetEntropyDevicesVirtualMachineConfiguration([]*vz.VirtioEntropyDeviceConfiguration{
|
||||
@@ -223,16 +181,16 @@ func runVirtualizationFramework(args []string) {
|
||||
})
|
||||
|
||||
var storageDevices []vz.StorageDeviceConfiguration
|
||||
for i, d := range disks {
|
||||
for i, d := range cfg.disks {
|
||||
var id, diskPath string
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
diskPath = filepath.Join(*state, "disk"+id+".raw")
|
||||
diskPath = filepath.Join(cfg.state, "disk"+id+".raw")
|
||||
}
|
||||
if d.Path == "" {
|
||||
log.Fatalf("disk specified with no size or name")
|
||||
return fmt.Errorf("disk specified with no size or name")
|
||||
}
|
||||
diskImageAttachment, err := vz.NewDiskImageStorageDeviceAttachment(
|
||||
diskPath,
|
||||
@@ -243,7 +201,7 @@ func runVirtualizationFramework(args []string) {
|
||||
}
|
||||
storageDeviceConfig, err := vz.NewVirtioBlockDeviceConfiguration(diskImageAttachment)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create virtio block device configuration: %v", err)
|
||||
return fmt.Errorf("Could not create virtio block device configuration: %v", err)
|
||||
}
|
||||
storageDevices = append(storageDevices, storageDeviceConfig)
|
||||
}
|
||||
@@ -257,7 +215,7 @@ func runVirtualizationFramework(args []string) {
|
||||
}
|
||||
storageDeviceConfig, err := vz.NewVirtioBlockDeviceConfiguration(diskImageAttachment)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create virtio block device configuration: %v", err)
|
||||
return fmt.Errorf("Could not create virtio block device configuration: %v", err)
|
||||
}
|
||||
storageDevices = append(storageDevices, storageDeviceConfig)
|
||||
}
|
||||
@@ -267,7 +225,7 @@ func runVirtualizationFramework(args []string) {
|
||||
// traditional memory balloon device which allows for managing guest memory. (optional)
|
||||
memoryBalloonDeviceConfiguration, err := vz.NewVirtioTraditionalMemoryBalloonDeviceConfiguration()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create virtio traditional memory balloon device configuration: %v", err)
|
||||
return fmt.Errorf("Could not create virtio traditional memory balloon device configuration: %v", err)
|
||||
}
|
||||
config.SetMemoryBalloonDevicesVirtualMachineConfiguration([]vz.MemoryBalloonDeviceConfiguration{
|
||||
memoryBalloonDeviceConfiguration,
|
||||
@@ -276,7 +234,7 @@ func runVirtualizationFramework(args []string) {
|
||||
// socket device (optional)
|
||||
socketDeviceConfiguration, err := vz.NewVirtioSocketDeviceConfiguration()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create virtio socket device configuration: %v", err)
|
||||
return fmt.Errorf("Could not create virtio socket device configuration: %v", err)
|
||||
}
|
||||
config.SetSocketDevicesVirtualMachineConfiguration([]vz.SocketDeviceConfiguration{
|
||||
socketDeviceConfiguration,
|
||||
@@ -288,7 +246,7 @@ func runVirtualizationFramework(args []string) {
|
||||
|
||||
vm, err := vz.NewVirtualMachine(config)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not create virtual machine: %v", err)
|
||||
return fmt.Errorf("Could not create virtual machine: %v", err)
|
||||
}
|
||||
|
||||
signalCh := make(chan os.Signal, 1)
|
||||
@@ -306,7 +264,7 @@ func runVirtualizationFramework(args []string) {
|
||||
result, err := vm.RequestStop()
|
||||
if err != nil {
|
||||
log.Println("request stop error:", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
log.Println("recieved signal", result)
|
||||
case newState := <-vm.StateChangedNotify():
|
||||
@@ -315,7 +273,7 @@ func runVirtualizationFramework(args []string) {
|
||||
}
|
||||
if newState == vz.VirtualMachineStateStopped {
|
||||
log.Println("stopped successfully")
|
||||
return
|
||||
return nil
|
||||
}
|
||||
case err := <-errCh:
|
||||
log.Println("in start:", err)
|
||||
|
||||
13
src/cmd/linuxkit/run_virtualizationframework_others.go
Normal file
13
src/cmd/linuxkit/run_virtualizationframework_others.go
Normal file
@@ -0,0 +1,13 @@
|
||||
//go:build !darwin
|
||||
// +build !darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Process the run arguments and execute run
|
||||
func runVirtualizationFramework(cfg virtualizationFramwworkConfig, image string) error {
|
||||
return errors.New("virtualization framework is available only on macOS")
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -10,6 +9,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
//Version 12 relates to Fusion 8 and WS 12
|
||||
@@ -64,144 +64,138 @@ ethernet0.generatedAddressOffset = "0"
|
||||
guestOS = "other3xlinux-64"
|
||||
`
|
||||
|
||||
func runVMware(args []string) {
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags := flag.NewFlagSet("vmware", flag.ExitOnError)
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s run vmware [options] prefix\n\n", invoked)
|
||||
fmt.Printf("'prefix' specifies the path to the VM image.\n")
|
||||
fmt.Printf("\n")
|
||||
fmt.Printf("Options:\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
cpus := flags.Int("cpus", 1, "Number of CPUs")
|
||||
mem := flags.Int("mem", 1024, "Amount of memory in MB")
|
||||
var disks Disks
|
||||
flags.Var(&disks, "disk", "Disk config. [file=]path[,size=1G]")
|
||||
state := flags.String("state", "", "Path to directory to keep VM state in")
|
||||
func runVMWareCmd() *cobra.Command {
|
||||
var (
|
||||
state string
|
||||
)
|
||||
|
||||
if err := flags.Parse(args); err != nil {
|
||||
log.Fatal("Unable to parse args")
|
||||
}
|
||||
remArgs := flags.Args()
|
||||
|
||||
if len(remArgs) == 0 {
|
||||
fmt.Println("Please specify the prefix to the image to boot")
|
||||
flags.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
prefix := remArgs[0]
|
||||
|
||||
if *state == "" {
|
||||
*state = prefix + "-state"
|
||||
}
|
||||
if err := os.MkdirAll(*state, 0755); err != nil {
|
||||
log.Fatalf("Could not create state directory: %v", err)
|
||||
}
|
||||
|
||||
var vmrunPath, vmDiskManagerPath string
|
||||
var vmrunArgs []string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
vmrunPath = "C:\\Program\\ files\\VMware Workstation\\vmrun.exe"
|
||||
vmDiskManagerPath = "C:\\Program\\ files\\VMware Workstation\\vmware-vdiskmanager.exe"
|
||||
vmrunArgs = []string{"-T", "ws", "start"}
|
||||
case "darwin":
|
||||
vmrunPath = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
|
||||
vmDiskManagerPath = "/Applications/VMware Fusion.app/Contents/Library/vmware-vdiskmanager"
|
||||
vmrunArgs = []string{"-T", "fusion", "start"}
|
||||
default:
|
||||
vmrunPath = "vmrun"
|
||||
vmDiskManagerPath = "vmware-vdiskmanager"
|
||||
fullVMrunPath, err := exec.LookPath(vmrunPath)
|
||||
if err != nil {
|
||||
// Kept as separate error as people may manually change their environment vars
|
||||
log.Fatalf("Unable to find %s within the $PATH", vmrunPath)
|
||||
}
|
||||
vmrunPath = fullVMrunPath
|
||||
vmrunArgs = []string{"-T", "ws", "start"}
|
||||
}
|
||||
|
||||
// Check vmrunPath exists before attempting to execute
|
||||
if _, err := os.Stat(vmrunPath); os.IsNotExist(err) {
|
||||
log.Fatalf("ERROR VMware executables can not be found, ensure software is installed")
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = filepath.Join(*state, "disk"+id+".vmdk")
|
||||
}
|
||||
if d.Format != "" && d.Format != "vmdk" {
|
||||
log.Fatalf("only vmdk supported for VMware driver")
|
||||
}
|
||||
if d.Path == "" {
|
||||
log.Fatalf("disk specified with no size or name")
|
||||
}
|
||||
disks[i] = d
|
||||
}
|
||||
|
||||
for _, d := range disks {
|
||||
// Check vmDiskManagerPath exist before attempting to execute
|
||||
if _, err := os.Stat(vmDiskManagerPath); os.IsNotExist(err) {
|
||||
log.Fatalf("ERROR VMware Disk Manager executables can not be found, ensure software is installed")
|
||||
}
|
||||
|
||||
// If disk doesn't exist then create one, error if disk is unreadable
|
||||
if _, err := os.Stat(d.Path); err != nil {
|
||||
if os.IsPermission(err) {
|
||||
log.Fatalf("Unable to read file [%s], please check permissions", d.Path)
|
||||
} else if os.IsNotExist(err) {
|
||||
log.Infof("Creating new VMware disk [%s]", d.Path)
|
||||
vmDiskCmd := exec.Command(vmDiskManagerPath, "-c", "-s", fmt.Sprintf("%dMB", d.Size), "-a", "lsilogic", "-t", "0", d.Path)
|
||||
if err = vmDiskCmd.Run(); err != nil {
|
||||
log.Fatalf("Error creating disk [%s]: %v", d.Path, err)
|
||||
}
|
||||
} else {
|
||||
log.Fatalf("Unable to read file [%s]: %v", d.Path, err)
|
||||
cmd := &cobra.Command{
|
||||
Use: "vmware",
|
||||
Short: "launch a VMWare instance using the provided image",
|
||||
Long: `Launch a VMWare instance using the provided image.
|
||||
'prefix' specifies the path to the VM image.
|
||||
`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Example: "linuxkit run vmware [options] prefix",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
prefix := args[0]
|
||||
if state == "" {
|
||||
state = prefix + "-state"
|
||||
}
|
||||
} else {
|
||||
log.Infof("Using existing disk [%s]", d.Path)
|
||||
}
|
||||
if err := os.MkdirAll(state, 0755); err != nil {
|
||||
return fmt.Errorf("Could not create state directory: %v", err)
|
||||
}
|
||||
|
||||
var vmrunPath, vmDiskManagerPath string
|
||||
var vmrunArgs []string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
vmrunPath = "C:\\Program\\ files\\VMware Workstation\\vmrun.exe"
|
||||
vmDiskManagerPath = "C:\\Program\\ files\\VMware Workstation\\vmware-vdiskmanager.exe"
|
||||
vmrunArgs = []string{"-T", "ws", "start"}
|
||||
case "darwin":
|
||||
vmrunPath = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
|
||||
vmDiskManagerPath = "/Applications/VMware Fusion.app/Contents/Library/vmware-vdiskmanager"
|
||||
vmrunArgs = []string{"-T", "fusion", "start"}
|
||||
default:
|
||||
vmrunPath = "vmrun"
|
||||
vmDiskManagerPath = "vmware-vdiskmanager"
|
||||
fullVMrunPath, err := exec.LookPath(vmrunPath)
|
||||
if err != nil {
|
||||
// Kept as separate error as people may manually change their environment vars
|
||||
return fmt.Errorf("Unable to find %s within the $PATH", vmrunPath)
|
||||
}
|
||||
vmrunPath = fullVMrunPath
|
||||
vmrunArgs = []string{"-T", "ws", "start"}
|
||||
}
|
||||
|
||||
// Check vmrunPath exists before attempting to execute
|
||||
if _, err := os.Stat(vmrunPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("ERROR VMware executables can not be found, ensure software is installed")
|
||||
}
|
||||
|
||||
for i, d := range disks {
|
||||
id := ""
|
||||
if i != 0 {
|
||||
id = strconv.Itoa(i)
|
||||
}
|
||||
if d.Size != 0 && d.Path == "" {
|
||||
d.Path = filepath.Join(state, "disk"+id+".vmdk")
|
||||
}
|
||||
if d.Format != "" && d.Format != "vmdk" {
|
||||
return fmt.Errorf("only vmdk supported for VMware driver")
|
||||
}
|
||||
if d.Path == "" {
|
||||
return fmt.Errorf("disk specified with no size or name")
|
||||
}
|
||||
disks[i] = d
|
||||
}
|
||||
|
||||
for _, d := range disks {
|
||||
// Check vmDiskManagerPath exist before attempting to execute
|
||||
if _, err := os.Stat(vmDiskManagerPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("ERROR VMware Disk Manager executables can not be found, ensure software is installed")
|
||||
}
|
||||
|
||||
// If disk doesn't exist then create one, error if disk is unreadable
|
||||
if _, err := os.Stat(d.Path); err != nil {
|
||||
if os.IsPermission(err) {
|
||||
return fmt.Errorf("Unable to read file [%s], please check permissions", d.Path)
|
||||
} else if os.IsNotExist(err) {
|
||||
log.Infof("Creating new VMware disk [%s]", d.Path)
|
||||
vmDiskCmd := exec.Command(vmDiskManagerPath, "-c", "-s", fmt.Sprintf("%dMB", d.Size), "-a", "lsilogic", "-t", "0", d.Path)
|
||||
if err = vmDiskCmd.Run(); err != nil {
|
||||
return fmt.Errorf("Error creating disk [%s]: %w", d.Path, err)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("Unable to read file [%s]: %w", d.Path, err)
|
||||
}
|
||||
} else {
|
||||
log.Infof("Using existing disk [%s]", d.Path)
|
||||
}
|
||||
}
|
||||
|
||||
if len(disks) > 1 {
|
||||
return fmt.Errorf("VMware driver currently only supports a single disk")
|
||||
}
|
||||
|
||||
disk := ""
|
||||
if len(disks) == 1 {
|
||||
disk = disks[0].Path
|
||||
}
|
||||
|
||||
// Build the contents of the VMWare .vmx file
|
||||
vmx := buildVMX(cpus, mem, disk, prefix)
|
||||
if vmx == "" {
|
||||
return fmt.Errorf("VMware .vmx file could not be generated, please confirm inputs")
|
||||
}
|
||||
|
||||
// Create the .vmx file
|
||||
vmxPath := filepath.Join(state, "linuxkit.vmx")
|
||||
err := os.WriteFile(vmxPath, []byte(vmx), 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error writing .vmx file: %v", err)
|
||||
}
|
||||
vmrunArgs = append(vmrunArgs, vmxPath)
|
||||
|
||||
execCmd := exec.Command(vmrunPath, vmrunArgs...)
|
||||
out, err := execCmd.Output()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error starting vmrun: %v", err)
|
||||
}
|
||||
|
||||
// check there is output to push to logging
|
||||
if len(out) > 0 {
|
||||
log.Info(out)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
if len(disks) > 1 {
|
||||
log.Fatalf("VMware driver currently only supports a single disk")
|
||||
}
|
||||
cmd.Flags().StringVar(&state, "state", "", "Path to directory to keep VM state in")
|
||||
|
||||
disk := ""
|
||||
if len(disks) == 1 {
|
||||
disk = disks[0].Path
|
||||
}
|
||||
|
||||
// Build the contents of the VMWare .vmx file
|
||||
vmx := buildVMX(*cpus, *mem, disk, prefix)
|
||||
if vmx == "" {
|
||||
log.Fatalf("VMware .vmx file could not be generated, please confirm inputs")
|
||||
}
|
||||
|
||||
// Create the .vmx file
|
||||
vmxPath := filepath.Join(*state, "linuxkit.vmx")
|
||||
err := os.WriteFile(vmxPath, []byte(vmx), 0644)
|
||||
if err != nil {
|
||||
log.Fatalf("Error writing .vmx file: %v", err)
|
||||
}
|
||||
vmrunArgs = append(vmrunArgs, vmxPath)
|
||||
|
||||
cmd := exec.Command(vmrunPath, vmrunArgs...)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
log.Fatalf("Error starting vmrun: %v", err)
|
||||
}
|
||||
|
||||
// check there is output to push to logging
|
||||
if len(out) > 0 {
|
||||
log.Info(out)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func buildVMX(cpus int, mem int, persistentDisk string, prefix string) string {
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func logRequest(handler http.Handler) http.Handler {
|
||||
@@ -17,19 +14,25 @@ func logRequest(handler http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// serve starts a local web server
|
||||
func serve(args []string) {
|
||||
flags := flag.NewFlagSet("serve", flag.ExitOnError)
|
||||
invoked := filepath.Base(os.Args[0])
|
||||
flags.Usage = func() {
|
||||
fmt.Printf("USAGE: %s serve [options]\n\n", invoked)
|
||||
fmt.Printf("Options:\n\n")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
portFlag := flags.String("port", ":8080", "Local port to serve on")
|
||||
dirFlag := flags.String("directory", ".", "Directory to serve")
|
||||
_ = flags.Parse(args)
|
||||
func serveCmd() *cobra.Command {
|
||||
var (
|
||||
port string
|
||||
dir string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "serve",
|
||||
Short: "serve a directory over http",
|
||||
Long: `Serve a directory over http.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
http.Handle("/", http.FileServer(http.Dir(dir)))
|
||||
log.Fatal(http.ListenAndServe(port, logRequest(http.DefaultServeMux)))
|
||||
|
||||
http.Handle("/", http.FileServer(http.Dir(*dirFlag)))
|
||||
log.Fatal(http.ListenAndServe(*portFlag, logRequest(http.DefaultServeMux)))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&port, "port", ":8080", "Local port to serve on")
|
||||
cmd.Flags().StringVar(&dir, "directory", ".", "Directory to serve")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -16,6 +16,10 @@ func (f *multipleFlag) String() string {
|
||||
return "A multiple flag is a type of flag that can be repeated any number of times"
|
||||
}
|
||||
|
||||
func (f *multipleFlag) Type() string {
|
||||
return "[]string"
|
||||
}
|
||||
|
||||
func (f *multipleFlag) Set(value string) error {
|
||||
*f = append(*f, value)
|
||||
return nil
|
||||
@@ -138,6 +142,10 @@ func (f *flagOverEnvVarOverDefaultString) Set(value string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *flagOverEnvVarOverDefaultString) Type() string {
|
||||
return "string"
|
||||
}
|
||||
|
||||
// Convert a multi-line string into an array of strings
|
||||
func splitLines(in string) []string {
|
||||
var res []string
|
||||
@@ -199,6 +207,10 @@ func (l *Disks) String() string {
|
||||
return fmt.Sprint(*l)
|
||||
}
|
||||
|
||||
func (l *Disks) Type() string {
|
||||
return "[]DiskConfig"
|
||||
}
|
||||
|
||||
// Set is used by flag to configure value from CLI
|
||||
func (l *Disks) Set(value string) error {
|
||||
d := DiskConfig{}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"errors"
|
||||
stdlog "log"
|
||||
"os"
|
||||
|
||||
ggcrlog "github.com/google/go-containerregistry/pkg/logs"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -26,37 +24,18 @@ func (f *infoFormatter) Format(entry *log.Entry) ([]byte, error) {
|
||||
return defaultLogFormatter.Format(entry)
|
||||
}
|
||||
|
||||
var (
|
||||
flagQuiet, flagVerbose *bool
|
||||
)
|
||||
|
||||
// AddLoggingFlags add the logging flags to a flagset, or, if none given,
|
||||
// the default flag package
|
||||
func AddLoggingFlags(fs *flag.FlagSet) {
|
||||
// if we have no flagset, add it to the default flag package
|
||||
if fs == nil {
|
||||
flagQuiet = flag.Bool("q", false, "Quiet execution")
|
||||
flagVerbose = flag.Bool("v", false, "Verbose execution")
|
||||
} else {
|
||||
flagQuiet = fs.Bool("q", false, "Quiet execution")
|
||||
flagVerbose = fs.Bool("v", false, "Verbose execution")
|
||||
}
|
||||
}
|
||||
|
||||
// SetupLogging once the flags have been parsed, setup the logging
|
||||
func SetupLogging() {
|
||||
func SetupLogging(quiet, verbose bool) error {
|
||||
// Set up logging
|
||||
log.SetFormatter(new(infoFormatter))
|
||||
log.SetLevel(log.InfoLevel)
|
||||
flag.Parse()
|
||||
if *flagQuiet && *flagVerbose {
|
||||
fmt.Printf("Can't set quiet and verbose flag at the same time\n")
|
||||
os.Exit(1)
|
||||
if quiet && verbose {
|
||||
return errors.New("can't set quiet and verbose flag at the same time")
|
||||
}
|
||||
if *flagQuiet {
|
||||
if quiet {
|
||||
log.SetLevel(log.ErrorLevel)
|
||||
}
|
||||
if *flagVerbose {
|
||||
if verbose {
|
||||
// Switch back to the standard formatter
|
||||
log.SetFormatter(defaultLogFormatter)
|
||||
log.SetLevel(log.DebugLevel)
|
||||
@@ -65,4 +44,5 @@ func SetupLogging() {
|
||||
ggcrlog.Debug = stdlog.New(log.StandardLogger().WriterLevel(log.DebugLevel), "", 0)
|
||||
}
|
||||
ggcrlog.Progress = stdlog.New(log.StandardLogger().WriterLevel(log.InfoLevel), "", 0)
|
||||
return nil
|
||||
}
|
||||
|
||||
201
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
Normal file
201
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2022 Alan Shreve (@inconshreveable)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
23
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/README.md
generated
vendored
Normal file
23
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/README.md
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
# mousetrap
|
||||
|
||||
mousetrap is a tiny library that answers a single question.
|
||||
|
||||
On a Windows machine, was the process invoked by someone double clicking on
|
||||
the executable file while browsing in explorer?
|
||||
|
||||
### Motivation
|
||||
|
||||
Windows developers unfamiliar with command line tools will often "double-click"
|
||||
the executable for a tool. Because most CLI tools print the help and then exit
|
||||
when invoked without arguments, this is often very frustrating for those users.
|
||||
|
||||
mousetrap provides a way to detect these invocations so that you can provide
|
||||
more helpful behavior and instructions on how to run the CLI tool. To see what
|
||||
this looks like, both from an organizational and a technical perspective, see
|
||||
https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
|
||||
|
||||
### The interface
|
||||
|
||||
The library exposes a single interface:
|
||||
|
||||
func StartedByExplorer() (bool)
|
||||
15
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
Normal file
15
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
// +build !windows
|
||||
|
||||
package mousetrap
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user
|
||||
// double-clicking on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
//
|
||||
// On non-Windows platforms, it always returns false.
|
||||
func StartedByExplorer() bool {
|
||||
return false
|
||||
}
|
||||
98
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
Normal file
98
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
// +build windows
|
||||
// +build !go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// defined by the Win32 API
|
||||
th32cs_snapprocess uintptr = 0x2
|
||||
)
|
||||
|
||||
var (
|
||||
kernel = syscall.MustLoadDLL("kernel32.dll")
|
||||
CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
|
||||
Process32First = kernel.MustFindProc("Process32FirstW")
|
||||
Process32Next = kernel.MustFindProc("Process32NextW")
|
||||
)
|
||||
|
||||
// ProcessEntry32 structure defined by the Win32 API
|
||||
type processEntry32 struct {
|
||||
dwSize uint32
|
||||
cntUsage uint32
|
||||
th32ProcessID uint32
|
||||
th32DefaultHeapID int
|
||||
th32ModuleID uint32
|
||||
cntThreads uint32
|
||||
th32ParentProcessID uint32
|
||||
pcPriClassBase int32
|
||||
dwFlags uint32
|
||||
szExeFile [syscall.MAX_PATH]uint16
|
||||
}
|
||||
|
||||
func getProcessEntry(pid int) (pe *processEntry32, err error) {
|
||||
snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
|
||||
if snapshot == uintptr(syscall.InvalidHandle) {
|
||||
err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
|
||||
return
|
||||
}
|
||||
defer syscall.CloseHandle(syscall.Handle(snapshot))
|
||||
|
||||
var processEntry processEntry32
|
||||
processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
|
||||
ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32First: %v", e1)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
if processEntry.th32ProcessID == uint32(pid) {
|
||||
pe = &processEntry
|
||||
return
|
||||
}
|
||||
|
||||
ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32Next: %v", e1)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getppid() (pid int, err error) {
|
||||
pe, err := getProcessEntry(os.Getpid())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
pid = int(pe.th32ParentProcessID)
|
||||
return
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
ppid, err := getppid()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pe, err := getProcessEntry(ppid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
name := syscall.UTF16ToString(pe.szExeFile[:])
|
||||
return name == "explorer.exe"
|
||||
}
|
||||
46
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
Normal file
46
src/cmd/linuxkit/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
// +build windows
|
||||
// +build go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
|
||||
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(snapshot)
|
||||
var procEntry syscall.ProcessEntry32
|
||||
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
|
||||
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for {
|
||||
if procEntry.ProcessID == uint32(pid) {
|
||||
return &procEntry, nil
|
||||
}
|
||||
err = syscall.Process32Next(snapshot, &procEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
pe, err := getProcessEntry(os.Getppid())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
|
||||
}
|
||||
86
src/cmd/linuxkit/vendor/github.com/mitchellh/go-ps/Vagrantfile
generated
vendored
86
src/cmd/linuxkit/vendor/github.com/mitchellh/go-ps/Vagrantfile
generated
vendored
@@ -1,43 +1,43 @@
|
||||
# -*- mode: ruby -*-
|
||||
# vi: set ft=ruby :
|
||||
|
||||
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
|
||||
VAGRANTFILE_API_VERSION = "2"
|
||||
|
||||
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
|
||||
config.vm.box = "chef/ubuntu-12.04"
|
||||
|
||||
config.vm.provision "shell", inline: $script
|
||||
|
||||
["vmware_fusion", "vmware_workstation"].each do |p|
|
||||
config.vm.provider "p" do |v|
|
||||
v.vmx["memsize"] = "1024"
|
||||
v.vmx["numvcpus"] = "2"
|
||||
v.vmx["cpuid.coresPerSocket"] = "1"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
$script = <<SCRIPT
|
||||
SRCROOT="/opt/go"
|
||||
|
||||
# Install Go
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential mercurial
|
||||
sudo hg clone -u release https://code.google.com/p/go ${SRCROOT}
|
||||
cd ${SRCROOT}/src
|
||||
sudo ./all.bash
|
||||
|
||||
# Setup the GOPATH
|
||||
sudo mkdir -p /opt/gopath
|
||||
cat <<EOF >/tmp/gopath.sh
|
||||
export GOPATH="/opt/gopath"
|
||||
export PATH="/opt/go/bin:\$GOPATH/bin:\$PATH"
|
||||
EOF
|
||||
sudo mv /tmp/gopath.sh /etc/profile.d/gopath.sh
|
||||
sudo chmod 0755 /etc/profile.d/gopath.sh
|
||||
|
||||
# Make sure the gopath is usable by bamboo
|
||||
sudo chown -R vagrant:vagrant $SRCROOT
|
||||
sudo chown -R vagrant:vagrant /opt/gopath
|
||||
SCRIPT
|
||||
# -*- mode: ruby -*-
|
||||
# vi: set ft=ruby :
|
||||
|
||||
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
|
||||
VAGRANTFILE_API_VERSION = "2"
|
||||
|
||||
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
|
||||
config.vm.box = "chef/ubuntu-12.04"
|
||||
|
||||
config.vm.provision "shell", inline: $script
|
||||
|
||||
["vmware_fusion", "vmware_workstation"].each do |p|
|
||||
config.vm.provider "p" do |v|
|
||||
v.vmx["memsize"] = "1024"
|
||||
v.vmx["numvcpus"] = "2"
|
||||
v.vmx["cpuid.coresPerSocket"] = "1"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
$script = <<SCRIPT
|
||||
SRCROOT="/opt/go"
|
||||
|
||||
# Install Go
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential mercurial
|
||||
sudo hg clone -u release https://code.google.com/p/go ${SRCROOT}
|
||||
cd ${SRCROOT}/src
|
||||
sudo ./all.bash
|
||||
|
||||
# Setup the GOPATH
|
||||
sudo mkdir -p /opt/gopath
|
||||
cat <<EOF >/tmp/gopath.sh
|
||||
export GOPATH="/opt/gopath"
|
||||
export PATH="/opt/go/bin:\$GOPATH/bin:\$PATH"
|
||||
EOF
|
||||
sudo mv /tmp/gopath.sh /etc/profile.d/gopath.sh
|
||||
sudo chmod 0755 /etc/profile.d/gopath.sh
|
||||
|
||||
# Make sure the gopath is usable by bamboo
|
||||
sudo chown -R vagrant:vagrant $SRCROOT
|
||||
sudo chown -R vagrant:vagrant /opt/gopath
|
||||
SCRIPT
|
||||
|
||||
39
src/cmd/linuxkit/vendor/github.com/spf13/cobra/.gitignore
generated
vendored
Normal file
39
src/cmd/linuxkit/vendor/github.com/spf13/cobra/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore
|
||||
# swap
|
||||
[._]*.s[a-w][a-z]
|
||||
[._]s[a-w][a-z]
|
||||
# session
|
||||
Session.vim
|
||||
# temporary
|
||||
.netrwhist
|
||||
*~
|
||||
# auto-generated tag files
|
||||
tags
|
||||
|
||||
*.exe
|
||||
cobra.test
|
||||
bin
|
||||
|
||||
.idea/
|
||||
*.iml
|
||||
62
src/cmd/linuxkit/vendor/github.com/spf13/cobra/.golangci.yml
generated
vendored
Normal file
62
src/cmd/linuxkit/vendor/github.com/spf13/cobra/.golangci.yml
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
# Copyright 2013-2022 The Cobra Authors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
run:
|
||||
deadline: 5m
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
#- bodyclose
|
||||
- deadcode
|
||||
#- depguard
|
||||
#- dogsled
|
||||
#- dupl
|
||||
- errcheck
|
||||
#- exhaustive
|
||||
#- funlen
|
||||
- gas
|
||||
#- gochecknoinits
|
||||
- goconst
|
||||
#- gocritic
|
||||
#- gocyclo
|
||||
#- gofmt
|
||||
- goimports
|
||||
- golint
|
||||
#- gomnd
|
||||
#- goprintffuncname
|
||||
#- gosec
|
||||
#- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- interfacer
|
||||
#- lll
|
||||
- maligned
|
||||
- megacheck
|
||||
#- misspell
|
||||
#- nakedret
|
||||
#- noctx
|
||||
#- nolintlint
|
||||
#- rowserrcheck
|
||||
#- scopelint
|
||||
#- staticcheck
|
||||
- structcheck
|
||||
#- stylecheck
|
||||
#- typecheck
|
||||
- unconvert
|
||||
#- unparam
|
||||
#- unused
|
||||
- varcheck
|
||||
#- whitespace
|
||||
fast: false
|
||||
3
src/cmd/linuxkit/vendor/github.com/spf13/cobra/.mailmap
generated
vendored
Normal file
3
src/cmd/linuxkit/vendor/github.com/spf13/cobra/.mailmap
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
Steve Francia <steve.francia@gmail.com>
|
||||
Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
|
||||
Fabiano Franz <ffranz@redhat.com> <contact@fabianofranz.com>
|
||||
37
src/cmd/linuxkit/vendor/github.com/spf13/cobra/CONDUCT.md
generated
vendored
Normal file
37
src/cmd/linuxkit/vendor/github.com/spf13/cobra/CONDUCT.md
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
## Cobra User Contract
|
||||
|
||||
### Versioning
|
||||
Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release.
|
||||
|
||||
### Backward Compatibility
|
||||
We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released.
|
||||
|
||||
### Deprecation
|
||||
Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github.
|
||||
|
||||
### CVE
|
||||
Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one.
|
||||
|
||||
### Communication
|
||||
Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors.
|
||||
|
||||
### Breaking Changes
|
||||
Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra.
|
||||
|
||||
There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version.
|
||||
|
||||
Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release.
|
||||
|
||||
Examples of breaking changes include:
|
||||
- Removing or renaming exported constant, variable, type, or function.
|
||||
- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc...
|
||||
- Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing.
|
||||
|
||||
There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging.
|
||||
|
||||
### CI Testing
|
||||
Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang.
|
||||
|
||||
### Disclaimer
|
||||
Changes to this document and the contents therein are at the discretion of the maintainers.
|
||||
None of the contents of this document are legally binding in any way to the maintainers or the users.
|
||||
50
src/cmd/linuxkit/vendor/github.com/spf13/cobra/CONTRIBUTING.md
generated
vendored
Normal file
50
src/cmd/linuxkit/vendor/github.com/spf13/cobra/CONTRIBUTING.md
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
# Contributing to Cobra
|
||||
|
||||
Thank you so much for contributing to Cobra. We appreciate your time and help.
|
||||
Here are some guidelines to help you get started.
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
Be kind and respectful to the members of the community. Take time to educate
|
||||
others who are seeking help. Harassment of any kind will not be tolerated.
|
||||
|
||||
## Questions
|
||||
|
||||
If you have questions regarding Cobra, feel free to ask it in the community
|
||||
[#cobra Slack channel][cobra-slack]
|
||||
|
||||
## Filing a bug or feature
|
||||
|
||||
1. Before filing an issue, please check the existing issues to see if a
|
||||
similar one was already opened. If there is one already opened, feel free
|
||||
to comment on it.
|
||||
1. If you believe you've found a bug, please provide detailed steps of
|
||||
reproduction, the version of Cobra and anything else you believe will be
|
||||
useful to help troubleshoot it (e.g. OS environment, environment variables,
|
||||
etc...). Also state the current behavior vs. the expected behavior.
|
||||
1. If you'd like to see a feature or an enhancement please open an issue with
|
||||
a clear title and description of what the feature is and why it would be
|
||||
beneficial to the project and its users.
|
||||
|
||||
## Submitting changes
|
||||
|
||||
1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to
|
||||
sign a CLA. Please sign the CLA :slightly_smiling_face:
|
||||
1. Tests: If you are submitting code, please ensure you have adequate tests
|
||||
for the feature. Tests can be run via `go test ./...` or `make test`.
|
||||
1. Since this is golang project, ensure the new code is properly formatted to
|
||||
ensure code consistency. Run `make all`.
|
||||
|
||||
### Quick steps to contribute
|
||||
|
||||
1. Fork the project.
|
||||
1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
|
||||
1. Create your feature branch (`git checkout -b my-new-feature`)
|
||||
1. Make changes and run tests (`make test`)
|
||||
1. Add them to staging (`git add .`)
|
||||
1. Commit your changes (`git commit -m 'Add some feature'`)
|
||||
1. Push to the branch (`git push origin my-new-feature`)
|
||||
1. Create new pull request
|
||||
|
||||
<!-- Links -->
|
||||
[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199
|
||||
174
src/cmd/linuxkit/vendor/github.com/spf13/cobra/LICENSE.txt
generated
vendored
Normal file
174
src/cmd/linuxkit/vendor/github.com/spf13/cobra/LICENSE.txt
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
13
src/cmd/linuxkit/vendor/github.com/spf13/cobra/MAINTAINERS
generated
vendored
Normal file
13
src/cmd/linuxkit/vendor/github.com/spf13/cobra/MAINTAINERS
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
maintainers:
|
||||
- spf13
|
||||
- johnSchnake
|
||||
- jpmcb
|
||||
- marckhouzam
|
||||
inactive:
|
||||
- anthonyfok
|
||||
- bep
|
||||
- bogem
|
||||
- broady
|
||||
- eparis
|
||||
- jharshman
|
||||
- wfernandes
|
||||
35
src/cmd/linuxkit/vendor/github.com/spf13/cobra/Makefile
generated
vendored
Normal file
35
src/cmd/linuxkit/vendor/github.com/spf13/cobra/Makefile
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
BIN="./bin"
|
||||
SRC=$(shell find . -name "*.go")
|
||||
|
||||
ifeq (, $(shell which golangci-lint))
|
||||
$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh")
|
||||
endif
|
||||
|
||||
ifeq (, $(shell which richgo))
|
||||
$(warning "could not find richgo in $(PATH), run: go install github.com/kyoh86/richgo@latest")
|
||||
endif
|
||||
|
||||
.PHONY: fmt lint test install_deps clean
|
||||
|
||||
default: all
|
||||
|
||||
all: fmt test
|
||||
|
||||
fmt:
|
||||
$(info ******************** checking formatting ********************)
|
||||
@test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)
|
||||
|
||||
lint:
|
||||
$(info ******************** running lint tools ********************)
|
||||
golangci-lint run -v
|
||||
|
||||
test: install_deps
|
||||
$(info ******************** running tests ********************)
|
||||
richgo test -v ./...
|
||||
|
||||
install_deps:
|
||||
$(info ******************** downloading dependencies ********************)
|
||||
go get -v ./...
|
||||
|
||||
clean:
|
||||
rm -rf $(BIN)
|
||||
112
src/cmd/linuxkit/vendor/github.com/spf13/cobra/README.md
generated
vendored
Normal file
112
src/cmd/linuxkit/vendor/github.com/spf13/cobra/README.md
generated
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||

|
||||
|
||||
Cobra is a library for creating powerful modern CLI applications.
|
||||
|
||||
Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),
|
||||
[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
|
||||
name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
|
||||
|
||||
[](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
|
||||
[](https://pkg.go.dev/github.com/spf13/cobra)
|
||||
[](https://goreportcard.com/report/github.com/spf13/cobra)
|
||||
[](https://gophers.slack.com/archives/CD3LP1199)
|
||||
|
||||
# Overview
|
||||
|
||||
Cobra is a library providing a simple interface to create powerful modern CLI
|
||||
interfaces similar to git & go tools.
|
||||
|
||||
Cobra provides:
|
||||
* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
|
||||
* Fully POSIX-compliant flags (including short & long versions)
|
||||
* Nested subcommands
|
||||
* Global, local and cascading flags
|
||||
* Intelligent suggestions (`app srver`... did you mean `app server`?)
|
||||
* Automatic help generation for commands and flags
|
||||
* Grouping help for subcommands
|
||||
* Automatic help flag recognition of `-h`, `--help`, etc.
|
||||
* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
|
||||
* Automatically generated man pages for your application
|
||||
* Command aliases so you can change things without breaking them
|
||||
* The flexibility to define your own help, usage, etc.
|
||||
* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps
|
||||
|
||||
# Concepts
|
||||
|
||||
Cobra is built on a structure of commands, arguments & flags.
|
||||
|
||||
**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
|
||||
|
||||
The best applications read like sentences when used, and as a result, users
|
||||
intuitively know how to interact with them.
|
||||
|
||||
The pattern to follow is
|
||||
`APPNAME VERB NOUN --ADJECTIVE`
|
||||
or
|
||||
`APPNAME COMMAND ARG --FLAG`.
|
||||
|
||||
A few good real world examples may better illustrate this point.
|
||||
|
||||
In the following example, 'server' is a command, and 'port' is a flag:
|
||||
|
||||
hugo server --port=1313
|
||||
|
||||
In this command we are telling Git to clone the url bare.
|
||||
|
||||
git clone URL --bare
|
||||
|
||||
## Commands
|
||||
|
||||
Command is the central point of the application. Each interaction that
|
||||
the application supports will be contained in a Command. A command can
|
||||
have children commands and optionally run an action.
|
||||
|
||||
In the example above, 'server' is the command.
|
||||
|
||||
[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command)
|
||||
|
||||
## Flags
|
||||
|
||||
A flag is a way to modify the behavior of a command. Cobra supports
|
||||
fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
|
||||
A Cobra command can define flags that persist through to children commands
|
||||
and flags that are only available to that command.
|
||||
|
||||
In the example above, 'port' is the flag.
|
||||
|
||||
Flag functionality is provided by the [pflag
|
||||
library](https://github.com/spf13/pflag), a fork of the flag standard library
|
||||
which maintains the same interface while adding POSIX compliance.
|
||||
|
||||
# Installing
|
||||
Using Cobra is easy. First, use `go get` to install the latest version
|
||||
of the library.
|
||||
|
||||
```
|
||||
go get -u github.com/spf13/cobra@latest
|
||||
```
|
||||
|
||||
Next, include Cobra in your application:
|
||||
|
||||
```go
|
||||
import "github.com/spf13/cobra"
|
||||
```
|
||||
|
||||
# Usage
|
||||
`cobra-cli` is a command line program to generate cobra applications and command files.
|
||||
It will bootstrap your application scaffolding to rapidly
|
||||
develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.
|
||||
|
||||
It can be installed by running:
|
||||
|
||||
```
|
||||
go install github.com/spf13/cobra-cli@latest
|
||||
```
|
||||
|
||||
For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
|
||||
|
||||
For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).
|
||||
|
||||
# License
|
||||
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
|
||||
63
src/cmd/linuxkit/vendor/github.com/spf13/cobra/active_help.go
generated
vendored
Normal file
63
src/cmd/linuxkit/vendor/github.com/spf13/cobra/active_help.go
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
activeHelpMarker = "_activeHelp_ "
|
||||
// The below values should not be changed: programs will be using them explicitly
|
||||
// in their user documentation, and users will be using them explicitly.
|
||||
activeHelpEnvVarSuffix = "_ACTIVE_HELP"
|
||||
activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP"
|
||||
activeHelpGlobalDisable = "0"
|
||||
)
|
||||
|
||||
// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.
|
||||
// Such strings will be processed by the completion script and will be shown as ActiveHelp
|
||||
// to the user.
|
||||
// The array parameter should be the array that will contain the completions.
|
||||
// This function can be called multiple times before and/or after completions are added to
|
||||
// the array. Each time this function is called with the same array, the new
|
||||
// ActiveHelp line will be shown below the previous ones when completion is triggered.
|
||||
func AppendActiveHelp(compArray []string, activeHelpStr string) []string {
|
||||
return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))
|
||||
}
|
||||
|
||||
// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
|
||||
// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper
|
||||
// case, with all - replaced by _.
|
||||
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
|
||||
// is set to "0".
|
||||
func GetActiveHelpConfig(cmd *Command) string {
|
||||
activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar)
|
||||
if activeHelpCfg != activeHelpGlobalDisable {
|
||||
activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name()))
|
||||
}
|
||||
return activeHelpCfg
|
||||
}
|
||||
|
||||
// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment
|
||||
// variable. It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the
|
||||
// root command in upper case, with all - replaced by _.
|
||||
func activeHelpEnvVar(name string) string {
|
||||
// This format should not be changed: users will be using it explicitly.
|
||||
activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix))
|
||||
return strings.ReplaceAll(activeHelpEnvVar, "-", "_")
|
||||
}
|
||||
157
src/cmd/linuxkit/vendor/github.com/spf13/cobra/active_help.md
generated
vendored
Normal file
157
src/cmd/linuxkit/vendor/github.com/spf13/cobra/active_help.md
generated
vendored
Normal file
@@ -0,0 +1,157 @@
|
||||
# Active Help
|
||||
|
||||
Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion.
|
||||
|
||||
For example,
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding.
|
||||
|
||||
bash-5.1$ bin/helm package [tab]
|
||||
Please specify the path to the chart to package
|
||||
|
||||
bash-5.1$ bin/helm package [tab][tab]
|
||||
bin/ internal/ scripts/ pkg/ testdata/
|
||||
```
|
||||
|
||||
**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program.
|
||||
## Supported shells
|
||||
|
||||
Active Help is currently only supported for the following shells:
|
||||
- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.
|
||||
- Zsh
|
||||
|
||||
## Adding Active Help messages
|
||||
|
||||
As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md).
|
||||
|
||||
Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details.
|
||||
|
||||
### Active Help for nouns
|
||||
|
||||
Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example:
|
||||
|
||||
```go
|
||||
cmd := &cobra.Command{
|
||||
Use: "add [NAME] [URL]",
|
||||
Short: "add a chart repository",
|
||||
Args: require.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return addRepo(args)
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
var comps []string
|
||||
if len(args) == 0 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
} else if len(args) == 1 {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
|
||||
} else {
|
||||
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
|
||||
}
|
||||
return comps, cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
```
|
||||
The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior:
|
||||
```
|
||||
bash-5.1$ helm repo add [tab]
|
||||
You must choose a name for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana [tab]
|
||||
You must specify the URL for the repo you are adding
|
||||
|
||||
bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab]
|
||||
This command does not take any more arguments
|
||||
```
|
||||
**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions.
|
||||
|
||||
### Active Help for flags
|
||||
|
||||
Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example:
|
||||
```go
|
||||
_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) != 2 {
|
||||
return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
return compVersionFlag(args[1], toComplete)
|
||||
})
|
||||
```
|
||||
The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.
|
||||
```
|
||||
bash-5.1$ bin/helm install myrelease --version 2.0.[tab]
|
||||
You must first specify the chart to install before the --version flag can be completed
|
||||
|
||||
bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]
|
||||
2.0.1 2.0.2 2.0.3
|
||||
```
|
||||
|
||||
## User control of Active Help
|
||||
|
||||
You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any.
|
||||
Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.
|
||||
|
||||
The way to configure Active Help is to use the program's Active Help environment
|
||||
variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your
|
||||
program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever
|
||||
Active Help configuration values are supported by the program.
|
||||
|
||||
For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user
|
||||
would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.
|
||||
|
||||
For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the
|
||||
Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages
|
||||
should or should not be added (instead of reading the environment variable directly).
|
||||
|
||||
For example:
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
activeHelpLevel := cobra.GetActiveHelpConfig(cmd)
|
||||
|
||||
var comps []string
|
||||
if len(args) == 0 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding")
|
||||
}
|
||||
} else if len(args) == 1 {
|
||||
if activeHelpLevel != "off" {
|
||||
comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding")
|
||||
}
|
||||
} else {
|
||||
if activeHelpLevel == "local" {
|
||||
comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments")
|
||||
}
|
||||
}
|
||||
return comps, cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
```
|
||||
**Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly.
|
||||
|
||||
**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to.
|
||||
|
||||
**Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string.
|
||||
## Active Help with Cobra's default completion command
|
||||
|
||||
Cobra provides a default `completion` command for programs that wish to use it.
|
||||
When using the default `completion` command, Active Help is configurable in the same
|
||||
fashion as described above using environment variables. You may wish to document this in more
|
||||
details for your users.
|
||||
|
||||
## Debugging Active Help
|
||||
|
||||
Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details.
|
||||
|
||||
When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `<PROGRAM>_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below:
|
||||
```
|
||||
$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
_activeHelp_ WARNING: cannot re-use a name that is still in use
|
||||
:0
|
||||
Completion ended with directive: ShellCompDirectiveDefault
|
||||
|
||||
$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>
|
||||
bitnami/haproxy
|
||||
bitnami/harbor
|
||||
:0
|
||||
Completion ended with directive: ShellCompDirectiveDefault
|
||||
```
|
||||
131
src/cmd/linuxkit/vendor/github.com/spf13/cobra/args.go
generated
vendored
Normal file
131
src/cmd/linuxkit/vendor/github.com/spf13/cobra/args.go
generated
vendored
Normal file
@@ -0,0 +1,131 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PositionalArgs func(cmd *Command, args []string) error
|
||||
|
||||
// Legacy arg validation has the following behaviour:
|
||||
// - root commands with no subcommands can take arbitrary arguments
|
||||
// - root commands with subcommands will do subcommand validity checking
|
||||
// - subcommands will always accept arbitrary arguments
|
||||
func legacyArgs(cmd *Command, args []string) error {
|
||||
// no subcommand, always take args
|
||||
if !cmd.HasSubCommands() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// root command with subcommands, do subcommand checking.
|
||||
if !cmd.HasParent() && len(args) > 0 {
|
||||
return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NoArgs returns an error if any args are included.
|
||||
func NoArgs(cmd *Command, args []string) error {
|
||||
if len(args) > 0 {
|
||||
return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OnlyValidArgs returns an error if there are any positional args that are not in
|
||||
// the `ValidArgs` field of `Command`
|
||||
func OnlyValidArgs(cmd *Command, args []string) error {
|
||||
if len(cmd.ValidArgs) > 0 {
|
||||
// Remove any description that may be included in ValidArgs.
|
||||
// A description is following a tab character.
|
||||
var validArgs []string
|
||||
for _, v := range cmd.ValidArgs {
|
||||
validArgs = append(validArgs, strings.Split(v, "\t")[0])
|
||||
}
|
||||
for _, v := range args {
|
||||
if !stringInSlice(v, validArgs) {
|
||||
return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ArbitraryArgs never returns an error.
|
||||
func ArbitraryArgs(cmd *Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MinimumNArgs returns an error if there is not at least N args.
|
||||
func MinimumNArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) < n {
|
||||
return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MaximumNArgs returns an error if there are more than N args.
|
||||
func MaximumNArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) > n {
|
||||
return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExactArgs returns an error if there are not exactly n args.
|
||||
func ExactArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) != n {
|
||||
return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// RangeArgs returns an error if the number of args is not within the expected range.
|
||||
func RangeArgs(min int, max int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) < min || len(args) > max {
|
||||
return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MatchAll allows combining several PositionalArgs to work in concert.
|
||||
func MatchAll(pargs ...PositionalArgs) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
for _, parg := range pargs {
|
||||
if err := parg(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExactValidArgs returns an error if there are not exactly N positional args OR
|
||||
// there are any positional args that are not in the `ValidArgs` field of `Command`
|
||||
//
|
||||
// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead
|
||||
func ExactValidArgs(n int) PositionalArgs {
|
||||
return MatchAll(ExactArgs(n), OnlyValidArgs)
|
||||
}
|
||||
712
src/cmd/linuxkit/vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
Normal file
712
src/cmd/linuxkit/vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
Normal file
@@ -0,0 +1,712 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Annotations for Bash completion.
|
||||
const (
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
|
||||
BashCompCustom = "cobra_annotation_bash_completion_custom"
|
||||
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
|
||||
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
|
||||
)
|
||||
|
||||
func writePreamble(buf io.StringWriter, name string) {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`
|
||||
__%[1]s_debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
|
||||
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
|
||||
fi
|
||||
}
|
||||
|
||||
# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
|
||||
# _init_completion. This is a very minimal version of that function.
|
||||
__%[1]s_init_completion()
|
||||
{
|
||||
COMPREPLY=()
|
||||
_get_comp_words_by_ref "$@" cur prev words cword
|
||||
}
|
||||
|
||||
__%[1]s_index_of_word()
|
||||
{
|
||||
local w word=$1
|
||||
shift
|
||||
index=0
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
index=$((index+1))
|
||||
done
|
||||
index=-1
|
||||
}
|
||||
|
||||
__%[1]s_contains_word()
|
||||
{
|
||||
local w word=$1; shift
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
__%[1]s_handle_go_custom_completion()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"
|
||||
|
||||
local shellCompDirectiveError=%[3]d
|
||||
local shellCompDirectiveNoSpace=%[4]d
|
||||
local shellCompDirectiveNoFileComp=%[5]d
|
||||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
|
||||
local out requestComp lastParam lastChar comp directive args
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
args=("${words[@]:1}")
|
||||
# Disable ActiveHelp which is not supported for bash completion v1
|
||||
requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"
|
||||
|
||||
lastParam=${words[$((${#words[@]}-1))]}
|
||||
lastChar=${lastParam:$((${#lastParam}-1)):1}
|
||||
__%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"
|
||||
|
||||
if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
|
||||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go method.
|
||||
__%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter"
|
||||
requestComp="${requestComp} \"\""
|
||||
fi
|
||||
|
||||
__%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"
|
||||
# Use eval to handle any environment variables and such
|
||||
out=$(eval "${requestComp}" 2>/dev/null)
|
||||
|
||||
# Extract the directive integer at the very end of the output following a colon (:)
|
||||
directive=${out##*:}
|
||||
# Remove the directive
|
||||
out=${out%%:*}
|
||||
if [ "${directive}" = "${out}" ]; then
|
||||
# There is not directive specified
|
||||
directive=0
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}"
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
|
||||
# Error code. No completion.
|
||||
__%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"
|
||||
return
|
||||
else
|
||||
if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
__%[1]s_debug "${FUNCNAME[0]}: activating no space"
|
||||
compopt -o nospace
|
||||
fi
|
||||
fi
|
||||
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
__%[1]s_debug "${FUNCNAME[0]}: activating no file completion"
|
||||
compopt +o default
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local fullFilter filter filteringCmd
|
||||
# Do not use quotes around the $out variable or else newline
|
||||
# characters will be kept.
|
||||
for filter in ${out}; do
|
||||
fullFilter+="$filter|"
|
||||
done
|
||||
|
||||
filteringCmd="_filedir $fullFilter"
|
||||
__%[1]s_debug "File filtering command: $filteringCmd"
|
||||
$filteringCmd
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
|
||||
# File completion for directories only
|
||||
local subdir
|
||||
# Use printf to strip any trailing newline
|
||||
subdir=$(printf "%%s" "${out}")
|
||||
if [ -n "$subdir" ]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
__%[1]s_handle_subdirs_in_dir_flag "$subdir"
|
||||
else
|
||||
__%[1]s_debug "Listing directories in ."
|
||||
_filedir -d
|
||||
fi
|
||||
else
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${out}" -- "$cur")
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_handle_reply()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}"
|
||||
local comp
|
||||
case $cur in
|
||||
-*)
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
compopt -o nospace
|
||||
fi
|
||||
local allflags
|
||||
if [ ${#must_have_one_flag[@]} -ne 0 ]; then
|
||||
allflags=("${must_have_one_flag[@]}")
|
||||
else
|
||||
allflags=("${flags[*]} ${two_word_flags[*]}")
|
||||
fi
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${allflags[*]}" -- "$cur")
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
[[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
|
||||
fi
|
||||
|
||||
# complete after --flag=abc
|
||||
if [[ $cur == *=* ]]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
compopt +o nospace
|
||||
fi
|
||||
|
||||
local index flag
|
||||
flag="${cur%%=*}"
|
||||
__%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"
|
||||
COMPREPLY=()
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
PREFIX=""
|
||||
cur="${cur#*=}"
|
||||
${flags_completion[${index}]}
|
||||
if [ -n "${ZSH_VERSION:-}" ]; then
|
||||
# zsh completion needs --flag= prefix
|
||||
eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "${flag_parsing_disabled}" ]]; then
|
||||
# If flag parsing is enabled, we have completed the flags and can return.
|
||||
# If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough
|
||||
# to possibly call handle_go_custom_completion.
|
||||
return 0;
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
# check if we are handling a flag with special work handling
|
||||
local index
|
||||
__%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
${flags_completion[${index}]}
|
||||
return
|
||||
fi
|
||||
|
||||
# we are parsing a flag and don't have a special handler, no completion
|
||||
if [[ ${cur} != "${words[cword]}" ]]; then
|
||||
return
|
||||
fi
|
||||
|
||||
local completions
|
||||
completions=("${commands[@]}")
|
||||
if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
completions+=("${must_have_one_noun[@]}")
|
||||
elif [[ -n "${has_completion_function}" ]]; then
|
||||
# if a go completion function is provided, defer to that function
|
||||
__%[1]s_handle_go_custom_completion
|
||||
fi
|
||||
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
|
||||
completions+=("${must_have_one_flag[@]}")
|
||||
fi
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${completions[*]}" -- "$cur")
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${noun_aliases[*]}" -- "$cur")
|
||||
fi
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
|
||||
if declare -F __%[1]s_custom_func >/dev/null; then
|
||||
# try command name qualified custom func
|
||||
__%[1]s_custom_func
|
||||
else
|
||||
# otherwise fall back to unqualified for compatibility
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
fi
|
||||
|
||||
# available in bash-completion >= 2, not always present on macOS
|
||||
if declare -F __ltrim_colon_completions >/dev/null; then
|
||||
__ltrim_colon_completions "$cur"
|
||||
fi
|
||||
|
||||
# If there is only 1 completion and it is a flag with an = it will be completed
|
||||
# but we don't want a space after the =
|
||||
if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then
|
||||
compopt -o nospace
|
||||
fi
|
||||
}
|
||||
|
||||
# The arguments should be in the form "ext1|ext2|extn"
|
||||
__%[1]s_handle_filename_extension_flag()
|
||||
{
|
||||
local ext="$1"
|
||||
_filedir "@(${ext})"
|
||||
}
|
||||
|
||||
__%[1]s_handle_subdirs_in_dir_flag()
|
||||
{
|
||||
local dir="$1"
|
||||
pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
|
||||
}
|
||||
|
||||
__%[1]s_handle_flag()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
# if a command required a flag, and we found it, unset must_have_one_flag()
|
||||
local flagname=${words[c]}
|
||||
local flagvalue=""
|
||||
# if the word contained an =
|
||||
if [[ ${words[c]} == *"="* ]]; then
|
||||
flagvalue=${flagname#*=} # take in as flagvalue after the =
|
||||
flagname=${flagname%%=*} # strip everything after the =
|
||||
flagname="${flagname}=" # but put the = back
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"
|
||||
if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then
|
||||
must_have_one_flag=()
|
||||
fi
|
||||
|
||||
# if you set a flag which only applies to this command, don't show subcommands
|
||||
if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
|
||||
commands=()
|
||||
fi
|
||||
|
||||
# keep flag value with flagname as flaghash
|
||||
# flaghash variable is an associative array which is only supported in bash > 3.
|
||||
if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then
|
||||
if [ -n "${flagvalue}" ] ; then
|
||||
flaghash[${flagname}]=${flagvalue}
|
||||
elif [ -n "${words[ $((c+1)) ]}" ] ; then
|
||||
flaghash[${flagname}]=${words[ $((c+1)) ]}
|
||||
else
|
||||
flaghash[${flagname}]="true" # pad "true" for bool flag
|
||||
fi
|
||||
fi
|
||||
|
||||
# skip the argument to a two word flag
|
||||
if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then
|
||||
__%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"
|
||||
c=$((c+1))
|
||||
# if we are looking for a flags value, don't show commands
|
||||
if [[ $c -eq $cword ]]; then
|
||||
commands=()
|
||||
fi
|
||||
fi
|
||||
|
||||
c=$((c+1))
|
||||
|
||||
}
|
||||
|
||||
__%[1]s_handle_noun()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
|
||||
must_have_one_noun=()
|
||||
elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then
|
||||
must_have_one_noun=()
|
||||
fi
|
||||
|
||||
nouns+=("${words[c]}")
|
||||
c=$((c+1))
|
||||
}
|
||||
|
||||
__%[1]s_handle_command()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
local next_command
|
||||
if [[ -n ${last_command} ]]; then
|
||||
next_command="_${last_command}_${words[c]//:/__}"
|
||||
else
|
||||
if [[ $c -eq 0 ]]; then
|
||||
next_command="_%[1]s_root_command"
|
||||
else
|
||||
next_command="_${words[c]//:/__}"
|
||||
fi
|
||||
fi
|
||||
c=$((c+1))
|
||||
__%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"
|
||||
declare -F "$next_command" >/dev/null && $next_command
|
||||
}
|
||||
|
||||
__%[1]s_handle_word()
|
||||
{
|
||||
if [[ $c -ge $cword ]]; then
|
||||
__%[1]s_handle_reply
|
||||
return
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
if [[ "${words[c]}" == -* ]]; then
|
||||
__%[1]s_handle_flag
|
||||
elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then
|
||||
__%[1]s_handle_command
|
||||
elif [[ $c -eq 0 ]]; then
|
||||
__%[1]s_handle_command
|
||||
elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then
|
||||
# aliashash variable is an associative array which is only supported in bash > 3.
|
||||
if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then
|
||||
words[c]=${aliashash[${words[c]}]}
|
||||
__%[1]s_handle_command
|
||||
else
|
||||
__%[1]s_handle_noun
|
||||
fi
|
||||
else
|
||||
__%[1]s_handle_noun
|
||||
fi
|
||||
__%[1]s_handle_word
|
||||
}
|
||||
|
||||
`, name, ShellCompNoDescRequestCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
func writePostscript(buf io.StringWriter, name string) {
|
||||
name = strings.ReplaceAll(name, ":", "__")
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`{
|
||||
local cur prev words cword split
|
||||
declare -A flaghash 2>/dev/null || :
|
||||
declare -A aliashash 2>/dev/null || :
|
||||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
_init_completion -s || return
|
||||
else
|
||||
__%[1]s_init_completion -n "=" || return
|
||||
fi
|
||||
|
||||
local c=0
|
||||
local flag_parsing_disabled=
|
||||
local flags=()
|
||||
local two_word_flags=()
|
||||
local local_nonpersistent_flags=()
|
||||
local flags_with_completion=()
|
||||
local flags_completion=()
|
||||
local commands=("%[1]s")
|
||||
local command_aliases=()
|
||||
local must_have_one_flag=()
|
||||
local must_have_one_noun=()
|
||||
local has_completion_function=""
|
||||
local last_command=""
|
||||
local nouns=()
|
||||
local noun_aliases=()
|
||||
|
||||
__%[1]s_handle_word
|
||||
}
|
||||
|
||||
`, name))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
complete -o default -F __start_%s %s
|
||||
else
|
||||
complete -o default -o nospace -F __start_%s %s
|
||||
fi
|
||||
|
||||
`, name, name, name, name))
|
||||
WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n")
|
||||
}
|
||||
|
||||
func writeCommands(buf io.StringWriter, cmd *Command) {
|
||||
WriteStringAndCheck(buf, " commands=()\n")
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() && c != cmd.helpCommand {
|
||||
continue
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name()))
|
||||
writeCmdAliases(buf, c)
|
||||
}
|
||||
WriteStringAndCheck(buf, "\n")
|
||||
}
|
||||
|
||||
func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) {
|
||||
for key, value := range annotations {
|
||||
switch key {
|
||||
case BashCompFilenameExt:
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
|
||||
|
||||
var ext string
|
||||
if len(value) > 0 {
|
||||
ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")
|
||||
} else {
|
||||
ext = "_filedir"
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))
|
||||
case BashCompCustom:
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
|
||||
|
||||
if len(value) > 0 {
|
||||
handlers := strings.Join(value, "; ")
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
|
||||
} else {
|
||||
WriteStringAndCheck(buf, " flags_completion+=(:)\n")
|
||||
}
|
||||
case BashCompSubdirsInDir:
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
|
||||
|
||||
var ext string
|
||||
if len(value) == 1 {
|
||||
ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]
|
||||
} else {
|
||||
ext = "_filedir -d"
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cbn = "\")\n"
|
||||
|
||||
func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
|
||||
name := flag.Shorthand
|
||||
format := " "
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format += "two_word_"
|
||||
}
|
||||
format += "flags+=(\"-%s" + cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, name))
|
||||
writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)
|
||||
}
|
||||
|
||||
func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
|
||||
name := flag.Name
|
||||
format := " flags+=(\"--%s"
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format += "="
|
||||
}
|
||||
format += cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, name))
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format = " two_word_flags+=(\"--%s" + cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, name))
|
||||
}
|
||||
writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
|
||||
}
|
||||
|
||||
func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
|
||||
name := flag.Name
|
||||
format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, name))
|
||||
if len(flag.Shorthand) > 0 {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))
|
||||
}
|
||||
}
|
||||
|
||||
// Setup annotations for go completions for registered flags
|
||||
func prepareCustomAnnotationsForFlags(cmd *Command) {
|
||||
flagCompletionMutex.RLock()
|
||||
defer flagCompletionMutex.RUnlock()
|
||||
for flag := range flagCompletionFunctions {
|
||||
// Make sure the completion script calls the __*_go_custom_completion function for
|
||||
// every registered flag. We need to do this here (and not when the flag was registered
|
||||
// for completion) so that we can know the root command name for the prefix
|
||||
// of __<prefix>_go_custom_completion
|
||||
if flag.Annotations == nil {
|
||||
flag.Annotations = map[string][]string{}
|
||||
}
|
||||
flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}
|
||||
}
|
||||
}
|
||||
|
||||
func writeFlags(buf io.StringWriter, cmd *Command) {
|
||||
prepareCustomAnnotationsForFlags(cmd)
|
||||
WriteStringAndCheck(buf, ` flags=()
|
||||
two_word_flags=()
|
||||
local_nonpersistent_flags=()
|
||||
flags_with_completion=()
|
||||
flags_completion=()
|
||||
|
||||
`)
|
||||
|
||||
if cmd.DisableFlagParsing {
|
||||
WriteStringAndCheck(buf, " flag_parsing_disabled=1\n")
|
||||
}
|
||||
|
||||
localNonPersistentFlags := cmd.LocalNonPersistentFlags()
|
||||
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
writeFlag(buf, flag, cmd)
|
||||
if len(flag.Shorthand) > 0 {
|
||||
writeShortFlag(buf, flag, cmd)
|
||||
}
|
||||
// localNonPersistentFlags are used to stop the completion of subcommands when one is set
|
||||
// if TraverseChildren is true we should allow to complete subcommands
|
||||
if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren {
|
||||
writeLocalNonPersistentFlag(buf, flag)
|
||||
}
|
||||
})
|
||||
cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
writeFlag(buf, flag, cmd)
|
||||
if len(flag.Shorthand) > 0 {
|
||||
writeShortFlag(buf, flag, cmd)
|
||||
}
|
||||
})
|
||||
|
||||
WriteStringAndCheck(buf, "\n")
|
||||
}
|
||||
|
||||
func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
|
||||
WriteStringAndCheck(buf, " must_have_one_flag=()\n")
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
for key := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
if flag.Value.Type() != "bool" {
|
||||
format += "="
|
||||
}
|
||||
format += cbn
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))
|
||||
|
||||
if len(flag.Shorthand) > 0 {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
|
||||
WriteStringAndCheck(buf, " must_have_one_noun=()\n")
|
||||
sort.Strings(cmd.ValidArgs)
|
||||
for _, value := range cmd.ValidArgs {
|
||||
// Remove any description that may be included following a tab character.
|
||||
// Descriptions are not supported by bash completion.
|
||||
value = strings.Split(value, "\t")[0]
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
|
||||
}
|
||||
if cmd.ValidArgsFunction != nil {
|
||||
WriteStringAndCheck(buf, " has_completion_function=1\n")
|
||||
}
|
||||
}
|
||||
|
||||
func writeCmdAliases(buf io.StringWriter, cmd *Command) {
|
||||
if len(cmd.Aliases) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
sort.Strings(cmd.Aliases)
|
||||
|
||||
WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n"))
|
||||
for _, value := range cmd.Aliases {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
|
||||
}
|
||||
WriteStringAndCheck(buf, ` fi`)
|
||||
WriteStringAndCheck(buf, "\n")
|
||||
}
|
||||
func writeArgAliases(buf io.StringWriter, cmd *Command) {
|
||||
WriteStringAndCheck(buf, " noun_aliases=()\n")
|
||||
sort.Strings(cmd.ArgAliases)
|
||||
for _, value := range cmd.ArgAliases {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value))
|
||||
}
|
||||
}
|
||||
|
||||
func gen(buf io.StringWriter, cmd *Command) {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() && c != cmd.helpCommand {
|
||||
continue
|
||||
}
|
||||
gen(buf, c)
|
||||
}
|
||||
commandName := cmd.CommandPath()
|
||||
commandName = strings.ReplaceAll(commandName, " ", "_")
|
||||
commandName = strings.ReplaceAll(commandName, ":", "__")
|
||||
|
||||
if cmd.Root() == cmd {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))
|
||||
} else {
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName))
|
||||
}
|
||||
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName))
|
||||
WriteStringAndCheck(buf, "\n")
|
||||
WriteStringAndCheck(buf, " command_aliases=()\n")
|
||||
WriteStringAndCheck(buf, "\n")
|
||||
|
||||
writeCommands(buf, cmd)
|
||||
writeFlags(buf, cmd)
|
||||
writeRequiredFlag(buf, cmd)
|
||||
writeRequiredNouns(buf, cmd)
|
||||
writeArgAliases(buf, cmd)
|
||||
WriteStringAndCheck(buf, "}\n\n")
|
||||
}
|
||||
|
||||
// GenBashCompletion generates bash completion file and writes to the passed writer.
|
||||
func (c *Command) GenBashCompletion(w io.Writer) error {
|
||||
buf := new(bytes.Buffer)
|
||||
writePreamble(buf, c.Name())
|
||||
if len(c.BashCompletionFunction) > 0 {
|
||||
buf.WriteString(c.BashCompletionFunction + "\n")
|
||||
}
|
||||
gen(buf, c)
|
||||
writePostscript(buf, c.Name())
|
||||
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func nonCompletableFlag(flag *pflag.Flag) bool {
|
||||
return flag.Hidden || len(flag.Deprecated) > 0
|
||||
}
|
||||
|
||||
// GenBashCompletionFile generates bash completion file.
|
||||
func (c *Command) GenBashCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenBashCompletion(outFile)
|
||||
}
|
||||
93
src/cmd/linuxkit/vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
Normal file
93
src/cmd/linuxkit/vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
# Generating Bash Completions For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
||||
## Bash legacy dynamic completions
|
||||
|
||||
For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution.
|
||||
|
||||
**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own.
|
||||
|
||||
The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions.
|
||||
|
||||
Some code that works in kubernetes:
|
||||
|
||||
```bash
|
||||
const (
|
||||
bash_completion_func = `__kubectl_parse_get()
|
||||
{
|
||||
local kubectl_output out
|
||||
if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
|
||||
out=($(echo "${kubectl_output}" | awk '{print $1}'))
|
||||
COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_get_resource()
|
||||
{
|
||||
if [[ ${#nouns[@]} -eq 0 ]]; then
|
||||
return 1
|
||||
fi
|
||||
__kubectl_parse_get ${nouns[${#nouns[@]} -1]}
|
||||
if [[ $? -eq 0 ]]; then
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_custom_func() {
|
||||
case ${last_command} in
|
||||
kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
|
||||
__kubectl_get_resource
|
||||
return
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
}
|
||||
`)
|
||||
```
|
||||
|
||||
And then I set that in my command definition:
|
||||
|
||||
```go
|
||||
cmds := &cobra.Command{
|
||||
Use: "kubectl",
|
||||
Short: "kubectl controls the Kubernetes cluster manager",
|
||||
Long: `kubectl controls the Kubernetes cluster manager.
|
||||
|
||||
Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
|
||||
Run: runHelp,
|
||||
BashCompletionFunction: bash_completion_func,
|
||||
}
|
||||
```
|
||||
|
||||
The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`__<command-use>_custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
|
||||
|
||||
Similarly, for flags:
|
||||
|
||||
```go
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "namespace",
|
||||
Usage: usage,
|
||||
Annotations: annotation,
|
||||
}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`
|
||||
value, e.g.:
|
||||
|
||||
```bash
|
||||
__kubectl_get_namespaces()
|
||||
{
|
||||
local template
|
||||
template="{{ range .items }}{{ .metadata.name }} {{ end }}"
|
||||
local kubectl_out
|
||||
if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
|
||||
COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
```
|
||||
383
src/cmd/linuxkit/vendor/github.com/spf13/cobra/bash_completionsV2.go
generated
vendored
Normal file
383
src/cmd/linuxkit/vendor/github.com/spf13/cobra/bash_completionsV2.go
generated
vendored
Normal file
@@ -0,0 +1,383 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {
|
||||
buf := new(bytes.Buffer)
|
||||
genBashComp(buf, c.Name(), includeDesc)
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*-
|
||||
|
||||
__%[1]s_debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
|
||||
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
|
||||
fi
|
||||
}
|
||||
|
||||
# Macs have bash3 for which the bash-completion package doesn't include
|
||||
# _init_completion. This is a minimal version of that function.
|
||||
__%[1]s_init_completion()
|
||||
{
|
||||
COMPREPLY=()
|
||||
_get_comp_words_by_ref "$@" cur prev words cword
|
||||
}
|
||||
|
||||
# This function calls the %[1]s program to obtain the completion
|
||||
# results and the directive. It fills the 'out' and 'directive' vars.
|
||||
__%[1]s_get_completion_results() {
|
||||
local requestComp lastParam lastChar args
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
args=("${words[@]:1}")
|
||||
requestComp="${words[0]} %[2]s ${args[*]}"
|
||||
|
||||
lastParam=${words[$((${#words[@]}-1))]}
|
||||
lastChar=${lastParam:$((${#lastParam}-1)):1}
|
||||
__%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}"
|
||||
|
||||
if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
|
||||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go method.
|
||||
__%[1]s_debug "Adding extra empty parameter"
|
||||
requestComp="${requestComp} ''"
|
||||
fi
|
||||
|
||||
# When completing a flag with an = (e.g., %[1]s -n=<TAB>)
|
||||
# bash focuses on the part after the =, so we need to remove
|
||||
# the flag part from $cur
|
||||
if [[ "${cur}" == -*=* ]]; then
|
||||
cur="${cur#*=}"
|
||||
fi
|
||||
|
||||
__%[1]s_debug "Calling ${requestComp}"
|
||||
# Use eval to handle any environment variables and such
|
||||
out=$(eval "${requestComp}" 2>/dev/null)
|
||||
|
||||
# Extract the directive integer at the very end of the output following a colon (:)
|
||||
directive=${out##*:}
|
||||
# Remove the directive
|
||||
out=${out%%:*}
|
||||
if [ "${directive}" = "${out}" ]; then
|
||||
# There is not directive specified
|
||||
directive=0
|
||||
fi
|
||||
__%[1]s_debug "The completion directive is: ${directive}"
|
||||
__%[1]s_debug "The completions are: ${out}"
|
||||
}
|
||||
|
||||
__%[1]s_process_completion_results() {
|
||||
local shellCompDirectiveError=%[3]d
|
||||
local shellCompDirectiveNoSpace=%[4]d
|
||||
local shellCompDirectiveNoFileComp=%[5]d
|
||||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
|
||||
# Error code. No completion.
|
||||
__%[1]s_debug "Received error from custom completion go code"
|
||||
return
|
||||
else
|
||||
if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
__%[1]s_debug "Activating no space"
|
||||
compopt -o nospace
|
||||
else
|
||||
__%[1]s_debug "No space directive not supported in this version of bash"
|
||||
fi
|
||||
fi
|
||||
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
__%[1]s_debug "Activating no file completion"
|
||||
compopt +o default
|
||||
else
|
||||
__%[1]s_debug "No file completion directive not supported in this version of bash"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Separate activeHelp from normal completions
|
||||
local completions=()
|
||||
local activeHelp=()
|
||||
__%[1]s_extract_activeHelp
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local fullFilter filter filteringCmd
|
||||
|
||||
# Do not use quotes around the $completions variable or else newline
|
||||
# characters will be kept.
|
||||
for filter in ${completions[*]}; do
|
||||
fullFilter+="$filter|"
|
||||
done
|
||||
|
||||
filteringCmd="_filedir $fullFilter"
|
||||
__%[1]s_debug "File filtering command: $filteringCmd"
|
||||
$filteringCmd
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
|
||||
# File completion for directories only
|
||||
|
||||
# Use printf to strip any trailing newline
|
||||
local subdir
|
||||
subdir=$(printf "%%s" "${completions[0]}")
|
||||
if [ -n "$subdir" ]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
|
||||
else
|
||||
__%[1]s_debug "Listing directories in ."
|
||||
_filedir -d
|
||||
fi
|
||||
else
|
||||
__%[1]s_handle_completion_types
|
||||
fi
|
||||
|
||||
__%[1]s_handle_special_char "$cur" :
|
||||
__%[1]s_handle_special_char "$cur" =
|
||||
|
||||
# Print the activeHelp statements before we finish
|
||||
if [ ${#activeHelp[*]} -ne 0 ]; then
|
||||
printf "\n";
|
||||
printf "%%s\n" "${activeHelp[@]}"
|
||||
printf "\n"
|
||||
|
||||
# The prompt format is only available from bash 4.4.
|
||||
# We test if it is available before using it.
|
||||
if (x=${PS1@P}) 2> /dev/null; then
|
||||
printf "%%s" "${PS1@P}${COMP_LINE[@]}"
|
||||
else
|
||||
# Can't print the prompt. Just print the
|
||||
# text the user had typed, it is workable enough.
|
||||
printf "%%s" "${COMP_LINE[@]}"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# Separate activeHelp lines from real completions.
|
||||
# Fills the $activeHelp and $completions arrays.
|
||||
__%[1]s_extract_activeHelp() {
|
||||
local activeHelpMarker="%[8]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
|
||||
while IFS='' read -r comp; do
|
||||
if [ "${comp:0:endIndex}" = "$activeHelpMarker" ]; then
|
||||
comp=${comp:endIndex}
|
||||
__%[1]s_debug "ActiveHelp found: $comp"
|
||||
if [ -n "$comp" ]; then
|
||||
activeHelp+=("$comp")
|
||||
fi
|
||||
else
|
||||
# Not an activeHelp line but a normal completion
|
||||
completions+=("$comp")
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out}")
|
||||
}
|
||||
|
||||
__%[1]s_handle_completion_types() {
|
||||
__%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE"
|
||||
|
||||
case $COMP_TYPE in
|
||||
37|42)
|
||||
# Type: menu-complete/menu-complete-backward and insert-completions
|
||||
# If the user requested inserting one completion at a time, or all
|
||||
# completions at once on the command-line we must remove the descriptions.
|
||||
# https://github.com/spf13/cobra/issues/1508
|
||||
local tab=$'\t' comp
|
||||
while IFS='' read -r comp; do
|
||||
[[ -z $comp ]] && continue
|
||||
# Strip any description
|
||||
comp=${comp%%%%$tab*}
|
||||
# Only consider the completions that match
|
||||
if [[ $comp == "$cur"* ]]; then
|
||||
COMPREPLY+=("$comp")
|
||||
fi
|
||||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
;;
|
||||
|
||||
*)
|
||||
# Type: complete (normal completion)
|
||||
__%[1]s_handle_standard_completion_case
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
__%[1]s_handle_standard_completion_case() {
|
||||
local tab=$'\t' comp
|
||||
|
||||
# Short circuit to optimize if we don't have descriptions
|
||||
if [[ "${completions[*]}" != *$tab* ]]; then
|
||||
IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur")
|
||||
return 0
|
||||
fi
|
||||
|
||||
local longest=0
|
||||
local compline
|
||||
# Look for the longest completion so that we can format things nicely
|
||||
while IFS='' read -r compline; do
|
||||
[[ -z $compline ]] && continue
|
||||
# Strip any description before checking the length
|
||||
comp=${compline%%%%$tab*}
|
||||
# Only consider the completions that match
|
||||
[[ $comp == "$cur"* ]] || continue
|
||||
COMPREPLY+=("$compline")
|
||||
if ((${#comp}>longest)); then
|
||||
longest=${#comp}
|
||||
fi
|
||||
done < <(printf "%%s\n" "${completions[@]}")
|
||||
|
||||
# If there is a single completion left, remove the description text
|
||||
if [ ${#COMPREPLY[*]} -eq 1 ]; then
|
||||
__%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
|
||||
comp="${COMPREPLY[0]%%%%$tab*}"
|
||||
__%[1]s_debug "Removed description from single completion, which is now: ${comp}"
|
||||
COMPREPLY[0]=$comp
|
||||
else # Format the descriptions
|
||||
__%[1]s_format_comp_descriptions $longest
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_handle_special_char()
|
||||
{
|
||||
local comp="$1"
|
||||
local char=$2
|
||||
if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
|
||||
local word=${comp%%"${comp##*${char}}"}
|
||||
local idx=${#COMPREPLY[*]}
|
||||
while [[ $((--idx)) -ge 0 ]]; do
|
||||
COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"}
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_format_comp_descriptions()
|
||||
{
|
||||
local tab=$'\t'
|
||||
local comp desc maxdesclength
|
||||
local longest=$1
|
||||
|
||||
local i ci
|
||||
for ci in ${!COMPREPLY[*]}; do
|
||||
comp=${COMPREPLY[ci]}
|
||||
# Properly format the description string which follows a tab character if there is one
|
||||
if [[ "$comp" == *$tab* ]]; then
|
||||
__%[1]s_debug "Original comp: $comp"
|
||||
desc=${comp#*$tab}
|
||||
comp=${comp%%%%$tab*}
|
||||
|
||||
# $COLUMNS stores the current shell width.
|
||||
# Remove an extra 4 because we add 2 spaces and 2 parentheses.
|
||||
maxdesclength=$(( COLUMNS - longest - 4 ))
|
||||
|
||||
# Make sure we can fit a description of at least 8 characters
|
||||
# if we are to align the descriptions.
|
||||
if [[ $maxdesclength -gt 8 ]]; then
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
for ((i = ${#comp} ; i < longest ; i++)); do
|
||||
comp+=" "
|
||||
done
|
||||
else
|
||||
# Don't pad the descriptions so we can fit more text after the completion
|
||||
maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
|
||||
fi
|
||||
|
||||
# If there is enough space for any description text,
|
||||
# truncate the descriptions that are too long for the shell width
|
||||
if [ $maxdesclength -gt 0 ]; then
|
||||
if [ ${#desc} -gt $maxdesclength ]; then
|
||||
desc=${desc:0:$(( maxdesclength - 1 ))}
|
||||
desc+="…"
|
||||
fi
|
||||
comp+=" ($desc)"
|
||||
fi
|
||||
COMPREPLY[ci]=$comp
|
||||
__%[1]s_debug "Final comp: $comp"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
__start_%[1]s()
|
||||
{
|
||||
local cur prev words cword split
|
||||
|
||||
COMPREPLY=()
|
||||
|
||||
# Call _init_completion from the bash-completion package
|
||||
# to prepare the arguments properly
|
||||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
_init_completion -n "=:" || return
|
||||
else
|
||||
__%[1]s_init_completion -n "=:" || return
|
||||
fi
|
||||
|
||||
__%[1]s_debug
|
||||
__%[1]s_debug "========= starting completion logic =========="
|
||||
__%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"
|
||||
|
||||
# The user could have moved the cursor backwards on the command-line.
|
||||
# We need to trigger completion from the $cword location, so we need
|
||||
# to truncate the command-line ($words) up to the $cword location.
|
||||
words=("${words[@]:0:$cword+1}")
|
||||
__%[1]s_debug "Truncated words[*]: ${words[*]},"
|
||||
|
||||
local out directive
|
||||
__%[1]s_get_completion_results
|
||||
__%[1]s_process_completion_results
|
||||
}
|
||||
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
complete -o default -F __start_%[1]s %[1]s
|
||||
else
|
||||
complete -o default -o nospace -F __start_%[1]s %[1]s
|
||||
fi
|
||||
|
||||
# ex: ts=4 sw=4 et filetype=sh
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
|
||||
activeHelpMarker))
|
||||
}
|
||||
|
||||
// GenBashCompletionFileV2 generates Bash completion version 2.
|
||||
func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenBashCompletionV2(outFile, includeDesc)
|
||||
}
|
||||
|
||||
// GenBashCompletionV2 generates Bash completion file version 2
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {
|
||||
return c.genBashCompletion(w, includeDesc)
|
||||
}
|
||||
239
src/cmd/linuxkit/vendor/github.com/spf13/cobra/cobra.go
generated
vendored
Normal file
239
src/cmd/linuxkit/vendor/github.com/spf13/cobra/cobra.go
generated
vendored
Normal file
@@ -0,0 +1,239 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Commands similar to git, go tools and other modern CLI tools
|
||||
// inspired by go, go-Commander, gh and subcommand
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var templateFuncs = template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"trimRightSpace": trimRightSpace,
|
||||
"trimTrailingWhitespaces": trimRightSpace,
|
||||
"appendIfNotPresent": appendIfNotPresent,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
}
|
||||
|
||||
var initializers []func()
|
||||
var finalizers []func()
|
||||
|
||||
const (
|
||||
defaultPrefixMatching = false
|
||||
defaultCommandSorting = true
|
||||
defaultCaseInsensitive = false
|
||||
)
|
||||
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
var EnablePrefixMatching = defaultPrefixMatching
|
||||
|
||||
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
// To disable sorting, set it to false.
|
||||
var EnableCommandSorting = defaultCommandSorting
|
||||
|
||||
// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
|
||||
var EnableCaseInsensitive = defaultCaseInsensitive
|
||||
|
||||
// MousetrapHelpText enables an information splash screen on Windows
|
||||
// if the CLI is started from explorer.exe.
|
||||
// To disable the mousetrap, just set this variable to blank string ("").
|
||||
// Works only on Microsoft Windows.
|
||||
var MousetrapHelpText = `This is a command line tool.
|
||||
|
||||
You need to open cmd.exe and run it from there.
|
||||
`
|
||||
|
||||
// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows
|
||||
// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed.
|
||||
// To disable the mousetrap, just set MousetrapHelpText to blank string ("").
|
||||
// Works only on Microsoft Windows.
|
||||
var MousetrapDisplayDuration = 5 * time.Second
|
||||
|
||||
// AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
// template generation.
|
||||
func AddTemplateFunc(name string, tmplFunc interface{}) {
|
||||
templateFuncs[name] = tmplFunc
|
||||
}
|
||||
|
||||
// AddTemplateFuncs adds multiple template functions that are available to Usage and
|
||||
// Help template generation.
|
||||
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
|
||||
for k, v := range tmplFuncs {
|
||||
templateFuncs[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// OnInitialize sets the passed functions to be run when each command's
|
||||
// Execute method is called.
|
||||
func OnInitialize(y ...func()) {
|
||||
initializers = append(initializers, y...)
|
||||
}
|
||||
|
||||
// OnFinalize sets the passed functions to be run when each command's
|
||||
// Execute method is terminated.
|
||||
func OnFinalize(y ...func()) {
|
||||
finalizers = append(finalizers, y...)
|
||||
}
|
||||
|
||||
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
// ints and then compared.
|
||||
func Gt(a interface{}, b interface{}) bool {
|
||||
var left, right int64
|
||||
av := reflect.ValueOf(a)
|
||||
|
||||
switch av.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
left = int64(av.Len())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
left = av.Int()
|
||||
case reflect.String:
|
||||
left, _ = strconv.ParseInt(av.String(), 10, 64)
|
||||
}
|
||||
|
||||
bv := reflect.ValueOf(b)
|
||||
|
||||
switch bv.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
right = int64(bv.Len())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
right = bv.Int()
|
||||
case reflect.String:
|
||||
right, _ = strconv.ParseInt(bv.String(), 10, 64)
|
||||
}
|
||||
|
||||
return left > right
|
||||
}
|
||||
|
||||
// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
func Eq(a interface{}, b interface{}) bool {
|
||||
av := reflect.ValueOf(a)
|
||||
bv := reflect.ValueOf(b)
|
||||
|
||||
switch av.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
panic("Eq called on unsupported type")
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return av.Int() == bv.Int()
|
||||
case reflect.String:
|
||||
return av.String() == bv.String()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func trimRightSpace(s string) string {
|
||||
return strings.TrimRightFunc(s, unicode.IsSpace)
|
||||
}
|
||||
|
||||
// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
|
||||
func appendIfNotPresent(s, stringToAppend string) string {
|
||||
if strings.Contains(s, stringToAppend) {
|
||||
return s
|
||||
}
|
||||
return s + " " + stringToAppend
|
||||
}
|
||||
|
||||
// rpad adds padding to the right of a string.
|
||||
func rpad(s string, padding int) string {
|
||||
template := fmt.Sprintf("%%-%ds", padding)
|
||||
return fmt.Sprintf(template, s)
|
||||
}
|
||||
|
||||
// tmpl executes the given template text on data, writing the result to w.
|
||||
func tmpl(w io.Writer, text string, data interface{}) error {
|
||||
t := template.New("top")
|
||||
t.Funcs(templateFuncs)
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
}
|
||||
|
||||
// ld compares two strings and returns the levenshtein distance between them.
|
||||
func ld(s, t string, ignoreCase bool) int {
|
||||
if ignoreCase {
|
||||
s = strings.ToLower(s)
|
||||
t = strings.ToLower(t)
|
||||
}
|
||||
d := make([][]int, len(s)+1)
|
||||
for i := range d {
|
||||
d[i] = make([]int, len(t)+1)
|
||||
}
|
||||
for i := range d {
|
||||
d[i][0] = i
|
||||
}
|
||||
for j := range d[0] {
|
||||
d[0][j] = j
|
||||
}
|
||||
for j := 1; j <= len(t); j++ {
|
||||
for i := 1; i <= len(s); i++ {
|
||||
if s[i-1] == t[j-1] {
|
||||
d[i][j] = d[i-1][j-1]
|
||||
} else {
|
||||
min := d[i-1][j]
|
||||
if d[i][j-1] < min {
|
||||
min = d[i][j-1]
|
||||
}
|
||||
if d[i-1][j-1] < min {
|
||||
min = d[i-1][j-1]
|
||||
}
|
||||
d[i][j] = min + 1
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return d[len(s)][len(t)]
|
||||
}
|
||||
|
||||
func stringInSlice(a string, list []string) bool {
|
||||
for _, b := range list {
|
||||
if b == a {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.
|
||||
func CheckErr(msg interface{}) {
|
||||
if msg != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error:", msg)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.
|
||||
func WriteStringAndCheck(b io.StringWriter, s string) {
|
||||
_, err := b.WriteString(s)
|
||||
CheckErr(err)
|
||||
}
|
||||
1810
src/cmd/linuxkit/vendor/github.com/spf13/cobra/command.go
generated
vendored
Normal file
1810
src/cmd/linuxkit/vendor/github.com/spf13/cobra/command.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
20
src/cmd/linuxkit/vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
Normal file
20
src/cmd/linuxkit/vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package cobra
|
||||
|
||||
var preExecHookFn func(*Command)
|
||||
41
src/cmd/linuxkit/vendor/github.com/spf13/cobra/command_win.go
generated
vendored
Normal file
41
src/cmd/linuxkit/vendor/github.com/spf13/cobra/command_win.go
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/inconshreveable/mousetrap"
|
||||
)
|
||||
|
||||
var preExecHookFn = preExecHook
|
||||
|
||||
func preExecHook(c *Command) {
|
||||
if MousetrapHelpText != "" && mousetrap.StartedByExplorer() {
|
||||
c.Print(MousetrapHelpText)
|
||||
if MousetrapDisplayDuration > 0 {
|
||||
time.Sleep(MousetrapDisplayDuration)
|
||||
} else {
|
||||
c.Println("Press return to continue...")
|
||||
fmt.Scanln()
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
871
src/cmd/linuxkit/vendor/github.com/spf13/cobra/completions.go
generated
vendored
Normal file
871
src/cmd/linuxkit/vendor/github.com/spf13/cobra/completions.go
generated
vendored
Normal file
@@ -0,0 +1,871 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
// ShellCompRequestCmd is the name of the hidden command that is used to request
|
||||
// completion results from the program. It is used by the shell completion scripts.
|
||||
ShellCompRequestCmd = "__complete"
|
||||
// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request
|
||||
// completion results without their description. It is used by the shell completion scripts.
|
||||
ShellCompNoDescRequestCmd = "__completeNoDesc"
|
||||
)
|
||||
|
||||
// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.
|
||||
var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
|
||||
|
||||
// lock for reading and writing from flagCompletionFunctions
|
||||
var flagCompletionMutex = &sync.RWMutex{}
|
||||
|
||||
// ShellCompDirective is a bit map representing the different behaviors the shell
|
||||
// can be instructed to have once completions have been provided.
|
||||
type ShellCompDirective int
|
||||
|
||||
type flagCompError struct {
|
||||
subCommand string
|
||||
flagName string
|
||||
}
|
||||
|
||||
func (e *flagCompError) Error() string {
|
||||
return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'"
|
||||
}
|
||||
|
||||
const (
|
||||
// ShellCompDirectiveError indicates an error occurred and completions should be ignored.
|
||||
ShellCompDirectiveError ShellCompDirective = 1 << iota
|
||||
|
||||
// ShellCompDirectiveNoSpace indicates that the shell should not add a space
|
||||
// after the completion even if there is a single completion provided.
|
||||
ShellCompDirectiveNoSpace
|
||||
|
||||
// ShellCompDirectiveNoFileComp indicates that the shell should not provide
|
||||
// file completion even when no completion is provided.
|
||||
ShellCompDirectiveNoFileComp
|
||||
|
||||
// ShellCompDirectiveFilterFileExt indicates that the provided completions
|
||||
// should be used as file extension filters.
|
||||
// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()
|
||||
// is a shortcut to using this directive explicitly. The BashCompFilenameExt
|
||||
// annotation can also be used to obtain the same behavior for flags.
|
||||
ShellCompDirectiveFilterFileExt
|
||||
|
||||
// ShellCompDirectiveFilterDirs indicates that only directory names should
|
||||
// be provided in file completion. To request directory names within another
|
||||
// directory, the returned completions should specify the directory within
|
||||
// which to search. The BashCompSubdirsInDir annotation can be used to
|
||||
// obtain the same behavior but only for flags.
|
||||
ShellCompDirectiveFilterDirs
|
||||
|
||||
// ===========================================================================
|
||||
|
||||
// All directives using iota should be above this one.
|
||||
// For internal use.
|
||||
shellCompDirectiveMaxValue
|
||||
|
||||
// ShellCompDirectiveDefault indicates to let the shell perform its default
|
||||
// behavior after completions have been provided.
|
||||
// This one must be last to avoid messing up the iota count.
|
||||
ShellCompDirectiveDefault ShellCompDirective = 0
|
||||
)
|
||||
|
||||
const (
|
||||
// Constants for the completion command
|
||||
compCmdName = "completion"
|
||||
compCmdNoDescFlagName = "no-descriptions"
|
||||
compCmdNoDescFlagDesc = "disable completion descriptions"
|
||||
compCmdNoDescFlagDefault = false
|
||||
)
|
||||
|
||||
// CompletionOptions are the options to control shell completion
|
||||
type CompletionOptions struct {
|
||||
// DisableDefaultCmd prevents Cobra from creating a default 'completion' command
|
||||
DisableDefaultCmd bool
|
||||
// DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag
|
||||
// for shells that support completion descriptions
|
||||
DisableNoDescFlag bool
|
||||
// DisableDescriptions turns off all completion descriptions for shells
|
||||
// that support them
|
||||
DisableDescriptions bool
|
||||
// HiddenDefaultCmd makes the default 'completion' command hidden
|
||||
HiddenDefaultCmd bool
|
||||
}
|
||||
|
||||
// NoFileCompletions can be used to disable file completion for commands that should
|
||||
// not trigger file completions.
|
||||
func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
return nil, ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
||||
// FixedCompletions can be used to create a completion function which always
|
||||
// returns the same results.
|
||||
func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
||||
return choices, directive
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
|
||||
func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
|
||||
flag := c.Flag(flagName)
|
||||
if flag == nil {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
|
||||
}
|
||||
flagCompletionMutex.Lock()
|
||||
defer flagCompletionMutex.Unlock()
|
||||
|
||||
if _, exists := flagCompletionFunctions[flag]; exists {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)
|
||||
}
|
||||
flagCompletionFunctions[flag] = f
|
||||
return nil
|
||||
}
|
||||
|
||||
// Returns a string listing the different directive enabled in the specified parameter
|
||||
func (d ShellCompDirective) string() string {
|
||||
var directives []string
|
||||
if d&ShellCompDirectiveError != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveError")
|
||||
}
|
||||
if d&ShellCompDirectiveNoSpace != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveNoSpace")
|
||||
}
|
||||
if d&ShellCompDirectiveNoFileComp != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveNoFileComp")
|
||||
}
|
||||
if d&ShellCompDirectiveFilterFileExt != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveFilterFileExt")
|
||||
}
|
||||
if d&ShellCompDirectiveFilterDirs != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveFilterDirs")
|
||||
}
|
||||
if len(directives) == 0 {
|
||||
directives = append(directives, "ShellCompDirectiveDefault")
|
||||
}
|
||||
|
||||
if d >= shellCompDirectiveMaxValue {
|
||||
return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)
|
||||
}
|
||||
return strings.Join(directives, ", ")
|
||||
}
|
||||
|
||||
// Adds a special hidden command that can be used to request custom completions.
|
||||
func (c *Command) initCompleteCmd(args []string) {
|
||||
completeCmd := &Command{
|
||||
Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
|
||||
Aliases: []string{ShellCompNoDescRequestCmd},
|
||||
DisableFlagsInUseLine: true,
|
||||
Hidden: true,
|
||||
DisableFlagParsing: true,
|
||||
Args: MinimumNArgs(1),
|
||||
Short: "Request shell completion choices for the specified command-line",
|
||||
Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",
|
||||
"to request completion choices for the specified command-line.", ShellCompRequestCmd),
|
||||
Run: func(cmd *Command, args []string) {
|
||||
finalCmd, completions, directive, err := cmd.getCompletions(args)
|
||||
if err != nil {
|
||||
CompErrorln(err.Error())
|
||||
// Keep going for multiple reasons:
|
||||
// 1- There could be some valid completions even though there was an error
|
||||
// 2- Even without completions, we need to print the directive
|
||||
}
|
||||
|
||||
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
|
||||
for _, comp := range completions {
|
||||
if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {
|
||||
// Remove all activeHelp entries in this case
|
||||
if strings.HasPrefix(comp, activeHelpMarker) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if noDescriptions {
|
||||
// Remove any description that may be included following a tab character.
|
||||
comp = strings.Split(comp, "\t")[0]
|
||||
}
|
||||
|
||||
// Make sure we only write the first line to the output.
|
||||
// This is needed if a description contains a linebreak.
|
||||
// Otherwise the shell scripts will interpret the other lines as new flags
|
||||
// and could therefore provide a wrong completion.
|
||||
comp = strings.Split(comp, "\n")[0]
|
||||
|
||||
// Finally trim the completion. This is especially important to get rid
|
||||
// of a trailing tab when there are no description following it.
|
||||
// For example, a sub-command without a description should not be completed
|
||||
// with a tab at the end (or else zsh will show a -- following it
|
||||
// although there is no description).
|
||||
comp = strings.TrimSpace(comp)
|
||||
|
||||
// Print each possible completion to stdout for the completion script to consume.
|
||||
fmt.Fprintln(finalCmd.OutOrStdout(), comp)
|
||||
}
|
||||
|
||||
// As the last printout, print the completion directive for the completion script to parse.
|
||||
// The directive integer must be that last character following a single colon (:).
|
||||
// The completion script expects :<directive>
|
||||
fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)
|
||||
|
||||
// Print some helpful info to stderr for the user to understand.
|
||||
// Output from stderr must be ignored by the completion script.
|
||||
fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())
|
||||
},
|
||||
}
|
||||
c.AddCommand(completeCmd)
|
||||
subCmd, _, err := c.Find(args)
|
||||
if err != nil || subCmd.Name() != ShellCompRequestCmd {
|
||||
// Only create this special command if it is actually being called.
|
||||
// This reduces possible side-effects of creating such a command;
|
||||
// for example, having this command would cause problems to a
|
||||
// cobra program that only consists of the root command, since this
|
||||
// command would cause the root command to suddenly have a subcommand.
|
||||
c.RemoveCommand(completeCmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
|
||||
// The last argument, which is not completely typed by the user,
|
||||
// should not be part of the list of arguments
|
||||
toComplete := args[len(args)-1]
|
||||
trimmedArgs := args[:len(args)-1]
|
||||
|
||||
var finalCmd *Command
|
||||
var finalArgs []string
|
||||
var err error
|
||||
// Find the real command for which completion must be performed
|
||||
// check if we need to traverse here to parse local flags on parent commands
|
||||
if c.Root().TraverseChildren {
|
||||
finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)
|
||||
} else {
|
||||
// For Root commands that don't specify any value for their Args fields, when we call
|
||||
// Find(), if those Root commands don't have any sub-commands, they will accept arguments.
|
||||
// However, because we have added the __complete sub-command in the current code path, the
|
||||
// call to Find() -> legacyArgs() will return an error if there are any arguments.
|
||||
// To avoid this, we first remove the __complete command to get back to having no sub-commands.
|
||||
rootCmd := c.Root()
|
||||
if len(rootCmd.Commands()) == 1 {
|
||||
rootCmd.RemoveCommand(c)
|
||||
}
|
||||
|
||||
finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs)
|
||||
}
|
||||
if err != nil {
|
||||
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
|
||||
return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
|
||||
}
|
||||
finalCmd.ctx = c.ctx
|
||||
|
||||
// These flags are normally added when `execute()` is called on `finalCmd`,
|
||||
// however, when doing completion, we don't call `finalCmd.execute()`.
|
||||
// Let's add the --help and --version flag ourselves.
|
||||
finalCmd.InitDefaultHelpFlag()
|
||||
finalCmd.InitDefaultVersionFlag()
|
||||
|
||||
// Check if we are doing flag value completion before parsing the flags.
|
||||
// This is important because if we are completing a flag value, we need to also
|
||||
// remove the flag name argument from the list of finalArgs or else the parsing
|
||||
// could fail due to an invalid value (incomplete) for the flag.
|
||||
flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
|
||||
|
||||
// Check if interspersed is false or -- was set on a previous arg.
|
||||
// This works by counting the arguments. Normally -- is not counted as arg but
|
||||
// if -- was already set or interspersed is false and there is already one arg then
|
||||
// the extra added -- is counted as arg.
|
||||
flagCompletion := true
|
||||
_ = finalCmd.ParseFlags(append(finalArgs, "--"))
|
||||
newArgCount := finalCmd.Flags().NArg()
|
||||
|
||||
// Parse the flags early so we can check if required flags are set
|
||||
if err = finalCmd.ParseFlags(finalArgs); err != nil {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
|
||||
}
|
||||
|
||||
realArgCount := finalCmd.Flags().NArg()
|
||||
if newArgCount > realArgCount {
|
||||
// don't do flag completion (see above)
|
||||
flagCompletion = false
|
||||
}
|
||||
// Error while attempting to parse flags
|
||||
if flagErr != nil {
|
||||
// If error type is flagCompError and we don't want flagCompletion we should ignore the error
|
||||
if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {
|
||||
return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr
|
||||
}
|
||||
}
|
||||
|
||||
// Look for the --help or --version flags. If they are present,
|
||||
// there should be no further completions.
|
||||
if helpOrVersionFlagPresent(finalCmd) {
|
||||
return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil
|
||||
}
|
||||
|
||||
// We only remove the flags from the arguments if DisableFlagParsing is not set.
|
||||
// This is important for commands which have requested to do their own flag completion.
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
finalArgs = finalCmd.Flags().Args()
|
||||
}
|
||||
|
||||
if flag != nil && flagCompletion {
|
||||
// Check if we are completing a flag value subject to annotations
|
||||
if validExts, present := flag.Annotations[BashCompFilenameExt]; present {
|
||||
if len(validExts) != 0 {
|
||||
// File completion filtered by extensions
|
||||
return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil
|
||||
}
|
||||
|
||||
// The annotation requests simple file completion. There is no reason to do
|
||||
// that since it is the default behavior anyway. Let's ignore this annotation
|
||||
// in case the program also registered a completion function for this flag.
|
||||
// Even though it is a mistake on the program's side, let's be nice when we can.
|
||||
}
|
||||
|
||||
if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {
|
||||
if len(subDir) == 1 {
|
||||
// Directory completion from within a directory
|
||||
return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil
|
||||
}
|
||||
// Directory completion
|
||||
return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil
|
||||
}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
var directive ShellCompDirective
|
||||
|
||||
// Enforce flag groups before doing flag completions
|
||||
finalCmd.enforceFlagGroupsForCompletion()
|
||||
|
||||
// Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;
|
||||
// doing this allows for completion of persistent flag names even for commands that disable flag parsing.
|
||||
//
|
||||
// When doing completion of a flag name, as soon as an argument starts with
|
||||
// a '-' we know it is a flag. We cannot use isFlagArg() here as it requires
|
||||
// the flag name to be complete
|
||||
if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion {
|
||||
// First check for required flags
|
||||
completions = completeRequireFlags(finalCmd, toComplete)
|
||||
|
||||
// If we have not found any required flags, only then can we show regular flags
|
||||
if len(completions) == 0 {
|
||||
doCompleteFlags := func(flag *pflag.Flag) {
|
||||
if !flag.Changed ||
|
||||
strings.Contains(flag.Value.Type(), "Slice") ||
|
||||
strings.Contains(flag.Value.Type(), "Array") {
|
||||
// If the flag is not already present, or if it can be specified multiple times (Array or Slice)
|
||||
// we suggest it as a completion
|
||||
completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
|
||||
}
|
||||
}
|
||||
|
||||
// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands
|
||||
// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and
|
||||
// non-inherited flags.
|
||||
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
doCompleteFlags(flag)
|
||||
})
|
||||
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
doCompleteFlags(flag)
|
||||
})
|
||||
}
|
||||
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {
|
||||
// If there is a single completion, the shell usually adds a space
|
||||
// after the completion. We don't want that if the flag ends with an =
|
||||
directive = ShellCompDirectiveNoSpace
|
||||
}
|
||||
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
// If DisableFlagParsing==false, we have completed the flags as known by Cobra;
|
||||
// we can return what we found.
|
||||
// If DisableFlagParsing==true, Cobra may not be aware of all flags, so we
|
||||
// let the logic continue to see if ValidArgsFunction needs to be called.
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
} else {
|
||||
directive = ShellCompDirectiveDefault
|
||||
if flag == nil {
|
||||
foundLocalNonPersistentFlag := false
|
||||
// If TraverseChildren is true on the root command we don't check for
|
||||
// local flags because we can use a local flag on a parent command
|
||||
if !finalCmd.Root().TraverseChildren {
|
||||
// Check if there are any local, non-persistent flags on the command-line
|
||||
localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()
|
||||
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {
|
||||
foundLocalNonPersistentFlag = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Complete subcommand names, including the help command
|
||||
if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {
|
||||
// We only complete sub-commands if:
|
||||
// - there are no arguments on the command-line and
|
||||
// - there are no local, non-persistent flags on the command-line or TraverseChildren is true
|
||||
for _, subCmd := range finalCmd.Commands() {
|
||||
if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
|
||||
if strings.HasPrefix(subCmd.Name(), toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
||||
}
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Complete required flags even without the '-' prefix
|
||||
completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)
|
||||
|
||||
// Always complete ValidArgs, even if we are completing a subcommand name.
|
||||
// This is for commands that have both subcommands and ValidArgs.
|
||||
if len(finalCmd.ValidArgs) > 0 {
|
||||
if len(finalArgs) == 0 {
|
||||
// ValidArgs are only for the first argument
|
||||
for _, validArg := range finalCmd.ValidArgs {
|
||||
if strings.HasPrefix(validArg, toComplete) {
|
||||
completions = append(completions, validArg)
|
||||
}
|
||||
}
|
||||
directive = ShellCompDirectiveNoFileComp
|
||||
|
||||
// If no completions were found within commands or ValidArgs,
|
||||
// see if there are any ArgAliases that should be completed.
|
||||
if len(completions) == 0 {
|
||||
for _, argAlias := range finalCmd.ArgAliases {
|
||||
if strings.HasPrefix(argAlias, toComplete) {
|
||||
completions = append(completions, argAlias)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If there are ValidArgs specified (even if they don't match), we stop completion.
|
||||
// Only one of ValidArgs or ValidArgsFunction can be used for a single command.
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
// Let the logic continue so as to add any ValidArgsFunction completions,
|
||||
// even if we already found sub-commands.
|
||||
// This is for commands that have subcommands but also specify a ValidArgsFunction.
|
||||
}
|
||||
}
|
||||
|
||||
// Find the completion function for the flag or command
|
||||
var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
if flag != nil && flagCompletion {
|
||||
flagCompletionMutex.RLock()
|
||||
completionFn = flagCompletionFunctions[flag]
|
||||
flagCompletionMutex.RUnlock()
|
||||
} else {
|
||||
completionFn = finalCmd.ValidArgsFunction
|
||||
}
|
||||
if completionFn != nil {
|
||||
// Go custom completion defined for this flag or command.
|
||||
// Call the registered completion function to get the completions.
|
||||
var comps []string
|
||||
comps, directive = completionFn(finalCmd, finalArgs, toComplete)
|
||||
completions = append(completions, comps...)
|
||||
}
|
||||
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
func helpOrVersionFlagPresent(cmd *Command) bool {
|
||||
if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&
|
||||
len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {
|
||||
return true
|
||||
}
|
||||
if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&
|
||||
len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
|
||||
if nonCompletableFlag(flag) {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
flagName := "--" + flag.Name
|
||||
if strings.HasPrefix(flagName, toComplete) {
|
||||
// Flag without the =
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
|
||||
// Why suggest both long forms: --flag and --flag= ?
|
||||
// This forces the user to *always* have to type either an = or a space after the flag name.
|
||||
// Let's be nice and avoid making users have to do that.
|
||||
// Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.
|
||||
// The = form will still work, we just won't suggest it.
|
||||
// This also makes the list of suggested flags shorter as we avoid all the = forms.
|
||||
//
|
||||
// if len(flag.NoOptDefVal) == 0 {
|
||||
// // Flag requires a value, so it can be suffixed with =
|
||||
// flagName += "="
|
||||
// completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
// }
|
||||
}
|
||||
|
||||
flagName = "-" + flag.Shorthand
|
||||
if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
}
|
||||
|
||||
return completions
|
||||
}
|
||||
|
||||
func completeRequireFlags(finalCmd *Command, toComplete string) []string {
|
||||
var completions []string
|
||||
|
||||
doCompleteRequiredFlags := func(flag *pflag.Flag) {
|
||||
if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {
|
||||
if !flag.Changed {
|
||||
// If the flag is not already present, we suggest it as a completion
|
||||
completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands
|
||||
// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and
|
||||
// non-inherited flags.
|
||||
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
doCompleteRequiredFlags(flag)
|
||||
})
|
||||
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
doCompleteRequiredFlags(flag)
|
||||
})
|
||||
|
||||
return completions
|
||||
}
|
||||
|
||||
func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {
|
||||
if finalCmd.DisableFlagParsing {
|
||||
// We only do flag completion if we are allowed to parse flags
|
||||
// This is important for commands which have requested to do their own flag completion.
|
||||
return nil, args, lastArg, nil
|
||||
}
|
||||
|
||||
var flagName string
|
||||
trimmedArgs := args
|
||||
flagWithEqual := false
|
||||
orgLastArg := lastArg
|
||||
|
||||
// When doing completion of a flag name, as soon as an argument starts with
|
||||
// a '-' we know it is a flag. We cannot use isFlagArg() here as that function
|
||||
// requires the flag name to be complete
|
||||
if len(lastArg) > 0 && lastArg[0] == '-' {
|
||||
if index := strings.Index(lastArg, "="); index >= 0 {
|
||||
// Flag with an =
|
||||
if strings.HasPrefix(lastArg[:index], "--") {
|
||||
// Flag has full name
|
||||
flagName = lastArg[2:index]
|
||||
} else {
|
||||
// Flag is shorthand
|
||||
// We have to get the last shorthand flag name
|
||||
// e.g. `-asd` => d to provide the correct completion
|
||||
// https://github.com/spf13/cobra/issues/1257
|
||||
flagName = lastArg[index-1 : index]
|
||||
}
|
||||
lastArg = lastArg[index+1:]
|
||||
flagWithEqual = true
|
||||
} else {
|
||||
// Normal flag completion
|
||||
return nil, args, lastArg, nil
|
||||
}
|
||||
}
|
||||
|
||||
if len(flagName) == 0 {
|
||||
if len(args) > 0 {
|
||||
prevArg := args[len(args)-1]
|
||||
if isFlagArg(prevArg) {
|
||||
// Only consider the case where the flag does not contain an =.
|
||||
// If the flag contains an = it means it has already been fully processed,
|
||||
// so we don't need to deal with it here.
|
||||
if index := strings.Index(prevArg, "="); index < 0 {
|
||||
if strings.HasPrefix(prevArg, "--") {
|
||||
// Flag has full name
|
||||
flagName = prevArg[2:]
|
||||
} else {
|
||||
// Flag is shorthand
|
||||
// We have to get the last shorthand flag name
|
||||
// e.g. `-asd` => d to provide the correct completion
|
||||
// https://github.com/spf13/cobra/issues/1257
|
||||
flagName = prevArg[len(prevArg)-1:]
|
||||
}
|
||||
// Remove the uncompleted flag or else there could be an error created
|
||||
// for an invalid value for that flag
|
||||
trimmedArgs = args[:len(args)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(flagName) == 0 {
|
||||
// Not doing flag completion
|
||||
return nil, trimmedArgs, lastArg, nil
|
||||
}
|
||||
|
||||
flag := findFlag(finalCmd, flagName)
|
||||
if flag == nil {
|
||||
// Flag not supported by this command, the interspersed option might be set so return the original args
|
||||
return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName}
|
||||
}
|
||||
|
||||
if !flagWithEqual {
|
||||
if len(flag.NoOptDefVal) != 0 {
|
||||
// We had assumed dealing with a two-word flag but the flag is a boolean flag.
|
||||
// In that case, there is no value following it, so we are not really doing flag completion.
|
||||
// Reset everything to do noun completion.
|
||||
trimmedArgs = args
|
||||
flag = nil
|
||||
}
|
||||
}
|
||||
|
||||
return flag, trimmedArgs, lastArg, nil
|
||||
}
|
||||
|
||||
// InitDefaultCompletionCmd adds a default 'completion' command to c.
|
||||
// This function will do nothing if any of the following is true:
|
||||
// 1- the feature has been explicitly disabled by the program,
|
||||
// 2- c has no subcommands (to avoid creating one),
|
||||
// 3- c already has a 'completion' command provided by the program.
|
||||
func (c *Command) InitDefaultCompletionCmd() {
|
||||
if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {
|
||||
return
|
||||
}
|
||||
|
||||
for _, cmd := range c.commands {
|
||||
if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {
|
||||
// A completion command is already available
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions
|
||||
|
||||
completionCmd := &Command{
|
||||
Use: compCmdName,
|
||||
Short: "Generate the autocompletion script for the specified shell",
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell.
|
||||
See each sub-command's help for details on how to use the generated script.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
Hidden: c.CompletionOptions.HiddenDefaultCmd,
|
||||
GroupID: c.completionCommandGroupID,
|
||||
}
|
||||
c.AddCommand(completionCmd)
|
||||
|
||||
out := c.OutOrStdout()
|
||||
noDesc := c.CompletionOptions.DisableDescriptions
|
||||
shortDesc := "Generate the autocompletion script for %s"
|
||||
bash := &Command{
|
||||
Use: "bash",
|
||||
Short: fmt.Sprintf(shortDesc, "bash"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell.
|
||||
|
||||
This script depends on the 'bash-completion' package.
|
||||
If it is not installed already, you can install it via your OS's package manager.
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
source <(%[1]s completion bash)
|
||||
|
||||
To load completions for every new session, execute once:
|
||||
|
||||
#### Linux:
|
||||
|
||||
%[1]s completion bash > /etc/bash_completion.d/%[1]s
|
||||
|
||||
#### macOS:
|
||||
|
||||
%[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
|
||||
|
||||
You will need to start a new shell for this setup to take effect.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
return cmd.Root().GenBashCompletionV2(out, !noDesc)
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
zsh := &Command{
|
||||
Use: "zsh",
|
||||
Short: fmt.Sprintf(shortDesc, "zsh"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell.
|
||||
|
||||
If shell completion is not already enabled in your environment you will need
|
||||
to enable it. You can execute the following once:
|
||||
|
||||
echo "autoload -U compinit; compinit" >> ~/.zshrc
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
source <(%[1]s completion zsh); compdef _%[1]s %[1]s
|
||||
|
||||
To load completions for every new session, execute once:
|
||||
|
||||
#### Linux:
|
||||
|
||||
%[1]s completion zsh > "${fpath[1]}/_%[1]s"
|
||||
|
||||
#### macOS:
|
||||
|
||||
%[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s
|
||||
|
||||
You will need to start a new shell for this setup to take effect.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
if noDesc {
|
||||
return cmd.Root().GenZshCompletionNoDesc(out)
|
||||
}
|
||||
return cmd.Root().GenZshCompletion(out)
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
fish := &Command{
|
||||
Use: "fish",
|
||||
Short: fmt.Sprintf(shortDesc, "fish"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell.
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
%[1]s completion fish | source
|
||||
|
||||
To load completions for every new session, execute once:
|
||||
|
||||
%[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
|
||||
|
||||
You will need to start a new shell for this setup to take effect.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
return cmd.Root().GenFishCompletion(out, !noDesc)
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
powershell := &Command{
|
||||
Use: "powershell",
|
||||
Short: fmt.Sprintf(shortDesc, "powershell"),
|
||||
Long: fmt.Sprintf(`Generate the autocompletion script for powershell.
|
||||
|
||||
To load completions in your current shell session:
|
||||
|
||||
%[1]s completion powershell | Out-String | Invoke-Expression
|
||||
|
||||
To load completions for every new session, add the output of the above command
|
||||
to your powershell profile.
|
||||
`, c.Root().Name()),
|
||||
Args: NoArgs,
|
||||
ValidArgsFunction: NoFileCompletions,
|
||||
RunE: func(cmd *Command, args []string) error {
|
||||
if noDesc {
|
||||
return cmd.Root().GenPowerShellCompletion(out)
|
||||
}
|
||||
return cmd.Root().GenPowerShellCompletionWithDesc(out)
|
||||
|
||||
},
|
||||
}
|
||||
if haveNoDescFlag {
|
||||
powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
|
||||
}
|
||||
|
||||
completionCmd.AddCommand(bash, zsh, fish, powershell)
|
||||
}
|
||||
|
||||
func findFlag(cmd *Command, name string) *pflag.Flag {
|
||||
flagSet := cmd.Flags()
|
||||
if len(name) == 1 {
|
||||
// First convert the short flag into a long flag
|
||||
// as the cmd.Flag() search only accepts long flags
|
||||
if short := flagSet.ShorthandLookup(name); short != nil {
|
||||
name = short.Name
|
||||
} else {
|
||||
set := cmd.InheritedFlags()
|
||||
if short = set.ShorthandLookup(name); short != nil {
|
||||
name = short.Name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return cmd.Flag(name)
|
||||
}
|
||||
|
||||
// CompDebug prints the specified string to the same file as where the
|
||||
// completion script prints its logs.
|
||||
// Note that completion printouts should never be on stdout as they would
|
||||
// be wrongly interpreted as actual completion choices by the completion script.
|
||||
func CompDebug(msg string, printToStdErr bool) {
|
||||
msg = fmt.Sprintf("[Debug] %s", msg)
|
||||
|
||||
// Such logs are only printed when the user has set the environment
|
||||
// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
|
||||
if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {
|
||||
f, err := os.OpenFile(path,
|
||||
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err == nil {
|
||||
defer f.Close()
|
||||
WriteStringAndCheck(f, msg)
|
||||
}
|
||||
}
|
||||
|
||||
if printToStdErr {
|
||||
// Must print to stderr for this not to be read by the completion script.
|
||||
fmt.Fprint(os.Stderr, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// CompDebugln prints the specified string with a newline at the end
|
||||
// to the same file as where the completion script prints its logs.
|
||||
// Such logs are only printed when the user has set the environment
|
||||
// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
|
||||
func CompDebugln(msg string, printToStdErr bool) {
|
||||
CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)
|
||||
}
|
||||
|
||||
// CompError prints the specified completion message to stderr.
|
||||
func CompError(msg string) {
|
||||
msg = fmt.Sprintf("[Error] %s", msg)
|
||||
CompDebug(msg, true)
|
||||
}
|
||||
|
||||
// CompErrorln prints the specified completion message to stderr with a newline at the end.
|
||||
func CompErrorln(msg string) {
|
||||
CompError(fmt.Sprintf("%s\n", msg))
|
||||
}
|
||||
234
src/cmd/linuxkit/vendor/github.com/spf13/cobra/fish_completions.go
generated
vendored
Normal file
234
src/cmd/linuxkit/vendor/github.com/spf13/cobra/fish_completions.go
generated
vendored
Normal file
@@ -0,0 +1,234 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
// Variables should not contain a '-' or ':' character
|
||||
nameForVar := name
|
||||
nameForVar = strings.ReplaceAll(nameForVar, "-", "_")
|
||||
nameForVar = strings.ReplaceAll(nameForVar, ":", "_")
|
||||
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`
|
||||
function __%[1]s_debug
|
||||
set -l file "$BASH_COMP_DEBUG_FILE"
|
||||
if test -n "$file"
|
||||
echo "$argv" >> $file
|
||||
end
|
||||
end
|
||||
|
||||
function __%[1]s_perform_completion
|
||||
__%[1]s_debug "Starting __%[1]s_perform_completion"
|
||||
|
||||
# Extract all args except the last one
|
||||
set -l args (commandline -opc)
|
||||
# Extract the last arg and escape it in case it is a space
|
||||
set -l lastArg (string escape -- (commandline -ct))
|
||||
|
||||
__%[1]s_debug "args: $args"
|
||||
__%[1]s_debug "last arg: $lastArg"
|
||||
|
||||
# Disable ActiveHelp which is not supported for fish shell
|
||||
set -l requestComp "%[9]s=0 $args[1] %[3]s $args[2..-1] $lastArg"
|
||||
|
||||
__%[1]s_debug "Calling $requestComp"
|
||||
set -l results (eval $requestComp 2> /dev/null)
|
||||
|
||||
# Some programs may output extra empty lines after the directive.
|
||||
# Let's ignore them or else it will break completion.
|
||||
# Ref: https://github.com/spf13/cobra/issues/1279
|
||||
for line in $results[-1..1]
|
||||
if test (string trim -- $line) = ""
|
||||
# Found an empty line, remove it
|
||||
set results $results[1..-2]
|
||||
else
|
||||
# Found non-empty line, we have our proper output
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
set -l comps $results[1..-2]
|
||||
set -l directiveLine $results[-1]
|
||||
|
||||
# For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
|
||||
# completions must be prefixed with the flag
|
||||
set -l flagPrefix (string match -r -- '-.*=' "$lastArg")
|
||||
|
||||
__%[1]s_debug "Comps: $comps"
|
||||
__%[1]s_debug "DirectiveLine: $directiveLine"
|
||||
__%[1]s_debug "flagPrefix: $flagPrefix"
|
||||
|
||||
for comp in $comps
|
||||
printf "%%s%%s\n" "$flagPrefix" "$comp"
|
||||
end
|
||||
|
||||
printf "%%s\n" "$directiveLine"
|
||||
end
|
||||
|
||||
# This function does two things:
|
||||
# - Obtain the completions and store them in the global __%[1]s_comp_results
|
||||
# - Return false if file completion should be performed
|
||||
function __%[1]s_prepare_completions
|
||||
__%[1]s_debug ""
|
||||
__%[1]s_debug "========= starting completion logic =========="
|
||||
|
||||
# Start fresh
|
||||
set --erase __%[1]s_comp_results
|
||||
|
||||
set -l results (__%[1]s_perform_completion)
|
||||
__%[1]s_debug "Completion results: $results"
|
||||
|
||||
if test -z "$results"
|
||||
__%[1]s_debug "No completion, probably due to a failure"
|
||||
# Might as well do file completion, in case it helps
|
||||
return 1
|
||||
end
|
||||
|
||||
set -l directive (string sub --start 2 $results[-1])
|
||||
set --global __%[1]s_comp_results $results[1..-2]
|
||||
|
||||
__%[1]s_debug "Completions are: $__%[1]s_comp_results"
|
||||
__%[1]s_debug "Directive is: $directive"
|
||||
|
||||
set -l shellCompDirectiveError %[4]d
|
||||
set -l shellCompDirectiveNoSpace %[5]d
|
||||
set -l shellCompDirectiveNoFileComp %[6]d
|
||||
set -l shellCompDirectiveFilterFileExt %[7]d
|
||||
set -l shellCompDirectiveFilterDirs %[8]d
|
||||
|
||||
if test -z "$directive"
|
||||
set directive 0
|
||||
end
|
||||
|
||||
set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)
|
||||
if test $compErr -eq 1
|
||||
__%[1]s_debug "Received error directive: aborting."
|
||||
# Might as well do file completion, in case it helps
|
||||
return 1
|
||||
end
|
||||
|
||||
set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)
|
||||
set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)
|
||||
if test $filefilter -eq 1; or test $dirfilter -eq 1
|
||||
__%[1]s_debug "File extension filtering or directory filtering not supported"
|
||||
# Do full file completion instead
|
||||
return 1
|
||||
end
|
||||
|
||||
set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)
|
||||
set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)
|
||||
|
||||
__%[1]s_debug "nospace: $nospace, nofiles: $nofiles"
|
||||
|
||||
# If we want to prevent a space, or if file completion is NOT disabled,
|
||||
# we need to count the number of valid completions.
|
||||
# To do so, we will filter on prefix as the completions we have received
|
||||
# may not already be filtered so as to allow fish to match on different
|
||||
# criteria than the prefix.
|
||||
if test $nospace -ne 0; or test $nofiles -eq 0
|
||||
set -l prefix (commandline -t | string escape --style=regex)
|
||||
__%[1]s_debug "prefix: $prefix"
|
||||
|
||||
set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results)
|
||||
set --global __%[1]s_comp_results $completions
|
||||
__%[1]s_debug "Filtered completions are: $__%[1]s_comp_results"
|
||||
|
||||
# Important not to quote the variable for count to work
|
||||
set -l numComps (count $__%[1]s_comp_results)
|
||||
__%[1]s_debug "numComps: $numComps"
|
||||
|
||||
if test $numComps -eq 1; and test $nospace -ne 0
|
||||
# We must first split on \t to get rid of the descriptions to be
|
||||
# able to check what the actual completion will be.
|
||||
# We don't need descriptions anyway since there is only a single
|
||||
# real completion which the shell will expand immediately.
|
||||
set -l split (string split --max 1 \t $__%[1]s_comp_results[1])
|
||||
|
||||
# Fish won't add a space if the completion ends with any
|
||||
# of the following characters: @=/:.,
|
||||
set -l lastChar (string sub -s -1 -- $split)
|
||||
if not string match -r -q "[@=/:.,]" -- "$lastChar"
|
||||
# In other cases, to support the "nospace" directive we trick the shell
|
||||
# by outputting an extra, longer completion.
|
||||
__%[1]s_debug "Adding second completion to perform nospace directive"
|
||||
set --global __%[1]s_comp_results $split[1] $split[1].
|
||||
__%[1]s_debug "Completions are now: $__%[1]s_comp_results"
|
||||
end
|
||||
end
|
||||
|
||||
if test $numComps -eq 0; and test $nofiles -eq 0
|
||||
# To be consistent with bash and zsh, we only trigger file
|
||||
# completion when there are no other completions
|
||||
__%[1]s_debug "Requesting file completion"
|
||||
return 1
|
||||
end
|
||||
end
|
||||
|
||||
return 0
|
||||
end
|
||||
|
||||
# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves
|
||||
# so we can properly delete any completions provided by another script.
|
||||
# Only do this if the program can be found, or else fish may print some errors; besides,
|
||||
# the existing completions will only be loaded if the program can be found.
|
||||
if type -q "%[2]s"
|
||||
# The space after the program name is essential to trigger completion for the program
|
||||
# and not completion of the program name itself.
|
||||
# Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
|
||||
complete --do-complete "%[2]s " > /dev/null 2>&1
|
||||
end
|
||||
|
||||
# Remove any pre-existing completions for the program since we will be handling all of them.
|
||||
complete -c %[2]s -e
|
||||
|
||||
# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results
|
||||
# which provides the program's completion choices.
|
||||
complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
|
||||
|
||||
`, nameForVar, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
// GenFishCompletion generates fish completion file and writes to the passed writer.
|
||||
func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
|
||||
buf := new(bytes.Buffer)
|
||||
genFishComp(buf, c.Name(), includeDesc)
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
// GenFishCompletionFile generates fish completion file.
|
||||
func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenFishCompletion(outFile, includeDesc)
|
||||
}
|
||||
4
src/cmd/linuxkit/vendor/github.com/spf13/cobra/fish_completions.md
generated
vendored
Normal file
4
src/cmd/linuxkit/vendor/github.com/spf13/cobra/fish_completions.md
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
## Generating Fish Completions For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
||||
224
src/cmd/linuxkit/vendor/github.com/spf13/cobra/flag_groups.go
generated
vendored
Normal file
224
src/cmd/linuxkit/vendor/github.com/spf13/cobra/flag_groups.go
generated
vendored
Normal file
@@ -0,0 +1,224 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
requiredAsGroup = "cobra_annotation_required_if_others_set"
|
||||
mutuallyExclusive = "cobra_annotation_mutually_exclusive"
|
||||
)
|
||||
|
||||
// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
|
||||
// if the command is invoked with a subset (but not all) of the given flags.
|
||||
func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
|
||||
c.mergePersistentFlags()
|
||||
for _, v := range flagNames {
|
||||
f := c.Flags().Lookup(v)
|
||||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v))
|
||||
}
|
||||
if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil {
|
||||
// Only errs if the flag isn't found.
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors
|
||||
// if the command is invoked with more than one flag from the given set of flags.
|
||||
func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
|
||||
c.mergePersistentFlags()
|
||||
for _, v := range flagNames {
|
||||
f := c.Flags().Lookup(v)
|
||||
if f == nil {
|
||||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v))
|
||||
}
|
||||
// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.
|
||||
if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the
|
||||
// first error encountered.
|
||||
func (c *Command) ValidateFlagGroups() error {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
}
|
||||
|
||||
flags := c.Flags()
|
||||
|
||||
// groupStatus format is the list of flags as a unique ID,
|
||||
// then a map of each flag name and whether it is set or not.
|
||||
groupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
flags.VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
if err := validateRequiredFlagGroups(groupStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {
|
||||
for _, fname := range flagnames {
|
||||
f := fs.Lookup(fname)
|
||||
if f == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) {
|
||||
groupInfo, found := pflag.Annotations[annotation]
|
||||
if found {
|
||||
for _, group := range groupInfo {
|
||||
if groupStatus[group] == nil {
|
||||
flagnames := strings.Split(group, " ")
|
||||
|
||||
// Only consider this flag group at all if all the flags are defined.
|
||||
if !hasAllFlags(flags, flagnames...) {
|
||||
continue
|
||||
}
|
||||
|
||||
groupStatus[group] = map[string]bool{}
|
||||
for _, name := range flagnames {
|
||||
groupStatus[group][name] = false
|
||||
}
|
||||
}
|
||||
|
||||
groupStatus[group][pflag.Name] = pflag.Changed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateRequiredFlagGroups(data map[string]map[string]bool) error {
|
||||
keys := sortedKeys(data)
|
||||
for _, flagList := range keys {
|
||||
flagnameAndStatus := data[flagList]
|
||||
|
||||
unset := []string{}
|
||||
for flagname, isSet := range flagnameAndStatus {
|
||||
if !isSet {
|
||||
unset = append(unset, flagname)
|
||||
}
|
||||
}
|
||||
if len(unset) == len(flagnameAndStatus) || len(unset) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Sort values, so they can be tested/scripted against consistently.
|
||||
sort.Strings(unset)
|
||||
return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
|
||||
keys := sortedKeys(data)
|
||||
for _, flagList := range keys {
|
||||
flagnameAndStatus := data[flagList]
|
||||
var set []string
|
||||
for flagname, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
set = append(set, flagname)
|
||||
}
|
||||
}
|
||||
if len(set) == 0 || len(set) == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Sort values, so they can be tested/scripted against consistently.
|
||||
sort.Strings(set)
|
||||
return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sortedKeys(m map[string]map[string]bool) []string {
|
||||
keys := make([]string, len(m))
|
||||
i := 0
|
||||
for k := range m {
|
||||
keys[i] = k
|
||||
i++
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
// enforceFlagGroupsForCompletion will do the following:
|
||||
// - when a flag in a group is present, other flags in the group will be marked required
|
||||
// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden
|
||||
// This allows the standard completion logic to behave appropriately for flag groups
|
||||
func (c *Command) enforceFlagGroupsForCompletion() {
|
||||
if c.DisableFlagParsing {
|
||||
return
|
||||
}
|
||||
|
||||
flags := c.Flags()
|
||||
groupStatus := map[string]map[string]bool{}
|
||||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{}
|
||||
c.Flags().VisitAll(func(pflag *flag.Flag) {
|
||||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)
|
||||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)
|
||||
})
|
||||
|
||||
// If a flag that is part of a group is present, we make all the other flags
|
||||
// of that group required so that the shell completion suggests them automatically
|
||||
for flagList, flagnameAndStatus := range groupStatus {
|
||||
for _, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
// One of the flags of the group is set, mark the other ones as required
|
||||
for _, fName := range strings.Split(flagList, " ") {
|
||||
_ = c.MarkFlagRequired(fName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If a flag that is mutually exclusive to others is present, we hide the other
|
||||
// flags of that group so the shell completion does not suggest them
|
||||
for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {
|
||||
for flagName, isSet := range flagnameAndStatus {
|
||||
if isSet {
|
||||
// One of the flags of the mutually exclusive group is set, mark the other ones as hidden
|
||||
// Don't mark the flag that is already set as hidden because it may be an
|
||||
// array or slice flag and therefore must continue being suggested
|
||||
for _, fName := range strings.Split(flagList, " ") {
|
||||
if fName != flagName {
|
||||
flag := c.Flags().Lookup(fName)
|
||||
flag.Hidden = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
310
src/cmd/linuxkit/vendor/github.com/spf13/cobra/powershell_completions.go
generated
vendored
Normal file
310
src/cmd/linuxkit/vendor/github.com/spf13/cobra/powershell_completions.go
generated
vendored
Normal file
@@ -0,0 +1,310 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but
|
||||
// can be downloaded separately for windows 7 or 8.1).
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
// Variables should not contain a '-' or ':' character
|
||||
nameForVar := name
|
||||
nameForVar = strings.Replace(nameForVar, "-", "_", -1)
|
||||
nameForVar = strings.Replace(nameForVar, ":", "_", -1)
|
||||
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-
|
||||
|
||||
function __%[1]s_debug {
|
||||
if ($env:BASH_COMP_DEBUG_FILE) {
|
||||
"$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
|
||||
}
|
||||
}
|
||||
|
||||
filter __%[1]s_escapeStringWithSpecialChars {
|
||||
`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+`
|
||||
}
|
||||
|
||||
[scriptblock]$__%[2]sCompleterBlock = {
|
||||
param(
|
||||
$WordToComplete,
|
||||
$CommandAst,
|
||||
$CursorPosition
|
||||
)
|
||||
|
||||
# Get the current command line and convert into a string
|
||||
$Command = $CommandAst.CommandElements
|
||||
$Command = "$Command"
|
||||
|
||||
__%[1]s_debug ""
|
||||
__%[1]s_debug "========= starting completion logic =========="
|
||||
__%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
|
||||
|
||||
# The user could have moved the cursor backwards on the command-line.
|
||||
# We need to trigger completion from the $CursorPosition location, so we need
|
||||
# to truncate the command-line ($Command) up to the $CursorPosition location.
|
||||
# Make sure the $Command is longer then the $CursorPosition before we truncate.
|
||||
# This happens because the $Command does not include the last space.
|
||||
if ($Command.Length -gt $CursorPosition) {
|
||||
$Command=$Command.Substring(0,$CursorPosition)
|
||||
}
|
||||
__%[1]s_debug "Truncated command: $Command"
|
||||
|
||||
$ShellCompDirectiveError=%[4]d
|
||||
$ShellCompDirectiveNoSpace=%[5]d
|
||||
$ShellCompDirectiveNoFileComp=%[6]d
|
||||
$ShellCompDirectiveFilterFileExt=%[7]d
|
||||
$ShellCompDirectiveFilterDirs=%[8]d
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Split the command at the first space to separate the program and arguments.
|
||||
$Program,$Arguments = $Command.Split(" ",2)
|
||||
|
||||
$RequestComp="$Program %[3]s $Arguments"
|
||||
__%[1]s_debug "RequestComp: $RequestComp"
|
||||
|
||||
# we cannot use $WordToComplete because it
|
||||
# has the wrong values if the cursor was moved
|
||||
# so use the last argument
|
||||
if ($WordToComplete -ne "" ) {
|
||||
$WordToComplete = $Arguments.Split(" ")[-1]
|
||||
}
|
||||
__%[1]s_debug "New WordToComplete: $WordToComplete"
|
||||
|
||||
|
||||
# Check for flag with equal sign
|
||||
$IsEqualFlag = ($WordToComplete -Like "--*=*" )
|
||||
if ( $IsEqualFlag ) {
|
||||
__%[1]s_debug "Completing equal sign flag"
|
||||
# Remove the flag part
|
||||
$Flag,$WordToComplete = $WordToComplete.Split("=",2)
|
||||
}
|
||||
|
||||
if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
|
||||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go method.
|
||||
__%[1]s_debug "Adding extra empty parameter"
|
||||
`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+`
|
||||
`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+`
|
||||
}
|
||||
|
||||
__%[1]s_debug "Calling $RequestComp"
|
||||
# First disable ActiveHelp which is not supported for Powershell
|
||||
$env:%[9]s=0
|
||||
|
||||
#call the command store the output in $out and redirect stderr and stdout to null
|
||||
# $Out is an array contains each line per element
|
||||
Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
|
||||
|
||||
# get directive from last line
|
||||
[int]$Directive = $Out[-1].TrimStart(':')
|
||||
if ($Directive -eq "") {
|
||||
# There is no directive specified
|
||||
$Directive = 0
|
||||
}
|
||||
__%[1]s_debug "The completion directive is: $Directive"
|
||||
|
||||
# remove directive (last element) from out
|
||||
$Out = $Out | Where-Object { $_ -ne $Out[-1] }
|
||||
__%[1]s_debug "The completions are: $Out"
|
||||
|
||||
if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
|
||||
# Error code. No completion.
|
||||
__%[1]s_debug "Received error from custom completion go code"
|
||||
return
|
||||
}
|
||||
|
||||
$Longest = 0
|
||||
$Values = $Out | ForEach-Object {
|
||||
#Split the output in name and description
|
||||
`+" $Name, $Description = $_.Split(\"`t\",2)"+`
|
||||
__%[1]s_debug "Name: $Name Description: $Description"
|
||||
|
||||
# Look for the longest completion so that we can format things nicely
|
||||
if ($Longest -lt $Name.Length) {
|
||||
$Longest = $Name.Length
|
||||
}
|
||||
|
||||
# Set the description to a one space string if there is none set.
|
||||
# This is needed because the CompletionResult does not accept an empty string as argument
|
||||
if (-Not $Description) {
|
||||
$Description = " "
|
||||
}
|
||||
@{Name="$Name";Description="$Description"}
|
||||
}
|
||||
|
||||
|
||||
$Space = " "
|
||||
if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
|
||||
# remove the space here
|
||||
__%[1]s_debug "ShellCompDirectiveNoSpace is called"
|
||||
$Space = ""
|
||||
}
|
||||
|
||||
if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
|
||||
(($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
|
||||
__%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
|
||||
|
||||
# return here to prevent the completion of the extensions
|
||||
return
|
||||
}
|
||||
|
||||
$Values = $Values | Where-Object {
|
||||
# filter the result
|
||||
$_.Name -like "$WordToComplete*"
|
||||
|
||||
# Join the flag back if we have an equal sign flag
|
||||
if ( $IsEqualFlag ) {
|
||||
__%[1]s_debug "Join the equal sign flag back to the completion value"
|
||||
$_.Name = $Flag + "=" + $_.Name
|
||||
}
|
||||
}
|
||||
|
||||
if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
|
||||
__%[1]s_debug "ShellCompDirectiveNoFileComp is called"
|
||||
|
||||
if ($Values.Length -eq 0) {
|
||||
# Just print an empty string here so the
|
||||
# shell does not start to complete paths.
|
||||
# We cannot use CompletionResult here because
|
||||
# it does not accept an empty string as argument.
|
||||
""
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
# Get the current mode
|
||||
$Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
|
||||
__%[1]s_debug "Mode: $Mode"
|
||||
|
||||
$Values | ForEach-Object {
|
||||
|
||||
# store temporary because switch will overwrite $_
|
||||
$comp = $_
|
||||
|
||||
# PowerShell supports three different completion modes
|
||||
# - TabCompleteNext (default windows style - on each key press the next option is displayed)
|
||||
# - Complete (works like bash)
|
||||
# - MenuComplete (works like zsh)
|
||||
# You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>
|
||||
|
||||
# CompletionResult Arguments:
|
||||
# 1) CompletionText text to be used as the auto completion result
|
||||
# 2) ListItemText text to be displayed in the suggestion list
|
||||
# 3) ResultType type of completion result
|
||||
# 4) ToolTip text for the tooltip with details about the object
|
||||
|
||||
switch ($Mode) {
|
||||
|
||||
# bash like
|
||||
"Complete" {
|
||||
|
||||
if ($Values.Length -eq 1) {
|
||||
__%[1]s_debug "Only one completion left"
|
||||
|
||||
# insert space after value
|
||||
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
|
||||
} else {
|
||||
# Add the proper number of spaces to align the descriptions
|
||||
while($comp.Name.Length -lt $Longest) {
|
||||
$comp.Name = $comp.Name + " "
|
||||
}
|
||||
|
||||
# Check for empty description and only add parentheses if needed
|
||||
if ($($comp.Description) -eq " " ) {
|
||||
$Description = ""
|
||||
} else {
|
||||
$Description = " ($($comp.Description))"
|
||||
}
|
||||
|
||||
[System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
|
||||
}
|
||||
}
|
||||
|
||||
# zsh like
|
||||
"MenuComplete" {
|
||||
# insert space after value
|
||||
# MenuComplete will automatically show the ToolTip of
|
||||
# the highlighted value at the bottom of the suggestions.
|
||||
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
}
|
||||
|
||||
# TabCompleteNext and in case we get something unknown
|
||||
Default {
|
||||
# Like MenuComplete but we don't want to add a space here because
|
||||
# the user need to press space anyway to get the completion.
|
||||
# Description will not be shown because that's not possible with TabCompleteNext
|
||||
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock
|
||||
`, name, nameForVar, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
|
||||
}
|
||||
|
||||
func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {
|
||||
buf := new(bytes.Buffer)
|
||||
genPowerShellComp(buf, c.Name(), includeDesc)
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.genPowerShellCompletion(outFile, includeDesc)
|
||||
}
|
||||
|
||||
// GenPowerShellCompletionFile generates powershell completion file without descriptions.
|
||||
func (c *Command) GenPowerShellCompletionFile(filename string) error {
|
||||
return c.genPowerShellCompletionFile(filename, false)
|
||||
}
|
||||
|
||||
// GenPowerShellCompletion generates powershell completion file without descriptions
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenPowerShellCompletion(w io.Writer) error {
|
||||
return c.genPowerShellCompletion(w, false)
|
||||
}
|
||||
|
||||
// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.
|
||||
func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error {
|
||||
return c.genPowerShellCompletionFile(filename, true)
|
||||
}
|
||||
|
||||
// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error {
|
||||
return c.genPowerShellCompletion(w, true)
|
||||
}
|
||||
3
src/cmd/linuxkit/vendor/github.com/spf13/cobra/powershell_completions.md
generated
vendored
Normal file
3
src/cmd/linuxkit/vendor/github.com/spf13/cobra/powershell_completions.md
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Generating PowerShell Completions For Your Own cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details.
|
||||
60
src/cmd/linuxkit/vendor/github.com/spf13/cobra/projects_using_cobra.md
generated
vendored
Normal file
60
src/cmd/linuxkit/vendor/github.com/spf13/cobra/projects_using_cobra.md
generated
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
## Projects using Cobra
|
||||
|
||||
- [Allero](https://github.com/allero-io/allero)
|
||||
- [Arduino CLI](https://github.com/arduino/arduino-cli)
|
||||
- [Bleve](https://blevesearch.com/)
|
||||
- [Cilium](https://cilium.io/)
|
||||
- [CloudQuery](https://github.com/cloudquery/cloudquery)
|
||||
- [CockroachDB](https://www.cockroachlabs.com/)
|
||||
- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)
|
||||
- [Datree](https://github.com/datreeio/datree)
|
||||
- [Delve](https://github.com/derekparker/delve)
|
||||
- [Docker (distribution)](https://github.com/docker/distribution)
|
||||
- [Etcd](https://etcd.io/)
|
||||
- [Gardener](https://github.com/gardener/gardenctl)
|
||||
- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)
|
||||
- [Git Bump](https://github.com/erdaltsksn/git-bump)
|
||||
- [GitHub CLI](https://github.com/cli/cli)
|
||||
- [GitHub Labeler](https://github.com/erdaltsksn/gh-label)
|
||||
- [Golangci-lint](https://golangci-lint.run)
|
||||
- [GopherJS](https://github.com/gopherjs/gopherjs)
|
||||
- [GoReleaser](https://goreleaser.com)
|
||||
- [Helm](https://helm.sh)
|
||||
- [Hugo](https://gohugo.io)
|
||||
- [Infracost](https://github.com/infracost/infracost)
|
||||
- [Istio](https://istio.io)
|
||||
- [Kool](https://github.com/kool-dev/kool)
|
||||
- [Kubernetes](https://kubernetes.io/)
|
||||
- [Kubescape](https://github.com/armosec/kubescape)
|
||||
- [KubeVirt](https://github.com/kubevirt/kubevirt)
|
||||
- [Linkerd](https://linkerd.io/)
|
||||
- [Mattermost-server](https://github.com/mattermost/mattermost-server)
|
||||
- [Mercure](https://mercure.rocks/)
|
||||
- [Meroxa CLI](https://github.com/meroxa/cli)
|
||||
- [Metal Stack CLI](https://github.com/metal-stack/metalctl)
|
||||
- [Moby (former Docker)](https://github.com/moby/moby)
|
||||
- [Moldy](https://github.com/Moldy-Community/moldy)
|
||||
- [Multi-gitter](https://github.com/lindell/multi-gitter)
|
||||
- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
|
||||
- [nFPM](https://nfpm.goreleaser.com)
|
||||
- [Okteto](https://github.com/okteto/okteto)
|
||||
- [OpenShift](https://www.openshift.com/)
|
||||
- [Ory Hydra](https://github.com/ory/hydra)
|
||||
- [Ory Kratos](https://github.com/ory/kratos)
|
||||
- [Pixie](https://github.com/pixie-io/pixie)
|
||||
- [Polygon Edge](https://github.com/0xPolygon/polygon-edge)
|
||||
- [Pouch](https://github.com/alibaba/pouch)
|
||||
- [ProjectAtomic (enterprise)](https://www.projectatomic.io/)
|
||||
- [Prototool](https://github.com/uber/prototool)
|
||||
- [Pulumi](https://www.pulumi.com)
|
||||
- [QRcp](https://github.com/claudiodangelis/qrcp)
|
||||
- [Random](https://github.com/erdaltsksn/random)
|
||||
- [Rclone](https://rclone.org/)
|
||||
- [Scaleway CLI](https://github.com/scaleway/scaleway-cli)
|
||||
- [Skaffold](https://skaffold.dev/)
|
||||
- [Tendermint](https://github.com/tendermint/tendermint)
|
||||
- [Twitch CLI](https://github.com/twitchdev/twitch-cli)
|
||||
- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)
|
||||
- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)
|
||||
- [Werf](https://werf.io/)
|
||||
- [ZITADEL](https://github.com/zitadel/zitadel)
|
||||
98
src/cmd/linuxkit/vendor/github.com/spf13/cobra/shell_completions.go
generated
vendored
Normal file
98
src/cmd/linuxkit/vendor/github.com/spf13/cobra/shell_completions.go
generated
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// MarkFlagRequired instructs the various shell completion implementations to
|
||||
// prioritize the named flag when performing completion,
|
||||
// and causes your command to report an error if invoked without the flag.
|
||||
func (c *Command) MarkFlagRequired(name string) error {
|
||||
return MarkFlagRequired(c.Flags(), name)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagRequired instructs the various shell completion implementations to
|
||||
// prioritize the named persistent flag when performing completion,
|
||||
// and causes your command to report an error if invoked without the flag.
|
||||
func (c *Command) MarkPersistentFlagRequired(name string) error {
|
||||
return MarkFlagRequired(c.PersistentFlags(), name)
|
||||
}
|
||||
|
||||
// MarkFlagRequired instructs the various shell completion implementations to
|
||||
// prioritize the named flag when performing completion,
|
||||
// and causes your command to report an error if invoked without the flag.
|
||||
func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
|
||||
return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
|
||||
}
|
||||
|
||||
// MarkFlagFilename instructs the various shell completion implementations to
|
||||
// limit completions for the named flag to the specified file extensions.
|
||||
func (c *Command) MarkFlagFilename(name string, extensions ...string) error {
|
||||
return MarkFlagFilename(c.Flags(), name, extensions...)
|
||||
}
|
||||
|
||||
// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
|
||||
// The bash completion script will call the bash function f for the flag.
|
||||
//
|
||||
// This will only work for bash completion.
|
||||
// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows
|
||||
// to register a Go function which will work across all shells.
|
||||
func (c *Command) MarkFlagCustom(name string, f string) error {
|
||||
return MarkFlagCustom(c.Flags(), name, f)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagFilename instructs the various shell completion
|
||||
// implementations to limit completions for the named persistent flag to the
|
||||
// specified file extensions.
|
||||
func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
|
||||
return MarkFlagFilename(c.PersistentFlags(), name, extensions...)
|
||||
}
|
||||
|
||||
// MarkFlagFilename instructs the various shell completion implementations to
|
||||
// limit completions for the named flag to the specified file extensions.
|
||||
func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
|
||||
return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
|
||||
}
|
||||
|
||||
// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
|
||||
// The bash completion script will call the bash function f for the flag.
|
||||
//
|
||||
// This will only work for bash completion.
|
||||
// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows
|
||||
// to register a Go function which will work across all shells.
|
||||
func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
|
||||
return flags.SetAnnotation(name, BashCompCustom, []string{f})
|
||||
}
|
||||
|
||||
// MarkFlagDirname instructs the various shell completion implementations to
|
||||
// limit completions for the named flag to directory names.
|
||||
func (c *Command) MarkFlagDirname(name string) error {
|
||||
return MarkFlagDirname(c.Flags(), name)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagDirname instructs the various shell completion
|
||||
// implementations to limit completions for the named persistent flag to
|
||||
// directory names.
|
||||
func (c *Command) MarkPersistentFlagDirname(name string) error {
|
||||
return MarkFlagDirname(c.PersistentFlags(), name)
|
||||
}
|
||||
|
||||
// MarkFlagDirname instructs the various shell completion implementations to
|
||||
// limit completions for the named flag to directory names.
|
||||
func MarkFlagDirname(flags *pflag.FlagSet, name string) error {
|
||||
return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{})
|
||||
}
|
||||
568
src/cmd/linuxkit/vendor/github.com/spf13/cobra/shell_completions.md
generated
vendored
Normal file
568
src/cmd/linuxkit/vendor/github.com/spf13/cobra/shell_completions.md
generated
vendored
Normal file
@@ -0,0 +1,568 @@
|
||||
# Generating shell completions
|
||||
|
||||
Cobra can generate shell completions for multiple shells.
|
||||
The currently supported shells are:
|
||||
- Bash
|
||||
- Zsh
|
||||
- fish
|
||||
- PowerShell
|
||||
|
||||
Cobra will automatically provide your program with a fully functional `completion` command,
|
||||
similarly to how it provides the `help` command.
|
||||
|
||||
## Creating your own completion command
|
||||
|
||||
If you do not wish to use the default `completion` command, you can choose to
|
||||
provide your own, which will take precedence over the default one. (This also provides
|
||||
backwards-compatibility with programs that already have their own `completion` command.)
|
||||
|
||||
If you are using the `cobra-cli` generator,
|
||||
which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli),
|
||||
you can create a completion command by running
|
||||
|
||||
```bash
|
||||
cobra-cli add completion
|
||||
```
|
||||
and then modifying the generated `cmd/completion.go` file to look something like this
|
||||
(writing the shell script to stdout allows the most flexible use):
|
||||
|
||||
```go
|
||||
var completionCmd = &cobra.Command{
|
||||
Use: "completion [bash|zsh|fish|powershell]",
|
||||
Short: "Generate completion script",
|
||||
Long: fmt.Sprintf(`To load completions:
|
||||
|
||||
Bash:
|
||||
|
||||
$ source <(%[1]s completion bash)
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
# Linux:
|
||||
$ %[1]s completion bash > /etc/bash_completion.d/%[1]s
|
||||
# macOS:
|
||||
$ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
|
||||
|
||||
Zsh:
|
||||
|
||||
# If shell completion is not already enabled in your environment,
|
||||
# you will need to enable it. You can execute the following once:
|
||||
|
||||
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
|
||||
|
||||
# You will need to start a new shell for this setup to take effect.
|
||||
|
||||
fish:
|
||||
|
||||
$ %[1]s completion fish | source
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
|
||||
|
||||
PowerShell:
|
||||
|
||||
PS> %[1]s completion powershell | Out-String | Invoke-Expression
|
||||
|
||||
# To load completions for every new session, run:
|
||||
PS> %[1]s completion powershell > %[1]s.ps1
|
||||
# and source this file from your PowerShell profile.
|
||||
`,cmd.Root().Name()),
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
|
||||
Args: cobra.ExactValidArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
switch args[0] {
|
||||
case "bash":
|
||||
cmd.Root().GenBashCompletion(os.Stdout)
|
||||
case "zsh":
|
||||
cmd.Root().GenZshCompletion(os.Stdout)
|
||||
case "fish":
|
||||
cmd.Root().GenFishCompletion(os.Stdout, true)
|
||||
case "powershell":
|
||||
cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
|
||||
}
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.
|
||||
|
||||
## Adapting the default completion command
|
||||
|
||||
Cobra provides a few options for the default `completion` command. To configure such options you must set
|
||||
the `CompletionOptions` field on the *root* command.
|
||||
|
||||
To tell Cobra *not* to provide the default `completion` command:
|
||||
```
|
||||
rootCmd.CompletionOptions.DisableDefaultCmd = true
|
||||
```
|
||||
|
||||
To tell Cobra to mark the default `completion` command as *hidden*:
|
||||
```
|
||||
rootCmd.CompletionOptions.HiddenDefaultCmd = true
|
||||
```
|
||||
|
||||
To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:
|
||||
```
|
||||
rootCmd.CompletionOptions.DisableNoDescFlag = true
|
||||
```
|
||||
|
||||
To tell Cobra to completely disable descriptions for completions:
|
||||
```
|
||||
rootCmd.CompletionOptions.DisableDescriptions = true
|
||||
```
|
||||
|
||||
# Customizing completions
|
||||
|
||||
The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.
|
||||
|
||||
## Completion of nouns
|
||||
|
||||
### Static completion of nouns
|
||||
|
||||
Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field.
|
||||
For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them.
|
||||
Some simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs = []string{ "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
Short: "Display one or many resources",
|
||||
Long: get_long,
|
||||
Example: get_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
cobra.CheckErr(RunGet(f, out, cmd, args))
|
||||
},
|
||||
ValidArgs: validArgs,
|
||||
}
|
||||
```
|
||||
|
||||
Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:
|
||||
|
||||
```bash
|
||||
$ kubectl get [tab][tab]
|
||||
node pod replicationcontroller service
|
||||
```
|
||||
|
||||
#### Aliases for nouns
|
||||
|
||||
If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go
|
||||
argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
ValidArgs: validArgs,
|
||||
ArgAliases: argAliases
|
||||
}
|
||||
```
|
||||
|
||||
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
|
||||
the completion algorithm if entered manually, e.g. in:
|
||||
|
||||
```bash
|
||||
$ kubectl get rc [tab][tab]
|
||||
backend frontend database
|
||||
```
|
||||
|
||||
Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of
|
||||
replication controllers following `rc`.
|
||||
|
||||
### Dynamic completion of nouns
|
||||
|
||||
In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.
|
||||
Simplified code from `helm status` looks like:
|
||||
|
||||
```go
|
||||
cmd := &cobra.Command{
|
||||
Use: "status RELEASE_NAME",
|
||||
Short: "Display the status of the named release",
|
||||
Long: status_long,
|
||||
RunE: func(cmd *cobra.Command, args []string) {
|
||||
RunGet(args[0])
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) != 0 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
```
|
||||
Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
|
||||
Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like:
|
||||
|
||||
```bash
|
||||
$ helm status [tab][tab]
|
||||
harbor notary rook thanos
|
||||
```
|
||||
You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`
|
||||
```go
|
||||
// Indicates that the shell will perform its default behavior after completions
|
||||
// have been provided (this implies none of the other directives).
|
||||
ShellCompDirectiveDefault
|
||||
|
||||
// Indicates an error occurred and completions should be ignored.
|
||||
ShellCompDirectiveError
|
||||
|
||||
// Indicates that the shell should not add a space after the completion,
|
||||
// even if there is a single completion provided.
|
||||
ShellCompDirectiveNoSpace
|
||||
|
||||
// Indicates that the shell should not provide file completion even when
|
||||
// no completion is provided.
|
||||
ShellCompDirectiveNoFileComp
|
||||
|
||||
// Indicates that the returned completions should be used as file extension filters.
|
||||
// For example, to complete only files of the form *.json or *.yaml:
|
||||
// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt
|
||||
// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
|
||||
// is a shortcut to using this directive explicitly.
|
||||
//
|
||||
ShellCompDirectiveFilterFileExt
|
||||
|
||||
// Indicates that only directory names should be provided in file completion.
|
||||
// For example:
|
||||
// return nil, ShellCompDirectiveFilterDirs
|
||||
// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.
|
||||
//
|
||||
// To request directory names within another directory, the returned completions
|
||||
// should specify a single directory name within which to search. For example,
|
||||
// to complete directories within "themes/":
|
||||
// return []string{"themes"}, ShellCompDirectiveFilterDirs
|
||||
//
|
||||
ShellCompDirectiveFilterDirs
|
||||
```
|
||||
|
||||
***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.
|
||||
|
||||
#### Debugging
|
||||
|
||||
Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly:
|
||||
```bash
|
||||
$ helm __complete status har<ENTER>
|
||||
harbor
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command:
|
||||
```bash
|
||||
$ helm __complete status ""<ENTER>
|
||||
harbor
|
||||
notary
|
||||
rook
|
||||
thanos
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:
|
||||
```go
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and optionally prints to stderr.
|
||||
cobra.CompDebug(msg string, printToStdErr bool) {
|
||||
cobra.CompDebugln(msg string, printToStdErr bool)
|
||||
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and to stderr.
|
||||
cobra.CompError(msg string)
|
||||
cobra.CompErrorln(msg string)
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above.
|
||||
|
||||
## Completions for flags
|
||||
|
||||
### Mark flags as required
|
||||
|
||||
Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so:
|
||||
|
||||
```go
|
||||
cmd.MarkFlagRequired("pod")
|
||||
cmd.MarkFlagRequired("container")
|
||||
```
|
||||
|
||||
and you'll get something like
|
||||
|
||||
```bash
|
||||
$ kubectl exec [tab][tab]
|
||||
-c --container= -p --pod=
|
||||
```
|
||||
|
||||
### Specify dynamic flag completion
|
||||
|
||||
As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.
|
||||
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
|
||||
})
|
||||
```
|
||||
Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
|
||||
|
||||
```bash
|
||||
$ helm status --output [tab][tab]
|
||||
json table yaml
|
||||
```
|
||||
|
||||
#### Debugging
|
||||
|
||||
You can also easily debug your Go completion code for flags:
|
||||
```bash
|
||||
$ helm __complete status --output ""
|
||||
json
|
||||
table
|
||||
yaml
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above.
|
||||
|
||||
### Specify valid filename extensions for flags that take a filename
|
||||
|
||||
To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.MarkFlagFilename(flagName, "yaml", "json")
|
||||
```
|
||||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})
|
||||
```
|
||||
|
||||
### Limit flag completions to directory names
|
||||
|
||||
To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.MarkFlagDirname(flagName)
|
||||
```
|
||||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return nil, cobra.ShellCompDirectiveFilterDirs
|
||||
})
|
||||
```
|
||||
To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
})
|
||||
```
|
||||
### Descriptions for completions
|
||||
|
||||
Cobra provides support for completion descriptions. Such descriptions are supported for each shell
|
||||
(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)).
|
||||
For commands and flags, Cobra will provide the descriptions automatically, based on usage information.
|
||||
For example, using zsh:
|
||||
```
|
||||
$ helm s[tab]
|
||||
search -- search for a keyword in charts
|
||||
show -- show information of a chart
|
||||
status -- displays the status of the named release
|
||||
```
|
||||
while using fish:
|
||||
```
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
```
|
||||
|
||||
Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp
|
||||
}}
|
||||
```
|
||||
or
|
||||
```go
|
||||
ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
|
||||
```
|
||||
## Bash completions
|
||||
|
||||
### Dependencies
|
||||
|
||||
The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion))
|
||||
|
||||
### Aliases
|
||||
|
||||
You can also configure `bash` aliases for your program and they will also support completions.
|
||||
|
||||
```bash
|
||||
alias aliasname=origcommand
|
||||
complete -o default -F __start_origcommand aliasname
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$ aliasname <tab><tab>
|
||||
completion firstcommand secondcommand
|
||||
```
|
||||
### Bash legacy dynamic completions
|
||||
|
||||
For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
|
||||
Please refer to [Bash Completions](bash_completions.md) for details.
|
||||
|
||||
### Bash completion V2
|
||||
|
||||
Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling
|
||||
`GenBashCompletion()` or `GenBashCompletionFile()`.
|
||||
|
||||
A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or
|
||||
`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion
|
||||
(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion
|
||||
solution described in this document.
|
||||
Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash
|
||||
completion V2 solution which provides the following extra features:
|
||||
- Supports completion descriptions (like the other shells)
|
||||
- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines)
|
||||
- Streamlined user experience thanks to a completion behavior aligned with the other shells
|
||||
|
||||
`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()`
|
||||
you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra
|
||||
will provide the description automatically based on usage information. You can choose to make this option configurable by
|
||||
your users.
|
||||
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab][tab]
|
||||
search (search for a keyword in charts) status (display the status of the named release)
|
||||
show (show information of a chart)
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab][tab]
|
||||
search show status
|
||||
```
|
||||
**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.
|
||||
## Zsh completions
|
||||
|
||||
Cobra supports native zsh completion generated from the root `cobra.Command`.
|
||||
The generated completion script should be put somewhere in your `$fpath` and be named
|
||||
`_<yourProgram>`. You will need to start a new shell for the completions to become available.
|
||||
|
||||
Zsh supports descriptions for completions. Cobra will provide the description automatically,
|
||||
based on usage information. Cobra provides a way to completely disable such descriptions by
|
||||
using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make
|
||||
this a configurable option to your users.
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab]
|
||||
search -- search for a keyword in charts
|
||||
show -- show information of a chart
|
||||
status -- displays the status of the named release
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
|
||||
### Zsh completions standardization
|
||||
|
||||
Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced.
|
||||
Please refer to [Zsh Completions](zsh_completions.md) for details.
|
||||
|
||||
## fish completions
|
||||
|
||||
Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
* The following flag completion annotations are not supported and will be ignored for `fish`:
|
||||
* `BashCompFilenameExt` (filtering by file extension)
|
||||
* `BashCompSubdirsInDir` (filtering by directory)
|
||||
* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`:
|
||||
* `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
|
||||
* `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
|
||||
* Similarly, the following completion directives are not supported and will be ignored for `fish`:
|
||||
* `ShellCompDirectiveFilterFileExt` (filtering by file extension)
|
||||
* `ShellCompDirectiveFilterDirs` (filtering by directory)
|
||||
|
||||
## PowerShell completions
|
||||
|
||||
Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
|
||||
The script is designed to support all three PowerShell completion modes:
|
||||
|
||||
* TabCompleteNext (default windows style - on each key press the next option is displayed)
|
||||
* Complete (works like bash)
|
||||
* MenuComplete (works like zsh)
|
||||
|
||||
You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.
|
||||
|
||||
Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
|
||||
|
||||
```
|
||||
# With descriptions and Mode 'Complete'
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
|
||||
# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
|
||||
search for a keyword in charts
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
### Aliases
|
||||
|
||||
You can also configure `powershell` aliases for your program and they will also support completions.
|
||||
|
||||
```
|
||||
$ sal aliasname origcommand
|
||||
$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$ aliasname <tab>
|
||||
completion firstcommand secondcommand
|
||||
```
|
||||
The name of the completer block variable is of the form `$__<programName>CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
* The following flag completion annotations are not supported and will be ignored for `powershell`:
|
||||
* `BashCompFilenameExt` (filtering by file extension)
|
||||
* `BashCompSubdirsInDir` (filtering by directory)
|
||||
* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:
|
||||
* `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
|
||||
* `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
|
||||
* Similarly, the following completion directives are not supported and will be ignored for `powershell`:
|
||||
* `ShellCompDirectiveFilterFileExt` (filtering by file extension)
|
||||
* `ShellCompDirectiveFilterDirs` (filtering by directory)
|
||||
695
src/cmd/linuxkit/vendor/github.com/spf13/cobra/user_guide.md
generated
vendored
Normal file
695
src/cmd/linuxkit/vendor/github.com/spf13/cobra/user_guide.md
generated
vendored
Normal file
@@ -0,0 +1,695 @@
|
||||
# User Guide
|
||||
|
||||
While you are welcome to provide your own organization, typically a Cobra-based
|
||||
application will follow the following organizational structure:
|
||||
|
||||
```
|
||||
▾ appName/
|
||||
▾ cmd/
|
||||
add.go
|
||||
your.go
|
||||
commands.go
|
||||
here.go
|
||||
main.go
|
||||
```
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
## Using the Cobra Generator
|
||||
|
||||
Cobra-CLI is its own program that will create your application and add any
|
||||
commands you want. It's the easiest way to incorporate Cobra into your application.
|
||||
|
||||
For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
|
||||
|
||||
## Using the Cobra Library
|
||||
|
||||
To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
|
||||
You will optionally provide additional commands as you see fit.
|
||||
|
||||
### Create rootCmd
|
||||
|
||||
Cobra doesn't require any special constructors. Simply create your commands.
|
||||
|
||||
Ideally you place this in app/cmd/root.go:
|
||||
|
||||
```go
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "hugo",
|
||||
Short: "Hugo is a very fast static site generator",
|
||||
Long: `A Fast and Flexible Static Site Generator built with
|
||||
love by spf13 and friends in Go.
|
||||
Complete documentation is available at https://gohugo.io/documentation/`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// Do Stuff Here
|
||||
},
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You will additionally define flags and handle configuration in your init() function.
|
||||
|
||||
For example cmd/root.go:
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
// Used for flags.
|
||||
cfgFile string
|
||||
userLicense string
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "cobra-cli",
|
||||
Short: "A generator for Cobra based Applications",
|
||||
Long: `Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.`,
|
||||
}
|
||||
)
|
||||
|
||||
// Execute executes the root command.
|
||||
func Execute() error {
|
||||
return rootCmd.Execute()
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
|
||||
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
|
||||
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
|
||||
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
|
||||
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
|
||||
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
|
||||
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.SetDefault("license", "apache")
|
||||
|
||||
rootCmd.AddCommand(addCmd)
|
||||
rootCmd.AddCommand(initCmd)
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Find home directory.
|
||||
home, err := os.UserHomeDir()
|
||||
cobra.CheckErr(err)
|
||||
|
||||
// Search config in home directory with name ".cobra" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigType("yaml")
|
||||
viper.SetConfigName(".cobra")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv()
|
||||
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Create your main.go
|
||||
|
||||
With the root command you need to have your main function execute it.
|
||||
Execute should be run on the root for clarity, though it can be called on any command.
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
### Create additional commands
|
||||
|
||||
Additional commands can be defined and typically are each given their own file
|
||||
inside of the cmd/ directory.
|
||||
|
||||
If you wanted to create a version command you would create cmd/version.go and
|
||||
populate it with the following:
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number of Hugo",
|
||||
Long: `All software has versions. This is Hugo's`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Returning and handling errors
|
||||
|
||||
If you wish to return an error to the caller of a command, `RunE` can be used.
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(tryCmd)
|
||||
}
|
||||
|
||||
var tryCmd = &cobra.Command{
|
||||
Use: "try",
|
||||
Short: "Try and possibly fail at something",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if err := someFunc(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The error can then be caught at the execute function call.
|
||||
|
||||
## Working with Flags
|
||||
|
||||
Flags provide modifiers to control how the action command operates.
|
||||
|
||||
### Assign flags to a command
|
||||
|
||||
Since the flags are defined and used in different locations, we need to
|
||||
define a variable outside with the correct scope to assign the flag to
|
||||
work with.
|
||||
|
||||
```go
|
||||
var Verbose bool
|
||||
var Source string
|
||||
```
|
||||
|
||||
There are two different approaches to assign a flag.
|
||||
|
||||
### Persistent Flags
|
||||
|
||||
A flag can be 'persistent', meaning that this flag will be available to the
|
||||
command it's assigned to as well as every command under that command. For
|
||||
global flags, assign a flag as a persistent flag on the root.
|
||||
|
||||
```go
|
||||
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
|
||||
```
|
||||
|
||||
### Local Flags
|
||||
|
||||
A flag can also be assigned locally, which will only apply to that specific command.
|
||||
|
||||
```go
|
||||
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
|
||||
```
|
||||
|
||||
### Local Flag on Parent Commands
|
||||
|
||||
By default, Cobra only parses local flags on the target command, and any local flags on
|
||||
parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will
|
||||
parse local flags on each command before executing the target command.
|
||||
|
||||
```go
|
||||
command := cobra.Command{
|
||||
Use: "print [OPTIONS] [COMMANDS]",
|
||||
TraverseChildren: true,
|
||||
}
|
||||
```
|
||||
|
||||
### Bind Flags with Config
|
||||
|
||||
You can also bind your flags with [viper](https://github.com/spf13/viper):
|
||||
```go
|
||||
var author string
|
||||
|
||||
func init() {
|
||||
rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
|
||||
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the persistent flag `author` is bound with `viper`.
|
||||
**Note**: the variable `author` will not be set to the value from config,
|
||||
when the `--author` flag is provided by user.
|
||||
|
||||
More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
|
||||
|
||||
### Required flags
|
||||
|
||||
Flags are optional by default. If instead you wish your command to report an error
|
||||
when a flag has not been set, mark it as required:
|
||||
```go
|
||||
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
|
||||
rootCmd.MarkFlagRequired("region")
|
||||
```
|
||||
|
||||
Or, for persistent flags:
|
||||
```go
|
||||
rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
|
||||
rootCmd.MarkPersistentFlagRequired("region")
|
||||
```
|
||||
|
||||
### Flag Groups
|
||||
|
||||
If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then
|
||||
Cobra can enforce that requirement:
|
||||
```go
|
||||
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
|
||||
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
|
||||
rootCmd.MarkFlagsRequiredTogether("username", "password")
|
||||
```
|
||||
|
||||
You can also prevent different flags from being provided together if they represent mutually
|
||||
exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:
|
||||
```go
|
||||
rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")
|
||||
rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")
|
||||
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
|
||||
```
|
||||
|
||||
In both of these cases:
|
||||
- both local and persistent flags can be used
|
||||
- **NOTE:** the group is only enforced on commands where every flag is defined
|
||||
- a flag may appear in multiple groups
|
||||
- a group may contain any number of flags
|
||||
|
||||
## Positional and Custom Arguments
|
||||
|
||||
Validation of positional arguments can be specified using the `Args` field of `Command`.
|
||||
The following validators are built in:
|
||||
|
||||
- Number of arguments:
|
||||
- `NoArgs` - report an error if there are any positional args.
|
||||
- `ArbitraryArgs` - accept any number of args.
|
||||
- `MinimumNArgs(int)` - report an error if less than N positional args are provided.
|
||||
- `MaximumNArgs(int)` - report an error if more than N positional args are provided.
|
||||
- `ExactArgs(int)` - report an error if there are not exactly N positional args.
|
||||
- `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.
|
||||
- Content of the arguments:
|
||||
- `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args.
|
||||
|
||||
If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.
|
||||
|
||||
Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.
|
||||
For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional
|
||||
args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as
|
||||
shown below:
|
||||
|
||||
```go
|
||||
var cmd = &cobra.Command{
|
||||
Short: "hello",
|
||||
Args: MatchAll(ExactArgs(2), OnlyValidArgs),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hello, World!")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.
|
||||
For example:
|
||||
|
||||
```go
|
||||
var cmd = &cobra.Command{
|
||||
Short: "hello",
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
// Optionally run one of the validators provided by cobra
|
||||
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
// Run the custom validation logic
|
||||
if myapp.IsValidColor(args[0]) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid color specified: %s", args[0])
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hello, World!")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
In the example below, we have defined three commands. Two are at the top level
|
||||
and one (cmdTimes) is a child of one of the top commands. In this case the root
|
||||
is not executable, meaning that a subcommand is required. This is accomplished
|
||||
by not providing a 'Run' for the 'rootCmd'.
|
||||
|
||||
We have only defined one flag for a single command.
|
||||
|
||||
More documentation about flags is available at https://github.com/spf13/pflag
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var echoTimes int
|
||||
|
||||
var cmdPrint = &cobra.Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `print is for printing anything back to the screen.
|
||||
For many years people have printed back to the screen.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Print: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdEcho = &cobra.Command{
|
||||
Use: "echo [string to echo]",
|
||||
Short: "Echo anything to the screen",
|
||||
Long: `echo is for echoing anything back.
|
||||
Echo works a lot like print, except it has a child command.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Echo: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdTimes = &cobra.Command{
|
||||
Use: "times [string to echo]",
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: `echo things multiple times back to the user by providing
|
||||
a count and a string.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
for i := 0; i < echoTimes; i++ {
|
||||
fmt.Println("Echo: " + strings.Join(args, " "))
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
|
||||
|
||||
var rootCmd = &cobra.Command{Use: "app"}
|
||||
rootCmd.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).
|
||||
|
||||
## Help Command
|
||||
|
||||
Cobra automatically adds a help command to your application when you have subcommands.
|
||||
This will be called when a user runs 'app help'. Additionally, help will also
|
||||
support all other commands as input. Say, for instance, you have a command called
|
||||
'create' without any additional configuration; Cobra will work when 'app help
|
||||
create' is called. Every command will automatically have the '--help' flag added.
|
||||
|
||||
### Example
|
||||
|
||||
The following output is automatically generated by Cobra. Nothing beyond the
|
||||
command and flag definitions are needed.
|
||||
|
||||
$ cobra-cli help
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.
|
||||
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
|
||||
Use "cobra-cli [command] --help" for more information about a command.
|
||||
|
||||
|
||||
Help is just a command like any other. There is no special logic or behavior
|
||||
around it. In fact, you can provide your own if you want.
|
||||
|
||||
### Grouping commands in help
|
||||
|
||||
Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly
|
||||
defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element
|
||||
of that subcommand. The groups will appear in the help output in the same order as they are defined using different
|
||||
calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using
|
||||
`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.
|
||||
|
||||
### Defining your own help
|
||||
|
||||
You can provide your own Help command or your own template for the default command to use
|
||||
with the following functions:
|
||||
|
||||
```go
|
||||
cmd.SetHelpCommand(cmd *Command)
|
||||
cmd.SetHelpFunc(f func(*Command, []string))
|
||||
cmd.SetHelpTemplate(s string)
|
||||
```
|
||||
|
||||
The latter two will also apply to any children commands.
|
||||
|
||||
## Usage Message
|
||||
|
||||
When the user provides an invalid flag or invalid command, Cobra responds by
|
||||
showing the user the 'usage'.
|
||||
|
||||
### Example
|
||||
You may recognize this from the help above. That's because the default help
|
||||
embeds the usage as part of its output.
|
||||
|
||||
$ cobra-cli --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra-cli [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra-cli
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration
|
||||
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
|
||||
### Defining your own usage
|
||||
You can provide your own usage function or template for Cobra to use.
|
||||
Like help, the function and template are overridable through public methods:
|
||||
|
||||
```go
|
||||
cmd.SetUsageFunc(f func(*Command) error)
|
||||
cmd.SetUsageTemplate(s string)
|
||||
```
|
||||
|
||||
## Version Flag
|
||||
|
||||
Cobra adds a top-level '--version' flag if the Version field is set on the root command.
|
||||
Running an application with the '--version' flag will print the version to stdout using
|
||||
the version template. The template can be customized using the
|
||||
`cmd.SetVersionTemplate(s string)` function.
|
||||
|
||||
## PreRun and PostRun Hooks
|
||||
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
- `Run`
|
||||
- `PostRun`
|
||||
- `PersistentPostRun`
|
||||
|
||||
An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "root [sub]",
|
||||
Short: "My root command",
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
|
||||
},
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
var subCmd = &cobra.Command{
|
||||
Use: "sub [no options!]",
|
||||
Short: "My subcommand",
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
rootCmd.AddCommand(subCmd)
|
||||
|
||||
rootCmd.SetArgs([]string{""})
|
||||
rootCmd.Execute()
|
||||
fmt.Println()
|
||||
rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
Inside rootCmd PersistentPreRun with args: []
|
||||
Inside rootCmd PreRun with args: []
|
||||
Inside rootCmd Run with args: []
|
||||
Inside rootCmd PostRun with args: []
|
||||
Inside rootCmd PersistentPostRun with args: []
|
||||
|
||||
Inside rootCmd PersistentPreRun with args: [arg1 arg2]
|
||||
Inside subCmd PreRun with args: [arg1 arg2]
|
||||
Inside subCmd Run with args: [arg1 arg2]
|
||||
Inside subCmd PostRun with args: [arg1 arg2]
|
||||
Inside subCmd PersistentPostRun with args: [arg1 arg2]
|
||||
```
|
||||
|
||||
## Suggestions when "unknown command" happens
|
||||
|
||||
Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
|
||||
|
||||
```
|
||||
$ hugo srever
|
||||
Error: unknown command "srever" for "hugo"
|
||||
|
||||
Did you mean this?
|
||||
server
|
||||
|
||||
Run 'hugo --help' for usage.
|
||||
```
|
||||
|
||||
Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
|
||||
|
||||
If you need to disable suggestions or tweak the string distance in your command, use:
|
||||
|
||||
```go
|
||||
command.DisableSuggestions = true
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```go
|
||||
command.SuggestionsMinimumDistance = 1
|
||||
```
|
||||
|
||||
You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which
|
||||
you don't want aliases. Example:
|
||||
|
||||
```
|
||||
$ kubectl remove
|
||||
Error: unknown command "remove" for "kubectl"
|
||||
|
||||
Did you mean this?
|
||||
delete
|
||||
|
||||
Run 'kubectl help' for usage.
|
||||
```
|
||||
|
||||
## Generating documentation for your command
|
||||
|
||||
Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).
|
||||
|
||||
## Generating shell completions
|
||||
|
||||
Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md).
|
||||
|
||||
## Providing Active Help
|
||||
|
||||
Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md).
|
||||
301
src/cmd/linuxkit/vendor/github.com/spf13/cobra/zsh_completions.go
generated
vendored
Normal file
301
src/cmd/linuxkit/vendor/github.com/spf13/cobra/zsh_completions.go
generated
vendored
Normal file
@@ -0,0 +1,301 @@
|
||||
// Copyright 2013-2022 The Cobra Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// GenZshCompletionFile generates zsh completion file including descriptions.
|
||||
func (c *Command) GenZshCompletionFile(filename string) error {
|
||||
return c.genZshCompletionFile(filename, true)
|
||||
}
|
||||
|
||||
// GenZshCompletion generates zsh completion file including descriptions
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenZshCompletion(w io.Writer) error {
|
||||
return c.genZshCompletion(w, true)
|
||||
}
|
||||
|
||||
// GenZshCompletionFileNoDesc generates zsh completion file without descriptions.
|
||||
func (c *Command) GenZshCompletionFileNoDesc(filename string) error {
|
||||
return c.genZshCompletionFile(filename, false)
|
||||
}
|
||||
|
||||
// GenZshCompletionNoDesc generates zsh completion file without descriptions
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenZshCompletionNoDesc(w io.Writer) error {
|
||||
return c.genZshCompletion(w, false)
|
||||
}
|
||||
|
||||
// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was
|
||||
// not consistent with Bash completion. It has therefore been disabled.
|
||||
// Instead, when no other completion is specified, file completion is done by
|
||||
// default for every argument. One can disable file completion on a per-argument
|
||||
// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp.
|
||||
// To achieve file extension filtering, one can use ValidArgsFunction and
|
||||
// ShellCompDirectiveFilterFileExt.
|
||||
//
|
||||
// Deprecated
|
||||
func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore
|
||||
// been disabled.
|
||||
// To achieve the same behavior across all shells, one can use
|
||||
// ValidArgs (for the first argument only) or ValidArgsFunction for
|
||||
// any argument (can include the first one also).
|
||||
//
|
||||
// Deprecated
|
||||
func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.genZshCompletion(outFile, includeDesc)
|
||||
}
|
||||
|
||||
func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {
|
||||
buf := new(bytes.Buffer)
|
||||
genZshComp(buf, c.Name(), includeDesc)
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s
|
||||
|
||||
# zsh completion for %-36[1]s -*- shell-script -*-
|
||||
|
||||
__%[1]s_debug()
|
||||
{
|
||||
local file="$BASH_COMP_DEBUG_FILE"
|
||||
if [[ -n ${file} ]]; then
|
||||
echo "$*" >> "${file}"
|
||||
fi
|
||||
}
|
||||
|
||||
_%[1]s()
|
||||
{
|
||||
local shellCompDirectiveError=%[3]d
|
||||
local shellCompDirectiveNoSpace=%[4]d
|
||||
local shellCompDirectiveNoFileComp=%[5]d
|
||||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
|
||||
local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace
|
||||
local -a completions
|
||||
|
||||
__%[1]s_debug "\n========= starting completion logic =========="
|
||||
__%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"
|
||||
|
||||
# The user could have moved the cursor backwards on the command-line.
|
||||
# We need to trigger completion from the $CURRENT location, so we need
|
||||
# to truncate the command-line ($words) up to the $CURRENT location.
|
||||
# (We cannot use $CURSOR as its value does not work when a command is an alias.)
|
||||
words=("${=words[1,CURRENT]}")
|
||||
__%[1]s_debug "Truncated words[*]: ${words[*]},"
|
||||
|
||||
lastParam=${words[-1]}
|
||||
lastChar=${lastParam[-1]}
|
||||
__%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"
|
||||
|
||||
# For zsh, when completing a flag with an = (e.g., %[1]s -n=<TAB>)
|
||||
# completions must be prefixed with the flag
|
||||
setopt local_options BASH_REMATCH
|
||||
if [[ "${lastParam}" =~ '-.*=' ]]; then
|
||||
# We are dealing with a flag with an =
|
||||
flagPrefix="-P ${BASH_REMATCH}"
|
||||
fi
|
||||
|
||||
# Prepare the command to obtain completions
|
||||
requestComp="${words[1]} %[2]s ${words[2,-1]}"
|
||||
if [ "${lastChar}" = "" ]; then
|
||||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go completion code.
|
||||
__%[1]s_debug "Adding extra empty parameter"
|
||||
requestComp="${requestComp} \"\""
|
||||
fi
|
||||
|
||||
__%[1]s_debug "About to call: eval ${requestComp}"
|
||||
|
||||
# Use eval to handle any environment variables and such
|
||||
out=$(eval ${requestComp} 2>/dev/null)
|
||||
__%[1]s_debug "completion output: ${out}"
|
||||
|
||||
# Extract the directive integer following a : from the last line
|
||||
local lastLine
|
||||
while IFS='\n' read -r line; do
|
||||
lastLine=${line}
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
__%[1]s_debug "last line: ${lastLine}"
|
||||
|
||||
if [ "${lastLine[1]}" = : ]; then
|
||||
directive=${lastLine[2,-1]}
|
||||
# Remove the directive including the : and the newline
|
||||
local suffix
|
||||
(( suffix=${#lastLine}+2))
|
||||
out=${out[1,-$suffix]}
|
||||
else
|
||||
# There is no directive specified. Leave $out as is.
|
||||
__%[1]s_debug "No directive found. Setting do default"
|
||||
directive=0
|
||||
fi
|
||||
|
||||
__%[1]s_debug "directive: ${directive}"
|
||||
__%[1]s_debug "completions: ${out}"
|
||||
__%[1]s_debug "flagPrefix: ${flagPrefix}"
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
|
||||
__%[1]s_debug "Completion received error. Ignoring completions."
|
||||
return
|
||||
fi
|
||||
|
||||
local activeHelpMarker="%[8]s"
|
||||
local endIndex=${#activeHelpMarker}
|
||||
local startIndex=$((${#activeHelpMarker}+1))
|
||||
local hasActiveHelp=0
|
||||
while IFS='\n' read -r comp; do
|
||||
# Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
|
||||
if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
|
||||
__%[1]s_debug "ActiveHelp found: $comp"
|
||||
comp="${comp[$startIndex,-1]}"
|
||||
if [ -n "$comp" ]; then
|
||||
compadd -x "${comp}"
|
||||
__%[1]s_debug "ActiveHelp will need delimiter"
|
||||
hasActiveHelp=1
|
||||
fi
|
||||
|
||||
continue
|
||||
fi
|
||||
|
||||
if [ -n "$comp" ]; then
|
||||
# If requested, completions are returned with a description.
|
||||
# The description is preceded by a TAB character.
|
||||
# For zsh's _describe, we need to use a : instead of a TAB.
|
||||
# We first need to escape any : as part of the completion itself.
|
||||
comp=${comp//:/\\:}
|
||||
|
||||
local tab="$(printf '\t')"
|
||||
comp=${comp//$tab/:}
|
||||
|
||||
__%[1]s_debug "Adding completion: ${comp}"
|
||||
completions+=${comp}
|
||||
lastComp=$comp
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
|
||||
# Add a delimiter after the activeHelp statements, but only if:
|
||||
# - there are completions following the activeHelp statements, or
|
||||
# - file completion will be performed (so there will be choices after the activeHelp)
|
||||
if [ $hasActiveHelp -eq 1 ]; then
|
||||
if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
|
||||
__%[1]s_debug "Adding activeHelp delimiter"
|
||||
compadd -x "--"
|
||||
hasActiveHelp=0
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
|
||||
__%[1]s_debug "Activating nospace."
|
||||
noSpace="-S ''"
|
||||
fi
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local filteringCmd
|
||||
filteringCmd='_files'
|
||||
for filter in ${completions[@]}; do
|
||||
if [ ${filter[1]} != '*' ]; then
|
||||
# zsh requires a glob pattern to do file filtering
|
||||
filter="\*.$filter"
|
||||
fi
|
||||
filteringCmd+=" -g $filter"
|
||||
done
|
||||
filteringCmd+=" ${flagPrefix}"
|
||||
|
||||
__%[1]s_debug "File filtering command: $filteringCmd"
|
||||
_arguments '*:filename:'"$filteringCmd"
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
|
||||
# File completion for directories only
|
||||
local subdir
|
||||
subdir="${completions[1]}"
|
||||
if [ -n "$subdir" ]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
pushd "${subdir}" >/dev/null 2>&1
|
||||
else
|
||||
__%[1]s_debug "Listing directories in ."
|
||||
fi
|
||||
|
||||
local result
|
||||
_arguments '*:dirname:_files -/'" ${flagPrefix}"
|
||||
result=$?
|
||||
if [ -n "$subdir" ]; then
|
||||
popd >/dev/null 2>&1
|
||||
fi
|
||||
return $result
|
||||
else
|
||||
__%[1]s_debug "Calling _describe"
|
||||
if eval _describe "completions" completions $flagPrefix $noSpace; then
|
||||
__%[1]s_debug "_describe found some completions"
|
||||
|
||||
# Return the success of having called _describe
|
||||
return 0
|
||||
else
|
||||
__%[1]s_debug "_describe did not find completions."
|
||||
__%[1]s_debug "Checking if we should do file completion."
|
||||
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
|
||||
__%[1]s_debug "deactivating file completion"
|
||||
|
||||
# We must return an error code here to let zsh know that there were no
|
||||
# completions found by _describe; this is what will trigger other
|
||||
# matching algorithms to attempt to find completions.
|
||||
# For example zsh can match letters in the middle of words.
|
||||
return 1
|
||||
else
|
||||
# Perform file completion
|
||||
__%[1]s_debug "Activating file completion"
|
||||
|
||||
# We must return the result of this command, so it must be the
|
||||
# last command, or else we must store its result to return it.
|
||||
_arguments '*:filename:_files'" ${flagPrefix}"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# don't run the completion function when being source-ed or eval-ed
|
||||
if [ "$funcstack[1]" = "_%[1]s" ]; then
|
||||
_%[1]s
|
||||
fi
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs,
|
||||
activeHelpMarker))
|
||||
}
|
||||
48
src/cmd/linuxkit/vendor/github.com/spf13/cobra/zsh_completions.md
generated
vendored
Normal file
48
src/cmd/linuxkit/vendor/github.com/spf13/cobra/zsh_completions.md
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
## Generating Zsh Completion For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
||||
## Zsh completions standardization
|
||||
|
||||
Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced.
|
||||
|
||||
### Deprecation summary
|
||||
|
||||
See further below for more details on these deprecations.
|
||||
|
||||
* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored.
|
||||
* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored.
|
||||
* Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`.
|
||||
* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored.
|
||||
* Instead use `ValidArgsFunction`.
|
||||
|
||||
### Behavioral changes
|
||||
|
||||
**Noun completion**
|
||||
|Old behavior|New behavior|
|
||||
|---|---|
|
||||
|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis|
|
||||
|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`|
|
||||
`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored|
|
||||
|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)|
|
||||
|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior|
|
||||
|
||||
**Flag-value completion**
|
||||
|
||||
|Old behavior|New behavior|
|
||||
|---|---|
|
||||
|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion|
|
||||
|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored|
|
||||
|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)|
|
||||
|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells|
|
||||
|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`|
|
||||
|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`|
|
||||
|
||||
**Improvements**
|
||||
|
||||
* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`)
|
||||
* File completion by default if no other completions found
|
||||
* Handling of required flags
|
||||
* File extension filtering no longer mutually exclusive with bash usage
|
||||
* Completion of directory names *within* another directory
|
||||
* Support for `=` form of flags
|
||||
2
src/cmd/linuxkit/vendor/github.com/spf13/pflag/.gitignore
generated
vendored
Normal file
2
src/cmd/linuxkit/vendor/github.com/spf13/pflag/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
.idea/*
|
||||
|
||||
22
src/cmd/linuxkit/vendor/github.com/spf13/pflag/.travis.yml
generated
vendored
Normal file
22
src/cmd/linuxkit/vendor/github.com/spf13/pflag/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
sudo: false
|
||||
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.9.x
|
||||
- 1.10.x
|
||||
- 1.11.x
|
||||
- tip
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
|
||||
install:
|
||||
- go get golang.org/x/lint/golint
|
||||
- export PATH=$GOPATH/bin:$PATH
|
||||
- go install ./...
|
||||
|
||||
script:
|
||||
- verify/all.sh -v
|
||||
- go test ./...
|
||||
28
src/cmd/linuxkit/vendor/github.com/spf13/pflag/LICENSE
generated
vendored
Normal file
28
src/cmd/linuxkit/vendor/github.com/spf13/pflag/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
Copyright (c) 2012 Alex Ogier. All rights reserved.
|
||||
Copyright (c) 2012 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
296
src/cmd/linuxkit/vendor/github.com/spf13/pflag/README.md
generated
vendored
Normal file
296
src/cmd/linuxkit/vendor/github.com/spf13/pflag/README.md
generated
vendored
Normal file
@@ -0,0 +1,296 @@
|
||||
[](https://travis-ci.org/spf13/pflag)
|
||||
[](https://goreportcard.com/report/github.com/spf13/pflag)
|
||||
[](https://godoc.org/github.com/spf13/pflag)
|
||||
|
||||
## Description
|
||||
|
||||
pflag is a drop-in replacement for Go's flag package, implementing
|
||||
POSIX/GNU-style --flags.
|
||||
|
||||
pflag is compatible with the [GNU extensions to the POSIX recommendations
|
||||
for command-line options][1]. For a more precise description, see the
|
||||
"Command-line flag syntax" section below.
|
||||
|
||||
[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
|
||||
|
||||
pflag is available under the same style of BSD license as the Go language,
|
||||
which can be found in the LICENSE file.
|
||||
|
||||
## Installation
|
||||
|
||||
pflag is available using the standard `go get` command.
|
||||
|
||||
Install by running:
|
||||
|
||||
go get github.com/spf13/pflag
|
||||
|
||||
Run tests by running:
|
||||
|
||||
go test github.com/spf13/pflag
|
||||
|
||||
## Usage
|
||||
|
||||
pflag is a drop-in replacement of Go's native flag package. If you import
|
||||
pflag under the name "flag" then all code should continue to function
|
||||
with no changes.
|
||||
|
||||
``` go
|
||||
import flag "github.com/spf13/pflag"
|
||||
```
|
||||
|
||||
There is one exception to this: if you directly instantiate the Flag struct
|
||||
there is one more field "Shorthand" that you will need to set.
|
||||
Most code never instantiates this struct directly, and instead uses
|
||||
functions such as String(), BoolVar(), and Var(), and is therefore
|
||||
unaffected.
|
||||
|
||||
Define flags using flag.String(), Bool(), Int(), etc.
|
||||
|
||||
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
|
||||
|
||||
``` go
|
||||
var ip *int = flag.Int("flagname", 1234, "help message for flagname")
|
||||
```
|
||||
|
||||
If you like, you can bind the flag to a variable using the Var() functions.
|
||||
|
||||
``` go
|
||||
var flagvar int
|
||||
func init() {
|
||||
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
|
||||
}
|
||||
```
|
||||
|
||||
Or you can create custom flags that satisfy the Value interface (with
|
||||
pointer receivers) and couple them to flag parsing by
|
||||
|
||||
``` go
|
||||
flag.Var(&flagVal, "name", "help message for flagname")
|
||||
```
|
||||
|
||||
For such flags, the default value is just the initial value of the variable.
|
||||
|
||||
After all flags are defined, call
|
||||
|
||||
``` go
|
||||
flag.Parse()
|
||||
```
|
||||
|
||||
to parse the command line into the defined flags.
|
||||
|
||||
Flags may then be used directly. If you're using the flags themselves,
|
||||
they are all pointers; if you bind to variables, they're values.
|
||||
|
||||
``` go
|
||||
fmt.Println("ip has value ", *ip)
|
||||
fmt.Println("flagvar has value ", flagvar)
|
||||
```
|
||||
|
||||
There are helper functions available to get the value stored in a Flag if you have a FlagSet but find
|
||||
it difficult to keep up with all of the pointers in your code.
|
||||
If you have a pflag.FlagSet with a flag called 'flagname' of type int you
|
||||
can use GetInt() to get the int value. But notice that 'flagname' must exist
|
||||
and it must be an int. GetString("flagname") will fail.
|
||||
|
||||
``` go
|
||||
i, err := flagset.GetInt("flagname")
|
||||
```
|
||||
|
||||
After parsing, the arguments after the flag are available as the
|
||||
slice flag.Args() or individually as flag.Arg(i).
|
||||
The arguments are indexed from 0 through flag.NArg()-1.
|
||||
|
||||
The pflag package also defines some new functions that are not in flag,
|
||||
that give one-letter shorthands for flags. You can use these by appending
|
||||
'P' to the name of any function that defines a flag.
|
||||
|
||||
``` go
|
||||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||
var flagvar bool
|
||||
func init() {
|
||||
flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
|
||||
}
|
||||
flag.VarP(&flagVal, "varname", "v", "help message")
|
||||
```
|
||||
|
||||
Shorthand letters can be used with single dashes on the command line.
|
||||
Boolean shorthand flags can be combined with other shorthand flags.
|
||||
|
||||
The default set of command-line flags is controlled by
|
||||
top-level functions. The FlagSet type allows one to define
|
||||
independent sets of flags, such as to implement subcommands
|
||||
in a command-line interface. The methods of FlagSet are
|
||||
analogous to the top-level functions for the command-line
|
||||
flag set.
|
||||
|
||||
## Setting no option default values for flags
|
||||
|
||||
After you create a flag it is possible to set the pflag.NoOptDefVal for
|
||||
the given flag. Doing this changes the meaning of the flag slightly. If
|
||||
a flag has a NoOptDefVal and the flag is set on the command line without
|
||||
an option the flag will be set to the NoOptDefVal. For example given:
|
||||
|
||||
``` go
|
||||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||
flag.Lookup("flagname").NoOptDefVal = "4321"
|
||||
```
|
||||
|
||||
Would result in something like
|
||||
|
||||
| Parsed Arguments | Resulting Value |
|
||||
| ------------- | ------------- |
|
||||
| --flagname=1357 | ip=1357 |
|
||||
| --flagname | ip=4321 |
|
||||
| [nothing] | ip=1234 |
|
||||
|
||||
## Command line flag syntax
|
||||
|
||||
```
|
||||
--flag // boolean flags, or flags with no option default values
|
||||
--flag x // only on flags without a default value
|
||||
--flag=x
|
||||
```
|
||||
|
||||
Unlike the flag package, a single dash before an option means something
|
||||
different than a double dash. Single dashes signify a series of shorthand
|
||||
letters for flags. All but the last shorthand letter must be boolean flags
|
||||
or a flag with a default value
|
||||
|
||||
```
|
||||
// boolean or flags where the 'no option default value' is set
|
||||
-f
|
||||
-f=true
|
||||
-abc
|
||||
but
|
||||
-b true is INVALID
|
||||
|
||||
// non-boolean and flags without a 'no option default value'
|
||||
-n 1234
|
||||
-n=1234
|
||||
-n1234
|
||||
|
||||
// mixed
|
||||
-abcs "hello"
|
||||
-absd="hello"
|
||||
-abcs1234
|
||||
```
|
||||
|
||||
Flag parsing stops after the terminator "--". Unlike the flag package,
|
||||
flags can be interspersed with arguments anywhere on the command line
|
||||
before this terminator.
|
||||
|
||||
Integer flags accept 1234, 0664, 0x1234 and may be negative.
|
||||
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
|
||||
TRUE, FALSE, True, False.
|
||||
Duration flags accept any input valid for time.ParseDuration.
|
||||
|
||||
## Mutating or "Normalizing" Flag names
|
||||
|
||||
It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.
|
||||
|
||||
**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag
|
||||
|
||||
``` go
|
||||
func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
from := []string{"-", "_"}
|
||||
to := "."
|
||||
for _, sep := range from {
|
||||
name = strings.Replace(name, sep, to, -1)
|
||||
}
|
||||
return pflag.NormalizedName(name)
|
||||
}
|
||||
|
||||
myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
```
|
||||
|
||||
**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name
|
||||
|
||||
``` go
|
||||
func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
switch name {
|
||||
case "old-flag-name":
|
||||
name = "new-flag-name"
|
||||
break
|
||||
}
|
||||
return pflag.NormalizedName(name)
|
||||
}
|
||||
|
||||
myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)
|
||||
```
|
||||
|
||||
## Deprecating a flag or its shorthand
|
||||
It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used.
|
||||
|
||||
**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead.
|
||||
```go
|
||||
// deprecate a flag by specifying its name and a usage message
|
||||
flags.MarkDeprecated("badflag", "please use --good-flag instead")
|
||||
```
|
||||
This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used.
|
||||
|
||||
**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n".
|
||||
```go
|
||||
// deprecate a flag shorthand by specifying its flag name and a usage message
|
||||
flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only")
|
||||
```
|
||||
This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used.
|
||||
|
||||
Note that usage message is essential here, and it should not be empty.
|
||||
|
||||
## Hidden flags
|
||||
It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text.
|
||||
|
||||
**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available.
|
||||
```go
|
||||
// hide a flag by specifying its name
|
||||
flags.MarkHidden("secretFlag")
|
||||
```
|
||||
|
||||
## Disable sorting of flags
|
||||
`pflag` allows you to disable sorting of flags for help and usage message.
|
||||
|
||||
**Example**:
|
||||
```go
|
||||
flags.BoolP("verbose", "v", false, "verbose output")
|
||||
flags.String("coolflag", "yeaah", "it's really cool flag")
|
||||
flags.Int("usefulflag", 777, "sometimes it's very useful")
|
||||
flags.SortFlags = false
|
||||
flags.PrintDefaults()
|
||||
```
|
||||
**Output**:
|
||||
```
|
||||
-v, --verbose verbose output
|
||||
--coolflag string it's really cool flag (default "yeaah")
|
||||
--usefulflag int sometimes it's very useful (default 777)
|
||||
```
|
||||
|
||||
|
||||
## Supporting Go flags when using pflag
|
||||
In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary
|
||||
to support flags defined by third-party dependencies (e.g. `golang/glog`).
|
||||
|
||||
**Example**: You want to add the Go flags to the `CommandLine` flagset
|
||||
```go
|
||||
import (
|
||||
goflag "flag"
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
var ip *int = flag.Int("flagname", 1234, "help message for flagname")
|
||||
|
||||
func main() {
|
||||
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
|
||||
flag.Parse()
|
||||
}
|
||||
```
|
||||
|
||||
## More info
|
||||
|
||||
You can see the full reference documentation of the pflag package
|
||||
[at godoc.org][3], or through go's standard documentation system by
|
||||
running `godoc -http=:6060` and browsing to
|
||||
[http://localhost:6060/pkg/github.com/spf13/pflag][2] after
|
||||
installation.
|
||||
|
||||
[2]: http://localhost:6060/pkg/github.com/spf13/pflag
|
||||
[3]: http://godoc.org/github.com/spf13/pflag
|
||||
94
src/cmd/linuxkit/vendor/github.com/spf13/pflag/bool.go
generated
vendored
Normal file
94
src/cmd/linuxkit/vendor/github.com/spf13/pflag/bool.go
generated
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
package pflag
|
||||
|
||||
import "strconv"
|
||||
|
||||
// optional interface to indicate boolean flags that can be
|
||||
// supplied without "=value" text
|
||||
type boolFlag interface {
|
||||
Value
|
||||
IsBoolFlag() bool
|
||||
}
|
||||
|
||||
// -- bool Value
|
||||
type boolValue bool
|
||||
|
||||
func newBoolValue(val bool, p *bool) *boolValue {
|
||||
*p = val
|
||||
return (*boolValue)(p)
|
||||
}
|
||||
|
||||
func (b *boolValue) Set(s string) error {
|
||||
v, err := strconv.ParseBool(s)
|
||||
*b = boolValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *boolValue) Type() string {
|
||||
return "bool"
|
||||
}
|
||||
|
||||
func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
|
||||
|
||||
func (b *boolValue) IsBoolFlag() bool { return true }
|
||||
|
||||
func boolConv(sval string) (interface{}, error) {
|
||||
return strconv.ParseBool(sval)
|
||||
}
|
||||
|
||||
// GetBool return the bool value of a flag with the given name
|
||||
func (f *FlagSet) GetBool(name string) (bool, error) {
|
||||
val, err := f.getFlagType(name, "bool", boolConv)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return val.(bool), nil
|
||||
}
|
||||
|
||||
// BoolVar defines a bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a bool variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
|
||||
f.BoolVarP(p, name, "", value, usage)
|
||||
}
|
||||
|
||||
// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
|
||||
flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage)
|
||||
flag.NoOptDefVal = "true"
|
||||
}
|
||||
|
||||
// BoolVar defines a bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a bool variable in which to store the value of the flag.
|
||||
func BoolVar(p *bool, name string, value bool, usage string) {
|
||||
BoolVarP(p, name, "", value, usage)
|
||||
}
|
||||
|
||||
// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
|
||||
flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage)
|
||||
flag.NoOptDefVal = "true"
|
||||
}
|
||||
|
||||
// Bool defines a bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a bool variable that stores the value of the flag.
|
||||
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
|
||||
return f.BoolP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
|
||||
p := new(bool)
|
||||
f.BoolVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Bool defines a bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a bool variable that stores the value of the flag.
|
||||
func Bool(name string, value bool, usage string) *bool {
|
||||
return BoolP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolP(name, shorthand string, value bool, usage string) *bool {
|
||||
b := CommandLine.BoolP(name, shorthand, value, usage)
|
||||
return b
|
||||
}
|
||||
185
src/cmd/linuxkit/vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
Normal file
185
src/cmd/linuxkit/vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
Normal file
@@ -0,0 +1,185 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- boolSlice Value
|
||||
type boolSliceValue struct {
|
||||
value *[]bool
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
|
||||
bsv := new(boolSliceValue)
|
||||
bsv.value = p
|
||||
*bsv.value = val
|
||||
return bsv
|
||||
}
|
||||
|
||||
// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
|
||||
// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
|
||||
func (s *boolSliceValue) Set(val string) error {
|
||||
|
||||
// remove all quote characters
|
||||
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
|
||||
|
||||
// read flag arguments with CSV parser
|
||||
boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse boolean values into slice
|
||||
out := make([]bool, 0, len(boolStrSlice))
|
||||
for _, boolStr := range boolStrSlice {
|
||||
b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
|
||||
s.changed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type returns a string that uniquely represents this flag's type.
|
||||
func (s *boolSliceValue) Type() string {
|
||||
return "boolSlice"
|
||||
}
|
||||
|
||||
// String defines a "native" format for this boolean slice flag value.
|
||||
func (s *boolSliceValue) String() string {
|
||||
|
||||
boolStrSlice := make([]string, len(*s.value))
|
||||
for i, b := range *s.value {
|
||||
boolStrSlice[i] = strconv.FormatBool(b)
|
||||
}
|
||||
|
||||
out, _ := writeAsCSV(boolStrSlice)
|
||||
|
||||
return "[" + out + "]"
|
||||
}
|
||||
|
||||
func (s *boolSliceValue) fromString(val string) (bool, error) {
|
||||
return strconv.ParseBool(val)
|
||||
}
|
||||
|
||||
func (s *boolSliceValue) toString(val bool) string {
|
||||
return strconv.FormatBool(val)
|
||||
}
|
||||
|
||||
func (s *boolSliceValue) Append(val string) error {
|
||||
i, err := s.fromString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*s.value = append(*s.value, i)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *boolSliceValue) Replace(val []string) error {
|
||||
out := make([]bool, len(val))
|
||||
for i, d := range val {
|
||||
var err error
|
||||
out[i], err = s.fromString(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
*s.value = out
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *boolSliceValue) GetSlice() []string {
|
||||
out := make([]string, len(*s.value))
|
||||
for i, d := range *s.value {
|
||||
out[i] = s.toString(d)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func boolSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Empty string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []bool{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]bool, len(ss))
|
||||
for i, t := range ss {
|
||||
var err error
|
||||
out[i], err = strconv.ParseBool(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetBoolSlice returns the []bool value of a flag with the given name.
|
||||
func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
|
||||
val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
|
||||
if err != nil {
|
||||
return []bool{}, err
|
||||
}
|
||||
return val.([]bool), nil
|
||||
}
|
||||
|
||||
// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
||||
f.VarP(newBoolSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
||||
f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
||||
func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
||||
CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
||||
CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
||||
func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
|
||||
p := []bool{}
|
||||
f.BoolSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
||||
p := []bool{}
|
||||
f.BoolSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
||||
func BoolSlice(name string, value []bool, usage string) *[]bool {
|
||||
return CommandLine.BoolSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
||||
return CommandLine.BoolSliceP(name, shorthand, value, usage)
|
||||
}
|
||||
209
src/cmd/linuxkit/vendor/github.com/spf13/pflag/bytes.go
generated
vendored
Normal file
209
src/cmd/linuxkit/vendor/github.com/spf13/pflag/bytes.go
generated
vendored
Normal file
@@ -0,0 +1,209 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded
|
||||
type bytesHexValue []byte
|
||||
|
||||
// String implements pflag.Value.String.
|
||||
func (bytesHex bytesHexValue) String() string {
|
||||
return fmt.Sprintf("%X", []byte(bytesHex))
|
||||
}
|
||||
|
||||
// Set implements pflag.Value.Set.
|
||||
func (bytesHex *bytesHexValue) Set(value string) error {
|
||||
bin, err := hex.DecodeString(strings.TrimSpace(value))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*bytesHex = bin
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type implements pflag.Value.Type.
|
||||
func (*bytesHexValue) Type() string {
|
||||
return "bytesHex"
|
||||
}
|
||||
|
||||
func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue {
|
||||
*p = val
|
||||
return (*bytesHexValue)(p)
|
||||
}
|
||||
|
||||
func bytesHexConv(sval string) (interface{}, error) {
|
||||
|
||||
bin, err := hex.DecodeString(sval)
|
||||
|
||||
if err == nil {
|
||||
return bin, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
|
||||
}
|
||||
|
||||
// GetBytesHex return the []byte value of a flag with the given name
|
||||
func (f *FlagSet) GetBytesHex(name string) ([]byte, error) {
|
||||
val, err := f.getFlagType(name, "bytesHex", bytesHexConv)
|
||||
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
return val.([]byte), nil
|
||||
}
|
||||
|
||||
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
|
||||
// The argument p points to an []byte variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) {
|
||||
f.VarP(newBytesHexValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
|
||||
f.VarP(newBytesHexValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
|
||||
// The argument p points to an []byte variable in which to store the value of the flag.
|
||||
func BytesHexVar(p *[]byte, name string, value []byte, usage string) {
|
||||
CommandLine.VarP(newBytesHexValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
|
||||
CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BytesHex defines an []byte flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an []byte variable that stores the value of the flag.
|
||||
func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte {
|
||||
p := new([]byte)
|
||||
f.BytesHexVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
|
||||
p := new([]byte)
|
||||
f.BytesHexVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// BytesHex defines an []byte flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an []byte variable that stores the value of the flag.
|
||||
func BytesHex(name string, value []byte, usage string) *[]byte {
|
||||
return CommandLine.BytesHexP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
|
||||
return CommandLine.BytesHexP(name, shorthand, value, usage)
|
||||
}
|
||||
|
||||
// BytesBase64 adapts []byte for use as a flag. Value of flag is Base64 encoded
|
||||
type bytesBase64Value []byte
|
||||
|
||||
// String implements pflag.Value.String.
|
||||
func (bytesBase64 bytesBase64Value) String() string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(bytesBase64))
|
||||
}
|
||||
|
||||
// Set implements pflag.Value.Set.
|
||||
func (bytesBase64 *bytesBase64Value) Set(value string) error {
|
||||
bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*bytesBase64 = bin
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type implements pflag.Value.Type.
|
||||
func (*bytesBase64Value) Type() string {
|
||||
return "bytesBase64"
|
||||
}
|
||||
|
||||
func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value {
|
||||
*p = val
|
||||
return (*bytesBase64Value)(p)
|
||||
}
|
||||
|
||||
func bytesBase64ValueConv(sval string) (interface{}, error) {
|
||||
|
||||
bin, err := base64.StdEncoding.DecodeString(sval)
|
||||
if err == nil {
|
||||
return bin, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
|
||||
}
|
||||
|
||||
// GetBytesBase64 return the []byte value of a flag with the given name
|
||||
func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) {
|
||||
val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv)
|
||||
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
return val.([]byte), nil
|
||||
}
|
||||
|
||||
// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
|
||||
// The argument p points to an []byte variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
|
||||
f.VarP(newBytesBase64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
|
||||
f.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
|
||||
// The argument p points to an []byte variable in which to store the value of the flag.
|
||||
func BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
|
||||
CommandLine.VarP(newBytesBase64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
|
||||
CommandLine.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an []byte variable that stores the value of the flag.
|
||||
func (f *FlagSet) BytesBase64(name string, value []byte, usage string) *[]byte {
|
||||
p := new([]byte)
|
||||
f.BytesBase64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
|
||||
p := new([]byte)
|
||||
f.BytesBase64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an []byte variable that stores the value of the flag.
|
||||
func BytesBase64(name string, value []byte, usage string) *[]byte {
|
||||
return CommandLine.BytesBase64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
|
||||
return CommandLine.BytesBase64P(name, shorthand, value, usage)
|
||||
}
|
||||
96
src/cmd/linuxkit/vendor/github.com/spf13/pflag/count.go
generated
vendored
Normal file
96
src/cmd/linuxkit/vendor/github.com/spf13/pflag/count.go
generated
vendored
Normal file
@@ -0,0 +1,96 @@
|
||||
package pflag
|
||||
|
||||
import "strconv"
|
||||
|
||||
// -- count Value
|
||||
type countValue int
|
||||
|
||||
func newCountValue(val int, p *int) *countValue {
|
||||
*p = val
|
||||
return (*countValue)(p)
|
||||
}
|
||||
|
||||
func (i *countValue) Set(s string) error {
|
||||
// "+1" means that no specific value was passed, so increment
|
||||
if s == "+1" {
|
||||
*i = countValue(*i + 1)
|
||||
return nil
|
||||
}
|
||||
v, err := strconv.ParseInt(s, 0, 0)
|
||||
*i = countValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *countValue) Type() string {
|
||||
return "count"
|
||||
}
|
||||
|
||||
func (i *countValue) String() string { return strconv.Itoa(int(*i)) }
|
||||
|
||||
func countConv(sval string) (interface{}, error) {
|
||||
i, err := strconv.Atoi(sval)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// GetCount return the int value of a flag with the given name
|
||||
func (f *FlagSet) GetCount(name string) (int, error) {
|
||||
val, err := f.getFlagType(name, "count", countConv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return val.(int), nil
|
||||
}
|
||||
|
||||
// CountVar defines a count flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int variable in which to store the value of the flag.
|
||||
// A count flag will add 1 to its value every time it is found on the command line
|
||||
func (f *FlagSet) CountVar(p *int, name string, usage string) {
|
||||
f.CountVarP(p, name, "", usage)
|
||||
}
|
||||
|
||||
// CountVarP is like CountVar only take a shorthand for the flag name.
|
||||
func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) {
|
||||
flag := f.VarPF(newCountValue(0, p), name, shorthand, usage)
|
||||
flag.NoOptDefVal = "+1"
|
||||
}
|
||||
|
||||
// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set
|
||||
func CountVar(p *int, name string, usage string) {
|
||||
CommandLine.CountVar(p, name, usage)
|
||||
}
|
||||
|
||||
// CountVarP is like CountVar only take a shorthand for the flag name.
|
||||
func CountVarP(p *int, name, shorthand string, usage string) {
|
||||
CommandLine.CountVarP(p, name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Count defines a count flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
// A count flag will add 1 to its value every time it is found on the command line
|
||||
func (f *FlagSet) Count(name string, usage string) *int {
|
||||
p := new(int)
|
||||
f.CountVarP(p, name, "", usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// CountP is like Count only takes a shorthand for the flag name.
|
||||
func (f *FlagSet) CountP(name, shorthand string, usage string) *int {
|
||||
p := new(int)
|
||||
f.CountVarP(p, name, shorthand, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Count defines a count flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
// A count flag will add 1 to its value evey time it is found on the command line
|
||||
func Count(name string, usage string) *int {
|
||||
return CommandLine.CountP(name, "", usage)
|
||||
}
|
||||
|
||||
// CountP is like Count only takes a shorthand for the flag name.
|
||||
func CountP(name, shorthand string, usage string) *int {
|
||||
return CommandLine.CountP(name, shorthand, usage)
|
||||
}
|
||||
86
src/cmd/linuxkit/vendor/github.com/spf13/pflag/duration.go
generated
vendored
Normal file
86
src/cmd/linuxkit/vendor/github.com/spf13/pflag/duration.go
generated
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// -- time.Duration Value
|
||||
type durationValue time.Duration
|
||||
|
||||
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
|
||||
*p = val
|
||||
return (*durationValue)(p)
|
||||
}
|
||||
|
||||
func (d *durationValue) Set(s string) error {
|
||||
v, err := time.ParseDuration(s)
|
||||
*d = durationValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *durationValue) Type() string {
|
||||
return "duration"
|
||||
}
|
||||
|
||||
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
|
||||
|
||||
func durationConv(sval string) (interface{}, error) {
|
||||
return time.ParseDuration(sval)
|
||||
}
|
||||
|
||||
// GetDuration return the duration value of a flag with the given name
|
||||
func (f *FlagSet) GetDuration(name string) (time.Duration, error) {
|
||||
val, err := f.getFlagType(name, "duration", durationConv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return val.(time.Duration), nil
|
||||
}
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
f.VarP(newDurationValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
|
||||
f.VarP(newDurationValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
p := new(time.Duration)
|
||||
f.DurationVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
|
||||
p := new(time.Duration)
|
||||
f.DurationVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
return CommandLine.DurationP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
|
||||
return CommandLine.DurationP(name, shorthand, value, usage)
|
||||
}
|
||||
166
src/cmd/linuxkit/vendor/github.com/spf13/pflag/duration_slice.go
generated
vendored
Normal file
166
src/cmd/linuxkit/vendor/github.com/spf13/pflag/duration_slice.go
generated
vendored
Normal file
@@ -0,0 +1,166 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// -- durationSlice Value
|
||||
type durationSliceValue struct {
|
||||
value *[]time.Duration
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue {
|
||||
dsv := new(durationSliceValue)
|
||||
dsv.value = p
|
||||
*dsv.value = val
|
||||
return dsv
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) Set(val string) error {
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]time.Duration, len(ss))
|
||||
for i, d := range ss {
|
||||
var err error
|
||||
out[i], err = time.ParseDuration(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
}
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
s.changed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) Type() string {
|
||||
return "durationSlice"
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) String() string {
|
||||
out := make([]string, len(*s.value))
|
||||
for i, d := range *s.value {
|
||||
out[i] = fmt.Sprintf("%s", d)
|
||||
}
|
||||
return "[" + strings.Join(out, ",") + "]"
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) fromString(val string) (time.Duration, error) {
|
||||
return time.ParseDuration(val)
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) toString(val time.Duration) string {
|
||||
return fmt.Sprintf("%s", val)
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) Append(val string) error {
|
||||
i, err := s.fromString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*s.value = append(*s.value, i)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) Replace(val []string) error {
|
||||
out := make([]time.Duration, len(val))
|
||||
for i, d := range val {
|
||||
var err error
|
||||
out[i], err = s.fromString(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
*s.value = out
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *durationSliceValue) GetSlice() []string {
|
||||
out := make([]string, len(*s.value))
|
||||
for i, d := range *s.value {
|
||||
out[i] = s.toString(d)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func durationSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Empty string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []time.Duration{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]time.Duration, len(ss))
|
||||
for i, d := range ss {
|
||||
var err error
|
||||
out[i], err = time.ParseDuration(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetDurationSlice returns the []time.Duration value of a flag with the given name
|
||||
func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) {
|
||||
val, err := f.getFlagType(name, "durationSlice", durationSliceConv)
|
||||
if err != nil {
|
||||
return []time.Duration{}, err
|
||||
}
|
||||
return val.([]time.Duration), nil
|
||||
}
|
||||
|
||||
// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []time.Duration variable in which to store the value of the flag.
|
||||
func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
|
||||
f.VarP(newDurationSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
|
||||
f.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string.
|
||||
// The argument p points to a duration[] variable in which to store the value of the flag.
|
||||
func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []time.Duration variable that stores the value of the flag.
|
||||
func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
|
||||
p := []time.Duration{}
|
||||
f.DurationSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
|
||||
p := []time.Duration{}
|
||||
f.DurationSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []time.Duration variable that stores the value of the flag.
|
||||
func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
|
||||
return CommandLine.DurationSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
|
||||
return CommandLine.DurationSliceP(name, shorthand, value, usage)
|
||||
}
|
||||
1239
src/cmd/linuxkit/vendor/github.com/spf13/pflag/flag.go
generated
vendored
Normal file
1239
src/cmd/linuxkit/vendor/github.com/spf13/pflag/flag.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
88
src/cmd/linuxkit/vendor/github.com/spf13/pflag/float32.go
generated
vendored
Normal file
88
src/cmd/linuxkit/vendor/github.com/spf13/pflag/float32.go
generated
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
package pflag
|
||||
|
||||
import "strconv"
|
||||
|
||||
// -- float32 Value
|
||||
type float32Value float32
|
||||
|
||||
func newFloat32Value(val float32, p *float32) *float32Value {
|
||||
*p = val
|
||||
return (*float32Value)(p)
|
||||
}
|
||||
|
||||
func (f *float32Value) Set(s string) error {
|
||||
v, err := strconv.ParseFloat(s, 32)
|
||||
*f = float32Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *float32Value) Type() string {
|
||||
return "float32"
|
||||
}
|
||||
|
||||
func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) }
|
||||
|
||||
func float32Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseFloat(sval, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return float32(v), nil
|
||||
}
|
||||
|
||||
// GetFloat32 return the float32 value of a flag with the given name
|
||||
func (f *FlagSet) GetFloat32(name string) (float32, error) {
|
||||
val, err := f.getFlagType(name, "float32", float32Conv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return val.(float32), nil
|
||||
}
|
||||
|
||||
// Float32Var defines a float32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
|
||||
f.VarP(newFloat32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
|
||||
f.VarP(newFloat32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32Var defines a float32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float32 variable in which to store the value of the flag.
|
||||
func Float32Var(p *float32, name string, value float32, usage string) {
|
||||
CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
|
||||
CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32 defines a float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
|
||||
p := new(float32)
|
||||
f.Float32VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
|
||||
p := new(float32)
|
||||
f.Float32VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float32 defines a float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float32 variable that stores the value of the flag.
|
||||
func Float32(name string, value float32, usage string) *float32 {
|
||||
return CommandLine.Float32P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32P(name, shorthand string, value float32, usage string) *float32 {
|
||||
return CommandLine.Float32P(name, shorthand, value, usage)
|
||||
}
|
||||
174
src/cmd/linuxkit/vendor/github.com/spf13/pflag/float32_slice.go
generated
vendored
Normal file
174
src/cmd/linuxkit/vendor/github.com/spf13/pflag/float32_slice.go
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- float32Slice Value
|
||||
type float32SliceValue struct {
|
||||
value *[]float32
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newFloat32SliceValue(val []float32, p *[]float32) *float32SliceValue {
|
||||
isv := new(float32SliceValue)
|
||||
isv.value = p
|
||||
*isv.value = val
|
||||
return isv
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) Set(val string) error {
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]float32, len(ss))
|
||||
for i, d := range ss {
|
||||
var err error
|
||||
var temp64 float64
|
||||
temp64, err = strconv.ParseFloat(d, 32)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out[i] = float32(temp64)
|
||||
|
||||
}
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
s.changed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) Type() string {
|
||||
return "float32Slice"
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) String() string {
|
||||
out := make([]string, len(*s.value))
|
||||
for i, d := range *s.value {
|
||||
out[i] = fmt.Sprintf("%f", d)
|
||||
}
|
||||
return "[" + strings.Join(out, ",") + "]"
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) fromString(val string) (float32, error) {
|
||||
t64, err := strconv.ParseFloat(val, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return float32(t64), nil
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) toString(val float32) string {
|
||||
return fmt.Sprintf("%f", val)
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) Append(val string) error {
|
||||
i, err := s.fromString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*s.value = append(*s.value, i)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) Replace(val []string) error {
|
||||
out := make([]float32, len(val))
|
||||
for i, d := range val {
|
||||
var err error
|
||||
out[i], err = s.fromString(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
*s.value = out
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *float32SliceValue) GetSlice() []string {
|
||||
out := make([]string, len(*s.value))
|
||||
for i, d := range *s.value {
|
||||
out[i] = s.toString(d)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func float32SliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Empty string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []float32{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]float32, len(ss))
|
||||
for i, d := range ss {
|
||||
var err error
|
||||
var temp64 float64
|
||||
temp64, err = strconv.ParseFloat(d, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = float32(temp64)
|
||||
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetFloat32Slice return the []float32 value of a flag with the given name
|
||||
func (f *FlagSet) GetFloat32Slice(name string) ([]float32, error) {
|
||||
val, err := f.getFlagType(name, "float32Slice", float32SliceConv)
|
||||
if err != nil {
|
||||
return []float32{}, err
|
||||
}
|
||||
return val.([]float32), nil
|
||||
}
|
||||
|
||||
// Float32SliceVar defines a float32Slice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []float32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float32SliceVar(p *[]float32, name string, value []float32, usage string) {
|
||||
f.VarP(newFloat32SliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) {
|
||||
f.VarP(newFloat32SliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32SliceVar defines a float32[] flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float32[] variable in which to store the value of the flag.
|
||||
func Float32SliceVar(p *[]float32, name string, value []float32, usage string) {
|
||||
CommandLine.VarP(newFloat32SliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) {
|
||||
CommandLine.VarP(newFloat32SliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32Slice defines a []float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []float32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float32Slice(name string, value []float32, usage string) *[]float32 {
|
||||
p := []float32{}
|
||||
f.Float32SliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 {
|
||||
p := []float32{}
|
||||
f.Float32SliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// Float32Slice defines a []float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []float32 variable that stores the value of the flag.
|
||||
func Float32Slice(name string, value []float32, usage string) *[]float32 {
|
||||
return CommandLine.Float32SliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 {
|
||||
return CommandLine.Float32SliceP(name, shorthand, value, usage)
|
||||
}
|
||||
84
src/cmd/linuxkit/vendor/github.com/spf13/pflag/float64.go
generated
vendored
Normal file
84
src/cmd/linuxkit/vendor/github.com/spf13/pflag/float64.go
generated
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
package pflag
|
||||
|
||||
import "strconv"
|
||||
|
||||
// -- float64 Value
|
||||
type float64Value float64
|
||||
|
||||
func newFloat64Value(val float64, p *float64) *float64Value {
|
||||
*p = val
|
||||
return (*float64Value)(p)
|
||||
}
|
||||
|
||||
func (f *float64Value) Set(s string) error {
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
*f = float64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *float64Value) Type() string {
|
||||
return "float64"
|
||||
}
|
||||
|
||||
func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
|
||||
|
||||
func float64Conv(sval string) (interface{}, error) {
|
||||
return strconv.ParseFloat(sval, 64)
|
||||
}
|
||||
|
||||
// GetFloat64 return the float64 value of a flag with the given name
|
||||
func (f *FlagSet) GetFloat64(name string) (float64, error) {
|
||||
val, err := f.getFlagType(name, "float64", float64Conv)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return val.(float64), nil
|
||||
}
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
|
||||
f.VarP(newFloat64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
|
||||
f.VarP(newFloat64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func Float64Var(p *float64, name string, value float64, usage string) {
|
||||
CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
|
||||
CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
|
||||
p := new(float64)
|
||||
f.Float64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
|
||||
p := new(float64)
|
||||
f.Float64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func Float64(name string, value float64, usage string) *float64 {
|
||||
return CommandLine.Float64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float64P(name, shorthand string, value float64, usage string) *float64 {
|
||||
return CommandLine.Float64P(name, shorthand, value, usage)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user