2023-12-13 15:10:20 +01:00
|
|
|
// Package sheet implements functions pertaining to parsing, searching, and
|
|
|
|
// displaying cheatsheets.
|
2019-10-20 16:02:28 +02:00
|
|
|
package sheet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2022-08-05 02:38:49 +02:00
|
|
|
"os"
|
2019-10-20 16:02:28 +02:00
|
|
|
"sort"
|
|
|
|
)
|
|
|
|
|
2022-08-26 18:20:58 +02:00
|
|
|
// Frontmatter encapsulates cheatsheet frontmatter data
|
|
|
|
type frontmatter struct {
|
|
|
|
Tags []string
|
|
|
|
Syntax string
|
|
|
|
}
|
|
|
|
|
2019-10-20 16:02:28 +02:00
|
|
|
// Sheet encapsulates sheet information
|
|
|
|
type Sheet struct {
|
2020-11-27 22:39:34 +01:00
|
|
|
Title string
|
|
|
|
CheatPath string
|
|
|
|
Path string
|
|
|
|
Text string
|
|
|
|
Tags []string
|
|
|
|
Syntax string
|
|
|
|
ReadOnly bool
|
2019-10-20 16:02:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// New initializes a new Sheet
|
|
|
|
func New(
|
|
|
|
title string,
|
2020-11-27 22:39:34 +01:00
|
|
|
cheatpath string,
|
2019-10-20 16:02:28 +02:00
|
|
|
path string,
|
|
|
|
tags []string,
|
|
|
|
readOnly bool,
|
|
|
|
) (Sheet, error) {
|
|
|
|
|
|
|
|
// read the cheatsheet file
|
2022-08-05 02:38:49 +02:00
|
|
|
markdown, err := os.ReadFile(path)
|
2019-10-20 16:02:28 +02:00
|
|
|
if err != nil {
|
|
|
|
return Sheet{}, fmt.Errorf("failed to read file: %s, %v", path, err)
|
|
|
|
}
|
|
|
|
|
2022-08-26 18:20:58 +02:00
|
|
|
// parse the raw cheatsheet text
|
|
|
|
fm, text, err := parse(string(markdown))
|
2019-10-20 16:02:28 +02:00
|
|
|
if err != nil {
|
|
|
|
return Sheet{}, fmt.Errorf("failed to parse front-matter: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// merge the sheet-specific tags into the cheatpath tags
|
|
|
|
tags = append(tags, fm.Tags...)
|
|
|
|
|
|
|
|
// sort strings so they pretty-print nicely
|
|
|
|
sort.Strings(tags)
|
|
|
|
|
|
|
|
// initialize and return a sheet
|
|
|
|
return Sheet{
|
2020-11-27 22:39:34 +01:00
|
|
|
Title: title,
|
|
|
|
CheatPath: cheatpath,
|
|
|
|
Path: path,
|
2022-08-26 18:06:13 +02:00
|
|
|
Text: text,
|
2020-11-27 22:39:34 +01:00
|
|
|
Tags: tags,
|
|
|
|
Syntax: fm.Syntax,
|
|
|
|
ReadOnly: readOnly,
|
2019-10-20 16:02:28 +02:00
|
|
|
}, nil
|
|
|
|
}
|