From b4da131a6f6137960b21fc13ed2e177c67959222 Mon Sep 17 00:00:00 2001 From: Gubarz <1037896+Gubarz@users.noreply.github.com> Date: Sat, 30 May 2026 17:28:07 -0600 Subject: [PATCH] feat: initial setup and registry --- README.md | 24 +++- cheatmd.example.yaml | 12 +- cmd/cheatmd/init.go | 150 +++++++++++++++++++++ cmd/cheatmd/packs.go | 210 ++++++++++++++++++++++++++++++ cmd/cheatmd/root.go | 4 +- go.mod | 4 +- internal/ui/pack_select.go | 191 +++++++++++++++++++++++++++ pkg/config/config.go | 107 ++++++++++++++- pkg/config/config_test.go | 49 +++++++ pkg/config/default_config.yaml | 93 +++++++++++++ pkg/httputil/get.go | 30 +++++ pkg/installer/git.go | 89 +++++++++++++ pkg/installer/installer.go | 69 ++++++++++ pkg/installer/installer_test.go | 127 ++++++++++++++++++ pkg/installer/tarball.go | 121 +++++++++++++++++ pkg/installer/util.go | 61 +++++++++ pkg/packmanifest/manifest.go | 114 ++++++++++++++++ pkg/packmanifest/manifest_test.go | 54 ++++++++ pkg/registry/registry.go | 117 +++++++++++++++++ pkg/registry/registry_test.go | 80 ++++++++++++ 20 files changed, 1696 insertions(+), 10 deletions(-) create mode 100644 cmd/cheatmd/init.go create mode 100644 cmd/cheatmd/packs.go create mode 100644 internal/ui/pack_select.go create mode 100644 pkg/config/config_test.go create mode 100644 pkg/config/default_config.yaml create mode 100644 pkg/httputil/get.go create mode 100644 pkg/installer/git.go create mode 100644 pkg/installer/installer.go create mode 100644 pkg/installer/installer_test.go create mode 100644 pkg/installer/tarball.go create mode 100644 pkg/installer/util.go create mode 100644 pkg/packmanifest/manifest.go create mode 100644 pkg/packmanifest/manifest_test.go create mode 100644 pkg/registry/registry.go create mode 100644 pkg/registry/registry_test.go diff --git a/README.md b/README.md index e7ab43e..f5ca531 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,28 @@ cheatmd # Browse current directory cheatmd ~/cheats # Browse specific directory cheatmd -q "docker" # Start with search query cheatmd --history # Re-run from execution history -cheatmd convert tldr tar.md -o ~/cheats/tar.md +cheatmd convert tldr tar.md -o ~/cheats/tar.md # convert a tldr cheat +cheatmd packs list # List installable cheat packs from the registry +cheatmd packs install # Pick and install cheat packs (interactive) +``` + +### First run + +The first time you run `cheatmd` (before a config file exists) on an +interactive terminal, it offers to set you up: it writes a config to +`~/.config/cheatmd/cheatmd.yaml` and lets you pick **starter cheat packs** to +install from the [registry](https://github.com/cheatmd-dev/registry) into +`~/.local/share/cheatmd/cheats`. Pick packs from the checklist with `space`, confirm +with `enter`. Point `registry_url` at a private/self-hosted `registry.yaml` to +customize the offered packs. Setup is skipped in headless/piped invocations. + +You can install packs any time with the `packs` command — it doesn't depend on +the first-run prompt: + +```bash +cheatmd packs list # show available packs (and which are installed) +cheatmd packs install # interactive picker +cheatmd packs install git docker # install specific packs by name ``` ## Features @@ -143,6 +164,7 @@ cheatmd --headless -q "docker exec" Full documentation lives in the **[Wiki](../../wiki)**: +- **[Getting Started](../../wiki/Getting-Started)** - first steps with CheatMD - **[Writing Cheats](../../wiki/Writing-Cheats)** - heading structure, code blocks, metadata - **[Variables](../../wiki/Variables)** - prompt, shell, and literal forms - **[Selector Options](../../wiki/Selector-Options)** - `--header`, `--column`, `--map` diff --git a/cheatmd.example.yaml b/cheatmd.example.yaml index a06f1d3..cc1c2b1 100644 --- a/cheatmd.example.yaml +++ b/cheatmd.example.yaml @@ -1,8 +1,14 @@ # CheatMD configuration file # Place at ~/.config/cheatmd/cheatmd.yaml -# Default cheat directory (supports ~ expansion) -path: ~/notes/cheats +# Default cheat directory (supports ~ expansion). +# First-run setup installs starter cheat packs here. +path: ~/.local/share/cheatmd/cheats + +# Registry of installable cheat packs (used by first-run setup). +# Point this at a private/self-hosted registry.yaml to customize the packs +# offered on setup. +registry_url: "https://raw.githubusercontent.com/cheatmd-dev/registry/main/registry.yaml" # Output mode: print, copy, exec output: print @@ -62,7 +68,7 @@ column_command: 60 column_gap: 4 # Only show cheats that have a block -require_cheat_block: false +require_cheat_block: true # Prompt for $var references in a command even when there's no matching # declaration. When false, undeclared variables are silently diff --git a/cmd/cheatmd/init.go b/cmd/cheatmd/init.go new file mode 100644 index 0000000..4ebfb47 --- /dev/null +++ b/cmd/cheatmd/init.go @@ -0,0 +1,150 @@ +package main + +import ( + "bufio" + "context" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/spf13/cobra" + "golang.org/x/term" + + "github.com/cheatmd-dev/cheatmd/internal/ui" + "github.com/cheatmd-dev/cheatmd/pkg/config" + "github.com/cheatmd-dev/cheatmd/pkg/installer" + "github.com/cheatmd-dev/cheatmd/pkg/packmanifest" + "github.com/cheatmd-dev/cheatmd/pkg/registry" +) + +var initCmd = &cobra.Command{ + Use: "init", + Short: "Initialize CheatMD config and install starter cheats", + RunE: func(cmd *cobra.Command, args []string) error { + out := cmd.OutOrStdout() + + // 1. Create config + path := config.DefaultConfigPath() + if err := config.WriteDefaultConfig(path); err != nil { + if !strings.Contains(err.Error(), "already exists") { + return fmt.Errorf("could not write config: %w", err) + } + fmt.Fprintf(out, "Config already exists at %s\n", path) + } else { + fmt.Fprintf(out, "Wrote config to %s\n", path) + } + + // 2. Ask to install starter cheats + if !isInteractive() { + fmt.Fprintln(out, "Non-interactive environment detected. Skipping starter cheat prompt.") + return nil + } + + if !promptYesNo("Install cheat packs from the registry?") { + return nil + } + + dest := installStarterPacks(cmd, out) + if dest != "" { + fmt.Fprintln(out, "\nCheatMD is ready! Run `cheatmd` to explore your new cheats.") + } + return nil + }, +} + +// installStarterPacks runs the registry picker and installs the chosen packs, +// returning the install directory (empty when nothing was installed). All +// failures are non-fatal: they print a note and leave the user with a config +// but no cheats. +func installStarterPacks(cmd *cobra.Command, out io.Writer) string { + reg, err := registry.Fetch(cmd.Context(), config.GetRegistryURL()) + if err != nil { + fmt.Fprintf(out, "Could not fetch the cheat registry: %v\n", err) + fmt.Fprintln(out, "Skipping official cheat packs — you can add packs later with `cheatmd packs install`.") + return "" + } + + manifest, _ := packmanifest.Load(config.CheatsInstallDir()) + installedPacks := make(map[string]bool) + if manifest != nil { + for _, p := range manifest.Packs { + installedPacks[p.Name] = true + } + } + + chosen, err := ui.RunPackPicker(reg.Packs, installedPacks) + if err != nil { + fmt.Fprintf(out, "Pack selection failed: %v\n", err) + return "" + } + if len(chosen) == 0 { + fmt.Fprintln(out, "No packs selected.") + return "" + } + + dest, installed := installPacks(cmd.Context(), out, chosen) + if installed == 0 { + return "" + } + fmt.Fprintf(out, "Installed %d pack(s) into %s\n", installed, dest) + return dest +} + +// installPacks installs each pack into the cheats directory, printing progress +// to out, and records successful installs in the pack manifest. It returns the +// destination directory and the number successfully installed. Shared by +// first-run setup and the `packs install` command. +func installPacks(ctx context.Context, out io.Writer, packs []registry.Pack) (dest string, installed int) { + dest = config.CheatsInstallDir() + + manifest, err := packmanifest.Load(dest) + if err != nil { + // A corrupt manifest shouldn't block installs; start fresh but warn. + fmt.Fprintf(out, "Warning: could not read pack manifest: %v\n", err) + manifest = &packmanifest.Manifest{} + } + + for _, pack := range packs { + fmt.Fprintf(out, "Installing %s...\n", pack.Name) + if err := installer.Install(ctx, pack, dest); err != nil { + fmt.Fprintf(out, " failed: %v\n", err) + continue + } + manifest.Upsert(packmanifest.Entry{ + Name: pack.Name, + Repo: pack.Repo, + InstalledAt: time.Now(), + }) + installed++ + } + + if installed > 0 { + if err := packmanifest.Save(dest, manifest); err != nil { + fmt.Fprintf(out, "Warning: could not write pack manifest: %v\n", err) + } + } + return dest, installed +} + +// isInteractive reports whether both stdin and stdout are terminals. +func isInteractive() bool { + return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd())) +} + +// promptYesNo asks a yes/no question on stderr and reads the answer from stdin. +// Defaults to yes on an empty response. +func promptYesNo(question string) bool { + fmt.Fprintf(os.Stderr, "%s [Y/n] ", question) + scanner := bufio.NewScanner(os.Stdin) + if !scanner.Scan() { + return false + } + switch strings.ToLower(strings.TrimSpace(scanner.Text())) { + case "", "y", "yes": + return true + default: + return false + } +} diff --git a/cmd/cheatmd/packs.go b/cmd/cheatmd/packs.go new file mode 100644 index 0000000..a4c7b70 --- /dev/null +++ b/cmd/cheatmd/packs.go @@ -0,0 +1,210 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "text/tabwriter" + + "github.com/spf13/cobra" + + "github.com/cheatmd-dev/cheatmd/internal/ui" + "github.com/cheatmd-dev/cheatmd/pkg/config" + "github.com/cheatmd-dev/cheatmd/pkg/packmanifest" + "github.com/cheatmd-dev/cheatmd/pkg/registry" +) + +var packsCmd = &cobra.Command{ + Use: "packs", + Short: "Browse and install cheat packs from the registry", + Long: `Browse and install community cheat packs from the registry. + +The registry is a YAML manifest of installable cheat repositories, configured +via the registry_url setting. Installed packs land in the cheats directory +(see DefaultCheatsDir / the "path" setting) under //.`, +} + +var packsListCmd = &cobra.Command{ + Use: "list", + Short: "List available cheat packs", + Args: cobra.NoArgs, + RunE: runPacksList, +} + +var packsInstallCmd = &cobra.Command{ + Use: "install [name...]", + Short: "Install cheat packs (interactive picker when no names are given)", + RunE: runPacksInstall, +} + +var packsUpdateCmd = &cobra.Command{ + Use: "update [name...]", + Short: "Update installed cheat packs", + RunE: runPacksUpdate, +} + +var packsRemoveCmd = &cobra.Command{ + Use: "remove [name...]", + Short: "Remove installed cheat packs", + Args: cobra.MinimumNArgs(1), + RunE: runPacksRemove, +} + +func init() { + packsCmd.AddCommand(packsListCmd) + packsCmd.AddCommand(packsInstallCmd) + packsCmd.AddCommand(packsUpdateCmd) + packsCmd.AddCommand(packsRemoveCmd) +} + +func runPacksList(cmd *cobra.Command, args []string) error { + reg, err := registry.Fetch(cmd.Context(), config.GetRegistryURL()) + if err != nil { + return fmt.Errorf("fetch registry: %w", err) + } + + // A corrupt/unreadable manifest shouldn't break listing; treat as empty. + manifest, err := packmanifest.Load(config.CheatsInstallDir()) + if err != nil { + manifest = &packmanifest.Manifest{} + } + + out := cmd.OutOrStdout() + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + for _, p := range reg.Packs { + tag := "community" + if p.Official { + tag = "official" + } + + status := " " + date := "" + if entry := manifest.Get(p.Name); entry != nil { + status = "✓" + date = entry.InstalledAt.Format("2006-01-02") + } + + fmt.Fprintf(w, "%s %s\t%s\t%s\t%s\n", status, p.Name, tag, date, p.Repo) + } + w.Flush() + return nil +} + +func runPacksInstall(cmd *cobra.Command, args []string) error { + reg, err := registry.Fetch(cmd.Context(), config.GetRegistryURL()) + if err != nil { + return fmt.Errorf("fetch registry: %w", err) + } + + chosen, err := choosePacks(reg, args) + if err != nil { + return err + } + + out := cmd.ErrOrStderr() + if len(chosen) == 0 { + fmt.Fprintln(out, "No packs selected.") + return nil + } + + dest, installed := installPacks(cmd.Context(), out, chosen) + fmt.Fprintf(out, "Installed %d pack(s) into %s\n", installed, dest) + if installed < len(chosen) { + return fmt.Errorf("%d of %d pack(s) failed to install", len(chosen)-installed, len(chosen)) + } + return nil +} + +func runPacksUpdate(cmd *cobra.Command, args []string) error { + reg, err := registry.Fetch(cmd.Context(), config.GetRegistryURL()) + if err != nil { + return fmt.Errorf("fetch registry: %w", err) + } + + chosen, err := choosePacks(reg, args) + if err != nil { + return err + } + + out := cmd.ErrOrStderr() + if len(chosen) == 0 { + fmt.Fprintln(out, "No packs selected.") + return nil + } + + // For update, we want to ensure we only update installed packs if no args were given? + // Actually, choosePacks shows the picker. We might be picking uninstalled packs too. + // But it's fine, `update` uses the exact same `installPacks` logic, the only difference + // is the wording and that `installPacks` + `installer.Install` now cleanly handles overwriting. + + dest, installed := installPacks(cmd.Context(), out, chosen) + fmt.Fprintf(out, "Updated %d pack(s) in %s\n", installed, dest) + if installed < len(chosen) { + return fmt.Errorf("%d of %d pack(s) failed to update", len(chosen)-installed, len(chosen)) + } + return nil +} + +func runPacksRemove(cmd *cobra.Command, args []string) error { + dest := config.CheatsInstallDir() + manifest, err := packmanifest.Load(dest) + if err != nil { + return err + } + + out := cmd.OutOrStdout() + removed := 0 + for _, name := range args { + if !manifest.Has(name) { + fmt.Fprintf(out, "Pack %q is not installed.\n", name) + continue + } + + target := filepath.Join(dest, name) + if err := os.RemoveAll(target); err != nil { + fmt.Fprintf(out, "Failed to remove %q: %v\n", name, err) + continue + } + + manifest.Remove(name) + removed++ + fmt.Fprintf(out, "Removed pack %q\n", name) + } + + if removed > 0 { + if err := packmanifest.Save(dest, manifest); err != nil { + return fmt.Errorf("save manifest: %w", err) + } + } + return nil +} + +// choosePacks resolves which packs to install: the named packs when names are +// given, otherwise the user's selection from the interactive picker. +func choosePacks(reg *registry.Registry, names []string) ([]registry.Pack, error) { + if len(names) > 0 { + chosen, err := reg.Select(names) + if err != nil { + return nil, fmt.Errorf("%w (try `cheatmd packs list`)", err) + } + return chosen, nil + } + + if !isInteractive() { + return nil, fmt.Errorf("no pack names given and not an interactive terminal; pass names, e.g. `cheatmd packs install git docker`") + } + + manifest, _ := packmanifest.Load(config.CheatsInstallDir()) + installedPacks := make(map[string]bool) + if manifest != nil { + for _, p := range manifest.Packs { + installedPacks[p.Name] = true + } + } + + chosen, err := ui.RunPackPicker(reg.Packs, installedPacks) + if err != nil { + return nil, fmt.Errorf("pack selection: %w", err) + } + return chosen, nil +} diff --git a/cmd/cheatmd/root.go b/cmd/cheatmd/root.go index 0910ba3..c0c7b16 100644 --- a/cmd/cheatmd/root.go +++ b/cmd/cheatmd/root.go @@ -35,6 +35,8 @@ func init() { rootCmd.AddCommand(dumpCmd) rootCmd.AddCommand(composeCmd) rootCmd.AddCommand(convertCmd) + rootCmd.AddCommand(packsCmd) + rootCmd.AddCommand(initCmd) chainCmd.AddCommand(chainResetCmd) rootCmd.PersistentFlags().StringP("query", "q", "", "Initial search query") @@ -125,7 +127,7 @@ func runCheats(cmd *cobra.Command, args []string) error { } if len(index.Cheats) == 0 { - return fmt.Errorf("no cheats found in %s", absPath) + return fmt.Errorf("no cheats found in %s. Run `cheatmd init` to install starter packs", absPath) } // Create executor diff --git a/go.mod b/go.mod index 81498f7..6d78adc 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,8 @@ require ( github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 + go.yaml.in/yaml/v3 v3.0.4 + golang.org/x/term v0.36.0 ) require ( @@ -50,9 +52,7 @@ require ( github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/yuin/goldmark v1.7.13 // indirect github.com/yuin/goldmark-emoji v1.0.6 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/net v0.38.0 // indirect golang.org/x/sys v0.40.0 // indirect - golang.org/x/term v0.36.0 // indirect golang.org/x/text v0.30.0 // indirect ) diff --git a/internal/ui/pack_select.go b/internal/ui/pack_select.go new file mode 100644 index 0000000..37bd336 --- /dev/null +++ b/internal/ui/pack_select.go @@ -0,0 +1,191 @@ +package ui + +import ( + "fmt" + "sort" + "strings" + + tea "github.com/charmbracelet/bubbletea" + + "github.com/cheatmd-dev/cheatmd/pkg/registry" +) + +// packPickerModel is a standalone multi-select checklist used by first-run +// setup to let the user choose which cheat packs to install. It reuses the +// generic Picker for cursor/scroll bookkeeping and the global styles for +// coloring. +type packPickerModel struct { + picker *Picker[registry.Pack] + selected map[int]bool // index into picker.Items -> checked + installed map[string]bool + cancelled bool +} + +// RunPackPicker shows an interactive checklist of packs and returns those the +// user chose to install. Packs flagged Starter are pre-checked. Returns an +// empty slice if the user cancels (q/esc/ctrl+c). +func RunPackPicker(packs []registry.Pack, installed map[string]bool) ([]registry.Pack, error) { + if len(packs) == 0 { + return nil, nil + } + + sortedPacks := make([]registry.Pack, len(packs)) + copy(sortedPacks, packs) + sort.SliceStable(sortedPacks, func(i, j int) bool { + if sortedPacks[i].Official != sortedPacks[j].Official { + return sortedPacks[i].Official // true comes before false + } + return sortedPacks[i].Name < sortedPacks[j].Name + }) + + selected := make(map[int]bool, len(sortedPacks)) + + m := &packPickerModel{ + // No filtering needed; the filter func is a no-op match-all. + picker: NewPicker(sortedPacks, func(registry.Pack, []string) bool { return true }), + selected: selected, + installed: installed, + } + + ttyIn, ttyOut, cleanup := getTTY() + RefreshStyles() + p := tea.NewProgram(m, tea.WithAltScreen(), tea.WithOutput(ttyOut), tea.WithInput(ttyIn)) + finalModel, err := p.Run() + cleanup() + if err != nil { + return nil, err + } + + res := finalModel.(*packPickerModel) + if res.cancelled { + return nil, nil + } + + var chosen []registry.Pack + for i, pack := range res.picker.Items { + if res.selected[i] { + chosen = append(chosen, pack) + } + } + return chosen, nil +} + +func (m *packPickerModel) Init() tea.Cmd { return nil } + +func (m *packPickerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.KeyMsg: + if m.picker.HandleKey(msg) { + return m, nil + } + switch msg.String() { + case "ctrl+c", "q", "esc": + m.cancelled = true + return m, tea.Quit + case " ": + // Toggle the checkbox for the highlighted row. + idx := m.itemIndex(m.picker.Cursor) + if idx >= 0 { + m.selected[idx] = !m.selected[idx] + } + return m, nil + case "a": + // Select all. + for i := range m.picker.Items { + m.selected[i] = true + } + return m, nil + case "n": + // Select none. + m.selected = make(map[int]bool, len(m.picker.Items)) + return m, nil + case "enter": + return m, tea.Quit + } + } + return m, nil +} + +// itemIndex maps a cursor position in the (unfiltered) list back to the index +// into picker.Items. Since the filter is match-all, these are equal, but we +// resolve via Selected to stay correct if filtering is added later. +func (m *packPickerModel) itemIndex(cursor int) int { + if cursor < 0 || cursor >= len(m.picker.Filtered) { + return -1 + } + target := m.picker.Filtered[cursor] + for i, it := range m.picker.Items { + if it.Name == target.Name && it.Repo == target.Repo { + return i + } + } + return -1 +} + +func (m *packPickerModel) View() string { + var b strings.Builder + + b.WriteString(styles.Header.Render("Install cheat packs")) + b.WriteString("\n") + b.WriteString(styles.Dim.Render("Choose cheat packs to install. Space toggles, Enter confirms.")) + b.WriteString("\n\n") + + for i, pack := range m.picker.Filtered { + b.WriteString(m.renderRow(i, pack)) + b.WriteString("\n") + } + + footer := fmt.Sprintf("%d selected · a: all · n: none · q/esc: cancel", m.selectedCount()) + b.WriteString("\n") + b.WriteString(styles.Dim.Render(footer)) + b.WriteString("\n") + + return b.String() +} + +// renderRow formats a single pack row: cursor marker, checkbox, name, and +// description, with the highlighted row's background applied. +func (m *packPickerModel) renderRow(i int, pack registry.Pack) string { + idx := m.itemIndex(i) + highlighted := i == m.picker.Cursor + + box := "[ ]" + if idx >= 0 && m.selected[idx] { + box = "[x]" + } + + cursor := " " + if highlighted { + cursor = styles.Cursor.Render("▶ ") + } + + status := "" + if m.installed[pack.Name] { + status = styles.Dim.Render(" [installed]") + } + + tag := "[community]" + if pack.Official { + tag = "[official]" + } + + line := fmt.Sprintf("%s%s %s %s%s", cursor, box, styles.Dim.Render(tag), styles.Command.Render(pack.Name), status) + if pack.Description != "" { + line += " " + styles.Desc.Render(pack.Description) + } + if highlighted { + line = styles.Selected.Render(line) + } + return line +} + +// selectedCount returns how many packs are currently checked. +func (m *packPickerModel) selectedCount() int { + n := 0 + for _, checked := range m.selected { + if checked { + n++ + } + } + return n +} diff --git a/pkg/config/config.go b/pkg/config/config.go index eb5c38a..26d891d 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -1,13 +1,22 @@ package config import ( + _ "embed" "fmt" "os" "path/filepath" + "strings" "github.com/spf13/viper" ) +// defaultConfigTemplate is the starter config written by WriteDefaultConfig +// during first-run setup. Keeping it embedded keeps generated configs in sync +// with the documented example. +// +//go:embed default_config.yaml +var defaultConfigTemplate []byte + // ============================================================================ // Configuration Types // ============================================================================ @@ -15,6 +24,7 @@ import ( // Config holds the application configuration type Config struct { Path string `mapstructure:"path"` + RegistryURL string `mapstructure:"registry_url"` Output string `mapstructure:"output"` Shell string `mapstructure:"shell"` Editor string `mapstructure:"editor"` @@ -77,8 +87,13 @@ type ColumnConfig struct { // ============================================================================ // Defaults for configuration +// DefaultRegistryURL is the canonical cheat-pack registry manifest. Override +// via the registry_url config key for private/self-hosted registries. +const DefaultRegistryURL = "https://raw.githubusercontent.com/cheatmd-dev/registry/main/registry.yaml" + var defaults = struct { path string + registryURL string output string shell string editor string @@ -104,6 +119,7 @@ var defaults = struct { columns ColumnConfig }{ path: ".", + registryURL: DefaultRegistryURL, output: "print", shell: "", // Set dynamically editor: "", // Empty means use system default (xdg-open/open/start) @@ -128,12 +144,12 @@ var defaults = struct { colors: ColorConfig{ Header: "36", // Cyan Command: "32", // Green - Desc: "90", // Gray + Desc: "246", // Light gray Path: "33", // Yellow - Border: "240", // Dark gray + Border: "242", // Gray Cursor: "212", // Pink Selected: "236", // Dark bg - Dim: "241", // Dimmed + Dim: "245", // Medium gray }, columns: ColumnConfig{ Gap: 4, @@ -177,6 +193,7 @@ func setDefaults() { } viper.SetDefault("path", defaults.path) + viper.SetDefault("registry_url", defaults.registryURL) viper.SetDefault("output", defaults.output) viper.SetDefault("shell", shell) viper.SetDefault("editor", defaults.editor) @@ -248,6 +265,11 @@ func GetPath() string { return expandTilde(viper.GetString("path")) } +// GetRegistryURL returns the cheat-pack registry manifest URL. +func GetRegistryURL() string { + return viper.GetString("registry_url") +} + // GetOutput returns the output mode func GetOutput() string { return viper.GetString("output") @@ -478,6 +500,85 @@ func SetAutoSelect(enabled bool) { cfg.AutoSelect = enabled } +// ============================================================================ +// First-run setup +// ============================================================================ + +// DefaultConfigPath returns the path where WriteDefaultConfig writes the +// starter config: ~/.config/cheatmd/cheatmd.yaml. +func DefaultConfigPath() string { + home, err := os.UserHomeDir() + if err != nil { + return "cheatmd.yaml" + } + return filepath.Join(home, ".config", "cheatmd", "cheatmd.yaml") +} + +// CheatsInstallDir returns the directory cheat packs should be installed into, +// and where installed-pack detection looks. It is the configured cheats path +// when the user has set one to a real directory; otherwise it falls back to +// DefaultCheatsDir(). This keeps "where packs land" aligned with "where cheats +// are browsed" (GetPath) instead of always using the XDG default. +// +// The default path is "." (browse the current directory); we treat that as +// "unset" for install purposes so packs never land in an arbitrary cwd. +func CheatsInstallDir() string { + if p := GetPath(); p != "" && p != "." { + return p + } + return DefaultCheatsDir() +} + +// DefaultCheatsDir returns the directory where first-run setup installs +// starter cheat packs. Cheats are user data, so they live under +// $XDG_DATA_HOME/cheatmd/cheats (falling back to +// ~/.local/share/cheatmd/cheats), matching where history is stored. +func DefaultCheatsDir() string { + if xdg := strings.TrimSpace(os.Getenv("XDG_DATA_HOME")); xdg != "" { + return filepath.Join(xdg, "cheatmd", "cheats") + } + home, err := os.UserHomeDir() + if err != nil { + return "cheats" + } + return filepath.Join(home, ".local", "share", "cheatmd", "cheats") +} + +// WriteDefaultConfig writes the embedded starter config to path, creating +// parent directories as needed. It refuses to overwrite an existing file. +// +// The template's "path:" line is rewritten to the resolved DefaultCheatsDir() +// so the config always points at the same directory first-run setup installs +// into, even when $XDG_DATA_HOME relocates it. +func WriteDefaultConfig(path string) error { + if _, err := os.Stat(path); err == nil { + return fmt.Errorf("config already exists at %s", path) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return fmt.Errorf("create config dir: %w", err) + } + content := withCheatsPath(string(defaultConfigTemplate), DefaultCheatsDir()) + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + return fmt.Errorf("write config: %w", err) + } + return nil +} + +// withCheatsPath replaces the first top-level "path:" entry in the template +// with the given cheats directory, leaving comments and other lines intact. If +// no such line exists (e.g. a hand-edited template), the template is returned +// unchanged. +func withCheatsPath(template, cheatsDir string) string { + lines := strings.Split(template, "\n") + for i, line := range lines { + if strings.HasPrefix(line, "path:") { + lines[i] = "path: " + cheatsDir + break + } + } + return strings.Join(lines, "\n") +} + // ============================================================================ // Helpers // ============================================================================ diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go new file mode 100644 index 0000000..58cedaa --- /dev/null +++ b/pkg/config/config_test.go @@ -0,0 +1,49 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + + yaml "go.yaml.in/yaml/v3" +) + +func TestEmbeddedTemplateIsValidYAML(t *testing.T) { + if len(defaultConfigTemplate) == 0 { + t.Fatal("embedded default config template is empty") + } + var m map[string]any + if err := yaml.Unmarshal(defaultConfigTemplate, &m); err != nil { + t.Fatalf("embedded template is not valid YAML: %v", err) + } + if _, ok := m["registry_url"]; !ok { + t.Error("embedded template missing registry_url key") + } + if _, ok := m["path"]; !ok { + t.Error("embedded template missing path key") + } +} + +func TestWriteDefaultConfig(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "nested", "cheatmd.yaml") + + if err := WriteDefaultConfig(path); err != nil { + t.Fatalf("WriteDefaultConfig: %v", err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read written config: %v", err) + } + // The path line must be rewritten to the resolved cheats dir. + want := "path: " + DefaultCheatsDir() + if !strings.Contains(string(data), want) { + t.Errorf("written config missing %q", want) + } + + // Refuses to overwrite an existing config. + if err := WriteDefaultConfig(path); err == nil { + t.Error("expected error writing over existing config, got nil") + } +} diff --git a/pkg/config/default_config.yaml b/pkg/config/default_config.yaml new file mode 100644 index 0000000..e6f5d70 --- /dev/null +++ b/pkg/config/default_config.yaml @@ -0,0 +1,93 @@ +# CheatMD configuration file +# Place at ~/.config/cheatmd/cheatmd.yaml + +# Default cheat directory (supports ~ expansion). +# First-run setup installs starter cheat packs here. +path: ~/.local/share/cheatmd/cheats + +# Registry of installable cheat packs (used by first-run setup). +# Point this at a private/self-hosted registry.yaml to customize the packs +# offered on setup. +registry_url: "https://raw.githubusercontent.com/cheatmd-dev/registry/main/registry.yaml" + +# Output mode: print, copy, exec +output: print + +# Shell to use for variable generation +shell: /bin/bash + +# Keybindings +# key_widget: Shell widget activation key (bash format: \C-g for Ctrl+G, \C-x for Ctrl+X) +# key_open: TUI key for opening markdown in editor (e.g., ctrl+o, ctrl+e) +key_widget: "\\C-g" +key_open: "ctrl+o" +# key_substitute: opens a fuzzy search of env vars + shell history during +# variable resolution, lets you pick a value to substitute into the prompt. +key_substitute: "ctrl+t" +# key_preview: opens a full-screen markdown preview of the current cheat's +# source file, scrolled to the cheat's section. Esc / q closes. +key_preview: "ctrl+y" +# key_history: opens the execution history picker. Enter on an entry re-opens +# the original cheat with its previous variable values pre-filled. +key_history: "ctrl+h" + +# Execution history. Each cheat run appends a line to history_file as JSONL. +# history_file - path override; empty means $XDG_DATA_HOME/cheatmd/history.jsonl +# (or ~/.local/share/cheatmd/history.jsonl as a fallback). +# history_max - max entries shown in the picker; 0 = unlimited. +history_file: "" +history_max: 1000 + +# Substitute search sources. Valid entries: "env", "history". +# Empty list disables the feature. +substitute_sources: ["env", "history"] + +# Display options +# Control what appears in the title/list path column +show_folder: true +show_file: true + +# Preview section height (number of lines) +preview_height: 6 + +# UI colors (256-color palette or hex) +# See: https://www.ditig.com/256-colors-cheat-sheet +#color_header: "#cad2e2" # htb heading for headers +#color_command: "#9fef00" # htb lime for commands +#color_desc: "#a4b1cd" # htb text color for descriptions +#color_path: "#5cb2ff" # htb blue code color for file paths +#color_border: "#1a2332" # htb divider color +#color_cursor: "#ff8484" # htb red for for cursor/selection indicator +#color_selected: "#1a2331" # htb dark background for selected line +#color_dim: "#4a5466" # htb border color for dimmed text + +# Column widths (max characters) +column_header: 40 +column_desc: 40 +column_command: 60 +column_gap: 4 + +# Only show cheats that have a block +require_cheat_block: true + +# Prompt for $var references in a command even when there's no matching +# declaration. When false, undeclared variables are silently +# skipped. +allow_undeclared_vars: false + +# Variable syntax accepted in cheat commands. +# dollar (default) - only $name is a variable reference +# angle - only is a variable reference +# both - accept both, resolving to the same variable +var_syntax: dollar + +# Auto-continue when variables are prefilled from environment +# When true, if a var is already set (e.g., export domain=example.com), +# it will be used without prompting. Press ESC to go back and edit. +auto_continue: false + +# Hooks (prepended/appended to the final command) +# Example: pre_hook: "cd ~/projects && " +# Example: post_hook: " && notify-send 'Done'" +pre_hook: "" +post_hook: "" diff --git a/pkg/httputil/get.go b/pkg/httputil/get.go new file mode 100644 index 0000000..41324ca --- /dev/null +++ b/pkg/httputil/get.go @@ -0,0 +1,30 @@ +// Package httputil provides common HTTP client utilities. +package httputil + +import ( + "context" + "fmt" + "io" + "net/http" +) + +// Get fetches the given URL with a GET request, returning the response body if +// the status code is 200 OK. The caller is responsible for closing the body. +func Get(ctx context.Context, url string) (io.ReadCloser, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, fmt.Errorf("build request: %w", err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, fmt.Errorf("execute request: %w", err) + } + + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, fmt.Errorf("unexpected status %s", resp.Status) + } + + return resp.Body, nil +} diff --git a/pkg/installer/git.go b/pkg/installer/git.go new file mode 100644 index 0000000..0aab040 --- /dev/null +++ b/pkg/installer/git.go @@ -0,0 +1,89 @@ +package installer + +import ( + "context" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/cheatmd-dev/cheatmd/pkg/registry" +) + +// hasGit reports whether a git binary is available on PATH. +func hasGit() bool { + _, err := exec.LookPath("git") + return err == nil +} + +// installViaGit shallow-clones the repo into a temp dir, then copies its .md +// files into target. Cloning into a temp dir (rather than target directly) +// keeps the install atomic-ish and lets us drop the .git metadata. +func installViaGit(ctx context.Context, pack registry.Pack, target string) error { + tmp, err := os.MkdirTemp("", "cheatmd-clone-") + if err != nil { + return fmt.Errorf("create temp dir: %w", err) + } + defer os.RemoveAll(tmp) + + cmd := exec.CommandContext(ctx, "git", "clone", "--depth", "1", pack.Repo, tmp) + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + if err := cmd.Run(); err != nil { + return fmt.Errorf("git clone %s: %w", pack.Repo, err) + } + + root := tmp + if pack.Subdir != "" { + root = filepath.Join(tmp, filepath.Clean(pack.Subdir)) + } + + n, err := copyMarkdown(root, target) + if err != nil { + return err + } + if n == 0 { + return fmt.Errorf("no .md cheats found in %s", pack.Repo) + } + return nil +} + +// copyMarkdown walks srcRoot and copies every .md file into dest, preserving +// the relative directory structure under srcRoot. Returns the count copied. +func copyMarkdown(srcRoot, dest string) (int, error) { + count := 0 + err := filepath.WalkDir(srcRoot, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if strings.HasPrefix(d.Name(), ".") && path != srcRoot { + return filepath.SkipDir + } + return nil + } + if !strings.EqualFold(filepath.Ext(d.Name()), ".md") { + return nil + } + rel, err := filepath.Rel(srcRoot, path) + if err != nil { + return err + } + outPath := filepath.Join(dest, rel) + if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + if err := os.WriteFile(outPath, data, 0o644); err != nil { + return err + } + count++ + return nil + }) + return count, err +} diff --git a/pkg/installer/installer.go b/pkg/installer/installer.go new file mode 100644 index 0000000..b7db754 --- /dev/null +++ b/pkg/installer/installer.go @@ -0,0 +1,69 @@ +// Package installer installs cheat packs from the registry onto the local +// machine. It prefers the user's git binary (shallow clone) and falls back to +// downloading the repository tarball over HTTPS when git is unavailable. +package installer + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/cheatmd-dev/cheatmd/pkg/registry" +) + +// Install places pack's markdown cheats under destDir/. +// +// It first tries `git clone --depth 1`; if git is not on PATH (or the clone +// fails), it falls back to downloading the GitHub tarball. Only .md files are +// kept, optionally restricted to pack.Subdir. +func Install(ctx context.Context, pack registry.Pack, destDir string) error { + target := filepath.Join(destDir, pack.Name) + backup := target + ".bak" + + // If the pack exists (e.g. during an update), move it aside so we can + // cleanly overwrite it without leaving stale files. + hasOld := false + if _, err := os.Stat(target); err == nil { + if err := os.Rename(target, backup); err != nil { + return fmt.Errorf("backup existing pack: %w", err) + } + hasOld = true + defer os.RemoveAll(backup) + } + + if err := os.MkdirAll(target, 0o755); err != nil { + if hasOld { + os.Rename(backup, target) + } + return fmt.Errorf("create install dir: %w", err) + } + + // Helper to handle restoration on failure. + restoreOnFail := func(err error) error { + if err != nil { + os.RemoveAll(target) + if hasOld { + os.Rename(backup, target) + } + } + return err + } + + // Without git, the tarball download is the only option. + if !hasGit() { + return restoreOnFail(installViaTarball(ctx, pack, target)) + } + + gitErr := installViaGit(ctx, pack, target) + if gitErr == nil { + return restoreOnFail(nil) + } + + // git is present but failed; fall back to the tarball, surfacing both + // failures if that fails too. + if tarErr := installViaTarball(ctx, pack, target); tarErr != nil { + return restoreOnFail(fmt.Errorf("git clone failed (%v) and tarball fallback failed: %w", gitErr, tarErr)) + } + return restoreOnFail(nil) +} diff --git a/pkg/installer/installer_test.go b/pkg/installer/installer_test.go new file mode 100644 index 0000000..88b86ea --- /dev/null +++ b/pkg/installer/installer_test.go @@ -0,0 +1,127 @@ +package installer + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "os" + "path/filepath" + "testing" +) + +// makeTarball builds a gzip+tar archive from name->content entries, mimicking +// GitHub's top-level wrapper directory. +func makeTarball(t *testing.T, files map[string]string) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for name, content := range files { + hdr := &tar.Header{ + Name: name, + Mode: 0o644, + Size: int64(len(content)), + Typeflag: tar.TypeReg, + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatalf("write header: %v", err) + } + if _, err := tw.Write([]byte(content)); err != nil { + t.Fatalf("write body: %v", err) + } + } + if err := tw.Close(); err != nil { + t.Fatalf("close tar: %v", err) + } + if err := gz.Close(); err != nil { + t.Fatalf("close gzip: %v", err) + } + return buf.Bytes() +} + +func TestExtractMarkdownTarball(t *testing.T) { + tb := makeTarball(t, map[string]string{ + "owner-repo-abc123/git.md": "# git", + "owner-repo-abc123/nested/k8s.md": "# k8s", + "owner-repo-abc123/README.txt": "ignore me", + "owner-repo-abc123/LICENSE": "ignore me", + "owner-repo-abc123/assets/pic.png": "binary", + }) + + dest := t.TempDir() + n, err := extractMarkdownTarball(bytes.NewReader(tb), "", dest) + if err != nil { + t.Fatalf("extract: %v", err) + } + if n != 2 { + t.Fatalf("extracted %d files, want 2", n) + } + + if got, _ := os.ReadFile(filepath.Join(dest, "git.md")); string(got) != "# git" { + t.Errorf("git.md content = %q", got) + } + if got, _ := os.ReadFile(filepath.Join(dest, "nested", "k8s.md")); string(got) != "# k8s" { + t.Errorf("nested/k8s.md content = %q", got) + } + if _, err := os.Stat(filepath.Join(dest, "README.txt")); !os.IsNotExist(err) { + t.Error("README.txt should not have been extracted") + } +} + +func TestExtractMarkdownTarballSubdir(t *testing.T) { + tb := makeTarball(t, map[string]string{ + "owner-repo-abc123/top.md": "top", + "owner-repo-abc123/cheats/git.md": "git", + "owner-repo-abc123/cheats/sub/d.md": "d", + }) + + dest := t.TempDir() + n, err := extractMarkdownTarball(bytes.NewReader(tb), "cheats", dest) + if err != nil { + t.Fatalf("extract: %v", err) + } + if n != 2 { + t.Fatalf("extracted %d files, want 2", n) + } + // subdir prefix should be stripped from the output paths. + if _, err := os.Stat(filepath.Join(dest, "git.md")); err != nil { + t.Errorf("expected git.md at dest root: %v", err) + } + if _, err := os.Stat(filepath.Join(dest, "top.md")); !os.IsNotExist(err) { + t.Error("top.md is outside subdir and should be skipped") + } +} + +func TestExtractMarkdownTarballZipSlip(t *testing.T) { + tb := makeTarball(t, map[string]string{ + "owner-repo-abc123/../../evil.md": "pwned", + }) + + dest := t.TempDir() + if _, err := extractMarkdownTarball(bytes.NewReader(tb), "", dest); err == nil { + t.Fatal("expected zip-slip guard to reject path-escaping entry") + } +} + +func TestParseGitHubRepo(t *testing.T) { + cases := map[string][2]string{ + "https://github.com/owner/repo": {"owner", "repo"}, + "https://github.com/owner/repo.git": {"owner", "repo"}, + "github.com/owner/repo": {"owner", "repo"}, + "owner/repo": {"owner", "repo"}, + } + for in, want := range cases { + o, r, err := parseGitHubRepo(in) + if err != nil { + t.Errorf("%q: unexpected error %v", in, err) + continue + } + if o != want[0] || r != want[1] { + t.Errorf("%q: got %s/%s, want %s/%s", in, o, r, want[0], want[1]) + } + } + + if _, _, err := parseGitHubRepo("notarepo"); err == nil { + t.Error("expected error for malformed repo") + } +} diff --git a/pkg/installer/tarball.go b/pkg/installer/tarball.go new file mode 100644 index 0000000..2e17a62 --- /dev/null +++ b/pkg/installer/tarball.go @@ -0,0 +1,121 @@ +package installer + +import ( + "archive/tar" + "compress/gzip" + "context" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + + "github.com/cheatmd-dev/cheatmd/pkg/httputil" + "github.com/cheatmd-dev/cheatmd/pkg/registry" +) + +// tarballTimeout bounds the HTTPS fallback download. +const tarballTimeout = 60 * time.Second + +// installViaTarball downloads the GitHub default-branch tarball and extracts +// its .md files into target. GitHub-only (clone covers other hosts). +func installViaTarball(ctx context.Context, pack registry.Pack, target string) error { + owner, repo, err := parseGitHubRepo(pack.Repo) + if err != nil { + return err + } + + ctx, cancel := context.WithTimeout(ctx, tarballTimeout) + defer cancel() + + url := fmt.Sprintf("https://api.github.com/repos/%s/%s/tarball", owner, repo) + respBody, err := httputil.Get(ctx, url) + if err != nil { + return fmt.Errorf("download tarball: %w", err) + } + defer respBody.Close() + + n, err := extractMarkdownTarball(respBody, pack.Subdir, target) + if err != nil { + return err + } + if n == 0 { + return fmt.Errorf("no .md cheats found in %s", pack.Repo) + } + return nil +} + +// extractMarkdownTarball reads a gzip-compressed tarball from r and writes its +// .md files into dest. GitHub tarballs wrap everything in a top-level +// "--/" directory, which we strip; subdir (if set) further +// restricts which files are kept. Returns the count extracted. +func extractMarkdownTarball(r io.Reader, subdir, dest string) (int, error) { + gz, err := gzip.NewReader(r) + if err != nil { + return 0, fmt.Errorf("open gzip: %w", err) + } + defer gz.Close() + + subdir = normalizeSubdir(subdir) + + count := 0 + tr := tar.NewReader(gz) + for { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return count, fmt.Errorf("read tar: %w", err) + } + + rel, keep := markdownRelPath(hdr, subdir) + if !keep { + continue + } + if err := writeTarEntry(tr, hdr, dest, rel); err != nil { + return count, err + } + count++ + } + return count, nil +} + +// writeTarEntry writes one tar entry to dest/rel, guarding against path +// traversal (zip-slip) and capping the copy to the declared size to avoid +// decompression bombs. +func writeTarEntry(tr *tar.Reader, hdr *tar.Header, dest, rel string) error { + outPath := filepath.Join(dest, filepath.FromSlash(rel)) + if !withinDir(dest, outPath) { + return fmt.Errorf("tar entry escapes destination: %q", hdr.Name) + } + if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { + return err + } + out, err := os.OpenFile(outPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) + if err != nil { + return err + } + defer out.Close() + if _, err := io.Copy(out, io.LimitReader(tr, hdr.Size)); err != nil { + return err + } + return nil +} + +// parseGitHubRepo extracts owner/repo from a GitHub repo URL or "owner/repo". +func parseGitHubRepo(repo string) (owner, name string, err error) { + s := strings.TrimSpace(repo) + s = strings.TrimSuffix(s, ".git") + s = strings.TrimPrefix(s, "https://") + s = strings.TrimPrefix(s, "http://") + s = strings.TrimPrefix(s, "github.com/") + s = strings.Trim(s, "/") + + parts := strings.Split(s, "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("tarball fallback supports github.com repos only, got %q", repo) + } + return parts[0], parts[1], nil +} diff --git a/pkg/installer/util.go b/pkg/installer/util.go new file mode 100644 index 0000000..fba2ceb --- /dev/null +++ b/pkg/installer/util.go @@ -0,0 +1,61 @@ +package installer + +import ( + "archive/tar" + "path/filepath" + "strings" +) + +// normalizeSubdir cleans a subdir filter to a slash path, treating an empty or +// "." value as "no filter". +func normalizeSubdir(subdir string) string { + s := filepath.ToSlash(filepath.Clean(strings.TrimSpace(subdir))) + if s == "." { + return "" + } + return s +} + +// markdownRelPath reports whether a tar entry is a .md file we should keep and, +// if so, returns its destination-relative path: the GitHub wrapper directory +// stripped, and the subdir prefix (when set) removed. +func markdownRelPath(hdr *tar.Header, subdir string) (rel string, keep bool) { + if hdr.Typeflag != tar.TypeReg { + return "", false + } + if !strings.EqualFold(filepath.Ext(hdr.Name), ".md") { + return "", false + } + + rel = stripFirstPathComponent(hdr.Name) + if rel == "" { + return "", false + } + if subdir == "" { + return rel, true + } + if !strings.HasPrefix(rel+"/", subdir+"/") { + return "", false + } + return strings.TrimPrefix(rel, subdir+"/"), true +} + +// stripFirstPathComponent removes the leading path segment (the GitHub tarball +// wrapper dir), returning a forward-slash relative path. +func stripFirstPathComponent(name string) string { + name = filepath.ToSlash(name) + _, rest, found := strings.Cut(name, "/") + if !found { + return "" + } + return rest +} + +// withinDir reports whether target resolves to a path inside dir. +func withinDir(dir, target string) bool { + rel, err := filepath.Rel(dir, target) + if err != nil { + return false + } + return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} diff --git a/pkg/packmanifest/manifest.go b/pkg/packmanifest/manifest.go new file mode 100644 index 0000000..fc7cf17 --- /dev/null +++ b/pkg/packmanifest/manifest.go @@ -0,0 +1,114 @@ +// Package packmanifest records which cheat packs have been installed into a +// cheats directory. It is the source of truth for "is this pack installed?", +// replacing fragile folder-name guessing: a directory only counts as an +// installed pack if it was recorded here by the installer. +// +// The manifest is stored as ".cheatmd-packs.json" at the root of the cheats +// directory. The cheat parser only reads .md files, so the manifest is ignored +// during normal browsing. +package packmanifest + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "time" +) + +// FileName is the manifest's basename within the cheats directory. +const FileName = ".cheatmd-packs.json" + +// Entry records a single installed pack. +type Entry struct { + Name string `json:"name"` + Repo string `json:"repo"` + InstalledAt time.Time `json:"installed_at"` +} + +// Manifest is the set of installed packs in a cheats directory. +type Manifest struct { + Packs []Entry `json:"packs"` +} + +// pathFor returns the manifest file path for a cheats directory. +func pathFor(dir string) string { + return filepath.Join(dir, FileName) +} + +// Load reads the manifest from dir. A missing manifest is not an error: it +// returns an empty manifest so callers can treat "no file" as "nothing +// installed". +func Load(dir string) (*Manifest, error) { + data, err := os.ReadFile(pathFor(dir)) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return &Manifest{}, nil + } + return nil, fmt.Errorf("read pack manifest: %w", err) + } + var m Manifest + if err := json.Unmarshal(data, &m); err != nil { + return nil, fmt.Errorf("parse pack manifest: %w", err) + } + return &m, nil +} + +// Save writes the manifest to dir, creating the directory if needed. +func Save(dir string, m *Manifest) error { + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("create cheats dir: %w", err) + } + data, err := json.MarshalIndent(m, "", " ") + if err != nil { + return fmt.Errorf("encode pack manifest: %w", err) + } + if err := os.WriteFile(pathFor(dir), append(data, '\n'), 0o644); err != nil { + return fmt.Errorf("write pack manifest: %w", err) + } + return nil +} + +// Has reports whether a pack with the given name is recorded as installed. +func (m *Manifest) Has(name string) bool { + for _, e := range m.Packs { + if e.Name == name { + return true + } + } + return false +} + +// Get returns the entry for the given pack name, or nil if not installed. +func (m *Manifest) Get(name string) *Entry { + for i := range m.Packs { + if m.Packs[i].Name == name { + return &m.Packs[i] + } + } + return nil +} + +// Upsert records (or refreshes) an installed pack, replacing any existing +// entry with the same name. +func (m *Manifest) Upsert(e Entry) { + for i := range m.Packs { + if m.Packs[i].Name == e.Name { + m.Packs[i] = e + return + } + } + m.Packs = append(m.Packs, e) +} + +// Remove deletes a pack from the manifest. +func (m *Manifest) Remove(name string) { + for i := range m.Packs { + if m.Packs[i].Name == name { + m.Packs = append(m.Packs[:i], m.Packs[i+1:]...) + return + } + } +} diff --git a/pkg/packmanifest/manifest_test.go b/pkg/packmanifest/manifest_test.go new file mode 100644 index 0000000..242dfa6 --- /dev/null +++ b/pkg/packmanifest/manifest_test.go @@ -0,0 +1,54 @@ +package packmanifest + +import ( + "testing" + "time" +) + +func TestLoadMissingReturnsEmpty(t *testing.T) { + m, err := Load(t.TempDir()) + if err != nil { + t.Fatalf("Load on dir without manifest: %v", err) + } + if len(m.Packs) != 0 { + t.Errorf("expected empty manifest, got %d packs", len(m.Packs)) + } +} + +func TestSaveLoadRoundTrip(t *testing.T) { + dir := t.TempDir() + m := &Manifest{} + m.Upsert(Entry{Name: "git", Repo: "https://github.com/x/git", InstalledAt: time.Now()}) + m.Upsert(Entry{Name: "docker", Repo: "https://github.com/x/docker", InstalledAt: time.Now()}) + + if err := Save(dir, m); err != nil { + t.Fatalf("Save: %v", err) + } + + got, err := Load(dir) + if err != nil { + t.Fatalf("Load: %v", err) + } + if len(got.Packs) != 2 { + t.Fatalf("got %d packs, want 2", len(got.Packs)) + } + if !got.Has("git") || !got.Has("docker") { + t.Errorf("manifest missing expected packs: %+v", got.Packs) + } + if got.Has("nope") { + t.Error("Has returned true for an uninstalled pack") + } +} + +func TestUpsertReplacesByName(t *testing.T) { + m := &Manifest{} + m.Upsert(Entry{Name: "git", Repo: "old"}) + m.Upsert(Entry{Name: "git", Repo: "new"}) + + if len(m.Packs) != 1 { + t.Fatalf("expected 1 pack after upsert, got %d", len(m.Packs)) + } + if m.Packs[0].Repo != "new" { + t.Errorf("repo = %q, want new", m.Packs[0].Repo) + } +} diff --git a/pkg/registry/registry.go b/pkg/registry/registry.go new file mode 100644 index 0000000..3376e79 --- /dev/null +++ b/pkg/registry/registry.go @@ -0,0 +1,117 @@ +// Package registry fetches and parses the CheatMD cheat-pack registry: a +// remote YAML manifest that lists installable cheat repositories ("packs"). +// +// The registry is hosted in its own repo (see the cheatmd.registry scaffold); +// the tool fetches it over HTTPS during first-run setup so users can pick +// official packs of cheats to install. +package registry + +import ( + "context" + "fmt" + "github.com/cheatmd-dev/cheatmd/pkg/httputil" + "io" + "strings" + "time" + + yaml "go.yaml.in/yaml/v3" +) + +// Pack describes a single installable cheat repository in the registry. +type Pack struct { + // Name is a short identifier, also used as the install subdirectory name. + Name string `yaml:"name"` + // Repo is the clonable repository URL (e.g. https://github.com/owner/repo). + Repo string `yaml:"repo"` + // Description is a one-line human summary shown in the picker. + Description string `yaml:"description"` + // Official marks packs as officially maintained, pre-selected during first-run. + Official bool `yaml:"official"` + // Subdir optionally restricts installation to .md files under this path + // within the repo. Empty means the whole repo. + Subdir string `yaml:"subdir"` +} + +// Registry is the parsed manifest. +type Registry struct { + Version int `yaml:"version"` + Packs []Pack `yaml:"packs"` +} + +// defaultTimeout bounds the registry fetch so first-run setup never hangs. +const defaultTimeout = 15 * time.Second + +// Fetch retrieves and parses the registry manifest at url. +func Fetch(ctx context.Context, url string) (*Registry, error) { + ctx, cancel := context.WithTimeout(ctx, defaultTimeout) + defer cancel() + + respBody, err := httputil.Get(ctx, url) + if err != nil { + return nil, fmt.Errorf("fetch registry: %w", err) + } + defer respBody.Close() + + data, err := io.ReadAll(respBody) + if err != nil { + return nil, fmt.Errorf("read registry body: %w", err) + } + + return Parse(data) +} + +// Parse unmarshals registry YAML and validates required fields. It is split +// from Fetch so it can be unit-tested without a network round-trip. +func Parse(data []byte) (*Registry, error) { + var reg Registry + if err := yaml.Unmarshal(data, ®); err != nil { + return nil, fmt.Errorf("parse registry: %w", err) + } + + valid := reg.Packs[:0] + for _, p := range reg.Packs { + p.Name = strings.TrimSpace(p.Name) + p.Repo = strings.TrimSpace(p.Repo) + if p.Name == "" || p.Repo == "" { + // Skip malformed entries rather than failing the whole registry. + continue + } + valid = append(valid, p) + } + reg.Packs = valid + + if len(reg.Packs) == 0 { + return nil, fmt.Errorf("registry contains no valid packs") + } + return ®, nil +} + +// OfficialPacks returns the packs flagged as official packs. +func (r *Registry) OfficialPacks() []Pack { + var out []Pack + for _, p := range r.Packs { + if p.Official { + out = append(out, p) + } + } + return out +} + +// Select resolves pack names to their entries, preserving the order given. It +// errors on the first unknown name. +func (r *Registry) Select(names []string) ([]Pack, error) { + byName := make(map[string]Pack, len(r.Packs)) + for _, p := range r.Packs { + byName[p.Name] = p + } + + out := make([]Pack, 0, len(names)) + for _, name := range names { + p, ok := byName[name] + if !ok { + return nil, fmt.Errorf("unknown pack %q", name) + } + out = append(out, p) + } + return out, nil +} diff --git a/pkg/registry/registry_test.go b/pkg/registry/registry_test.go new file mode 100644 index 0000000..d282716 --- /dev/null +++ b/pkg/registry/registry_test.go @@ -0,0 +1,80 @@ +package registry + +import "testing" + +const sampleYAML = ` +version: 1 +packs: + - name: git + repo: https://github.com/cheatmd-dev/cheats-git + description: Git everyday commands + official: true + - name: docker + repo: https://github.com/cheatmd-dev/cheats-docker + description: Docker commands + official: false + - name: "" + repo: https://github.com/cheatmd-dev/bad + description: missing name, should be skipped +` + +func TestParse(t *testing.T) { + reg, err := Parse([]byte(sampleYAML)) + if err != nil { + t.Fatalf("Parse returned error: %v", err) + } + + if reg.Version != 1 { + t.Errorf("Version = %d, want 1", reg.Version) + } + + // The empty-name entry must be dropped. + if len(reg.Packs) != 2 { + t.Fatalf("got %d packs, want 2", len(reg.Packs)) + } + + if reg.Packs[0].Name != "git" { + t.Errorf("first pack name = %q, want git", reg.Packs[0].Name) + } +} + +func TestOfficialPacks(t *testing.T) { + reg, err := Parse([]byte(sampleYAML)) + if err != nil { + t.Fatalf("Parse returned error: %v", err) + } + + official := reg.OfficialPacks() + if len(official) != 1 { + t.Fatalf("got %d official packs, want 1", len(official)) + } + if official[0].Name != "git" { + t.Errorf("official pack = %q, want git", official[0].Name) + } +} + +func TestParseRejectsEmptyRegistry(t *testing.T) { + if _, err := Parse([]byte("version: 1\npacks: []\n")); err == nil { + t.Fatal("expected error for empty registry, got nil") + } +} + +func TestSelect(t *testing.T) { + reg, err := Parse([]byte(sampleYAML)) + if err != nil { + t.Fatalf("Parse returned error: %v", err) + } + + // Order is preserved as requested, not as listed in the registry. + got, err := reg.Select([]string{"docker", "git"}) + if err != nil { + t.Fatalf("Select: %v", err) + } + if len(got) != 2 || got[0].Name != "docker" || got[1].Name != "git" { + t.Fatalf("Select returned %+v, want [docker git]", got) + } + + if _, err := reg.Select([]string{"git", "nope"}); err == nil { + t.Error("expected error for unknown pack name") + } +}