undocker/internal/cmdrootfs/cmdrootfs.go

62 lines
1.3 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
type (
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,
}
}
func (*Command) ShortDesc() string { return "Flatten a docker container image to a tarball" }
func (*Command) LongDesc() string { return "" }
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)
}