snippets

package module
v0.0.0-...-2007626 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2025 License: MIT Imports: 10 Imported by: 0

README

snippets

Build Status Go Reference

snippets is a Go package for creating, searching and managing text snippets in a text file. Useful for managing both human and machine readable/writeable config files.

An example of a text file that contains snippets managed by this package could look like this:

Hello World!
# edgeguard:BEGIN kind=site managed=true name=0xffs.xyz
# content of site
# edgeguard:END
This is normal content.
# edgeguard:BEGIN kind=site name=prologic.dev
# content of another site
# edgeguard:END
Something at the end.

See the Package Docs for more details.

Quick Start

import "go.mills.io/snippets"

Example

Removing snippets
package main

import (
    "fmt"

    "go.mills.io/snippets"
)

func main() {
	s := snippets.NewSnippets()
	s.Open(DefaultCaddyFile)
	defer s.Close()

	if err := s.Remove(fmt.Sprintf(`kind == "site*" && name == "%s"`, site)); err != nil {
		return fmt.Errorf("error removing site: %v", err)
	}

	data, err := s.Bytes()
	if err != nil {
		return fmt.Errorf("error getting Caddyfile bytes: %v", err)
	}

	if err := os.WriteFile(DefaultCaddyFile, data, 0644); err != nil {
		return fmt.Errorf("error writing Caddyfile: %v", err)
	}
}
Finding snippets
package main

import (
    "fmt"

    "go.mills.io/snippets"
)

func main() {
	s := snippets.NewSnippets()
	s.Open(DefaultCaddyFile)
	defer s.Close()

	xs, err := s.Find(`kind == "site"`)
	if err != nil {
		return fmt.Errorf("error finding sites: %v", err)
	}

	for _, x := range xs {
		fmt.Println(x.Metadata()["name"])
	}
}

License

snippets is licensed under the terms of the MIT License.

Documentation

Overview

Package snippets manages snippets and file content.

Index

Constants

View Source
const (
	// DefaultStartOfComment is the default start of comment for the Snippets instance
	DefaultStartOfComment = "#"

	// DefaultPrefix is the default prefix for the Snippets instance
	DefaultPrefix = "edgeguard"

	// DefaultBeginMarker is the default begin marker for the Snippets instance
	DefaultBeginMarker = "BEGIN"

	// DefaultEndMarker is the default end marker for the Snippets instance
	DefaultEndMarker = "END"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CapturedSnippet

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

CapturedSnippet represents a captured snippet.

func (*CapturedSnippet) Bytes

func (cs *CapturedSnippet) Bytes() []byte

Bytes returns the byte representation of the CapturedSnippet. It reconstructs the original format of the snippet by writing the start and end line numbers, followed by the key-value pairs in the metadata, and the content of the snippet. The format is "startLine-endLine: key1=value1 key2=value2 ...\nline1\nline2...\n# edgeguard:END\n". The returned byte slice is the result of calling String() on the CapturedSnippet.

func (*CapturedSnippet) Content

func (cs *CapturedSnippet) Content() *Lines

Content returns the content of the CapturedSnippet as a slice of strings. The content is the raw content of the snippet, without any metadata or start/end line numbers.

func (*CapturedSnippet) End

func (cs *CapturedSnippet) End(endLine int)

End updates the end line number of the snippet.

func (*CapturedSnippet) Metadata

func (cs *CapturedSnippet) Metadata() Metadata

Metadata returns the metadata associated with the CapturedSnippet.

func (*CapturedSnippet) String

func (cs *CapturedSnippet) String() string

String returns a string representation of the captured snippet. The string contains the start and end line numbers, followed by the key-value pairs in the metadata. The format is "startLine-endLine: key1=value1 key2=value2 ...".

type Lines

type Lines []string

Lines is a slice of strings representing lines of text

func (*Lines) Append

func (l *Lines) Append(line string)

Append adds a new line to the end of the Lines.

func (*Lines) Bytes

func (l *Lines) Bytes() []byte

Bytes returns the Lines as a byte slice. The byte slice is the result of calling String() on the Lines and casting the result to a byte slice.

func (*Lines) Clear

func (l *Lines) Clear()

Clear removes all elements from the Lines slice, leaving it empty.

func (*Lines) Get

func (l *Lines) Get(index int) string

Get returns the line at the specified index from the Lines slice. If the index is out of bounds, this will result in a runtime panic.

func (*Lines) Insert

func (l *Lines) Insert(line string, position int)

Insert adds a new line at the specified position in the Lines slice. The new line is added before the line at the specified position. If the position is invalid (out of bounds), the function does nothing.

func (*Lines) Len

func (l *Lines) Len() int

Len returns the length of the Lines slice.

func (*Lines) Remove

func (l *Lines) Remove(start, end int)

Remove removes lines from the Lines slice between start and end, inclusive. If the start or end index is invalid, the function does nothing.

func (*Lines) String

func (l *Lines) String() string

String returns the Lines as a single string with each line separated by a newline character.

type Metadata

type Metadata map[string]string

Metadata is a map of key-value pairs

func (Metadata) String

func (m Metadata) String() string

type Option

type Option func(*Snippets)

Option is a function that configures a Snippets instance

func WithBeginMarker

func WithBeginMarker(beginMarker string) Option

WithBeginMarker sets the begin marker for the Snippets instance

func WithEndMarker

func WithEndMarker(endMarker string) Option

WithEndMarker sets the end marker for the Snippets instance

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix sets the prefix for the Snippets instance

func WithStartOfComment

func WithStartOfComment(startOfComment string) Option

WithStartOfComment sets the start of comment for the Snippets instance

type OriginalLine

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

OriginalLine represents an original line.

func (*OriginalLine) Bytes

func (o *OriginalLine) Bytes() []byte

Bytes returns the original line as a byte slice.

func (*OriginalLine) Content

func (o *OriginalLine) Content() *Lines

Content returns the content of the original line. As an original line is a single line, its content is the same as the line itself.

func (*OriginalLine) End

func (o *OriginalLine) End(_ int)

End is a no-op for OriginalLine, as it does not support modifying the line.

func (*OriginalLine) GetStartLine

func (o *OriginalLine) GetStartLine() int

GetStartLine returns the line number of the original line. As an original line is a single line, its start and end line numbers are the same.

func (*OriginalLine) Metadata

func (o *OriginalLine) Metadata() Metadata

Metadata returns the metadata associated with this snippet. For OriginalLine, this will always be nil, as original lines do not support metadata.

func (*OriginalLine) String

func (o *OriginalLine) String() string

String returns the original line as a string.

type Snippet

type Snippet interface {
	String() string
	Bytes() []byte
	End(int)
	Metadata() Metadata
	Content() *Lines
}

Snippet represents a captured snippet.

type Snippets

type Snippets struct {
	StartOfComment string
	Prefix         string
	BeginMarker    string
	EndMarker      string
	// contains filtered or unexported fields
}

Snippets represents a collection of snippets.

func NewSnippets

func NewSnippets(opts ...Option) *Snippets

NewSnippets creates a new instance of Snippets with default values for StartOfComment, Prefix, BeginMarker, and EndMarker. It accepts a variadic number of Option functions that can be used to modify the defaults. The options are applied in the order they are provided.

func (*Snippets) Append

func (s *Snippets) Append(snippet Snippet)

Append adds a snippet to the end of the file, adjusting its start and end lines to match the current file state. The snippet is added to the end of the Snippets list and the modified flag is set to true.

func (*Snippets) Bytes

func (s *Snippets) Bytes() ([]byte, error)

Bytes returns the byte representation of the current state of the file content, including any modifications made to snippets. It reconstructs the file content by merging the original lines and the updated snippets, maintaining the order of the original file. If successful, it returns the modified content as a byte slice. An error is returned only if there is an issue with the underlying operations.

func (*Snippets) Close

func (s *Snippets) Close()

Close releases any resources allocated by the Snippets instance, such as the underlying file or in-memory snippets. It should be called when the instance is no longer needed to ensure proper resource cleanup.

func (*Snippets) Find

func (s *Snippets) Find(input string) ([]Snippet, error)

Find returns a list of snippets that match the given expression.

The expression is evaluated against each snippet's metadata and content. If the expression evaluates to true, the snippet is added to the result list.

The expression is evaluated using the expr package, which supports a simple expression language. The language is similar to Go's conditional expression syntax, but it is not as powerful. For example, the expression "name == 'foo'" will match snippets with a "name" metadata key equal to "foo".

If the expression is invalid, an error is returned.

func (*Snippets) Insert

func (s *Snippets) Insert(snippet Snippet, position int) error

Insert adds a snippet at a specified position within the original content. It adjusts the start and end lines of the snippet based on the current file state. Returns an error if the position is invalid (out of bounds).

func (*Snippets) Open

func (s *Snippets) Open(filePath string) error

Open reads the file and parses it into snippets.

func (*Snippets) Remove

func (s *Snippets) Remove(input string) error

Remove removes snippets from the Snippets instance based on an expression.

The expression is evaluated against each snippet's metadata and content. If the expression evaluates to true, the snippet is removed from the Snippets list.

The expression is evaluated using the expr package, which supports a simple expression language. The language is similar to Go's conditional expression syntax, but it is not as powerful. For example, the expression "name == 'foo'" will remove snippets with a "name" metadata key equal to "foo".

If the expression is invalid, an error is returned.

Jump to

Keyboard shortcuts

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