github.com/rotari-dev/rotari/internal/tableview

Overview

package tableview // import "github.com/rotari-dev/rotari/internal/tableview"

Package tableview reads what the Table viewer shows: delimited text and JSON
Lines files or a directory's files as rows of cells, a page at a time, and the
image, audio, video, and PDF files its cells name. It knows nothing of jobs,
runs, or HTTP: callers supply a Target, the file or directory and the roots
whose files may be read.

Constants

const (
	// TypePath cells name a file relative to the directory.
	TypePath = "path"
	// TypeDuration cells are seconds.
	TypeDuration = "duration"
	// TypeBytes cells are a size in bytes; a filter's value may carry a
	// binary suffix, as 10M or 1.5G.
	TypeBytes = "bytes"
	// TypeTime cells are RFC 3339 times in UTC, which sort as text.
	TypeTime   = "time"
	TypeNumber = "number"
)
    Column types a directory listing's columns carry; a delimited file's columns
    are untyped text.

const (
	// ViewFiles lists one file per row.
	ViewFiles = "files"
	// ViewStems lists one stem per row and one group per column.
	ViewStems = "stems"
)
    The views of a directory.

const (
	// GroupAuto is GroupExtension when every file is directly in the
	// directory, and GroupTop otherwise.
	GroupAuto = ""
	// GroupTop groups by the first directory in the path; the stem is the
	// rest without its extension.
	GroupTop = "top"
	// GroupParent groups by the file's directory; the stem is its name
	// without its extension.
	GroupParent = "parent"
	// GroupExtension groups by extension; the stem is the path without it.
	GroupExtension = "extension"
	// GroupSuffix groups by the end of the name after the last
	// SuffixSeparator; the stem is the path before it.
	GroupSuffix = "suffix"
)
    How the stems view splits a file's path into a group and a stem.

const (
	OpEqual        = "="
	OpNotEqual     = "!="
	OpLess         = "<"
	OpLessEqual    = "<="
	OpGreater      = ">"
	OpGreaterEqual = ">="
	OpContains     = "contains"
	OpNotContains  = "not_contains"
	OpEmpty        = "empty"
	OpNotEmpty     = "not_empty"
	OpRegex        = "regex"
	OpNotRegex     = "not_regex"
)
    The operators a Condition takes. Equality compares numbers when the cell
    and the value both read as one, and text otherwise; the orderings match
    only cells that read as numbers. Contains compares text, case-sensitive.
    Regex searches the cell's text with Go's regexp syntax, in which matching
    takes time linear in the cell, so a pattern from a shared link cannot hang
    the server.

const (
	DefaultLimit = 100
	MaxLimit     = 1000
)
    Limits on one page.

const (
	FileBase      = "file"
	DirectoryBase = "directory"
)
    The bases a Target adds for itself.

Variables

var ErrOutsideRoots = errors.New("outside the allowed roots")
    ErrOutsideRoots marks a path that no allowed root contains.

var MediaTypes = map[string]string{
	".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
	".gif": "image/gif", ".svg": "image/svg+xml",
	".wav": "audio/wav", ".mp3": "audio/mpeg", ".flac": "audio/flac",
	".ogg": "audio/ogg", ".oga": "audio/ogg", ".opus": "audio/ogg", ".m4a": "audio/mp4",
	".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
	".pdf": "application/pdf",
}
    MediaTypes are the files shown inline, by lower-case extension: images,
    audio, video, and PDFs.

var TablePatterns = []string{
	"*.csv", "*.CSV", "*.tsv", "*.TSV", "*.tab", "*.TAB", "*.psv", "*.PSV",
	"*.txt", "*.TXT", "*.scp", "*.SCP", "*.lst", "*.LST", "*.list", "*.LIST",
	"*.dat", "*.DAT", "*.jsonl", "*.JSONL",
}
    TablePatterns are the base names of table files the viewer opens as rows.
    Any delimited file can be read as a table when named directly.

Functions

func DocumentPreview(name string) string
    DocumentPreview reports a document the viewer opens directly: it is
    "markdown" for Markdown files, "text" for supported source/config files, and
    empty for other names. Media types such as PDF are classified separately.

func IsTableFile(name string) bool
    IsTableFile reports whether a file of base name name is one TablePatterns
    offers as a table.

func MediaKind(name string) string
    MediaKind is "image", "audio", "video", or "pdf" for a name MediaTypes
    lists, and "" for any other.

func RootOf(path string, roots []string) (string, string, bool)
    RootOf returns the first root that lexically contains path, and path
    relative to it. Opening through os.Root then refuses a symlink that leaves
    the root.

func ViewerPatterns() []string
    ViewerPatterns lists file names that open directly in the Table viewer,
    as tables or document previews.

Types

type Base struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Path  string `json:"-"`
}
    Base is a directory media paths may be relative to.

type Column struct {
	Name string `json:"name"`
	Type string `json:"type,omitempty"`
}
    Column is one column of a table. Type tells how its cells read (TypePath and
    the others); a delimited file's columns are untyped.

type ColumnStats struct {
	Count  int `json:"count"`
	Unique int `json:"unique"`
	// UniqueOver reports more than uniqueLimit distinct values; Unique then
	// stops at the limit.
	UniqueOver bool     `json:"unique_over,omitempty"`
	Numeric    int      `json:"numeric"`
	Mean       *float64 `json:"mean,omitempty"`
	Std        *float64 `json:"std,omitempty"`
	Min        *float64 `json:"min,omitempty"`
	Max        *float64 `json:"max,omitempty"`
	Sum        *float64 `json:"sum,omitempty"`
	// The quartiles of the numbers, interpolated linearly as pandas does.
	Q25       *float64   `json:"q25,omitempty"`
	Q50       *float64   `json:"q50,omitempty"`
	Q75       *float64   `json:"q75,omitempty"`
	Histogram *Histogram `json:"histogram,omitempty"`
	// Top is the most frequent non-blank values, most frequent and then first
	// seen first, unless every value appears once.
	Top []TopValue `json:"top,omitempty"`
	// TopOver reports too many distinct values to say which are most frequent.
	TopOver bool `json:"top_over,omitempty"`
}
    ColumnStats summarizes one column's non-empty cells, like pandas' describe:
    how many, how many distinct, and for those that read as numbers, their mean,
    sample standard deviation, extremes, and sum.

type Condition struct {
	Column int    `json:"column"`
	Op     string `json:"op"`
	Value  string `json:"value,omitempty"`
}
    Condition selects rows by the cell in one column, counted from 0. A row
    shorter than the column has an empty cell there.

func ParseConditions(text string) ([]Condition, error)
    ParseConditions reads conditions from their JSON list.

type Description struct {
	Columns []ColumnStats `json:"columns"`
	Matched int           `json:"matched"`
	Total   int           `json:"total"`
	// DistributionOver reports more numbers than distributionLimit, which leaves
	// out every column's quartiles and histogram.
	DistributionOver bool `json:"distribution_over,omitempty"`
}
    Description is Describe's result: one entry per column, over the rows the
    filters select.

type Export struct {
	// Has unexported fields.
}
    Export is the rows a query selects, ready to write in the source's own
    format. Preparing it finds whatever would refuse the query, so that nothing
    has been written when that happens.

func (export *Export) Stream(ctx context.Context, writer io.Writer) error
    Stream writes the header, if the format has one, and every selected row in
    order. An error after the first write leaves the output short, so the caller
    must not let it pass for a whole file.

type Format struct {
	Separator rune
	// Header makes the first record the column names instead of a row.
	Header bool
}
    Format is how a delimited file splits into rows and cells: records separated
    by newlines and cells by Separator, with double quotes around a cell that
    holds either, as in CSV. Blank lines are skipped.

type Histogram struct {
	Min    float64 `json:"min"`
	Max    float64 `json:"max"`
	Counts []int   `json:"counts"`
}
    Histogram counts a column's numbers in equal-width bins from Min to Max.

type Listing struct {
	// Pattern chooses files by their path relative to the directory, with
	// "/" between names: "*" matches within a name, "**" any number of
	// directories, and {a,b} either alternative. "" is "**/*".
	Pattern string
	// Expanded names directories relative to the target whose children
	// should be read. All ancestors must also be expanded.
	Expanded []string
	View     string
	Group    string
	// SuffixSeparator splits a name for GroupSuffix.
	SuffixSeparator string
	// Incomplete keeps only the stems missing a file in some group.
	Incomplete bool
}
    Listing is how a directory becomes a table.

type Media struct {
	Kind       string      `json:"kind"`
	Ref        string      `json:"ref"`
	Base       string      `json:"base,omitempty"`
	Properties *Properties `json:"properties,omitempty"`
	Error      string      `json:"error,omitempty"`
}
    Media is what a cell names: an image, audio, video, or PDF file, with its
    properties or why they are not shown. Ref and Base request the file from the
    viewer's media route.

type Page struct {
	Columns []Column `json:"columns"`
	Rows    []Row    `json:"rows"`
	Offset  int      `json:"offset"`
	// Matched counts the rows the query selects; Total counts them all.
	Matched int `json:"matched"`
	Total   int `json:"total"`
	// Cut reports cells shortened to cellLimit bytes.
	Cut   bool     `json:"cut,omitempty"`
	Notes []string `json:"notes,omitempty"`
}
    Page is one page of a table.

type Properties struct {
	Format string `json:"format"`
	Size   int64  `json:"size"`
	// Duration is in seconds.
	Duration   float64 `json:"duration,omitempty"`
	SampleRate int     `json:"sample_rate,omitempty"`
	Channels   int     `json:"channels,omitempty"`
	BitDepth   int     `json:"bit_depth,omitempty"`
	// Bitrate is in bits per second: the format's own for uncompressed
	// audio and constant-bitrate MP3, otherwise the file's size over its
	// duration.
	Bitrate int `json:"bitrate,omitempty"`
	Width   int `json:"width,omitempty"`
	Height  int `json:"height,omitempty"`
}
    Properties describe a supported preview file from its headers, without
    decoding it. A field is zero when the format does not record it or the file
    could not be read that far.

func Probe(file io.ReaderAt, size int64, extension string) Properties
    Probe reads a media file's properties by its extension. A file whose headers
    do not parse still has its format, from the extension, and size.

type Query struct {
	Filters []Condition
	Sort    *Sort
	Offset  int
	Limit   int
	// Base is the ID of the base relative media paths in a file's cells
	// resolve from; "" is the first.
	Base string
}
    Query selects a page of rows: those every filter matches, in the sort's
    order or the source's.

type Row struct {
	Number int            `json:"number"`
	Cells  []string       `json:"cells"`
	Media  map[int]*Media `json:"media,omitempty"`
	// Directory is the relative path of an expandable directory row.
	Directory string `json:"directory,omitempty"`
	// Tables lists a directory's path cells, by column, that name a table
	// file (IsTableFile), which the viewer can open on its own.
	Tables []int `json:"tables,omitempty"`
}
    Row is a row of a page; Number counts data rows from 1 in the source.
    Media describes the cells, by column, that name a previewable file.

type Sort struct {
	Column     int
	Descending bool
}
    Sort orders rows by one column. Cells that read as numbers come first,
    by value, then the rest by text; equal cells keep the file's order.

type Table struct {
	// Has unexported fields.
}
    Table is a source of rows the viewer pages through.

func OpenDirectory(target Target, listing Listing) (*Table, error)
    OpenDirectory lists target, a directory, as listing asks.

func OpenFile(target Target, format Format) (*Table, error)
    OpenFile reads target as a delimited file.

func OpenJSONLines(target Target) (*Table, error)
    OpenJSONLines reads a file of one JSON value per line as a table. Object
    keys become columns; arrays and scalar values use a "value" column.

func (table *Table) Columns() []Column
    Columns names the table's columns.

func (table *Table) Describe(filters []Condition) (Description, error)
    Describe summarizes every column over the rows the filters select. It reads
    the whole source once, and is cached per source version and filters.

func (table *Table) Order(sort Sort) ([]int, error)
    Order returns the numbers of every row, counted from 0, in the order a sort
    puts them, as Page reads them; a static snapshot of the viewer sorts with
    it. The slice is shared and must not be changed.

func (table *Table) Page(query Query) (Page, error)
    Page reads the rows a query selects, and describes previewable files named
    by their cells.

func (table *Table) PrepareExport(filters []Condition, sort *Sort) (*Export, error)
    PrepareExport selects the rows filters and sort do, as Page does.

type Target struct {
	Path  string
	Roots []string
	// Bases are directories a relative media path in a file's cells may be
	// resolved from, the first being the default; the file's own directory
	// (FileBase) is added after them. A directory's paths are relative to
	// the directory itself (DirectoryBase).
	Bases []Base
}
    Target is what a viewer shows: a table or document file, or a directory,
    by absolute path, under one of Roots. Every file the viewer reads, the
    target and the media its cells name, is opened through os.Root under a root
    that lexically contains it, so a symlink cannot leave the roots.

func (target Target) AllBases(directory bool) []Base
    AllBases lists the bases media paths of the target may be relative to:
    for a file, the caller's and then the file's directory; for a directory,
    only the directory.

func (target Target) Open(path string) (*os.File, error)
    Open opens a file ResolveMedia or ResolvePath returned.

func (target Target) ResolveMedia(directory bool, baseID, ref string) (string, error)
    ResolveMedia returns the absolute path of a supported preview file a cell
    names: an absolute path as it is, or a relative one joined to the base with
    that ID. The file must be under a root; whether it exists is found when it
    is opened.

func (target Target) ResolvePath(directory bool, baseID, ref string) (string, error)
    ResolvePath returns the absolute path of any file a cell names, as
    ResolveMedia does without asking for a media file: one the viewer reads as
    text.

func (target Target) Stat() (os.FileInfo, error)
    Stat describes the target, opened through its root.

type TopValue struct {
	Value string `json:"value"`
	Count int    `json:"count"`
	Cut   bool   `json:"cut,omitempty"`
}
    TopValue is one of a column's most frequent values. Cut reports a value
    shortened to topValueBytes.