feat: add help, init, completion and conf-file URL resolution
This commit is contained in:
+9
-1
@@ -50,10 +50,18 @@ nfpms:
|
||||
# noreplace: puppet manages this file's contents (hiera-driven URL), so an
|
||||
# upgrade must not overwrite it.
|
||||
- src: packaging/encapic.conf
|
||||
dst: /etc/encapic/encapic.conf
|
||||
dst: /etc/encapi/encapic.conf
|
||||
type: "config|noreplace"
|
||||
file_info:
|
||||
mode: 0644
|
||||
- src: completions/encapic.bash
|
||||
dst: /usr/share/bash-completion/completions/encapic
|
||||
file_info:
|
||||
mode: 0644
|
||||
- src: completions/_encapic
|
||||
dst: /usr/share/zsh/site-functions/_encapic
|
||||
file_info:
|
||||
mode: 0644
|
||||
|
||||
checksum:
|
||||
# One <artifact>.sha256 per file rather than a single checksums.txt: the
|
||||
|
||||
@@ -25,10 +25,34 @@ reshapes it, and prints the resulting ENC YAML to stdout. It exits non-zero on
|
||||
any HTTP or parse failure — including a 404 for an unknown node — so the puppet
|
||||
exec `node_terminus` fails safe rather than compiling an empty catalog.
|
||||
|
||||
- `ENCAPI_URL` overrides the encapi base URL. The compiled-in default is
|
||||
`http://encapi.encapi.svc.cluster.local` (the in-cluster service).
|
||||
- The HTTP request has a 10s timeout.
|
||||
|
||||
`encapic --help` lists every command.
|
||||
|
||||
### Configuration
|
||||
|
||||
The encapi base URL comes from the first of:
|
||||
|
||||
1. the `ENCAPI_URL` environment variable;
|
||||
2. `${XDG_CONFIG_HOME:-~/.config}/encapi/encapic.conf`;
|
||||
3. `/etc/encapi/encapic.conf`;
|
||||
4. `/etc/encapic/encapic.conf` (legacy, read-only fallback);
|
||||
5. the compiled-in default `http://encapi.encapi.svc.cluster.local`.
|
||||
|
||||
Conf files are shell-sourceable `KEY=VALUE` (`ENCAPI_URL=https://...`).
|
||||
`encapic init` prompts for the URL, writes the user conf and offers to install
|
||||
shell completion. With no config found, an interactive run prints a hint to
|
||||
stderr; non-TTY runs (the puppet exec ENC) stay silent.
|
||||
|
||||
### Shell completion
|
||||
|
||||
```
|
||||
encapic completion bash|zsh # print the script
|
||||
encapic completion bash|zsh --install # install under ${XDG_DATA_HOME:-~/.local/share}
|
||||
```
|
||||
|
||||
The RPM also installs both scripts system-wide.
|
||||
|
||||
### Pinning a host to `testing`
|
||||
|
||||
```
|
||||
@@ -107,14 +131,16 @@ The VM puppet masters install the RPM from `rpm-internal`:
|
||||
dnf install encapic
|
||||
```
|
||||
|
||||
It ships three paths:
|
||||
It ships:
|
||||
|
||||
- `/usr/bin/encapic` — the binary;
|
||||
- `/usr/bin/encapic-enc` — the ENC entrypoint. Puppet's exec `node_terminus`
|
||||
invokes `external_nodes` with a certname and no environment, so the shim
|
||||
sources the URL before exec'ing the binary. Point `external_nodes` at this,
|
||||
not at `/usr/bin/encapic`;
|
||||
- `/etc/encapic/encapic.conf` — `ENCAPI_URL=...`, defaulting to the external
|
||||
- `/etc/encapi/encapic.conf` — `ENCAPI_URL=...`, defaulting to the external
|
||||
address `https://encapi.k8s.syd1.au.unkin.net` because a VM cannot resolve
|
||||
the in-cluster default. Shipped `%config(noreplace)` so puppet may own its
|
||||
contents without an upgrade reverting them.
|
||||
contents without an upgrade reverting them. The shim and binary still read
|
||||
the legacy `/etc/encapic/encapic.conf` as a fallback;
|
||||
- bash and zsh completion scripts.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed completions/encapic.bash
|
||||
var bashCompletion string
|
||||
|
||||
//go:embed completions/_encapic
|
||||
var zshCompletion string
|
||||
|
||||
var completionScripts = map[string]string{"bash": bashCompletion, "zsh": zshCompletion}
|
||||
|
||||
func completionPath(shell string) (string, error) {
|
||||
d := xdgDir("XDG_DATA_HOME", filepath.Join(".local", "share"))
|
||||
if d == "" {
|
||||
return "", fmt.Errorf("cannot determine user data directory")
|
||||
}
|
||||
if shell == "zsh" {
|
||||
return filepath.Join(d, "zsh", "site-functions", "_encapic"), nil
|
||||
}
|
||||
return filepath.Join(d, "bash-completion", "completions", "encapic"), nil
|
||||
}
|
||||
|
||||
func installCompletion(shell string, out io.Writer) error {
|
||||
path, err := completionPath(shell)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(completionScripts[shell]), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(out, "installed %s completion to %s\n", shell, path); err != nil {
|
||||
return err
|
||||
}
|
||||
dir := filepath.Dir(path)
|
||||
if shell == "zsh" && !strings.Contains(":"+os.Getenv("FPATH")+":", ":"+dir+":") {
|
||||
_, err = fmt.Fprintf(out, "hint: add to ~/.zshrc before compinit: fpath=(%s $fpath)\n", dir)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func completion(args []string, out io.Writer) error {
|
||||
if len(args) < 1 || len(args) > 2 || (len(args) == 2 && args[1] != "--install") {
|
||||
return fmt.Errorf("usage: encapic completion bash|zsh [--install]")
|
||||
}
|
||||
script, ok := completionScripts[args[0]]
|
||||
if !ok {
|
||||
return fmt.Errorf("unsupported shell %q: want bash or zsh", args[0])
|
||||
}
|
||||
if len(args) == 2 {
|
||||
return installCompletion(args[0], out)
|
||||
}
|
||||
_, err := io.WriteString(out, script)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCompletionPrint(t *testing.T) {
|
||||
for shell, marker := range map[string]string{"bash": "complete -F _encapic encapic", "zsh": "#compdef encapic"} {
|
||||
var out bytes.Buffer
|
||||
if err := run([]string{"encapic", "completion", shell}, &out); err != nil {
|
||||
t.Fatalf("%s: %v", shell, err)
|
||||
}
|
||||
if !strings.Contains(out.String(), marker) {
|
||||
t.Errorf("%s script missing %q", shell, marker)
|
||||
}
|
||||
for _, word := range []string{"init", "set-testing", "completion", "bash zsh", "--install"} {
|
||||
if !strings.Contains(out.String(), word) {
|
||||
t.Errorf("%s script does not complete %q", shell, word)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletionErrors(t *testing.T) {
|
||||
for _, args := range [][]string{{}, {"fish"}, {"bash", "--bogus"}, {"bash", "--install", "x"}} {
|
||||
if err := completion(args, &bytes.Buffer{}); err == nil {
|
||||
t.Errorf("completion(%q) succeeded, want error", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletionInstall(t *testing.T) {
|
||||
data := t.TempDir()
|
||||
t.Setenv("XDG_DATA_HOME", data)
|
||||
zshDir := filepath.Join(data, "zsh", "site-functions")
|
||||
|
||||
cases := []struct {
|
||||
shell, path, fpath string
|
||||
hint bool
|
||||
}{
|
||||
{"bash", filepath.Join(data, "bash-completion", "completions", "encapic"), "", false},
|
||||
{"zsh", filepath.Join(zshDir, "_encapic"), "/usr/share/zsh/site-functions", true},
|
||||
{"zsh", filepath.Join(zshDir, "_encapic"), "/a:" + zshDir + ":/b", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Setenv("FPATH", tc.fpath)
|
||||
var out bytes.Buffer
|
||||
if err := run([]string{"encapic", "completion", tc.shell, "--install"}, &out); err != nil {
|
||||
t.Fatalf("%s install: %v", tc.shell, err)
|
||||
}
|
||||
b, err := os.ReadFile(tc.path)
|
||||
if err != nil || string(b) != completionScripts[tc.shell] {
|
||||
t.Errorf("%s: script not at %s: %v", tc.shell, tc.path, err)
|
||||
}
|
||||
if got := strings.Contains(out.String(), "fpath=("+zshDir); got != tc.hint {
|
||||
t.Errorf("%s FPATH=%q: hint = %v, want %v (%q)", tc.shell, tc.fpath, got, tc.hint, out.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletionInstallDefaultsToLocalShare(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("XDG_DATA_HOME", "")
|
||||
path, err := completionPath("bash")
|
||||
if err != nil || path != filepath.Join(home, ".local", "share", "bash-completion", "completions", "encapic") {
|
||||
t.Errorf("completionPath = %q, %v", path, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#compdef encapic
|
||||
|
||||
_encapic() {
|
||||
case $CURRENT in
|
||||
2) compadd -- init set-testing completion help --help --version ;;
|
||||
3) [[ $words[2] == completion ]] && compadd -- bash zsh ;;
|
||||
4) [[ $words[2] == completion ]] && compadd -- --install ;;
|
||||
esac
|
||||
}
|
||||
|
||||
if [[ $funcstack[1] == _encapic ]]; then
|
||||
_encapic "$@"
|
||||
else
|
||||
compdef _encapic encapic
|
||||
fi
|
||||
@@ -0,0 +1,11 @@
|
||||
# bash completion for encapic
|
||||
_encapic() {
|
||||
local cur=${COMP_WORDS[COMP_CWORD]} words=""
|
||||
case $COMP_CWORD in
|
||||
1) words="init set-testing completion help --help --version" ;;
|
||||
2) [[ ${COMP_WORDS[1]} == completion ]] && words="bash zsh" ;;
|
||||
3) [[ ${COMP_WORDS[1]} == completion ]] && words="--install" ;;
|
||||
esac
|
||||
mapfile -t COMPREPLY < <(compgen -W "$words" -- "$cur")
|
||||
}
|
||||
complete -F _encapic encapic
|
||||
@@ -0,0 +1,153 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const initDefaultURL = "https://encapi"
|
||||
|
||||
// systemConfPaths follow the user conf in precedence; the legacy path is a
|
||||
// read-only fallback for hosts whose puppet still manages it.
|
||||
var systemConfPaths = []string{"/etc/encapi/encapic.conf", "/etc/encapic/encapic.conf"}
|
||||
|
||||
func xdgDir(env, fallback string) string {
|
||||
if d := os.Getenv(env); d != "" {
|
||||
return d
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, fallback)
|
||||
}
|
||||
|
||||
func userConfPath() string {
|
||||
d := xdgDir("XDG_CONFIG_HOME", ".config")
|
||||
if d == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(d, "encapi", "encapic.conf")
|
||||
}
|
||||
|
||||
// resolveBaseURL returns the encapi URL and whether it came from env or a conf
|
||||
// file rather than the compiled default.
|
||||
func resolveBaseURL() (string, bool) {
|
||||
if u := os.Getenv("ENCAPI_URL"); u != "" {
|
||||
return u, true
|
||||
}
|
||||
for _, p := range append([]string{userConfPath()}, systemConfPaths...) {
|
||||
if u := readConfURL(p); u != "" {
|
||||
return u, true
|
||||
}
|
||||
}
|
||||
return defaultBaseURL, false
|
||||
}
|
||||
|
||||
func baseURL() string {
|
||||
u, found := resolveBaseURL()
|
||||
if !found {
|
||||
if fi, err := os.Stderr.Stat(); err == nil && fi.Mode()&os.ModeCharDevice != 0 {
|
||||
fmt.Fprintln(os.Stderr, "hint: no config found, run 'encapic init'")
|
||||
}
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func readConfURL(path string) string {
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
u := ""
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
|
||||
if ok && strings.TrimSpace(strings.TrimPrefix(k, "export ")) == "ENCAPI_URL" {
|
||||
u = strings.Trim(strings.TrimSpace(v), `"'`)
|
||||
}
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func validURL(raw string) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return fmt.Errorf("invalid encapi URL %q: want http(s)://host", raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func prompt(r *bufio.Reader, out io.Writer, q string) (string, error) {
|
||||
if _, err := fmt.Fprint(out, q); err != nil {
|
||||
return "", err
|
||||
}
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(line), nil
|
||||
}
|
||||
|
||||
func initConfig(in io.Reader, out io.Writer) error {
|
||||
path := userConfPath()
|
||||
if path == "" {
|
||||
return errors.New("cannot determine user config directory")
|
||||
}
|
||||
r := bufio.NewReader(in)
|
||||
u, err := prompt(r, out, fmt.Sprintf("encapi URL [%s]: ", initDefaultURL))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if u == "" {
|
||||
u = initDefaultURL
|
||||
}
|
||||
if err := validURL(u); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
write, verb := true, "wrote"
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
ans, err := prompt(r, out, path+" exists, overwrite? [y/N] ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
write = strings.EqualFold(ans, "y") || strings.EqualFold(ans, "yes")
|
||||
if !write {
|
||||
verb = "kept"
|
||||
}
|
||||
}
|
||||
if write {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("ENCAPI_URL="+u+"\n"), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := fmt.Fprintf(out, "%s %s\n", verb, path); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ans, err := prompt(r, out, "Install shell completion? [Y/n] ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ans != "" && !strings.EqualFold(ans, "y") && !strings.EqualFold(ans, "yes") {
|
||||
return nil
|
||||
}
|
||||
shell := filepath.Base(os.Getenv("SHELL"))
|
||||
if _, ok := completionScripts[shell]; !ok {
|
||||
_, err := fmt.Fprintf(out, "skipping completion: unsupported shell %q (bash|zsh)\n", shell)
|
||||
return err
|
||||
}
|
||||
return installCompletion(shell, out)
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
dir, err := os.MkdirTemp("", "encapic-test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
systemConfPaths = nil
|
||||
_ = os.Unsetenv("ENCAPI_URL")
|
||||
_ = os.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
|
||||
_ = os.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data"))
|
||||
code := m.Run()
|
||||
_ = os.RemoveAll(dir)
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func writeConf(t *testing.T, path, body string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveBaseURLPrecedence(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "user"))
|
||||
user := filepath.Join(dir, "user", "encapi", "encapic.conf")
|
||||
system := filepath.Join(dir, "etc", "encapi", "encapic.conf")
|
||||
legacy := filepath.Join(dir, "etc", "encapic", "encapic.conf")
|
||||
old := systemConfPaths
|
||||
systemConfPaths = []string{system, legacy}
|
||||
t.Cleanup(func() { systemConfPaths = old })
|
||||
|
||||
check := func(want string, wantFound bool) {
|
||||
t.Helper()
|
||||
got, found := resolveBaseURL()
|
||||
if got != want || found != wantFound {
|
||||
t.Errorf("resolveBaseURL() = %q, %v; want %q, %v", got, found, want, wantFound)
|
||||
}
|
||||
}
|
||||
|
||||
t.Setenv("ENCAPI_URL", "")
|
||||
check(defaultBaseURL, false)
|
||||
writeConf(t, legacy, "ENCAPI_URL=https://legacy\n")
|
||||
check("https://legacy", true)
|
||||
writeConf(t, system, "# comment\nENCAPI_URL=\"https://system\"\n")
|
||||
check("https://system", true)
|
||||
writeConf(t, user, "OTHER=x\nexport ENCAPI_URL='https://user'\n")
|
||||
check("https://user", true)
|
||||
t.Setenv("ENCAPI_URL", "https://env")
|
||||
check("https://env", true)
|
||||
|
||||
t.Setenv("ENCAPI_URL", "")
|
||||
writeConf(t, user, "OTHER=x\n")
|
||||
check("https://system", true)
|
||||
}
|
||||
|
||||
func TestInitConfig(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, input, want string
|
||||
wantErr bool
|
||||
}{
|
||||
{"default", "\nn\n", "ENCAPI_URL=https://encapi\n", false},
|
||||
{"custom", "http://encapi.example:8080\nn\n", "ENCAPI_URL=http://encapi.example:8080\n", false},
|
||||
{"invalid", "ftp://nope\n", "", true},
|
||||
{"no host", "encapi.example\n", "", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
var out bytes.Buffer
|
||||
err := initConfig(strings.NewReader(tc.input), &out)
|
||||
if (err != nil) != tc.wantErr {
|
||||
t.Fatalf("err = %v, wantErr %v", err, tc.wantErr)
|
||||
}
|
||||
b, rerr := os.ReadFile(userConfPath())
|
||||
if tc.wantErr {
|
||||
if rerr == nil {
|
||||
t.Errorf("conf written despite invalid URL: %q", b)
|
||||
}
|
||||
return
|
||||
}
|
||||
if string(b) != tc.want {
|
||||
t.Errorf("conf = %q, want %q", b, tc.want)
|
||||
}
|
||||
if !strings.Contains(out.String(), "encapi URL [https://encapi]: ") {
|
||||
t.Errorf("missing URL prompt in %q", out.String())
|
||||
}
|
||||
fi, err := os.Stat(filepath.Dir(userConfPath()))
|
||||
if err != nil || fi.Mode().Perm() != 0o700 {
|
||||
t.Errorf("conf dir mode = %v, %v; want 0700", fi.Mode().Perm(), err)
|
||||
}
|
||||
t.Setenv("ENCAPI_URL", "")
|
||||
if got, found := resolveBaseURL(); !found || got+"\n" != strings.TrimPrefix(tc.want, "ENCAPI_URL=") {
|
||||
t.Errorf("resolveBaseURL after init = %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitConfigOverwrite(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
writeConf(t, userConfPath(), "ENCAPI_URL=https://keep\n")
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := initConfig(strings.NewReader("https://new\n\nn\n"), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(userConfPath()); string(b) != "ENCAPI_URL=https://keep\n" {
|
||||
t.Errorf("conf overwritten without consent: %q", b)
|
||||
}
|
||||
if !strings.Contains(out.String(), "overwrite? [y/N]") {
|
||||
t.Errorf("no overwrite prompt in %q", out.String())
|
||||
}
|
||||
|
||||
if err := initConfig(strings.NewReader("https://new\ny\nn\n"), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(userConfPath()); string(b) != "ENCAPI_URL=https://new\n" {
|
||||
t.Errorf("conf not overwritten after yes: %q", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitInstallsCompletion(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_DATA_HOME", t.TempDir())
|
||||
|
||||
t.Setenv("SHELL", "/bin/bash")
|
||||
var out bytes.Buffer
|
||||
if err := initConfig(strings.NewReader("\n\n"), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path, _ := completionPath("bash")
|
||||
if b, err := os.ReadFile(path); err != nil || string(b) != bashCompletion {
|
||||
t.Errorf("bash completion not installed at %s: %v", path, err)
|
||||
}
|
||||
|
||||
t.Setenv("SHELL", "/usr/bin/fish")
|
||||
out.Reset()
|
||||
if err := initConfig(strings.NewReader("\ny\n"), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out.String(), `unsupported shell "fish"`) {
|
||||
t.Errorf("no skip note for fish in %q", out.String())
|
||||
}
|
||||
}
|
||||
@@ -38,12 +38,24 @@ import (
|
||||
var version = "dev"
|
||||
|
||||
// defaultBaseURL is compiled in and points at the in-cluster encapi service. It
|
||||
// is overridden by the ENCAPI_URL environment variable when set.
|
||||
// is overridden by ENCAPI_URL from the environment or a conf file.
|
||||
const defaultBaseURL = "http://encapi.encapi.svc.cluster.local"
|
||||
|
||||
// httpTimeout bounds the whole request; the puppet exec ENC must not hang.
|
||||
const httpTimeout = 10 * time.Second
|
||||
|
||||
const usage = `usage:
|
||||
encapic <certname> print the Puppet ENC YAML for certname
|
||||
encapic set-testing <certname> pin certname to the testing environment
|
||||
encapic init write ~/.config/encapi/encapic.conf
|
||||
encapic completion bash|zsh [--install] print or install shell completion
|
||||
encapic -h | --help | help show this help
|
||||
encapic -v | --version show the version
|
||||
|
||||
ENCAPI_URL is read from the environment, then ~/.config/encapi/encapic.conf,
|
||||
/etc/encapi/encapic.conf, /etc/encapic/encapic.conf, else the in-cluster default.
|
||||
`
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args, os.Stdout); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
@@ -54,22 +66,29 @@ func main() {
|
||||
// run is the testable entry point. It writes the ENC YAML to out and returns a
|
||||
// non-nil error on any failure.
|
||||
func run(args []string, out io.Writer) error {
|
||||
if len(args) == 2 && (args[1] == "-v" || args[1] == "--version") {
|
||||
_, err := fmt.Fprintf(out, "encapic %s\n", version)
|
||||
return err
|
||||
if len(args) == 2 {
|
||||
switch args[1] {
|
||||
case "-v", "--version":
|
||||
_, err := fmt.Fprintf(out, "encapic %s\n", version)
|
||||
return err
|
||||
case "-h", "--help", "help":
|
||||
_, err := io.WriteString(out, usage)
|
||||
return err
|
||||
case "init":
|
||||
return initConfig(os.Stdin, out)
|
||||
}
|
||||
}
|
||||
if len(args) >= 2 && args[1] == "completion" {
|
||||
return completion(args[2:], out)
|
||||
}
|
||||
if len(args) == 3 && args[1] == "set-testing" {
|
||||
return setTesting(args[2], out)
|
||||
}
|
||||
if len(args) != 2 {
|
||||
return fmt.Errorf("usage: %s <certname> | %s set-testing <certname>", args[0], args[0])
|
||||
if len(args) != 2 || strings.HasPrefix(args[1], "-") {
|
||||
return fmt.Errorf("invalid arguments %q\n%s", args[1:], strings.TrimSuffix(usage, "\n"))
|
||||
}
|
||||
certname := args[1]
|
||||
|
||||
baseURL := os.Getenv("ENCAPI_URL")
|
||||
if baseURL == "" {
|
||||
baseURL = defaultBaseURL
|
||||
}
|
||||
baseURL := baseURL()
|
||||
|
||||
body, err := fetch(baseURL, certname)
|
||||
if err != nil {
|
||||
|
||||
@@ -107,6 +107,27 @@ func TestRunUsage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunUnknownFlag(t *testing.T) {
|
||||
err := run([]string{"encapic", "--bogus"}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "usage:") {
|
||||
t.Fatalf("err = %v, want usage error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunHelp(t *testing.T) {
|
||||
for _, arg := range []string{"-h", "--help", "help"} {
|
||||
var out bytes.Buffer
|
||||
if err := run([]string{"encapic", arg}, &out); err != nil {
|
||||
t.Fatalf("%s: %v", arg, err)
|
||||
}
|
||||
for _, want := range []string{"<certname>", "set-testing", "init", "completion bash|zsh [--install]", "--version", "ENCAPI_URL"} {
|
||||
if !strings.Contains(out.String(), want) {
|
||||
t.Errorf("%s output missing %q", arg, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunVersion(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
if err := run([]string{"encapic", "--version"}, &out); err != nil {
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
# environment, so the encapi URL cannot be inherited; source it here instead.
|
||||
set -eu
|
||||
|
||||
if [ -r /etc/encapic/encapic.conf ]; then
|
||||
. /etc/encapic/encapic.conf
|
||||
fi
|
||||
for conf in /etc/encapic/encapic.conf /etc/encapi/encapic.conf; do
|
||||
if [ -r "$conf" ]; then
|
||||
. "$conf"
|
||||
fi
|
||||
done
|
||||
if [ -n "${ENCAPI_URL:-}" ]; then
|
||||
export ENCAPI_URL
|
||||
fi
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Base URL of the encapi service, read by /usr/bin/encapic-enc.
|
||||
# Base URL of the encapi service, read by encapic and /usr/bin/encapic-enc.
|
||||
# The binary's compiled-in default is the in-cluster address, which VM puppet
|
||||
# masters cannot resolve.
|
||||
ENCAPI_URL=https://encapi.k8s.syd1.au.unkin.net
|
||||
|
||||
+1
-4
@@ -20,10 +20,7 @@ const defaultVaultAddr = "https://vault.service.consul:8200"
|
||||
// setTesting pins certname to the testing environment via encapi, using a
|
||||
// Vault identity OIDC token for the encapi-testing role.
|
||||
func setTesting(certname string, out io.Writer) error {
|
||||
baseURL := os.Getenv("ENCAPI_URL")
|
||||
if baseURL == "" {
|
||||
baseURL = defaultBaseURL
|
||||
}
|
||||
baseURL := baseURL()
|
||||
if err := requireHTTPS("ENCAPI_URL", baseURL); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user