Initial commit

This commit is contained in:
2025-02-28 12:11:24 +02:00
commit 47340aebb8
7 changed files with 534 additions and 0 deletions

48
Makefile Normal file
View File

@@ -0,0 +1,48 @@
SHELL := /bin/env oksh
export PATH := $(PATH)
all: fmt lintfix tidy test clean build
debug:
@echo "PATH: $(PATH)"
@echo "GOPATH: $(shell go env GOPATH)"
@which go
@which gofumpt
@which gci
@which golangci-lint
clean:
rm -rf ./dist
# Test
test:
go test -race ./...
tidy:
go mod tidy
# Format code
fmt:
gofumpt -l -w .
gci write .
# Run linter
lint: fmt
golangci-lint run
# Run linter and fix
lintfix: fmt
golangci-lint run --fix
build: clean
mkdir ./dist
go build -race -o ./dist/gmi2html ./bin/gmi2html/gmi2html.go
show-updates:
go list -m -u all
update:
go get -u all
update-patch:
go get -u=patch all

15
README.md Normal file
View File

@@ -0,0 +1,15 @@
# gmi2html
A small library (and CLI tool) that converts Gemini text to HTML.
To run tests and build:
```shell
make
```
Running:
```shell
./dist/gmi2html <gemtext.gmi >gemtext.html
```

31
bin/gmi2html/gmi2html.go Normal file
View File

@@ -0,0 +1,31 @@
package main
import (
"fmt"
"io"
"os"
"github.com/antanst/gmi2html"
)
func main() {
err := runApp()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func runApp() error {
data, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
html := gmi2html.Gmi2html(string(data), "")
_, err = fmt.Fprintf(os.Stdout, "%s", html)
if err != nil {
return err
}
return nil
}

135
gmi2html.go Normal file
View File

@@ -0,0 +1,135 @@
package gmi2html
import (
"bytes"
"fmt"
"html/template"
"net/url"
"regexp"
"strings"
)
// Based on https://geminiprotocol.net/docs/gemtext-specification.gmi
// Gmi2html converts Gemini text to HTML with proper escaping and wraps it in a container with typography-focused CSS
func Gmi2html(text string, title string) string {
content := convertGeminiContent(text)
// Handle any template errors with container
var buffer bytes.Buffer
err := containerTmpl.Execute(&buffer, struct {
Title string
Content template.HTML
}{
Title: title,
Content: template.HTML(content), // Content already properly escaped in convertGeminiContent
})
if err != nil {
fmt.Printf("Error executing container template: %s\n", err)
return ""
}
return buffer.String()
}
// convertGeminiContent converts Gemini text to HTML with proper escaping
func convertGeminiContent(text string) string {
lines := strings.Split(text, "\n")
var buffer bytes.Buffer
normalMode := true
for _, line := range lines {
switch {
case strings.HasPrefix(line, "=>"):
handleLinkLine(&buffer, line)
case strings.HasPrefix(line, "```"):
normalMode = !normalMode
// Don't output the ``` line
case strings.HasPrefix(line, "###"):
content := strings.TrimSpace(strings.TrimPrefix(line, "###"))
err := h3Tmpl.Execute(&buffer, content)
if err != nil {
return ""
}
case strings.HasPrefix(line, "##"):
content := strings.TrimSpace(strings.TrimPrefix(line, "##"))
err := h2Tmpl.Execute(&buffer, content)
if err != nil {
return ""
}
case strings.HasPrefix(line, "#"):
content := strings.TrimSpace(strings.TrimPrefix(line, "#"))
err := h1Tmpl.Execute(&buffer, content)
if err != nil {
return ""
}
case strings.HasPrefix(line, "*"):
content := strings.TrimSpace(strings.TrimPrefix(line, "*"))
err := listItemTmpl.Execute(&buffer, content)
if err != nil {
return ""
}
case strings.HasPrefix(line, ">"):
content := strings.TrimSpace(strings.TrimPrefix(line, ">"))
err := blockquoteTmpl.Execute(&buffer, content)
if err != nil {
return ""
}
default:
if normalMode {
err := textLineTmpl.Execute(&buffer, line)
if err != nil {
return ""
}
} else {
err := preformattedTmpl.Execute(&buffer, line)
if err != nil {
return ""
}
}
}
}
return buffer.String()
}
// handleLinkLine parses and renders a link line
func handleLinkLine(buffer *bytes.Buffer, linkLine string) {
url, description, err := parseGeminiLink(linkLine)
if err != nil {
fmt.Printf("Error parsing gemini link line: %s\n", err)
return
}
err = linkTmpl.Execute(buffer, struct {
URL, Description string
}{url, description})
if err != nil {
return
}
}
// parseGeminiLink extracts URL and description from a link line
func parseGeminiLink(linkLine string) (string, string, error) {
re := regexp.MustCompile(`^=>[ \t]+(\S+)([ \t]+.*)?`)
matches := re.FindStringSubmatch(linkLine)
if len(matches) == 0 {
return "", "", fmt.Errorf("error parsing link line: no regexp match for line %s", linkLine)
}
urlStr := matches[1]
// Check: Unescape the URL if escaped
_, err := url.QueryUnescape(urlStr)
if err != nil {
return "", "", fmt.Errorf("error parsing link line: %w input '%s'", err, linkLine)
}
// Set description to URL if not provided
description := urlStr
if len(matches) > 2 && strings.TrimSpace(matches[2]) != "" {
description = strings.TrimSpace(matches[2])
}
return urlStr, description, nil
}

159
gmi2html_test.go Normal file
View File

@@ -0,0 +1,159 @@
package gmi2html
import (
"strings"
"testing"
)
func TestConvertGeminiContent(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "Simple text line",
input: "This is a simple text line",
expected: `<p class="gemini-textline">This is a simple text line</p>`,
},
{
name: "Heading line level 1",
input: "# Main heading",
expected: `<h1 class="gemini-heading-1">Main heading</h1>`,
},
{
name: "Link line with description",
input: "=> https://example.com Example site",
expected: `<div class="gemini-link-container"><a href="https://example.com">Example site</a></div>`,
},
{
name: "List item",
input: "* List item 1",
expected: `<p class="gemini-list-item">• List item 1</p>`,
},
{
name: "Quote line",
input: "> This is a quote",
expected: `<blockquote class="gemini-blockquote">This is a quote</blockquote>`,
},
{
name: "Preformatted text",
input: "```\ncode line 1\ncode line 2\n```",
expected: `<pre class="gemini-preformatted">code line 1</pre><pre class="gemini-preformatted">code line 2</pre>`,
},
{
name: "Mixed content",
input: "# Title\n\nNormal paragraph\n\n=> https://example.com Link to example",
expected: `<h1 class="gemini-heading-1">Title</h1><p class="gemini-textline"></p><p class="gemini-textline">Normal paragraph</p><p class="gemini-textline"></p><div class="gemini-link-container"><a href="https://example.com">Link to example</a></div>`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := convertGeminiContent(tt.input)
if result != tt.expected {
t.Errorf("convertGeminiContent(%q):\ngot: %s\nwant: %s",
tt.input, result, tt.expected)
}
})
}
}
func TestGmi2html(t *testing.T) {
sample := "# Hello Gemini\n\nThis is a test document.\n\n=> https://gemini.circumlunar.space/ Project Gemini"
result := Gmi2html(sample, "Gemini Test")
// Check that it contains the expected elements
if !strings.Contains(result, "<title>Gemini Test</title>") {
t.Error("Output HTML missing title")
}
if !strings.Contains(result, "<h1 class=\"gemini-heading-1\">Hello Gemini</h1>") {
t.Error("Output HTML missing properly formatted heading")
}
if !strings.Contains(result, "<a href=\"https://gemini.circumlunar.space/\">Project Gemini</a>") {
t.Error("Output HTML missing properly formatted link")
}
// Check that CSS is included
if !strings.Contains(result, "<style>") {
t.Error("Output HTML missing style section")
}
// Check that basic HTML structure is there
if !strings.Contains(result, "<!DOCTYPE html>") {
t.Error("Output HTML missing doctype declaration")
}
if !strings.Contains(result, "<div class=\"gemini-container\">") {
t.Error("Output HTML missing container div")
}
}
func TestParseGeminiLink(t *testing.T) {
tests := []struct {
name string
input string
expectedURL string
expectedDesc string
expectError bool
}{
{
name: "Valid link with description",
input: "=> https://example.com Example site",
expectedURL: "https://example.com",
expectedDesc: "Example site",
expectError: false,
},
{
name: "Valid link without description",
input: "=> https://example.com",
expectedURL: "https://example.com",
expectedDesc: "https://example.com",
expectError: false,
},
{
name: "Link with special characters",
input: "=> https://example.com/search?q=test Test search",
expectedURL: "https://example.com/search?q=test",
expectedDesc: "Test search",
expectError: false,
},
{
name: "Malformed link line",
input: "=>",
expectedURL: "",
expectedDesc: "",
expectError: true,
},
{
name: "Link with multiple spaces in description",
input: "=> https://example.com Multiple spaces",
expectedURL: "https://example.com",
expectedDesc: "Multiple spaces",
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
url, desc, err := parseGeminiLink(tt.input)
// Check error expectation
if (err != nil) != tt.expectError {
t.Errorf("Expected error: %v, got error: %v", tt.expectError, err != nil)
}
// If we expect success, check the result
if !tt.expectError {
if url != tt.expectedURL {
t.Errorf("Expected URL: %s, got: %s", tt.expectedURL, url)
}
if desc != tt.expectedDesc {
t.Errorf("Expected description: %s, got: %s", tt.expectedDesc, desc)
}
}
})
}
}

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/antanst/gmi2html
go 1.23.6

143
templates.go Normal file
View File

@@ -0,0 +1,143 @@
package gmi2html
import "html/template"
// Templates for different line types
var (
textLineTmpl = template.Must(template.New("textLine").Parse(`<p class="gemini-textline">{{.}}</p>`))
h1Tmpl = template.Must(template.New("h1").Parse(`<h1 class="gemini-heading-1">{{.}}</h1>`))
h2Tmpl = template.Must(template.New("h2").Parse(`<h2 class="gemini-heading-2">{{.}}</h2>`))
h3Tmpl = template.Must(template.New("h3").Parse(`<h3 class="gemini-heading-3">{{.}}</h3>`))
listItemTmpl = template.Must(template.New("listItem").Parse(`<p class="gemini-list-item">• {{.}}</p>`))
blockquoteTmpl = template.Must(template.New("blockquote").Parse(`<blockquote class="gemini-blockquote">{{.}}</blockquote>`))
preformattedTmpl = template.Must(template.New("preformatted").Parse(`<pre class="gemini-preformatted">{{.}}</pre>`))
linkTmpl = template.Must(template.New("link").Parse(`<div class="gemini-link-container"><a href="{{.URL}}">{{.Description}}</a></div>`))
// Container template with typography-focused CSS
containerTmpl = template.Must(template.New("container").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.Title}}</title>
<style>
:root {
--text-color: #333;
--bg-color: #fff;
--link-color: #0066cc;
--link-hover: #004080;
--quote-bg: #f5f5f5;
--quote-border: #ddd;
--pre-bg: #f8f8f8;
--pre-border: #eaeaea;
}
@media (prefers-color-scheme: dark) {
:root {
--text-color: #eee;
--bg-color: #292929;
--link-color: #4a9eff;
--link-hover: #77b6ff;
--quote-bg: #333;
--quote-border: #444;
--pre-bg: #2a2a2a;
--pre-border: #3a3a3a;
}
}
body {
font-family: "Source Serif Pro", "Georgia", "Cambria", serif;
color: var(--text-color);
/* background-color: var(--bg-color); */
max-width: 34rem;
margin: 0 auto;
padding: 1rem 1rem;
font-size: 16px;
text-align: justify;
hyphens: auto;
-webkit-hyphens: auto;
-ms-hyphens: auto;
}
.gemini-container {
width: 100%;
}
.gemini-heading-1 {
font-size: 2rem;
margin-top: 1rem;
margin-bottom: 1rem;
font-weight: 700;
line-height: 1.2;
}
.gemini-heading-2 {
font-size: 1.6rem;
margin-top: 0.8rem;
margin-bottom: 0.8rem;
font-weight: 600;
line-height: 1.3;
}
.gemini-heading-3 {
font-size: 1.3rem;
margin-top: 0.7rem;
margin-bottom: 0.7rem;
font-weight: 600;
line-height: 1.4;
}
.gemini-textline {
margin-bottom: 1rem;
}
.gemini-list-item {
margin: 0.5rem 0;
padding-left: 0.5rem;
}
.gemini-link-container {
margin: 1rem 0;
}
.gemini-link-container a {
color: var(--link-color);
text-decoration: none;
border-bottom: 1px solid transparent;
transition: border-color 0.2s ease;
}
.gemini-link-container a:hover {
color: var(--link-hover);
border-bottom-color: var(--link-hover);
}
.gemini-blockquote {
background-color: var(--quote-bg);
border-left: 3px solid var(--quote-border);
margin: 1.5rem 0;
padding: 0.8rem 1rem;
font-style: italic;
}
.gemini-preformatted {
background-color: var(--pre-bg);
border: 1px solid var(--pre-border);
border-radius: 3px;
padding: 1rem;
overflow-x: auto;
font-family: monospace;
font-size: 0.9rem;
margin: 1rem 0;
white-space: pre-wrap;
}
</style>
</head>
<body>
<div class="gemini-container">
{{.Content}}
</div>
</body>
</html>`))
)