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:
2026-09-04 08:41:25 -05:00
commit 5da1eee08f
26 changed files with 4956 additions and 0 deletions
+173
View File
@@ -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)
}
+385
View File
@@ -0,0 +1,385 @@
package cli
import (
"encoding/json"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/fakeglpi"
)
const (
testApp = "fake-app-token-0123456789"
testUser = "fake-user-token-0123456789"
)
func boot(t *testing.T) *fakeglpi.Server {
t.Helper()
srv := fakeglpi.New(testApp, testUser)
t.Cleanup(srv.Close)
t.Setenv("MGLPI_URL", srv.URL)
t.Setenv("MGLPI_APP_TOKEN", testApp)
t.Setenv("MGLPI_USER_TOKEN", testUser)
t.Setenv("MGLPI_PROFILE_ID", "")
return srv
}
func run(t *testing.T, args ...string) (string, string, int) {
t.Helper()
var out, errb strings.Builder
code := Run(args, &out, &errb)
return out.String(), errb.String(), code
}
func contentFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "content.txt")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
return path
}
func TestUsageErrors(t *testing.T) {
boot(t)
tests := []struct {
name string
args []string
}{
{"no args", nil},
{"unknown command", []string{"frobnicate"}},
{"change alone", []string{"change"}},
{"change create without title", []string{"change", "create"}},
{"change show without id", []string{"change", "show"}},
{"change show non-numeric id", []string{"change", "show", "abc"}},
{"change transition bad status name", []string{"change", "transition", "5", "bogus"}},
{"change list bad status name", []string{"change", "list", "--status", "bogus"}},
{"ci search without term", []string{"ci", "search", "Computer"}},
{"ci show without id", []string{"ci", "show", "Computer"}},
{"whoami with positional", []string{"whoami", "extra"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out, errb, code := run(t, tt.args...)
if code != 1 {
t.Fatalf("code = %d (out %q, err %q), want 1", code, out, errb)
}
if out != "" {
t.Errorf("usage error wrote to stdout: %q", out)
}
if errb == "" {
t.Errorf("no diagnostic on stderr")
}
})
}
}
func TestConfigErrorIsExitOne(t *testing.T) {
boot(t)
t.Setenv("MGLPI_URL", "")
t.Setenv("MGLPI_APP_TOKEN", "")
t.Setenv("MGLPI_USER_TOKEN", "")
_, errb, code := run(t, "change", "list")
if code != 1 {
t.Fatalf("code = %d, want 1 (config)", code)
}
if !strings.Contains(errb, "MGLPI_URL") {
t.Fatalf("stderr = %q", errb)
}
}
func TestWhoami(t *testing.T) {
boot(t)
out, errb, code := run(t, "whoami")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
for _, want := range []string{"Self-Service", "Hotliner", "Super-admin", "active"} {
if !strings.Contains(out, want) {
t.Errorf("whoami output missing %q:\n%s", want, out)
}
}
out, _, code = run(t, "whoami", "-o", "json")
if code != 0 {
t.Fatalf("json whoami code %d", code)
}
var got struct {
Profiles []struct {
ID int `json:"id"`
Name string `json:"name"`
IsActive bool `json:"is_active"`
} `json:"profiles"`
}
if err := json.Unmarshal([]byte(out), &got); err != nil || len(got.Profiles) != 3 {
t.Errorf("json whoami = %q err %v", out, err)
}
}
func TestChangeCreateFullFlags(t *testing.T) {
srv := boot(t)
content := contentFile(t, "<p>scope body</p>")
out, errb, code := run(t, "change", "create",
"--title", "Quota: per-identity accounting",
"--content", content,
"--urgency", "3", "--impact", "4",
"-o", "json")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
var got struct {
Change struct {
ID int `json:"id"`
} `json:"change"`
}
if err := json.Unmarshal([]byte(out), &got); err != nil || got.Change.ID == 0 {
t.Fatalf("stdout not json: %v (%q)", err, out)
}
stored, ok := srv.Change(got.Change.ID)
if !ok || stored.Name != "Quota: per-identity accounting" || stored.Content != "<p>scope body</p>" ||
stored.Urgency != 3 || stored.Impact != 4 || stored.Status != fakeglpi.StatusNew {
t.Errorf("stored = %+v", stored)
}
}
func TestChangeCreateRequiresTitle(t *testing.T) {
boot(t)
_, errb, code := run(t, "change", "create")
if code != 1 || !strings.Contains(errb, "--title") {
t.Fatalf("code = %d stderr = %q, want usage naming --title", code, errb)
}
}
func TestChangeList(t *testing.T) {
srv := boot(t)
open := srv.AddChange(fakeglpi.Change{Name: "open one", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
solved := srv.AddChange(fakeglpi.Change{Name: "solved one", Status: fakeglpi.StatusSolved, Urgency: 3, Impact: 3})
out, errb, code := run(t, "change", "list")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, "open one") || !strings.Contains(out, strconv.Itoa(open)) {
t.Errorf("text list = %q", out)
}
out, _, code = run(t, "change", "list", "--status", "solved")
if code != 0 || !strings.Contains(out, "solved one") || strings.Contains(out, "open one") {
t.Errorf("status filter = %q code %d", out, code)
}
out, _, code = run(t, "change", "list", "--status", strconv.Itoa(fakeglpi.StatusNew))
if code != 0 || !strings.Contains(out, "open one") || strings.Contains(out, "solved one") {
t.Errorf("numeric status filter = %q code %d", out, code)
}
out, _, code = run(t, "change", "list", "-o", "json")
if code != 0 {
t.Fatalf("json list code %d", code)
}
var arr struct {
Changes []struct {
ID int `json:"id"`
Name string `json:"name"`
Status int `json:"status"`
} `json:"changes"`
}
if err := json.Unmarshal([]byte(out), &arr); err != nil || len(arr.Changes) != 2 || arr.Changes[0].ID != open || arr.Changes[1].Status != fakeglpi.StatusSolved {
t.Errorf("json list = %q err %v", out, err)
}
_ = solved
}
func TestChangeShow(t *testing.T) {
srv := boot(t)
id := srv.AddChange(fakeglpi.Change{Name: "shown change", Content: "body text", Status: fakeglpi.StatusAssigned, Urgency: 4, Impact: 3})
out, errb, code := run(t, "change", "show", strconv.Itoa(id))
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
for _, want := range []string{strconv.Itoa(id), "shown change", "body text", "assigned", "4"} {
if !strings.Contains(out, want) {
t.Errorf("show output missing %q:\n%s", want, out)
}
}
out, _, code = run(t, "change", "show", strconv.Itoa(id), "-o", "json")
if code != 0 {
t.Fatalf("json show code %d", code)
}
var got struct {
Change struct {
ID int `json:"id"`
Name string `json:"name"`
Content string `json:"content"`
Status int `json:"status"`
} `json:"change"`
}
if err := json.Unmarshal([]byte(out), &got); err != nil || got.Change.Name != "shown change" || got.Change.Status != fakeglpi.StatusAssigned {
t.Errorf("json show = %q err %v", out, err)
}
}
func TestChangeTransition(t *testing.T) {
srv := boot(t)
id := srv.AddChange(fakeglpi.Change{Name: "flow", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
out, errb, code := run(t, "change", "transition", strconv.Itoa(id), "solved")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, strconv.Itoa(id)) {
t.Errorf("confirmation = %q", out)
}
if got, _ := srv.Change(id); got.Status != fakeglpi.StatusSolved {
t.Errorf("stored status = %d, want solved", got.Status)
}
out, errb, code = run(t, "change", "transition", strconv.Itoa(id), strconv.Itoa(fakeglpi.StatusClosed))
if code != 0 {
t.Fatalf("numeric transition code = %d, stderr = %q", code, errb)
}
if got, _ := srv.Change(id); got.Status != fakeglpi.StatusClosed {
t.Errorf("stored status = %d, want closed", got.Status)
}
}
func TestChangeFollowup(t *testing.T) {
srv := boot(t)
id := srv.AddChange(fakeglpi.Change{Name: "with note", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
content := contentFile(t, "REPORT delivered: see inbox")
out, errb, code := run(t, "change", "followup", strconv.Itoa(id), "--content", content)
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, strconv.Itoa(id)) {
t.Errorf("confirmation = %q", out)
}
fups := srv.Followups(id)
if len(fups) != 1 || fups[0].Content != "REPORT delivered: see inbox" {
t.Errorf("followups = %+v", fups)
}
empty := contentFile(t, "")
_, errb, code = run(t, "change", "followup", strconv.Itoa(id), "--content", empty)
if code != 1 || !strings.Contains(errb, "content") {
t.Errorf("empty followup = code %d stderr %q, want usage error", code, errb)
}
}
func TestCISearchAndShow(t *testing.T) {
srv := boot(t)
web := srv.AddItem("Computer", map[string]any{"name": "web-01", "serial": "ABC123"})
out, errb, code := run(t, "ci", "search", "Computer", "web")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, "web-01") || !strings.Contains(out, strconv.Itoa(web)) {
t.Errorf("search = %q", out)
}
out, _, code = run(t, "ci", "search", "Computer", "web", "-o", "json")
if code != 0 {
t.Fatalf("json search code %d", code)
}
var arr struct {
Results []struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"results"`
}
if err := json.Unmarshal([]byte(out), &arr); err != nil || len(arr.Results) != 1 || arr.Results[0].Name != "web-01" {
t.Errorf("json search = %q err %v", out, err)
}
out, _, code = run(t, "ci", "show", "Computer", strconv.Itoa(web), "-o", "json")
if code != 0 {
t.Fatalf("ci show code = %d", code)
}
var raw map[string]any
if err := json.Unmarshal([]byte(out), &raw); err != nil || raw["serial"] != "ABC123" {
t.Errorf("ci show = %q err %v", out, err)
}
if _, errb, code := run(t, "ci", "show", "Computer", "424242"); code != 2 || !strings.Contains(errb, "http 404") {
t.Errorf("missing ci = code %d stderr %q, want exit 2 http 404", code, errb)
}
}
// THE agent-mode CLI proof: the fake rejects change creation unless the
// session's active profile is 5; --profile and MGLPI_PROFILE_ID both
// must flip it.
func TestProfileSwitchAgentMode(t *testing.T) {
tests := []struct {
name string
envProfile string
flag []string
wantCode int
}{
{"no profile -> rejected", "", nil, 2},
{"--profile 5 -> accepted", "", []string{"--profile", "5"}, 0},
{"--profile 4 -> rejected", "", []string{"--profile", "4"}, 2},
{"env profile 5 -> accepted", "5", nil, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := boot(t)
srv.RequireChangeProfile = 5
t.Setenv("MGLPI_PROFILE_ID", tt.envProfile)
args := append([]string{"change", "create", "--title", "agent-mode", "--content", "-"}, tt.flag...)
out, errb, code := run(t, args...)
if code != tt.wantCode {
t.Fatalf("code = %d (stderr %q), want %d", code, errb, tt.wantCode)
}
if tt.wantCode == 0 {
if !strings.Contains(out, "created change #") {
t.Errorf("out = %q", out)
}
} else if !strings.Contains(errb, "http 403") {
t.Errorf("stderr = %q, want http 403", errb)
}
})
}
}
func TestAPIErrorIsExitTwo(t *testing.T) {
srv := boot(t)
srv.Fail = &fakeglpi.FailSpec{Status: 404, Body: `[{"ERROR_ITEM_NOT_FOUND":"gone %s"}]`}
out, errb, code := run(t, "change", "list")
if code != 2 {
t.Fatalf("code = %d, want 2", code)
}
if out != "" {
t.Errorf("stdout on API error: %q", out)
}
lines := strings.Split(strings.TrimRight(errb, "\n"), "\n")
if len(lines) != 1 || !strings.Contains(lines[0], "http 404") {
t.Fatalf("stderr = %q, want single parseable line with http 404", errb)
}
}
func TestTokensNeverPrinted(t *testing.T) {
srv := fakeglpi.New(testApp, testUser)
t.Cleanup(srv.Close)
t.Setenv("MGLPI_URL", srv.URL)
t.Setenv("MGLPI_APP_TOKEN", "wrong-app-token")
t.Setenv("MGLPI_USER_TOKEN", testUser)
t.Setenv("MGLPI_PROFILE_ID", "")
_, errb, code := run(t, "change", "list")
if code != 2 {
t.Fatalf("code = %d, want 2", code)
}
if strings.Contains(errb, "wrong-app-token") || strings.Contains(errb, testUser) || strings.Contains(errb, testApp) {
t.Fatalf("stderr leaks a token: %q", errb)
}
if strings.Count(errb, "\n") != 1 { // one diagnostic line + trailing newline
t.Fatalf("stderr not one line: %q", errb)
}
}
func TestHelpExitsZero(t *testing.T) {
boot(t)
out, _, code := run(t, "help")
if code != 0 || !strings.Contains(out, "change") {
t.Fatalf("help code = %d out = %q", code, out)
}
}
+366
View File
@@ -0,0 +1,366 @@
package cli
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
)
func marshalIndent(v any) ([]byte, error) { return json.MarshalIndent(v, "", " ") }
// --- whoami -----------------------------------------------------------------
// cmdWhoami lists the session's profiles. It NEVER switches the active
// profile (agent mode's MGLPI_PROFILE_ID is deliberately not applied).
func cmdWhoami(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("whoami", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 0 {
return usageErr(stderr, "whoami: usage: mglpi whoami")
}
c, _, err := client(*cfgPath, 0)
if err != nil {
return usageErr(stderr, "%v", err)
}
profs, err := c.GetMyProfiles(context.Background())
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"profiles": profs})
return 0
}
for _, p := range profs {
line := fmt.Sprintf("%-6d %s", p.ID, p.Name)
if p.IsActive {
line += " [active]"
}
fmt.Fprintln(stdout, line)
}
return 0
}
// --- change -------------------------------------------------------------------
func cmdChange(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
return usageErr(stderr, "change: expected list|show|create|transition|followup (see mglpi help)")
}
sub, rest := args[0], args[1:]
switch sub {
case "list":
return cmdChangeList(rest, stdout, stderr)
case "show":
return cmdChangeShow(rest, stdout, stderr)
case "create":
return cmdChangeCreate(rest, stdout, stderr)
case "transition":
return cmdChangeTransition(rest, stdout, stderr)
case "followup":
return cmdChangeFollowup(rest, stdout, stderr)
default:
return usageErr(stderr, "change: unknown subcommand %q", sub)
}
}
// withClient is the common preamble: resolve config + profile, switch
// profile when one is set (an API op -> exit 2 on failure), and hand
// the client over.
func withClient(stderr io.Writer, cfgPath string, profileFlag int, fn func(c *glpi.Client, ctx context.Context) int) int {
c, profile, err := client(cfgPath, profileFlag)
if err != nil {
return usageErr(stderr, "%v", err)
}
ctx := context.Background()
if profile > 0 {
if err := c.ChangeActiveProfile(ctx, profile); err != nil {
return apiErr(stderr, err)
}
}
return fn(c, ctx)
}
func cmdChangeList(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change list", stderr)
status := fs.String("status", "", "filter by status name or numeric id (e.g. new, solved, 1)")
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 0 {
return usageErr(stderr, "change list: usage: mglpi change list [--status N|NAME]")
}
want := 0
if *status != "" {
if id, ok := glpi.StatusID(*status); ok {
want = id
} else {
n, err := strconv.Atoi(*status)
if err != nil || n <= 0 {
return usageErr(stderr, "change list: --status must be a status name or positive number, got %q", *status)
}
want = n
}
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
rows, err := c.ListChanges(ctx, want)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"changes": rows})
return 0
}
for _, r := range rows {
fmt.Fprintf(stdout, "%-6d %-12s %s\n", r.ID, glpi.StatusName(r.Status), r.Name)
}
return 0
})
}
func cmdChangeShow(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change show", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 1 {
return usageErr(stderr, "change show: usage: mglpi change show ID")
}
id, err := strconv.Atoi(pos[0])
if err != nil {
return usageErr(stderr, "change show: ID must be numeric, got %q", pos[0])
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
ch, err := c.GetChange(ctx, id)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"change": ch})
return 0
}
printChange(stdout, ch)
return 0
})
}
func printChange(w io.Writer, ch *glpi.Change) {
fmt.Fprintf(w, "#%d %s\n", ch.ID, ch.Name)
fmt.Fprintf(w, "Status: %-12s Urgency: %d Impact: %d\n", glpi.StatusName(ch.Status), ch.Urgency, ch.Impact)
fmt.Fprintf(w, "Created: %s Updated: %s\n", ch.Date, ch.DateMod)
if ch.Content != "" {
fmt.Fprintln(w)
fmt.Fprintln(w, ch.Content)
}
}
func cmdChangeCreate(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change create", stderr)
title := fs.String("title", "", "change title (required)")
content := fs.String("content", "-", "content body from FILE, or - for stdin")
urgency := fs.Int("urgency", 3, "urgency 1..5 (3 = medium)")
impact := fs.Int("impact", 3, "impact 1..5 (3 = medium)")
profile := fs.Int("profile", 0, "agent profile id to switch to after InitSession (e.g. 5 = Hotliner)")
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 0 || *title == "" {
return usageErr(stderr, "change create: usage: mglpi change create --title T [--urgency N] [--impact N] [--profile N] [--content FILE|-]")
}
if *urgency < 1 || *urgency > 5 || *impact < 1 || *impact > 5 {
return usageErr(stderr, "change create: --urgency/--impact must be 1..5")
}
body := ""
if *content != "" {
text, err := readBody(*content)
if err != nil {
return usageErr(stderr, "%v", err)
}
body = text
}
return withClient(stderr, *cfgPath, *profile, func(c *glpi.Client, ctx context.Context) int {
id, err := c.CreateChange(ctx, *title, body, *urgency, *impact)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"change": map[string]any{"id": id}})
return 0
}
fmt.Fprintf(stdout, "created change #%d\n", id)
return 0
})
}
func cmdChangeTransition(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change transition", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 2 {
return usageErr(stderr, "change transition: usage: mglpi change transition ID STATUS")
}
id, err := strconv.Atoi(pos[0])
if err != nil {
return usageErr(stderr, "change transition: ID must be numeric, got %q", pos[0])
}
status, ok := glpi.StatusID(pos[1])
if !ok {
status, err = strconv.Atoi(pos[1])
if err != nil || status <= 0 {
return usageErr(stderr, "change transition: STATUS must be a status name or positive number, got %q", pos[1])
}
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
if err := c.TransitionChange(ctx, id, status); err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
ch, err := c.GetChange(ctx, id)
if err != nil {
return apiErr(stderr, err)
}
emitJSON(stdout, map[string]any{"change": ch})
return 0
}
fmt.Fprintf(stdout, "updated change #%d (status %s)\n", id, glpi.StatusName(status))
return 0
})
}
func cmdChangeFollowup(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change followup", stderr)
content := fs.String("content", "-", "followup body from FILE, or - for stdin")
profile := fs.Int("profile", 0, "agent profile id to switch to after InitSession")
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 1 {
return usageErr(stderr, "change followup: usage: mglpi change followup ID [--content FILE|-]")
}
id, err := strconv.Atoi(pos[0])
if err != nil {
return usageErr(stderr, "change followup: ID must be numeric, got %q", pos[0])
}
body := ""
if *content != "" {
text, err := readBody(*content)
if err != nil {
return usageErr(stderr, "%v", err)
}
body = text
}
if strings.TrimSpace(body) == "" {
return usageErr(stderr, "change followup: content is required (stdin or --content FILE)")
}
return withClient(stderr, *cfgPath, *profile, func(c *glpi.Client, ctx context.Context) int {
if err := c.AddFollowup(ctx, id, body); err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"followup": map[string]any{"items_id": id}})
return 0
}
fmt.Fprintf(stdout, "added followup to change #%d\n", id)
return 0
})
}
// readBody loads a body from a file, or from stdin when path is "-".
func readBody(path string) (string, error) {
if path == "-" {
b, err := io.ReadAll(os.Stdin)
if err != nil {
return "", fmt.Errorf("content: cannot read stdin: %w", err)
}
return string(b), nil
}
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("content: cannot read %s", path)
}
return string(b), nil
}
// --- ci ----------------------------------------------------------------------
func cmdCI(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
return usageErr(stderr, "ci: expected search|show (see mglpi help)")
}
sub, rest := args[0], args[1:]
switch sub {
case "search":
return cmdCISearch(rest, stdout, stderr)
case "show":
return cmdCIShow(rest, stdout, stderr)
default:
return usageErr(stderr, "ci: unknown subcommand %q", sub)
}
}
func cmdCISearch(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("ci search", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 2 {
return usageErr(stderr, "ci search: usage: mglpi ci search TYPE TERM")
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
rows, err := c.SearchCI(ctx, pos[0], pos[1])
if err != nil {
return apiErr(stderr, err)
}
type result struct {
ID int `json:"id"`
Name string `json:"name"`
}
results := make([]result, 0, len(rows))
for _, r := range rows {
results = append(results, result{ID: r.ID, Name: r.Name})
}
if *out == "json" {
emitJSON(stdout, map[string]any{"results": results})
return 0
}
for _, r := range results {
fmt.Fprintf(stdout, "%-6d %s\n", r.ID, r.Name)
}
return 0
})
}
func cmdCIShow(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("ci show", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 2 {
return usageErr(stderr, "ci show: usage: mglpi ci show TYPE ID")
}
id, err := strconv.Atoi(pos[1])
if err != nil {
return usageErr(stderr, "ci show: ID must be numeric, got %q", pos[1])
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
obj, err := c.GetItem(ctx, pos[0], id)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, obj)
return 0
}
fmt.Fprintf(stdout, "%s #%d %s\n", pos[0], id, obj["name"])
for _, k := range sortedKeys(obj) {
if k == "id" || k == "name" {
continue
}
fmt.Fprintf(stdout, " %s: %v\n", k, obj[k])
}
return 0
})
}
// sortedKeys orders an object's keys for stable text output.
func sortedKeys(m map[string]any) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}