core

package
v0.0.0-...-2b6d340 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2024 License: GPL-3.0 Imports: 50 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	DefaultSRSBoostFactor = 100
	DefaultSRSAlgorithm   = "Anki2"
	DefaultSRSEaseFactor  = 2.5
)

SRS

View Source
const DefaultConfig = `` /* 183-byte string literal not displayed */

Default .nt/config content

View Source
const DefaultEaseFactor = 2.5 // Same as Anki
View Source
const DefaultFirstInterval = 1 // day
View Source
const DefaultGitIgnore = `
/database.db
/database.db-journal
/objects/
/index
/refs/
`

Default .nt/.gitignore content

View Source
const DefaultIgnore = `
build/
README.md
`

Default .ntignore content

View Source
const DefaultLint = `` /* 366-byte string literal not displayed */
View Source
const Indent int = 2

Default indentation in front matter

View Source
const LargeMaxWidthOrHeight = 1980

Maximum width and/or height for large blobs.

View Source
const MaxObjectsPerPackFileDefault = 100

Database

View Source
const MinEaseFactor = 1.3 // Same as Anki
View Source
const NoteLongTitleSeparator string = " / "

NoteLongTitleSeparator represents the separator when determine the long title of a note.

View Source
const PreviewMaxWidthOrHeight = 600

Maximum width and/or height for preview blobs.

View Source
const ReferenceKindAuthor = "author"
View Source
const ReferenceKindBook = "book"

Variables

View Source
var AudioExtensions = []string{".mp3", ".wav"}

List of supported audio formats

View Source
var (
	ErrObjectNotExist = errors.New("object does not exist")
)
View Source
var IndexFilesFirst = func(a, b string) bool {
	dirA := filepath.Dir(a)
	dirB := filepath.Dir(b)
	if dirA != dirB {
		return a < b
	}
	baseA := text.TrimExtension(filepath.Base(a))
	baseB := text.TrimExtension(filepath.Base(b))

	if strings.EqualFold(baseA, "index") {
		return true
	} else if strings.EqualFold(baseB, "index") {
		return false
	}
	return a < b
}

IndexFilesFirst ensures index files are processed first.

View Source
var LintRules = map[string]LintRuleDefinition{

	"no-duplicate-note-title": {
		Eval: NoDuplicateNoteTitle,
	},

	"no-duplicate-slug": {
		Eval: NoDuplicateSlug,
	},

	"min-lines-between-notes": {
		Eval: MinLinesBetweenNotes,
	},

	"max-lines-between-notes": {
		Eval: MaxLinesBetweenNotes,
	},

	"note-title-match": {
		Eval: NoteTitleMatch,
	},

	"no-free-note": {
		Eval: NoFreeNote,
	},

	"no-dangling-media": {
		Eval: NoDanglingMedia,
	},

	"no-dead-wikilink": {
		Eval: NoDeadWikilink,
	},

	"no-extension-wikilink": {
		Eval: NoExtensionWikilink,
	},

	"no-ambiguous-wikilink": {
		Eval: NoAmbiguousWikilink,
	},

	"check-attribute": {
		Eval: CheckAttribute,
	},

	"require-quote-tag": {
		Eval: RequireQuoteTag,
	},
}
View Source
var PictureExtensions = []string{".jpg", ".jpeg", ".png", ".gif", ".svg", ".avif"}

List of supported picture formats

View Source
var VideoExtensions = []string{".mp4", ".ogg", ".webm"}

List of supported picture formats

Functions

func AppendLines

func AppendLines(t *testing.T, path string, text string)

AppendLines append multiple lines in a file.

func AssertContentEqual

func AssertContentEqual(t *testing.T, expected string, file *File)

func AssertFrontMatterEqual

func AssertFrontMatterEqual(t *testing.T, expected string, file *File)

func AssertNoFiles

func AssertNoFiles(t *testing.T)

func AssertNoFlashcards

func AssertNoFlashcards(t *testing.T)
func AssertNoLinks(t *testing.T)

func AssertNoMedias

func AssertNoMedias(t *testing.T)

func AssertNoNotes

func AssertNoNotes(t *testing.T)

func AssertNoReminders

func AssertNoReminders(t *testing.T)

func AssertTrimEqual

func AssertTrimEqual(t *testing.T, expected string, actual string)

func AttributesJSON

func AttributesJSON(attributes map[string]interface{}) (string, error)

func AttributesString

func AttributesString(attributes map[string]interface{}) (string, error)

AttributesString formats the current attributes to the YAML front matter format.

func AttributesYAML

func AttributesYAML(attributes map[string]interface{}) (string, error)

func BoolPointer

func BoolPointer(b bool) *bool

func CastAttribute

func CastAttribute(value interface{}, declaredType string) interface{}

CastAttribute enforces the type declared in linter schemas.

func CastAttributes

func CastAttributes(attributes map[string]interface{}, types map[string]string) map[string]interface{}

CastAttributes enforces the types declared in linter schemas.

func CompactYAML

func CompactYAML(doc string) string

CompactYAML removes leading spaces in front of sequences.

Ex:

doc:
  - toto: tata

Becomes

doc:
- toto: tata
Example (Dump)
doc := `
creator:
  name: Julien
  hobbies:
    - name: Running
      frequency: 3/weeks
`
var node yaml.Node
err := yaml.Unmarshal([]byte(doc), &node)
if err != nil {
	log.Fatal(err)
}
spew.Dump(node)

// (yaml.Node) {
// 	Kind: DocumentNode,
// 	Style: "",
// 	Tag: (string) "",
// 	Value: (string) "",
// 	Content: ([]*yaml.Node) (len=1 cap=1) {
// 	 (*yaml.Node)(0xc0000b8be0)({
// 	  Kind: MappingNode,
// 	  Style: "",
// 	  Tag: (string) (len=5) "!!map",
// 	  Value: (string) "",
// 	  Content: ([]*yaml.Node) (len=2 cap=2) {
// 	   (*yaml.Node)(0xc0000b8c80)({
// 		Kind: ScalarNode,
// 		Style: "",
// 		Tag: (string) (len=5) "!!str",
// 		Value: (string) (len=7) "creator",
// 		Content: ([]*yaml.Node) <nil>,
// 	   }),
// 	   (*yaml.Node)(0xc0000b8d20)({
// 		Kind: MappingNode,
// 		Style: "",
// 		Tag: (string) (len=5) "!!map",
// 		Value: (string) "",
// 		Content: ([]*yaml.Node) (len=4 cap=4) {
// 		 (*yaml.Node)(0xc0000b8dc0)({
// 		  Kind: ScalarNode,
// 		  Style: "",
// 		  Tag: (string) (len=5) "!!str",
// 		  Value: (string) (len=4) "name",
// 		  Content: ([]*yaml.Node) <nil>,
// 		 }),
// 		 (*yaml.Node)(0xc0000b8e60)({
// 		  Kind: ScalarNode,
// 		  Style: "",
// 		  Tag: (string) (len=5) "!!str",
// 		  Value: (string) (len=6) "Julien",
// 		  Content: ([]*yaml.Node) <nil>,
// 		 }),
// 		 (*yaml.Node)(0xc0000b8f00)({
// 		  Kind: ScalarNode,
// 		  Style: "",
// 		  Tag: (string) (len=5) "!!str",
// 		  Value: (string) (len=7) "hobbies",
// 		  Content: ([]*yaml.Node) <nil>,
// 		 }),
// 		 (*yaml.Node)(0xc0000b8fa0)({
// 		  Kind: SequenceNode,
// 		  Style: "",
// 		  Tag: (string) (len=5) "!!seq",
// 		  Value: (string) "",
// 		  Content: ([]*yaml.Node) (len=1 cap=1) {
// 		   (*yaml.Node)(0xc0000b9040)({
// 			Kind: MappingNode,
// 			Style: "",
// 			Tag: (string) (len=5) "!!map",
// 			Value: (string) "",
// 			Content: ([]*yaml.Node) (len=4 cap=4) {
// 			 (*yaml.Node)(0xc0000b90e0)({
// 			  Kind: ScalarNode,
// 			  Style: "",
// 			  Tag: (string) (len=5) "!!str",
// 			  Value: (string) (len=4) "name",
// 			  Content: ([]*yaml.Node) <nil>,
// 			 }),
// 			 (*yaml.Node)(0xc0000b9180)({
// 			  Kind: ScalarNode,
// 			  Style: "",
// 			  Tag: (string) (len=5) "!!str",
// 			  Value: (string) (len=7) "Running",
// 			  Content: ([]*yaml.Node) <nil>,
// 			 }),
// 			 (*yaml.Node)(0xc0000b9220)({
// 			  Kind: ScalarNode,
// 			  Style: "",
// 			  Tag: (string) (len=5) "!!str",
// 			  Value: (string) (len=9) "frequency",
// 			  Content: ([]*yaml.Node) <nil>,
// 			 }),
// 			 (*yaml.Node)(0xc0000b92c0)({
// 			  Kind: ScalarNode,
// 			  Style: "",
// 			  Tag: (string) (len=5) "!!str",
// 			  Value: (string) (len=7) "3/weeks",
// 			  Content: ([]*yaml.Node) <nil>,
// 			 })
// 			},
// 		   })
// 		  },
// 		 })
// 		},
// 	   })
// 	  },
// 	 })
// 	},
// }
Output:

Example (WithObject)
type Person struct {
	Name string
	Age  int
}
me := Person{
	Name: "Julien",
	Age:  36,
}
var meNode yaml.Node
data, err := yaml.Marshal(&me)
if err != nil {
	log.Fatal(err)
}
err = yaml.Unmarshal(data, &meNode)
if err != nil {
	log.Fatal(err)
}

config := &yaml.Node{
	Kind: yaml.DocumentNode,
	Content: []*yaml.Node{
		{
			Kind: yaml.MappingNode,
			Content: []*yaml.Node{
				{
					Kind:        yaml.ScalarNode,
					Value:       "creator",
					LineComment: "# Who?",
				},
				meNode.Content[0],
			},
		},
	},
}

bytes, err := yaml.Marshal(config)
if err != nil {
	log.Fatalf("Unable to marshall: %v", err)
}

log.Println("\n---\n" + string(bytes) + "---")
Output:

Example (WithScalars)
config := &yaml.Node{
	Kind: yaml.DocumentNode,
	Content: []*yaml.Node{
		{
			Kind: yaml.MappingNode,
			Content: []*yaml.Node{
				{
					Kind:        yaml.ScalarNode,
					Value:       "key1",
					HeadComment: "# This section is for key1",
					LineComment: "# TODO Complete",
				},
				{
					Kind:  yaml.ScalarNode,
					Style: yaml.DoubleQuotedStyle,
					Value: "value1",
				},

				{
					Kind:  yaml.ScalarNode,
					Value: "key2",
				},
				{
					Kind:  yaml.ScalarNode,
					Style: yaml.DoubleQuotedStyle,
					Value: "value2",
				},
			},
		},
	},
}

bytes, err := yaml.Marshal(config)
if err != nil {
	log.Fatalf("Unable to marshall: %v", err)
}

log.Printf("\n---\n" + string(bytes) + "---")
Output:

func DetermineFileSlug

func DetermineFileSlug(path string) string

DetermineFileSlug generates a slug from a file path.

func DetermineNoteSlug

func DetermineNoteSlug(fileSlug string, attributeSlug string, kind NoteKind, shortTitle string) string

DetermineNoteSlug determines the note slug from the attributes.

func DiffKeys

func DiffKeys(a, b map[string]interface{}) []string

func EvaluateTimeExpression

func EvaluateTimeExpression(expr string) (time.Time, error)

EvaluateTimeExpression determine the next matching reminder date

func ExtractBlockTagsAndAttributes

func ExtractBlockTagsAndAttributes(content string) ([]string, map[string]interface{})

ExtractBlockTagsAndAttributes searches for all tags and attributes declared on standalone lines (in comparison with tags/attributes defined, for example, on To-Do list items).

func FilterNonInheritableAttributes

func FilterNonInheritableAttributes(attributes map[string]interface{}, relativePath string, kind NoteKind) map[string]interface{}

FilterNonInheritableAttributes removes from the list all non-inheritable attributes.

func FormatLongTitle

func FormatLongTitle(titles ...string) string

FormatLongTitle formats the long title of a note.

func FreezeAt

func FreezeAt(t *testing.T, point time.Time) time.Time

FreezeAt wraps the clock API to register the cleanup function at the end of the test.

func FreezeNow

func FreezeNow(t *testing.T) time.Time

FreezeNow wraps the clock API to register the cleanup function at the end of the test.

func GetSchemaAttributeType

func GetSchemaAttributeType(name string) string

GetSchemaAttributeType returns the type for the given attribute and defaults to string if no declaration is found.

func GetSchemaAttributeTypes

func GetSchemaAttributeTypes() map[string]string

GetSchemaAttributeTypes returns all declared attributes with their JSON types.

func HumanTime

func HumanTime(t *testing.T, str string) time.Time

func IsArray

func IsArray(value interface{}) bool

IsArray returns if a variable is a JSON array.

func IsBool

func IsBool(value interface{}) bool

IsBool returns if a variable is a JSON boolean.

func IsComposite

func IsComposite(value interface{}) bool

IsComposite returns if a variable is a composite type.

func IsExec

func IsExec(mode os.FileMode) bool

func IsExecAny

func IsExecAny(mode os.FileMode) bool

func IsExecOther

func IsExecOther(mode os.FileMode) bool

func IsExecOwner

func IsExecOwner(mode os.FileMode) bool

func IsFloat

func IsFloat(value interface{}) bool

IsFloat returns if a variable is a JSON number of float type.

func IsInteger

func IsInteger(value interface{}) bool

IsInteger returns if a variable is a JSON number of integer type.

func IsNumber

func IsNumber(value interface{}) bool

IsNumber returns if a variable is a JSON number.

func IsObject

func IsObject(value interface{}) bool

IsObject returns if a variable is a JSON map.

func IsPrimitive

func IsPrimitive(value interface{}) bool

IsPrimitive returns if a variable is a primitive type.

func IsString

func IsString(value interface{}) bool

IsString returns if a variable is a JSON string.

func MatchWikilink(txt string) bool

MatchWikilink tests if a text is a wikilink.

func MergeAttribute

func MergeAttribute(attributes map[string]interface{}, name string, value interface{})

func MergeAttributes

func MergeAttributes(attributes ...map[string]interface{}) map[string]interface{}

func MustCountFiles

func MustCountFiles(t *testing.T) int

func MustCountFlashcards

func MustCountFlashcards(t *testing.T) int
func MustCountLinks(t *testing.T) int

func MustCountMedias

func MustCountMedias(t *testing.T) int

func MustCountNotes

func MustCountNotes(t *testing.T) int

func MustCountReminders

func MustCountReminders(t *testing.T) int

func MustDeleteFile

func MustDeleteFile(t *testing.T, path string)

MustDeleteFile remove a file iin the current collection.

func MustWriteFile

func MustWriteFile(t *testing.T, path string, content string)

MustWriteFile edits the file in the current collection to force the given content.

func NewOID

func NewOID() string

func NewOIDFromBytes

func NewOIDFromBytes(b []byte) string

func NonInheritableAttributes

func NonInheritableAttributes(relativePath string, kind NoteKind) []string

NonInheritableAttributes returns the attributes that must not be inherited.

func OIDToPath

func OIDToPath(oid string) string

OIDToPath converts an oid to a file path.

func ReadRefs

func ReadRefs() map[string]string

func RemoveTagsAndAttributes

func RemoveTagsAndAttributes(content string) string

RemoveTagsAndAttributes removes all tags and attributes from a text.

func ReplaceLine

func ReplaceLine(t *testing.T, path string, lineNumber int, oldLine string, newLine string)

ReplaceLine replaces a line inside a file.

func Reset

func Reset()

Reset forces singletons to be recreated. Useful between unit tests.

func ResetOID

func ResetOID()

ResetOID restores the original unique OID generator. Useful in tests with a defer after overriding the default generator.

func SetNextOIDs

func SetNextOIDs(t *testing.T, oids ...string)

SetNextOIDs configures a predefined list of OID

func SetUpCollectionFromFileContent

func SetUpCollectionFromFileContent(t *testing.T, name, content string) string

SetUpCollectionFromFileContent populates a temp directory based on the given file content.

func SetUpCollectionFromGoldenDir

func SetUpCollectionFromGoldenDir(t *testing.T) string

SetUpCollectionFromGoldenDir populates a temp directory containing a valid .nt collection.

func SetUpCollectionFromGoldenDirNamed

func SetUpCollectionFromGoldenDirNamed(t *testing.T, testname string) string

SetUpCollectionFromGoldenDir populates a temp directory based on the given golden dir name.

func SetUpCollectionFromGoldenFile

func SetUpCollectionFromGoldenFile(t *testing.T) string

SetUpCollectionFromGoldenFile populates a temp directory containing a valid .nt collection and a single file.

func SetUpCollectionFromGoldenFileNamed

func SetUpCollectionFromGoldenFileNamed(t *testing.T, testname string) string

SetUpCollectionFromGoldenFileNamed populates a temp directory based on the given golden file name.

func SetUpCollectionFromTempDir

func SetUpCollectionFromTempDir(t *testing.T) string

SetUpCollectionFromTempDir populates a temp directory containing a valid .nt collection.

func SettingsJSON

func SettingsJSON(settings map[string]any) (string, error)

func StripBlockTagsAndAttributes

func StripBlockTagsAndAttributes(content string) string

StripTagsAndAttributes remove all tags and attributes.

func ToSafeYAMLNode

func ToSafeYAMLNode(value interface{}) *yaml.Node

func ToSafeYAMLValue

func ToSafeYAMLValue(node *yaml.Node) interface{}

func UnescapeTestContent

func UnescapeTestContent(content string) string

UnescapeTestContent supports content using a special character instead of backticks.

func UnmarshalAttributes

func UnmarshalAttributes(rawValue string) (map[string]interface{}, error)

UnmarshalAttributes unmarshall attributes and ensure the right types are used.

func UseFixedOID

func UseFixedOID(t *testing.T, value string)

UseFixedOID configures a fixed OID value

func UseSequenceOID

func UseSequenceOID(t *testing.T)

UseFixedOID configures a fixed OID value

Types

type Attribute

type Attribute struct {
	Key   string
	Value interface{}
}

type BlobFile

type BlobFile struct {
	Ref  *BlobRef
	Data []byte
}

func NewBlobFile

func NewBlobFile(ref *BlobRef, data []byte) *BlobFile

func (*BlobFile) Read

func (c *BlobFile) Read(r io.Reader) error

Read populates a commit from an object file.

func (*BlobFile) Save

func (c *BlobFile) Save() error

Save writes a new file inside .nt/objects.

func (*BlobFile) Write

func (c *BlobFile) Write(w io.Writer) error

Write dumps a commit to an object file.

type BlobRef

type BlobRef struct {
	// OID to locate the blob file in .nt/objects
	OID        string                 `yaml:"oid"`
	MimeType   string                 `yaml:"mime"`
	Attributes map[string]interface{} `yaml:"attributes"`
	Tags       []string               `yaml:"tags"`
}

func MustWriteBlob

func MustWriteBlob(path string, tags []string) *BlobRef

MustWriteBlob writes a new blob object or fails.

func QueryBlob

func QueryBlob(db SQLClient, whereClause string, args ...any) (*BlobRef, error)

func QueryBlobs

func QueryBlobs(db SQLClient, whereClause string, args ...any) ([]*BlobRef, error)

type CardType

type CardType int
const (
	CardNew        CardType = 0
	CardLearning   CardType = 1
	CardReview     CardType = 2
	CardRelearning CardType = 3
)

type Collection

type Collection struct {
	Path string `yaml:"path"`
}

func CurrentCollection

func CurrentCollection() *Collection

func NewCollection

func NewCollection() (*Collection, error)

func (*Collection) Add

func (c *Collection) Add(paths ...string) error

Add implements the command `nt add`.`

func (*Collection) Close

func (c *Collection) Close()

func (*Collection) CountAttributes

func (c *Collection) CountAttributes() (map[string]int, error)

CountAttributes returns the attributes with their associated count.

func (*Collection) CountFiles

func (c *Collection) CountFiles() (int, error)

CountFiles returns the total number of files.

func (*Collection) CountFlashcards

func (c *Collection) CountFlashcards() (int, error)

CountFlashcards returns the total number of flashcards.

func (c *Collection) CountLinks() (int, error)

CountLinks returns the total number of links.

func (*Collection) CountMedias

func (c *Collection) CountMedias() (int, error)

CountMedias returns the total number of medias.

func (*Collection) CountNotes

func (c *Collection) CountNotes() (int, error)

CountNotes returns the total number of notes.

func (*Collection) CountNotesByKind

func (c *Collection) CountNotesByKind() (map[NoteKind]int, error)

CountNotesByKind returns the total number of notes for every kind.

func (*Collection) CountObjectsByType

func (c *Collection) CountObjectsByType() (map[string]int, error)

CountObjectsByType returns the total number of objects for every type.

func (*Collection) CountRelations

func (c *Collection) CountRelations() (int, error)

CountRelations returns the total number of relations.

func (*Collection) CountReminders

func (c *Collection) CountReminders() (int, error)

CountReminders returns the total number of reminders.

func (*Collection) CountTags

func (c *Collection) CountTags() (map[string]int, error)

CountTags returns the tags with their associated count.

func (*Collection) DeleteRelations

func (c *Collection) DeleteRelations(obj Object) error

func (*Collection) Diff

func (c *Collection) Diff(staged bool) (string, error)

Diff show changes between commits and working tree.

func (*Collection) DumpNotes

func (c *Collection) DumpNotes() error

func (*Collection) FindBlobFromOID

func (c *Collection) FindBlobFromOID(oid string) (*BlobRef, error)

func (*Collection) FindBlobsFromMedia

func (c *Collection) FindBlobsFromMedia(mediaOID string) ([]*BlobRef, error)

func (*Collection) FindFileByRelativePath

func (c *Collection) FindFileByRelativePath(relativePath string) (*File, error)
func (c *Collection) FindFileByWikilink(wikilink string) (*File, error)

func (*Collection) FindFilesByRelativePathPrefix

func (c *Collection) FindFilesByRelativePathPrefix(relativePathPrefix string) ([]*File, error)
func (c *Collection) FindFilesByWikilink(wikilink string) ([]*File, error)

func (*Collection) FindFilesLastCheckedBefore

func (c *Collection) FindFilesLastCheckedBefore(point time.Time, path string) ([]*File, error)

func (*Collection) FindFlashcardByHash

func (c *Collection) FindFlashcardByHash(hash string) (*Flashcard, error)

func (*Collection) FindFlashcardByShortTitle

func (c *Collection) FindFlashcardByShortTitle(shortTitle string) (*Flashcard, error)

func (*Collection) FindFlashcardsLastCheckedBefore

func (c *Collection) FindFlashcardsLastCheckedBefore(point time.Time, path string) ([]*Flashcard, error)

func (*Collection) FindLinkByGoName

func (c *Collection) FindLinkByGoName(goName string) (*Link, error)

func (*Collection) FindLinksByText

func (c *Collection) FindLinksByText(text string) ([]*Link, error)

func (*Collection) FindLinksLastCheckedBefore

func (c *Collection) FindLinksLastCheckedBefore(point time.Time, path string) ([]*Link, error)

func (*Collection) FindMatchingNote

func (c *Collection) FindMatchingNote(relativePath string, parsedNote *ParsedNote) (*Note, error)

func (*Collection) FindMediaByHash

func (c *Collection) FindMediaByHash(hash string) (*Media, error)

func (*Collection) FindMediaByRelativePath

func (c *Collection) FindMediaByRelativePath(relativePath string) (*Media, error)

func (*Collection) FindMediasLastCheckedBefore

func (c *Collection) FindMediasLastCheckedBefore(point time.Time) ([]*Media, error)

func (*Collection) FindNoteByHash

func (c *Collection) FindNoteByHash(hash string) (*Note, error)

func (*Collection) FindNoteByPathAndTitle

func (c *Collection) FindNoteByPathAndTitle(relativePath string, title string) (*Note, error)

func (*Collection) FindNoteBySlug

func (c *Collection) FindNoteBySlug(slug string) (*Note, error)

func (*Collection) FindNoteByTitle

func (c *Collection) FindNoteByTitle(title string) (*Note, error)
func (c *Collection) FindNoteByWikilink(wikilink string) (*Note, error)

func (*Collection) FindNotesByFileOID

func (c *Collection) FindNotesByFileOID(oid string) ([]*Note, error)
func (c *Collection) FindNotesByWikilink(wikilink string) ([]*Note, error)

func (*Collection) FindNotesLastCheckedBefore

func (c *Collection) FindNotesLastCheckedBefore(point time.Time, path string) ([]*Note, error)

func (*Collection) FindRelations

func (c *Collection) FindRelations() ([]*Relation, error)

func (*Collection) FindRelationsFrom

func (c *Collection) FindRelationsFrom(oid string) ([]*Relation, error)

func (*Collection) FindRelationsTo

func (c *Collection) FindRelationsTo(oid string) ([]*Relation, error)

func (*Collection) FindReminders

func (c *Collection) FindReminders() ([]*Reminder, error)

func (*Collection) FindRemindersByUpcomingDate

func (c *Collection) FindRemindersByUpcomingDate(deadline time.Time) ([]*Reminder, error)

func (*Collection) FindRemindersLastCheckedBefore

func (c *Collection) FindRemindersLastCheckedBefore(point time.Time, path string) ([]*Reminder, error)

func (*Collection) FindRemindersMatching

func (c *Collection) FindRemindersMatching(noteOID string, descriptionRaw string) ([]*Reminder, error)

func (*Collection) GetAbsolutePath

func (c *Collection) GetAbsolutePath(path string) string

GetAbsolutePath converts a relative path from the collection to an absolute path on disk.

func (*Collection) GetFileRelativePath

func (c *Collection) GetFileRelativePath(fileAbsolutePath string) (string, error)

GetFileRelativePath converts a relative path of a file to a relative path from the collection.

func (*Collection) GetNoteRelativePath

func (c *Collection) GetNoteRelativePath(fileRelativePath string, srcPath string) (string, error)

GetNoteRelativePath converts a relative path from a note to a relative path from the collection root directory.

func (*Collection) Lint

func (c *Collection) Lint(ruleNames []string, paths ...string) (*LintResult, error)

Lint run linter rules on all files under the given paths.

func (*Collection) LoadFileByOID

func (c *Collection) LoadFileByOID(oid string) (*File, error)

func (*Collection) LoadFlashcardByNoteOID

func (c *Collection) LoadFlashcardByNoteOID(noteID string) (*Flashcard, error)

func (*Collection) LoadFlashcardByOID

func (c *Collection) LoadFlashcardByOID(oid string) (*Flashcard, error)

func (*Collection) LoadLinkByOID

func (c *Collection) LoadLinkByOID(oid string) (*Link, error)

func (*Collection) LoadMediaByOID

func (c *Collection) LoadMediaByOID(oid string) (*Media, error)

func (*Collection) LoadNoteByOID

func (c *Collection) LoadNoteByOID(oid string) (*Note, error)

func (*Collection) LoadReminderByOID

func (c *Collection) LoadReminderByOID(oid string) (*Reminder, error)

func (*Collection) SearchNotes

func (c *Collection) SearchNotes(q string) ([]*Note, error)

SearchNotes query notes to find the ones matching a list of criteria.

Examples:

tag:favorite kind:reference kind:note path:projects/

func (*Collection) Stats

func (c *Collection) Stats() (*Stats, error)

Stats returns various statitics about the storage.

func (*Collection) StatsInDB

func (c *Collection) StatsInDB() (*StatsInDB, error)

StatsInDB returns various statistics about the .nt/database.db file.

func (*Collection) Status

func (c *Collection) Status() (string, error)

Status displays current objects in staging area.

func (*Collection) UpdateRelations

func (c *Collection) UpdateRelations(source Object) error

type Commit

type Commit struct {
	OID       string       `yaml:"oid"`
	CTime     time.Time    `yaml:"ctime"`
	MTime     time.Time    `yaml:"mtime"`
	PackFiles PackFileRefs `yaml:"packfiles"`
}

func NewCommit

func NewCommit() *Commit

NewCommit initializes a new empty commit.

func NewCommitFromPackFiles

func NewCommitFromPackFiles(packFiles ...*PackFile) *Commit

NewCommitFromPackFiles initializes a new commit referencing the given pack files.

func NewCommitWithOID

func NewCommitWithOID(oid string) *Commit

NewCommitWithOID initializes a new commit with a given OID.

func (*Commit) AppendPackFile

func (c *Commit) AppendPackFile(packFile *PackFile)

AppendPackFile appends a new pack file OID in the commit.

func (*Commit) IncludePackFile

func (c *Commit) IncludePackFile(oid string) (*PackFileRef, bool)

IncludePackFile returns the pack file is present in the commit.

func (Commit) String

func (c Commit) String() string

type CommitGraph

type CommitGraph struct {
	UpdatedAt time.Time `yaml:"updated_at,omitempty"`
	Commits   []*Commit `yaml:"commits,omitempty"`
}

CommitGraph represents a .nt/objects/info/commit-graph file. See https://git-scm.com/docs/commit-graph for inspiration.

The commit graph is used to quickly finds commit to download and/or diffs between local and remote directories. Useful when pulling or pushing commits.

func NewCommitGraph

func NewCommitGraph() *CommitGraph

NewCommitGraph instantiates a new commit graph.

func NewCommitGraphFromPath

func NewCommitGraphFromPath(path string) (*CommitGraph, error)

NewCommitGraphFromPath loads a commit-graph file from a path.

func ReadCommitGraph

func ReadCommitGraph() *CommitGraph

func (*CommitGraph) AppendCommit

func (c *CommitGraph) AppendCommit(commit *Commit) error

AppendCommit pushes a new commit.

func (*CommitGraph) Diff

func (c *CommitGraph) Diff(other *CommitGraph) *CommitGraphDiff

Diff reports differences to reconcile the receiver with the given commit graph.

func (*CommitGraph) Dump

func (c *CommitGraph) Dump()

Dump must be used for debug purpose only.

func (*CommitGraph) LastCommitsFrom

func (c *CommitGraph) LastCommitsFrom(head string) ([]*Commit, error)

LastCommits returns all commits pushed after head.

func (*CommitGraph) Read

func (cg *CommitGraph) Read(r io.Reader) error

Read instantiates a commit graph from an existing file

func (*CommitGraph) Ref

func (c *CommitGraph) Ref() string

Ref returns the commit OID of the last commit.

func (*CommitGraph) Save

func (c *CommitGraph) Save() error

Save persists the commit-graph locally.

func (*CommitGraph) SaveTo

func (c *CommitGraph) SaveTo(path string) error

SaveTo persists the commit-graph to the given path.

func (*CommitGraph) Write

func (c *CommitGraph) Write(w io.Writer) error

Write dumps the commit graph.

type CommitGraphDiff

type CommitGraphDiff struct {
	// Commits present only in the compared commit graph
	MissingCommits []*Commit
	// Pack files present only in the compared commit graph
	MissingPackFiles PackFileRefs
	// Pack files no longer present in the compared commit graph
	ObsoletePackFiles PackFileRefs
	// Pack files edited since by a gc
	EditedPackFiles PackFileRefs
}

type Config

type Config struct {
	// Absolute top directory containing the .nt sub-directory
	RootDirectory string

	// .nt/config content
	ConfigFile ConfigFile

	// .nt/lint content
	LintFile LintFile

	// .ntignore content
	IgnoreFile IgnoreFile

	// Toggle this flag to skip some side-effects
	DryRun bool
	// contains filtered or unexported fields
}

func CurrentConfig

func CurrentConfig() *Config

func InitConfigFromDirectory

func InitConfigFromDirectory(path string) (*Config, error)

InitConfigFromDirectory creates the .nt configuration directory with default files including .ntignore.

func ReadConfigFromDirectory

func ReadConfigFromDirectory(path string) (*Config, error)

ReadConfigFromDirectory loads the configuration by searching for a .nt directory in the given directory or any parent directories. It fails if a directory already exists.

func (*Config) Check

func (c *Config) Check() error

func (*Config) Converter

func (c *Config) Converter() medias.Converter

Converter returns the convertor to use when creating blobs from media files.

func (*Config) SetParallel

func (c *Config) SetParallel(value int)

SetParallel overrides the value in config file.

func (*Config) TempDir

func (c *Config) TempDir() string

TempDir returns the privileged temporary directory to use when generating temporary files.

type ConfigCore

type ConfigCore struct {
	Extensions            []string
	MaxObjectsPerPackFile int
}

type ConfigDeck

type ConfigDeck struct {
	Name  string
	Query string
	// General attributes
	BoostFactor         int // How passionate I am on this topic (100 = neutral, 80 = challenging, 120 = smooth)
	NewFlashcardsPerDay int // How many new flashcards to add every day (= 0 no more cards for now)
	MaxFlashcardsPerDay int // How many flashcards (including new) to review every day (= 0 no limit, review what is due)
	// Specific attributes
	Algorithm         string         // Anki2
	AlgorithmSettings map[string]any // SRS-specific attributes
}

type ConfigFile

type ConfigFile struct {
	Core      ConfigCore
	Medias    ConfigMedias
	Remote    ConfigRemote
	Deck      map[string]*ConfigDeck
	Search    map[string]*ConfigSearch
	Reference map[string]*ConfigReference
}

Note: Fields must be public for toml package to unmarshall

func (*ConfigFile) ConfigureFSRemote

func (f *ConfigFile) ConfigureFSRemote(dir string) *ConfigFile

ConfigureFSRemote defines a local remote using the file system.

func (*ConfigFile) ConfigureS3Remote

func (f *ConfigFile) ConfigureS3Remote(bucketName, accessKey, secretKey string) *ConfigFile

ConfigureS3Remote defines a remote using a S3 backend.

func (*ConfigFile) SupportExtension

func (f *ConfigFile) SupportExtension(path string) bool

SupportExtension checks if the given file extension must be considered.

type ConfigLintRule

type ConfigLintRule struct {

	// Name of the rule. Must exists in the registry of rules.
	Name string `yaml:"name"`

	// Severity of the rule: "error", "warning". Default to "error".
	Severity string `yaml:"severity"`

	// Optional arguments for the rule.
	Args []string `yaml:"args"`

	// PathRestrictions returns on which paths to evaluate the rule.
	// Glob expressions are supported and ! as prefix indicated to exclude.
	Includes GlobPaths `yaml:"includes"`
}

type ConfigLintSchema

type ConfigLintSchema struct {
	// Name of the schema used when reporting violations.
	Name       string                       `yaml:"name"`
	Kind       string                       `yaml:"kind"`
	Path       string                       `yaml:"path"`
	Attributes []*ConfigLintSchemaAttribute `yaml:"attributes"`
}

func (ConfigLintSchema) MatchesPath

func (c ConfigLintSchema) MatchesPath(path string) bool

type ConfigLintSchemaAttribute

type ConfigLintSchemaAttribute struct {
	Name     string   `yaml:"name"`
	Type     string   `yaml:"type"`
	Aliases  []string `yaml:"aliases"`
	Pattern  string   `yaml:"pattern"`
	Required *bool    `yaml:"required"`
	Inherit  *bool    `yaml:"inherit"`
}

func GetSchemaAttributes

func GetSchemaAttributes(relativePath string, kind NoteKind) []*ConfigLintSchemaAttribute

GetSchemaAttributes calculates the list of declared attributes for a given note.

func (ConfigLintSchemaAttribute) String

func (a ConfigLintSchemaAttribute) String() string

type ConfigMedias

type ConfigMedias struct {
	Command  string
	Parallel int
	Preset   string
}

type ConfigReference

type ConfigReference struct {
	Title    string // Ex: "A book"
	Manager  string // Ex: "zotero"
	Path     string // Ex: "references/books"
	Template string // Ex: "# {{.Title}}\n"
}

type ConfigRemote

type ConfigRemote struct {
	Type string // fs or s3
	// fs-specific attributes
	Dir string
	// s3-specific attributes
	Endpoint   string
	AccessKey  string
	SecretKey  string
	BucketName string
	Secure     bool
	// Storj-specific attributes
	AccessGrant string
}

type ConfigSearch

type ConfigSearch struct {
	Q    string
	Name string
}

type DB

type DB struct {
	// contains filtered or unexported fields
}

func CurrentDB

func CurrentDB() *DB

func (*DB) BeginTransaction

func (db *DB) BeginTransaction() error

BeginTransaction starts a new transaction.

func (*DB) BlobExists

func (db *DB) BlobExists(oid string) bool

BlobExists checks if a blob exists locally.

func (*DB) Client

func (db *DB) Client() SQLClient

Client returns the client to use to query the database.

func (*DB) Close

func (db *DB) Close() error

func (*DB) Commit

func (db *DB) Commit(msg string) error

Commit creates a new commit object and clear the staging area.

func (*DB) CommitTransaction

func (db *DB) CommitTransaction() error

CommitTransaction ends the current transaction.

func (*DB) CompressCommit

func (db *DB) CompressCommit(commit *Commit) (bool, error)

CompressCommit remove obsolete pack objects and merge small pack files together.

func (*DB) CompressPackFile

func (db *DB) CompressPackFile(packFile *PackFile) (bool, error)

CompressPackFile parses a pack file to remove obsolete pack objects.

func (*DB) DeleteBlob

func (db *DB) DeleteBlob(media *Media, blob *BlobRef) error

DeleteBlob removes a single blob on disk

func (*DB) DeleteBlobs

func (db *DB) DeleteBlobs(media *Media) error

DeleteBlobs removes all blobs on disk from a media

func (*DB) DeletePackFile

func (db *DB) DeletePackFile(packFile *PackFile) error

DeletePackFile removes a single pack file on disk

func (*DB) Diff

func (db *DB) Diff() (string, error)

Diff show the changes in the staging area.

func (*DB) GC

func (db *DB) GC() error

GC removes non referenced objects/blobs in the local directory.

func (*DB) Head

func (db *DB) Head() *Commit

Head returns the latest commit or nil if no commit exists.

func (*DB) ObjectExists

func (db *DB) ObjectExists(oid string) bool

ObjectExists checks if a blob exists locally.

func (*DB) Origin

func (db *DB) Origin() Remote

Origin returns the origin implementation based on the optional configured type.

func (*DB) PrintIndex

func (db *DB) PrintIndex()

func (*DB) Pull

func (db *DB) Pull() error

Pull retrieves remote objects.

func (*DB) Push

func (db *DB) Push() error

Push pushes new objects remotely.

func (*DB) ReadBlob

func (db *DB) ReadBlob(oid string) ([]byte, error)

ReadBlob reads a blob file on disk.

func (*DB) ReadCommit

func (db *DB) ReadCommit(oid string) (*Commit, bool)

ReadCommit checks for a commit with the given id.

func (*DB) ReadCommittedObject

func (db *DB) ReadCommittedObject(oid string) (StatefulObject, error)

ReadCommittedObject reads the last known committed version of stateful object on disk.

func (*DB) ReadLastStagedOrCommittedObject

func (db *DB) ReadLastStagedOrCommittedObject(oid string) (StatefulObject, error)

ReadLastStagedOrCommittedObject reads the last known version of stateful object in staging area or in commits.

func (*DB) ReadLastStagedOrCommittedObjectFromDB

func (db *DB) ReadLastStagedOrCommittedObjectFromDB(oid string) (StatefulObject, error)

ReadLastStagedOrCommittedObjectFromDB reads the last known version (in staging or committed) by rereading the database.

func (*DB) ReadPackFile

func (db *DB) ReadPackFile(oid string) (*PackFile, error)

ReadPackFile reads a pack file on disk.

func (*DB) ReadPackFilesFromCommit

func (db *DB) ReadPackFilesFromCommit(commit *Commit) ([]*PackFile, error)

ReadPackFilesFromCommit reads all pack files referenced by the commit.

func (*DB) Ref

func (db *DB) Ref(name string) (string, bool)

Ref returns the commit OID for the given ref

func (*DB) Reset

func (db *DB) Reset() error

Reset reverts the latest add command.

func (*DB) RollbackTransaction

func (db *DB) RollbackTransaction() error

RollbackTransaction aborts the current transaction.

func (*DB) StageObject

func (db *DB) StageObject(obj StatefulObject) error

func (*DB) StatsOnDisk

func (db *DB) StatsOnDisk() (*StatsOnDisk, error)

StatsOnDisk returns various statistics about the .nt/objects directory.

func (*DB) WIP

func (db *DB) WIP() *WIP

WIP returns the registry of currently processed notes.

func (*DB) WriteBlob

func (db *DB) WriteBlob(oid string, data []byte) error

WriteBlob writes a blob file on disk

type FSRemote

type FSRemote struct {
	// contains filtered or unexported fields
}

func NewFSRemote

func NewFSRemote(dirpath string) (*FSRemote, error)

func (*FSRemote) DeleteObject

func (r *FSRemote) DeleteObject(key string) error

func (*FSRemote) GetObject

func (r *FSRemote) GetObject(key string) ([]byte, error)

func (*FSRemote) PutObject

func (r *FSRemote) PutObject(key string, data []byte) error

type Feedback

type Feedback string
const (
	// Anki-inspired feedbacks
	FeedbackEasy  Feedback = "easy"
	FeedbackGood  Feedback = "good"
	FeedbackAgain Feedback = "again"
	FeedbackHard  Feedback = "hard"
	// Special feedbacks
	FeedbackTooEasy Feedback = "too-easy" // Used to bury a card to max interval
	FeedbackTooHard Feedback = "too-hard" // Used to relearn a card from scratch
)

type File

type File struct {
	// A unique identifier among all files
	OID string `yaml:"oid"`
	// A unique human-friendly slug
	Slug string `yaml:"slug"`

	// Optional parent file (= index.md)
	ParentFileOID string `yaml:"file_oid,omitempty"`
	ParentFile    *File  `yaml:"-"` // Lazy-loaded

	// A relative path to the collection directory
	RelativePath string `yaml:"relative_path"`
	// The full wikilink to this file (without the extension)
	Wikilink string `yaml:"wikilink"`

	// The FrontMatter for the note file
	FrontMatter *yaml.Node `yaml:"front_matter"`

	// Merged attributes
	Attributes map[string]interface{} `yaml:"attributes,omitempty"`

	// Original title of the main heading without leading # characters
	Title string `yaml:"title,omitempty"`
	// Short title of the main heading without the kind prefix if present
	ShortTitle string `yaml:"short_title,omitempty"`

	Body     string `yaml:"body"`
	BodyLine int    `yaml:"body_line"`

	// Permission of the file (required to save back)
	Mode fs.FileMode `yaml:"mode"`
	// Size of the file (can be useful to detect changes)
	Size int64 `yaml:"size"`
	// Hash of the content (can be useful to detect changes too)
	Hash string `yaml:"hash"`
	// Content last modification date
	MTime time.Time `yaml:"mtime"`

	CreatedAt     time.Time `yaml:"created_at"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	DeletedAt     time.Time `yaml:"deleted_at,omitempty"`
	LastCheckedAt time.Time `yaml:"-"`
	// contains filtered or unexported fields
}

func NewEmptyFile

func NewEmptyFile(name string) *File

func NewFileFromAttributes

func NewFileFromAttributes(parent *File, name string, attributes []Attribute) *File

func NewFileFromParsedFile

func NewFileFromParsedFile(parent *File, parsedFile *ParsedFile) *File

func NewFileFromPath

func NewFileFromPath(parent *File, filepath string) (*File, error)

func NewOrExistingFile

func NewOrExistingFile(parent *File, path string) (*File, error)

func QueryFile

func QueryFile(db SQLClient, whereClause string, args ...any) (*File, error)

func QueryFiles

func QueryFiles(db SQLClient, whereClause string, args ...any) ([]*File, error)

func (*File) AbsoluteBodyLine

func (f *File) AbsoluteBodyLine(bodyLine int) int

AbsoluteBodyLine returns the line number in the file by taking into consideration the front matter.

func (*File) Blobs

func (f *File) Blobs() []*BlobRef

func (*File) Check

func (f *File) Check() error

func (*File) Delete

func (f *File) Delete() error

func (*File) FindFlashcardByTitle

func (f *File) FindFlashcardByTitle(shortTitle string) *Flashcard

FindFlashcardByTitle searches for a given flashcard based on its title.

func (*File) FindNoteByKindAndShortTitle

func (f *File) FindNoteByKindAndShortTitle(kind NoteKind, shortTitle string) *Note

FindNoteByKindAndShortTitle searches for a given note based on its kind and title.

func (*File) ForceState

func (f *File) ForceState(state State)

func (*File) FormatToHTML

func (f *File) FormatToHTML() string

func (*File) FormatToJSON

func (f *File) FormatToJSON() string

func (*File) FormatToMarkdown

func (f *File) FormatToMarkdown() string

func (*File) FormatToText

func (f *File) FormatToText() string

func (*File) FormatToYAML

func (f *File) FormatToYAML() string

func (*File) FrontMatterString

func (f *File) FrontMatterString() (string, error)

FrontMatterString formats the current attributes to the YAML front matter format.

func (*File) GetAttribute

func (f *File) GetAttribute(key string) interface{}

GetAttribute extracts a single attribute value at the top.

func (*File) GetAttributes

func (f *File) GetAttributes() map[string]interface{}

GetAttributes returns all file-specific and inherited attributes.

func (*File) GetFlashcards

func (f *File) GetFlashcards() []*Flashcard

GetFlashcards extracts flashcards from the file.

func (*File) GetMedias

func (f *File) GetMedias() []*Media

GetMedias extracts medias from the file.

func (*File) GetNotes

func (f *File) GetNotes() []*Note

func (*File) GetTags

func (f *File) GetTags() []string

GetTags returns all defined tags.

func (*File) HasTag

func (f *File) HasTag(name string) bool

HasTag returns if a file has a given tag.

func (*File) Insert

func (f *File) Insert() error

func (*File) Kind

func (f *File) Kind() string

func (*File) ModificationTime

func (f *File) ModificationTime() time.Time

func (*File) New

func (f *File) New() bool

func (*File) Read

func (f *File) Read(r io.Reader) error

func (*File) Refresh

func (f *File) Refresh() (bool, error)

func (*File) Relations

func (f *File) Relations() []*Relation

func (*File) Save

func (f *File) Save() error

func (*File) SaveOnDisk

func (f *File) SaveOnDisk() error

func (*File) SetAlive

func (f *File) SetAlive()

func (*File) SetAttribute

func (f *File) SetAttribute(key string, value interface{})

SetAttribute overrides or defines a single attribute.

func (*File) State

func (f *File) State() State

func (File) String

func (f File) String() string

func (*File) SubObjects

func (f *File) SubObjects() []StatefulObject

func (*File) UniqueOID

func (f *File) UniqueOID() string

func (*File) Update

func (f *File) Update() error

func (*File) Updated

func (f *File) Updated() bool

func (*File) Write

func (f *File) Write(w io.Writer) error

type Flashcard

type Flashcard struct {
	OID string `yaml:"oid"`

	// Short title of the note (denormalized field)
	ShortTitle string `yaml:"short_title"`

	// File
	FileOID string `yaml:"file_oid"`
	File    *File  `yaml:"-"` // Lazy-loaded

	// Note representing the flashcard
	NoteOID string `yaml:"note_oid"`
	Note    *Note  `yaml:"-"` // Lazy-loaded

	// The filepath of the file containing the note (denormalized field)
	RelativePath string `yaml:"relative_path"`

	// List of tags
	Tags []string `yaml:"tags,omitempty"`

	// Fields in Markdown (best for editing)
	FrontMarkdown string `yaml:"front_markdown"`
	BackMarkdown  string `yaml:"back_markdown"`
	// Fields in HTML (best for rendering)
	FrontHTML string `yaml:"front_html"`
	BackHTML  string `yaml:"back_html"`
	// Fields in raw text (best for indexing)
	FrontText string `yaml:"front_text"`
	BackText  string `yaml:"back_text"`

	// Timestamps to track changes
	CreatedAt     time.Time `yaml:"created_at"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	DeletedAt     time.Time `yaml:"deleted_at,omitempty"`
	LastCheckedAt time.Time `yaml:"-"`

	// SRS
	DueAt     time.Time      `yaml:"due_at,omitempty"`
	StudiedAt time.Time      `yaml:"studied_at,omitempty"`
	Settings  map[string]any `yaml:"settings,omitempty"`
	// contains filtered or unexported fields
}

func MustFindFlashcardByShortTitle

func MustFindFlashcardByShortTitle(t *testing.T, shortTitle string) *Flashcard

func NewFlashcard

func NewFlashcard(file *File, note *Note) *Flashcard

NewFlashcard initializes a new flashcard.

func NewOrExistingFlashcard

func NewOrExistingFlashcard(file *File, note *Note) *Flashcard

func QueryFlashcard

func QueryFlashcard(db SQLClient, whereClause string, args ...any) (*Flashcard, error)

func QueryFlashcards

func QueryFlashcards(db SQLClient, whereClause string, args ...any) ([]*Flashcard, error)

func (*Flashcard) Blobs

func (f *Flashcard) Blobs() []*BlobRef

func (*Flashcard) Check

func (f *Flashcard) Check() error

func (*Flashcard) Delete

func (f *Flashcard) Delete() error

func (*Flashcard) ForceState

func (f *Flashcard) ForceState(state State)

func (*Flashcard) Insert

func (f *Flashcard) Insert() error

func (*Flashcard) Kind

func (f *Flashcard) Kind() string

func (*Flashcard) ModificationTime

func (f *Flashcard) ModificationTime() time.Time

func (*Flashcard) New

func (f *Flashcard) New() bool

func (*Flashcard) Read

func (f *Flashcard) Read(r io.Reader) error

func (*Flashcard) Refresh

func (f *Flashcard) Refresh() (bool, error)

func (*Flashcard) Relations

func (f *Flashcard) Relations() []*Relation

func (*Flashcard) Save

func (f *Flashcard) Save() error

func (*Flashcard) State

func (f *Flashcard) State() State

func (Flashcard) String

func (f Flashcard) String() string

func (*Flashcard) SubObjects

func (f *Flashcard) SubObjects() []StatefulObject

func (*Flashcard) UniqueOID

func (f *Flashcard) UniqueOID() string

func (*Flashcard) Update

func (f *Flashcard) Update() error

func (*Flashcard) Updated

func (f *Flashcard) Updated() bool

func (*Flashcard) Write

func (f *Flashcard) Write(w io.Writer) error

type GlobPath

type GlobPath string

func (GlobPath) Expr

func (g GlobPath) Expr() string

func (GlobPath) Match

func (g GlobPath) Match(path string) bool

Match tests a given path. NB: Directories must have a trailing /.

func (GlobPath) Negate

func (g GlobPath) Negate() bool

type GlobPaths

type GlobPaths []GlobPath

func (GlobPaths) Match

func (g GlobPaths) Match(path string) bool

Match tests if a file path satisfies the conditions.

type IgnoreFile

type IgnoreFile struct {
	Entries GlobPaths
}

func (*IgnoreFile) MustExcludeFile

func (i *IgnoreFile) MustExcludeFile(path string, dir bool) bool

type Index

type Index struct {
	Objects []*IndexObject `yaml:"objects"`

	// Mapping between pack files and their commit OID
	PackFiles map[string]string `yaml:"packfiles"`

	// A list of pack files that is known to be orphans
	OrphanPackFiles []*IndexOrphanPackFile `yaml:"orphan_packfiles"`

	// A list of blobs that is known to be orphans
	OrphanBlobs []*IndexOrphanBlob `yaml:"orphan_blobs"`

	StagingArea StagingArea `yaml:"staging"`
	// contains filtered or unexported fields
}

Index See https://git-scm.com/docs/index-format for inspiration.

The index file is used to determine if an object is new and to quickly locate which the commit file containing the object otherwise. Useful when adding or restoring objects.

func NewIndex

func NewIndex() *Index

NewIndex instantiates a new index.

func NewIndexFromPath

func NewIndexFromPath(path string) (*Index, error)

NewIndexFromPath loads an index file from a file.

func ReadIndex

func ReadIndex() *Index

func (*Index) AppendPackFile

func (i *Index) AppendPackFile(commitOID string, packFile *PackFile)

AppendPackFile completes the index with object from a pack file.

func (*Index) CloneForRemote

func (i *Index) CloneForRemote() *Index

CloneForRemote prepares a cleaned index before a push.

func (*Index) CountChanges

func (i *Index) CountChanges() int

CountChanges returns the number of changes currently present in the staging area.

func (*Index) CreateCommitFromStagingArea

func (i *Index) CreateCommitFromStagingArea() (*Commit, []*PackFile)

CreateCommit generates a new commit from current changes in the staging area.

func (*Index) Diff

func (i *Index) Diff(other *Index) *IndexDiff

Diff reports differences to reconcile the receiver with the given index.

func (*Index) FindCommitContaining

func (i *Index) FindCommitContaining(objectOID string) (string, bool)

FindCommitContaining returns the commit associated with a given object.

func (*Index) FindPackFileContaining

func (i *Index) FindPackFileContaining(objectOID string) (string, bool)

FindPackFileContaining returns the pack file associated with a given object.

func (*Index) IsOrphanBlob

func (i *Index) IsOrphanBlob(oid string) bool

IsOrphanBlob checks if the blob has already beeing deleted.

func (*Index) Read

func (i *Index) Read(r io.Reader) error

Read read an index from the file.

func (*Index) ReadIndexObject

func (i *Index) ReadIndexObject(objectOID string) (*IndexObject, bool)

ReadIndexObject searches for the given object in the index.

func (*Index) Save

func (i *Index) Save() error

Save persists the index on disk.

func (*Index) StageObject

func (i *Index) StageObject(obj StatefulObject) error

StageObject registers a changed object into the staging area

func (*Index) Write

func (i *Index) Write(w io.Writer) error

Write dumps the index to a file.

type IndexDiff

type IndexDiff struct {
	// Objects present only in the compared index
	MissingObjects []*IndexObject
	// Pack Files no longer present in the compared index
	MissingOrphanPackFiles []string
	// Blobs no longer present in the compared index
	MissingOrphanBlobs []string
}

type IndexObject

type IndexObject struct {
	OID   string    `yaml:"oid"`
	Kind  string    `yaml:"kind"`
	MTime time.Time `yaml:"mtime"`
	// The commit (and its packfile) containing the latest version (empty for uncommitted object)
	CommitOID   string `yaml:"commit_oid"`
	PackFileOID string `yaml:"packfile_oid"`
}

func (IndexObject) String

func (i IndexObject) String() string

type IndexOrphanBlob

type IndexOrphanBlob struct {
	OID   string    `yaml:"oid"`
	DTime time.Time `yaml:"dtime"`
	// The media that introduced this blob
	MediaOID string `yaml:"media_oid"`
}

type IndexOrphanPackFile

type IndexOrphanPackFile struct {
	OID   string    `yaml:"oid"`
	DTime time.Time `yaml:"dtime"`
}
type Link struct {
	OID string `yaml:"oid"`

	NoteOID string `yaml:"note_oid"`

	// The filepath of the file containing the note (denormalized field)
	RelativePath string `yaml:"relative_path"`

	// The link text
	Text string `yaml:"text"`

	// The link destination
	URL string `yaml:"url"`

	// The optional link title
	Title string `yaml:"title"`

	// The optional GO name
	GoName string `yaml:"go_name"`

	// Timestamps to track changes
	CreatedAt     time.Time `yaml:"created_at"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	DeletedAt     time.Time `yaml:"deleted_at,omitempty"`
	LastCheckedAt time.Time `yaml:"-"`
	// contains filtered or unexported fields
}
func NewLink(note *Note, text, url, title, goName string) *Link
func NewOrExistingLink(note *Note, text, url, title, goName string) *Link
func QueryLink(db SQLClient, whereClause string, args ...any) (*Link, error)
func QueryLinks(db SQLClient, whereClause string, args ...any) ([]*Link, error)

func (*Link) Blobs

func (l *Link) Blobs() []*BlobRef

func (*Link) Check

func (l *Link) Check() error

func (*Link) Delete

func (l *Link) Delete() error

func (*Link) ForceState

func (l *Link) ForceState(state State)

func (*Link) Insert

func (l *Link) Insert() error

func (*Link) Kind

func (l *Link) Kind() string

func (*Link) ModificationTime

func (l *Link) ModificationTime() time.Time

func (*Link) New

func (l *Link) New() bool

func (*Link) Read

func (l *Link) Read(r io.Reader) error

func (*Link) Refresh

func (l *Link) Refresh() (bool, error)

func (*Link) Relations

func (l *Link) Relations() []*Relation

func (*Link) Save

func (l *Link) Save() error

func (*Link) State

func (l *Link) State() State

func (Link) String

func (l Link) String() string

func (*Link) SubObjects

func (l *Link) SubObjects() []StatefulObject

func (*Link) UniqueOID

func (l *Link) UniqueOID() string

func (*Link) Update

func (l *Link) Update() error

func (*Link) Updated

func (l *Link) Updated() bool

func (*Link) Write

func (l *Link) Write(w io.Writer) error

type LintFile

type LintFile struct {
	Rules []ConfigLintRule `yaml:"rules"`

	Schemas []ConfigLintSchema `yaml:"schemas"`
}

func (*LintFile) GetAttributeDefinition

func (l *LintFile) GetAttributeDefinition(name string, filter func(schema ConfigLintSchema) bool) *ConfigLintSchemaAttribute

GetAttributeDefinition returns the attribute definition to use.

func (*LintFile) IsInheritableAttribute

func (l *LintFile) IsInheritableAttribute(attributeName string, filePath string) bool

IsInheritableAttribute returns if an attribute can be inherited between files/notes.

func (*LintFile) Severity

func (l *LintFile) Severity(name string) string

Severity returns the severity of a lint rule.

type LintResult

type LintResult struct {
	AnalyzedFiles int
	AffectedFiles int
	Warnings      []*Violation
	Errors        []*Violation
}

func (*LintResult) Append

func (r *LintResult) Append(violations ...*Violation)

Append merges new violations into the current result.

func (LintResult) String

func (r LintResult) String() string

type LintRule

type LintRule func(*ParsedFile, []string) ([]*Violation, error)

LintRule describes the interface that rules must conform.

type LintRuleDefinition

type LintRuleDefinition struct {
	Eval LintRule
}

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

func CurrentLogger

func CurrentLogger() *Logger

func NewLogger

func NewLogger() *Logger

func (*Logger) Debug

func (l *Logger) Debug(v ...any)

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...any)

func (*Logger) Fatal

func (l *Logger) Fatal(v ...any)

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, v ...any)

func (*Logger) Info

func (l *Logger) Info(v ...any)

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...any)

func (*Logger) SetVerboseLevel

func (l *Logger) SetVerboseLevel(level VerboseLevel) *Logger

SetVerboseLevel overrides the default verbose level

func (*Logger) Trace

func (l *Logger) Trace(v ...any)

func (*Logger) Tracef

func (l *Logger) Tracef(format string, v ...any)

func (*Logger) Warn

func (l *Logger) Warn(v ...any)

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...any)

type MatchedFile

type MatchedFile struct {
	Path         string
	RelativePath string
	DirEntry     fs.DirEntry
	FileInfo     fs.FileInfo
}

type Media

type Media struct {
	OID string `yaml:"oid"`

	// Relative path
	RelativePath string `yaml:"relative_path"`

	// Type of media
	MediaKind MediaKind `yaml:"kind"`

	// Media exists on disk
	Dangling bool `yaml:"dangling"`

	// File extension in lowercase
	Extension string `yaml:"extension"`

	// Content last modification date
	MTime time.Time `yaml:"mtime"`

	// MD5 Checksum
	Hash string `yaml:"hash"`

	// 	Size of the file
	Size int64 `yaml:"size"`

	// Permission of the file
	Mode fs.FileMode `yaml:"mode"`

	// Eager-loaded list of blobs
	BlobRefs []*BlobRef `yaml:"blobs"`

	// Timestamps to track changes
	CreatedAt     time.Time `yaml:"created_at"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	DeletedAt     time.Time `yaml:"deleted_at,omitempty"`
	LastCheckedAt time.Time `yaml:"-"`
	// contains filtered or unexported fields
}

func NewMedia

func NewMedia(relpath string) *Media

NewMedia initializes a new media.

func NewOrExistingMedia

func NewOrExistingMedia(relpath string) *Media

func QueryMedia

func QueryMedia(db SQLClient, whereClause string, args ...any) (*Media, error)

func QueryMedias

func QueryMedias(db SQLClient, whereClause string, args ...any) ([]*Media, error)

func (*Media) Blobs

func (m *Media) Blobs() []*BlobRef

func (*Media) Check

func (m *Media) Check() error

func (*Media) Delete

func (m *Media) Delete() error

func (*Media) DeleteBlobs

func (m *Media) DeleteBlobs() error

func (*Media) ForceState

func (m *Media) ForceState(state State)

func (*Media) Insert

func (m *Media) Insert() error

func (*Media) InsertBlobs

func (m *Media) InsertBlobs() error

func (*Media) Kind

func (m *Media) Kind() string

func (*Media) ModificationTime

func (m *Media) ModificationTime() time.Time

func (*Media) New

func (m *Media) New() bool

func (*Media) Read

func (m *Media) Read(r io.Reader) error

func (*Media) Refresh

func (m *Media) Refresh() (bool, error)

func (*Media) Relations

func (m *Media) Relations() []*Relation

func (*Media) Save

func (m *Media) Save() error

func (*Media) State

func (m *Media) State() State

func (Media) String

func (m Media) String() string

func (*Media) SubObjects

func (m *Media) SubObjects() []StatefulObject

func (*Media) UniqueOID

func (m *Media) UniqueOID() string

func (*Media) Update

func (m *Media) Update() error

func (*Media) UpdateBlobs

func (m *Media) UpdateBlobs()

func (*Media) Updated

func (m *Media) Updated() bool

func (*Media) Write

func (m *Media) Write(w io.Writer) error

type MediaKind

type MediaKind string
const (
	KindUnknown  MediaKind = "unknown"
	KindAudio    MediaKind = "audio"
	KindPicture  MediaKind = "picture"
	KindVideo    MediaKind = "video"
	KindDocument MediaKind = "document"
)

func DetectMediaKind

func DetectMediaKind(filename string) MediaKind

DetectMediaKind returns the media kind based on a file path.

type Note

type Note struct {
	// A unique identifier among all files
	OID string `yaml:"oid"`
	// A unique human-friendly slug
	Slug string `yaml:"slug"`

	// File containing the note
	FileOID string `yaml:"file_oid"`
	File    *File  `yaml:"-"` // Lazy-loaded

	// Parent Note surrounding the note
	ParentNoteOID string `yaml:"parent_note_oid"`
	ParentNote    *Note  `yaml:"-"` // Lazy-loaded

	// Type of note
	NoteKind NoteKind `yaml:"kind"`

	// Original title of the note without leading # characters
	Title string `yaml:"title"`
	// Long title of the note without the kind prefix but prefixed by parent note's short titles
	LongTitle string `yaml:"long_title"`
	// Short title of the note without the kind prefix
	ShortTitle string `yaml:"short_title"`

	// The filepath of the file containing the note (denormalized field)
	RelativePath string `yaml:"relative_path"`
	// The full wikilink to this note (without the extension)
	Wikilink string `yaml:"wikilink"`

	// Merged attributes
	Attributes map[string]interface{} `yaml:"attributes,omitempty"`

	// Merged tags
	Tags []string `yaml:"tags,omitempty"`

	// Line number (1-based index) of the note section title
	Line int `yaml:"line"`

	// Content in various formats (best for editing, rendering, writing, etc.)
	ContentRaw      string `yaml:"content_raw"`
	Hash            string `yaml:"content_hash"`
	TitleMarkdown   string `yaml:"title_markdown"`
	TitleHTML       string `yaml:"title_html"`
	TitleText       string `yaml:"title_text"`
	ContentMarkdown string `yaml:"content_markdown"`
	ContentHTML     string `yaml:"content_html"`
	ContentText     string `yaml:"content_text"`
	CommentMarkdown string `yaml:"comment_markdown,omitempty"`
	CommentHTML     string `yaml:"comment_html,omitempty"`
	CommentText     string `yaml:"comment_text,omitempty"`

	// Timestamps to track changes
	CreatedAt     time.Time `yaml:"created_at"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	DeletedAt     time.Time `yaml:"deleted_at,omitempty"`
	LastCheckedAt time.Time `yaml:"-"`
	// contains filtered or unexported fields
}

func MustFindNoteByPathAndTitle

func MustFindNoteByPathAndTitle(t *testing.T, relativePath, longTitle string) *Note

func NewNote

func NewNote(f *File, parent *Note, parsedNote *ParsedNote) *Note

NewNote creates a new note from given attributes.

func NewOrExistingNote

func NewOrExistingNote(f *File, parent *Note, parsedNote *ParsedNote) *Note

NewOrExistingNote loads and updates an existing note or creates a new one if new.

func QueryNote

func QueryNote(db SQLClient, whereClause string, args ...any) (*Note, error)

func QueryNotes

func QueryNotes(db SQLClient, whereClause string, args ...any) ([]*Note, error)

func (*Note) Blobs

func (n *Note) Blobs() []*BlobRef

func (*Note) Check

func (n *Note) Check() error

func (*Note) Delete

func (n *Note) Delete() error

func (*Note) ForceState

func (n *Note) ForceState(state State)

func (*Note) FormatToHTML

func (n *Note) FormatToHTML() string

func (*Note) FormatToJSON

func (n *Note) FormatToJSON() string

func (*Note) FormatToMarkdown

func (n *Note) FormatToMarkdown() string

func (*Note) FormatToText

func (n *Note) FormatToText() string

func (*Note) FormatToYAML

func (n *Note) FormatToYAML() string

func (*Note) GetAttribute

func (n *Note) GetAttribute(name string) interface{}

func (*Note) GetAttributeString

func (n *Note) GetAttributeString(name, defaultValue string) string

func (*Note) GetAttributes

func (n *Note) GetAttributes() map[string]interface{}

func (*Note) GetFile

func (n *Note) GetFile() *File

GetFile returns the containing file, loading it from database if necessary.

func (n *Note) GetLinks() []*Link

GetLinks extracts special links from a note.

func (*Note) GetMedias

func (n *Note) GetMedias() []*Media

GetMedias extracts medias from the note.

func (*Note) GetNoteAttributes

func (n *Note) GetNoteAttributes() map[string]interface{}

GetNoteAttributes returns the attributes specifically present on the note.

func (*Note) GetNoteTags

func (n *Note) GetNoteTags() []string

GetNoteTags returns the tags specifically present on the note.

func (*Note) GetParentNote

func (n *Note) GetParentNote() *Note

GetParentNote returns the parent note, loading it from database if necessary.

func (*Note) GetReminders

func (n *Note) GetReminders() []*Reminder

GetReminders extracts reminders from the note.

func (*Note) GetTags

func (n *Note) GetTags() []string

func (*Note) HasAttribute

func (n *Note) HasAttribute(name string) bool

func (*Note) HasTag

func (n *Note) HasTag(name string) bool

HasTag returns if a file has a given tag.

func (*Note) Insert

func (n *Note) Insert() error

func (*Note) Kind

func (n *Note) Kind() string

func (*Note) ModificationTime

func (n *Note) ModificationTime() time.Time

func (*Note) New

func (n *Note) New() bool

func (*Note) Read

func (n *Note) Read(r io.Reader) error

func (*Note) Refresh

func (n *Note) Refresh() (bool, error)

func (*Note) Relations

func (n *Note) Relations() []*Relation
func (n *Note) ReplaceMediasByOIDLinks(md string) string

ReplaceMediasByOIDLinks replaces all non-dangling links by a OID fake link.

func (*Note) RunHooks

func (n *Note) RunHooks(hookNames []string) error

RunHooks triggers all hooks on the note.

func (*Note) Save

func (n *Note) Save() error

func (*Note) SetAttribute

func (n *Note) SetAttribute(name string, value interface{})

func (*Note) State

func (n *Note) State() State

func (Note) String

func (n Note) String() string

func (*Note) SubObjects

func (n *Note) SubObjects() []StatefulObject

func (*Note) UniqueOID

func (n *Note) UniqueOID() string

func (*Note) Update

func (n *Note) Update() error

func (*Note) Updated

func (n *Note) Updated() bool

func (*Note) Write

func (n *Note) Write(w io.Writer) error

type NoteKind

type NoteKind string
const (
	KindFree       NoteKind = "free"
	KindReference  NoteKind = "reference"
	KindNote       NoteKind = "note"
	KindFlashcard  NoteKind = "flashcard"
	KindCheatsheet NoteKind = "cheatsheet"
	KindQuote      NoteKind = "quote"
	KindJournal    NoteKind = "journal"
	KindTodo       NoteKind = "todo"
	KindArtwork    NoteKind = "artwork"
	KindSnippet    NoteKind = "snippet"
)

type OIDGenerator

type OIDGenerator interface {
	NewOID() string
	NewOIDFromBytes(b []byte) string
}

type Object

type Object interface {
	// Kind returns the object kind to determine which kind of object to create.
	Kind() string
	// UniqueOID returns the OID of the object.
	UniqueOID() string
	// ModificationTime returns the last modification time.
	ModificationTime() time.Time

	// SubObjects returns the objects directly contained by this object.
	SubObjects() []StatefulObject
	// Blobs returns the optional blobs associated with this object.
	Blobs() []*BlobRef
	// Relations returns the relations where the current object is the source.
	Relations() []*Relation

	// Read rereads the object from YAML.
	Read(r io.Reader) error
	// Write writes the object to YAML.
	Write(w io.Writer) error

	// String returns a one-line description
	String() string
}

Object groups method common to all kinds of managed objects. Useful when creating commits in a generic way where a single commit groups different kinds of objects inside the same object.

type ObjectData

type ObjectData []byte // alias to serialize to YAML easily

ObjectData serializes any Object to base64 after zlib compression.

func NewObjectData

func NewObjectData(obj Object) (ObjectData, error)

NewObjectData creates a compressed-string representation of the object.

func (ObjectData) MarshalYAML

func (od ObjectData) MarshalYAML() (interface{}, error)

func (ObjectData) Unmarshal

func (od ObjectData) Unmarshal(target interface{}) error

func (*ObjectData) UnmarshalYAML

func (od *ObjectData) UnmarshalYAML(node *yaml.Node) error

type PackFile

type PackFile struct {
	OID         string        `yaml:"oid"`
	CTime       time.Time     `yaml:"ctime"`
	MTime       time.Time     `yaml:"mtime"`
	PackObjects []*PackObject `yaml:"objects"`
}

func NewPackFile

func NewPackFile() *PackFile

NewPackFile initializes a new empty pack file.

func NewPackFileFromPath

func NewPackFileFromPath(path string) (*PackFile, error)

NewPackFileFromPath reads a pack file file on disk or returns an empty instance.

func NewPackFileWithOID

func NewPackFileWithOID(oid string) *PackFile

NewPackFileWithOID initializes a new empty pack file with a given OID.

func (*PackFile) AppendObject

func (p *PackFile) AppendObject(obj StatefulObject) error

AppendObject registers a new object inside the pack file.

func (*PackFile) AppendPackObject

func (p *PackFile) AppendPackObject(obj *PackObject)

AppendPackObject registers a new stateful object inside the pack file.

func (*PackFile) AppendStagingObject

func (p *PackFile) AppendStagingObject(obj *StagingObject)

Append registers a new staged object inside a pack file.

func (*PackFile) Blobs

func (p *PackFile) Blobs() []*BlobRef

func (*PackFile) GetPackObject

func (p *PackFile) GetPackObject(oid string) (*PackObject, bool)

GetPackObject retrieves an object from a pack file.

func (*PackFile) Merge

func (p *PackFile) Merge(other *PackFile) (*PackFile, bool)

Merge tries to merge two pack files together by returning a new pack file containing the concatenation of both pack files.

func (*PackFile) Read

func (p *PackFile) Read(r io.Reader) error

Read populates a pack file from an object file.

func (*PackFile) Ref

func (p *PackFile) Ref() *PackFileRef

Ref returns a ref to the pack file.

func (*PackFile) Save

func (p *PackFile) Save() error

Save writes a new pack file inside .nt/objects.

func (*PackFile) SaveTo

func (p *PackFile) SaveTo(path string) error

SaveTo writes a new pack file to the given location.

func (*PackFile) UniqueOID

func (p *PackFile) UniqueOID() string

func (*PackFile) UnmarshallObject

func (p *PackFile) UnmarshallObject(oid string, target interface{}) error

UnmarshallObject extract a single object from a commit.

func (*PackFile) Write

func (p *PackFile) Write(w io.Writer) error

Write dumps a pack file to an object file.

type PackFileRef

type PackFileRef struct {
	OID   string    `yaml:"oid"`
	CTime time.Time `yaml:"ctime"`
	MTime time.Time `yaml:"mtime"`
}

func NewPackFileRefWithOID

func NewPackFileRefWithOID(oid string) *PackFileRef

NewPackFileRefWithOID initializes a new empty pack file ref with a given OID.

type PackFileRefs

type PackFileRefs []*PackFileRef

Convenient type to add methods

func (PackFileRefs) OIDs

func (p PackFileRefs) OIDs() []string

type PackObject

type PackObject struct {
	OID         string     `yaml:"oid"`
	Kind        string     `yaml:"kind"`
	State       State      `yaml:"state"` // (A) added, (D) deleted, (M) modified, (R) renamed
	MTime       time.Time  `yaml:"mtime"`
	Description string     `yaml:"desc"`
	Data        ObjectData `yaml:"data"`
}

func (*PackObject) ReadObject

func (p *PackObject) ReadObject() StatefulObject

ReadObject recreates the core object from a commit object.

type ParsedFile

type ParsedFile struct {
	// The paths to the file
	AbsolutePath string
	RelativePath string

	// Stat
	Stat  fs.FileInfo
	LStat fs.FileInfo

	// The raw file bytes
	Bytes []byte

	// Main Heading
	Slug       string
	Title      string
	ShortTitle string

	// The YAML Front Matter
	FrontMatter *yaml.Node
	// File attributes extracted from the Front Matter
	FileAttributes map[string]interface{}

	// The body (= content minus the front matter)
	Body     string
	BodyLine int
}

func ParseFile

func ParseFile(path string) (*ParsedFile, error)

ParseFile contains the main logic to parse a raw note file.

func (*ParsedFile) AbsoluteBodyLine

func (f *ParsedFile) AbsoluteBodyLine(bodyLine int) int

AbsoluteBodyLine returns the line number in the file by taking into consideration the front matter.

func (*ParsedFile) Content

func (f *ParsedFile) Content() string

Content returns the raw file content.

func (*ParsedFile) GetTags

func (f *ParsedFile) GetTags() []string

GetTags returns all defined tags on file.

func (*ParsedFile) HasTag

func (f *ParsedFile) HasTag(tagName string) bool

HasTag returns if the file has specifically a given tag.

func (*ParsedFile) Lint

func (f *ParsedFile) Lint(ruleNames []string) ([]*Violation, error)
func (f *ParsedFile) Wikilinks() []*Wikilink

Wikilinks returns the wikilinks present inside a file.

type ParsedMedia

type ParsedMedia struct {
	// The path as specified in the file. (Ex: "../medias/pic.png")
	RawPath string
	// The path relative to the root collection directory. (Ex: "references/medias/pic.png")
	RelativePath string
	// The absolute path. (Ex: "$HOME/notes/references/medias/pic.png")
	AbsolutePath string
	// Line number where the link present.
	Line int
}

func ParseMedias

func ParseMedias(fileRelativePath, fileBody string) []*ParsedMedia

ParseMedias extracts raw paths from a file or note body content.

type ParsedNote

type ParsedNote struct {
	Level          int
	Kind           NoteKind
	Slug           string
	Title          string
	ShortTitle     string
	Line           int
	Body           string
	NoteAttributes map[string]interface{}
	NoteTags       []string
}

ParsedNote represents a single raw note inside a file.

func MustParseNote

func MustParseNote(noteContent string, fileSlug string) *ParsedNote

MustParseNote is pratical in unit test to setup a new note.

func ParseNotes

func ParseNotes(fileBody string, fileSlug string) []*ParsedNote

ParseNotes extracts the notes from a file body.

func (*ParsedNote) Hash

func (n *ParsedNote) Hash() string

Hash returns the current hash to use when searching for an existing note in database to avoid recreating it.

func (n *ParsedNote) Wikilinks() []*Wikilink

Wikilinks returns the wikilinks present in the note.

type Query

type Query struct {
	Kinds      []string
	Tags       []string
	Attributes map[string]interface{}
	Path       string
	Terms      []string
}

func NewQuery

func NewQuery() *Query

NewQuery instantiates a new query.

func ParseQuery

func ParseQuery(q string) (*Query, error)

ParseQuery parses a user query.

type QueueType

type QueueType int
const (
	QueueSuspend  QueueType = -1 // leeches as manual suspension is not supported
	QueueNew      QueueType = 0  // new (never shown)
	QueueLearn    QueueType = 1  // learning/relearning
	QueueReview   QueueType = 2  // review (as for type)
	QueueDayLearn QueueType = 3  // in learning, next review in at least a day after the previous review
)

type Relation

type Relation struct {
	// Source
	SourceOID  string `yaml:"source_oid"`
	SourceKind string `yaml:"source_kind"`

	// Target
	TargetOID  string `yaml:"target_oid"`
	TargetKind string `yaml:"target_kind"`

	Type string `yaml:"type"`
}

func NewRelation

func NewRelation(oidA string, kindA string, oidB string, kindB string, relationType string) *Relation

NewRelation instantiates a new relation.

func NewRelationFromObjects

func NewRelationFromObjects(objA, objB Object, relationType string) *Relation

func QueryRelation

func QueryRelation(db SQLClient, whereClause string, args ...any) (*Relation, error)

func QueryRelations

func QueryRelations(db SQLClient, whereClause string, args ...any) ([]*Relation, error)

func (Relation) String

func (r Relation) String() string

type Reminder

type Reminder struct {
	OID string `yaml:"oid"`

	// File
	FileOID string `yaml:"file_oid"`
	File    *File  `yaml:"-"` // Lazy-loaded

	// Note representing the flashcard
	NoteOID string `yaml:"note_oid"`
	Note    *Note  `yaml:"-"` // Lazy-loaded

	// The filepath of the file containing the note (denormalized field)
	RelativePath string `yaml:"relative_path"`

	// Description
	DescriptionRaw      string `yaml:"description_raw"`
	DescriptionMarkdown string `yaml:"description_markdown"`
	DescriptionHTML     string `yaml:"description_html"`
	DescriptionText     string `yaml:"description_text"`

	// Tag value containig the formula to determine the next occurence
	Tag string `yaml:"tag"`

	// Timestamps to track progress
	LastPerformedAt time.Time `yaml:"last_performed_at"`
	NextPerformedAt time.Time `yaml:"next_performed_at"`

	// Timestamps to track changes
	CreatedAt     time.Time `yaml:"created_at"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	DeletedAt     time.Time `yaml:"deleted_at,omitempty"`
	LastCheckedAt time.Time `yaml:"-"`
	// contains filtered or unexported fields
}

func NewOrExistingReminder

func NewOrExistingReminder(note *Note, descriptionRaw, tag string) (*Reminder, error)

func NewReminder

func NewReminder(note *Note, descriptionRaw, tag string) (*Reminder, error)

NewReminder instantiates a new reminder.

func QueryReminder

func QueryReminder(db SQLClient, whereClause string, args ...any) (*Reminder, error)

func QueryReminders

func QueryReminders(db SQLClient, whereClause string, args ...any) ([]*Reminder, error)

func (*Reminder) Blobs

func (r *Reminder) Blobs() []*BlobRef

func (*Reminder) Check

func (r *Reminder) Check() error

func (*Reminder) Delete

func (r *Reminder) Delete() error

func (*Reminder) ForceState

func (r *Reminder) ForceState(state State)

func (*Reminder) Insert

func (r *Reminder) Insert() error

func (*Reminder) Kind

func (r *Reminder) Kind() string

func (*Reminder) ModificationTime

func (r *Reminder) ModificationTime() time.Time

func (*Reminder) New

func (r *Reminder) New() bool

func (*Reminder) Next

func (r *Reminder) Next() error

func (*Reminder) Read

func (n *Reminder) Read(r io.Reader) error

func (*Reminder) Refresh

func (r *Reminder) Refresh() (bool, error)

func (*Reminder) Relations

func (r *Reminder) Relations() []*Relation

func (*Reminder) Save

func (r *Reminder) Save() error

func (*Reminder) State

func (r *Reminder) State() State

func (Reminder) String

func (r Reminder) String() string

func (*Reminder) SubObjects

func (r *Reminder) SubObjects() []StatefulObject

func (*Reminder) UniqueOID

func (r *Reminder) UniqueOID() string

func (*Reminder) Update

func (r *Reminder) Update() error

func (*Reminder) Updated

func (r *Reminder) Updated() bool

func (*Reminder) Write

func (r *Reminder) Write(w io.Writer) error

type Remote

type Remote interface {
	GetObject(key string) ([]byte, error)
	PutObject(key string, content []byte) error
	DeleteObject(key string) error
}

Remote provides an abstraction in front of remote implementations.

A remote must be able to save different files: - info files (ex: commit-graph) - object files (ex: Commit, or File, Note, Flaschard, ...) - blob files (ex: medias in various sizes)

A remote is free to save files in any format as long as it can retrieve the same field when querying using the same key.

type Review

type Review struct {
	FlashcardOID string         `yaml:"flashcard_oid"`
	Feedback     Feedback       `yaml:"feedback"`
	DurationInMs int            `yaml:"duration_ms"`
	CompletedAt  time.Time      `yaml:"completed_at"`
	DueAt        time.Time      `yaml:"due_at"`
	Settings     map[string]any `yaml:"settings"` // Include algorithm-specific attributes (like the e-factor in SM-2)
}

type S3Remote

type S3Remote struct {
	// contains filtered or unexported fields
}

func NewS3RemoteWithCredentials

func NewS3RemoteWithCredentials(endpoint string, bucketName string, accessKey, secretKey string, secure bool) (*S3Remote, error)

func (*S3Remote) DeleteObject

func (r *S3Remote) DeleteObject(key string) error

func (*S3Remote) GetObject

func (r *S3Remote) GetObject(key string) ([]byte, error)

func (*S3Remote) PutObject

func (r *S3Remote) PutObject(key string, data []byte) error

type SQLClient

type SQLClient interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	Prepare(query string) (*sql.Stmt, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	Exec(query string, args ...any) (sql.Result, error)
	QueryRow(query string, args ...any) *sql.Row
	Query(query string, args ...any) (*sql.Rows, error)
}

Queryable provides a common interface between sql.DB and sql.Tx to make methods compatible with both.

type StagingArea

type StagingArea []*StagingObject

func (*StagingArea) ContainsFile

func (sa *StagingArea) ContainsFile(relpath string) (*StagingObject, bool)

Contains file returns the staging object from a given file path.

func (*StagingArea) Count

func (sa *StagingArea) Count() int

Count returns the number of objects inside the staging area.

func (*StagingArea) CountByState

func (sa *StagingArea) CountByState(state State) int

CountByState returns the number of objects inside the staging area in a given state.

func (*StagingArea) ReadObject

func (sa *StagingArea) ReadObject(objectOID string) (StatefulObject, bool)

ReadObject searches for the given object in staging area

func (*StagingArea) ReadStagingObject

func (sa *StagingArea) ReadStagingObject(objectOID string) (*StagingObject, bool)

ReadStagingObject searches for the given staging object in staging area

type StagingObject

type StagingObject struct {
	PackObject
	PreviousCommitOID   string `yaml:"previous_commit_oid"`
	PreviousPackFileOID string `yaml:"previous_packfile_oid"`
}

func (StagingObject) String

func (s StagingObject) String() string

type State

type State string

State describes an object status.

const (
	None     State = "none"
	Added    State = "added"
	Modified State = "modified"
	Deleted  State = "deleted"
)

type StatefulObject

type StatefulObject interface {
	Object

	Refresh() (bool, error)

	// State returns the current state.
	State() State
	// ForceState marks the object in the given state
	ForceState(newState State)

	// Save persists to DB
	Save() error
}

StatefulObject to represent the subset of updatable objects persisted in database.

type Stats

type Stats struct {
	OnDisk *StatsOnDisk
	InDB   *StatsInDB
}

type StatsInDB

type StatsInDB struct {
	Objects    map[string]int
	Kinds      map[NoteKind]int
	Tags       map[string]int
	Attributes map[string]int
	SizeKB     int64
}

func NewStatsInDBEmpty

func NewStatsInDBEmpty() *StatsInDB

type StatsOnDisk

type StatsOnDisk struct {
	// Number of files under .nt/objects
	ObjectFiles int
	// Number of commits in .nt/commit-graph
	Commits int
	// Number of blobs under .nt/objects
	Blobs int
	// Number of objects (file, note, etc.) present in commits
	Objects map[string]int
	// Number of objects listed in .nt/objects/index
	IndexObjects int
	// Total size of directory .nt/objects
	TotalSizeKB int64
}

func NewStatsOnDiskEmpty

func NewStatsOnDiskEmpty() *StatsOnDisk

type StorjRemote

type StorjRemote struct {
	// contains filtered or unexported fields
}

func NewStorjRemoteFromProject

func NewStorjRemoteFromProject(bucketName string, project *uplink.Project) (*StorjRemote, error)

NewStorjRemoteFromProject instantiates a client using a project (useful for testing purposes).

func NewStorjRemoteWithCredentials

func NewStorjRemoteWithCredentials(bucketName string, accessGrant string) (*StorjRemote, error)

NewStorjRemoteWithCredentials instantiates a client using the access grant.

func (*StorjRemote) DeleteObject

func (r *StorjRemote) DeleteObject(key string) error

func (*StorjRemote) GetObject

func (r *StorjRemote) GetObject(key string) ([]byte, error)

func (*StorjRemote) PutObject

func (r *StorjRemote) PutObject(key string, data []byte) error

type Study

type Study struct {
	OID       string    `yaml:"oid"`        // Not persisted in database but can be useful to deduplicate, etc.
	StartedAt time.Time `yaml:"started_at"` // Timestamp when the first card was revealed
	EndedAt   time.Time `yaml:"ended_at"`   // Timestamp when the last card was completed
	Reviews   []*Review `yaml:"reviews"`
}

func NewStudy

func NewStudy(flashcardOID string) *Study

NewStudy creates a new study.

func (*Study) Blobs

func (s *Study) Blobs() []*BlobRef

func (*Study) ForceState

func (s *Study) ForceState(state State)

func (*Study) Kind

func (s *Study) Kind() string

func (*Study) ModificationTime

func (s *Study) ModificationTime() time.Time

func (*Study) Read

func (s *Study) Read(r io.Reader) error

func (*Study) Refresh

func (s *Study) Refresh() (bool, error)

func (*Study) Relations

func (s *Study) Relations() []*Relation

func (*Study) Save

func (s *Study) Save() error

func (*Study) State

func (s *Study) State() State

func (Study) String

func (s Study) String() string

func (*Study) SubObjects

func (s *Study) SubObjects() []StatefulObject

func (*Study) UniqueOID

func (s *Study) UniqueOID() string

func (*Study) Write

func (s *Study) Write(w io.Writer) error

type VerboseLevel

type VerboseLevel int
const (
	VerboseOff VerboseLevel = iota
	VerboseInfo
	VerboseDebug
	VerboseTrace
)

type Violation

type Violation struct {
	// The name of the violation
	Name string
	// The human-readable description of the violation
	Message string
	// The relative path to the file containing the violation
	RelativePath string
	// The line number in the file containing the violation
	Line int
}

func CheckAttribute

func CheckAttribute(file *ParsedFile, args []string) ([]*Violation, error)

CheckAttribute implements the rule "check-attribute"

func MaxLinesBetweenNotes

func MaxLinesBetweenNotes(file *ParsedFile, args []string) ([]*Violation, error)

MaxLinesBetweenNotes implements the rule "min-lines-between-notes".

func MinLinesBetweenNotes

func MinLinesBetweenNotes(file *ParsedFile, args []string) ([]*Violation, error)

MinLinesBetweenNotes implements the rule "min-lines-between-notes".

func NoAmbiguousWikilink(file *ParsedFile, args []string) ([]*Violation, error)

NoAmbiguousWikilink implements the rule "no-ambiguous-wikilink"

func NoDanglingMedia

func NoDanglingMedia(file *ParsedFile, args []string) ([]*Violation, error)

NoDanglingMedia implements the rule "no-dangling-media".

func NoDeadWikilink(file *ParsedFile, args []string) ([]*Violation, error)

NoDeadWikilink implements the rule "no-dead-wikilink".

func NoDuplicateNoteTitle

func NoDuplicateNoteTitle(file *ParsedFile, args []string) ([]*Violation, error)

NoDuplicateNoteTitle implements the rule "no-duplicate-note-title".

func NoDuplicateSlug

func NoDuplicateSlug(file *ParsedFile, args []string) ([]*Violation, error)

NoDuplicateSlug implements the rule "no-duplicate-slug".

func NoExtensionWikilink(file *ParsedFile, args []string) ([]*Violation, error)

NoExtensionWikilink implements the rule "no-extension-wikilink".

func NoFreeNote

func NoFreeNote(file *ParsedFile, args []string) ([]*Violation, error)

NoFreeNote implements the rule "no-free-note".

func NoteTitleMatch

func NoteTitleMatch(file *ParsedFile, args []string) ([]*Violation, error)

NoteTitleMatch implements the rule "note-title-match".

func RequireQuoteTag

func RequireQuoteTag(file *ParsedFile, args []string) ([]*Violation, error)

RequireQuoteTag implements the rule "require-quote-tag"

type WIP

type WIP struct {
	// contains filtered or unexported fields
}
func (w *WIP) FindNoteByWikilink(wikilink string) *Note

func (*WIP) Flush

func (w *WIP) Flush()

func (*WIP) Register

func (w *WIP) Register(note *Note)
type Wikilink struct {
	Link string
	Text string
	Line int
}

Wikilink is an internal link. See https://en.wikipedia.org/wiki/Help:Link

func NewWikilink(link string) (*Wikilink, error)

NewWikilink instantiates a new wikilink.

func ParseWikilinks(text string) []*Wikilink

ParseWikilinks extracts wikilinks from a text.

func (*Wikilink) Anchored

func (w *Wikilink) Anchored() bool

Anchored indicates if a link points to a section in the current file. (ex: [[#A section below]])

func (*Wikilink) ContainsExtension

func (w *Wikilink) ContainsExtension() bool

ContainsExtenstion tests if the extension is specified in the link.

func (*Wikilink) External

func (w *Wikilink) External() bool

External returns if the link points to a different file.

func (*Wikilink) Internal

func (w *Wikilink) Internal() bool

Internal returns if the link points to the current file.

func (*Wikilink) Path

func (w *Wikilink) Path() string

Path returns the link without the optional fragment.

func (*Wikilink) Piped

func (w *Wikilink) Piped() bool

Piped indicates if a text is present to describe the link. (ex: [[link|A text]])

func (*Wikilink) Section

func (w *Wikilink) Section() string

Section returns the fragment part of the link.

func (Wikilink) String

func (w Wikilink) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL