utils

package
v0.0.34 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: BSD-3-Clause Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTableLimit        = 350
	DefaultPlayQueue         = 120
	DefaultSubtitleMix       = 0.35
	DefaultFileRowsReadLimit = 500000
	DefaultMultiplePlayback  = -1
	DefaultOpenLimit         = 7
)
View Source
const (
	DefaultAudioBitrate = 256000  // 256 kbps
	DefaultVideoBitrate = 1500000 // 1500 kbps
)

Default bitrates for duration estimation (bits per second)

Variables

View Source
var (
	ApplicationStart = time.Now().Unix()
	IsWindows        = runtime.GOOS == "windows"
	IsLinux          = runtime.GOOS == "linux"
	IsMac            = runtime.GOOS == "darwin"
	TERMINAL_SIZE    = struct{ columns, rows int }{80, 24}
)
View Source
var (
	VideoExtensionMap   = make(map[string]bool)
	AudioExtensionMap   = make(map[string]bool)
	ImageExtensionMap   = make(map[string]bool)
	TextExtensionMap    = make(map[string]bool)
	ComicExtensionMap   = make(map[string]bool)
	ArchiveExtensionMap = make(map[string]bool)
	MediaExtensionMap   = make(map[string]bool)
)
View Source
var (
	Stdin  io.Reader = os.Stdin
	Stdout io.Writer = os.Stdout
	Stderr io.Writer = os.Stderr
)
View Source
var (
	// Version is the git version that produced this binary.
	Version string

	// When is the datestamp that produced this binary.
	When string

	// BuildSettings contains additional build information.
	BuildSettings []debug.BuildSetting

	// Deps contains dependency information.
	Deps []*debug.Module
)
View Source
var ArchiveExtensions = []string{
	"7z", "arj", "arc", "adf", "br", "bz2", "gz", "iso", "lha", "lzh", "lzx", "pak", "rar", "sit", "tar", "tar.bz2", "tar.gz", "tar.xz", "tar.zst", "tbz2", "tgz", "txz", "tzst", "xz", "zoo", "zip", "zst", "zstd", "cbz", "cbr",
}
View Source
var AudioExtensions = []string{
	"mka", "opus", "oga", "ogg", "mp3", "mpga", "m2a", "m4a", "m4r", "caf", "m4b", "flac", "wav", "pcm", "aif", "aiff", "wma", "aac", "aa3", "ac3", "ape", "dsf", "dff",
}
View Source
var ComicExtensions = []string{
	"cbz", "cbr",
}
View Source
var ImageExtensions = []string{}/* 146 elements not displayed */
View Source
var SQLiteExtensions = []string{".sqlite", ".sqlite3", ".db", ".db3", ".s3db", ".sl3"}
View Source
var SubtitleExtensions = []string{
	"srt", "vtt", "mks", "ass", "ssa", "lrc", "idx", "sub",
}
View Source
var TextExtensions = []string{
	"txt", "epub", "mobi", "pdf", "azw", "azw3", "fb2", "djvu", "zim",
}
View Source
var UnreliableDurationFormats = map[string]int{

	".vob": 5000000,
	".ifo": 5000000,
	".vro": 5000000,

	".m2t":  15000000,
	".m2ts": 15000000,
	".mts":  15000000,
	".mod":  10000000,
	".tod":  12000000,

	".divx": 4000000,
	".xvid": 4000000,
	".rm":   2000000,
	".rmvb": 3000000,
	".wmv":  3000000,
	".asf":  3000000,

	".avchd": 20000000,
	".bdmv":  30000000,
	".mpls":  30000000,

	".iso": 8000000,
}

UnreliableDurationFormats are formats known to have unreliable duration metadata (DVD, Blu-ray, camcorder formats, and older codecs) The int value is the estimated bitrate in bits per second for each format

View Source
var VideoExtensions = []string{}/* 281 elements not displayed */

Functions

func AdjustDuration

func AdjustDuration(duration int, start *int, end *int) int

func AllowDictsLikeSQL

func AllowDictsLikeSQL(data []map[string]any, allowlist []map[string]any) []map[string]any

AllowDictsLikeSQL filters data by keeping only items that match at least one pattern in the allowlist

func AltName

func AltName(path string) string

AltName returns an alternative filename if the given path already exists

func AutoUpdate

func AutoUpdate()

AutoUpdate will periodically check for an update and install it.

func BlockDictsLikeSQL

func BlockDictsLikeSQL(data []map[string]any, blocklist []map[string]any) []map[string]any

BlockDictsLikeSQL filters data by removing items that match any pattern in the blocklist

func BoolToInt64

func BoolToInt64(b bool) int64

func CalculatePercentiles

func CalculatePercentiles(values []int64) []int64

func CalculateSegments

func CalculateSegments(total float64, chunk float64, gap float64) []float64

func CalculateSegmentsInt

func CalculateSegmentsInt(total int64, chunk int64, gap float64) []int64

func CastCommand

func CastCommand(castDevice string, args ...string) error

CastCommand builds and executes a catt command with optional device specification

func Chunks

func Chunks[T any](slice []T, chunkSize int) [][]T

func CleanPath

func CleanPath(path string, opts CleanPathOptions) string

func CleanString

func CleanString(s string) string

func CmdDetach

func CmdDetach(name string, args ...string) error

CmdDetach runs a command in the background, detached from the current process

func CmdInteractive

func CmdInteractive(name string, args ...string) error

CmdInteractive runs a command connected to the current process's terminal

func ColDuration

func ColDuration(data []map[string]any, key string) []map[string]any

func ColFilesize

func ColFilesize(data []map[string]any, key string) []map[string]any

func ColNaturalDate

func ColNaturalDate(data []map[string]any, key string) []map[string]any

func Combine

func Combine(vals ...any) string

func CommandExists added in v0.0.34

func CommandExists(cmd string) bool

CommandExists checks if a command is available in PATH or common installation paths Results are cached to avoid repeated syscalls

func CommonPath

func CommonPath(paths []string) string

CommonPath returns the longest common path prefix Always returns forward slashes for cross-platform consistency

func CommonPathFull

func CommonPathFull(paths []string) string

CommonPathFull returns a common path prefix. Previously it included common words in the suffix, but this was confusing for UI.

func CompareBlockStrings

func CompareBlockStrings(pattern, value string) bool

CompareBlockStrings implements SQL-like % wildcard matching

func Concat

func Concat[T any](slices ...[]T) []T

func Confirm

func Confirm(message string) bool

func Conform

func Conform[T any](v any) []T

func ConstructSearchBindings

func ConstructSearchBindings(include, exclude, columns []string, exact bool) (string, map[string]any)

ConstructSearchBindings returns a SQL where clause and a map of named bindings for inclusion and exclusion

func ConvertEpubToOEB

func ConvertEpubToOEB(inputPath string) (string, error)

ConvertEpubToOEB converts EPUB/text documents to HTML format using calibre's ebook-convert. The converted files are stored in ~/.cache/disco with automatic cleanup of files older than 3 days. Returns the path to the converted HTML directory.

func CorpusStats

func CorpusStats(corpus [][]string) map[string]int

CorpusStats returns word counts across all lines

func CountWordsFast added in v0.0.30

func CountWordsFast(b []byte) int

CountWordsFast estimates word count by counting spaces. This is much faster than strings.Fields() and sufficient for duration estimation.

func DetectMimeType

func DetectMimeType(path string) string

DetectMimeType returns the mimetype of a file based on extension Used only for HTTP Content-Type headers in streaming

func DictFilterBool

func DictFilterBool(d map[string]any) map[string]any

func DirExists

func DirExists(path string) bool

func DivideSequence

func DivideSequence[T Number](slice []T) float64

func Divisors

func Divisors(n int) []int

func DurationShort

func DurationShort(seconds int) string

func EscapeXML

func EscapeXML(s string) string

func EstimateDurationFromSize added in v0.0.34

func EstimateDurationFromSize(size int64, isVideo bool) float64

EstimateDurationFromSize estimates duration from file size and bitrate Returns duration in seconds

func EstimateDurationFromSizeWithFormat added in v0.0.34

func EstimateDurationFromSizeWithFormat(size int64, ext string) float64

EstimateDurationFromSizeWithFormat estimates duration from file size using format-specific bitrate Returns duration in seconds

func EstimateReadingDuration added in v0.0.30

func EstimateReadingDuration(wordCount int) int64

EstimateReadingDuration calculates reading duration in seconds from word count. Uses average reading speed of 220 words per minute.

func EstimateWordCountFromSize added in v0.0.30

func EstimateWordCountFromSize(path string, size int64) int

EstimateWordCountFromSize estimates word count from file size. Uses format-specific ratios to account for images, formatting, etc. Returns estimated word count.

func ExpandStdin

func ExpandStdin(paths []string) []string

func ExtractSubtitleInfo

func ExtractSubtitleInfo(subPath string) (displayName, languageCode, codec string)

ExtractSubtitleInfo extracts language and codec information from a subtitle filename Returns (displayName, languageCode, codec) Examples:

  • movie.en.srt -> "English (ssa)", "en", "ssa" (ass is displayed as ssa)
  • movie_eng.ass -> "English (ssa)", "eng", "ssa"
  • movie.srt -> "srt", "", "srt"
  • movie.EN.srt -> "English (ssa)", "en", "ssa"
  • movie - English.srt -> "English (srt)", "en", "srt" (full language names supported)

func ExtractText

func ExtractText(path string) (string, error)

ExtractText extracts plain text from a given file path. Supports a wide range of text and document formats. Uses lightweight tools first (pdftotext, native zip), with calibre as fallback.

func ExtractWords

func ExtractWords(s string) []string

func FileExists

func FileExists(path string) bool

func FilterDeleted

func FilterDeleted(paths []string) []string

FilterDeleted returns only the paths that currently exist on the filesystem

func FilterPath

func FilterPath(path string, flags models.PathFilterFlags) bool

FilterPath checks if a path matches PathFilterFlags

func FindMainContentFile

func FindMainContentFile(oebDir string) string

FindMainContentFile finds the main HTML content file in a calibre output directory Skips cover/metadata pages and finds the actual book content

func Flatten

func Flatten(v any) []any

func FlattenWrapperFolder

func FlattenWrapperFolder(outputDir string) error

FlattenWrapperFolder removes a single subfolder if it's the only entry in outputDir

func Float64Value added in v0.0.30

func Float64Value(f *float64) float64

func FloatFromPercent

func FloatFromPercent(s string) (float64, error)

func FolderSize

func FolderSize(path string) int64

FolderSize calculates the total size of all files in a folder (recursively)

func FormatDuration

func FormatDuration(seconds int) string

func FormatDurationShort

func FormatDurationShort(seconds int) string

func FormatPlaybackDuration

func FormatPlaybackDuration(duration, segmentStart, segmentEnd int64) string

func FormatSize

func FormatSize(bytes int64) string

func FormatTime

func FormatTime(timestamp int64) string

func FromTimestampSeconds

func FromTimestampSeconds(s string) float64

func FtsQuote

func FtsQuote(query []string) []string

FtsQuote quotes search terms for FTS5 unless they already contain FTS operators

func FullHashFile

func FullHashFile(path string) (string, error)

FullHashFile calculates a full sha256 hash of a file

func FzfSelect

func FzfSelect(items []string, multi bool) ([]string, error)

FzfSelect runs fzf with the given items and returns the selected items

func GenerateHLSPlaylist

func GenerateHLSPlaylist(path string, duration float64, segmentDuration int) string

func GenerateRSVPAss

func GenerateRSVPAss(text string, wpm int) (string, float64)

GenerateRSVPAss generates an ASS subtitle file content for RSVP.

func GenerateTTS

func GenerateTTS(text string, outputPath string, wpm int) error

GenerateTTS generates a WAV file from text using espeak-ng.

func GetCattNowPlayingFile

func GetCattNowPlayingFile() string

func GetClearLineSequence added in v0.0.34

func GetClearLineSequence() string

GetClearLineSequence returns the escape sequence to clear/overwrite a line. We use \x1b[K (Erase from cursor to end of line) which is standard for overwriting.

func GetCommandPath added in v0.0.34

func GetCommandPath(name string) string

GetCommandPath returns the absolute path to a command

func GetConfigDir

func GetConfigDir() string

func GetContentTypeFromExt added in v0.0.34

func GetContentTypeFromExt(ext string) string

GetContentTypeFromExt returns the content type based on file extension

func GetDefaultBrowser

func GetDefaultBrowser() string

func GetDurationForTimeout added in v0.0.34

func GetDurationForTimeout(duration float64, size int64, ext string) float64

GetDurationForTimeout returns a duration value suitable for timeout calculations. If the provided duration is valid (> 0), it returns it as-is. If duration is <= 0, it estimates from file size:

  • For unreliable formats (DVD, Blu-ray, etc.), uses format-specific bitrate
  • For other formats, uses default video bitrate

Returns 0 if size is invalid (<= 0)

func GetEstimatedBitrate added in v0.0.34

func GetEstimatedBitrate(ext string) int

GetEstimatedBitrate returns the estimated bitrate for a format Returns 0 if the format is not in the unreliable formats map

func GetExternalSubtitles

func GetExternalSubtitles(path string) []string

GetExternalSubtitles finds external subtitle files associated with a media file Supports patterns: movie.srt, movie.en.srt, movie_eng.srt, movie.EN.srt, movie.eng.srt, etc.

func GetFloat64

func GetFloat64(v any) float64

func GetHLSSegmentArgs

func GetHLSSegmentArgs(path string, startTime float64, segmentDuration int, strategy TranscodeStrategy) []string

func GetHTMLFiles

func GetHTMLFiles(dir string) []string

GetHTMLFiles returns a list of HTML files in the directory sorted by filename

func GetImageBrightness added in v0.0.32

func GetImageBrightness(data []byte) (float64, error)

GetImageBrightness calculates the average brightness of an image. Returns a value between 0.0 (black) and 1.0 (white).

func GetInt

func GetInt(v any) int

func GetInt64

func GetInt64(v any) int64

func GetLanguageCode added in v0.0.10

func GetLanguageCode(name string) string

GetLanguageCode converts a full language name to its code

func GetLanguageName added in v0.0.10

func GetLanguageName(code string) string

GetLanguageName converts a language code to its full name

func GetMpvListenSocket

func GetMpvListenSocket() string

func GetMpvSocketPath

func GetMpvSocketPath(provided string) string

GetMpvSocketPath returns the socket path to use, either from provided value or default

func GetMpvWatchLaterDir

func GetMpvWatchLaterDir() string

func GetMpvWatchSocket

func GetMpvWatchSocket() string

func GetPathDisplayWidth added in v0.0.34

func GetPathDisplayWidth() int

GetPathDisplayWidth returns the recommended width for displaying paths Takes into account terminal width and leaves room for other columns

func GetPlayhead

func GetPlayhead(flags models.GlobalFlags, path string, startTime time.Time, existingPlayhead int, mediaDuration int) int

GetPlayhead calculates the playhead position based on session duration, existing playhead and mpv watch_later

func GetString

func GetString(v any) string

func GetTempDir

func GetTempDir() string

func GetTerminalWidth added in v0.0.34

func GetTerminalWidth() int

GetTerminalWidth returns the current terminal width

func GlobMatchAll

func GlobMatchAll(path string, patterns []string) bool

func GlobMatchAny

func GlobMatchAny(path string, patterns []string) bool

func HasUnreliableDuration added in v0.0.34

func HasUnreliableDuration(ext string) bool

HasUnreliableDuration checks if a file extension is known to have unreliable duration metadata

func HumanToBits

func HumanToBits(s string) (int64, error)

func HumanToBytes

func HumanToBytes(s string) (int64, error)

func HumanToSeconds

func HumanToSeconds(s string) (int64, error)

func Int64Value

func Int64Value(i *int64) int64

func IsDigit

func IsDigit(s string) bool

func IsEmptyFolder

func IsEmptyFolder(path string) bool

IsEmptyFolder checks if a folder contains no files (recursively)

func IsFileOpen

func IsFileOpen(path string) bool

IsFileOpen checks if a file is currently open by any process

func IsGenericTitle

func IsGenericTitle(title string) bool

func IsImageTooDark added in v0.0.32

func IsImageTooDark(data []byte, threshold float64) bool

IsImageTooDark returns true if the image brightness is below the threshold.

func IsLanguageCode added in v0.0.10

func IsLanguageCode(s string) bool

IsLanguageCode checks if a string looks like a language code

func IsSQLite

func IsSQLite(path string) bool

func IsTZAware

func IsTZAware(t time.Time) bool

IsTZAware checks if a time is not in the Local or UTC location (as a proxy for "aware") In Go, time.Time is always aware of its Location.

func IsTimecodeLike

func IsTimecodeLike(s string) bool

func LastChars

func LastChars(s string) string

func LineSorter

func LineSorter(flags models.GlobalFlags, corpusStats map[string]int, originalLines []string, corpus [][]string) []string

LineSorter sorts original lines based on their processed words

func LineSplitter

func LineSplitter(regexs []*regexp.Regexp, line string) []string

LineSplitter splits a line into words using multiple regex patterns

func LinearInterpolation

func LinearInterpolation(x float64, dataPoints [][2]float64) float64

func ListDictFilterBool

func ListDictFilterBool(data []map[string]any) []map[string]any

func LoadString

func LoadString(s string) any

func MatchesAny

func MatchesAny(path string, patterns []string) bool

func Max

func Max[T Number](a, b T) T

func MaybeUpdate

func MaybeUpdate() bool

MaybeUpdate will check for an update and install it immediately. Returns true if an update was successfully installed and the process should restart.

func Min

func Min[T Number](a, b T) T

func MostSimilarSchema

func MostSimilarSchema(keys []string, existingTables map[string]map[string]string) string

MostSimilarSchema finds the table in existingTables that has the most columns in common with keys

func MpvArgsToMap

func MpvArgsToMap(argStrings []string) map[string]string

MpvArgsToMap parses mpv command line arguments into a map

func MpvGetProperty

func MpvGetProperty(socketPath string, name string) (any, error)

MpvGetProperty gets a property from mpv

func MpvLoadFile

func MpvLoadFile(socketPath string, path string, mode string) error

MpvLoadFile loads a file into mpv

func MpvPause

func MpvPause(socketPath string, pause bool) error

MpvPause pauses or unpauses playback

func MpvSeek

func MpvSeek(socketPath string, value float64, mode string) error

MpvSeek seeks to a specific position

func MpvSetProperty

func MpvSetProperty(socketPath string, name string, value any) error

MpvSetProperty sets a property in mpv

func MpvWatchLaterValue

func MpvWatchLaterValue(path, key string) (string, error)

MpvWatchLaterValue reads a value for a given key from an mpv watch_later file

func NaturalLess

func NaturalLess(s1, s2 string) bool

func OrderedSet

func OrderedSet[T comparable](slice []T) []T

func ParseBitrate added in v0.0.34

func ParseBitrate(s string) int64

ParseBitrate parses a human-readable bitrate string to int64 bits per second

func ParseDate

func ParseDate(dateStr string) int64

ParseDate parses a date string into a Unix timestamp using a fixed set of layouts

func ParseDateOrRelative

func ParseDateOrRelative(dateStr string) int64

UtcFromLocalTimestamp converts a local Unix timestamp to a UTC time.Time ParseDateOrRelative parses a date string into a Unix timestamp. It supports absolute dates (YYYY-MM-DD) and relative strings (e.g., "3 days").

func ParseDurationString added in v0.0.34

func ParseDurationString(s string) time.Duration

ParseDurationString parses duration strings like "10s", "20m", "1h". Defaults to minutes if no unit is specified.

func ParsePercentOrBytes added in v0.0.34

func ParsePercentOrBytes(s string) float64

ParsePercentOrBytes parses a string like "5%" or "100MB" into a float64 ratio or bytes

func ParsePercentileRange

func ParsePercentileRange(s string) (min, max float64, ok bool)

func ParseSize added in v0.0.34

func ParseSize(s string) int64

ParseSize parses a human-readable size string to int64 bytes

func PartialStartswith

func PartialStartswith(s string, list []string) (string, error)

func PathToMpvWatchLaterMD5

func PathToMpvWatchLaterMD5(path string) string

PathToMpvWatchLaterMD5 returns the MD5 hash of the absolute path, which mpv uses for filenames

func PathToSentence

func PathToSentence(path string) string

func PathToTokenized added in v0.0.30

func PathToTokenized(path string) string

func PathTupleFromURL

func PathTupleFromURL(rawURL string) (string, string)

PathTupleFromURL returns (parentDir, filename) from a URL

func Percent

func Percent(value, total float64) float64

func PercentageDifference

func PercentageDifference(v1, v2 float64) float64

func Percentile

func Percentile[T Number](slice []T, p float64) float64

func PrintJSON added in v0.0.30

func PrintJSON(data any) error

PrintJSON encodes data as indented JSON to stdout

func PrintOverwrite

func PrintOverwrite(text string)

PrintOverwrite overwrites the current line in the terminal with the given text

func Prompt

func Prompt(message string) string

func QuickWordCount added in v0.0.30

func QuickWordCount(path string, size int64) (int, error)

QuickWordCount extracts text and counts words for duration estimation. Optimized for speed over accuracy - suitable for ingest-time processing. Returns word count and error. For files with very low word counts (<300), falls back to size-based estimation to avoid false positives from sparse or image-heavy files.

func RandomFilename

func RandomFilename(path string) string

RandomFilename appends a random string to the filename before the extension

func RandomFloat

func RandomFloat() float64

func RandomInt

func RandomInt(min, max int) int

func RandomString

func RandomString(n int) string

RandomString returns a random hexadecimal string of the given length

func ReadLines

func ReadLines(r io.Reader) []string

func RelativeDatetime

func RelativeDatetime(timestamp int64) string

func Relativize

func Relativize(path string) string

Relativize removes leading slashes and drive letters

func RemoveConsecutive

func RemoveConsecutive(s, char string) string

func RemoveConsecutiveWhitespace

func RemoveConsecutiveWhitespace(s string) string

func RemoveConsecutives

func RemoveConsecutives(s string, chars []string) string

func RemoveExcessiveLinebreaks

func RemoveExcessiveLinebreaks(s string) string

func RemovePrefixes

func RemovePrefixes(s string, prefixes []string) string

func RemoveSuffixes

func RemoveSuffixes(s string, suffixes []string) string

func RemoveTextInsideBrackets

func RemoveTextInsideBrackets(s string) string

func Rename

func Rename(flags models.GlobalFlags, src, dst string) error

Rename renames a file, respecting simulation mode

func RenameMoveFile

func RenameMoveFile(flags models.GlobalFlags, src, dst string) error

RenameMoveFile moves a file from src to dst, creating parent directories if needed

func RenameNoReplace

func RenameNoReplace(src, dst string) error

RenameNoReplace renames a file only if the destination does not exist

func ResolveAbsolutePath

func ResolveAbsolutePath(s string) string

ResolveAbsolutePath expands user home and returns absolute path if it exists

func Rmtree

func Rmtree(flags models.GlobalFlags, path string) error

Rmtree deletes a directory tree, respecting simulation mode

func SafeFloat

func SafeFloat(s string) *float64

func SafeIndex

func SafeIndex[T comparable](slice []T, val T) int

func SafeInt

func SafeInt(s string) *int

func SafeJSONLoads

func SafeJSONLoads(s string) any

func SafeJoin

func SafeJoin(base string, userPath string) string

SafeJoin joins a base path with a user-provided path, preventing directory traversal

func SafeLen

func SafeLen[T any](slice []T) int

func SafeMean

func SafeMean[T Number](slice []T) float64

func SafeMedian

func SafeMedian[T Number](slice []T) float64

func SafePop

func SafePop[T any](slice []T) (T, []T)

func SafeSum

func SafeSum[T Number](slice []T) T

func SafeUnpack

func SafeUnpack[T comparable](vals ...T) T

func SampleHashFile

func SampleHashFile(path string, threads int, gap float64, chunkSize int64) (string, error)

SampleHashFile calculates a hash based on small file segments

func SanitizeFilename

func SanitizeFilename(name string) string

SanitizeFilename replaces special characters with underscores for calibre compatibility

func SecondsToHHMMSS

func SecondsToHHMMSS(seconds int64) string

func Shorten

func Shorten(text string, maxWidth int) string

func ShortenMiddle

func ShortenMiddle(text string, maxWidth int) string

func ShouldOverrideDuration added in v0.0.34

func ShouldOverrideDuration(reportedDuration float64, size int64, ext string) (float64, bool)

ShouldOverrideDuration determines if reported duration should be overridden with an estimate based on file size. Returns true only when:

  • File extension matches an unreliable format
  • Reported duration is suspiciously low (< 2 minutes)
  • Estimated duration is much higher (> 2 minutes)

func Similarity

func Similarity[T comparable](a, b []T) float64

func SizeTimeout

func SizeTimeout(timeoutSize string, totalSize int64) bool

func SpecificDate

func SpecificDate(dates ...string) *time.Time

SpecificDate finds the earliest most-specific past date from a list of strings

func SplitAndTrim

func SplitAndTrim(s, sep string) []string

func SqlHumanTime

func SqlHumanTime(s string) string

func StringValue

func StringValue(s *string) string

func StripEnclosingQuotes

func StripEnclosingQuotes(s string) string

func StripMountSyntax

func StripMountSyntax(path string) string

StripMountSyntax is a repeated relativize

func SuperParser

func SuperParser(dateStr string) *time.Time

SuperParser uses dateparse to attempt to parse a date string with various strategies

func TextProcessor

func TextProcessor(flags models.GlobalFlags, lines []string) []string

TextProcessor orchestrates the splitting and sorting of text lines

func Title

func Title(s string) string

func ToDecade

func ToDecade(year int) string

func ToNullFloat64

func ToNullFloat64(f float64) sql.NullFloat64

func ToNullInt64

func ToNullInt64(i int64) sql.NullInt64

func ToNullString

func ToNullString(s string) sql.NullString

func Trash

func Trash(flags models.GlobalFlags, path string) error

Trash moves a file to the system trash if available, otherwise deletes it

func TrimPathSegments

func TrimPathSegments(path string, desiredLength int) string

TrimPathSegments reduces the length of path segments to fit within desiredLength. It uses a fish-shell style where parent/grandparent segments are reduced to their first letter.

func TruncateMiddle added in v0.0.34

func TruncateMiddle(s string, max int) string

TruncateMiddle truncates a string in the middle with ellipsis

func TubeDate

func TubeDate(v map[string]any) *int64

TubeDate extracts and parses dates from various common metadata keys

func UnParagraph

func UnParagraph(s string) string

func Unique

func Unique[T comparable](slice []T) []T
func Unlink(flags models.GlobalFlags, path string) error

Unlink deletes a file, respecting simulation mode

func UtcFromLocalTimestamp

func UtcFromLocalTimestamp(n int64) time.Time

func ValueCounts

func ValueCounts[T comparable](slice []T) []int

func WordSorter

func WordSorter(flags models.GlobalFlags, corpusStats map[string]int, lineWords []string) []string

WordSorter sorts words within a line based on various criteria

Types

type CleanPathOptions

type CleanPathOptions struct {
	MaxNameLen       int
	DotSpace         bool
	CaseInsensitive  bool
	LowercaseFolders bool
	DedupeParts      bool
}

type CmdResult

type CmdResult struct {
	Stdout   string
	Stderr   string
	ExitCode int
}

CmdResult wraps the output of a command execution

func Cmd

func Cmd(name string, args ...string) (CmdResult, error)

Cmd runs a command and returns its output and exit code

func CmdWithTimeout

func CmdWithTimeout(ctx context.Context, name string, args ...string) (CmdResult, error)

CmdWithTimeout runs a command with a timeout

type FileStats

type FileStats struct {
	Size         int64
	TimeCreated  int64
	TimeModified int64
}

func GetFileStats

func GetFileStats(path string) (FileStats, error)

GetFileStats returns size and timestamps for a file

type HybridSearchQuery added in v0.0.30

type HybridSearchQuery struct {
	// FTS terms: individual words searched via FTS5 (works with detail=none)
	FTSTerms []string
	// Phrases: exact phrases searched via LIKE (trigram-optimized)
	Phrases []string
	// Original query for reference
	Original string
}

HybridSearchQuery holds the split query components for hybrid FTS+LIKE search

func ParseHybridSearchQuery added in v0.0.30

func ParseHybridSearchQuery(query string) *HybridSearchQuery

ParseHybridSearchQuery splits a search query into FTS terms and phrase patterns Phrases are quoted strings like "exact phrase" Terms are unquoted words searched via FTS

func (*HybridSearchQuery) BuildFTSQuery added in v0.0.30

func (h *HybridSearchQuery) BuildFTSQuery(joinOp string) string

BuildFTSQuery constructs the FTS MATCH query from terms For trigram + detail=none, we use first 3 chars of each word for filtering This is a loose filter - actual matching is done by LIKE for phrases

func (*HybridSearchQuery) BuildFTSQueryExact added in v0.0.30

func (h *HybridSearchQuery) BuildFTSQueryExact(joinOp string) string

BuildFTSQueryExact constructs an exact FTS MATCH query Uses full terms instead of trigrams for precise matching

func (*HybridSearchQuery) HasFTSTerms added in v0.0.30

func (h *HybridSearchQuery) HasFTSTerms() bool

HasFTSTerms returns true if the query contains FTS term searches

func (*HybridSearchQuery) HasPhrases added in v0.0.30

func (h *HybridSearchQuery) HasPhrases() bool

HasPhrases returns true if the query contains phrase searches

type MpvCommand

type MpvCommand struct {
	Command []any `json:"command"`
}

type MpvResponse

type MpvResponse struct {
	Data  any    `json:"data"`
	Error string `json:"error"`
	ID    int    `json:"request_id"`
}

func MpvCall

func MpvCall(socketPath string, args ...any) (*MpvResponse, error)

MpvCall sends a command to mpv via IPC socket and returns the response

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64
}

type PlainHandler

type PlainHandler struct {
	Level slog.Leveler
	Out   io.Writer
	Attrs []slog.Attr
}

func (*PlainHandler) Enabled

func (h *PlainHandler) Enabled(_ context.Context, level slog.Level) bool

func (*PlainHandler) Handle

func (h *PlainHandler) Handle(_ context.Context, r slog.Record) error

func (*PlainHandler) WithAttrs

func (h *PlainHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*PlainHandler) WithGroup

func (h *PlainHandler) WithGroup(name string) slog.Handler

type Range

type Range struct {
	Min   *int64
	Max   *int64
	Value *int64
}

func ParseRange

func ParseRange(s string, humanToX func(string) (int64, error)) (Range, error)

func (Range) Matches

func (r Range) Matches(val int64) bool

type Slice

type Slice struct {
	Start *int
	Stop  *int
	Step  *int
}

func ParseSlice

func ParseSlice(s string) (Slice, error)

type TerminalWidth added in v0.0.34

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

TerminalWidth tracks the current terminal width and updates on resize

type TranscodeStrategy

type TranscodeStrategy struct {
	NeedsTranscode bool
	VideoCopy      bool
	AudioCopy      bool
	TargetMime     string
}

func GetTranscodeStrategy

func GetTranscodeStrategy(m models.Media) TranscodeStrategy

Directories

Path Synopsis
Package pathutil provides cross-platform path handling utilities.
Package pathutil provides cross-platform path handling utilities.

Jump to

Keyboard shortcuts

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