undocker/main.go

75 lines
1.3 KiB
Go
Raw Normal View History

2021-05-24 00:11:57 +03:00
package main
import (
2021-05-24 00:11:58 +03:00
"fmt"
"io"
2021-05-24 00:11:57 +03:00
"os"
2021-05-24 00:11:58 +03:00
"path/filepath"
"runtime"
2021-05-24 00:11:57 +03:00
2021-05-24 00:11:58 +03:00
"git.sr.ht/~motiejus/code/undocker/rootfs"
2021-05-24 00:11:57 +03:00
)
2021-05-24 00:11:58 +03:00
const _usage = `Usage:
2021-05-24 00:11:58 +03:00
%s <infile> <outfile>
2021-05-24 00:11:58 +03:00
Flatten a Docker container image to a root file system.
Arguments:
<infile>: Input Docker container. Tarball.
<outfile>: Output tarball, the root file system. '-' is stdout.
`
2021-05-24 00:11:58 +03:00
2021-05-24 00:11:58 +03:00
func main() {
2021-05-24 00:11:58 +03:00
runtime.GOMAXPROCS(1) // no need to create that many threads
if len(os.Args) != 3 {
fmt.Fprintf(os.Stderr, _usage, filepath.Base(os.Args[0]))
os.Exit(1)
}
c := &command{flattener: rootfs.Flatten, Stdout: os.Stdout}
if err := c.execute(os.Args[1], os.Args[2]); err != nil {
fmt.Errorf("Error: %v", err)
2021-05-24 00:11:57 +03:00
os.Exit(1)
}
os.Exit(0)
}
2021-05-24 00:11:58 +03:00
type command struct {
flattener func(io.ReadSeeker, io.Writer) error
Stdout io.Writer
}
2021-05-24 00:11:58 +03:00
func (c *command) execute(infile string, outfile string) (err error) {
rd, err := os.Open(infile)
2021-05-24 00:11:58 +03:00
if err != nil {
return err
}
defer func() {
err1 := rd.Close()
if err == nil {
err = err1
}
}()
var out io.Writer
2021-05-24 00:11:58 +03:00
if outfile == "-" {
2021-05-24 00:11:58 +03:00
out = c.Stdout
} else {
2021-05-24 00:11:58 +03:00
outf, err := os.Create(outfile)
2021-05-24 00:11:58 +03:00
if err != nil {
return fmt.Errorf("create: %w", err)
}
defer func() {
err1 := outf.Close()
if err == nil {
err = err1
}
}()
out = outf
}
return c.flattener(rd, out)
}