undocker/internal/cmdrootfs/cmdrootfs.go

65 lines
1.4 KiB
Go
Raw Normal View History

package cmdrootfs
import (
"errors"
2021-05-24 00:11:58 +03:00
"fmt"
2021-05-24 00:11:58 +03:00
"io"
"os"
goflags "github.com/jessevdk/go-flags"
"github.com/motiejus/code/undocker/rootfs"
"go.uber.org/multierr"
)
2021-05-24 00:11:58 +03:00
const _description = "Flatten a docker container image to a tarball"
2021-05-24 00:11:58 +03:00
type (
2021-05-24 00:11:58 +03:00
// Command is an implementation of go-flags.Command
2021-05-24 00:11:58 +03:00
Command struct {
2021-05-24 00:11:58 +03:00
flattener func(io.ReadSeeker, io.Writer) error
Stdout io.Writer
2021-05-24 00:11:58 +03:00
2021-05-24 00:11:58 +03:00
PositionalArgs struct {
2021-05-24 00:11:58 +03:00
Infile goflags.Filename `long:"infile" desc:"Input tarball"`
Outfile string `long:"outfile" desc:"Output path, stdout is '-'"`
2021-05-24 00:11:58 +03:00
} `positional-args:"yes" required:"yes"`
}
)
2021-05-24 00:11:58 +03:00
func NewCommand() *Command {
return &Command{
flattener: rootfs.Flatten,
Stdout: os.Stdout,
}
}
2021-05-24 00:11:58 +03:00
func (*Command) ShortDesc() string { return _description }
func (*Command) LongDesc() string { return _description }
2021-05-24 00:11:58 +03:00
2021-05-24 00:11:58 +03:00
// Execute executes rootfs Command
func (c *Command) Execute(args []string) (err error) {
if len(args) != 0 {
return errors.New("too many args")
}
2021-05-24 00:11:58 +03:00
rd, err := os.Open(string(c.PositionalArgs.Infile))
if err != nil {
return err
}
2021-05-24 00:11:58 +03:00
defer func() { err = multierr.Append(err, rd.Close()) }()
2021-05-24 00:11:58 +03:00
var out io.Writer
if fname := string(c.PositionalArgs.Outfile); fname == "-" {
2021-05-24 00:11:58 +03:00
out = c.Stdout
} else {
2021-05-24 00:11:58 +03:00
outf, err := os.Create(fname)
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
}
2021-05-24 00:11:58 +03:00
return c.flattener(rd, out)
}