Documentation
¶
Overview ¶
Package trackparse parses music track strings ("Artist feat. Guest - Title (Remix)") and whole tracklists into structured data: artists with roles, the title, versions and remixes, junk such as "[Official Video]", positions and timestamps. Everything it recognizes goes into a field, and anything it does not recognize stays in the title, word for word.
track := trackparse.Parse( "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]", ) track.Artists[1].Name, track.Artists[1].Role // "Becky Hill", RoleFeatured track.Title // "Afterglow" track.Versions[0].Type // VersionTypeRemix track.Versions[0].Artists[0].Name // "Sub Focus" track.Junk[0].Raw, track.Junk[0].Kind // "Official Video", JunkKindVideo track.Position.Number // 1
Functions ¶
Parse parses one track string, ParseArtists a bare artist credit, Format renders a track back to a string, Normalize is the Unicode cleanup every function runs first, and AllArtists lists the credits together with the remixers. ParseTracklist reads a whole tracklist, one entry per line, and checks its times; ApplyEdits rewrites only the lines its edits name. The functions that take options have a With form (ParseWith, FormatWith, ParseTracklistWith, ...); the zero value of every options struct is the default. A Parser compiles parse options once for many calls.
Results and JSON ¶
Fields that are null in the spec's JSON are pointers, nil when absent, and slices in a result are never nil. Version types, junk kinds, warnings and the other names are typed string constants whose value is the spec's name; a function per type, such as AllVersionTypes, lists them. Every result type has a MarshalJSON method that returns the bytes JSON.stringify writes in the JavaScript package (json.Marshal then escapes <, > and &; see the README), and Track.UnmarshalJSON reads that form back.
Errors and concurrency ¶
Nothing panics, and no parsing or editing function returns an error: any string gives a complete result. Invalid UTF-8 is read as the WHATWG decoder reads it, each maximal ill-formed subsequence becoming one U+FFFD, so every output string is valid UTF-8. An edit that cannot be applied is reported as an EditWarningCodeEditInvalid warning. The package functions and a Parser are safe for concurrent use.
Spec and other languages ¶
This is the Go port of a spec-driven parser. The JavaScript (npm), Python (PyPI), Rust (crates.io) and Go packages implement one spec, pass the same shared fixtures, give the same output on every fixture input, and are released together under one version number (SpecVersion). Comments in the source cite the spec's rule IDs (R0 to R13).
- Documentation, with every example in all four languages: https://4matic.github.io/trackparse/
- Playground: https://4matic.github.io/trackparse/playground/
- Spec: https://github.com/4matic/trackparse/blob/main/spec/SPEC.md
- Repository and README: https://github.com/4matic/trackparse/tree/main/go
Example ¶
Parse a messy track string: every part it recognizes goes into a field, and anything it does not recognize stays in the title.
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
track := trackparse.Parse(
"01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]",
)
for _, a := range track.Artists {
fmt.Printf("%s (%s)\n", a.Name, a.Role)
}
fmt.Println(track.Title)
fmt.Println(track.FullTitle)
v := track.Versions[0]
fmt.Println(v.Type, v.Artists[0].Name, v.Modifiers)
fmt.Println(track.Junk[0].Raw, track.Junk[0].Kind)
fmt.Println(track.Position.Number, track.Mode)
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{
Joiners: trackparse.JoinersCanonical,
}))
}
Output: Wilkinson (primary) Becky Hill (featured) Tom Cane (featured) Afterglow Afterglow (Sub Focus VIP Remix) remix Sub Focus [vip] Official Video video 1 youtube Wilkinson feat. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)
Index ¶
- Constants
- func Format(track Track) string
- func FormatWith(track Track, options FormatOptions) string
- func Normalize(input string) string
- func Ptr[T any](v T) *T
- type Artist
- type Delimiter
- type Edit
- func Delete(line int) Edit
- func Insert(after int, text string) Edit
- func SetRest(line int, rest string) Edit
- func SetTime(line int, seconds float64) Edit
- func Shift(seconds float64) Edit
- func ShiftFrom(seconds float64, from int) Edit
- func ShiftLines(seconds float64, lines ...int) Edit
- func SortByTime() Edit
- type EditOp
- type EditResult
- type EditWarning
- type EditWarningCode
- type Entry
- type EntryKind
- type Eol
- type FeatPlacement
- type Flags
- type FormatOptions
- type JoinerStyle
- type Junk
- type JunkKind
- type JunkPhrase
- type Keywords
- type Mode
- type ParseOptions
- type Parser
- type Parts
- type Position
- type Role
- type Severity
- type Source
- type SplitAnd
- type Stats
- type Suggestion
- type Timestamp
- type Track
- type Tracklist
- type TracklistOptions
- type TracklistTime
- type TracklistWarning
- type Version
- type VersionHead
- type VersionType
- type VersionsOption
- type Warning
- type WarningCode
Examples ¶
Constants ¶
const SpecVersion = "0.6.0" // x-release-please-version
SpecVersion is the version of the spec this module implements.
Variables ¶
This section is empty.
Functions ¶
func Format ¶
Format renders a parsed track back to a string (R11) with the default options: artists, " - ", the title and its versions, written as they were found.
func FormatWith ¶
func FormatWith(track Track, options FormatOptions) string
FormatWith is Format with options.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
track := trackparse.Parse("01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)")
fmt.Println(trackparse.Format(track))
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{
Feat: trackparse.FeatTitle,
Joiners: trackparse.JoinersCanonical,
}))
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{
Feat: trackparse.FeatOmit,
Versions: trackparse.VersionsNone,
}))
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{Position: true}))
}
Output: Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix) Wilkinson - Afterglow (feat. Becky Hill) (Sub Focus Remix) Wilkinson - Afterglow 01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)
func Normalize ¶
Normalize is the Unicode cleanup (R1) every function runs first: NFC; zero-width characters, the BOM and soft hyphens removed; fullwidth brackets, smart quotes and dash variants mapped to ASCII; whitespace collapsed and trimmed. Running it twice changes nothing.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
fmt.Println(trackparse.Normalize("Noisia\u200b – Stigma (VIP)"))
}
Output: Noisia - Stigma (VIP)
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns a pointer to a copy of v. It sets the pointer fields of the options:
trackparse.FormatOptions{FeatMarker: trackparse.Ptr("ft.")}
trackparse.TracklistOptions{AudioSeconds: trackparse.Ptr(3600.0)}
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
// A pointer to 0 is an audio of length 0, as audioSeconds: 0 in JavaScript.
list := trackparse.ParseTracklistWith("00:00 A - B\n00:30 C - D", trackparse.TracklistOptions{
AudioSeconds: trackparse.Ptr(0.0),
})
for _, w := range list.Warnings {
fmt.Println(w.Code, w.Line)
}
track := trackparse.Parse("Wilkinson ft. Becky Hill - Afterglow")
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{FeatMarker: trackparse.Ptr("with")}))
}
Output: time-after-audio-end 2 Wilkinson with Becky Hill - Afterglow
Types ¶
type Artist ¶
type Artist struct {
// Name is the name as written, trimmed.
Name string
// Role is what the artist did on the track.
Role Role
// Joiner is the raw joiner or marker text that preceded the name in its credit list; nil
// for the first name of a list.
Joiner *string
// Source is where in the string the artist was found.
Source Source
}
Artist is one credited artist.
func AllArtists ¶
AllArtists is every artist of the track, the version credits (remixers) included, in the order written and without duplicates.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
track := trackparse.Parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)")
for _, a := range trackparse.AllArtists(track) {
fmt.Printf("%s:%s\n", a.Name, a.Role)
}
}
Output: Wilkinson:primary Becky Hill:featured Sub Focus:remixer
func ParseArtists ¶
ParseArtists splits an artist credit string into artists (R10), with the default options.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
for _, a := range trackparse.ParseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo") {
joiner := "<nil>"
if a.Joiner != nil {
joiner = *a.Joiner
}
fmt.Printf("%s:%s joiner=%s\n", a.Name, a.Role, joiner)
}
}
Output: Sub Focus:primary joiner=<nil> Wilkinson:primary joiner=, Dimension:primary joiner=& Kojo:featured joiner=feat.
func ParseArtistsWith ¶
func ParseArtistsWith(input string, options ParseOptions) []Artist
ParseArtistsWith is ParseArtists with options.
func (Artist) MarshalJSON ¶
MarshalJSON writes the spec's JSON form: camelCase keys in the schema's order, every key present. The bytes are those of JSON.stringify in the JavaScript package.
type Delimiter ¶
type Delimiter string
Delimiter is how a version was written: in a bracket group, or after a dash.
const ( DelimiterParen Delimiter = "(" DelimiterSquare Delimiter = "[" DelimiterCurly Delimiter = "{" DelimiterDash Delimiter = "-" )
The version delimiters.
func AllDelimiters ¶
func AllDelimiters() []Delimiter
AllDelimiters returns every Delimiter, in the spec's order. Each call returns a new slice.
type Edit ¶
type Edit struct {
// Op is the operation.
Op EditOp
// Line is the line to change (set-time, set-rest, delete).
Line int
// Seconds is the new time (set-time) or the amount to add (shift; negative moves back).
Seconds float64
// Lines limits a shift to these lines. Nil means not given; an empty non-nil slice shifts
// no line.
Lines []int
// From limits a shift to this line and the ones after it. Nil means not given.
From *int
// Rest is the new text after the time and gap (set-rest).
Rest string
// After is the line to insert after; 0 inserts at the start (insert).
After int
// Text is the new line, without a terminator (insert).
Text string
}
Edit is one edit of a tracklist text (R13.9). Line numbers are 1-based and refer to the text as the previous edit left it. Build one with SetTime, Shift, ShiftFrom, ShiftLines, SortByTime, SetRest, Insert or Delete; each operation reads only its own fields. An edit that cannot be applied changes nothing and is reported as EditWarningCodeEditInvalid.
func Insert ¶
Insert is the edit that inserts text as a new line after line after (0: at the start).
func SetTime ¶
SetTime is the edit that rewrites the time of line, keeping its written style (R13.9.2).
func ShiftLines ¶
ShiftLines is the edit that adds seconds to the given lines only.
func SortByTime ¶
func SortByTime() Edit
SortByTime is the edit that sorts the timed lines stably, each with the untimed lines after it (R13.9.4).
func (Edit) MarshalJSON ¶
MarshalJSON writes the edit as the spec does ({"op":"set-time","line":3,"seconds":90}), with only the fields of its operation.
type EditOp ¶
type EditOp string
EditOp names the operation of an Edit (R13.9).
const ( EditOpSetTime EditOp = "set-time" EditOpShift EditOp = "shift" EditOpSortByTime EditOp = "sort-by-time" EditOpSetRest EditOp = "set-rest" EditOpInsert EditOp = "insert" EditOpDelete EditOp = "delete" )
The edit operations.
func AllEditOps ¶
func AllEditOps() []EditOp
AllEditOps returns every EditOp, in the spec's order. Each call returns a new slice.
type EditResult ¶
type EditResult struct {
// Text is the edited text.
Text string
// Changed are the line numbers (in the final text) of lines an edit wrote; sorted, unique.
Changed []int
// Warnings has one warning per edit that could not be applied as asked.
Warnings []EditWarning
}
EditResult is the result of ApplyEdits.
func ApplyEdits ¶
func ApplyEdits(text string, edits []Edit) EditResult
ApplyEdits applies edits to a tracklist text (R13.9), in order, each to the result of the previous one. Lines no edit wrote stay byte-identical, after invalid UTF-8 is replaced (each maximal ill-formed subpart becomes one U+FFFD, as in every function). An edit that cannot be applied changes nothing and is reported as EditWarningCodeEditInvalid.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
text := "48:20 Noisia - Stigma\r\n59:31 Alix Perez - Fade Away\r\n00:03:10 Imanu - Sacrifice\r\n"
result := trackparse.ApplyEdits(text, []trackparse.Edit{
trackparse.SetTime(3, 3790),
trackparse.ShiftFrom(45, 2),
})
fmt.Printf("%q\n", result.Text)
fmt.Println(result.Changed)
w := result.Warnings[0]
fmt.Println(w.Code, w.Edit, *w.Line)
result = trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.ShiftLines(-3000, 1)})
fmt.Println(result.Warnings[0].Code)
result = trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.Delete(9)})
fmt.Println(result.Warnings[0].Code, result.Text == text)
}
Output: "48:20 Noisia - Stigma\r\n01:00:16 Alix Perez - Fade Away\r\n01:03:55 Imanu - Sacrifice\r\n" [2 3] style-upgraded 1 2 time-clamped edit-invalid true
func ApplyEditsWith ¶
func ApplyEditsWith(text string, edits []Edit, options TracklistOptions) EditResult
ApplyEditsWith is ApplyEdits with options. The options are accepted for symmetry with the other ports (R13.10); edits do not depend on them today.
func (EditResult) MarshalJSON ¶
func (r EditResult) MarshalJSON() ([]byte, error)
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type EditWarning ¶
type EditWarning struct {
// Code is what happened.
Code EditWarningCode
// Edit is the index of the edit in the edits slice.
Edit int
// Line is the line concerned; for edit-invalid the edit's own line (or after), which may
// not exist in the text. Edits pass their line numbers through float64, as JavaScript
// numbers do, so a line beyond 2^53 in magnitude comes back rounded to a float64 value
// (Delete(1<<53 + 1) is reported as line 9007199254740992).
Line *int
}
EditWarning is a warning about one edit.
func (EditWarning) MarshalJSON ¶
func (x EditWarning) MarshalJSON() ([]byte, error)
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type EditWarningCode ¶
type EditWarningCode string
EditWarningCode is the code of an edit warning (R13.9).
const ( EditWarningCodeEditInvalid EditWarningCode = "edit-invalid" EditWarningCodeTimeClamped EditWarningCode = "time-clamped" EditWarningCodeStyleUpgraded EditWarningCode = "style-upgraded" )
The edit warning codes.
func AllEditWarningCodes ¶
func AllEditWarningCodes() []EditWarningCode
AllEditWarningCodes returns every EditWarningCode, in the spec's order. Each call returns a new slice.
type Entry ¶
type Entry struct {
// Line is the 1-based line number.
Line int
// Kind is what the line is.
Kind EntryKind
// Eol is the line terminator that followed it.
Eol Eol
// Raw is the line as written, without its terminator. Never normalized.
Raw string
// Parts is Raw cut into lead, time, gap and rest.
Parts Parts
// Time is the line's time, if it has a valid one.
Time *TracklistTime
// Track is the parse of the line text, for track and marker entries.
Track *Track
// Layered is true when the line's text after any time starts with w/: a track played over
// the previous one (R13.13).
Layered bool
}
Entry is one line of a tracklist.
func (Entry) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type EntryKind ¶
type EntryKind string
EntryKind is what a line of a tracklist is (R13.3).
const ( EntryKindTrack EntryKind = "track" EntryKindMarker EntryKind = "marker" EntryKindHeader EntryKind = "header" EntryKindLink EntryKind = "link" EntryKindNote EntryKind = "note" EntryKindBlank EntryKind = "blank" )
The entry kinds.
func AllEntryKinds ¶
func AllEntryKinds() []EntryKind
AllEntryKinds returns every EntryKind, in the spec's order. Each call returns a new slice.
type Eol ¶
type Eol string
Eol is the line terminator that followed a line (R13.1.1). The value is the terminator itself; EolNone is the empty string, for a last line without one.
The line terminators.
type FeatPlacement ¶
type FeatPlacement string
FeatPlacement is where FormatWith writes featured artists (R11.2). The zero value means FeatSource.
const ( FeatSource FeatPlacement = "source" FeatArtist FeatPlacement = "artist" FeatTitle FeatPlacement = "title" FeatOmit FeatPlacement = "omit" )
The FeatPlacement values. Any other string places featured artists nowhere, as in the JavaScript package.
type Flags ¶
type Flags struct {
// Explicit is true when the track is marked Explicit or Dirty.
Explicit bool
// Clean is true when the track is marked Clean.
Clean bool
// UnknownArtist is true when the artist is a placeholder (ID, Unknown Artist).
UnknownArtist bool
// UnknownTitle is true when the title is a placeholder (ID, Untitled).
UnknownTitle bool
}
Flags are yes/no facts about the track.
func (Flags) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type FormatOptions ¶
type FormatOptions struct {
// Feat is where featured artists go; the zero value means [FeatSource] (where they were
// found).
Feat FeatPlacement
// FeatMarker is the marker written in front of featured lists instead of the one in the
// input. Nil means the input's marker; a pointer to "" writes an empty marker, as the
// JavaScript option featMarker: "" does. Set it with [Ptr].
FeatMarker *string
// Joiners is the joiner style; the zero value means [JoinersOriginal].
Joiners JoinerStyle
// Versions is whether versions are written; the zero value means [VersionsAll].
Versions VersionsOption
// OmitProducers leaves out the prod. credits (the JavaScript option producers: false).
OmitProducers bool
// Position writes the position in front.
Position bool
}
FormatOptions are the options of FormatWith (R11). The zero value is what Format uses.
type JoinerStyle ¶
type JoinerStyle string
JoinerStyle is whether FormatWith writes joiners as written or in their canonical form (R11.5). The zero value means JoinersOriginal.
const ( JoinersOriginal JoinerStyle = "original" JoinersCanonical JoinerStyle = "canonical" )
The JoinerStyle values. Any other string behaves as JoinersOriginal.
type Junk ¶
type Junk struct {
// Raw is the fragment as written, without its brackets.
Raw string
// Kind is what kind of noise it is.
Kind JunkKind
}
Junk is a fragment that says nothing about the track: Official Video, HD, Free Download. It is taken out of the title and kept here (the parser extracts, it does not delete).
func (Junk) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type JunkKind ¶
type JunkKind string
JunkKind is what kind of noise a junk fragment is (R5). A junk phrase added through Keywords can carry any string, which the output keeps as given.
const ( JunkKindVideo JunkKind = "video" JunkKindAudio JunkKind = "audio" JunkKindLyrics JunkKind = "lyrics" JunkKindQuality JunkKind = "quality" JunkKindPromo JunkKind = "promo" JunkKindPlatform JunkKind = "platform" JunkKindLabel JunkKind = "label" JunkKindGenre JunkKind = "genre" JunkKindOther JunkKind = "other" )
The junk kinds of the spec.
func AllJunkKinds ¶
func AllJunkKinds() []JunkKind
AllJunkKinds returns the junk kinds of the spec, in the spec's order. Each call returns a new slice.
type JunkPhrase ¶
type JunkPhrase struct {
// Phrase is the phrase, matched with ASCII lowercasing.
Phrase string
// Kind is the junk kind it gives. Any string is kept as given in the output.
Kind JunkKind
}
JunkPhrase is an extra junk phrase and its kind, such as JunkPhrase{Phrase: "out now", Kind: JunkKindPromo}.
type Keywords ¶
type Keywords struct {
// VersionHeads are extra version heads.
VersionHeads []VersionHead
// Descriptors are extra descriptor words (Extended, Deluxe).
Descriptors []string
// Genres are extra genre names.
Genres []string
// Junk are extra junk phrases.
Junk []JunkPhrase
// FeatMarkers are extra markers that introduce featured artists.
FeatMarkers []string
}
Keywords is extra vocabulary, added to the built-in word lists (R12). The two maps of the JavaScript options are ordered slices here: a repeated key keeps its first place and takes the last value, and integer-like keys come first in ascending order, exactly as JavaScript reads an object.
type Mode ¶
type Mode string
Mode is the mode a string is parsed in (R2). In a Track it is clean, youtube, filename or tracklist, never auto. In ParseOptions and TracklistOptions, ModeAuto asks the parser to pick one (auto never resolves to tracklist, R13.6), and the empty string means the option's default: auto for a parse, tracklist for a tracklist.
const ( ModeAuto Mode = "auto" ModeClean Mode = "clean" ModeYouTube Mode = "youtube" ModeFilename Mode = "filename" ModeTracklist Mode = "tracklist" )
The modes. Any other string in an option behaves as the JavaScript package does with an unknown mode: no youtube detection, filenames still detected.
type ParseOptions ¶
type ParseOptions struct {
// Mode is the mode; the zero value means [ModeAuto], which picks one from the string.
Mode Mode
// Uploader is the channel name, used in youtube mode as the artist when the title has no
// separator (R6.8). Empty means none.
Uploader string
// KnownArtists are names that must never be split (R7.3a): Chase & Status, Above & Beyond.
KnownArtists []string
// SplitAnd is when "and" splits a credit list; the zero value means [SplitAndAuto].
SplitAnd SplitAnd
// Keywords is extra vocabulary.
Keywords Keywords
}
ParseOptions are the options of ParseWith, ParseArtistsWith and NewParser (R12). The zero value is what Parse uses.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser parses with fixed options, compiled once. It is safe for concurrent use. The zero Parser uses the default options.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
parser := trackparse.NewParser(trackparse.ParseOptions{
KnownArtists: []string{"Chase & Status", "Camo & Krooked"},
Keywords: trackparse.Keywords{
VersionHeads: []trackparse.VersionHead{{Key: "rerub", Type: trackparse.VersionTypeRework}},
},
})
track := parser.Parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)")
fmt.Println(len(track.Artists), track.Artists[0].Name, track.Artists[1].Name)
fmt.Println(track.Versions[0].Type)
// The zero Parser uses the default options.
var plain trackparse.Parser
fmt.Println(len(plain.Parse("Chase & Status - Baddadan").Artists))
}
Output: 2 Chase & Status Camo & Krooked rework 2
func NewParser ¶
func NewParser(options ParseOptions) *Parser
NewParser compiles options (R12) into a Parser.
func (*Parser) ParseArtists ¶
ParseArtists splits an artist credit string with the parser's options (R10).
type Parts ¶
type Parts struct {
// Lead is what stands before the time: indentation, a bullet, an opening bracket.
Lead string
// Time is the time as written, without brackets; empty when the line has none.
Time string
// Gap is what stands between the time and the rest: a closing bracket, whitespace, a
// separator.
Gap string
// Rest is everything after that.
Rest string
}
Parts is a line cut into four pieces that join back to it: Lead + Time + Gap + Rest is the raw line (R13.1.3).
func (Parts) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type Position ¶
type Position struct {
// Raw is the number as written, without the separator after it.
Raw string
// Number is its value.
Number int
}
Position is a track number in front of the string (R4.2).
func (Position) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type Role ¶
type Role string
Role is what an artist did on the track (R7).
type Severity ¶
type Severity string
Severity is how serious a tracklist warning is.
func AllSeverities ¶
func AllSeverities() []Severity
AllSeverities returns every Severity, in the spec's order. Each call returns a new slice.
type Source ¶
type Source string
Source is where in the string an artist was found: the artist side, the title side, or a version group.
const ( SourceArtist Source = "artist" SourceTitle Source = "title" SourceVersion Source = "version" )
The artist sources.
func AllSources ¶
func AllSources() []Source
AllSources returns every Source, in the spec's order. Each call returns a new slice.
type SplitAnd ¶
type SplitAnd string
SplitAnd is when the word "and" splits a credit list (R7.3). "&" and the other joiners always split. The zero value means SplitAndAuto.
const ( SplitAndAuto SplitAnd = "auto" SplitAndAlways SplitAnd = "always" SplitAndNever SplitAnd = "never" )
The SplitAnd values. In ParseOptions any other string behaves as SplitAndAlways, as in the JavaScript package; in TracklistOptions it behaves as SplitAndAuto.
type Stats ¶
type Stats struct {
// Lines is the number of lines (entries).
Lines int
// Tracks is the number of track entries.
Tracks int
// Markers is the number of marker entries.
Markers int
// Timed is the number of entries with a time.
Timed int
// FirstTime is the time of the first timed entry, in seconds.
FirstTime *float64
// LastTime is the time of the last timed entry, in seconds.
LastTime *float64
}
Stats are counts over a tracklist.
func (Stats) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type Suggestion ¶
type Suggestion struct {
// Line is the line to change.
Line int
// Raw is the time to write there.
Raw string
// Seconds is that time in seconds.
Seconds float64
}
Suggestion is a fix for a time-out-of-order warning that changes one or two digits (R13.7).
func (Suggestion) MarshalJSON ¶
func (s Suggestion) MarshalJSON() ([]byte, error)
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type Timestamp ¶
type Timestamp struct {
// Raw is the time as written, without brackets.
Raw string
// Seconds is the time in seconds.
Seconds int
}
Timestamp is a cue time in front of a single track string (R4.1), in whole seconds.
func (Timestamp) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type Track ¶
type Track struct {
// Input is the string that was parsed, unchanged.
Input string
// Mode is the mode it was parsed in; never [ModeAuto].
Mode Mode
// Position is a leading track number.
Position *Position
// Timestamp is a leading cue time.
Timestamp *Timestamp
// Artists are the primary, featured and producer credits, in the order written. Remixers
// are in Versions; [AllArtists] gives both.
Artists []Artist
// Title is the title without versions, featured credits and junk.
Title string
// FullTitle is the title with its versions, as written.
FullTitle string
// Versions are the remixes, edits and other versions, in the order written.
Versions []Version
// Year is a release year found outside the versions.
Year *int
// Flags are yes/no facts.
Flags Flags
// Junk are the fragments that say nothing about the track.
Junk []Junk
// Warnings are guesses the caller may want to check.
Warnings []Warning
}
Track is the result of Parse: everything recognized in one track string. Anything recognized is in a field; anything not recognized stays in Title verbatim.
func Parse ¶
Parse parses one track string with the default options.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
track := trackparse.Parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)")
v := track.Versions[0]
fmt.Println(track.Artists[0].Name, "/", track.Title)
fmt.Println(v.Type, v.Raw, v.Delimiter)
fmt.Println(*v.Descriptor, *v.Year)
fmt.Println(track.Year == nil, len(track.Warnings))
}
Output: Queen / Bohemian Rhapsody live Live at Wembley 1986 ( at Wembley 1986 true 0
func ParseWith ¶
func ParseWith(input string, options ParseOptions) Track
ParseWith parses one track string with options (R12). To parse many strings with the same options, build a Parser once instead: the options' tables are compiled per call here.
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
names := func(t trackparse.Track) []string {
var out []string
for _, a := range t.Artists {
out = append(out, a.Name)
}
return out
}
fmt.Println(names(trackparse.Parse("Chase & Status - Baddadan")))
fmt.Println(names(trackparse.ParseWith("Chase & Status - Baddadan", trackparse.ParseOptions{
KnownArtists: []string{"Chase & Status"},
})))
track := trackparse.ParseWith(`"Numb" by Linkin Park`, trackparse.ParseOptions{
Mode: trackparse.ModeYouTube,
})
fmt.Println(names(track), track.Title, track.Warnings)
track = trackparse.ParseWith("Shelter", trackparse.ParseOptions{
Mode: trackparse.ModeYouTube,
Uploader: "Porter Robinson",
})
fmt.Println(names(track), track.Title)
}
Output: [Chase Status] [Chase & Status] [Linkin Park] Numb [bySplit] [Porter Robinson] Shelter
Example (Keywords) ¶
Keywords add words to the built-in lists.
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
fmt.Println(trackparse.Parse("Artist - Song [Some Label Rip]").Title)
track := trackparse.ParseWith("Artist - Song [Some Label Rip]", trackparse.ParseOptions{
Keywords: trackparse.Keywords{
Junk: []trackparse.JunkPhrase{{Phrase: "some label rip", Kind: trackparse.JunkKindLabel}},
},
})
fmt.Println(track.Title)
fmt.Println(track.Junk[0].Raw, track.Junk[0].Kind)
}
Output: Song [Some Label Rip] Song Some Label Rip label
func (Track) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON). Track.UnmarshalJSON reads it back.
Example ¶
package main
import (
"encoding/json"
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
track := trackparse.Parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus VIP Remix) [HD]")
b, err := json.Marshal(track)
if err != nil {
panic(err)
}
fmt.Println(string(b))
var back trackparse.Track
if err := json.Unmarshal(b, &back); err != nil {
panic(err)
}
fmt.Println(back.FullTitle, back.Versions[0].Artists[0].Name)
}
Output: {"input":"Wilkinson ft. Becky Hill - Afterglow (Sub Focus VIP Remix) [HD]","mode":"youtube","position":null,"timestamp":null,"artists":[{"name":"Wilkinson","role":"primary","joiner":null,"source":"artist"},{"name":"Becky Hill","role":"featured","joiner":"ft.","source":"artist"}],"title":"Afterglow","fullTitle":"Afterglow (Sub Focus VIP Remix)","versions":[{"type":"remix","raw":"Sub Focus VIP Remix","artists":[{"name":"Sub Focus","role":"remixer","joiner":null,"source":"version"}],"modifiers":["vip"],"descriptor":null,"year":null,"unknownArtist":false,"delimiter":"("}],"year":null,"flags":{"explicit":false,"clean":false,"unknownArtist":false,"unknownTitle":false},"junk":[{"raw":"HD","kind":"quality"}],"warnings":[]} Afterglow (Sub Focus VIP Remix) Sub Focus
Example (EscapeHTML) ¶
encoding/json escapes <, > and & (and U+2028, U+2029) in what MarshalJSON returns. An Encoder with SetEscapeHTML(false) keeps the bytes JSON.stringify writes.
package main
import (
"bytes"
"encoding/json"
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
track := trackparse.Parse("Chase & Status - Baddadan")
b, _ := json.Marshal(track.Artists[1])
fmt.Println(string(b))
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
_ = enc.Encode(track.Artists[1])
fmt.Print(buf.String())
b, _ = track.Artists[1].MarshalJSON()
fmt.Println(string(b))
}
Output: {"name":"Status","role":"primary","joiner":"\u0026","source":"artist"} {"name":"Status","role":"primary","joiner":"&","source":"artist"} {"name":"Status","role":"primary","joiner":"&","source":"artist"}
func (*Track) UnmarshalJSON ¶
UnmarshalJSON reads the spec's JSON form of a track, as Track.MarshalJSON writes it. Unknown keys are ignored and missing keys keep their zero value; a key of the wrong type is an error. Enum values are taken as written.
type Tracklist ¶
type Tracklist struct {
// SpecVersion is the version of the spec the result follows.
SpecVersion string
// Entries has one entry per line, in order.
Entries []Entry
// Warnings are ordered by line.
Warnings []TracklistWarning
// Stats are the counts.
Stats Stats
}
Tracklist is the result of ParseTracklist: one entry per line, the warnings and the counts. The entries' Raw and Eol, joined, are the text again (R13.1.2).
func ParseTracklist ¶
ParseTracklist parses a multi-line tracklist with the default options (R13). The text is split at LF, CRLF and CR only; every line becomes one entry, and the entries' Raw and Eol, joined, are the text again (R13.1.2).
Example ¶
package main
import (
"fmt"
"strings"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
text := strings.Join([]string{
"Hour 2",
"48:20 Noisia - Stigma",
"52:47 Mefjus & Kasra - Bandwagon (Phace Remix)",
"56:05 Black Sun Empire - ID",
"59:31 Alix Perez - Fade Away",
"01:03:10 Interview with Hybris",
"01:07:44 Imanu - Sacrifice",
"00:11:02 Current Value feat. Teddy Killerz - Payload", // typo for 01:11:02
"01:15:36 Hybris - Spinning Top",
}, "\r\n")
list := trackparse.ParseTracklist(text)
var joined strings.Builder
var kinds []trackparse.EntryKind
for _, e := range list.Entries {
joined.WriteString(e.Raw + string(e.Eol))
kinds = append(kinds, e.Kind)
}
fmt.Println(joined.String() == text)
fmt.Println(kinds)
e := list.Entries[2]
fmt.Println(e.Time.Raw, e.Time.Seconds)
fmt.Printf("%q\n", e.Parts.Rest)
fmt.Println(len(e.Track.Artists), e.Track.Title, e.Track.Versions[0].Type)
fmt.Println(list.Entries[3].Track.Flags.UnknownTitle)
for _, w := range list.Warnings {
fmt.Println(w.Code, w.Line, w.Severity)
if s := w.Suggestion; s != nil {
fmt.Println(" suggestion:", s.Line, s.Raw, s.Seconds)
}
}
s := list.Stats
fmt.Println(s.Lines, s.Tracks, s.Markers, s.Timed, *s.FirstTime, *s.LastTime)
}
Output: true [header track track track track marker track track track] 52:47 3167 "Mefjus & Kasra - Bandwagon (Phace Remix)" 2 Bandwagon remix true no-start-at-zero 2 info time-out-of-order 8 warning suggestion: 8 01:11:02 4262 9 7 1 8 2900 4536
func ParseTracklistWith ¶
func ParseTracklistWith(text string, options TracklistOptions) Tracklist
ParseTracklistWith is ParseTracklist with options (R13.10).
Example ¶
package main
import (
"fmt"
trackparse "github.com/4matic/trackparse/go"
)
func main() {
list := trackparse.ParseTracklistWith("00:00 A - B\n1:02:03 C - D", trackparse.TracklistOptions{
AudioSeconds: trackparse.Ptr(3600.0),
})
fmt.Println(list.Warnings[0].Code, list.Warnings[0].Line)
}
Output: time-after-audio-end 2
func (Tracklist) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type TracklistOptions ¶
type TracklistOptions struct {
// Mode is the per-line parse mode; the zero value means [ModeTracklist]. [ModeAuto] picks
// a mode per line.
Mode Mode
// KnownArtists are names that must never be split (R7.3a).
KnownArtists []string
// SplitAnd is when "and" splits a credit list; the zero value means [SplitAndAuto].
SplitAnd SplitAnd
// Keywords is extra vocabulary for the per-line parse.
Keywords Keywords
// AudioSeconds is the length of the audio in seconds; it enables time-after-audio-end.
// Nil means unknown, and so do negative and non-finite values. A pointer to 0 is an audio
// of length 0, as the JavaScript option audioSeconds: 0. Set it with [Ptr].
AudioSeconds *float64
// MarkerWords are extra marker words (R13.3): a line that is only such a word is a marker.
MarkerWords []string
}
TracklistOptions are the options of ParseTracklistWith and ApplyEditsWith (R13.10). The zero value is what ParseTracklist uses.
type TracklistTime ¶
type TracklistTime struct {
// Raw is the time as written, without brackets.
Raw string
// Seconds is the time in seconds; it may carry a fraction. A whole value is an integer in
// JSON.
Seconds float64
}
TracklistTime is the time of a tracklist line (R13.2.5).
func (TracklistTime) MarshalJSON ¶
func (t TracklistTime) MarshalJSON() ([]byte, error)
MarshalJSON writes the spec's JSON form; a whole number of seconds is an integer.
type TracklistWarning ¶
type TracklistWarning struct {
// Code is what is wrong.
Code WarningCode
// Line is the 1-based line it is about.
Line int
// Severity is how serious it is.
Severity Severity
// Suggestion is a fix, for time-out-of-order when exactly one small change repairs the
// order.
Suggestion *Suggestion
}
TracklistWarning is a warning about a tracklist (R13.7).
func (TracklistWarning) MarshalJSON ¶
func (x TracklistWarning) MarshalJSON() ([]byte, error)
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type Version ¶
type Version struct {
// Type is the version type.
Type VersionType
// Raw is the version text as written, without its brackets.
Raw string
// Artists are who made it (role remixer); empty for versions without a credit.
Artists []Artist
// Modifiers are the other version words of the group, as lowercase keys ("extended" in
// "Extended Remix").
Modifiers []string
// Descriptor is free text of the version that is neither a credit nor a keyword.
Descriptor *string
// Year is a year written inside the version.
Year *int
// UnknownArtist is true when the credit is a placeholder such as ID or Unknown.
UnknownArtist bool
// Delimiter is how the version was written.
Delimiter Delimiter
}
Version is one version of the track: a remix, an edit, a live take, a remaster (R5, R8).
func (Version) MarshalJSON ¶
MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).
type VersionHead ¶
type VersionHead struct {
// Key is the word or phrase, matched with ASCII lowercasing.
Key string
// Type is the version type it gives. Any string is kept as given in the output.
Type VersionType
}
VersionHead is an extra version head word and the version type it means, such as VersionHead{Key: "rerub", Type: VersionTypeRework}.
type VersionType ¶
type VersionType string
VersionType is the type of a version (R5): remix, edit, live, remaster and so on. A version head added through Keywords can carry any string, which the output keeps as given.
const ( VersionTypeRemix VersionType = "remix" VersionTypeBootleg VersionType = "bootleg" VersionTypeVIP VersionType = "vip" VersionTypeEdit VersionType = "edit" VersionTypeFlip VersionType = "flip" VersionTypeRefix VersionType = "refix" VersionTypeRework VersionType = "rework" VersionTypeMashup VersionType = "mashup" VersionTypeBlend VersionType = "blend" VersionTypeDub VersionType = "dub" VersionTypeMix VersionType = "mix" VersionTypeExtended VersionType = "extended" VersionTypeRadio VersionType = "radio" VersionTypeClub VersionType = "club" VersionTypeOriginal VersionType = "original" VersionTypeInstrumental VersionType = "instrumental" VersionTypeAcapella VersionType = "acapella" VersionTypeLive VersionType = "live" VersionTypeAcoustic VersionType = "acoustic" VersionTypeRemaster VersionType = "remaster" VersionTypeDemo VersionType = "demo" VersionTypeReprise VersionType = "reprise" VersionTypeCover VersionType = "cover" VersionTypeVersion VersionType = "version" VersionTypeSpedUp VersionType = "spedUp" VersionTypeSlowed VersionType = "slowed" VersionTypeNightcore VersionType = "nightcore" )
The version types of the spec.
func AllVersionTypes ¶
func AllVersionTypes() []VersionType
AllVersionTypes returns the 27 version types of the spec, in the spec's order. Each call returns a new slice.
type VersionsOption ¶
type VersionsOption string
VersionsOption is whether FormatWith writes the versions (R11.3). The zero value means VersionsAll.
const ( VersionsAll VersionsOption = "all" VersionsNone VersionsOption = "none" )
The VersionsOption values. Any other string behaves as VersionsNone, as in the JavaScript package.
type Warning ¶
type Warning string
Warning is a warning of the single-track parser: the result is a guess the caller may want to check.
const ( WarningNoSeparator Warning = "noSeparator" WarningAmbiguousSeparator Warning = "ambiguousSeparator" WarningUnspacedDashSplit Warning = "unspacedDashSplit" WarningAsymmetricDashSplit Warning = "asymmetricDashSplit" WarningBySplit Warning = "bySplit" WarningQuotedTitleSplit Warning = "quotedTitleSplit" WarningAmbiguousMixCredit Warning = "ambiguousMixCredit" WarningUnbalancedBrackets Warning = "unbalancedBrackets" )
The track warnings.
func AllWarnings ¶
func AllWarnings() []Warning
AllWarnings returns every Warning, in the spec's order. Each call returns a new slice.
type WarningCode ¶
type WarningCode string
WarningCode is the code of a tracklist warning (R13.7).
const ( WarningCodeTimeMissing WarningCode = "time-missing" WarningCodeTimeOutOfOrder WarningCode = "time-out-of-order" WarningCodeTimeDuplicate WarningCode = "time-duplicate" WarningCodeNoStartAtZero WarningCode = "no-start-at-zero" WarningCodeTimeAfterAudioEnd WarningCode = "time-after-audio-end" WarningCodeInvalidTime WarningCode = "invalid-time" WarningCodePositionGap WarningCode = "position-gap" WarningCodePositionDuplicate WarningCode = "position-duplicate" WarningCodeLineUnparsed WarningCode = "line-unparsed" )
The tracklist warning codes, in the table order of the spec.
func AllWarningCodes ¶
func AllWarningCodes() []WarningCode
AllWarningCodes returns every WarningCode, in the spec's order. Each call returns a new slice.
Source Files
¶
- artists.go
- assemble.go
- classify.go
- context.go
- credits.go
- data_gen.go
- digits.go
- doc.go
- format.go
- json.go
- mode.go
- normalize.go
- options.go
- parser.go
- prefix.go
- scanner.go
- separator.go
- tables.go
- title.go
- tl_edits.go
- tl_emphasis.go
- tl_kinds.go
- tl_options.go
- tl_parse.go
- tl_positions.go
- tl_split.go
- tl_times.go
- tl_warnings.go
- trackparse.go
- types.go
- unicode.go
- unicode_gen.go
- wire.go
- words.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
cmd/dump
command
Command dump is the Go side of the cross-port diff (scripts/compare-ports.mjs): JSONL in, JSON out.
|
Command dump is the Go side of the cross-port diff (scripts/compare-ports.mjs): JSONL in, JSON out. |
|
wire
Package wire is the JSON door into trackparse: every public function called with loose JSON arguments, returning JSON.
|
Package wire is the JSON door into trackparse: every public function called with loose JSON arguments, returning JSON. |