GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Why Go
  • Case Studies
  • Use Cases
  • Security
  • Learn
  • Effective Go
  • Go User Manual
  • Standard library
  • Release Notes
  • API
  • Packages
  • Recorded Talks
  • Meetups
  • Conferences

This view

  • Original page
  • New address

GeezerVison is showing pkg.go.dev — trackparse package - github.com/4matic/trackparse/go - Go Packages

Details

  • checked Valid go.mod file

    The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.

  • checked Redistributable license

    Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.

  • checked Tagged version

    Modules with tagged versions give importers more predictable builds.

  • unchecked Stable version

    When a project reaches major version v1 it is considered stable.

  • Learn more about best practices

Repository

github.com/4matic/trackparse

Links

  • Open Source Insights Logo Open Source Insights
  • API documentation on pkg.go.dev
  • Changelog
  • Project README
  • GitHub repository

README ¶

trackparse

Go Reference Go version tests license

Documentation · Getting started · Playground · API on pkg.go.dev · Changelog

Turn messy track names into structured data: who made it, who's featured, who remixed it, and what's just noise.

01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]

Most title parsers split that into "Wilkinson ft. Becky Hill & Tom Cane" and "Afterglow (Sub Focus VIP Remix)" and stop. Others "clean" it and throw the feat and the remix away. trackparse keeps all of it. Everything it recognizes goes into a field, and anything it doesn't recognize stays in the title, word for word (try it in the playground).

This is the Go port of trackparse. Its behaviour is defined by a shared spec and pinned by 13,565 fixtures. It passes all of them, and for every fixture input its output is byte-identical to the JavaScript, Python, Rust and C packages.

  • Go 1.22 or later (the go line of go.mod; CI runs the tests on 1.22 and on the latest stable)
  • No dependencies: go.mod has no require line
  • No unsafe, no cgo, no regular expressions
  • Never panics and never returns an error: any string gives a result (Errors)

Install

go get github.com/4matic/trackparse/go@latest
import trackparse "github.com/4matic/trackparse/go"

The import path ends in /go because the module lives in the go/ folder of the repository, next to the other ports. The package name is trackparse, so the alias in the import line is optional; it only makes the name visible to readers and to tools that guess it from the path.

Quick start

Docs: Getting started

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)
}
// Wilkinson (primary)
// Becky Hill (featured)
// Tom Cane (featured)

fmt.Println(track.Title)                                     // Afterglow
fmt.Println(track.FullTitle)                                 // Afterglow (Sub Focus VIP Remix)
v := track.Versions[0]
fmt.Println(v.Type, v.Artists[0].Name, v.Modifiers)          // remix Sub Focus [vip]
fmt.Println(track.Junk[0].Raw, track.Junk[0].Kind)           // Official Video video
fmt.Println(track.Position.Number, track.Mode)               // 1 youtube

fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{
	Joiners: trackparse.JoinersCanonical,
}))
// Wilkinson feat. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)

json.Marshal gives the spec's JSON, with the same camelCase keys the JavaScript package uses (JSON has the details):

track := trackparse.Parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus VIP Remix) [HD]")
b, _ := json.Marshal(track)
fmt.Println(string(b))
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,
  "label": null,
  "flags": { "explicit": false, "clean": false, "unknownArtist": false, "unknownTitle": false },
  "junk": [{ "raw": "HD", "kind": "quality" }],
  "warnings": []
}

(Reformatted for width; the keys and values are exactly what json.Marshal returns.)

The examples on pkg.go.dev are Example functions in example_test.go, so go test checks their output.

API

Docs: Other functions

Parse(input string) Track
ParseWith(input string, options ParseOptions) Track
ParseArtists(input string) []Artist
ParseArtistsWith(input string, options ParseOptions) []Artist
Format(track Track) string
FormatWith(track Track, options FormatOptions) string
Normalize(input string) string
AllArtists(track Track) []Artist
NewParser(options ParseOptions) *Parser    // parser.Parse(..), parser.ParseArtists(..)
SpecVersion string

ParseTracklist(text string) Tracklist
ParseTracklistWith(text string, options TracklistOptions) Tracklist
ApplyEdits(text string, edits []Edit) EditResult
ApplyEditsWith(text string, edits []Edit, options TracklistOptions) EditResult

Every function has a plain form with the default options and a With form that takes them. Tracklists are in the same package; there is no subpackage. Each function has a section below, an entry on pkg.go.dev and a page in the API reference, where every example has a Go tab.

Parse and ParseOptions

Docs: parse and ParsedTrack · Options · Parse, ParseWith and ParseOptions on pkg.go.dev

Parses one track string, running rules R1 to R9 of the spec in order.

Field Zero value means
Mode ModeAuto ModeClean, ModeYouTube, ModeFilename, ModeTracklist, or ModeAuto to detect from the string. See Modes
Uploader none YouTube channel name, used as the artist when there's no separator (- Topic and VEVO are dropped)
KnownArtists none Names that are never split. There is no built-in list
SplitAnd SplitAndAuto SplitAndAuto splits on and only after a comma or semicolon (A, B and C), so Simon and Garfunkel stays whole. Also SplitAndAlways, SplitAndNever
Keywords none Extra vocabulary, added to the built-in lists (see below)

Options are plain structs, and the zero value of every struct is the default: Parse(s) is ParseWith(s, ParseOptions{}). Set only the fields you need.

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"))) // [Chase Status]
fmt.Println(names(trackparse.ParseWith("Chase & Status - Baddadan", trackparse.ParseOptions{
	KnownArtists: []string{"Chase & Status"},
}))) // [Chase & Status]
fmt.Println(names(trackparse.ParseWith("Simon and Garfunkel - Mrs. Robinson", trackparse.ParseOptions{
	SplitAnd: trackparse.SplitAndAlways,
}))) // [Simon Garfunkel]

Keywords adds words to the built-in lists (your own words):

Field Type
VersionHeads []VersionHead Word that sets a version type ({Key: "rerub", Type: VersionTypeRework})
Descriptors []string Words kept as a version's Descriptor
Genres []string Genre words
Junk []JunkPhrase Phrase to junk kind ({Phrase: "some label rip", Kind: JunkKindLabel})
FeatMarkers []string Extra feat markers

The two maps of the JavaScript options are ordered slices here. A key given twice keeps its first place and takes the last value, as in a JavaScript object.

fmt.Println(trackparse.Parse("Artist - Song [Some Label Rip]").Title) // Song [Some Label Rip]

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)                           // Song
fmt.Println(track.Junk[0].Raw, track.Junk[0].Kind) // Some Label Rip label
Pointer fields and Ptr

Every option value of the other ports has a Go spelling. Where the zero value of a field is also a value someone may want to pass, the field is a pointer, and nil means "not set":

  • FormatOptions.FeatMarker is a *string. nil keeps the input's marker; a pointer to "" writes an empty marker, as featMarker: "" does in JavaScript.
  • TracklistOptions.AudioSeconds is a *float64. nil means the length is unknown; a pointer to 0 is an audio of length 0, which flags every time after 0:00.

trackparse.Ptr(v) returns a pointer to a copy of v, so a literal fits in one expression: FormatOptions{FeatMarker: trackparse.Ptr("featuring")}, TracklistOptions{AudioSeconds: trackparse.Ptr(3600.0)}.

Mode is a string field whose zero value "" means the default of the function: ModeAuto ("auto") for ParseWith, ModeTracklist for ParseTracklistWith. Both constants can also be passed explicitly, so TracklistOptions{Mode: trackparse.ModeAuto} parses each line in auto mode.

Option values are typed strings, so a value outside the constants compiles. It behaves as the JavaScript package behaves with that value, as the doc comment of each type says: an unknown SplitAnd is SplitAndAlways in ParseOptions, an unknown Versions is VersionsNone, and so on. Nothing panics.

Track

Docs: ParsedTrack fields · Track on pkg.go.dev

Field Type
Input string The original string, untouched
Mode Mode Resolved mode: ModeClean, ModeYouTube, ModeFilename or ModeTracklist
Position *Position Track number: &Position{Raw: "01", Number: 1}
Timestamp *Timestamp Leading cue time: [12:34] gives &Timestamp{Raw: "12:34", Seconds: 754}
Artists []Artist Primary, featured and producer credits. Remixers live in Versions
Title string Clean title. Brackets it doesn't recognize stay in
FullTitle string Title with the versions re-attached
Versions []Version Remixes and other versions, left to right
Year *int From (2015) or - 2015
Label *string Record label after a spaced bullet: Stigma • VISION gives "VISION"
Flags Flags Explicit, Clean, UnknownArtist, UnknownTitle
Junk []Junk What was taken out, each with a Kind
Warnings []Warning Heuristics that fired

Fields that are null in JSON are pointers, nil when absent. Slices in a result from the parser are never nil, so they marshal as [].

Artist{Name, Role, Joiner, Source}:

  • Role is RolePrimary, RoleFeatured, RoleRemixer or RoleProducer.
  • Joiner is the text before the name as written ("&", ",", "ft.", "prod. by"), or nil for the first name in a list.
  • Source is where the credit came from: SourceArtist (left of the dash), SourceTitle (right of it) or SourceVersion.

Version{Type, Raw, Artists, Modifiers, Descriptor, Year, UnknownArtist, Delimiter}:

track := trackparse.Parse("Pendulum - Watercolour (Extended VIP Mix)")
v := track.Versions[0]
fmt.Println(v.Type, v.Raw, v.Modifiers, v.Delimiter) // vip Extended VIP Mix [extended] (

track = trackparse.Parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)")
v = track.Versions[0]
fmt.Println(v.Type, *v.Descriptor, *v.Year) // live at Wembley 1986

Version types, junk kinds, warnings, roles, modes and the tracklist codes are typed strings (type VersionType string) with one constant per spec name: VersionTypeRemix, JunkKindVideo, WarningNoSeparator, WarningCodeTimeOutOfOrder (the 27 version types, junk kinds). The value is the name used in the spec and in JSON, so string(v.Type) is "remix" and a switch on the constants works. A function per type returns every constant in the spec's order, as a new slice each time (AllVersionTypes(), AllJunkKinds(), AllWarnings(), ...):

fmt.Println(trackparse.VersionTypeSpedUp)        // spedUp
fmt.Println(len(trackparse.AllVersionTypes()))   // 27
fmt.Println(trackparse.AllRoles())               // [primary featured remixer producer]

A later spec version can add a version type or a warning, so a switch on them needs a default case. A version head or junk phrase added through Keywords can carry any string as its type or kind, and the result keeps that string as given.

JSON

Docs: Serializing to JSON

Every result type has MarshalJSON, which writes compact JSON matching parsed-track.schema.json and tracklist.schema.json: camelCase keys in the schema's order, every key present, whole seconds as integers (3167, not 3167.0). Its bytes are those of JSON.stringify(parse(s)) in JavaScript. Track also has UnmarshalJSON, which reads that form back; Edit marshals as the spec writes an edit ({"op":"set-time","line":3,"seconds":90}).

encoding/json changes some bytes of what MarshalJSON returns, not the values: json.Marshal escapes <, >, &, U+2028 and U+2029 ("&" becomes "\u0026"). For the exact JSON.stringify bytes, call MarshalJSON directly or use an Encoder with SetEscapeHTML(false) (which adds a newline after each value):

track := trackparse.Parse("Chase & Status - Baddadan")

b, _ := json.Marshal(track.Artists[1])
fmt.Println(string(b)) // {"name":"Status","role":"primary","joiner":"\u0026","source":"artist"}

enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.Encode(track.Artists[1]) // {"name":"Status","role":"primary","joiner":"&","source":"artist"}

b, _ = track.Artists[1].MarshalJSON()
fmt.Println(string(b)) // {"name":"Status","role":"primary","joiner":"&","source":"artist"}

UnmarshalJSON ignores unknown keys, leaves missing keys at their zero value, keeps enum values as written, and returns an error for a key of the wrong type. The options structs have no JSON methods.

ParseArtists

Docs: parseArtists · Artists and credits

Splits a bare artist string (no title) (R10). ParseArtistsWith takes the same options as ParseWith.

for _, a := range trackparse.ParseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo") {
	fmt.Printf("%s:%s\n", a.Name, a.Role)
}
// Sub Focus:primary
// Wilkinson:primary
// Dimension:primary
// Kojo:featured
Format and FormatOptions

Docs: format · Formatting

Renders a track back to a string (format options, R11): Format, FormatWith, FormatOptions.

Field Zero value means
Feat FeatSource Where featured artists go: FeatSource (where they were), FeatArtist, FeatTitle ((feat. X) after the title) or FeatOmit
FeatMarker nil: the input's marker Marker for featured artists, such as trackparse.Ptr("featuring"). A pointer to "" writes an empty marker
Joiners JoinersOriginal JoinersOriginal keeps the joiners as written. JoinersCanonical writes and as &, vs as vs. and every feat marker as feat.
Versions VersionsAll VersionsAll or VersionsNone
OmitProducers false Leave out (prod. ...) credits (producers: false in JavaScript)
Position false Include the track number (01. )
OmitLabel false Leave out the label after a spaced bullet, • VISION (label: false in JavaScript)
track := trackparse.Parse("01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)")

fmt.Println(trackparse.Format(track))
// Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{
	Feat:    trackparse.FeatTitle,
	Joiners: trackparse.JoinersCanonical,
}))
// Wilkinson - Afterglow (feat. Becky Hill) (Sub Focus Remix)
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{
	Feat:     trackparse.FeatOmit,
	Versions: trackparse.VersionsNone,
}))
// Wilkinson - Afterglow
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{Position: true}))
// 01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{FeatMarker: trackparse.Ptr("featuring")}))
// Wilkinson featuring Becky Hill - Afterglow (Sub Focus Remix)

track = trackparse.Parse("Noisia - concussion • VISION • VISION RADIO RELOAD")
fmt.Println(trackparse.Format(track))
// Noisia - concussion • VISION
fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{OmitLabel: true}))
// Noisia - concussion
Normalize

Docs: normalize

The Unicode cleanup every function runs first: NFC, zero-width spaces, BOM and soft hyphens removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed (R1). Running it twice changes nothing (Normalize).

fmt.Println(trackparse.Normalize("Noisia\u200b – Stigma (VIP)")) // Noisia - Stigma (VIP)
AllArtists

Docs: allArtists

Credits plus every remixer, deduplicated (R9, AllArtists).

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)
}
// Wilkinson:primary
// Becky Hill:featured
// Sub Focus:remixer
Parser

Docs: createParser

A Parser resolves the options and builds the word tables once, for many calls. ParseWith builds them on every call, so use a Parser when the options are the same each time.

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.Versions[0].Type) // 2 rework

var plain trackparse.Parser // the zero Parser uses the default options
fmt.Println(len(plain.Parse("Chase & Status - Baddadan").Artists)) // 2

A Parser is safe for concurrent use by many goroutines, and so are the package functions. The default tables are built once, on first use.

SpecVersion

Docs: SPEC_VERSION · SpecVersion on pkg.go.dev

The spec version this module implements. It equals the module version: the Go module, the npm package, the PyPI package, the Rust crate, the C library and the spec are released together and always share one version number.

Modes

Docs: Modes · R2 in the spec · Mode on pkg.go.dev

Mode For Adds
ModeClean Store metadata, tags Only a spaced dash separates artist and title
ModeYouTube Video titles, scrobbles Pipe segments, "Title" by Artist, Artist: "Title", unspaced dashes, trailing junk, uploader fallback
ModeFilename Files Strips the extension, _ becomes a space, 01-Track numbering
ModeAuto Anything ModeFilename for known extensions, ModeYouTube when it sees junk, pipes or platform suffixes, ModeClean otherwise
ModeTracklist One line of a tracklist The first spaced dash always separates; _-_ too. Never picked by ModeAuto
youtube := trackparse.ParseOptions{Mode: trackparse.ModeYouTube}
track := trackparse.ParseWith(`"Numb" by Linkin Park`, youtube)
fmt.Println(track.Artists[0].Name, "/", track.Title, track.Warnings) // Linkin Park / Numb [bySplit]

track = trackparse.Parse("07_Burial_-_Archangel.mp3")
fmt.Println(track.Mode, track.Artists[0].Name, track.Title, track.Position.Number) // filename Burial Archangel 7

youtube.Uploader = "Porter Robinson"
fmt.Println(trackparse.ParseWith("Shelter", youtube).Artists[0].Name) // Porter Robinson

Try "Numb" by Linkin Park in youtube mode or 07_Burial_-_Archangel.mp3 in the playground.

Warnings

Docs: Warnings · Warning on pkg.go.dev

The parser never fails, but it says when it had to guess. track.Warnings is a []Warning, empty when every decision was unambiguous.

Constant JSON name Means
WarningNoSeparator noSeparator No artist/title separator was found. The whole string is the title
WarningAmbiguousSeparator ambiguousSeparator A two-part pipe title with no dash was read as artist and title
WarningUnspacedDashSplit unspacedDashSplit Split at a dash without spaces around it
WarningAsymmetricDashSplit asymmetricDashSplit Split at a dash with a space on one side only
WarningBySplit bySplit Read "Title" by Artist
WarningQuotedTitleSplit quotedTitleSplit Took a quoted span as the title and the text before it as the artist
WarningAmbiguousMixCredit ambiguousMixCredit <Name> Mix was read as a remix, but the name is long enough to be a style
WarningUnbalancedBrackets unbalancedBrackets A bracket was opened and never closed
track := trackparse.Parse("Around the World")
fmt.Println(len(track.Artists), track.Title, track.Warnings) // 0 Around the World [noSeparator]
fmt.Println(track.Warnings[0] == trackparse.WarningNoSeparator) // true

fmt.Println(trackparse.Parse("Noisia - Stigma (VIP").Warnings) // [unbalancedBrackets]

Tracklists have their own warnings, with line numbers. They are listed under Tracklists.

Tracklists

Docs: Tracklists · Editing tracklists · Tracklist API · Warnings

ParseTracklist parses a whole tracklist, one entry per line, and checks it. Each entry keeps its line exactly as written plus its own line ending, so joining every Raw and Eol is always the input, CRLF or not.

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) // true
fmt.Println(kinds) // [header track track track track marker track track track]

e := list.Entries[2]
fmt.Println(e.Time.Raw, e.Time.Seconds) // 52:47 3167
fmt.Printf("%q\n", e.Parts.Rest) // "Mefjus & Kasra - Bandwagon (Phace Remix)"
fmt.Println(len(e.Track.Artists), e.Track.Title, e.Track.Versions[0].Type) // 2 Bandwagon remix
fmt.Println(list.Entries[3].Track.Flags.UnknownTitle) // true (the ID)

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)
	}
}
// no-start-at-zero 2 info
// time-out-of-order 8 warning
//   suggestion: 8 01:11:02 4262

s := list.Stats
fmt.Println(s.Lines, s.Tracks, s.Markers, s.Timed, *s.FirstTime, *s.LastTime) // 9 7 1 8 2900 4536

The suggestion exists because exactly one time, one digit away from 00:11:02, fits between its neighbors. With several candidates or none, Suggestion is nil. Open this list in the playground.

ApplyEdits takes a slice of Edit values and only rewrites the lines they name:

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)
// "48:20 Noisia - Stigma\r\n01:00:16 Alix Perez - Fade Away\r\n01:03:55 Imanu - Sacrifice\r\n"
fmt.Println(result.Changed) // [2 3]
w := result.Warnings[0]
fmt.Println(w.Code, w.Edit, *w.Line) // style-upgraded 1 2

result = trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.ShiftLines(-3000, 1)})
fmt.Println(result.Warnings[0].Code) // time-clamped

result = trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.Delete(9)})
fmt.Println(result.Warnings[0].Code, result.Text == text) // edit-invalid true

A rewritten time keeps its line's style: 48:20 stays MM:SS, and a time that crosses the hour gets hours, with a style-upgraded warning. A time pushed below zero stops at zero and warns time-clamped. A bad edit changes nothing and warns edit-invalid (edit warnings, editing tracklists).

Edits (reference) are built with SetTime(line, seconds), Shift(seconds) (all timed lines), ShiftFrom(seconds, from), ShiftLines(seconds, lines...), SortByTime(), SetRest(line, rest), Insert(after, text) (after 0 inserts at the top) and Delete(line). Edit is a plain struct with an Op field, so you can also fill it yourself; each operation reads only its own fields. Line numbers are 1-based.

TracklistOptions (options) has Mode (zero value: ModeTracklist; ModeAuto picks a mode per line), KnownArtists, SplitAnd, Keywords, AudioSeconds (a *float64; it enables time-after-audio-end) and MarkerWords:

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) // time-after-audio-end 2
Result Fields
Tracklist SpecVersion, Entries, Warnings, Stats
Entry Line (1-based), Kind (EntryKindTrack, EntryKindMarker, EntryKindHeader, EntryKindLink, EntryKindNote, EntryKindBlank), Eol, Raw, Parts, Time (*TracklistTime), Track (*Track), Layered (the track text after any time starts with w/)
Parts Lead, Time, Gap, Rest, joined they give Raw
TracklistWarning Code (WarningCode), Line, Severity (SeverityInfo or SeverityWarning), Suggestion (*Suggestion)
TracklistTime Raw, Seconds (float64; Entry.Time, nil on untimed lines)
Suggestion Line, Raw, Seconds
Stats Lines, Tracks, Markers, Timed, FirstTime, LastTime (*float64)
EditResult Text, Changed, Warnings (EditWarning{Code, Edit, Line}, Line is *int)

Eol is the terminator itself (EolLF is "\n", EolCRLF is "\r\n", EolCR is "\r", and EolNone is "" for a last line without one), so e.Raw + string(e.Eol) is the line as it was.

Lists pasted with list bullets or Markdown emphasis (* 14:21 Artist - Title, **[**14:21**] Artist - Title**) read like plain lines; the decoration stays in Raw and Parts. A line whose track text (after any time) starts with w/ is Layered: a track played over the previous one (Markdown, layered tracks).

Warning codes (WarningCode): time-missing, time-out-of-order, time-duplicate, no-start-at-zero, time-after-audio-end (needs AudioSeconds), invalid-time, position-gap, position-duplicate, line-unparsed, as the constants WarningCodeTimeMissing to WarningCodeLineUnparsed. Edit warnings (EditWarningCode): EditWarningCodeEditInvalid, EditWarningCodeTimeClamped, EditWarningCodeStyleUpgraded. The Tracklist API reference explains each one, and the rules are in R13 of the spec.

Every line is parsed with ModeTracklist, where the first spaced dash always separates artist and title. ParseWith accepts it too:

track := trackparse.Parse("Electrosoul System - Liquid Metal")
fmt.Println(track.Title, "/", track.Junk[0].Raw, track.Junk[0].Kind) // Electrosoul System / Liquid Metal genre

track = trackparse.ParseWith("Electrosoul System - Liquid Metal", trackparse.ParseOptions{
	Mode: trackparse.ModeTracklist,
})
fmt.Println(track.Title) // Liquid Metal

Errors

No function returns an error and none panics (R0.8). Parse gives a complete Track for any string, "" included, and ParseTracklist and ApplyEdits return for any text. ApplyEdits reports an edit it cannot apply (a line that does not exist, non-finite seconds) as an EditWarningCodeEditInvalid warning and leaves the text alone. The only function with an error result is Track.UnmarshalJSON, which reads JSON you give it.

A Go string can hold bytes that are not valid UTF-8. Every function reads such input with the WHATWG rule, the one TextDecoder uses in JavaScript and String::from_utf8_lossy in Rust: each maximal ill-formed subsequence becomes one U+FFFD. So the Go module, the Rust crate and the C library read the same bytes as the same text, and every output string is valid UTF-8.

fmt.Printf("%q\n", trackparse.Parse("Noisia - Sti\xffgma\xe2\x82").Title) // "Sti�gma�"

\xff is one replacement character, and the truncated three-byte sequence \xe2\x82 is one more. (Go's own for range over a string would give one per byte.)

How it is tested

Docs: How it's tested · Ports

  • go test ./... runs all 13,565 shared fixtures (1,280 written by hand, the rest generated from the rules) and checks every output against the JSON Schema. The skip list is empty. The fixture test skips itself when ../spec is missing, as in the module zip that go get downloads.
  • The R0 primitives (whitespace, word keys, dedup keys, letters, NFC and NFD) are tested against values dumped from the JavaScript package.
  • Seeded property tests check the spec's invariants on generated input: no panic in any mode, Normalize idempotent, whitespace and dash noise not changing the result, no word of the input going missing, the Format round trip, and for tracklists the byte-for-byte round trip, edit locality and the shift round trip. Fuzz targets (go test -fuzz) check that nothing panics on any bytes and that every output string is valid UTF-8; one feeds Track.UnmarshalJSON and checks the JSON round trip.
  • A Parser with options, the zero Parser, the package functions, ParseTracklistWith and ApplyEdits are called from 16 goroutines at once and compared with a sequential run, under the race detector in CI.
  • The Example functions in example_test.go are checked by go test, so the examples on pkg.go.dev run as shown.
  • scripts/compare-ports.mjs runs every fixture input through the JavaScript package and this module and compares the complete JSON output, every field of it, not only the ones a fixture asserts. The Python and Rust packages and the C library are checked the same way.
  • CI runs go vet, staticcheck and go test -race on Go 1.22 and on the latest stable, and fails if go.mod gains a require line or the code calls sort.Slice (JavaScript sorts are stable, sort.Slice is not).

Unicode version

The Unicode facts the rules need (letters, uppercase letters, the lowercase mapping, and the NFC and NFD tables) are generated from Node 24, which has Unicode 17, and compiled into the module. Neither source that a Go program would usually take them from is used, because both follow the Go toolchain that builds the program:

  • the standard library's unicode package has the tables of its Go release (unicode.Version is "15.0.0" in Go 1.24);
  • golang.org/x/text/unicode/norm picks its NFC and NFD tables by build tag: Unicode 15 below Go 1.27, Unicode 17 from Go 1.27.

So the output does not depend on the Go version you build with. More in what the Go port taught.

This differs from the Rust crate, which takes NFC and NFD from the unicode-normalization crate and its Unicode 18 tables. Unicode 18 added 32 combining marks, so a string containing one of them can come out with its marks in another order in Rust than in JavaScript, Go and C. Strings without those marks are not affected, and every shared fixture gives the same bytes in all five ports.

Performance

There are no regular expressions, so there is no regex backtracking. Measured with go test -bench . -run '^$' -benchtime 2s (the benchmarks in bench_test.go) on an Intel i7-4770S, Go 1.24, and the JavaScript package on Node 24 with the same inputs on the same machine. Other programs were running, so the numbers vary by about 20% between runs:

Input Go JavaScript
A typical track (Noisia feat. Foreign Beggars - Shellshock (Phace Remix) [Official Video]) 0.04 to 0.06 ms 0.07 to 0.09 ms
10,000 code points of one repeated block (a & , a feat. , feat. X , (Remix) , [HD] , - , or the typical track) 3 to 7 ms 4 to 18 ms
A 42-line tracklist 1.4 to 1.8 ms 2.9 ms
A 10,000-line tracklist 0.33 to 0.38 s 0.8 to 0.9 s
ApplyEdits with a shift and a sort on 10,000 lines 60 to 67 ms 100 to 160 ms

Versioning

Changelog: go/CHANGELOG.md

The module version is the spec version (SpecVersion). Releases are tagged go/vX.Y.Z in the repository, the tag form the Go toolchain expects for a module in a subfolder, and the Go module proxy serves them from there. There is no upload step: the tag is the release. Every published version is listed on pkg.go.dev.

While it is 0.x, a release that changes the output for some input bumps the minor version, and a patch release only fixes bugs. go get -u moves to the newest minor, so if you store parsed results, upgrade on purpose and read the changelog first.

Other languages

Docs: Ports

The same parser exists for JavaScript, Python, Rust and C. All five implement one spec, pass the same fixtures, are released together under one version number, and return identical JSON for every fixture input. You can parse in one language and read the result in another. The one known difference is described under Unicode version.

Language Package Install Docs
JavaScript / TypeScript trackparse on npm npm install trackparse README · changelog · API
Python trackparse on PyPI pip install trackparse README · changelog · API
Rust trackparse on crates.io cargo add trackparse README · changelog · API on docs.rs
Go github.com/4matic/trackparse/go go get github.com/4matic/trackparse/go README · changelog · API on pkg.go.dev
C / C++ C library and C++ header CMake FetchContent from the release tarball, or the amalgamation (from 0.7.1) README · changelog · header

Limitations

Docs: Limitations and roadmap

  • Parse takes one track string. Whole tracklists go through ParseTracklist, which reads start times only: no durations, trailing times or time ranges.
  • Catalog numbers, key and BPM are not fields. They stay in the title. A record label is a field only after a spaced bullet (Stigma • VISION), and a bullet inside a title (Song • Part 2) is read as a label too.
  • There is no artist database. Pass KnownArtists for names that contain a joiner (Earth, Wind & Fire).

Development

From go/ in the repository (Node 24 is needed for the codegen scripts and the artist-side test data only):

node scripts/gen_data.mjs --check      # spec/data codegen is up to date
node scripts/gen_unicode.mjs --check   # Unicode tables are up to date
pnpm --filter trackparse build && node scripts/dump_artist_cases.mjs   # data for the artist-side tests
gofmt -l .                             # prints nothing
go vet ./...
go test -race ./...                    # every shared fixture, primitives, examples, API
TRACKPARSE_REPORT=1 go test -run TestFixtures -v   # pass rate per fixture file and per rule

The Go side of scripts/compare-ports.mjs is a command behind a build tag, so it is not part of the package API: go run -tags trackparse_wire ./internal/cmd/dump reads fixture calls as JSON lines and writes each result as the JavaScript package would. CI also runs go vet and staticcheck with -tags trackparse_wire.

Files mirror the JS reference one to one (scanner.go is scanner.ts, tl_parse.go is tracklist/parse.ts, and so on) and cite the same spec rule IDs. Behaviour changes start in the spec, not here: see AGENTS.md.

Links

  • Documentation, with every example in JavaScript, Python, Rust, Go and C, and a playground that runs the parser in your browser
  • API documentation on pkg.go.dev
  • Spec and its changelog
  • Changelog
  • Project README
  • GitHub repository
  • npm package · PyPI package · Rust crate · C library

License

MIT

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 and the C library (with a C++17 header) 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 five 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
    • func AllArtists(track Track) []Artist
    • func ParseArtists(input string) []Artist
    • func ParseArtistsWith(input string, options ParseOptions) []Artist
    • func (a Artist) MarshalJSON() ([]byte, error)
  • type Delimiter
    • func AllDelimiters() []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
    • func (e Edit) MarshalJSON() ([]byte, error)
  • type EditOp
    • func AllEditOps() []EditOp
  • type EditResult
    • func ApplyEdits(text string, edits []Edit) EditResult
    • func ApplyEditsWith(text string, edits []Edit, options TracklistOptions) EditResult
    • func (r EditResult) MarshalJSON() ([]byte, error)
  • type EditWarning
    • func (x EditWarning) MarshalJSON() ([]byte, error)
  • type EditWarningCode
    • func AllEditWarningCodes() []EditWarningCode
  • type Entry
    • func (e Entry) MarshalJSON() ([]byte, error)
  • type EntryKind
    • func AllEntryKinds() []EntryKind
  • type Eol
    • func AllEols() []Eol
  • type FeatPlacement
  • type Flags
    • func (f Flags) MarshalJSON() ([]byte, error)
  • type FormatOptions
  • type JoinerStyle
  • type Junk
    • func (j Junk) MarshalJSON() ([]byte, error)
  • type JunkKind
    • func AllJunkKinds() []JunkKind
  • type JunkPhrase
  • type Keywords
  • type Mode
    • func AllModes() []Mode
  • type ParseOptions
  • type Parser
    • func NewParser(options ParseOptions) *Parser
    • func (p *Parser) Parse(input string) Track
    • func (p *Parser) ParseArtists(input string) []Artist
  • type Parts
    • func (p Parts) MarshalJSON() ([]byte, error)
  • type Position
    • func (p Position) MarshalJSON() ([]byte, error)
  • type Role
    • func AllRoles() []Role
  • type Severity
    • func AllSeverities() []Severity
  • type Source
    • func AllSources() []Source
  • type SplitAnd
  • type Stats
    • func (s Stats) MarshalJSON() ([]byte, error)
  • type Suggestion
    • func (s Suggestion) MarshalJSON() ([]byte, error)
  • type Timestamp
    • func (t Timestamp) MarshalJSON() ([]byte, error)
  • type Track
    • func Parse(input string) Track
    • func ParseWith(input string, options ParseOptions) Track
    • func (t Track) MarshalJSON() ([]byte, error)
    • func (t *Track) UnmarshalJSON(data []byte) error
  • type Tracklist
    • func ParseTracklist(text string) Tracklist
    • func ParseTracklistWith(text string, options TracklistOptions) Tracklist
    • func (t Tracklist) MarshalJSON() ([]byte, error)
  • type TracklistOptions
  • type TracklistTime
    • func (t TracklistTime) MarshalJSON() ([]byte, error)
  • type TracklistWarning
    • func (x TracklistWarning) MarshalJSON() ([]byte, error)
  • type Version
    • func (v Version) MarshalJSON() ([]byte, error)
  • type VersionHead
  • type VersionType
    • func AllVersionTypes() []VersionType
  • type VersionsOption
  • type Warning
    • func AllWarnings() []Warning
  • type WarningCode
    • func AllWarningCodes() []WarningCode

Examples ¶

  • Package
  • AllArtists
  • ApplyEdits
  • FormatWith
  • Normalize
  • Parse
  • Parse (Label)
  • ParseArtists
  • ParseTracklist
  • ParseTracklistWith
  • ParseWith
  • ParseWith (Keywords)
  • Parser
  • Ptr
  • Track.MarshalJSON
  • Track.MarshalJSON (EscapeHTML)

Constants ¶

View Source
const SpecVersion = "0.8.1" // x-release-please-version

SpecVersion is the version of the spec this module implements.

Variables ¶

This section is empty.

Functions ¶

func Format ¶

func Format(track Track) string

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 ¶

func Normalize(input string) string

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 ¶

func AllArtists(track Track) []Artist

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 ¶

func ParseArtists(input string) []Artist

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 ¶

func (a Artist) MarshalJSON() ([]byte, error)

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 Delete ¶

func Delete(line int) Edit

Delete is the edit that removes line.

func Insert ¶

func Insert(after int, text string) Edit

Insert is the edit that inserts text as a new line after line after (0: at the start).

func SetRest ¶

func SetRest(line int, rest string) Edit

SetRest is the edit that replaces everything after the time and gap of line.

func SetTime ¶

func SetTime(line int, seconds float64) Edit

SetTime is the edit that rewrites the time of line, keeping its written style (R13.9.2).

func Shift ¶

func Shift(seconds float64) Edit

Shift is the edit that adds seconds to every timed line of the text.

func ShiftFrom ¶

func ShiftFrom(seconds float64, from int) Edit

ShiftFrom is the edit that adds seconds to every timed line from line from on.

func ShiftLines ¶

func ShiftLines(seconds float64, lines ...int) Edit

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 ¶

func (e Edit) MarshalJSON() ([]byte, error)

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 ¶

func (e Entry) MarshalJSON() ([]byte, error)

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.

const (
	EolLF   Eol = "\n"
	EolCRLF Eol = "\r\n"
	EolCR   Eol = "\r"
	EolNone Eol = ""
)

The line terminators.

func AllEols ¶

func AllEols() []Eol

AllEols returns every Eol, in the spec's order. Each call returns a new slice.

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 ¶

func (f Flags) MarshalJSON() ([]byte, error)

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
	// OmitLabel leaves out the record label after the title, " • " + label (R11.3; the
	// JavaScript option label: false).
	OmitLabel 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 fragment it is.
	Kind JunkKind
}

Junk is a fragment that is not part of the track's identity: noise (Official Video, HD), promo text (Free Download), platform names, a bracketed label, notes after a record label. It is taken out of the title and kept here (the parser extracts, it does not delete).

func (Junk) MarshalJSON ¶

func (j Junk) MarshalJSON() ([]byte, error)

MarshalJSON writes the spec's JSON form (see Artist.MarshalJSON).

type JunkKind ¶

type JunkKind string

JunkKind is what kind of fragment a junk entry is (R5, R8.7). 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"
	// JunkKindNote is a note after the record label, behind a second spaced bullet (R8.7).
	JunkKindNote JunkKind = "note"
)

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.

func AllModes ¶

func AllModes() []Mode

AllModes returns the modes a Track can have, in the spec's order. Each call returns a new slice.

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) Parse ¶

func (p *Parser) Parse(input string) Track

Parse parses one track string with the parser's options.

func (*Parser) ParseArtists ¶

func (p *Parser) ParseArtists(input string) []Artist

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 ¶

func (p Parts) MarshalJSON() ([]byte, error)

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 ¶

func (p Position) MarshalJSON() ([]byte, error)

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).

const (
	RolePrimary  Role = "primary"
	RoleFeatured Role = "featured"
	RoleRemixer  Role = "remixer"
	RoleProducer Role = "producer"
)

The artist roles.

func AllRoles ¶

func AllRoles() []Role

AllRoles returns every Role, in the spec's order. Each call returns a new slice.

type Severity ¶

type Severity string

Severity is how serious a tracklist warning is.

const (
	SeverityInfo    Severity = "info"
	SeverityWarning Severity = "warning"
)

The severities.

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 ¶

func (s Stats) MarshalJSON() ([]byte, error)

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 ¶

func (t Timestamp) MarshalJSON() ([]byte, error)

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
	// Label is the record label written after a spaced bullet on the title side (R8.7):
	// "Age Of Spin • WEAREHUMANS" gives "WEAREHUMANS". It is as written after R1, case kept,
	// with no lookup; nil when there is none. It is not the junk kind [JunkKindLabel], which is
	// a label name in brackets such as [NCS Release].
	Label *string
	// Flags are yes/no facts.
	Flags Flags
	// Junk are the fragments that are not part of the track's identity.
	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 ¶

func Parse(input string) Track

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

Example (Label) ¶
package main

import (
	"fmt"

	trackparse "github.com/4matic/trackparse/go"
)

func main() {
	track := trackparse.Parse("Noisia - concussion • VISION • VISION RADIO RELOAD")

	fmt.Printf("%q %q\n", track.Title, *track.Label)
	fmt.Printf("%+v\n", track.Junk)
	fmt.Println(trackparse.Format(track))
	fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{OmitLabel: true}))
}
Output:
"concussion" "VISION"
[{Raw:VISION RADIO RELOAD Kind:note}]
Noisia - concussion • VISION
Noisia - concussion

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 ¶

func (t Track) MarshalJSON() ([]byte, error)

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,"label":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 ¶

func (t *Track) UnmarshalJSON(data []byte) error

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 ¶

func ParseTracklist(text string) Tracklist

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 ¶

func (t Tracklist) MarshalJSON() ([]byte, error)

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 ¶

func (v Version) MarshalJSON() ([]byte, error)

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 ¶

View all 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.
Click to show internal directories.
Click to hide internal directories.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.