undocker/internal/cmdlxcconfig/cmdlxcconfig.go

62 lines
1.3 KiB
Go
Raw Normal View History

2021-05-24 00:11:58 +03:00
package cmdlxcconfig
import (
"errors"
2021-05-24 00:11:58 +03:00
"fmt"
"io"
2021-05-24 00:11:58 +03:00
"os"
goflags "github.com/jessevdk/go-flags"
"github.com/motiejus/code/undocker/lxcconfig"
"go.uber.org/multierr"
)
// Command is "lxcconfig" command
2021-05-24 00:11:58 +03:00
type (
Command struct {
2021-05-24 00:11:58 +03:00
Stdout io.Writer
2021-05-24 00:11:58 +03:00
PositionalArgs struct {
Infile goflags.Filename `long:"infile" description:"Input tarball"`
Outfile string `long:"outfile" description:"Output path, stdout is '-'"`
} `positional-args:"yes" required:"yes"`
}
)
2021-05-24 00:11:58 +03:00
2021-05-24 00:11:58 +03:00
func NewCommand() *Command {
return &Command{
Stdout: os.Stdout,
}
}
func (*Command) ShortDesc() string { return "Create an LXC-compatible container configuration" }
func (*Command) LongDesc() string { return "" }
2021-05-24 00:11:58 +03:00
// Execute executes lxcconfig Command
func (c *Command) Execute(args []string) (err error) {
if len(args) != 0 {
return errors.New("too many args")
}
rd, err := os.Open(string(c.PositionalArgs.Infile))
if err != nil {
return err
}
defer func() { err = multierr.Append(err, rd.Close()) }()
2021-05-24 00:11:58 +03:00
var out io.Writer
2021-05-24 00:11:58 +03:00
outf := string(c.PositionalArgs.Outfile)
2021-05-24 00:11:58 +03:00
if fname := string(c.PositionalArgs.Outfile); fname == "-" {
out = c.Stdout
2021-05-24 00:11:58 +03:00
} else {
2021-05-24 00:11:58 +03:00
outf, err := os.Create(outf)
2021-05-24 00:11:58 +03:00
if err != nil {
2021-05-24 00:11:58 +03:00
return fmt.Errorf("create: %w", err)
2021-05-24 00:11:58 +03:00
}
2021-05-24 00:11:58 +03:00
defer func() { err = multierr.Append(err, outf.Close()) }()
out = outf
2021-05-24 00:11:58 +03:00
}
return lxcconfig.LXCConfig(rd, out)
}