1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
2//
3// SPDX-License-Identifier: AGPL-3.0-or-later
4
5package shared
6
7import (
8 "fmt"
9 "os"
10 "strings"
11
12 "git.secluded.site/np/internal/cli"
13 "git.secluded.site/np/internal/session"
14 "github.com/spf13/cobra"
15)
16
17// Environment extracts the CLI environment from the command context.
18func Environment(cmd *cobra.Command) (*cli.Environment, error) {
19 env, ok := cli.FromContext(cmd.Context())
20 if !ok || env == nil {
21 return nil, fmt.Errorf("cli: environment not initialised")
22 }
23 return env, nil
24}
25
26// ActiveSession resolves the current session for cmd, printing guidance when absent.
27func ActiveSession(cmd *cobra.Command, env *cli.Environment) (session.Document, bool, error) {
28 cwd, err := os.Getwd()
29 if err != nil {
30 return session.Document{}, false, fmt.Errorf("determine working directory: %w", err)
31 }
32
33 doc, found, err := env.ActiveSession(cmd.Context(), cwd)
34 if err != nil {
35 return session.Document{}, false, err
36 }
37 if !found {
38 _, _ = fmt.Fprintln(cmd.OutOrStdout(), env.Localizer.T("session.none_active"))
39 return session.Document{}, false, nil
40 }
41 return doc, true, nil
42}
43
44// CommandString returns the full invocation string for logging events.
45func CommandString() string {
46 return strings.Join(os.Args, " ")
47}
48
49// PrintPlan renders the plan for sid, returning the state used for rendering.
50func PrintPlan(cmd *cobra.Command, env *cli.Environment, sid string) (cli.PlanState, error) {
51 state, err := cli.BuildPlanState(cmd.Context(), env, sid)
52 if err != nil {
53 return cli.PlanState{}, err
54 }
55
56 _, _ = fmt.Fprint(cmd.OutOrStdout(), cli.RenderPlan(state, env.Localizer))
57 return state, nil
58}