cmd.go

 1package cmd
 2
 3import (
 4	"fmt"
 5
 6	"github.com/charmbracelet/soft-serve/server/config"
 7	"github.com/gliderlabs/ssh"
 8	"github.com/spf13/cobra"
 9)
10
11// ContextKey is a type that can be used as a key in a context.
12type ContextKey string
13
14// String returns the string representation of the ContextKey.
15func (c ContextKey) String() string {
16	return "soft-serve cli context key " + string(c)
17}
18
19var (
20	// ConfigCtxKey is the key for the config in the context.
21	ConfigCtxKey = ContextKey("config")
22	// SessionCtxKey is the key for the session in the context.
23	SessionCtxKey = ContextKey("session")
24)
25
26var (
27	// ErrUnauthorized is returned when the user is not authorized to perform action.
28	ErrUnauthorized = fmt.Errorf("Unauthorized")
29	// ErrRepoNotFound is returned when the repo is not found.
30	ErrRepoNotFound = fmt.Errorf("Repository not found")
31	// ErrFileNotFound is returned when the file is not found.
32	ErrFileNotFound = fmt.Errorf("File not found")
33
34	usageTemplate = `Usage:{{if .Runnable}}{{if .HasParent }}
35  {{.Parent.Use}} {{end}}{{.Use}}{{if .HasAvailableFlags }} [flags]{{end}}{{end}}{{if .HasAvailableSubCommands}}
36  {{if .HasParent }}{{.Parent.Use}} {{end}}{{.Use}} [command]{{end}}{{if gt (len .Aliases) 0}}
37
38Aliases:
39  {{.NameAndAliases}}{{end}}{{if .HasExample}}
40
41Examples:
42{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
43
44Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
45  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
46
47Flags:
48{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
49
50Global Flags:
51{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
52
53Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
54  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
55
56Use "{{.UseLine}} [command] --help" for more information about a command.{{end}}
57`
58)
59
60// RootCommand is the root command for the server.
61func RootCommand() *cobra.Command {
62	rootCmd := &cobra.Command{
63		Use:                   "ssh [-p PORT] HOST",
64		Long:                  "Soft Serve is a self-hostable Git server for the command line.",
65		Args:                  cobra.MinimumNArgs(1),
66		DisableFlagsInUseLine: true,
67	}
68	rootCmd.SetUsageTemplate(usageTemplate)
69	rootCmd.CompletionOptions.DisableDefaultCmd = true
70	rootCmd.AddCommand(
71		RepoCommand(),
72	)
73
74	return rootCmd
75}
76
77func fromContext(cmd *cobra.Command) (*config.Config, ssh.Session) {
78	ctx := cmd.Context()
79	cfg := ctx.Value(ConfigCtxKey).(*config.Config)
80	s := ctx.Value(SessionCtxKey).(ssh.Session)
81	return cfg, s
82}