Add kubectl-bkl

This commit is contained in:
Ian Gulliver
2023-07-20 16:30:47 -07:00
parent 71b2358dc7
commit 63ffd5a168
3 changed files with 88 additions and 58 deletions

View File

@@ -3,31 +3,18 @@ package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"strings"
"syscall"
"github.com/gopatchy/bkl"
"golang.org/x/exp/slices"
"github.com/gopatchy/bkl/wrapper"
)
func main() {
if os.Getenv("BKL_VERSION") != "" {
bi, ok := debug.ReadBuildInfo()
if !ok {
fatal(fmt.Errorf("ReadBuildInfo() failed")) //nolint:goerr113
}
cmd := filepath.Base(os.Args[0])
fmt.Printf("%s", bi)
os.Exit(0)
}
cmd := strings.TrimSuffix(filepath.Base(os.Args[0]), "b")
args := slices.Clone(os.Args[1:])
if cmd == "bkl" {
if strings.HasSuffix(cmd, "b") {
cmd = strings.TrimSuffix(cmd, "b")
} else {
// Run as bklb, not via symlink
//nolint:goerr113,revive,stylecheck
fatal(fmt.Errorf(`Usage:
@@ -36,46 +23,7 @@ func main() {
See https://bkl.gopatchy.io/#bklb for detailed documentation.`))
}
cmdPath, err := exec.LookPath(cmd)
if err != nil {
fatal(err)
}
for i, arg := range args {
realPath, f, err := bkl.FileMatch(arg)
if err != nil {
continue
}
b := bkl.New()
err = b.MergeFileLayers(realPath)
if err != nil {
fatal(err)
}
pat := fmt.Sprintf(
"%s.*.%s",
filepath.Base(os.Args[0]),
filepath.Base(arg),
)
tmp, err := os.CreateTemp("", pat)
if err != nil {
fatal(err)
}
err = b.OutputToFile(tmp.Name(), f)
if err != nil {
fatal(err)
}
args[i] = tmp.Name()
tmp.Close()
}
fatal(syscall.Exec(cmdPath, append([]string{cmd}, args...), os.Environ()))
wrapper.WrapOrDie(cmd)
}
func fatal(err error) {

9
cmd/kubectl-bkl/main.go Normal file
View File

@@ -0,0 +1,9 @@
package main
import (
"github.com/gopatchy/bkl/wrapper"
)
func main() {
wrapper.WrapOrDie("kubectl")
}

73
wrapper/wrapper.go Normal file
View File

@@ -0,0 +1,73 @@
package wrapper
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"syscall"
"github.com/gopatchy/bkl"
"golang.org/x/exp/slices"
)
func WrapOrDie(cmd string) {
if os.Getenv("BKL_VERSION") != "" {
bi, ok := debug.ReadBuildInfo()
if !ok {
fatal(fmt.Errorf("ReadBuildInfo() failed")) //nolint:goerr113
}
fmt.Printf("%s", bi)
os.Exit(0)
}
cmdPath, err := exec.LookPath(cmd)
if err != nil {
fatal(err)
}
args := slices.Clone(os.Args[1:])
for i, arg := range args {
realPath, f, err := bkl.FileMatch(arg)
if err != nil {
continue
}
b := bkl.New()
err = b.MergeFileLayers(realPath)
if err != nil {
fatal(err)
}
pat := fmt.Sprintf(
"%s.*.%s",
filepath.Base(os.Args[0]),
filepath.Base(arg),
)
tmp, err := os.CreateTemp("", pat)
if err != nil {
fatal(err)
}
err = b.OutputToFile(tmp.Name(), f)
if err != nil {
fatal(err)
}
args[i] = tmp.Name()
tmp.Close()
}
fatal(syscall.Exec(cmdPath, append([]string{cmd}, args...), os.Environ()))
}
func fatal(err error) {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}