undocker/internal/cmdrootfs/cmdrootfs.go

75 lines
1.6 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"
2021-05-24 00:11:58 +03:00
"github.com/motiejus/code/undocker/internal/cmd"
"github.com/motiejus/code/undocker/rootfs"
"go.uber.org/multierr"
)
2021-05-24 00:11:58 +03:00
type (
2021-05-24 00:11:58 +03:00
flattener interface {
Flatten(io.Writer) error
}
rootfsFactory func(io.ReadSeeker) flattener
2021-05-24 00:11:58 +03:00
2021-05-24 00:11:58 +03:00
// Command is "rootfs" command
Command struct {
cmd.BaseCommand
2021-05-24 00:11:58 +03:00
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
rootfsNew rootfsFactory
}
)
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
if c.rootfsNew == nil {
2021-05-24 00:11:58 +03:00
c.init()
2021-05-24 00:11:58 +03:00
}
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.rootfsNew(rd).Flatten(out)
}
2021-05-24 00:11:58 +03:00
// init() initializes Command with the default options.
//
// Since constructors for sub-commands requires lots of boilerplate,
// command will initialize itself.
func (c *Command) init() {
c.BaseCommand.Init()
2021-05-24 00:11:58 +03:00
c.rootfsNew = func(r io.ReadSeeker) flattener {
2021-05-24 00:11:58 +03:00
return rootfs.New(r)
}
}