restructure project following best practices

https://go.dev/doc/modules/layout
This also enables us to later import just the db interaction part
say to the gemini capsule backend go project.
This commit is contained in:
Travis Shears 2025-10-04 19:40:27 +02:00
parent 928c82536f
commit 360fedbebe
11 changed files with 202 additions and 169 deletions

View file

@ -0,0 +1,80 @@
package ui
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
)
type Action string
const (
Write Action = "write"
Read Action = "read"
Edit Action = "edit"
Delete Action = "delete"
)
var actions = []Action{Write, Read, Edit, Delete}
type ActionListPageModel struct {
cursor int
}
func initialActionListPageModel() ActionListPageModel {
return ActionListPageModel{
cursor: 0,
}
}
func (m ActionListPageModel) InitActionListPage() tea.Cmd {
return nil
}
func (m ActionListPageModel) Update(msg tea.Msg, active bool, ctx *context) (ActionListPageModel, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
if !active {
return m, nil
}
switch msg.String() {
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < len(actions)-1 {
m.cursor++
}
case "enter", " ", "l":
action := actions[m.cursor]
switch action {
case Write:
return m, WritePostCMD(ctx.config)
case Read, Delete, Edit:
switchPageCmd := func() tea.Msg {
return SwitchPages{Page: EntryList}
}
actionToTakeCmd := func() tea.Msg {
return SelectActionToTake{ActionToTake: action}
}
loadGemLogsCmd := LoadGemlogsCMD(ctx.config)
return m, tea.Batch(switchPageCmd, loadGemLogsCmd, actionToTakeCmd)
}
}
}
return m, nil
}
func (m ActionListPageModel) View() string {
s := "Welcome to gemlog cli!\n\nWhat post action would you like to take?\n\n"
for i, action := range actions {
cursor := " "
if m.cursor == i {
cursor = ">"
}
s += fmt.Sprintf("%s %s\n", cursor, action)
}
return s
}

151
internal/ui/app.go Normal file
View file

@ -0,0 +1,151 @@
package ui
import (
"fmt"
"io"
"log/slog"
"os"
gemlog "git.travisshears.com/travisshears/gemlog-cli/gemlog"
tea "github.com/charmbracelet/bubbletea"
)
type Page string
const (
ActionList Page = "actionList"
EntryList Page = "entryList"
Entry Page = "entry"
)
type SwitchPages struct{ Page Page }
type Notification string
type ErrorMsg struct{ err error }
type GemLogsLoaded struct{ Logs []gemlog.GemlogListEntry }
type GemLogLoaded struct{ Log gemlog.GemlogEntry }
type uiState struct {
notification string
errorTxt string
page Page
entryListPage EntryListPageModel
entryPage EntryPageModel
actionListPage ActionListPageModel
}
type context struct {
config *gemlog.Config
}
type model struct {
ui uiState
context *context
}
func initialModel(config *gemlog.Config) model {
return model{
ui: uiState{
page: ActionList,
actionListPage: initialActionListPageModel(),
entryListPage: initialEntryListPageModel(),
entryPage: initialEntryPageModel(),
},
context: &context{
config: config,
},
}
}
func (m model) Init() tea.Cmd {
cmds := make([]tea.Cmd, 0)
cmds = append(cmds, tea.SetWindowTitle("Gemlog CLI"))
// TODO: add init commands from other pages
return tea.Batch(cmds...)
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmds := make([]tea.Cmd, 3)
switch msg := msg.(type) {
case SwitchPages:
m.ui.page = msg.Page
case ErrorMsg:
m.ui.errorTxt = fmt.Sprintf("%s\n\n", fmt.Errorf("%s", msg))
case Notification:
m.ui.notification = fmt.Sprintf("%s\n\n", string(msg))
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
}
}
actionListM, cmd := m.ui.actionListPage.Update(msg, m.ui.page == ActionList, m.context)
m.ui.actionListPage = actionListM
cmds = append(cmds, cmd)
entryListM, cmd := m.ui.entryListPage.Update(msg, m.ui.page == EntryList, m.context)
m.ui.entryListPage = entryListM
cmds = append(cmds, cmd)
entrytM, cmd := m.ui.entryPage.Update(msg, m.ui.page == Entry, m.context)
m.ui.entryPage = entrytM
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}
func (m model) View() string {
if len(m.ui.errorTxt) > 0 {
return m.ui.errorTxt
}
s := ""
if m.ui.notification != "" {
s += m.ui.notification
}
switch m.ui.page {
case ActionList:
s += m.ui.actionListPage.View()
case EntryList:
s += m.ui.entryListPage.View()
case Entry:
s += m.ui.entryPage.View()
}
s += "\nPress q to quit.\n"
return s
}
var enableLogs bool = false
func Run() {
if enableLogs {
f, err := tea.LogToFile("debug.log", "debug")
if err != nil {
fmt.Println("fatal:", err)
os.Exit(1)
}
defer f.Close()
} else {
logger := slog.New(slog.NewJSONHandler(io.Discard, nil))
slog.SetDefault(logger)
}
slog.Info("Starting gemlog cli")
config, err := gemlog.LoadConfig()
if err != nil {
fmt.Printf("Error loading config: %v", err)
os.Exit(1)
}
err = gemlog.CheckDBConnection(config)
if err != nil {
fmt.Printf("Error checking db connection: %v", err)
os.Exit(1)
}
p := tea.NewProgram(initialModel(config))
if _, err := p.Run(); err != nil {
fmt.Printf("Alas, there's been an error: %v", err)
os.Exit(1)
}
}

39
internal/ui/commands.go Normal file
View file

@ -0,0 +1,39 @@
package ui
import (
"fmt"
gemlog "git.travisshears.com/travisshears/gemlog-cli/gemlog"
tea "github.com/charmbracelet/bubbletea"
)
func DeleteGemlogCMD(config *gemlog.Config, id string, rev string) tea.Cmd {
return func() tea.Msg {
err := gemlog.DeleteGemlogEntry(config, id, rev)
if err != nil {
return ErrorMsg{err}
}
return Notification(fmt.Sprintf("Gemlog with id: %s deleted", id))
}
}
func LoadGemlogCMD(config *gemlog.Config, id string) tea.Cmd {
return func() tea.Msg {
log, err := gemlog.ReadGemlogEntry(config, id)
if err != nil {
return ErrorMsg{err}
}
return GemLogLoaded{Log: log}
}
}
func LoadGemlogsCMD(config *gemlog.Config) tea.Cmd {
return func() tea.Msg {
logs, err := gemlog.ListGemLogs(config)
if err != nil {
return ErrorMsg{err}
}
return GemLogsLoaded{Logs: logs}
}
}

44
internal/ui/entry.go Normal file
View file

@ -0,0 +1,44 @@
package ui
import (
gemlog "git.travisshears.com/travisshears/gemlog-cli/gemlog"
tea "github.com/charmbracelet/bubbletea"
)
type EntryPageModel struct {
entry gemlog.GemlogEntry
}
func initialEntryPageModel() EntryPageModel {
return EntryPageModel{}
}
func (m EntryPageModel) Update(msg tea.Msg, active bool, ctx *context) (EntryPageModel, tea.Cmd) {
switch msg := msg.(type) {
case GemLogLoaded:
m.entry = msg.Log
case tea.KeyMsg:
if !active {
return m, nil
}
switch msg.String() {
case "left", "h":
cmd := func() tea.Msg {
return SwitchPages{Page: EntryList}
}
return m, cmd
}
}
return m, nil
}
func (m EntryPageModel) View() string {
s := m.entry.Slug
s += "\n\n"
s += m.entry.Gemtxt
s += "\n\n-------------------------\n"
s += "\n\nPress h or left arrow to go back"
return s
}

88
internal/ui/entryList.go Normal file
View file

@ -0,0 +1,88 @@
package ui
import (
"fmt"
gemlog "git.travisshears.com/travisshears/gemlog-cli/gemlog"
tea "github.com/charmbracelet/bubbletea"
)
type EntryListPageModel struct {
entries []gemlog.GemlogListEntry
actionToTake Action
cursor int
}
type SelectActionToTake struct{ ActionToTake Action }
func initialEntryListPageModel() EntryListPageModel {
return EntryListPageModel{
cursor: 0,
actionToTake: Read,
}
}
func (m EntryListPageModel) Update(msg tea.Msg, active bool, ctx *context) (EntryListPageModel, tea.Cmd) {
switch msg := msg.(type) {
case SelectActionToTake:
m.actionToTake = msg.ActionToTake
case GemLogsLoaded:
m.entries = msg.Logs
return m, nil
case tea.KeyMsg:
if !active {
return m, nil
}
switch msg.String() {
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < len(actions)-1 {
m.cursor++
}
case "left", "h":
cmd := func() tea.Msg {
return SwitchPages{Page: ActionList}
}
return m, cmd
case "enter", " ", "l":
id := m.entries[m.cursor].ID
rev := m.entries[m.cursor].Rev
switch m.actionToTake {
// TODO: handle edit
case Read:
loadCmd := LoadGemlogCMD(ctx.config, id)
navCmd := func() tea.Msg {
return SwitchPages{Page: Entry}
}
return m, tea.Sequence(loadCmd, navCmd)
case Delete:
delCmd := DeleteGemlogCMD(ctx.config, id, rev)
loadCmd := LoadGemlogsCMD(ctx.config)
navCmd := func() tea.Msg {
return SwitchPages{Page: ActionList}
}
return m, tea.Sequence(delCmd, loadCmd, navCmd)
}
}
}
return m, nil
}
func (m EntryListPageModel) View() string {
s := fmt.Sprintf("Which entry would you like to %s\n\n", m.actionToTake)
for i, entry := range m.entries {
cursor := " "
if m.cursor == i {
cursor = ">"
}
s += fmt.Sprintf("%s %s : %s\n", cursor, entry.Date, entry.Slug)
}
s += "\n\n Press h or left arrow to go back"
return s
}

15
internal/ui/templates.go Normal file
View file

@ -0,0 +1,15 @@
package ui
const defaultTemplate = `title: todo
date: 2025-12-31
slug: todo
tags: cat, dog
---
Example text
=> https://travisshears.com example link
* Example list item 1
* Example list item 2
`

141
internal/ui/write.go Normal file
View file

@ -0,0 +1,141 @@
package ui
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
gemlog "git.travisshears.com/travisshears/gemlog-cli/gemlog"
tea "github.com/charmbracelet/bubbletea"
"gopkg.in/yaml.v3"
)
// TODO: add edit command
// func EditPostCMD(config *gemlog.Config) tea.Cmd {}
func WritePostCMD(config *gemlog.Config) tea.Cmd {
return func() tea.Msg {
// Create a temporary file
tmpFile, err := os.CreateTemp("/tmp", "gemlog-*.md")
if err != nil {
return ErrorMsg{fmt.Errorf("failed to create temporary file: %w", err)}
}
// Load initial content from template file
initialContent, err := os.ReadFile("templates/default_post.gmi")
if err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
return ErrorMsg{fmt.Errorf("failed to read template file: %w", err)}
}
if _, err := tmpFile.Write(initialContent); err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
return ErrorMsg{fmt.Errorf("failed to write initial content: %w", err)}
}
tmpFile.Close()
// Get the editor from environment variable, default to vim
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
// Create the command to open the editor with the temp file
c := exec.Command(editor, tmpFile.Name()) //nolint:gosec
// Return tea.ExecProcess which will suspend the TUI and run the editor
return tea.ExecProcess(c, func(err error) tea.Msg {
defer os.Remove(tmpFile.Name()) // Clean up the temp file
if err != nil {
return ErrorMsg{fmt.Errorf("editor command failed: %w", err)}
}
// Read the contents of the file after editing
content, readErr := os.ReadFile(tmpFile.Name())
if readErr != nil {
return ErrorMsg{fmt.Errorf("failed to read file contents: %w", readErr)}
}
gemlogEntry, err := parsePost(string(content))
if err != nil {
return ErrorMsg{fmt.Errorf("failed to parse post: %w", err)}
}
if err := gemlog.SaveGemlogEntry(config, &gemlogEntry); err != nil {
return ErrorMsg{fmt.Errorf("failed to save gemlog entry: %w", err)}
}
// Return success with the content
return Notification(fmt.Sprintf("Post created: \ngemini://travisshears.com/gemlog/%s\n\n", gemlogEntry.Slug))
})()
}
}
func parsePost(post string) (gemlog.GemlogEntry, error) {
// split post on new lines
lines := strings.Split(post, "\n")
// Find the separator line "---"
separatorIndex := -1
for i, line := range lines {
if strings.TrimSpace(line) == "---" {
separatorIndex = i
break
}
}
if separatorIndex == -1 {
return gemlog.GemlogEntry{}, fmt.Errorf("no frontmatter separator '---' found")
}
// Extract frontmatter and body
frontmatterLines := lines[:separatorIndex]
bodyLines := lines[separatorIndex+1:]
// Parse frontmatter YAML
frontmatterYAML := strings.Join(frontmatterLines, "\n")
var frontmatter struct {
Title string `yaml:"title"`
Date string `yaml:"date"`
Slug string `yaml:"slug"`
Tags string `yaml:"tags"`
}
if err := yaml.Unmarshal([]byte(frontmatterYAML), &frontmatter); err != nil {
return gemlog.GemlogEntry{}, fmt.Errorf("failed to parse frontmatter: %w", err)
}
// Parse date
date, err := time.Parse("2006-01-02", strings.TrimSpace(frontmatter.Date))
if err != nil {
return gemlog.GemlogEntry{}, fmt.Errorf("failed to parse date: %w", err)
}
// Parse tags (comma-separated)
var tags []string
if frontmatter.Tags != "" {
tagParts := strings.Split(frontmatter.Tags, ",")
for _, tag := range tagParts {
trimmed := strings.TrimSpace(tag)
if trimmed != "" {
tags = append(tags, trimmed)
}
}
}
// Join body lines
body := strings.Join(bodyLines, "\n")
return gemlog.GemlogEntry{
Title: frontmatter.Title,
Date: date,
Slug: frontmatter.Slug,
Tags: tags,
Gemtxt: body,
}, nil
}