2021-05-24 00:11:58 +03:00
|
|
|
package cmdrootfs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2021-05-24 00:11:58 +03:00
|
|
|
"io"
|
2021-05-24 00:11:58 +03:00
|
|
|
"os"
|
|
|
|
|
|
|
|
goflags "github.com/jessevdk/go-flags"
|
|
|
|
"github.com/motiejus/code/undocker/rootfs"
|
2021-05-24 00:11:58 +03:00
|
|
|
"github.com/ulikunitz/xz"
|
2021-05-24 00:11:58 +03:00
|
|
|
"go.uber.org/multierr"
|
|
|
|
)
|
|
|
|
|
2021-05-24 00:11:58 +03:00
|
|
|
// Command is "rootfs" command
|
|
|
|
type Command struct {
|
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
|
|
|
|
|
|
|
Xz bool `short:"J" long:"xz" description:"create XZ archive"`
|
|
|
|
|
|
|
|
rootfsNew func(io.ReadSeeker) io.WriterTo
|
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) {
|
2021-05-24 00:11:58 +03:00
|
|
|
if len(args) != 0 {
|
|
|
|
return errors.New("too many args")
|
|
|
|
}
|
2021-05-24 00:11:58 +03:00
|
|
|
if c.rootfsNew == nil {
|
|
|
|
c.rootfsNew = func(r io.ReadSeeker) io.WriterTo {
|
|
|
|
return rootfs.New(r)
|
|
|
|
}
|
|
|
|
}
|
2021-05-24 00:11:58 +03:00
|
|
|
|
2021-05-24 00:11:58 +03:00
|
|
|
rd, err := os.Open(string(c.PositionalArgs.Infile))
|
2021-05-24 00:11:58 +03:00
|
|
|
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
|
|
|
|
2021-05-24 00:11:58 +03:00
|
|
|
var out io.Writer
|
|
|
|
var outf *os.File
|
|
|
|
if fname := string(c.PositionalArgs.Outfile); fname == "-" {
|
|
|
|
outf = os.Stdout
|
2021-05-24 00:11:58 +03:00
|
|
|
} 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 {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2021-05-24 00:11:58 +03:00
|
|
|
out = outf
|
|
|
|
defer func() { err = multierr.Append(err, outf.Close()) }()
|
2021-05-24 00:11:58 +03:00
|
|
|
|
2021-05-24 00:11:58 +03:00
|
|
|
if c.Xz {
|
2021-05-24 00:11:58 +03:00
|
|
|
outz, err := xz.NewWriter(out)
|
|
|
|
if err != nil {
|
2021-05-24 00:11:58 +03:00
|
|
|
return err
|
|
|
|
}
|
2021-05-24 00:11:58 +03:00
|
|
|
defer func() { err = multierr.Append(err, outz.Close()) }()
|
|
|
|
out = outz
|
2021-05-24 00:11:58 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := c.rootfsNew(rd).WriteTo(out); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
2021-05-24 00:11:58 +03:00
|
|
|
}
|