ortfodb

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2024 License: MIT Imports: 70 Imported by: 5

README

ortfo/db

A readable, easy and enjoyable way to manage portfolio databases using directories and text files.

Installation

Pre-compiled binaries are available in the Releases page.

See the documentation on installation for more information

Usage

See documentation

Manage your portfolio's database — See https://github.com/ortfo/db for more information.

Usage:
  ortfodb [command]

Examples:
  $ ortfodb --config .ortfodb.yaml build database.json
  $ ortfodb add my-project

Available Commands:
  add         Add a new project to your portfolio
  build       Build the database
  completion  Generate the autocompletion script for the specified shell
  exporters   Commands related to ortfo/db exporters
  help        Help about any command
  replicate   Replicate a database directory from a built database file.
  schemas     Output JSON schemas for ortfodb's various resources

Flags:
  -c, --config string   config file path (default "ortfodb.yaml")
  -h, --help            help for ortfodb
      --scattered       Operate in scattered mode. In scattered mode, the description.md files are searched inside `.ortfo' folders in every folder of the database directory, instead of directly in the database directory's folders. See https://github.com/ortfo/
  -v, --version         version for ortfodb

Use "ortfodb [command] --help" for more information about a command.

Documentation

Overview

Package ortfodb exposes the various functions used by the ortfodb portfolio database creation command-line tool. It is notably used by ortfomk to share some common data between the two complementing programs. See https://ewen.works/ortfodb for more information.

Index

Constants

View Source
const (
	PatternLanguageMarker         string = `^::\s+(.+)$`
	PatternAbbreviationDefinition string = `^\s*\*\[([^\]]+)\]:\s+(.+)$`
	RuneLoop                      rune   = '~'
	RuneAutoplay                  rune   = '>'
	RuneHideControls              rune   = '='
)
View Source
const DefaultConfigurationFilename = "ortfodb.yaml"
View Source
const DefaultScatteredModeFolder = ".ortfo"
View Source
const Version = "1.5.0"

Variables

View Source
var AvailableJSONSchemas = []string{"configuration", "database", "tags", "technologies", "exporter"}
View Source
var BuiltinNativeExporters = []Exporter{
	&SqlExporter{},
	&LocalizeExporter{},
	&CustomExporter{},
}
View Source
var LogFilePath string
View Source
var PrependDateToLogs = false
View Source
var ThumbnailableContentTypes = []string{"image/*", "video/*", "application/pdf"}

Functions

func AcquireBuildLock

func AcquireBuildLock(outputFilename string) error

AcquireBuildLock ensures that only one process touches the output database file at the same time. An error is returned if the lock could not be acquired

func AnalyzeAudio

func AnalyzeAudio(file *os.File) uint

AnalyzeAudio takes in an os.File and returns the duration of the audio file in seconds. If any error occurs the duration will be 0.

func BuildIsFinished added in v1.5.0

func BuildIsFinished() bool

func BuildLockFilepath

func BuildLockFilepath(outputFilename string) string

BuildLockFilepath returns the path to the lock file for the given output database file.

func ConfigurationJSONSchema added in v0.1.3

func ConfigurationJSONSchema() *jsonschema.Schema

func DatabaseJSONSchema added in v0.1.3

func DatabaseJSONSchema() *jsonschema.Schema

func DetectStartDate

func DetectStartDate(workingDirectory string) (time.Time, error)

func DisplayError added in v1.4.1

func DisplayError(msg string, err error, fmtArgs ...interface{})

func DisplayValidationErrors

func DisplayValidationErrors(errors []gojsonschema.ResultError, filename string, rootPath ...string)

DisplayValidationErrors takes in a slice of json schema validation errors and displays them nicely to in the terminal.

func DisplayWarning added in v1.4.1

func DisplayWarning(msg string, err error, fmtArgs ...interface{})

func ExporterLogCustom added in v1.1.0

func ExporterLogCustom(exporter Exporter, verb string, color string, message string, fmtArgs ...interface{})

func ExporterLogCustomNoFormatting added in v1.1.0

func ExporterLogCustomNoFormatting(exporter Exporter, verb string, color string, message string)

func ExporterManifestJSONSchema added in v1.2.0

func ExporterManifestJSONSchema() *jsonschema.Schema

func FirstGitCommitDate

func FirstGitCommitDate(workingDirectory string) (time.Time, error)

func GatherPages

func GatherPages(inside string) (paths []string, err error)

GatherPages gathers all the .md files in inside/**/*.md and returns these paths

func GetExporterOptions added in v1.2.0

func GetExporterOptions[ConcreteOptionsType any](e Exporter, opts ExporterOptions) ConcreteOptionsType

GetExporterOptions returns the options for the given exporter. Use it to get your options in a nice struct. The struct will be of the same type as the one returned by e.OptionsType(). Example:

type MyExporterOptions struct {
		// Some option
		Option string `yaml:"option"`
}

func (e *MyExporter) OptionsType() any {
 	return MyExporterOptions{}
 }

func (e *MyExporter) After(ctx *ortfodb.RunContext, opts *ortfodb.ExporterOptions, db *ortfodb.Database) error {
	 options := GetExporterOptions[MyExporterOptions](e, opts)
	 // Now you can use options as a MyExporterOptions struct
	}

func HandleAltMediaEmbedSyntax

func HandleAltMediaEmbedSyntax(markdownRaw string) string

HandleAltMediaEmbedSyntax handles the >[...](...) syntax by replacing it in htmlRaw with ![...](...).

func LastGitCommitDate added in v0.3.0

func LastGitCommitDate(workingDirectory string) (time.Time, error)

func LoadConfiguration

func LoadConfiguration(filename string, loadInto *Configuration) error

LoadConfiguration loads the given configuration YAML file and puts it contents into loadInto.

func LogCustom

func LogCustom(verb string, color string, message string, fmtArgs ...interface{})

func LogCustomNoColor added in v1.4.1

func LogCustomNoColor(verb string, color string, message string, fmtArgs ...interface{})

LogCustomNoColor logs a message without applying colorstring syntax to message.

func LogCustomNoFormatting added in v1.1.0

func LogCustomNoFormatting(verb string, color string, message string)

func LogDebug added in v1.4.1

func LogDebug(message string, fmtArgs ...interface{})

LogDebug logs debug information.

func LogDebugNoColor added in v1.4.1

func LogDebugNoColor(message string, fmtArgs ...interface{})

LogDebugNoColor logs debug information without applying colorstring syntax to message.

func LogError added in v1.4.1

func LogError(message string, fmtArgs ...interface{})

LogError logs non-fatal errors.

func LogInfo added in v1.4.1

func LogInfo(message string, fmtArgs ...interface{})

LogInfo logs infos.

func LogWarning added in v1.4.1

func LogWarning(message string, fmtArgs ...interface{})

LogWarning logs warnings.

func MarkdownToHTML

func MarkdownToHTML(markdownRaw string) string

MarkdownToHTML converts markdown markdownRaw into an HTML string.

func ParseDescription

func ParseDescription[Metadata interface{}](ctx *RunContext, markdownRaw string) (metadata Metadata, blocks map[string][]ContentBlock, title map[string]HTMLString, footnotes map[string]Footnotes, abbreviations map[string]Abbreviations)

ParseDescription parses the markdown string from a description.md file and returns a ParsedDescription.

func ParseYAMLHeader

func ParseYAMLHeader[Metadata interface{}](descriptionRaw string) (Metadata, string)

ParseYAMLHeader parses the YAML header of a description markdown file and returns the rest of the content (all except the YAML header).

func Print added in v1.4.1

func Print(a ...interface{})

Print is like fmt.Print but automatically strips ANSI color codes if colors are disabled

func Printf added in v1.4.1

func Printf(format string, a ...interface{})

Printf is like fmt.Printf but automatically strips ANSI color codes if colors are disabled

func Println added in v1.4.1

func Println(a ...interface{})

Println is like fmt.Println but automatically strips ANSI color codes if colors are disabled

func ReadDescriptionFile

func ReadDescriptionFile(directory string) (string, error)

ReadDescriptionFile reads the description.md file in directory. Returns an empty string if the file is a directory or does not exist.

func ReleaseBuildLock added in v1.5.0

func ReleaseBuildLock(outputFilename string) error

func ResolveBlockID

func ResolveBlockID(blocks []ContentBlock, language string, blockRef string) (string, error)

ResolveBlockID returns the ID of a block, given its ref (user-facing content block references comprising of a content block type shorthand and an index). This index is 1-based.

func ShowingColors added in v1.4.1

func ShowingColors() bool

ShowingColors returns true if colors (ANSI escape codes) should be printed. Environment variables can control this: NO_COLOR=1 disables colors, and FORCE_COLOR=1 forces colors. Otherwise, heuristics (such as whether the output is an interactive terminal) are used.

func SplitOnLanguageMarkers

func SplitOnLanguageMarkers(markdownRaw string) (string, map[string]string)

SplitOnLanguageMarkers returns two values:

  1. the text before any language markers
  2. a map with language codes as keys and the content as values.

func TagsRepositoryJSONSchema added in v0.1.3

func TagsRepositoryJSONSchema() *jsonschema.Schema

func TechnologiesRepositoryJSONSchema added in v0.1.3

func TechnologiesRepositoryJSONSchema() *jsonschema.Schema

func ValidateAsJSONSchema added in v1.1.0

func ValidateAsJSONSchema(typ any, yaml bool, values any) []gojsonschema.ResultError

func ValidateConfiguration

func ValidateConfiguration(configFilepath string) (valid bool, validationErrors []gojsonschema.ResultError, err error)

ValidateConfiguration uses the JSON configuration schema ConfigurationJSONSchema to validate the configuration file at configFilepath. The third return value (of type error) is not nil when the validation process itself fails, not if the validation ran succesfully with a result of "not validated".

func ValidateExporterOptions added in v1.1.0

func ValidateExporterOptions(exporter Exporter, opts ExporterOptions) error

Types

type Abbreviations

type Abbreviations map[string]string

Abbreviations represents the abbreviations declared in a description.md file.

type AnalyzedBlogPage

type AnalyzedBlogPage struct {
	ID       string                      `json:"id"`
	BuiltAt  time.Time                   `json:"built_at"`
	Hash     string                      `json:"hash"`
	Metadata BlogMetadata                `json:"metadata"`
	Content  map[string]LocalizedContent `json:"content"`
	Partial  bool                        `json:"partial"`
}

type AnalyzedWork

type AnalyzedWork struct {
	ID              string             `json:"id"`
	BuiltAt         string             `json:"builtAt"`
	DescriptionHash string             `json:"descriptionHash"`
	Metadata        WorkMetadata       `json:"metadata"`
	Content         LocalizableContent `json:"content"`
	Partial         bool               `json:"Partial"`
}

AnalyzedWork represents a complete work, with analyzed mediae.

func SortWorksByDate

func SortWorksByDate(works []AnalyzedWork) []AnalyzedWork

func (AnalyzedWork) Colors

func (w AnalyzedWork) Colors(language string) ColorPalette

func (AnalyzedWork) FirstParagraph

func (work AnalyzedWork) FirstParagraph(lang string) (found bool, paragraph ContentBlock)

FirstParagraph returns the first paragraph content block of the given work in the given language

func (AnalyzedWork) ThumbnailBlock

func (w AnalyzedWork) ThumbnailBlock(language string) Media

func (AnalyzedWork) ThumbnailPath

func (w AnalyzedWork) ThumbnailPath(language string, size int) FilePathInsideMediaRoot

type Blog

type Blog map[string]AnalyzedBlogPage

func BuildBlog

func BuildBlog(inside string) (blog Blog, err error)

type BlogMetadata

type BlogMetadata struct {
	Aliases            []string                      `json:"aliases"`
	Projects           []string                      `json:"projects"`
	Date               time.Time                     `json:"date"`
	Tags               []string                      `json:"tags"`
	Thumbnail          FilePathInsidePortfolioFolder `json:"thumbnail"`
	Private            bool                          `json:"private"`
	AdditionalMetadata map[string]interface{}        `mapstructure:",remain" json:"additional_metadata"`
}

type BuildMetadata

type BuildMetadata struct {
	PreviousBuildDate time.Time
}

type BuildPhase

type BuildPhase string
const (
	PhaseThumbnails    BuildPhase = "Thumbnailing"
	PhaseMediaAnalysis BuildPhase = "Analyzing"
	PhaseBuilding      BuildPhase = "Building"
	PhaseBuilt         BuildPhase = "Built"
	PhaseUnchanged     BuildPhase = "Reusing"
)

type BuildSteps

type BuildSteps struct {
	ExtractColors  ExtractColorsConfiguration  `yaml:"extract colors"`
	MakeGifs       MakeGIFsConfiguration       `yaml:"make gifs"`
	MakeThumbnails MakeThumbnailsConfiguration `yaml:"make thumbnails"`
}

type ColorPalette

type ColorPalette struct {
	Primary   string `json:"primary"`
	Secondary string `json:"secondary"`
	Tertiary  string `json:"tertiary"`
}

ColorPalette reprensents the object in a Work's metadata.colors.

func ExtractColors

func ExtractColors(filename string) (ColorPalette, error)

ExtractColors extracts the 3 most proeminent colors from the given image-decodable file. See https://pkg.go.dev/image#Decode for what formats are decodable.

func (ColorPalette) Empty

func (colors ColorPalette) Empty() bool

func (ColorPalette) MergeWith added in v1.5.0

func (colors ColorPalette) MergeWith(other ColorPalette) ColorPalette

MergeWith merges the colors of the current palette with other: if a color is missing in the current palette, it is replaced by the one in other.

type Configuration

type Configuration struct {
	// Signals whether the configuration was instanciated by DefaultConfiguration.
	IsDefault bool `yaml:"-"`

	ExtractColors         ExtractColorsConfiguration  `yaml:"extract colors,omitempty"`
	MakeGifs              MakeGIFsConfiguration       `yaml:"make gifs,omitempty"`
	MakeThumbnails        MakeThumbnailsConfiguration `yaml:"make thumbnails,omitempty"`
	BuildMetadataFilepath string                      `yaml:"build metadata file,omitempty"`
	Media                 MediaConfiguration          `yaml:"media,omitempty"`
	ScatteredModeFolder   string                      `yaml:"scattered mode folder"`
	Tags                  TagsConfiguration           `yaml:"tags,omitempty"`
	Technologies          TechnologiesConfiguration   `yaml:"technologies,omitempty"`

	// Path to the directory containing all projects. Must be absolute.
	ProjectsDirectory string `yaml:"projects at"`

	// Exporter-specific configuration. Maps exporter names to their configuration.
	Exporters map[string]map[string]interface{} `yaml:"exporters,omitempty"`
	// contains filtered or unexported fields
}

Configuration represents what the ortfodb.yaml configuration file describes.

func DefaultConfiguration

func DefaultConfiguration() Configuration

func NewConfiguration

func NewConfiguration(filename string) (Configuration, error)

NewConfiguration loads a YAML configuration file. This function also validates the configuration and prints any error to the user. Use LoadConfiguration for a lower-level function that just loads the YAML file into a struct.

type ContentBlock

type ContentBlock struct {
	ID     string           `json:"id"`
	Type   ContentBlockType `json:"type"`
	Anchor string           `json:"anchor"`
	Index  int              `json:"index"`
	Media
	Paragraph
	Link
}

func ContentBlockByID

func ContentBlockByID(id string, blocks []ContentBlock) (block ContentBlock, ok bool)
func (b ContentBlock) AsLink() Link

func (ContentBlock) AsMedia

func (b ContentBlock) AsMedia() Media

func (ContentBlock) AsParagraph

func (b ContentBlock) AsParagraph() Paragraph

type ContentBlockType

type ContentBlockType string

ContentBlockType is one of "paragraph", "media" or "link"

func (t ContentBlockType) IsLink() bool

func (ContentBlockType) IsMedia

func (t ContentBlockType) IsMedia() bool

func (ContentBlockType) IsParagraph

func (t ContentBlockType) IsParagraph() bool

func (ContentBlockType) String

func (t ContentBlockType) String() string

type CustomExporter added in v1.1.0

type CustomExporter struct {
	Manifest ExporterManifest
	// contains filtered or unexported fields
}

func DownloadExporter added in v1.4.0

func DownloadExporter(name string, url string, config map[string]any) (*CustomExporter, error)

DownloadExporter loads an exporter from a URL.

func LoadExporter added in v1.4.0

func LoadExporter(name string, manifestRaw []byte, config map[string]any) (*CustomExporter, error)

LoadExporter loads an exporter from a manifest YAML file's contents.

func (*CustomExporter) After added in v1.1.0

func (e *CustomExporter) After(ctx *RunContext, opts ExporterOptions, db *Database) error

func (*CustomExporter) Before added in v1.1.0

func (e *CustomExporter) Before(ctx *RunContext, opts ExporterOptions) error

func (*CustomExporter) Description added in v1.2.0

func (e *CustomExporter) Description() string

func (*CustomExporter) Export added in v1.1.0

func (e *CustomExporter) Export(ctx *RunContext, opts ExporterOptions, work *AnalyzedWork) error

func (*CustomExporter) Name added in v1.1.0

func (e *CustomExporter) Name() string

func (*CustomExporter) OptionsType added in v1.1.0

func (e *CustomExporter) OptionsType() any

func (*CustomExporter) VerifyRequiredPrograms added in v1.2.0

func (e *CustomExporter) VerifyRequiredPrograms() error

type Database

type Database map[string]AnalyzedWork

func LoadDatabase added in v1.0.0

func LoadDatabase(at string, skipValidation bool) (database Database, err error)

func (Database) AsSlice

func (w Database) AsSlice() []AnalyzedWork

func (Database) GroupWorksByYear

func (w Database) GroupWorksByYear() [][]AnalyzedWork

GroupWorksByYear groups works by year, with most recent years first.

func (Database) Languages

func (w Database) Languages() []string

func (Database) Meta

func (w Database) Meta() DatabaseMeta

Meta gets the database meta information

func (Database) Partial

func (w Database) Partial() bool

Partial returns true if the database results from a partial build.

func (Database) Works

func (w Database) Works() map[string]AnalyzedWork

Works gets the mapping of all works

func (Database) WorksByDate

func (w Database) WorksByDate() []AnalyzedWork

WorksByDate gets all the works sorted by date, with most recent works first.

func (Database) WorksSlice

func (w Database) WorksSlice() []AnalyzedWork

WorksSlice gets the slice of all works in the database

type DatabaseMeta

type DatabaseMeta struct {
	// Partial is true if the database was not fully built.
	Partial bool
}

type Exporter added in v1.1.0

type Exporter interface {
	Name() string
	Description() string
	Before(ctx *RunContext, opts ExporterOptions) error
	Export(ctx *RunContext, opts ExporterOptions, work *AnalyzedWork) error
	After(ctx *RunContext, opts ExporterOptions, built *Database) error
	OptionsType() any
}

func BuiltinExporters added in v1.1.0

func BuiltinExporters() []Exporter

type ExporterCommand added in v1.1.0

type ExporterCommand struct {
	// Run a command in a shell
	Run string `yaml:"run,omitempty"`
	// Log a message. The first argument is the verb, the second is the color, the third is the message.
	Log []string `yaml:"log,omitempty"`
}

type ExporterManifest added in v1.1.0

type ExporterManifest struct {
	// The name of the exporter
	Name string `yaml:"name"`

	// Some documentation about the exporter
	Description string `yaml:"description"`

	// Commands to run before the build starts. Go text template that receives .Data
	Before []ExporterCommand `yaml:"before,omitempty"`

	// Commands to run after the build finishes. Go text template that receives .Data and .Database, the built database.
	After []ExporterCommand `yaml:"after,omitempty"`

	// Commands to run during the build, for each work. Go text template that receives .Data and .Work, the current work.
	Work []ExporterCommand `yaml:"work,omitempty"`

	// Initial data
	Data map[string]any `yaml:"data,omitempty"`

	// If true, will show every command that is run
	Verbose bool `yaml:"verbose,omitempty"`

	// List of programs that are required to be available in the PATH for the exporter to run.
	Requires []string `yaml:"requires,omitempty"`
}

type ExporterOptions added in v1.1.0

type ExporterOptions map[string]interface{}

type ExtractColorsConfiguration

type ExtractColorsConfiguration struct {
	Enabled      bool
	Extract      []string
	DefaultFiles []string `yaml:"default files"`
}

type FilePathInsideMediaRoot

type FilePathInsideMediaRoot string

FilePathInsideMediaRoot is a path relative to the media root directory.

func (FilePathInsideMediaRoot) Absolute

func (p FilePathInsideMediaRoot) Absolute(ctx *RunContext) string

func (FilePathInsideMediaRoot) URL

func (f FilePathInsideMediaRoot) URL(origin string) string

type FilePathInsidePortfolioFolder

type FilePathInsidePortfolioFolder string

FilePathInsidePortfolioFolder is a path relative to the scattered mode folder inside of a work directory. (example ../image.jpeg for an image in the work's directory, just outside of the portfolio-specific folder)

func (FilePathInsidePortfolioFolder) Absolute

func (f FilePathInsidePortfolioFolder) Absolute(ctx *RunContext, workID string) string

func (FilePathInsidePortfolioFolder) RelativeToMediaRoot

func (p FilePathInsidePortfolioFolder) RelativeToMediaRoot(ctx *RunContext, workID string) FilePathInsideMediaRoot

RelativeToMediaRoot returns the path to the media file relative to the media root.

input:   ./[work id]/[scattered mode folder]/[file path]
                                             -----------
                                             part of the path
output:  ./[work id]/[scattered mode folder]/[file path]
         -----------------------------------------------
         part of the path

type Flags

type Flags struct {
	Scattered        bool
	Silent           bool
	Minified         bool
	Config           string
	NoCache          bool
	WorkersCount     int
	ProgressInfoFile string
	ExportersToUse   []string
}

type Footnotes

type Footnotes map[string]HTMLString

Footnotes represents the footnote declarations in a description.md file.

type HTMLString

type HTMLString string

func (HTMLString) Markdown

func (html HTMLString) Markdown() string

func (HTMLString) String

func (s HTMLString) String() string

type ImageDimensions

type ImageDimensions struct {
	Width       int     `json:"width"`       // Width in pixels
	Height      int     `json:"height"`      // Height in pixels
	AspectRatio float32 `json:"aspectRatio"` // width / height
}

ImageDimensions represents metadata about a media as it's extracted from its file.

func AnalyzePDF

func AnalyzePDF(filename string) (dimensions ImageDimensions, pagesCount uint, err error)

AnalyzePDF returns an ImageDimensions struct for the first page of the PDF file at filename. It also returns the number of pages.

func AnalyzeVideo

func AnalyzeVideo(filename string) (dimensions ImageDimensions, duration uint, hasSound bool, err error)

AnalyzeVideo returns an ImageDimensions struct with the video's height, width and aspect ratio and a duration in seconds.

func GetImageDimensions

func GetImageDimensions(file *os.File) (ImageDimensions, error)

GetImageDimensions returns an ImageDimensions object, given a pointer to a file.

func GetSVGDimensions

func GetSVGDimensions(file *os.File) (ImageDimensions, error)

GetSVGDimensions returns an ImageDimensions object, given a pointer to a SVG file. If neither viewBox nor width & height attributes are set, the resulting dimensions will be 0x0.

type Layout

type Layout [][]LayoutCell

Layout is a 2D array of content block IDs

func ResolveLayout

func ResolveLayout(metadata WorkMetadata, language string, blocks []ContentBlock) (Layout, error)

ResolveLayout returns a layout, given the parsed description.

func (Layout) BlockIDs

func (layout Layout) BlockIDs() (blockIDs []string)

Return a unique list of all the block IDs in the layout.

func (Layout) Normalize

func (layout Layout) Normalize() (normalized Layout)

Normalize returns a normalized layout where every row has the same number of cells.

type LayoutCell

type LayoutCell string

LayoutCell is a single cell in the layout. It corresponds to the content block's ID.

type Link struct {
	Text  HTMLString `json:"text"`
	Title string     `json:"title"`
	URL   string     `json:"url"`
}

Link represents an (isolated) link declaration in a description.md file.

type LocalizableContent

type LocalizableContent map[string]LocalizedContent

func (LocalizableContent) Localize

func (c LocalizableContent) Localize(lang string) LocalizedContent

type LocalizeExporter added in v1.2.0

type LocalizeExporter struct {
}

func (*LocalizeExporter) After added in v1.2.0

func (e *LocalizeExporter) After(ctx *RunContext, opts ExporterOptions, db *Database) error

func (*LocalizeExporter) Before added in v1.2.0

func (e *LocalizeExporter) Before(ctx *RunContext, opts ExporterOptions) error

func (*LocalizeExporter) Description added in v1.2.0

func (e *LocalizeExporter) Description() string

func (*LocalizeExporter) Export added in v1.2.0

func (e *LocalizeExporter) Export(ctx *RunContext, opts ExporterOptions, work *AnalyzedWork) error

func (*LocalizeExporter) Name added in v1.2.0

func (e *LocalizeExporter) Name() string

func (*LocalizeExporter) OptionsType added in v1.2.0

func (e *LocalizeExporter) OptionsType() any

type LocalizeExporterOptions added in v1.2.0

type LocalizeExporterOptions struct {
	FilenameTemplate string `yaml:"filename_template"`
}

type LocalizedContent

type LocalizedContent struct {
	Layout    Layout         `json:"layout"`
	Blocks    []ContentBlock `json:"blocks"`
	Title     HTMLString     `json:"title"`
	Footnotes Footnotes      `json:"footnotes"`
}

type MakeGIFsConfiguration

type MakeGIFsConfiguration struct {
	Enabled          bool
	FileNameTemplate string `yaml:"file name template"`
}

type MakeThumbnailsConfiguration

type MakeThumbnailsConfiguration struct {
	Enabled          bool
	Sizes            []int
	InputFile        string `yaml:"input file"`
	FileNameTemplate string `yaml:"file name template"`
}

type Media

type Media struct {
	Alt               string                        `json:"alt"`
	Caption           string                        `json:"caption"`
	RelativeSource    FilePathInsidePortfolioFolder `json:"relativeSource"`
	DistSource        FilePathInsideMediaRoot       `json:"distSource"`
	ContentType       string                        `json:"contentType"`
	Size              int                           `json:"size"` // in bytes
	Dimensions        ImageDimensions               `json:"dimensions"`
	Online            bool                          `json:"online"`
	Duration          float64                       `json:"duration"` // in seconds
	HasSound          bool                          `json:"hasSound"`
	Colors            ColorPalette                  `json:"colors"`
	Thumbnails        ThumbnailsMap                 `json:"thumbnails"`
	ThumbnailsBuiltAt string                        `json:"thumbnailsBuiltAt"`
	Attributes        MediaAttributes               `json:"attributes"`
	Analyzed          bool                          `json:"analyzed"` // whether the media has been analyzed
}

Media represents a media object inserted in the work object's media array.

func FindMedia

func FindMedia(works Database, mediaEmbed Media, workID string) (found bool, media Media, builtAt time.Time)

func (Media) Thumbnailable

func (m Media) Thumbnailable() bool

type MediaAttributes

type MediaAttributes struct {
	Loop        bool `json:"loop"`        // Controlled with attribute character ~ (adds)
	Autoplay    bool `json:"autoplay"`    // Controlled with attribute character > (adds)
	Muted       bool `json:"muted"`       // Controlled with attribute character > (adds)
	Playsinline bool `json:"playsinline"` // Controlled with attribute character = (adds)
	Controls    bool `json:"controls"`    // Controlled with attribute character = (removes)
}

MediaAttributes stores which HTML attributes should be added to the media.

func ExtractAttributesFromAlt

func ExtractAttributesFromAlt(alt string) (string, MediaAttributes)

ExtractAttributesFromAlt extracts sigils from the end of the alt atetribute, returns the alt without them as well as the parse result.

type MediaConfiguration added in v1.5.0

type MediaConfiguration struct {
	// Path to the media directory.
	At string
}

type Paragraph

type Paragraph struct {
	Content HTMLString `json:"content"` // html
}

Paragraph represents a paragraph declaration in a description.md file.

func ReplaceAbbreviations

func ReplaceAbbreviations(paragraph Paragraph, currentLanguageAbbreviations Abbreviations) Paragraph

ReplaceAbbreviations processes the given Paragraph to replace abbreviations.

type ParsedWork

type ParsedWork AnalyzedWork

ParsedWork represents a work, but without analyzed media. All it contains is information from the description.md file.

type ProgressInfoEvent added in v0.2.0

type ProgressInfoEvent struct {
	// WorksDone is the number of works that have been built
	WorksDone int `json:"works_done"`
	// WorksTotal is the total number of works that will be built
	WorksTotal int        `json:"works_total"`
	WorkID     string     `json:"work_id"`
	Phase      BuildPhase `json:"phase"`
	Details    []string   `json:"details"`
}

ProgressInfoEvent represents an event that is appended to the progress JSONLines file.

type Project

type Project struct {
	ID             string
	DescriptionRaw string
	Description    ParsedWork
	Ctx            *RunContext
}

Project represents a project.

func (*Project) ProjectPath

func (p *Project) ProjectPath() string

GetProjectPath returns the project's folder path with regard to databaseDirectory.

type RunContext

type RunContext struct {
	Config                *Configuration
	DatabaseDirectory     string
	OutputDatabaseFile    string
	PreviousBuiltDatabase Database
	Flags                 Flags
	BuildMetadata         BuildMetadata
	ProgressInfoFile      string
	Exporters             []Exporter

	TagsRepository         []Tag
	TechnologiesRepository []Technology
	// contains filtered or unexported fields
}

RunContext holds several "global" references used throughout all the functions of a command.

func PrepareBuild

func PrepareBuild(databaseDirectory string, outputFilename string, flags Flags, config Configuration) (*RunContext, error)

func (*RunContext) AnalyzeMediaFile

func (ctx *RunContext) AnalyzeMediaFile(workID string, embedDeclaration Media) (usedCache bool, analyzedMedia Media, anchor string, err error)

AnalyzeMediaFile analyzes the file at its absolute filepath filename and returns a Media struct, merging the analysis' results with information from the matching MediaEmbedDeclaration. TODO prevent duplicate analysis of the same file in the current session even when file was never analyzed on previous runs of the command

func (*RunContext) Build

func (ctx *RunContext) Build(descriptionRaw string, outputFilename string, workID string) (AnalyzedWork, error)

Build builds a single work given the database & output folders, as wells as a work ID

func (*RunContext) BuildAll

func (ctx *RunContext) BuildAll(databaseDirectory string, outputFilename string, flags Flags, config Configuration) (Database, error)

BuildAll builds the database at outputFilename from databaseDirectory. Use LoadConfiguration (and ValidateConfiguration if desired) to get a Configuration.

func (*RunContext) BuildBlogPage

func (ctx *RunContext) BuildBlogPage(inside string, path string) (page AnalyzedBlogPage, err error)

BuildBlogPage builds the given blog page at the given path

func (*RunContext) BuildSome

func (ctx *RunContext) BuildSome(include string, databaseDirectory string, outputFilename string, flags Flags, config Configuration) (Database, error)

func (*RunContext) ComputeOutputThumbnailFilename

func (ctx *RunContext) ComputeOutputThumbnailFilename(media Media, blockID string, projectID string, targetSize int, lang string) FilePathInsideMediaRoot

ComputeOutputThumbnailFilename returns the filename where to save a thumbnail, using to the configuration and the given information. file name templates are relative to the output media directory. Placeholders that will be replaced in the file name template:

<project id>          the project’s id
<media directory>     the value of media.at in the configuration
<basename>            the media’s basename (with the extension)
<block id>            the media’s id
<size>                the current thumbnail size
<extension>           the media’s extension
<lang>                the current language.

func (*RunContext) ComputeProgressTotal

func (ctx *RunContext) ComputeProgressTotal() (workDirectories []fs.DirEntry, err error)

func (*RunContext) CreateDescriptionFile

func (ctx *RunContext) CreateDescriptionFile(workId string, metadataItems []string, forceOverwrite bool) (string, error)

func (*RunContext) DescriptionFilename

func (ctx *RunContext) DescriptionFilename(databaseDirectory string, workID string) string

func (*RunContext) DetectTags added in v0.1.2

func (ctx *RunContext) DetectTags(workId string, techs []Technology) (detecteds []Tag, err error)

func (*RunContext) DetectTechnologies added in v0.1.2

func (ctx *RunContext) DetectTechnologies(workId string) (detecteds []Technology, err error)

func (*RunContext) ExporterOptions added in v1.1.0

func (ctx *RunContext) ExporterOptions(exporter Exporter) (ExporterOptions, error)

ExporterOptions validates then returns the configuration options for the given exporter.

func (*RunContext) FindExporter added in v1.1.0

func (ctx *RunContext) FindExporter(name string) (Exporter, error)

func (*RunContext) FindTag added in v0.1.2

func (ctx *RunContext) FindTag(name string) (result Tag, ok bool)

func (*RunContext) FindTechnology added in v0.1.2

func (ctx *RunContext) FindTechnology(name string) (result Technology, ok bool)

func (*RunContext) HandleMedia

func (ctx *RunContext) HandleMedia(workID string, blockID string, embedDeclaration Media, language string) (media Media, anchor string, err error)

func (*RunContext) IncrementProgress

func (ctx *RunContext) IncrementProgress()

func (*RunContext) LoadTagsRepository added in v0.1.2

func (ctx *RunContext) LoadTagsRepository() ([]Tag, error)

func (*RunContext) LoadTechnologiesRepository added in v0.1.2

func (ctx *RunContext) LoadTechnologiesRepository() ([]Technology, error)

func (*RunContext) MakeThumbnail

func (ctx *RunContext) MakeThumbnail(media Media, targetSize int, saveTo string) error

MakeThumbnail creates a thumbnail on disk of the given media (it is assumed that the given media is an image). It returns the path where the thumbnail has been written to. saveTo should be relative to cwd.

func (*RunContext) ParseSingleLanguageDescription

func (ctx *RunContext) ParseSingleLanguageDescription(markdownRaw string) (title HTMLString, blocks []ContentBlock, footnotes Footnotes, abbreviations Abbreviations)

ParseSingleLanguageDescription takes in raw markdown without language markers (called on splitOnLanguageMarker's output). and returns parsed arrays of structs that make up each language's part in ParsedDescription's maps. order contains an array of nanoids that represent the order of the content blocks as they are in the original file.

func (*RunContext) PathToWorkFolder

func (ctx *RunContext) PathToWorkFolder(workID string) string

PathToWorkFolder returns the path to the work's folder, including the .portfoliodb part if --scattered.

func (*RunContext) ReplicateAll added in v1.0.0

func (ctx *RunContext) ReplicateAll(targetDatabase string, works Database) error

ReplicateAll recreates a database inside targetDatabase containing all the works in works.

func (*RunContext) ReplicateDescription added in v1.0.0

func (ctx *RunContext) ReplicateDescription(work AnalyzedWork) (string, error)

ReplicateDescription reconstructs the contents of a description.md file from a Work struct.

func (*RunContext) ReplicateOne added in v1.0.0

func (ctx *RunContext) ReplicateOne(targetDatabase string, work AnalyzedWork) error

ReplicateOne creates a description.md file in targetDatabase in the correct folder in order to replicate Work.

func (*RunContext) RunExporters added in v1.1.0

func (ctx *RunContext) RunExporters(work *AnalyzedWork) error

func (*RunContext) StartProgressBar added in v0.2.0

func (ctx *RunContext) StartProgressBar(total int)

func (*RunContext) Status

func (ctx *RunContext) Status(workID string, phase BuildPhase, details ...string)

Status updates the current progress and writes the progress to a file if --write-progress is set.

func (*RunContext) StopProgressBar added in v0.2.0

func (ctx *RunContext) StopProgressBar()

func (*RunContext) UpdateBuildMetadata

func (ctx *RunContext) UpdateBuildMetadata()

UpdateBuildMetadata updates metadata about the latest build.

func (*RunContext) UseCache

func (ctx *RunContext) UseCache(filename string, embedDeclaration Media, workID string) (used bool, media Media)

func (*RunContext) WriteBuildMetadata

func (ctx *RunContext) WriteBuildMetadata() error

WriteBuildMetadata writes the latest build metadata file.

func (*RunContext) WriteDatabase

func (ctx *RunContext) WriteDatabase(works Database, flags Flags, outputFilename string, partial bool)

type SqlExporter added in v1.1.0

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

func (*SqlExporter) After added in v1.1.0

func (e *SqlExporter) After(ctx *RunContext, opts ExporterOptions, built *Database) error

func (*SqlExporter) Before added in v1.1.0

func (e *SqlExporter) Before(ctx *RunContext, opts ExporterOptions) error

func (*SqlExporter) Description added in v1.2.0

func (e *SqlExporter) Description() string

func (*SqlExporter) Export added in v1.1.0

func (e *SqlExporter) Export(ctx *RunContext, opts ExporterOptions, work *AnalyzedWork) error

func (*SqlExporter) Name added in v1.1.0

func (e *SqlExporter) Name() string

func (*SqlExporter) OptionsType added in v1.1.0

func (e *SqlExporter) OptionsType() any

type SqlExporterOptions added in v1.1.0

type SqlExporterOptions struct {
	Language string `yaml:"language"`
	Output   string `yaml:"output,omitempty"`
}

type Tag added in v0.1.2

type Tag struct {
	// Singular-form name of the tag. For example, "Book".
	Singular string `yaml:"singular"`
	// Plural-form name of the tag. For example, "Books".
	Plural      string `yaml:"plural"`
	Description string `yaml:"description,omitempty"`
	// URL to a website where more information can be found about this tag.
	LearnMoreAt string `yaml:"learn more at,omitempty"`
	// Other singular-form names of tags that refer to this tag. The names mentionned here should not be used to define other tags.
	Aliases []string `yaml:"aliases,omitempty"`
	// Various ways to automatically detect that a work is tagged with this tag.
	DetectConditions struct {
		// Consider the work to be tagged with this tag if it contains any of the files specified here. Glob patterns are supported.
		// Files are searched relative to the work's folder (even in Scattered mode, files are not searched relative to the .ortfo folder)
		Files []string `yaml:"files,omitempty"`
		// To be implemented
		Search []string `yaml:"search,omitempty"`
		// Consider the work to be tagged with this tag if it was made with any of the technologies specified here.
		MadeWith []string `yaml:"made with,omitempty"`
	} `yaml:"detect,omitempty"`
}

Tag represents a category that can be assigned to a work. See https://ortfo.org/db/tags for more information.

func (Tag) Detect added in v0.1.2

func (t Tag) Detect(ctx *RunContext, workId string, techs []Technology) (bool, error)

func (Tag) ReferredToBy added in v0.1.2

func (t Tag) ReferredToBy(name string) bool

func (Tag) String added in v0.1.2

func (t Tag) String() string

type TagsConfiguration added in v1.5.0

type TagsConfiguration struct {
	// Path to file describing all tags.
	Repository string
}

type TechnologiesConfiguration added in v1.5.0

type TechnologiesConfiguration struct {
	// Path to file describing all technologies.
	Repository string
}

type Technology added in v0.1.2

type Technology struct {
	// The slug is a unique identifier for this technology, that's suitable for use in a website's URL.
	// For example, the page that shows all works using a technology with slug "a" could be at https://example.org/technologies/a.
	Slug string `yaml:"slug"`
	Name string `yaml:"name"`
	// Name of the person or organization that created this technology.
	By          string `yaml:"by,omitempty"`
	Description string `yaml:"description,omitempty"`

	// URL to a website where more information can be found about this technology.
	LearnMoreAt string `yaml:"learn more at,omitempty"`

	// Other technology slugs that refer to this technology. The slugs mentionned here should not be used in the definition of other technologies.
	Aliases []string `yaml:"aliases,omitempty"`

	// Files contains a list of gitignore-style patterns. If the work contains any of the patterns specified, we consider that technology to be used in the work.
	Files []string `yaml:"files,omitempty"`
	// Autodetect contains an expression of the form 'CONTENT in PATH' where CONTENT is a free-form unquoted string and PATH is a filepath relative to the work folder.
	// If CONTENT is found in PATH, we consider that technology to be used in the work.
	Autodetect []string `yaml:"autodetect,omitempty"`
}

Technology represents a "technology" (in the very broad sense) that was used to create a work. See https://ortfo.org/db/technologies for more information.

func (Technology) Detect added in v0.1.2

func (t Technology) Detect(ctx *RunContext, workId string) (bool, error)

func (Technology) ReferredToBy added in v0.1.2

func (t Technology) ReferredToBy(name string) bool

func (Technology) String added in v0.1.2

func (t Technology) String() string

type ThumbnailsMap

type ThumbnailsMap map[int]FilePathInsideMediaRoot

func (ThumbnailsMap) Closest

func (thumbnails ThumbnailsMap) Closest(size int) FilePathInsideMediaRoot

type TitleStyle

type TitleStyle string

type WorkMetadata

type WorkMetadata struct {
	Aliases            []string                      `json:"aliases" yaml:",omitempty"`
	Finished           string                        `json:"finished" yaml:",omitempty"`
	Started            string                        `json:"started"`
	MadeWith           []string                      `json:"madeWith" yaml:"made with"`
	Tags               []string                      `json:"tags"`
	Thumbnail          FilePathInsidePortfolioFolder `json:"thumbnail" yaml:",omitempty"`
	TitleStyle         TitleStyle                    `json:"titleStyle" yaml:"title style,omitempty"`
	Colors             ColorPalette                  `json:"colors" yaml:",omitempty"`
	PageBackground     string                        `json:"pageBackground" yaml:"page background,omitempty"`
	WIP                bool                          `json:"wip" yaml:",omitempty"`
	Private            bool                          `json:"private" yaml:",omitempty"`
	AdditionalMetadata map[string]interface{}        `mapstructure:",remain" json:"additionalMetadata" yaml:",omitempty"`
	DatabaseMetadata   DatabaseMeta                  `json:"databaseMetadata" yaml:"-" `
}

func (WorkMetadata) CreatedAt

func (m WorkMetadata) CreatedAt() time.Time

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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