wip constructors

This commit is contained in:
Motiejus Jakštys 2021-05-24 00:11:58 +03:00
parent 8ea717e6a9
commit 6d6bf4f076
4 changed files with 44 additions and 3 deletions

8
internal/cmd/BUILD Normal file
View File

@ -0,0 +1,8 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = ["cmd.go"],
importpath = "github.com/motiejus/code/undocker/internal/cmd",
visibility = ["//src/undocker:__subpackages__"],
)

20
internal/cmd/cmd.go Normal file
View File

@ -0,0 +1,20 @@
package cmd
import (
"io"
"os"
)
// BaseCommand provides common fields to all commands.
type BaseCommand struct {
Stdin io.ReadCloser
Stdout io.WriteCloser
Stderr io.WriteCloser
}
// Init initializes BaseCommand with default arguments
func (b *BaseCommand) Init() {
b.Stdin = os.Stdin
b.Stdout = os.Stdout
b.Stderr = os.Stderr
}

View File

@ -6,6 +6,7 @@ go_library(
importpath = "github.com/motiejus/code/undocker/internal/cmdrootfs",
visibility = ["//src/undocker:__subpackages__"],
deps = [
"//src/undocker/internal/cmd:go_default_library",
"//src/undocker/rootfs:go_default_library",
"@com_github_jessevdk_go_flags//:go_default_library",
"@com_github_ulikunitz_xz//:go_default_library",

View File

@ -6,6 +6,7 @@ import (
"os"
goflags "github.com/jessevdk/go-flags"
"github.com/motiejus/code/undocker/internal/cmd"
"github.com/motiejus/code/undocker/rootfs"
"github.com/ulikunitz/xz"
"go.uber.org/multierr"
@ -13,6 +14,8 @@ import (
// Command is "rootfs" command
type Command struct {
cmd.BaseCommand
PositionalArgs struct {
Infile goflags.Filename `long:"infile" description:"Input tarball"`
Outfile string `long:"outfile" description:"Output path, stdout is '-'"`
@ -29,9 +32,7 @@ func (c *Command) Execute(args []string) (err error) {
return errors.New("too many args")
}
if c.rootfsNew == nil {
c.rootfsNew = func(r io.ReadSeeker) io.WriterTo {
return rootfs.New(r)
}
c.init()
}
rd, err := os.Open(string(c.PositionalArgs.Infile))
@ -67,3 +68,14 @@ func (c *Command) Execute(args []string) (err error) {
}
return nil
}
// 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()
c.rootfsNew = func(r io.ReadSeeker) io.WriterTo {
return rootfs.New(r)
}
}