Compare commits

...

3 commits

12 changed files with 202 additions and 126 deletions

View file

@ -1,13 +1,5 @@
package gemlog
import (
"fmt"
"os"
"path/filepath"
"gopkg.in/yaml.v3"
)
// CouchDBConfig represents the CouchDB configuration section
type CouchDBConfig struct {
Host string `yaml:"host"`
@ -20,25 +12,3 @@ type CouchDBConfig struct {
type Config struct {
CouchDB CouchDBConfig `yaml:"couchdb"`
}
// LoadConfig reads and parses the YAML configuration file from ~/.config/gemlog-cli
func LoadConfig() (*Config, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get user home directory: %w", err)
}
configPath := filepath.Join(homeDir, ".config", "gemlog-cli", "config.yml")
data, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file %s: %w", configPath, err)
}
var config Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to parse YAML config: %w", err)
}
return &config, nil
}

View file

@ -1,21 +1,19 @@
package gemlog
import (
"crypto/rand"
"encoding/hex"
"fmt"
"time"
)
// GemlogEntry represents a single gemlog post entry
type GemlogEntry struct {
Title string `json:"title"`
Slug string `json:"slug"`
Date time.Time `json:"date"`
Tags []string `json:"tags"`
Gemtxt string `json:"gemtxt"`
Title string `json:"title"`
Slug string `json:"slug"`
Date time.Time `json:"date"`
// Tags []string `json:"tags"`
Gemtxt string `json:"gemtxt"`
}
// GemlogListEntry is for showing a list of gemlog entries without the main Gemtxt
type GemlogListEntry struct {
Title string `json:"title"`
Slug string `json:"slug"`
@ -23,25 +21,3 @@ type GemlogListEntry struct {
ID string `json:"id"`
Rev string `json:"rev"`
}
// NewUUID generates a new UUID v4 using crypto/rand
func NewUUID() (string, error) {
uuid := make([]byte, 16)
_, err := rand.Read(uuid)
if err != nil {
return "", fmt.Errorf("failed to generate UUID: %w", err)
}
// Set version (4) and variant bits according to RFC 4122
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant bits
// Format as standard UUID string: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
return fmt.Sprintf("%s-%s-%s-%s-%s",
hex.EncodeToString(uuid[0:4]),
hex.EncodeToString(uuid[4:6]),
hex.EncodeToString(uuid[6:8]),
hex.EncodeToString(uuid[8:10]),
hex.EncodeToString(uuid[10:16]),
), nil
}

View file

@ -119,7 +119,7 @@ func ReadGemlogEntry(config *Config, id string) (GemlogEntry, error) {
Slug: rawData.Slug,
Date: rawData.Date,
Gemtxt: rawData.GemText,
Tags: make([]string, 0),
// Tags: make([]string, 0),
}, nil
}
@ -151,6 +151,42 @@ func DeleteGemlogEntry(config *Config, id string, rev string) error {
return nil
}
func UpdateGemlogEntry(config *Config, entry *GemlogEntry, id string, rev string) error {
url := fmt.Sprintf("%s:%d/gemlog/%s?rev=%s", config.CouchDB.Host, config.CouchDB.Port, id, rev)
// Marshal the entry struct to JSON
jsonData, err := json.Marshal(entry)
if err != nil {
return fmt.Errorf("failed to marshal entry: %w", err)
}
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Add("authorization", genBasicAuthHeader(config.CouchDB.User, config.CouchDB.Password))
req.Header.Add("content-type", "application/json")
slog.Info("Sending request to update gemlog entry", "url", url, "data", string(jsonData))
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return fmt.Errorf("unexpected status code %d: %s", res.StatusCode, string(body))
}
return nil
}
func SaveGemlogEntry(config *Config, entry *GemlogEntry) error {
url := fmt.Sprintf("%s:%d/gemlog/", config.CouchDB.Host, config.CouchDB.Port)

1
go.mod
View file

@ -6,6 +6,7 @@ require (
github.com/charmbracelet/bubbles v0.21.0
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/muesli/reflow v0.3.0
gopkg.in/yaml.v3 v3.0.1
)

4
go.sum
View file

@ -22,14 +22,18 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=

View file

@ -118,9 +118,9 @@ func (m model) View() string {
return s
}
var enableLogs bool = false
var enableLogs bool = true
func Run() {
func Run(config *gemlog.Config) {
if enableLogs {
f, err := tea.LogToFile("debug.log", "debug")
if err != nil {
@ -133,12 +133,7 @@ func Run() {
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)
err := gemlog.CheckDBConnection(config)
if err != nil {
fmt.Printf("Error checking db connection: %v", err)
os.Exit(1)

View file

@ -0,0 +1,32 @@
package config
import (
"fmt"
"os"
"path/filepath"
gemlog "git.travisshears.com/travisshears/gemlog-cli/gemlog"
"gopkg.in/yaml.v3"
)
// LoadConfig reads and parses the YAML configuration file from ~/.config/gemlog-cli
func LoadConfig() (*gemlog.Config, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get user home directory: %w", err)
}
configPath := filepath.Join(homeDir, ".config", "gemlog-cli", "config.yml")
data, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file %s: %w", configPath, err)
}
var config gemlog.Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to parse YAML config: %w", err)
}
return &config, nil
}

View file

@ -8,6 +8,7 @@ import (
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/reflow/wordwrap"
)
type EntryPageModel struct {
@ -20,13 +21,8 @@ func initialEntryPageModel() EntryPageModel {
return EntryPageModel{}
}
func transformEntryToContent(entry gemlog.GemlogEntry) string {
content := entry.Slug
content += "\n\n"
content += entry.Gemtxt
content += "\n\n-------------------------\n"
content += "\n\nPress h or left arrow to go back"
return content
func wrapGemtxt(gemtxt string, width int) string {
return wordwrap.String(gemtxt, width)
}
func (m EntryPageModel) Update(msg tea.Msg, active bool, ctx *context) (EntryPageModel, tea.Cmd) {
@ -37,7 +33,7 @@ func (m EntryPageModel) Update(msg tea.Msg, active bool, ctx *context) (EntryPag
switch msg := msg.(type) {
case GemLogLoaded:
m.entry = msg.Log
m.viewport.SetContent(transformEntryToContent(m.entry))
m.viewport.SetContent(wrapGemtxt(m.entry.Gemtxt, m.viewport.Width))
case tea.KeyMsg:
if !active {
return m, nil
@ -50,7 +46,7 @@ func (m EntryPageModel) Update(msg tea.Msg, active bool, ctx *context) (EntryPag
return m, cmd
}
case tea.WindowSizeMsg:
headerHeight := lipgloss.Height(m.headerView())
headerHeight := lipgloss.Height(m.headerView("loading slug..."))
footerHeight := lipgloss.Height(m.footerView())
verticalMarginHeight := headerHeight + footerHeight
@ -63,7 +59,7 @@ func (m EntryPageModel) Update(msg tea.Msg, active bool, ctx *context) (EntryPag
m.viewport = viewport.New(msg.Width, msg.Height-verticalMarginHeight)
m.viewport.YPosition = headerHeight
m.viewport.SetContent(transformEntryToContent(m.entry))
m.viewport.SetContent(wrapGemtxt(m.entry.Gemtxt, msg.Width))
m.ready = true
} else {
m.viewport.Width = msg.Width
@ -83,7 +79,7 @@ func (m EntryPageModel) View() string {
return "\n Initializing..."
}
return fmt.Sprintf("%s\n%s\n%s", m.headerView(), m.viewport.View(), m.footerView())
return fmt.Sprintf("%s\n%s\n%s", m.headerView(m.entry.Slug), m.viewport.View(), m.footerView())
}
var (
@ -100,8 +96,8 @@ var (
}()
)
func (m EntryPageModel) headerView() string {
title := titleStyle.Render("Mr. Pager")
func (m EntryPageModel) headerView(slug string) string {
title := titleStyle.Render(slug)
line := strings.Repeat("─", max(0, m.viewport.Width-lipgloss.Width(title)))
return lipgloss.JoinHorizontal(lipgloss.Center, title, line)
}

View file

@ -52,7 +52,12 @@ func (m EntryListPageModel) Update(msg tea.Msg, active bool, ctx *context) (Entr
id := m.entries[m.cursor].ID
rev := m.entries[m.cursor].Rev
switch m.actionToTake {
// TODO: handle edit
case Edit:
editCmd := EditPostCMD(ctx.config, id, rev)
navCmd := func() tea.Msg {
return SwitchPages{Page: ActionList}
}
return m, tea.Sequence(editCmd, navCmd)
case Read:
loadCmd := LoadGemlogCMD(ctx.config, id)
navCmd := func() tea.Msg {

View file

@ -12,8 +12,84 @@ import (
"gopkg.in/yaml.v3"
)
type Frontmatter struct {
Title string `yaml:"title"`
Date string `yaml:"date"`
Slug string `yaml:"slug"`
// Tags []string `yaml:"tags"`
}
// TODO: add edit command
// func EditPostCMD(config *gemlog.Config) tea.Cmd {}
func EditPostCMD(config *gemlog.Config, id string, rev string) tea.Cmd {
return func() tea.Msg {
gemlogEntry, err := gemlog.ReadGemlogEntry(config, id)
if err != nil {
return ErrorMsg{fmt.Errorf("failed to read gemlog entry: %w", err)}
}
// 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)}
}
frontmatter := Frontmatter{
Title: gemlogEntry.Title,
Date: gemlogEntry.Date.Format("2006-01-02"),
Slug: gemlogEntry.Slug,
// Tags: []string{}, // or nil if empty is ok
}
yamlData, err := yaml.Marshal(&frontmatter)
if err != nil {
return ErrorMsg{fmt.Errorf("failed to marshal frontmatter: %w", err)}
}
initialContent := append(yamlData, []byte("---\n"+gemlogEntry.Gemtxt)...)
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.UpdateGemlogEntry(config, &gemlogEntry, id, rev); err != nil {
return ErrorMsg{fmt.Errorf("failed to save gemlog entry: %w", err)}
}
// Return success with the content
return Notification(fmt.Sprintf("Post updated: \ngemini://travisshears.com/gemlog/%s\n\n", gemlogEntry.Slug))
})()
}
}
func WritePostCMD(config *gemlog.Config) tea.Cmd {
return func() tea.Msg {
@ -23,15 +99,7 @@ func WritePostCMD(config *gemlog.Config) tea.Cmd {
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 {
if _, err := tmpFile.Write([]byte(defaultTemplate)); err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
return ErrorMsg{fmt.Errorf("failed to write initial content: %w", err)}
@ -99,12 +167,7 @@ func parsePost(post string) (gemlog.GemlogEntry, error) {
// 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"`
}
var frontmatter Frontmatter
if err := yaml.Unmarshal([]byte(frontmatterYAML), &frontmatter); err != nil {
return gemlog.GemlogEntry{}, fmt.Errorf("failed to parse frontmatter: %w", err)
@ -117,25 +180,25 @@ func parsePost(post string) (gemlog.GemlogEntry, error) {
}
// 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)
}
}
}
// 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,
Title: frontmatter.Title,
Date: date,
Slug: frontmatter.Slug,
// Tags: tags,
Gemtxt: body,
}, nil
}

12
main.go
View file

@ -1,9 +1,19 @@
package main
import (
"fmt"
"os"
ui "git.travisshears.com/travisshears/gemlog-cli/internal/ui"
config "git.travisshears.com/travisshears/gemlog-cli/internal/ui/config"
)
func main() {
ui.Run()
c, err := config.LoadConfig()
if err != nil {
fmt.Printf("Error loading config: %v", err)
os.Exit(1)
}
ui.Run(c)
}

View file

@ -1,12 +0,0 @@
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