-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathsnippet.go
94 lines (80 loc) · 2.22 KB
/
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"time"
"github.com/alecthomas/chroma/v2/quick"
)
// default values for empty state.
const (
defaultSnippetFolder = "misc"
defaultLanguage = "go"
defaultSnippetName = "Untitled Snippet"
defaultSnippetFileName = defaultSnippetName + "." + defaultLanguage
)
// defaultSnippet is a snippet with all of the default values, used for when
// there are no snippets available.
var defaultSnippet = Snippet{
Name: defaultSnippetName,
Folder: defaultSnippetFolder,
Language: defaultLanguage,
File: defaultSnippetFileName,
Date: time.Now(),
Tags: make([]string, 0),
}
// Snippet represents a snippet of code in a language.
// It is nested within a folder and can be tagged with metadata.
type Snippet struct {
Tags []string `json:"tags"`
Folder string `json:"folder"`
Date time.Time `json:"date"`
Favorite bool `json:"favorite"`
Name string `json:"title"`
File string `json:"file"`
Language string `json:"language"`
}
// String returns the folder/name.ext of the snippet.
func (s Snippet) String() string {
return fmt.Sprintf("%s/%s.%s", s.Folder, s.Name, s.Language)
}
// LegacyPath returns the legacy path <folder>-<file>
func (s Snippet) LegacyPath() string {
return s.File
}
// Path returns the path <folder>/<file>
func (s Snippet) Path() string {
return filepath.Join(s.Folder, s.File)
}
// Content returns the snippet contents.
func (s Snippet) Content(highlight bool) string {
config := readConfig()
file := filepath.Join(config.Home, s.Path())
content, err := os.ReadFile(file)
if err != nil {
return ""
}
if !highlight {
return string(content)
}
var b bytes.Buffer
err = quick.Highlight(&b, string(content), s.Language, "terminal16m", config.Theme)
if err != nil {
return string(content)
}
return b.String()
}
// Snippets is a wrapper for a snippets array to implement the fuzzy.Source
// interface.
type Snippets struct {
snippets []Snippet
}
// String returns the string of the snippet at the specified position i
func (s Snippets) String(i int) string {
return s.snippets[i].String()
}
// Len returns the length of the snippets array.
func (s Snippets) Len() int {
return len(s.snippets)
}