feat: v0 — glpi-go client, mglpi CLI, mglpi-mcp, fake-GLPI test suite [#767]
https://projects.knownelement.com/issues/767#note-4191
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
// Package cli implements the mglpi command line: a thin, machine-friendly
|
||||
// front end over the glpi library. Connection settings come from
|
||||
// MGLPI_URL / MGLPI_APP_TOKEN / MGLPI_USER_TOKEN env vars (plus optional
|
||||
// MGLPI_PROFILE_ID for agent mode) or a 0600 --config env file — tokens
|
||||
// are never flag values and never logged. Every command accepts -o json
|
||||
// for machine output. Exit codes: 0 ok, 1 usage/config, 2 API error
|
||||
// (single-line stderr carrying the http status, parseable).
|
||||
package cli
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/config"
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
|
||||
)
|
||||
|
||||
const usage = `mglpi: GLPI/CMDB CLI (stdlib-only, library-backed)
|
||||
|
||||
Usage:
|
||||
mglpi whoami [-o json]
|
||||
mglpi change create --title T [--urgency N] [--impact N] [--profile N]
|
||||
[--content FILE|-] [-o json]
|
||||
mglpi change show ID [-o json]
|
||||
mglpi change list [--status N|NAME] [-o json]
|
||||
mglpi change transition ID STATUS (STATUS numeric or: new evaluation
|
||||
approval test qualification waiting accepted assigned
|
||||
planned pending solved closed) [-o json]
|
||||
mglpi change followup ID [--content FILE|-] [-o json]
|
||||
mglpi ci search TYPE TERM [-o json]
|
||||
mglpi ci show TYPE ID [-o json]
|
||||
mglpi help
|
||||
|
||||
Connection: MGLPI_URL + MGLPI_APP_TOKEN + MGLPI_USER_TOKEN env vars, or
|
||||
--config PATH pointing at a 0600 env file with the same keys. Tokens
|
||||
never appear in flags, logs, or error output.
|
||||
|
||||
Agent mode: --profile N (or MGLPI_PROFILE_ID in the env file) switches
|
||||
the session's active profile (e.g. 5 = Hotliner) right after
|
||||
InitSession — servers that gate operations per profile then accept the
|
||||
calls. whoami never switches.
|
||||
|
||||
change create / change followup read their body from stdin by default
|
||||
(--content FILE to read a file instead).
|
||||
|
||||
Exit codes: 0 ok, 1 usage/config error, 2 API error (stderr: one line,
|
||||
"http NNN" included).`
|
||||
|
||||
// Run executes one command; it returns the process exit code.
|
||||
func Run(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprint(stderr, usage)
|
||||
return 1
|
||||
}
|
||||
// Hoist a leading global --config PATH onto the subcommand (the
|
||||
// subcommand flag sets already accept it anywhere).
|
||||
var hoisted []string
|
||||
for len(args) >= 2 && (args[0] == "--config" || args[0] == "-config") {
|
||||
hoisted = append(hoisted, args[0], args[1])
|
||||
args = args[2:]
|
||||
}
|
||||
if len(hoisted) > 0 {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprint(stderr, usage)
|
||||
return 1
|
||||
}
|
||||
args = append(args, hoisted...)
|
||||
}
|
||||
switch args[0] {
|
||||
case "help", "-h", "--help":
|
||||
fmt.Fprint(stdout, usage)
|
||||
return 0
|
||||
case "whoami":
|
||||
return cmdWhoami(args[1:], stdout, stderr)
|
||||
case "change":
|
||||
return cmdChange(args[1:], stdout, stderr)
|
||||
case "ci":
|
||||
return cmdCI(args[1:], stdout, stderr)
|
||||
default:
|
||||
fmt.Fprintf(stderr, "mglpi: unknown command %q\n\n%s\n", args[0], usage)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
// newFlags builds a quiet flag set with the shared --config and -o flags.
|
||||
func newFlags(name string, stderr io.Writer) (*flag.FlagSet, *string, *string) {
|
||||
fs := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
fs.SetOutput(io.Discard)
|
||||
cfg := fs.String("config", "", "env file with MGLPI_URL/MGLPI_APP_TOKEN/MGLPI_USER_TOKEN (must be 0600)")
|
||||
out := fs.String("o", "text", "output format: text|json")
|
||||
return fs, cfg, out
|
||||
}
|
||||
|
||||
// parseArgs parses flags that may appear AFTER positionals (the standard
|
||||
// flag package stops at the first positional; mglpi's documented surface
|
||||
// is "change show ID -o json", "ci search TYPE TERM"). It returns the
|
||||
// positional arguments.
|
||||
func parseArgs(fs *flag.FlagSet, args []string) ([]string, error) {
|
||||
var positionals []string
|
||||
rest := args
|
||||
for {
|
||||
if err := fs.Parse(rest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
got := fs.Args()
|
||||
i := 0
|
||||
for i < len(got) && (got[i] == "-" || !strings.HasPrefix(got[i], "-")) {
|
||||
i++
|
||||
}
|
||||
positionals = append(positionals, got[:i]...)
|
||||
if i == len(got) {
|
||||
return positionals, nil
|
||||
}
|
||||
rest = got[i:]
|
||||
}
|
||||
}
|
||||
|
||||
// client resolves config (env + optional 0600 file) and builds the
|
||||
// client, resolving the effective agent profile (flag wins over the
|
||||
// MGLPI_PROFILE_ID config key). A non-nil error means exit 1; profile
|
||||
// application (an API op) surfaces later as exit 2.
|
||||
func client(cfgPath string, profileFlag int) (*glpi.Client, int, error) {
|
||||
if cfgPath == "" {
|
||||
cfgPath = os.Getenv("MGLPI_CONFIG")
|
||||
}
|
||||
if cfgPath == "" {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
cand := filepath.Join(home, ".config", "mglpi", "env")
|
||||
if _, err := os.Stat(cand); err == nil {
|
||||
cfgPath = cand
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg, _, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
profile := profileFlag
|
||||
if profile == 0 {
|
||||
profile = cfg.ProfileID
|
||||
}
|
||||
return glpi.New(glpi.Config{
|
||||
BaseURL: cfg.BaseURL,
|
||||
AppToken: cfg.AppToken,
|
||||
UserToken: cfg.UserToken,
|
||||
}), profile, nil
|
||||
}
|
||||
|
||||
// apiErr reports an API failure the mglpi way: one line, exit 2.
|
||||
func apiErr(stderr io.Writer, err error) int {
|
||||
fmt.Fprintf(stderr, "mglpi: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
|
||||
// usageErr reports a usage/config failure: one line, exit 1.
|
||||
func usageErr(stderr io.Writer, format string, args ...any) int {
|
||||
fmt.Fprintf(stderr, "mglpi: "+format+"\n", args...)
|
||||
return 1
|
||||
}
|
||||
|
||||
// emitJSON pretty-prints v for -o json.
|
||||
func emitJSON(stdout io.Writer, v any) {
|
||||
b, err := marshalIndent(v)
|
||||
if err != nil {
|
||||
return // library types are JSON-clean by construction
|
||||
}
|
||||
stdout.Write(b)
|
||||
fmt.Fprintln(stdout)
|
||||
}
|
||||
Reference in New Issue
Block a user