From 51e3036bc56b2d0c9d194aa4f5b7e1e1bcfb7bc0 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 01/11] docs: the root README links every function, option, field, mode and warning to its reference, spec rule and API docs, opens its examples in the playground, and adds a Go module badge and an API docs column --- README.md | 388 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 214 insertions(+), 174 deletions(-) diff --git a/README.md b/README.md index 8bfead6..27b2717 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ [![PyPI](https://img.shields.io/pypi/v/trackparse?color=3775a9&logo=pypi&logoColor=white)](https://pypi.org/project/trackparse/) [![crates.io](https://img.shields.io/crates/v/trackparse?color=e6822a&logo=rust&logoColor=white)](https://crates.io/crates/trackparse) [![docs.rs](https://img.shields.io/docsrs/trackparse?logo=docsdotrs&logoColor=white)](https://docs.rs/trackparse) +[![Go module](https://img.shields.io/github/v/tag/4matic/trackparse?filter=go%2Fv*&label=go%20module&logo=go&logoColor=white&color=00add8)](https://pkg.go.dev/github.com/4matic/trackparse/go?tab=versions) [![Go Reference](https://pkg.go.dev/badge/github.com/4matic/trackparse/go.svg)](https://pkg.go.dev/github.com/4matic/trackparse/go)
[![js](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/js.yml?branch=main&label=js&logo=github)](https://github.com/4matic/trackparse/actions/workflows/js.yml) @@ -40,11 +41,15 @@ that Becky Hill is featured, that Sub Focus did the remix, or that it's a VIP. trackparse keeps all of it. Its one rule is **extract, don't delete**: everything it recognizes goes into a field, and anything it doesn't recognize stays in the title, word for word. -It comes as an npm package, a PyPI package, a Rust crate and a Go module, all named `trackparse`. -One [spec](spec/SPEC.md) and one set of fixtures define the behaviour. The four pass the same -fixtures and give the same output on every fixture input. The example below is JavaScript; -[Quick start](#quick-start) has the same calls in Python, Rust and Go, and you can try any string in -the [playground](https://4matic.github.io/trackparse/playground/). +It comes as an [npm package](https://www.npmjs.com/package/trackparse), a +[PyPI package](https://pypi.org/project/trackparse/), a +[Rust crate](https://crates.io/crates/trackparse) and a +[Go module](https://pkg.go.dev/github.com/4matic/trackparse/go), all named `trackparse`. +One [spec](spec/SPEC.md) and one set of [fixtures](spec/fixtures/README.md) define the behaviour. +The four pass the same fixtures and give the same output on every fixture input. The example below +is JavaScript; [Quick start](#quick-start) has the same calls in Python, Rust and Go. You can +[try this string in the playground](https://4matic.github.io/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D), +or any other. ```js import { parse } from "trackparse"; @@ -98,8 +103,12 @@ track.position; // { raw: '01', number: 1 } } ``` -Every key is always present. When a guess was involved, `warnings` says which one. Python's -`to_dict()`, Rust's `to_json()` and Go's `MarshalJSON` give this same JSON. +Every key is always present ([field reference](https://4matic.github.io/trackparse/reference/parse/#parsedtrack), +[JSON Schema](spec/schema/parsed-track.schema.json)). When a guess was involved, `warnings` says +which one. Python's [`to_dict()`](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json), +Rust's [`to_json()`](https://docs.rs/trackparse/latest/trackparse/struct.ParsedTrack.html#method.to_json) +and Go's [`MarshalJSON`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track.MarshalJSON) +give this same JSON. @@ -109,17 +118,17 @@ Every key is always present. When a guess was involved, `warnings` says which on | Number | What it means | |---|---| -| **13,130** shared fixtures | 1,203 written by hand, 11,927 generated from combinations. 100% pass in JS, Python, Rust and Go, nothing skipped. | +| **13,130** shared fixtures | [1,203 written by hand](https://4matic.github.io/trackparse/project/testing/#handwritten-1203-cases), [11,927 generated](https://4matic.github.io/trackparse/project/testing/#generated-11927-cases) from combinations. 100% pass in JS, Python, Rust and Go, nothing skipped. | | **1,239** of them on tracklists | 303 handwritten, 936 generated. They cover line splitting, times, bullets and Markdown, warnings and edits | -| **1,352** JS tests | Every fixture, a schema check on every output, property-based tests of the spec invariants, API tests | -| **27** version types | Remix, VIP, bootleg, extended, radio, original, live, remaster, sped up and more | +| **1,352** JS tests | Every fixture, a schema check on every output, property-based tests of the [spec invariants](https://4matic.github.io/trackparse/reference/spec/#invariants), API tests | +| **27** version types | [Remix, VIP, bootleg, extended, radio, original, live, remaster, sped up and more](https://4matic.github.io/trackparse/guides/versions/#the-27-types) | | **0** dependencies in JS, Python and Go | The Rust crate has one, `unicode-normalization`. The JS package is ESM + CJS with TypeScript types, about 18 kB gzipped. `trackparse/tracklist` adds about 8.4 KiB, only if you import it | | **Node 18+** | CI runs the full suite on 22 and 24, and every fixture against the built package on 18 and 20 | | **Python 3.9+** | 1,342 pytest tests on 3.9 to 3.14, plus every fixture against the built wheel. Output is byte-identical to JS | | **Rust 1.74+** | Every fixture, the tracklist invariants and the typed API tests on stable and on 1.74. Output is byte-identical to JS on every fixture and on about 790,000 random inputs | | **Go 1.22+** | Every fixture, the spec invariants and the examples with `go test -race` on 1.22 and on the latest stable. Output is byte-identical to JS on every fixture and on about 790,000 random inputs | -| **5,031** real tracklist lines | 117 podcast tracklists the tracklist rules were checked against. Every line round-trips byte for byte | -| **1** spec | [`spec/SPEC.md`](spec/SPEC.md) defines the behaviour. The packages share its version and are released together; the Go module's first release is 0.6.0 | +| **5,031** real tracklist lines | 117 podcast tracklists the tracklist rules were [checked against](https://4matic.github.io/trackparse/project/testing/#real-tracklists). Every line round-trips byte for byte | +| **1** spec | [`spec/SPEC.md`](spec/SPEC.md) defines the behaviour ([on the site](https://4matic.github.io/trackparse/reference/spec/)). The four packages share its version number and are released together | ## Install @@ -158,7 +167,10 @@ go get github.com/4matic/trackparse/go@latest **Docs:** [Getting started](https://4matic.github.io/trackparse/start/getting-started/) · [Introduction](https://4matic.github.io/trackparse/start/introduction/) -The four examples parse the same strings. The comments show what each expression evaluates to. +The four examples parse the same strings with [`parse`](https://4matic.github.io/trackparse/reference/parse/), +[`parseArtists`](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) and +[`format`](https://4matic.github.io/trackparse/reference/functions/#formattrack-options). The comments show what each expression +evaluates to. ### JavaScript @@ -180,12 +192,12 @@ format(parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)"), { feat: ``` CommonJS works too: `const { parse } = require("trackparse")`. The full JavaScript API, with the -TypeScript types, is in [`js/README.md`](js/README.md). +TypeScript types, is in [`js/README.md`](js/README.md#api). ### Python -Functions are snake_case and results are frozen dataclasses. `to_dict()` gives the spec's JSON -with camelCase keys, the same as the JS package returns. +Functions are snake_case and results are frozen dataclasses. [`to_dict()`](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json) +gives the spec's JSON with camelCase keys, the same as the JS package returns. ```python from trackparse import format_track, parse, parse_artists @@ -209,13 +221,15 @@ track.to_dict()["artists"][1] # {'name': 'Foreign Beggars', 'role': 'featured', 'joiner': 'feat.', 'source': 'artist'} ``` -Options are keyword arguments: `parse(s, mode="youtube", known_artists=["Chase & Status"])`. The -full Python API is in [`python/README.md`](python/README.md). +Options are keyword arguments: `parse(s, mode="youtube", known_artists=["Chase & Status"])` +([all options](https://4matic.github.io/trackparse/reference/options/)). The full Python API is in +[`python/README.md`](python/README.md#api). ### Rust -Results are structs with public fields, and roles, version types and junk kinds are enums. -`to_json()` writes the spec's JSON, byte for byte what `JSON.stringify` gives in JS. +Results are structs with public fields ([`ParsedTrack`](https://docs.rs/trackparse/latest/trackparse/struct.ParsedTrack.html)), and roles, +version types and junk kinds are enums. [`to_json()`](https://docs.rs/trackparse/latest/trackparse/struct.ParsedTrack.html#method.to_json) +writes the spec's JSON, byte for byte what `JSON.stringify` gives in JS. ```rust use trackparse::{format_track_with, parse, parse_artists, FeatPlacement, FormatOptions, JoinerStyle}; @@ -241,16 +255,17 @@ track.artists[1].to_json(); // {"name":"Foreign Beggars","role":"featured","joiner":"feat.","source":"artist"} ``` -Options are builders passed to the `_with` form of a function: -`parse_with(s, &ParseOptions::new().known_artists(["Chase & Status"]))`. The full Rust API is in -[`rust/README.md`](rust/README.md) and on [docs.rs](https://docs.rs/trackparse). +Options are builders ([`ParseOptions`](https://docs.rs/trackparse/latest/trackparse/struct.ParseOptions.html)) passed to the `_with` form +of a function: `parse_with(s, &ParseOptions::new().known_artists(["Chase & Status"]))`. The full +Rust API is in [`rust/README.md`](rust/README.md#api) and on [docs.rs](https://docs.rs/trackparse). ### Go -Results are structs with exported fields; fields that can be `null` are pointers. Roles, version -types and junk kinds are typed strings with constants (`trackparse.RoleFeatured`). `json.Marshal` -gives the spec's JSON, with `&`, `<` and `>` escaped as `&`, `<` and `>`: the same -values in different bytes. For the exact bytes of `JSON.stringify`, call `MarshalJSON` directly. +Results are structs with exported fields ([`Track`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track)); fields that can be `null` are +pointers. Roles, version types and junk kinds are typed strings with constants +(`trackparse.RoleFeatured`). `json.Marshal` gives the spec's JSON, with `&`, `<` and `>` escaped as `&`, `<` and `>`: the same +values in different bytes. For the exact bytes of `JSON.stringify`, call +[`MarshalJSON`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track.MarshalJSON) directly. ```go import ( @@ -289,11 +304,10 @@ fmt.Println(string(b)) // {"name":"Foreign Beggars","role":"featured","joiner":"feat.","source":"artist"} ``` -Options are plain structs whose zero value is the default (a field that must be told apart -from its zero value is a pointer, set with `trackparse.Ptr`), passed to the `With` form of a -function: `trackparse.ParseWith(s, trackparse.ParseOptions{KnownArtists: []string{"Chase & Status"}})`. -The full Go API is in [`go/README.md`](go/README.md) and on -[pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go). +Options are plain structs whose zero value is the default ([`ParseOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseOptions); a +field that must be told apart from its zero value is a pointer, set with +[`trackparse.Ptr`](https://pkg.go.dev/github.com/4matic/trackparse/go#Ptr)), passed to the `With` form of a function: `trackparse.ParseWith(s, trackparse.ParseOptions{KnownArtists: []string{"Chase & Status"}})`. +The full Go API is in [`go/README.md`](go/README.md#api) and on [pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go). Every example on the [documentation site](https://4matic.github.io/trackparse/) has JavaScript, Python, Rust and Go tabs. @@ -311,39 +325,39 @@ Python, Rust and Go tabs. **Docs:** [What it understands](https://4matic.github.io/trackparse/guides/what-it-understands/) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) · [Versions and remixes](https://4matic.github.io/trackparse/guides/versions/) · [Junk, flags and prefixes](https://4matic.github.io/trackparse/guides/junk-and-flags/) These are real outputs of `parse(input)` with default options, unless noted. They are the same in -all four languages. To try your own strings, use the -[playground](https://4matic.github.io/trackparse/playground/). +all four languages. Each input opens in the [playground](https://4matic.github.io/trackparse/playground/) with that string filled +in, so you can see the full output or change the string. | Input | Artists | Title | Versions / other | |---|---|---|---| -| `Noisia feat. Foreign Beggars - Shellshock` | Noisia, Foreign Beggars *(feat)* | `Shellshock` | | -| `Silk City - Electricity (with Dua Lipa)` | Silk City, Dua Lipa *(feat)* | `Electricity` | | -| `Skrillex & Diplo x Justin Bieber - Where Are Ü Now` | Skrillex, Diplo, Justin Bieber | `Where Are Ü Now` | | -| `Future - Mask Off (prod. by Metro Boomin)` | Future, Metro Boomin *(producer)* | `Mask Off` | | -| `Linkin Park - Numb (Remix by Skrillex)` | Linkin Park | `Numb` | remix by Skrillex | -| `Dimension - Offshore (Mefjus Remix / Noisia Remix)` | Dimension | `Offshore` | two remixes | -| `Pendulum - Watercolour (Extended VIP Mix)` | Pendulum | `Watercolour` | vip, +extended | -| `Noisia - Stigma (Phace Bootleg)` | Noisia | `Stigma` | bootleg by Phace | -| `Deadmau5 - Strobe (Radio Edit)` | Deadmau5 | `Strobe` | radio | -| `Netsky - Iron Heart (Levela Mix)` | Netsky | `Iron Heart` | remix by Levela | -| `The Beatles - Hey Jude - Remastered 2015` | The Beatles | `Hey Jude` | remaster, 2015 | -| `Taylor Swift - Love Story (Taylor's Version)` | Taylor Swift | `Love Story` | version, "Taylor's" | -| `Kordhell - Murder In My Mind (Slowed + Reverb)` | Kordhell | `Murder In My Mind` | slowed | -| `Eminem - Without Me (Explicit)` | Eminem | `Without Me` | explicit flag | -| `Daft Punk - One More Time (Official Music Video) [HD]` | Daft Punk | `One More Time` | junk: video, quality | -| `Elektronomia - Sky High [NCS Release]` | Elektronomia | `Sky High` | junk: label | -| `Porter Robinson - Shelter - YouTube` | Porter Robinson | `Shelter` | junk: platform | -| `01. Aphex Twin - Xtal` | Aphex Twin | `Xtal` | position 1 | -| `[12:34] Noisia - Stigma` | Noisia | `Stigma` | timestamp 754 s | -| `07_Burial_-_Archangel.mp3` | Burial | `Archangel` | filename mode, position 7 | -| `"Numb" by Linkin Park` *(youtube)* | Linkin Park | `Numb` | warning `bySplit` | -| `Blink-182-All The Small Things` *(youtube)* | Blink-182 | `All The Small Things` | warning `unspacedDashSplit` | -| `Кино - Группа крови (Remastered 2019)` | Кино | `Группа крови` | remaster, 2019 | -| `ID - ID (ID Remix)` | | `ID` | unknown artist, title and remixer | -| `AC/DC - Back In Black` | AC/DC | `Back In Black` | | -| `2 Unlimited - No Limit` | 2 Unlimited | `No Limit` | not a track number | -| `Mumford & Sons - Little Lion Man` | Mumford & Sons | `Little Lion Man` | not split | -| `The Rolling Stones - (I Can't Get No) Satisfaction` | The Rolling Stones | `(I Can't Get No) Satisfaction` | kept as is | +| [`Noisia feat. Foreign Beggars - Shellshock`](https://4matic.github.io/trackparse/playground/#track=Noisia%20feat.%20Foreign%20Beggars%20-%20Shellshock) | Noisia, Foreign Beggars *(feat)* | `Shellshock` | | +| [`Silk City - Electricity (with Dua Lipa)`](https://4matic.github.io/trackparse/playground/#track=Silk%20City%20-%20Electricity%20%28with%20Dua%20Lipa%29) | Silk City, Dua Lipa *(feat)* | `Electricity` | | +| [`Skrillex & Diplo x Justin Bieber - Where Are Ü Now`](https://4matic.github.io/trackparse/playground/#track=Skrillex%20%26%20Diplo%20x%20Justin%20Bieber%20-%20Where%20Are%20%C3%9C%20Now) | Skrillex, Diplo, Justin Bieber | `Where Are Ü Now` | | +| [`Future - Mask Off (prod. by Metro Boomin)`](https://4matic.github.io/trackparse/playground/#track=Future%20-%20Mask%20Off%20%28prod.%20by%20Metro%20Boomin%29) | Future, Metro Boomin *(producer)* | `Mask Off` | | +| [`Linkin Park - Numb (Remix by Skrillex)`](https://4matic.github.io/trackparse/playground/#track=Linkin%20Park%20-%20Numb%20%28Remix%20by%20Skrillex%29) | Linkin Park | `Numb` | remix by Skrillex | +| [`Dimension - Offshore (Mefjus Remix / Noisia Remix)`](https://4matic.github.io/trackparse/playground/#track=Dimension%20-%20Offshore%20%28Mefjus%20Remix%20%2F%20Noisia%20Remix%29) | Dimension | `Offshore` | two remixes | +| [`Pendulum - Watercolour (Extended VIP Mix)`](https://4matic.github.io/trackparse/playground/#track=Pendulum%20-%20Watercolour%20%28Extended%20VIP%20Mix%29) | Pendulum | `Watercolour` | vip, +extended | +| [`Noisia - Stigma (Phace Bootleg)`](https://4matic.github.io/trackparse/playground/#track=Noisia%20-%20Stigma%20%28Phace%20Bootleg%29) | Noisia | `Stigma` | bootleg by Phace | +| [`Deadmau5 - Strobe (Radio Edit)`](https://4matic.github.io/trackparse/playground/#track=Deadmau5%20-%20Strobe%20%28Radio%20Edit%29) | Deadmau5 | `Strobe` | radio | +| [`Netsky - Iron Heart (Levela Mix)`](https://4matic.github.io/trackparse/playground/#track=Netsky%20-%20Iron%20Heart%20%28Levela%20Mix%29) | Netsky | `Iron Heart` | remix by Levela | +| [`The Beatles - Hey Jude - Remastered 2015`](https://4matic.github.io/trackparse/playground/#track=The%20Beatles%20-%20Hey%20Jude%20-%20Remastered%202015) | The Beatles | `Hey Jude` | remaster, 2015 | +| [`Taylor Swift - Love Story (Taylor's Version)`](https://4matic.github.io/trackparse/playground/#track=Taylor%20Swift%20-%20Love%20Story%20%28Taylor%27s%20Version%29) | Taylor Swift | `Love Story` | version, "Taylor's" | +| [`Kordhell - Murder In My Mind (Slowed + Reverb)`](https://4matic.github.io/trackparse/playground/#track=Kordhell%20-%20Murder%20In%20My%20Mind%20%28Slowed%20%2B%20Reverb%29) | Kordhell | `Murder In My Mind` | slowed | +| [`Eminem - Without Me (Explicit)`](https://4matic.github.io/trackparse/playground/#track=Eminem%20-%20Without%20Me%20%28Explicit%29) | Eminem | `Without Me` | explicit flag | +| [`Daft Punk - One More Time (Official Music Video) [HD]`](https://4matic.github.io/trackparse/playground/#track=Daft%20Punk%20-%20One%20More%20Time%20%28Official%20Music%20Video%29%20%5BHD%5D) | Daft Punk | `One More Time` | junk: video, quality | +| [`Elektronomia - Sky High [NCS Release]`](https://4matic.github.io/trackparse/playground/#track=Elektronomia%20-%20Sky%20High%20%5BNCS%20Release%5D) | Elektronomia | `Sky High` | junk: label | +| [`Porter Robinson - Shelter - YouTube`](https://4matic.github.io/trackparse/playground/#track=Porter%20Robinson%20-%20Shelter%20-%20YouTube) | Porter Robinson | `Shelter` | junk: platform | +| [`01. Aphex Twin - Xtal`](https://4matic.github.io/trackparse/playground/#track=01.%20Aphex%20Twin%20-%20Xtal) | Aphex Twin | `Xtal` | position 1 | +| [`[12:34] Noisia - Stigma`](https://4matic.github.io/trackparse/playground/#track=%5B12%3A34%5D%20Noisia%20-%20Stigma) | Noisia | `Stigma` | timestamp 754 s | +| [`07_Burial_-_Archangel.mp3`](https://4matic.github.io/trackparse/playground/#track=07_Burial_-_Archangel.mp3) | Burial | `Archangel` | filename mode, position 7 | +| [`"Numb" by Linkin Park`](https://4matic.github.io/trackparse/playground/#track=%22Numb%22%20by%20Linkin%20Park&mode=youtube) *(youtube)* | Linkin Park | `Numb` | warning `bySplit` | +| [`Blink-182-All The Small Things`](https://4matic.github.io/trackparse/playground/#track=Blink-182-All%20The%20Small%20Things&mode=youtube) *(youtube)* | Blink-182 | `All The Small Things` | warning `unspacedDashSplit` | +| [`Кино - Группа крови (Remastered 2019)`](https://4matic.github.io/trackparse/playground/#track=%D0%9A%D0%B8%D0%BD%D0%BE%20-%20%D0%93%D1%80%D1%83%D0%BF%D0%BF%D0%B0%20%D0%BA%D1%80%D0%BE%D0%B2%D0%B8%20%28Remastered%202019%29) | Кино | `Группа крови` | remaster, 2019 | +| [`ID - ID (ID Remix)`](https://4matic.github.io/trackparse/playground/#track=ID%20-%20ID%20%28ID%20Remix%29) | | `ID` | unknown artist, title and remixer | +| [`AC/DC - Back In Black`](https://4matic.github.io/trackparse/playground/#track=AC%2FDC%20-%20Back%20In%20Black) | AC/DC | `Back In Black` | | +| [`2 Unlimited - No Limit`](https://4matic.github.io/trackparse/playground/#track=2%20Unlimited%20-%20No%20Limit) | 2 Unlimited | `No Limit` | not a track number | +| [`Mumford & Sons - Little Lion Man`](https://4matic.github.io/trackparse/playground/#track=Mumford%20%26%20Sons%20-%20Little%20Lion%20Man) | Mumford & Sons | `Little Lion Man` | not split | +| [`The Rolling Stones - (I Can't Get No) Satisfaction`](https://4matic.github.io/trackparse/playground/#track=The%20Rolling%20Stones%20-%20%28I%20Can%27t%20Get%20No%29%20Satisfaction) | The Rolling Stones | `(I Can't Get No) Satisfaction` | kept as is | ## Tracklists @@ -351,13 +365,16 @@ all four languages. To try your own strings, use the Mixes and podcasts come with a tracklist: a block of text, one track per line, usually with a start time in front. The tracklist module reads the whole block: `trackparse/tracklist` in JavaScript, -`trackparse.tracklist` in Python, `trackparse::tracklist` in Rust, and `ParseTracklist` in the -main Go package. Each line gets its kind, its time -and a full `ParsedTrack`. The list as a whole gets checks with line numbers, and edits rewrite only -the lines you name. +`trackparse.tracklist` in Python, [`trackparse::tracklist`](https://docs.rs/trackparse/latest/trackparse/tracklist/index.html) in Rust, and +[`ParseTracklist`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseTracklist) in the main Go package. Each line gets its +[kind](https://4matic.github.io/trackparse/guides/tracklists/#line-kinds), its [time](https://4matic.github.io/trackparse/guides/tracklists/#times) and a full +[`ParsedTrack`](https://4matic.github.io/trackparse/reference/parse/#parsedtrack). The list as a whole gets +[checks with line numbers](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings), and [edits](https://4matic.github.io/trackparse/guides/editing-tracklists/) +rewrite only the lines you name. The rules are [R13 in the spec](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists). Nothing is thrown away here either. Every line comes back with its original text and its own line -ending, so joining `raw + eol` over the entries gives you the input byte for byte. CRLF, LF and CR +ending, so joining `raw + eol` over the entries gives you the input byte for byte +([R13.1](https://4matic.github.io/trackparse/reference/spec/#r131-lines-and-the-lossless-guarantee)). CRLF, LF and CR all work, and trailing spaces survive. ```js @@ -399,11 +416,12 @@ list.stats; ``` `00:11:02` sits between `01:07:44` and `01:15:36`. Changing one digit gives exactly one time that -fits, `01:11:02`, so the warning carries it as a suggestion. When several fixes would fit, or none, -`suggestion` is `null` and you only get the warning. +fits, `01:11:02`, so the warning carries it as a [suggestion](https://4matic.github.io/trackparse/reference/warnings/#suggestions). When several +fixes would fit, or none, `suggestion` is `null` and you only get the warning. +[Open this list in the playground](https://4matic.github.io/trackparse/playground/#list=Hour%202%0A48%3A20%20Noisia%20-%20Stigma%0A52%3A47%20Mefjus%20%26%20Kasra%20-%20Bandwagon%20%28Phace%20Remix%29%0A56%3A05%20Black%20Sun%20Empire%20-%20ID%0A59%3A31%20Alix%20Perez%20-%20Fade%20Away%0A01%3A03%3A10%20Interview%20with%20Hybris%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20feat.%20Teddy%20Killerz%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top) to see every entry, or paste your own. -Edits work on the text and return new text. Apply the suggestion, then push everything from line 5 -on back by 45 seconds: +[Edits](https://4matic.github.io/trackparse/reference/tracklist/#edits) work on the text and return new text. Apply the +suggestion, then push everything from line 5 on back by 45 seconds: ```js const fix = list.warnings[1].suggestion; @@ -427,7 +445,7 @@ result.text.split("\r\n").slice(4); Lines 1 to 4 are untouched, CRLF included. A rewritten time keeps its line's style (hours or not, digit widths, fraction digits), so `52:47` plus 45 seconds would stay `MM:SS`. `59:31` crossed the hour, so it became `01:00:16` to match the list's other hour times, and the edit tells you with -`style-upgraded`. A time pushed below zero stops at `00:00` and warns `time-clamped`. A bad edit +`style-upgraded` ([edit warnings](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings)). A time pushed below zero stops at `00:00` and warns `time-clamped`. A bad edit (missing line, line without a time, `NaN`) changes nothing and warns `edit-invalid`. Neither function throws. @@ -448,7 +466,7 @@ result.changed # (5, 6, 7, 8, 9) result.warnings # (EditWarning(code='style-upgraded', edit=1, line=5),) ``` -In Rust an edit is an `Edit` value, and seconds are `f64`: +In Rust an edit is an [`Edit`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.Edit.html) value, and seconds are `f64`: ```rust use trackparse::tracklist::{apply_edits, parse_tracklist, Edit}; @@ -461,7 +479,7 @@ result.changed; // [5, 6, 7, 8, 9] result.warnings; // [EditWarning { code: StyleUpgraded, edit: 1, line: Some(5) }] ``` -In Go an edit is an `Edit` value built by a constructor, and seconds are `float64`: +In Go an edit is an [`Edit`](https://pkg.go.dev/github.com/4matic/trackparse/go#Edit) value built by a constructor, and seconds are `float64`: ```go fmt.Println(*trackparse.ParseTracklist(text).Warnings[1].Suggestion) @@ -491,24 +509,28 @@ text starts with `w/` is `layered`: a track played over the previous one Inside a tracklist the first ` - ` is the artist/title separator on practically every line. A single track string doesn't get that benefit of the doubt, so `parse()` sometimes reads the part after the -dash as a version or a genre. `parseTracklist` parses each line with `mode: "tracklist"`, which -trusts the first spaced dash. You can ask `parse()` for it too (`mode="tracklist"` in Python, +dash as a version or a genre. `parseTracklist` parses each line with +[`mode: "tracklist"`](https://4matic.github.io/trackparse/guides/modes/#tracklist-mode), which trusts the first spaced dash +([R13.6](https://4matic.github.io/trackparse/reference/spec/#r136-tracklist-mode)). You can ask `parse()` for it too (`mode="tracklist"` in Python, `ModeOption::Tracklist` in Rust, `ModeTracklist` in Go). These are real lines from a podcast archive: | Line | `parse(line)` | In a tracklist | |---|---|---| -| `Electrosoul System - Liquid Metal` | title `Electrosoul System`, `Liquid Metal` as genre junk | Electrosoul System / `Liquid Metal` | -| `Effector - 2012` | title `Effector`, year 2012 | Effector / `2012` | -| `Paperclip - Anticipation VIP` | title `Paperclip`, a `vip` version | Paperclip / `Anticipation VIP` | -| `ez4cheezy - Zhukovskiy dub` | title `ez4cheezy`, a `dub` version | ez4cheezy / `Zhukovskiy dub` | +| [`Electrosoul System - Liquid Metal`](https://4matic.github.io/trackparse/playground/#track=Electrosoul%20System%20-%20Liquid%20Metal&mode=tracklist) | title `Electrosoul System`, `Liquid Metal` as genre junk | Electrosoul System / `Liquid Metal` | +| [`Effector - 2012`](https://4matic.github.io/trackparse/playground/#track=Effector%20-%202012&mode=tracklist) | title `Effector`, year 2012 | Effector / `2012` | +| [`Paperclip - Anticipation VIP`](https://4matic.github.io/trackparse/playground/#track=Paperclip%20-%20Anticipation%20VIP&mode=tracklist) | title `Paperclip`, a `vip` version | Paperclip / `Anticipation VIP` | +| [`ez4cheezy - Zhukovskiy dub`](https://4matic.github.io/trackparse/playground/#track=ez4cheezy%20-%20Zhukovskiy%20dub&mode=tracklist) | title `ez4cheezy`, a `dub` version | ez4cheezy / `Zhukovskiy dub` | | `8 Linkin Park_-_Points Of Authority (Gydra Bootleg)` | no separator | position 8, Linkin Park / `Points Of Authority`, bootleg by Gydra | | `10 Optiv & BTK-Inception (Gydra remix)` | no separator | position 10, Optiv, BTK / `Inception`, remix by Gydra | The last two rows need the neighbours. A bare `8 ` only counts as a position when the nearest line -before or after it that has a time or a spaced dash starts with a bare 7 or 9. Dotted numbers like -`01.` never count as neighbours, so `2 Unlimited - No Limit` between `01.` and `03.` stays an artist. The tight +before or after it that has a time or a spaced dash starts with a bare 7 or 9 +([bare track numbers](https://4matic.github.io/trackparse/guides/tracklists/#bare-track-numbers), +[R13.5](https://4matic.github.io/trackparse/reference/spec/#r135-bare-positions)). Dotted numbers like `01.` never count as +neighbours, so `2 Unlimited - No Limit` between `01.` and `03.` stays an artist. The tight `BTK-Inception` dash only splits on a timed line without a marker word, and only when at least half -of the list uses spaced dashes. +of the list uses spaced dashes ([R6.10](https://4matic.github.io/trackparse/reference/spec/#r6-artisttitle-separator)). +[Try both lines with their neighbours](https://4matic.github.io/trackparse/playground/#list=00%3A00%207%20Noisia%20-%20Stigma%0A03%3A00%208%20Linkin%20Park_-_Points%20Of%20Authority%20%28Gydra%20Bootleg%29%0A06%3A00%209%20Optiv%20%26%20BTK-Inception%20%28Gydra%20remix%29%0A09%3A00%2010%20Imanu%20-%20Sacrifice) in the playground. ## How it's tested @@ -520,16 +542,17 @@ fixtures pin it down, and every port has to pass all of them. The JS and Python Rust crate and the Go module all do: **13,130 of 13,130**, with empty skip lists, in CI on every push. -Passing a fixture only checks the fields the case asserts, so +Passing a fixture only checks the fields the case asserts ([matching rules](spec/fixtures/README.md#matching-semantics-match-partial)), so [`scripts/compare-ports.mjs`](scripts/compare-ports.mjs) also runs every fixture input through all four ports and diffs the complete outputs, tracklists and edits included. Result: 0 differences, byte for byte. [`scripts/fuzz-ports.mjs`](scripts/fuzz-ports.mjs) does the same with random input. The Rust crate and the Go module were each compared with JS on about 500,000 random single-track -cases and 290,000 random tracklists with edits: 0 differences. +cases and 290,000 random tracklists with edits: 0 differences +([port against port](https://4matic.github.io/trackparse/project/testing/#port-against-port)). ### Handwritten: 1,203 cases in 27 files -Each case cites the spec rules it exercises. 62 of them spell out the complete output field by +Each case cites the [spec rules](https://4matic.github.io/trackparse/reference/spec/) it exercises. 62 of them spell out the complete output field by field, so nothing can drift unnoticed. | Group | Cases | What's in there | @@ -573,7 +596,8 @@ line; the expected tracks are the plain lines' tracks. ### Properties -Each port also checks the invariants from the spec on thousands of random strings. The JS suite +Each port also checks the [invariants from the spec](https://4matic.github.io/trackparse/reference/spec/#invariants) on thousands +of random strings. The JS suite uses [fast-check](https://github.com/dubzzz/fast-check), the Python suite [Hypothesis](https://hypothesis.works), and the Rust crate and the Go module small seeded generators of their own, so they need no extra dev dependency. The Go module also has fuzz @@ -588,7 +612,8 @@ targets for `go test -fuzz`. The invariants: - no word of the input goes missing (the Rust and Go suites); - `parse(format(parse(s)))` round-trips. -For tracklists, on random multi-line text and random edit lists: +For tracklists, on random multi-line text and random edit lists +([R13.11](https://4matic.github.io/trackparse/reference/spec/#r1311-tracklist-invariants)): - `raw + eol` over all entries gives the input back, and `lead + time + gap + rest` gives `raw`; - `applyEdits(t, [])` returns `t`, and an edit never touches a line it doesn't name; @@ -644,14 +669,18 @@ The four packages have the same functions: | JavaScript | Python | Rust | Go | |---|---|---|---| -| `parse(input, options?)` | `parse(input, **options)` | `parse(input)`, `parse_with(input, &options)` | `Parse(input)`, `ParseWith(input, options)` | -| `parseArtists(input, options?)` | `parse_artists(input, **options)` | `parse_artists(input)`, `parse_artists_with(input, &options)` | `ParseArtists(input)`, `ParseArtistsWith(input, options)` | -| `format(track, options?)` | `format_track(track, **options)` | `format_track(&track)`, `format_track_with(&track, &options)` | `Format(track)`, `FormatWith(track, options)` | -| `normalize(input)` | `normalize(input)` | `normalize(input)` | `Normalize(input)` | -| `allArtists(track)` | `all_artists(track)` | `all_artists(&track)` | `AllArtists(track)` | -| `createParser(options)` | `create_parser(**options)` | `Parser::new(&options)` | `NewParser(options)` | -| `SPEC_VERSION` | `SPEC_VERSION` | `SPEC_VERSION` | `SpecVersion` | -| `parseTracklist`, `applyEdits` from `trackparse/tracklist` | `parse_tracklist`, `apply_edits` from `trackparse.tracklist` | `parse_tracklist(_with)`, `apply_edits(_with)` from `trackparse::tracklist` | `ParseTracklist(With)`, `ApplyEdits(With)` in the same package | +| [`parse(input, options?)`](https://4matic.github.io/trackparse/reference/parse/) | `parse(input, **options)` | [`parse(input)`](https://docs.rs/trackparse/latest/trackparse/fn.parse.html), [`parse_with(input, &options)`](https://docs.rs/trackparse/latest/trackparse/fn.parse_with.html) | [`Parse(input)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Parse), [`ParseWith(input, options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseWith) | +| [`parseArtists(input, options?)`](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) | `parse_artists(input, **options)` | [`parse_artists(input)`](https://docs.rs/trackparse/latest/trackparse/fn.parse_artists.html), [`parse_artists_with(input, &options)`](https://docs.rs/trackparse/latest/trackparse/fn.parse_artists_with.html) | [`ParseArtists(input)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseArtists), [`ParseArtistsWith(input, options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseArtistsWith) | +| [`format(track, options?)`](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) | `format_track(track, **options)` | [`format_track(&track)`](https://docs.rs/trackparse/latest/trackparse/fn.format_track.html), [`format_track_with(&track, &options)`](https://docs.rs/trackparse/latest/trackparse/fn.format_track_with.html) | [`Format(track)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Format), [`FormatWith(track, options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#FormatWith) | +| [`normalize(input)`](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) | `normalize(input)` | [`normalize(input)`](https://docs.rs/trackparse/latest/trackparse/fn.normalize.html) | [`Normalize(input)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Normalize) | +| [`allArtists(track)`](https://4matic.github.io/trackparse/reference/functions/#allartiststrack) | `all_artists(track)` | [`all_artists(&track)`](https://docs.rs/trackparse/latest/trackparse/fn.all_artists.html) | [`AllArtists(track)`](https://pkg.go.dev/github.com/4matic/trackparse/go#AllArtists) | +| [`createParser(options)`](https://4matic.github.io/trackparse/reference/functions/#createparseroptions) | `create_parser(**options)` | [`Parser::new(&options)`](https://docs.rs/trackparse/latest/trackparse/struct.Parser.html) | [`NewParser(options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#NewParser) | +| [`SPEC_VERSION`](https://4matic.github.io/trackparse/reference/functions/#spec_version) | `SPEC_VERSION` | [`SPEC_VERSION`](https://docs.rs/trackparse/latest/trackparse/constant.SPEC_VERSION.html) | [`SpecVersion`](https://pkg.go.dev/github.com/4matic/trackparse/go#SpecVersion) | +| [`parseTracklist`](https://4matic.github.io/trackparse/reference/tracklist/#parsetracklisttext-options), [`applyEdits`](https://4matic.github.io/trackparse/reference/tracklist/#applyeditstext-edits-options) from `trackparse/tracklist` | `parse_tracklist`, `apply_edits` from `trackparse.tracklist` | [`parse_tracklist(_with)`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.parse_tracklist.html), [`apply_edits(_with)`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.apply_edits.html) from [`trackparse::tracklist`](https://docs.rs/trackparse/latest/trackparse/tracklist/index.html) | [`ParseTracklist(With)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseTracklist), [`ApplyEdits(With)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ApplyEdits) in the same package | + +The JavaScript names link to the [API reference](https://4matic.github.io/trackparse/reference/parse/), which shows every +language, Python included, in tabs. The Rust and Go names link to [docs.rs](https://docs.rs/trackparse) +and [pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go). The tables below use the JavaScript names, which are also the keys of the JSON output. In Python and Rust, options and fields are snake_case (`knownArtists` is `known_artists`, `fullTitle` is @@ -661,34 +690,34 @@ structs with `Vec` and `Option`, the fixed sets of names are enums (`VersionType exported CamelCase fields (`FullTitle`, `Version.Type`), pointers where the JSON has `null`, and typed string constants for the fixed sets (`trackparse.VersionTypeRemix`). Each package README lists its own signatures and types: [JavaScript](js/README.md#api), [Python](python/README.md#api), -[Rust](rust/README.md#api), [Go](go/README.md#api). The Rust items are also on -[docs.rs](https://docs.rs/trackparse), the Go ones on -[pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go). +[Rust](rust/README.md#api), [Go](go/README.md#api). No function throws or panics on any string, and bad options fall back to the defaults. The one exception is Python, which raises `TypeError` when the input is not a `str`. ### `parse(input, options?)` → `ParsedTrack` +**Docs:** [ParsedTrack](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) · [What it understands](https://4matic.github.io/trackparse/guides/what-it-understands/) + | Field | Type | | |---|---|---| | `input` | `string` | The original string, untouched | -| `mode` | `"clean" \| "youtube" \| "filename" \| "tracklist"` | Resolved mode | -| `position` | `{ raw, number } \| null` | Track number (`"01"` → 1) | -| `timestamp` | `{ raw, seconds } \| null` | Leading cue time (`"1:02:03"` → 3723) | -| `artists` | `Artist[]` | Primary, featured and producer credits. Remixers live in `versions` | +| `mode` | `"clean" \| "youtube" \| "filename" \| "tracklist"` | Resolved [mode](https://4matic.github.io/trackparse/guides/modes/) | +| `position` | `{ raw, number } \| null` | [Track number](https://4matic.github.io/trackparse/guides/junk-and-flags/#track-numbers) (`"01"` → 1) | +| `timestamp` | `{ raw, seconds } \| null` | Leading [cue time](https://4matic.github.io/trackparse/guides/junk-and-flags/#cue-times) (`"1:02:03"` → 3723) | +| `artists` | `Artist[]` | Primary, featured and producer [credits](https://4matic.github.io/trackparse/guides/artists/). Remixers live in `versions` | | `title` | `string` | Clean title. Brackets it doesn't recognize stay in | | `fullTitle` | `string` | `title` with versions re-attached | -| `versions` | `Version[]` | Remixes and versions, left to right | -| `year` | `number \| null` | From `(2015)` or `- 2015` | -| `flags` | `{ explicit, clean, unknownArtist, unknownTitle }` | | -| `junk` | `{ raw, kind }[]` | What was removed, and what kind of noise it was | -| `warnings` | `string[]` | Heuristics that fired | +| `versions` | `Version[]` | [Remixes and versions](https://4matic.github.io/trackparse/guides/versions/), left to right | +| `year` | `number \| null` | [From](https://4matic.github.io/trackparse/guides/junk-and-flags/#year) `(2015)` or `- 2015` | +| `flags` | `{ explicit, clean, unknownArtist, unknownTitle }` | [Flags](https://4matic.github.io/trackparse/guides/junk-and-flags/#flags) | +| `junk` | `{ raw, kind }[]` | What was removed, and what [kind of noise](https://4matic.github.io/trackparse/guides/junk-and-flags/#junk) it was | +| `warnings` | `string[]` | [Heuristics that fired](https://4matic.github.io/trackparse/reference/warnings/#track-warnings) |
Artist, Version, junk kinds and warnings -**Artist:** `{ name, role, joiner, source }` +**[Artist](https://4matic.github.io/trackparse/reference/parse/#artist):** `{ name, role, joiner, source }` - `role` is `primary`, `featured`, `remixer` or `producer`. `&`, `x` and `vs.` are joiners, not roles. - `joiner` is the text before the name as written (`"&"`, `","`, `"ft."`, `"prod. by"`), or `null` @@ -696,18 +725,18 @@ exception is Python, which raises `TypeError` when the input is not a `str`. - `source` is where the credit came from: `artist` (left of the dash), `title` (right of it) or `version`. -**Version:** `{ type, raw, artists, modifiers, descriptor, year, unknownArtist, delimiter }` +**[Version](https://4matic.github.io/trackparse/reference/parse/#version):** `{ type, raw, artists, modifiers, descriptor, year, unknownArtist, delimiter }` - `type`: `remix` `bootleg` `vip` `edit` `flip` `refix` `rework` `mashup` `blend` `dub` `mix` `extended` `radio` `club` `original` `instrumental` `acapella` `live` `acoustic` `remaster` `demo` `reprise` `cover` `version` `spedUp` `slowed` `nightcore` -- A generic word takes its type from the word in front of it: `Radio Edit` → radio, +- A [generic word](https://4matic.github.io/trackparse/guides/versions/#generic-words-borrow-their-meaning) takes its type from the word in front of it: `Radio Edit` → radio, `Extended Mix` → extended. ` Mix` is a remix by that name. - `modifiers` holds words that didn't become the type (`Extended VIP Mix` → vip, `["extended"]`). `descriptor` holds leftover text (`"Taylor's"`, `"at Wembley"`, `"D'n'B"`). - `delimiter` is `(`, `[`, `{`, or `-` for dash suffixes. -**Junk kinds:** `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. +**[Junk kinds](https://4matic.github.io/trackparse/reference/parse/#junk-kinds):** `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. The vocabulary is in [`spec/data`](spec/data). **Warnings:** `noSeparator`, `ambiguousSeparator`, `unspacedDashSplit`, `asymmetricDashSplit`, @@ -724,17 +753,19 @@ The JSON shape is fixed by [`spec/schema/parsed-track.schema.json`](spec/schema/ | Option | Default | | |---|---|---| -| `mode` | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or detect from the string | -| `knownArtists` | `[]` | Names that are never split (`Chase & Status`, `Earth, Wind & Fire`) | -| `uploader` | – | YouTube channel; in youtube mode it's used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | -| `splitAnd` | `"auto"` | `and` splits only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole | -| `keywords` | – | Extra vocabulary: `versionHeads`, `descriptors`, `genres`, `junk`, `featMarkers` | +| [`mode`](https://4matic.github.io/trackparse/guides/modes/) | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or detect from the string | +| [`knownArtists`](https://4matic.github.io/trackparse/guides/artists/#knownartists) | `[]` | Names that are never split (`Chase & Status`, `Earth, Wind & Fire`) | +| [`uploader`](https://4matic.github.io/trackparse/guides/modes/#the-uploader-fallback) | – | YouTube channel; in youtube mode it's used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | +| [`splitAnd`](https://4matic.github.io/trackparse/guides/artists/#and-is-special) | `"auto"` | `and` splits only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole | +| [`keywords`](https://4matic.github.io/trackparse/reference/options/#keywords) | – | Extra vocabulary: `versionHeads`, `descriptors`, `genres`, `junk`, `featMarkers` | JavaScript takes an options object, Python takes keyword arguments -(`parse(s, mode="youtube", uploader="Daft Punk")`), Rust takes a builder +(`parse(s, mode="youtube", uploader="Daft Punk")`), Rust takes a builder, +[`ParseOptions`](https://docs.rs/trackparse/latest/trackparse/struct.ParseOptions.html) (`parse_with(s, &ParseOptions::new().mode(ModeOption::Youtube).uploader("Daft Punk"))`), and Go -takes a struct whose zero value is the default -(`ParseWith(s, ParseOptions{Mode: ModeYouTube, Uploader: "Daft Punk"})`). +takes a struct whose zero value is the default, [`ParseOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseOptions) +(`ParseWith(s, ParseOptions{Mode: ModeYouTube, Uploader: "Daft Punk"})`). The rules for options are +[R12](https://4matic.github.io/trackparse/reference/spec/#r12-options) in the spec. ### Other functions @@ -742,12 +773,12 @@ takes a struct whose zero value is the default | Function | | |---|---| -| `parseArtists(input, options?)` | Split a bare artist string into credits | -| `format(track, options?)` | Render back to a string. Options: `feat` (`source`/`artist`/`title`/`omit`), `featMarker`, `joiners` (`original`/`canonical`), `versions`, `producers`, `position` | -| `normalize(input)` | The Unicode cleanup every function runs first: NFC, invisible characters, dash, bracket and quote variants | -| `allArtists(track)` | Credits plus every remixer, deduplicated | -| `createParser(options)` | Compile options once for repeated calls; per-call options merge over them | -| `SPEC_VERSION` | The spec version this build implements | +| [`parseArtists(input, options?)`](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) | Split a bare artist string into credits ([R10](https://4matic.github.io/trackparse/reference/spec/#r10-parseartists)) | +| [`format(track, options?)`](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) | Render back to a string ([R11](https://4matic.github.io/trackparse/reference/spec/#r11-format)). [Options](https://4matic.github.io/trackparse/reference/options/#format-options): `feat` (`source`/`artist`/`title`/`omit`), `featMarker`, `joiners` (`original`/`canonical`), `versions`, `producers`, `position` | +| [`normalize(input)`](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) | The Unicode cleanup every function runs first: NFC, invisible characters, dash, bracket and quote variants ([R1](https://4matic.github.io/trackparse/reference/spec/#r1-normalization)) | +| [`allArtists(track)`](https://4matic.github.io/trackparse/reference/functions/#allartiststrack) | Credits plus every remixer, deduplicated | +| [`createParser(options)`](https://4matic.github.io/trackparse/reference/functions/#createparseroptions) | Compile options once for repeated calls; per-call options merge over them | +| [`SPEC_VERSION`](https://4matic.github.io/trackparse/reference/functions/#spec_version) | The spec version this build implements | ```js import { createParser } from "trackparse"; @@ -795,15 +826,15 @@ fmt.Println(parser.Parse("Chase & Status x Camo & Krooked - Track (Alix Perez Re ### Modes -**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) +**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) · [R2 in the spec](https://4matic.github.io/trackparse/reference/spec/#r2-mode-prelude) | Mode | For | Adds | |---|---|---| | `clean` | Store metadata, tags | Only a spaced dash separates artist and title | -| `youtube` | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | -| `filename` | Files | Strips the extension, `_` → space, `01-Track` numbering | -| `auto` | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise | -| `tracklist` | One line of a tracklist | The first spaced dash always separates, and the words right after it are never read as a version or genre suffix. `_-_` splits too. `auto` never picks it | +| [`youtube`](https://4matic.github.io/trackparse/guides/modes/#youtube-mode) | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | +| [`filename`](https://4matic.github.io/trackparse/guides/modes/#filename-mode) | Files | Strips the extension, `_` → space, `01-Track` numbering | +| [`auto`](https://4matic.github.io/trackparse/guides/modes/#how-auto-decides) | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise | +| [`tracklist`](https://4matic.github.io/trackparse/guides/modes/#tracklist-mode) | One line of a tracklist | The first spaced dash always separates, and the words right after it are never read as a version or genre suffix. `_-_` splits too. `auto` never picks it | ### Tracklist API @@ -816,18 +847,20 @@ JSON shape is fixed by [`spec/schema/tracklist.schema.json`](spec/schema/trackli #### `parseTracklist(text, options?)` → `Tracklist` -`{ specVersion, entries, warnings, stats }`, every key always present. One entry per line: +`{ specVersion, entries, warnings, stats }`, every key always present +([reference](https://4matic.github.io/trackparse/reference/tracklist/#parsetracklisttext-options), [R13.8](https://4matic.github.io/trackparse/reference/spec/#r138-output)). One +[entry](https://4matic.github.io/trackparse/reference/tracklist/#tracklistentry) per line: | Field | Type | | |---|---|---| | `line` | `number` | 1-based | -| `kind` | `"track" \| "marker" \| "header" \| "link" \| "note" \| "blank"` | See below | +| `kind` | `"track" \| "marker" \| "header" \| "link" \| "note" \| "blank"` | See below and [R13.3](https://4matic.github.io/trackparse/reference/spec/#r133-line-kinds) | | `eol` | `"\n" \| "\r\n" \| "\r" \| ""` | The line's own terminator; `""` on a last line without one | | `raw` | `string` | The line exactly as written, never normalized | | `parts` | `{ lead, time, gap, rest }` | `raw` cut into four strings that join back into it. `lead` is spaces, a list bullet, Markdown emphasis or an opening bracket, `gap` is what sits between the time and the track (`] `, ` - `, ` \| `, ` => `) | -| `time` | `{ raw, seconds } \| null` | `12:34`, `1:02:03`, `125:30` (long mixes), `00:00:07.500` (7.5 s) | +| `time` | `{ raw, seconds } \| null` | [Time forms](https://4matic.github.io/trackparse/guides/tracklists/#times) ([R13.2](https://4matic.github.io/trackparse/reference/spec/#r132-times)): `12:34`, `1:02:03`, `125:30` (long mixes), `00:00:07.500` (7.5 s) | | `track` | `ParsedTrack \| null` | Parsed from `rest` in tracklist mode, without Markdown emphasis, a leading `w/` and a bare track number. Only `track` and `marker` lines have one | -| `layered` | `boolean` | The track text (after any time) starts with `w/` and a space: a track played over the previous one | +| `layered` | `boolean` | The track text (after any time) starts with `w/` and a space: a track played over the previous one ([R13.13](https://4matic.github.io/trackparse/reference/spec/#r1313-layered-tracks)) | Kinds: a line with a time is a `marker` when it has no separator and a word like `intro`, `break` or `interview` ([`spec/data/marker-words.json`](spec/data/marker-words.json)), otherwise a @@ -835,31 +868,33 @@ or `interview` ([`spec/data/marker-words.json`](spec/data/marker-words.json)), o separator is a `track`, one with a marker word and no separator is a `marker`, and anything else is a `note`. No line is ever dropped. -`stats` is `{ lines, tracks, markers, timed, firstTime, lastTime }`. +[`stats`](https://4matic.github.io/trackparse/reference/tracklist/#stats) is `{ lines, tracks, markers, timed, firstTime, lastTime }`. -`warnings` are `{ code, line, severity, suggestion }`, sorted by line. Per-line `ParsedTrack` +[`warnings`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) are `{ code, line, severity, suggestion }`, sorted by line +([R13.7](https://4matic.github.io/trackparse/reference/spec/#r137-warnings)). Per-line `ParsedTrack` warnings stay on `entries[i].track.warnings` and are not repeated here. | Code | Severity | When | |---|---|---| -| `time-missing` | warning | A track line has no time while other lines do (not raised on a `w/` line) | -| `time-out-of-order` | warning | Earlier than the previous timed line. May carry a `suggestion` | -| `time-duplicate` | warning | Same time as the previous timed line | -| `no-start-at-zero` | info | The first time isn't `0:00` | -| `time-after-audio-end` | warning | Past `audioSeconds` | -| `invalid-time` | warning | Looks like a time but isn't one (`1:75`, `0:61:00`). The line keeps it in `rest` | -| `position-gap` | warning | A track number isn't the previous one + 1 | -| `position-duplicate` | warning | Same track number as the previous one | -| `line-unparsed` | warning | A track line with no artist/title separator, or with nothing after the time | - -A `suggestion` is `{ line, raw, seconds }`: the one time, one or two digits away from the +| [`time-missing`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=time%2Dmissing) | warning | A track line has no time while other lines do (not raised on a `w/` line) | +| [`time-out-of-order`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=time%2Dout%2Dof%2Dorder) | warning | Earlier than the previous timed line. May carry a `suggestion` | +| [`time-duplicate`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=time%2Dduplicate) | warning | Same time as the previous timed line | +| [`no-start-at-zero`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=no%2Dstart%2Dat%2Dzero) | info | The first time isn't `0:00` | +| [`time-after-audio-end`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=time%2Dafter%2Daudio%2Dend) | warning | Past `audioSeconds` | +| [`invalid-time`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=invalid%2Dtime) | warning | Looks like a time but isn't one (`1:75`, `0:61:00`). The line keeps it in `rest` | +| [`position-gap`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=position%2Dgap) | warning | A track number isn't the previous one + 1 | +| [`position-duplicate`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=position%2Dduplicate) | warning | Same track number as the previous one | +| [`line-unparsed`](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings:~:text=line%2Dunparsed) | warning | A track line with no artist/title separator, or with nothing after the time | + +A [`suggestion`](https://4matic.github.io/trackparse/reference/warnings/#suggestions) is `{ line, raw, seconds }`: the one time, one or two digits away from the original, that puts the line back in order. If no time fits, it tries the previous timed line instead, since sometimes that is the typo (`01:22:21` followed by `01:03:55` suggests fixing the first one to `01:02:21`). Several candidates or none give `null`. #### `applyEdits(text, edits, options?)` → `{ text, changed, warnings }` -Edits run in order, each on the result of the one before, with line numbers as that text has them. +Edits run in order, each on the result of the one before, with line numbers as that text has them +([reference](https://4matic.github.io/trackparse/reference/tracklist/#applyeditstext-edits-options), [R13.9](https://4matic.github.io/trackparse/reference/spec/#r139-edits)). | Edit | Effect | |---|---| @@ -871,19 +906,19 @@ Edits run in order, each on the result of the one before, with line numbers as t | `{ op: "delete", line }` | Remove a line | `changed` lists the final line numbers of every line an edit wrote. Every other line keeps its -bytes and its line ending. Edit warnings are `{ code, edit, line }`, where `edit` is the index in +bytes and its line ending. [Edit warnings](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings) are `{ code, edit, line }`, where `edit` is the index in `edits` and `line` is `null` when the edit names no line (an unknown `op`, say): | Code | When | |---|---| -| `style-upgraded` | A time without hours passed one hour and gained them (`59:31` → `01:00:16`) | -| `time-clamped` | A time would go below zero and was set to zero | -| `edit-invalid` | Missing line, no time to set, a non-finite number, a time too large to write, a line break in `text`/`rest`, an unknown `op`. That edit changed nothing | +| [`style-upgraded`](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings:~:text=style%2Dupgraded) | A time without hours passed one hour and gained them (`59:31` → `01:00:16`) | +| [`time-clamped`](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings:~:text=time%2Dclamped) | A time would go below zero and was set to zero | +| [`edit-invalid`](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings:~:text=edit%2Dinvalid) | Missing line, no time to set, a non-finite number, a time too large to write, a line break in `text`/`rest`, an unknown `op`. That edit changed nothing | #### Tracklist options -Both functions take the same options. `applyEdits` accepts them for symmetry; edits don't depend on -them. +Both functions take the same options ([R13.10](https://4matic.github.io/trackparse/reference/spec/#r1310-options)). `applyEdits` accepts them for +symmetry; edits don't depend on them. | Option | Default | | |---|---|---| @@ -895,19 +930,21 @@ them. Python uses keyword arguments (`audio_seconds=`, `marker_words=`) and plain dicts for edits, with the same keys as JS: `{"op": "shift", "seconds": 45, "from": 5}`. -Rust has `parse_tracklist_with` and `apply_edits_with`, which take +Rust has [`parse_tracklist_with`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.parse_tracklist_with.html) and +[`apply_edits_with`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.apply_edits_with.html), which take `&TracklistOptions::new().audio_seconds(3600.0).marker_words(["drop"])`. Edits are built with -constructors on `Edit`: `set_time(line, seconds)`, `shift(seconds)`, `shift_from(seconds, from)`, +constructors on [`Edit`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.Edit.html): `set_time(line, seconds)`, `shift(seconds)`, `shift_from(seconds, from)`, `shift_lines(seconds, lines)`, `sort_by_time()`, `set_rest(line, rest)`, `insert(after, text)` and `delete(line)`. -Go has `ParseTracklistWith` and `ApplyEditsWith`, which take +Go has [`ParseTracklistWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseTracklistWith) and +[`ApplyEditsWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ApplyEditsWith), which take a [`TracklistOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#TracklistOptions): `TracklistOptions{AudioSeconds: trackparse.Ptr(3600.0), MarkerWords: []string{"drop"}}`. Edits -are built with `SetTime(line, seconds)`, `Shift(seconds)`, `ShiftFrom(seconds, from)`, +are built with [`SetTime(line, seconds)`](https://pkg.go.dev/github.com/4matic/trackparse/go#SetTime), `Shift(seconds)`, `ShiftFrom(seconds, from)`, `ShiftLines(seconds, lines...)`, `SortByTime()`, `SetRest(line, rest)`, `Insert(after, text)` and -`Delete(line)`. `AudioSeconds` is a pointer, so `nil` (unknown) and an audio of length 0 are -different values, and `Mode: trackparse.ModeAuto` parses each line in auto mode -([details](go/README.md#pointer-fields-and-ptr)). +`Delete(line)`, which all return an [`Edit`](https://pkg.go.dev/github.com/4matic/trackparse/go#Edit). `AudioSeconds` is a pointer, so `nil` +(unknown) and an audio of length 0 are different values, and `Mode: trackparse.ModeAuto` parses +each line in auto mode ([details](go/README.md#pointer-fields-and-ptr)). More on the options: [Tracklist options](https://4matic.github.io/trackparse/reference/options/#tracklist-options). @@ -915,7 +952,8 @@ More on the options: [Tracklist options](https://4matic.github.io/trackparse/ref **Docs:** [How it works](https://4matic.github.io/trackparse/project/how-it-works/) -The parser is a fixed pipeline of hand-written scanners over code points. It uses no regexes with +The parser is a fixed pipeline of hand-written scanners over code points +([R0 portability](https://4matic.github.io/trackparse/reference/spec/#r0-portability)). It uses no regexes with lookaround or backreferences and nothing backtracks, so long input can't make it hang: each port's tests parse 10,000-code-point inputs under a time limit. Writing it this way is also what lets the Python, Rust and Go ports give the same output as JavaScript. @@ -932,13 +970,14 @@ flowchart LR TI --> D ``` -Brackets are swapped for placeholders before anything is split, so a `&` inside `(Chase & Status -Remix)` can't break the artist list. Groups are classified on their own: junk, feat, producer, flag, -year, version, or unknown. Unknown ones go back into the title untouched. The full rules, R0–R12, +Brackets are swapped for placeholders before anything is split ([R3](https://4matic.github.io/trackparse/reference/spec/#r3-group-scanner-and-skeleton)), +so a `&` inside `(Chase & Status Remix)` can't break the artist list. Groups are classified on +their own ([R5](https://4matic.github.io/trackparse/reference/spec/#r5-group-classification)): junk, feat, producer, flag, year, version, or +unknown. Unknown ones go back into the title untouched. The full rules, R0–R12, are in [spec/SPEC.md](spec/SPEC.md), which the site also shows as a [page](https://4matic.github.io/trackparse/reference/spec/). -Tracklists (R13) sit on top of that. The text is split into lines with their terminators, a small +Tracklists ([R13](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists)) sit on top of that. The text is split into lines with their terminators, a small scanner reads the time at the start of each line, and the rest goes through the same pipeline in tracklist mode. Two things look across lines: bare track numbers are only accepted when a neighbour continues the sequence, and the unspaced-dash split is only switched on when most of the list uses @@ -948,16 +987,17 @@ spaced dashes. The checks run last, over the finished entries. **Docs:** [Ports](https://4matic.github.io/trackparse/project/ports/) -| Language | Package | Needs | README | Changelog | -|---|---|---|---|---| -| JavaScript / TypeScript | [`trackparse`](https://www.npmjs.com/package/trackparse) on npm | Node 18+ or any ES2020 runtime, no dependencies | [js/README.md](js/README.md) | [js/CHANGELOG.md](js/CHANGELOG.md) | -| Python | [`trackparse`](https://pypi.org/project/trackparse/) on PyPI | Python 3.9+, no dependencies | [python/README.md](python/README.md) | [python/CHANGELOG.md](python/CHANGELOG.md) | -| Rust | [`trackparse`](https://crates.io/crates/trackparse) on crates.io ([docs.rs](https://docs.rs/trackparse)) | Rust 1.74+, `unicode-normalization`, optional `serde` feature | [rust/README.md](rust/README.md) | [rust/CHANGELOG.md](rust/CHANGELOG.md) | -| Go | [`github.com/4matic/trackparse/go`](https://pkg.go.dev/github.com/4matic/trackparse/go) on pkg.go.dev | Go 1.22+, no dependencies | [go/README.md](go/README.md) | [go/CHANGELOG.md](go/CHANGELOG.md) | +| Language | Package | Needs | API docs | README | Changelog | +|---|---|---|---|---|---| +| JavaScript / TypeScript | [`trackparse`](https://www.npmjs.com/package/trackparse) on npm | Node 18+ or any ES2020 runtime, no dependencies | [reference](https://4matic.github.io/trackparse/reference/parse/) | [js/README.md](js/README.md) | [js/CHANGELOG.md](js/CHANGELOG.md) | +| Python | [`trackparse`](https://pypi.org/project/trackparse/) on PyPI | Python 3.9+, no dependencies | [reference](https://4matic.github.io/trackparse/reference/parse/) | [python/README.md](python/README.md) | [python/CHANGELOG.md](python/CHANGELOG.md) | +| Rust | [`trackparse`](https://crates.io/crates/trackparse) on crates.io | Rust 1.74+, `unicode-normalization`, optional `serde` feature | [docs.rs](https://docs.rs/trackparse) | [rust/README.md](rust/README.md) | [rust/CHANGELOG.md](rust/CHANGELOG.md) | +| Go | [`github.com/4matic/trackparse/go`](https://pkg.go.dev/github.com/4matic/trackparse/go) | Go 1.22+, no dependencies | [pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go) | [go/README.md](go/README.md) | [go/CHANGELOG.md](go/CHANGELOG.md) | The JavaScript package is the reference implementation. All four pass 13,130 of 13,130 fixtures, and the Python, Rust and Go output is byte-identical to JavaScript on every fixture input. Go -releases are the tags `go/vX.Y.Z`, which the Go module proxy serves. +releases are the tags `go/vX.Y.Z`, which the Go module proxy serves +([versions](https://pkg.go.dev/github.com/4matic/trackparse/go?tab=versions)). The spec and the packages share one version number and are released together, so the same version means the same spec and the same fixtures in every language. The one known difference From a5477aa6d99beb127ab39f38e2d54106646e8953 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 02/11] docs: AGENTS.md lists go/LICENSE and the 0.6.0 release lessons, and asks docs to link the first mention of a rule, option, field, warning or function and to give examples a playground link --- AGENTS.md | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a84a465..ff042bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,6 +113,8 @@ go/ Go module `github.com/4matic/trackparse/go`, package ` AllArtists, Parser/NewParser, ParseTracklist(With), ApplyEdits(With); invalid UTF-8 is sanitized here (WHATWG maximal subparts to U+FFFD) doc.go package overview shown on pkg.go.dev + LICENSE a copy of the root MIT license: the module zip holds only go/, and + pkg.go.dev hides the docs of a module without a license it can detect types.go public structs and typed-string enums (mirror the schemas); nullable fields are pointers options.go ParseOptions, FormatOptions, Keywords, TracklistOptions (zero value = the @@ -189,7 +191,7 @@ scripts/dump_py.py Python side of compare-ports (JSONL in, to_dict() JSON .github/release-notes/ optional hand-written highlights prepended to a GitHub Release release-please-config.json, .release-please-manifest.json release automation (never hand-edit the manifest) js/CHANGELOG.md, spec/CHANGELOG.md, python/CHANGELOG.md, rust/CHANGELOG.md, go/CHANGELOG.md - generated by release-please (go/CHANGELOG.md from the first Go release on) + generated by release-please ``` ## Golden rule @@ -478,6 +480,27 @@ matching site pages (`README.md`, `js/README.md`, `python/README.md`, `rust/READ when a page or heading moves. Use full `https://4matic.github.io/trackparse/...` URLs: npm, PyPI, crates.io and pkg.go.dev render the package READMEs where relative links break. +**Link the first mention.** In each section of a README or a site page, link the first mention of +a rule, option, field, warning or function to the place that explains it, and only the first: + +- a site page and heading anchor (`reference/functions/#formattrack-options`, + `guides/artists/#knownartists`); warnings use the text fragments described under + [Site internals](#site-internals-worth-knowing); +- a spec rule on the generated spec page, `reference/spec/#r6-artisttitle-separator`. Only the + rule groups (`## R6 …`) and the R13 subsections (`#r132-times`, `#r1310-options`) have anchors; + a rule such as R6.10 links its group; +- the API docs of that language: docs.rs item pages + (`https://docs.rs/trackparse/latest/trackparse/fn.parse_with.html`, + `…/tracklist/enum.Edit.html`, `…/struct.ParsedTrack.html#method.to_json`) and pkg.go.dev + anchors (`https://pkg.go.dev/github.com/4matic/trackparse/go#ParseWith`, `#Track.MarshalJSON`). + Check the anchor on the live page; pkg.go.dev ids are the identifier, `Type.Method` for methods. + +Give an example a prefilled playground link when seeing the whole output helps ("try it", "open +this list in the playground"). The hash is `#track=` with optional `mode`, `splitAnd`, +`known` and `uploader`, or `#list=` with optional `audioSeconds` and `known`; each value is +`encodeURIComponent`-encoded, and in Markdown also encode `(`, `)` and `'` (`%28`, `%29`, `%27`) +so the link target stays intact. Open the link once to check it shows what the text claims. + **Moving or removing a page.** npm (`homepage`), PyPI (`[project.urls]`) and published READMEs point at site URLs that can't be changed after a release. When a page moves or disappears, add a `redirects` entry in `site/astro.config.mjs` so the old URL keeps working, then update the @@ -798,7 +821,7 @@ Version rules: retries (`GOPROXY=https://proxy.golang.org go list -m github.com/4matic/trackparse/go@vX.Y.Z`), runs `go get` and a small program from a clean module, requests the version's `.info` from the proxy (pkg.go.dev adds versions it sees there; the page can take a few minutes), and appends - install notes to the GitHub Release. **A published Go version is permanent**: the proxy and the + install notes to the GitHub Release. The 0.6.0 release was the first to run it, and it passed. **A published Go version is permanent**: the proxy and the checksum database keep the tag's content forever, even if the tag is deleted or moved. Never move or re-create a `go/v…` tag. A bad version can only be marked with a `retract` directive in `go/go.mod`, released in a new version. @@ -808,7 +831,7 @@ Version rules: `-f rust_tag=rust-vX.Y.Z` (crates.io) or `-f go_tag=go/vX.Y.Z` (the Go checks, proxy request and release notes; the module itself was published by the tag). The npm job always republishes from a fresh release; a failed npm publish needs the same treatment by hand. -- **Things the 0.5.0 release taught:** +- **Things the 0.5.0 and 0.6.0 releases taught:** - The release PR is opened with `GITHUB_TOKEN`, so no CI runs on it and GitHub shows it as `UNSTABLE`. That is expected; `main` was green when it was generated. - A `docs:` commit under `js/`, `python/`, `rust/` or `go/` (a package README) opens a release PR. A @@ -819,8 +842,15 @@ Version rules: - After a release, check every registry by API, not by badge: `registry.npmjs.org`, `pypi.org/pypi/trackparse/json`, `crates.io/api/v1/crates/trackparse`, and the Go proxy: `proxy.golang.org/github.com/4matic/trackparse/go/@v/list`. - - The Go component's first changelog links `go/v0.5.1...go/vX.Y.Z`, a tag that never existed - (the manifest starts Go at the linked 0.5.1), as rust's first entry linked `rust-v0.4.0`. + - The Go component's first changelog (0.6.0) links `go/v0.5.1...go/v0.6.0`, a tag that never + existed (the manifest started Go at the linked 0.5.1), as rust's first entry linked + `rust-v0.4.0`. Leave it: changelogs are not edited by hand, and the next entry links real tags. + - pkg.go.dev shows a module's documentation only when it detects a license file in the module + zip, and the zip of a module in `go/` holds only that folder: the root `LICENSE` is not in it. + `go/LICENSE` is a copy of it; keep the two the same. Since the zip of a published version + never changes, a missing license can only be fixed by a new version. + - Go has no registry badge with a version. The root README's "go module" badge reads the GitHub + tags (`github/v/tag/4matic/trackparse?filter=go%2Fv*`) and shows the whole tag, `go/v0.6.0`. - Don't force-push a PR branch to pick up `main`: GitHub's rebase-merge rebases it when there are no conflicts. - **Agents never merge release PRs, publish, push tags or bump versions on their own initiative.** From 27f3d828c7d1f9fe1553a79a045a6319ba6cb5e7 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 03/11] docs(js): link options, fields, modes, warnings and functions to the site reference and the spec rules, with playground links and the other packages' READMEs, changelogs and API docs --- js/README.md | 126 +++++++++++++++++++++++++++++---------------------- 1 file changed, 71 insertions(+), 55 deletions(-) diff --git a/js/README.md b/js/README.md index 5ec86e7..cbb1f2c 100644 --- a/js/README.md +++ b/js/README.md @@ -5,7 +5,7 @@ [![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/js.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/js.yml) [![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE) -**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** +**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[API reference](https://4matic.github.io/trackparse/reference/parse/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[Changelog](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md)** **Turn messy track names into structured data: who made it, who's featured, who remixed it, and what's just noise.** @@ -17,18 +17,19 @@ what's just noise.** 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. +doesn't recognize stays in the title, word for word +([try it in the playground](https://4matic.github.io/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D)). This is the JavaScript and TypeScript package of [trackparse](https://github.com/4matic/trackparse), and the reference implementation. Its behaviour -is defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and -pinned by 13,130 fixtures. It passes all of them, and the +is defined by a [shared spec](https://4matic.github.io/trackparse/reference/spec/) and +pinned by [13,130 fixtures](https://4matic.github.io/trackparse/project/testing/). It passes all of them, and the [Python, Rust and Go packages](#other-languages) return the same output for every one. - Node 18 or later, browsers and other runtimes (no Node-specific APIs) - No dependencies - ESM and CommonJS, TypeScript types included -- Never throws +- [Never throws](#errors) ## Install @@ -64,8 +65,9 @@ format(track, { joiners: "canonical" }); // 'Wilkinson feat. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)' ``` -The result is a plain object, so `JSON.stringify(track)` gives the spec's JSON form. Every key is -always present: +The result is a plain object, so `JSON.stringify(track)` gives the spec's JSON form +([`ParsedTrack`](#parsedtrack), [serializing](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json)). Every key +is always present: ```js console.log(JSON.stringify(track, null, 2)); @@ -128,19 +130,23 @@ parseTracklist(text: string, options?: TracklistOptions): Tracklist applyEdits(text: string, edits: Edit[], options?: TracklistOptions): EditResult ``` +Each function has a section below and one in the [API reference](https://4matic.github.io/trackparse/reference/functions/). +The tracklist functions are under [Tracklists](#tracklists). + ### `parse(input, options?)` **Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) -Parses one track string. +Parses one track string, running [rules R1 to R9](https://4matic.github.io/trackparse/reference/spec/#r1-normalization) of the +spec in order. | Option | Default | | |---|---|---| -| `mode` | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string. See [Modes](#modes) | -| `uploader` | – | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | -| `knownArtists` | `[]` | Names that are never split. There is no built-in list | -| `splitAnd` | `"auto"` | `"auto"` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `"always"`, `"never"` | -| `keywords` | – | Extra vocabulary, added to the built-in lists (see below) | +| [`mode`](https://4matic.github.io/trackparse/guides/modes/) | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string. See [Modes](#modes) | +| [`uploader`](https://4matic.github.io/trackparse/guides/modes/#the-uploader-fallback) | – | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | +| [`knownArtists`](https://4matic.github.io/trackparse/guides/artists/#knownartists) | `[]` | Names that are never split. There is no built-in list | +| [`splitAnd`](https://4matic.github.io/trackparse/guides/artists/#and-is-special) | `"auto"` | `"auto"` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `"always"`, `"never"` | +| [`keywords`](https://4matic.github.io/trackparse/reference/options/#keywords) | – | Extra vocabulary, added to the built-in lists (see below) | ```js parse("Chase & Status - Baddadan").artists.map((a) => a.name); @@ -152,7 +158,7 @@ parse("Simon and Garfunkel - Mrs. Robinson", { splitAnd: "always" }).artists.map // [ 'Simon', 'Garfunkel' ] ``` -`keywords` is an object with any of these keys: +`keywords` is an object with any of these keys ([your own words](https://4matic.github.io/trackparse/guides/versions/#your-own-words)): | Key | Type | | |---|---|---| @@ -218,10 +224,11 @@ parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0]; // descriptor: 'at Wembley', year: 1986, unknownArtist: false, delimiter: '(' } ``` -- `VersionType`: `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`, +- `VersionType` ([the 27 types](https://4matic.github.io/trackparse/guides/versions/#the-27-types)): `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`, `dub`, `mix`, `extended`, `radio`, `club`, `original`, `instrumental`, `acapella`, `live`, `acoustic`, `remaster`, `demo`, `reprise`, `cover`, `version`, `spedUp`, `slowed`, `nightcore`. -- `JunkKind`: `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. +- `JunkKind` ([junk kinds](https://4matic.github.io/trackparse/reference/parse/#junk-kinds)): `video`, `audio`, `lyrics`, `quality`, `promo`, + `platform`, `label`, `genre`, `other`. - `Warning`: see [Warnings](#warnings). The same shape is published as a JSON Schema, @@ -231,7 +238,7 @@ The same shape is published as a JSON Schema, **Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) -Splits a bare artist string (no title). Takes the same options as `parse`. +Splits a bare artist string (no title) ([R10](https://4matic.github.io/trackparse/reference/spec/#r10-parseartists)). Takes the same options as `parse`. ```js import { parseArtists } from "trackparse"; @@ -249,7 +256,8 @@ parseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo"); **Docs:** [format](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/) -Renders a `ParsedTrack` back to a string: `Artists - Title (versions) (prod. ...)`. +Renders a `ParsedTrack` back to a string: `Artists - Title (versions) (prod. ...)` +([format options](https://4matic.github.io/trackparse/reference/options/#format-options), [R11](https://4matic.github.io/trackparse/reference/spec/#r11-format)). | Option | Default | | |---|---|---| @@ -277,8 +285,8 @@ format(t, { position: true }); // '01. Wilkinson ft. Becky **Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) 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. -Running it twice changes nothing. +removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed +([R1](https://4matic.github.io/trackparse/reference/spec/#r1-normalization)). Running it twice changes nothing. ```js import { normalize } from "trackparse"; @@ -291,7 +299,7 @@ normalize(" Artist\u200b — Title (Remix) “Quoted” "); **Docs:** [allArtists](https://4matic.github.io/trackparse/reference/functions/#allartiststrack) -Credits plus every remixer, deduplicated. +Credits plus every remixer, deduplicated ([R9](https://4matic.github.io/trackparse/reference/spec/#r9-assembly-and-dedup)). ```js import { allArtists, parse } from "trackparse"; @@ -326,21 +334,23 @@ r.junk; // [ { raw: 'Full Album', kind: 'other' } ] ### `SPEC_VERSION` -The version of the spec this build implements. It equals the package version: the npm package, +**Docs:** [SPEC_VERSION](https://4matic.github.io/trackparse/reference/functions/#spec_version) + +The version of the [spec](https://4matic.github.io/trackparse/reference/spec/) this build implements. It equals the package version: the npm package, the PyPI package, the Rust crate, the Go module and the spec are released together and always share one version number. ## Modes -**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) +**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) · [R2 in the spec](https://4matic.github.io/trackparse/reference/spec/#r2-mode-prelude) | Mode | For | Adds | |---|---|---| | `clean` | Store metadata, tags | Only a spaced dash separates artist and title | -| `youtube` | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | -| `filename` | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | -| `auto` | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise | -| `tracklist` | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `auto` | +| [`youtube`](https://4matic.github.io/trackparse/guides/modes/#youtube-mode) | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | +| [`filename`](https://4matic.github.io/trackparse/guides/modes/#filename-mode) | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | +| [`auto`](https://4matic.github.io/trackparse/guides/modes/#how-auto-decides) | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise | +| [`tracklist`](https://4matic.github.io/trackparse/guides/modes/#tracklist-mode) | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `auto` | ```js let t = parse('"Numb" by Linkin Park', { mode: "youtube" }); @@ -358,6 +368,9 @@ parse("Jay-Z-Numb").title; // 'Jay-Z-N parse("Jay-Z-Numb", { mode: "youtube" }).artists.map((a) => a.name); // [ 'Jay-Z' ] ``` +Try [`"Numb" by Linkin Park` in youtube mode](https://4matic.github.io/trackparse/playground/#track=%22Numb%22%20by%20Linkin%20Park&mode=youtube) or +[`07_Burial_-_Archangel.mp3`](https://4matic.github.io/trackparse/playground/#track=07_Burial_-_Archangel.mp3) in the playground. + ## Warnings **Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) @@ -367,14 +380,14 @@ empty when every decision was unambiguous. | Warning | Means | |---|---| -| `noSeparator` | No artist/title separator was found. The whole string is the title | -| `ambiguousSeparator` | A two-part pipe title with no dash was read as artist and title | -| `unspacedDashSplit` | Split at a dash without spaces around it | -| `asymmetricDashSplit` | Split at a dash with a space on one side only | -| `bySplit` | Read `"Title" by Artist` | -| `quotedTitleSplit` | Took a quoted span as the title and the text before it as the artist | -| `ambiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough to be a style | -| `unbalancedBrackets` | A bracket was opened and never closed | +| [`noSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=noSeparator) | No artist/title separator was found. The whole string is the title | +| [`ambiguousSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousSeparator) | A two-part pipe title with no dash was read as artist and title | +| [`unspacedDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unspacedDashSplit) | Split at a dash without spaces around it | +| [`asymmetricDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=asymmetricDashSplit) | Split at a dash with a space on one side only | +| [`bySplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=bySplit) | Read `"Title" by Artist` | +| [`quotedTitleSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=quotedTitleSplit) | Took a quoted span as the title and the text before it as the artist | +| [`ambiguousMixCredit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousMixCredit) | ` Mix` was read as a remix, but the name is long enough to be a style | +| [`unbalancedBrackets`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unbalancedBrackets) | A bracket was opened and never closed | ```js const t = parse("Around the World"); @@ -385,8 +398,8 @@ parse("Noisia - Stigma (VIP").warnings; // [ 'unbalancedBrackets' ] ``` -Tracklists have their own warnings, with line numbers. They are listed under -[Tracklists](#tracklists). +Tracklists have their own [warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings), with line numbers. They are listed +under [Tracklists](#tracklists). ## Tracklists @@ -437,10 +450,11 @@ list.stats; // { lines: 9, tracks: 7, markers: 1, timed: 8, firstTime: 2900, lastTime: 4536 } ``` -The suggestion exists because exactly one time, one digit away from `00:11:02`, fits between its -neighbours. With several candidates or none, `suggestion` is `null`. +The [suggestion](https://4matic.github.io/trackparse/reference/warnings/#suggestions) exists because exactly one time, one digit away from `00:11:02`, +fits between its neighbours. With several candidates or none, `suggestion` is `null`. +[Open this list in the playground](https://4matic.github.io/trackparse/playground/#list=Hour%202%0A48%3A20%20Noisia%20-%20Stigma%0A52%3A47%20Mefjus%20%26%20Kasra%20-%20Bandwagon%20%28Phace%20Remix%29%0A56%3A05%20Black%20Sun%20Empire%20-%20ID%0A59%3A31%20Alix%20Perez%20-%20Fade%20Away%0A01%3A03%3A10%20Interview%20with%20Hybris%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20feat.%20Teddy%20Killerz%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top). -`applyEdits` takes an array of edit objects and only rewrites the lines they name: +`applyEdits` takes an array of [edit objects](https://4matic.github.io/trackparse/reference/tracklist/#edits) and only rewrites the lines they name: ```js const fix = list.warnings[1].suggestion; @@ -459,10 +473,11 @@ applyEdits(text, [{ op: "shift", seconds: -3000, lines: [2, 3] }]).warnings; A rewritten time keeps its line's style: `52:47` stays `MM:SS`, and a time that crosses the hour gets hours like the rest of the list, 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`. +stops at zero and warns `time-clamped`. A bad edit changes nothing and warns `edit-invalid` +([edit warnings](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings), [editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/#times-keep-their-style)). -Both functions take the options `mode` (default `"tracklist"`), `knownArtists`, `splitAnd` and -`keywords`, as `parse` does, plus `audioSeconds` (the length of the audio, which turns on the +Both functions take the [options](https://4matic.github.io/trackparse/reference/options/#tracklist-options) `mode` (default +`"tracklist"`), `knownArtists`, `splitAnd` and `keywords`, as `parse` does, plus `audioSeconds` (the length of the audio, which turns on the `time-after-audio-end` check) and `markerWords` (extra words that make a line a marker): ```js @@ -489,19 +504,19 @@ previous one ([Markdown](https://4matic.github.io/trackparse/guides/tracklists/#markdown), [layered tracks](https://4matic.github.io/trackparse/guides/tracklists/#layered-tracks)). -Warning codes: `time-missing`, `time-out-of-order`, `time-duplicate`, `no-start-at-zero`, +[Warning codes](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings): `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`. Edits: `set-time {line, seconds}`, `shift {seconds, lines? | from?}` (all timed lines when neither is given), `sort-by-time {}`, `set-rest {line, rest}`, `insert {after, text}` (`after: 0` inserts at the top), `delete {line}`. The [Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each one, and the rules are in -[SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). +[R13 of the spec](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists). `JSON.stringify(list)` matches [`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/tracklist.schema.json). -Every line is parsed with `mode: "tracklist"`, where the first spaced dash always separates artist -and title. `parse()` accepts it too: +Every line is parsed with [`mode: "tracklist"`](https://4matic.github.io/trackparse/guides/tracklists/#tracklist-mode), where the +first spaced dash always separates artist and title. `parse()` accepts it too: ```js parse("Electrosoul System - Liquid Metal").junk; @@ -512,7 +527,7 @@ parse("Electrosoul System - Liquid Metal", { mode: "tracklist" }).title; ## Errors -No function throws. `parse` returns a complete `ParsedTrack` for any string, `""` included, and a +No function throws ([R0.8](https://4matic.github.io/trackparse/reference/spec/#r0-portability)). `parse` returns a complete `ParsedTrack` for any string, `""` included, and a value that isn't a string is read as `""`. An option of the wrong type or with an unknown value is ignored and the default is used. `applyEdits` reports a bad edit as an `edit-invalid` warning and leaves the text alone. @@ -559,7 +574,8 @@ catches a misspelt name. **Changelog:** [js/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) -The package version is the spec version (`SPEC_VERSION`). While it is 0.x, a release that changes +The package version is the spec version ([`SPEC_VERSION`](#spec_version)); every release is on +[npm](https://www.npmjs.com/package/trackparse?activeTab=versions). 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. If you store parsed results, pin the minor version with a tilde range (`"trackparse": "~0.6.0"` stays on 0.6.x) and read the changelog before moving up. @@ -572,12 +588,12 @@ The same parser exists for Python, Rust and Go. All four implement one spec, pas 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. -| Language | Package | Install | -|---|---|---| -| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | -| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | -| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | -| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | +| Language | Package | Install | Docs | +|---|---|---|---| +| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/js/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/python/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | [README](https://github.com/4matic/trackparse/blob/main/rust/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) · [API on docs.rs](https://docs.rs/trackparse) | +| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | [README](https://github.com/4matic/trackparse/blob/main/go/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/go/CHANGELOG.md) · [API on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go) | ## Limitations From 9933bcf68113b7ef91d305eb0508c85531c9f078 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 04/11] docs(python): link options, fields, modes, warnings and functions to the site reference and the spec rules, with playground links and the other packages' READMEs, changelogs and API docs --- python/README.md | 124 +++++++++++++++++++++++++++-------------------- 1 file changed, 71 insertions(+), 53 deletions(-) diff --git a/python/README.md b/python/README.md index e8ee640..956a73b 100644 --- a/python/README.md +++ b/python/README.md @@ -5,7 +5,7 @@ [![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/python.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/python.yml) [![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE) -**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** +**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[API reference](https://4matic.github.io/trackparse/reference/parse/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[Changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md)** **Turn messy track names into structured data: who made it, who's featured, who remixed it, and what's just noise.** @@ -17,17 +17,18 @@ what's just noise.** 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. +doesn't recognize stays in the title, word for word +([try it in the playground](https://4matic.github.io/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D)). This is the Python port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is -defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and pinned -by 13,130 fixtures. It passes all of them, and for every fixture input its output is byte-identical +defined by a [shared spec](https://4matic.github.io/trackparse/reference/spec/) and pinned +by [13,130 fixtures](https://4matic.github.io/trackparse/project/testing/). It passes all of them, and for every fixture input its output is byte-identical to the [JavaScript, Rust and Go packages](#other-languages). - Python 3.9 to 3.14 - No dependencies -- Typed (`py.typed`), immutable results -- Never raises on `str` input +- [Typed](#typing) (`py.typed`), immutable results +- [Never raises](#errors) on `str` input ## Install @@ -63,7 +64,8 @@ format_track(track, joiners="canonical") # 'Wilkinson feat. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)' ``` -`to_dict()` returns the spec's JSON form, with the same camelCase keys the JS package uses: +[`to_dict()`](#to_dict-and-from_dict) returns the spec's JSON form, with the same camelCase keys the JS +package uses: ```python import json @@ -130,17 +132,23 @@ parse_tracklist(text, *, mode="tracklist", known_artists=(), keywords=None, spli apply_edits(text, edits, *, ) -> EditResult ``` +Each function has a section below and one in the [API reference](https://4matic.github.io/trackparse/reference/functions/), +where every example has a Python tab. The tracklist functions are under [Tracklists](#tracklists). + ### `parse(input, **options)` **Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) +Parses one track string, running [rules R1 to R9](https://4matic.github.io/trackparse/reference/spec/#r1-normalization) of the +spec in order. + | Option | Default | | |---|---|---| -| `mode` | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string. See [Modes](#modes) | -| `uploader` | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | -| `known_artists` | `()` | Names that are never split. There is no built-in list | -| `split_and` | `"auto"` | `"auto"` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `"always"`, `"never"` | -| `keywords` | `None` | Extra vocabulary, added to the built-in lists (see below) | +| [`mode`](https://4matic.github.io/trackparse/guides/modes/) | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string. See [Modes](#modes) | +| [`uploader`](https://4matic.github.io/trackparse/guides/modes/#the-uploader-fallback) | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | +| [`known_artists`](https://4matic.github.io/trackparse/guides/artists/#knownartists) | `()` | Names that are never split. There is no built-in list | +| [`split_and`](https://4matic.github.io/trackparse/guides/artists/#and-is-special) | `"auto"` | `"auto"` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `"always"`, `"never"` | +| [`keywords`](https://4matic.github.io/trackparse/reference/options/#keywords) | `None` | Extra vocabulary, added to the built-in lists (see below) | ```python [a.name for a in parse("Chase & Status - Baddadan").artists] @@ -152,7 +160,7 @@ apply_edits(text, edits, *, ) -> EditResult # ['Simon', 'Garfunkel'] ``` -`keywords` is a dict with any of these keys: +`keywords` is a dict with any of these keys ([your own words](https://4matic.github.io/trackparse/guides/versions/#your-own-words)): | Key | Type | | |---|---|---| @@ -208,10 +216,11 @@ parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0] # descriptor='at Wembley', year=1986, unknown_artist=False, delimiter='(') ``` -- `VersionType`: `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`, +- `VersionType` ([the 27 types](https://4matic.github.io/trackparse/guides/versions/#the-27-types)): `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`, `dub`, `mix`, `extended`, `radio`, `club`, `original`, `instrumental`, `acapella`, `live`, `acoustic`, `remaster`, `demo`, `reprise`, `cover`, `version`, `spedUp`, `slowed`, `nightcore`. -- `JunkKind`: `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. +- `JunkKind` ([junk kinds](https://4matic.github.io/trackparse/reference/parse/#junk-kinds)): `video`, `audio`, `lyrics`, `quality`, `promo`, + `platform`, `label`, `genre`, `other`. - `Warning`: see [Warnings](#warnings). These are plain strings, typed as `Literal` aliases (see [Typing](#typing)). @@ -236,7 +245,7 @@ ParsedTrack.from_dict(track.to_dict()) == track # True **Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) -Splits a bare artist string (no title). Takes the same options as `parse`. +Splits a bare artist string (no title) ([R10](https://4matic.github.io/trackparse/reference/spec/#r10-parseartists)). Takes the same options as `parse`. ```python from trackparse import parse_artists @@ -249,7 +258,8 @@ from trackparse import parse_artists **Docs:** [format](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/) -Renders a track back to a string. +Renders a track back to a string ([format options](https://4matic.github.io/trackparse/reference/options/#format-options), +[R11](https://4matic.github.io/trackparse/reference/spec/#r11-format)). | Option | Default | | |---|---|---| @@ -279,8 +289,8 @@ format_track(t, position=True) # '01. Wilkinson ft. Becky Hill - Afterglow (Sub **Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) 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. -Running it twice changes nothing. +removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed +([R1](https://4matic.github.io/trackparse/reference/spec/#r1-normalization)). Running it twice changes nothing. ```python from trackparse import normalize @@ -293,7 +303,7 @@ normalize("Noisia\u200b – Stigma (VIP)") **Docs:** [allArtists](https://4matic.github.io/trackparse/reference/functions/#allartiststrack) -Credits plus every remixer, deduplicated. +Credits plus every remixer, deduplicated ([R9](https://4matic.github.io/trackparse/reference/spec/#r9-assembly-and-dedup)). ```python from trackparse import all_artists @@ -323,21 +333,23 @@ parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versi ### `SPEC_VERSION` -The version of the spec this build implements. It equals `__version__`: the PyPI package, the npm +**Docs:** [SPEC_VERSION](https://4matic.github.io/trackparse/reference/functions/#spec_version) + +The version of the [spec](https://4matic.github.io/trackparse/reference/spec/) this build implements. It equals `__version__`: the PyPI package, the npm package, the Rust crate, the Go module and the spec are released together and always share one version number. ## Modes -**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) +**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) · [R2 in the spec](https://4matic.github.io/trackparse/reference/spec/#r2-mode-prelude) | Mode | For | Adds | |---|---|---| | `clean` | Store metadata, tags | Only a spaced dash separates artist and title | -| `youtube` | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | -| `filename` | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | -| `auto` | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise | -| `tracklist` | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `auto` | +| [`youtube`](https://4matic.github.io/trackparse/guides/modes/#youtube-mode) | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | +| [`filename`](https://4matic.github.io/trackparse/guides/modes/#filename-mode) | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | +| [`auto`](https://4matic.github.io/trackparse/guides/modes/#how-auto-decides) | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise | +| [`tracklist`](https://4matic.github.io/trackparse/guides/modes/#tracklist-mode) | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `auto` | ```python t = parse('"Numb" by Linkin Park', mode="youtube") @@ -352,6 +364,9 @@ parse("Shelter", mode="youtube", uploader="Porter Robinson").artists # (Artist(name='Porter Robinson', role='primary', joiner=None, source='artist'),) ``` +Try [`"Numb" by Linkin Park` in youtube mode](https://4matic.github.io/trackparse/playground/#track=%22Numb%22%20by%20Linkin%20Park&mode=youtube) or +[`07_Burial_-_Archangel.mp3`](https://4matic.github.io/trackparse/playground/#track=07_Burial_-_Archangel.mp3) in the playground. + ## Warnings **Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) @@ -361,14 +376,14 @@ empty when every decision was unambiguous. | Warning | Means | |---|---| -| `noSeparator` | No artist/title separator was found. The whole string is the title | -| `ambiguousSeparator` | A two-part pipe title with no dash was read as artist and title | -| `unspacedDashSplit` | Split at a dash without spaces around it | -| `asymmetricDashSplit` | Split at a dash with a space on one side only | -| `bySplit` | Read `"Title" by Artist` | -| `quotedTitleSplit` | Took a quoted span as the title and the text before it as the artist | -| `ambiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough to be a style | -| `unbalancedBrackets` | A bracket was opened and never closed | +| [`noSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=noSeparator) | No artist/title separator was found. The whole string is the title | +| [`ambiguousSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousSeparator) | A two-part pipe title with no dash was read as artist and title | +| [`unspacedDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unspacedDashSplit) | Split at a dash without spaces around it | +| [`asymmetricDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=asymmetricDashSplit) | Split at a dash with a space on one side only | +| [`bySplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=bySplit) | Read `"Title" by Artist` | +| [`quotedTitleSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=quotedTitleSplit) | Took a quoted span as the title and the text before it as the artist | +| [`ambiguousMixCredit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousMixCredit) | ` Mix` was read as a remix, but the name is long enough to be a style | +| [`unbalancedBrackets`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unbalancedBrackets) | A bracket was opened and never closed | ```python t = parse("Around the World") @@ -379,8 +394,8 @@ parse("Noisia - Stigma (VIP").warnings # ('unbalancedBrackets',) ``` -Tracklists have their own warnings, with line numbers. They are listed under -[Tracklists](#tracklists). +Tracklists have their own [warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings), with line numbers. They are listed +under [Tracklists](#tracklists). ## Tracklists @@ -428,10 +443,11 @@ tl.stats # Stats(lines=9, tracks=7, markers=1, timed=8, first_time=2900, last_time=4536) ``` -The suggestion exists because exactly one time, one digit away from `00:11:02`, fits between its -neighbours. With several candidates or none, `suggestion` is `None`. +The [suggestion](https://4matic.github.io/trackparse/reference/warnings/#suggestions) exists because exactly one time, one digit away from `00:11:02`, +fits between its neighbours. With several candidates or none, `suggestion` is `None`. +[Open this list in the playground](https://4matic.github.io/trackparse/playground/#list=Hour%202%0A48%3A20%20Noisia%20-%20Stigma%0A52%3A47%20Mefjus%20%26%20Kasra%20-%20Bandwagon%20%28Phace%20Remix%29%0A56%3A05%20Black%20Sun%20Empire%20-%20ID%0A59%3A31%20Alix%20Perez%20-%20Fade%20Away%0A01%3A03%3A10%20Interview%20with%20Hybris%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20feat.%20Teddy%20Killerz%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top). -`apply_edits` takes a list of dicts with the spec's keys (`op`, `line`, `seconds`, `lines`, `from`, +`apply_edits` takes a list of dicts with the [spec's keys](https://4matic.github.io/trackparse/reference/tracklist/#edits) (`op`, `line`, `seconds`, `lines`, `from`, `after`, `text`, `rest`) and only rewrites the lines they name: ```python @@ -454,9 +470,10 @@ apply_edits(text, [{"op": "shift", "seconds": -3000, "lines": [2, 3]}]).warnings A rewritten time keeps its line's style: `52:47` stays `MM:SS`, and a time that crosses the hour gets hours like the rest of the list, 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`. +stops at zero and warns `time-clamped`. A bad edit changes nothing and warns `edit-invalid` +([edit warnings](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings), [editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/#times-keep-their-style)). -Both functions take the keyword options `mode` (default `"tracklist"`), `known_artists`, +Both functions take the keyword [options](https://4matic.github.io/trackparse/reference/options/#tracklist-options) `mode` (default `"tracklist"`), `known_artists`, `split_and` and `keywords`, as `parse` does, plus `audio_seconds` (the length of the audio, which turns on the `time-after-audio-end` check) and `marker_words` (extra words that make a line a marker): @@ -486,20 +503,20 @@ previous one ([Markdown](https://4matic.github.io/trackparse/guides/tracklists/#markdown), [layered tracks](https://4matic.github.io/trackparse/guides/tracklists/#layered-tracks)). -Warning codes: `time-missing`, `time-out-of-order`, `time-duplicate`, `no-start-at-zero`, +[Warning codes](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings): `time-missing`, `time-out-of-order`, `time-duplicate`, `no-start-at-zero`, `time-after-audio-end` (needs `audio_seconds`), `invalid-time`, `position-gap`, `position-duplicate`, `line-unparsed`. Edits: `set-time {line, seconds}`, `shift {seconds, lines? | from?}` (all timed lines when neither is given), `sort-by-time {}`, `set-rest {line, rest}`, `insert {after, text}` (`after: 0` inserts at the top), `delete {line}`. The [Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each one, and the rules are in -[SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). +[R13 of the spec](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists). `to_dict()` gives the camelCase JSON from [`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/tracklist.schema.json), byte-identical to the JS package's output. -Every line is parsed with `mode="tracklist"`, where the first spaced dash always separates artist -and title. `parse()` accepts it too: +Every line is parsed with [`mode="tracklist"`](https://4matic.github.io/trackparse/guides/tracklists/#tracklist-mode), where the +first spaced dash always separates artist and title. `parse()` accepts it too: ```python parse("Electrosoul System - Liquid Metal").junk @@ -510,7 +527,7 @@ parse("Electrosoul System - Liquid Metal", mode="tracklist").title ## Errors -Parsing is total: any `str` gives a complete `ParsedTrack`, `""` included, and `parse_tracklist` +Parsing is total ([R0.8](https://4matic.github.io/trackparse/reference/spec/#r0-portability)): any `str` gives a complete `ParsedTrack`, `""` included, and `parse_tracklist` and `apply_edits` return for any text. An option of the wrong type or with an unknown value is ignored and the default is used. `apply_edits` reports a bad edit as an `edit-invalid` warning and leaves the text alone. @@ -560,7 +577,8 @@ The package ships `py.typed` and passes `mypy --strict`. **Changelog:** [python/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) -The package version is the spec version (`SPEC_VERSION`). While it is 0.x, a release that changes +The package version is the spec version ([`SPEC_VERSION`](#spec_version)); every release is on +[PyPI](https://pypi.org/project/trackparse/). 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. If you store parsed results, pin the minor version (`trackparse~=0.6.0` stays on 0.6.x) and read the changelog before moving up. @@ -573,12 +591,12 @@ The same parser exists for JavaScript, Rust and Go. All four implement one spec, 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. -| Language | Package | Install | -|---|---|---| -| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | -| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | -| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | -| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | +| Language | Package | Install | Docs | +|---|---|---|---| +| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/js/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/python/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | [README](https://github.com/4matic/trackparse/blob/main/rust/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) · [API on docs.rs](https://docs.rs/trackparse) | +| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | [README](https://github.com/4matic/trackparse/blob/main/go/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/go/CHANGELOG.md) · [API on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go) | ## Limitations From 4377b4f12394db8a13b2ae2b0a97bbd739fbf8ed Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 05/11] docs(rust): link every item to docs.rs and to the site reference and spec rules, with playground links and the other packages' READMEs, changelogs and API docs --- rust/README.md | 161 +++++++++++++++++++++++++++++-------------------- 1 file changed, 95 insertions(+), 66 deletions(-) diff --git a/rust/README.md b/rust/README.md index 7191146..c0385fa 100644 --- a/rust/README.md +++ b/rust/README.md @@ -6,7 +6,7 @@ [![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/rust.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/rust.yml) [![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE) -**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[API on docs.rs](https://docs.rs/trackparse)** +**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[API on docs.rs](https://docs.rs/trackparse)** · **[Changelog](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md)** **Turn messy track names into structured data: who made it, who's featured, who remixed it, and what's just noise.** @@ -18,17 +18,18 @@ what's just noise.** 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. +doesn't recognize stays in the title, word for word +([try it in the playground](https://4matic.github.io/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D)). This is the Rust port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is -defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and pinned -by 13,130 fixtures. It passes all of them, and for every fixture input its output is byte-identical +defined by a [shared spec](https://4matic.github.io/trackparse/reference/spec/) and pinned +by [13,130 fixtures](https://4matic.github.io/trackparse/project/testing/). It passes all of them, and for every fixture input its output is byte-identical to the [JavaScript, Python and Go packages](#other-languages). - Rust 1.74 or later (the minimum supported version; CI runs the test suite on 1.74 and on stable) - One dependency (`unicode-normalization`); `serde` is optional - No `unsafe`, no regular expressions -- Never panics and never returns an error: any `&str` gives a result +- Never panics and never returns an error: any `&str` gives a result ([Errors](#errors)) ## Install @@ -68,8 +69,8 @@ assert_eq!( ); ``` -`to_json()` returns the spec's JSON form as compact text, with the same camelCase keys the -JavaScript package uses: +[`to_json()`](https://docs.rs/trackparse/latest/trackparse/struct.ParsedTrack.html#method.to_json) returns the spec's JSON form as compact +text, with the same camelCase keys the JavaScript package uses ([JSON and serde](#json-and-serde)): ```rust let track = trackparse::parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus VIP Remix) [HD]"); @@ -136,19 +137,25 @@ tracklist::apply_edits(text: &str, edits: &[Edit]) -> EditResult tracklist::apply_edits_with(text: &str, edits: &[Edit], options: &TracklistOptions) -> EditResult ``` -Every function has a plain form with the default options and a `_with` form that takes them. +Every function has a plain form with the default options and a `_with` form that takes them. Each +has a section below, a page on [docs.rs](https://docs.rs/trackparse) and one in the +[API reference](https://4matic.github.io/trackparse/reference/functions/), where every example has a Rust tab; the tracklist +functions are under [Tracklists](#tracklists). ### `parse` and `ParseOptions` -**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) +**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) · [`parse`](https://docs.rs/trackparse/latest/trackparse/fn.parse.html), [`parse_with`](https://docs.rs/trackparse/latest/trackparse/fn.parse_with.html) and [`ParseOptions`](https://docs.rs/trackparse/latest/trackparse/struct.ParseOptions.html) on docs.rs + +Parses one track string, running [rules R1 to R9](https://4matic.github.io/trackparse/reference/spec/#r1-normalization) of the +spec in order. | Option | Default | | |---|---|---| -| `mode` | `ModeOption::Auto` | `Clean`, `Youtube`, `Filename`, `Tracklist`, or `Auto` to detect from the string. See [Modes](#modes) | -| `uploader` | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | -| `known_artists` | empty | Names that are never split. There is no built-in list | -| `split_and` | `SplitAnd::Auto` | `Auto` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `Always`, `Never` | -| `keywords` | `None` | Extra vocabulary, added to the built-in lists (see below) | +| [`mode`](https://4matic.github.io/trackparse/guides/modes/) | `ModeOption::Auto` | `Clean`, `Youtube`, `Filename`, `Tracklist`, or `Auto` to detect from the string. See [Modes](#modes) | +| [`uploader`](https://4matic.github.io/trackparse/guides/modes/#the-uploader-fallback) | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | +| [`known_artists`](https://4matic.github.io/trackparse/guides/artists/#knownartists) | empty | Names that are never split. There is no built-in list | +| [`split_and`](https://4matic.github.io/trackparse/guides/artists/#and-is-special) | `SplitAnd::Auto` | `Auto` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `Always`, `Never` | +| [`keywords`](https://4matic.github.io/trackparse/reference/options/#keywords) | `None` | Extra vocabulary, added to the built-in lists (see below) | Options are built with chained setters. The structs are `#[non_exhaustive]`, so start from `ParseOptions::new()` (or `default()`); the fields are public and can also be assigned. @@ -171,7 +178,8 @@ assert_eq!( ); ``` -`KeywordOptions` adds words to the built-in lists: +[`KeywordOptions`](https://docs.rs/trackparse/latest/trackparse/struct.KeywordOptions.html) adds words to the built-in lists +([your own words](https://4matic.github.io/trackparse/guides/versions/#your-own-words)): | Setter | Field | | |---|---|---| @@ -195,7 +203,7 @@ assert_eq!(track.junk[0].kind, JunkKind::Label); ### `ParsedTrack` -**Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) +**Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) · [`ParsedTrack`](https://docs.rs/trackparse/latest/trackparse/struct.ParsedTrack.html) on docs.rs | Field | Type | | |---|---|---| @@ -240,10 +248,13 @@ assert_eq!(version.descriptor.as_deref(), Some("at Wembley")); assert_eq!(version.year, Some(1986)); ``` -Version types, junk kinds, warnings, roles and modes are enums (`VersionType`, `JunkKind`, -`Warning`, `ArtistRole`, `ArtistSource`, `Mode`, `ModeOption`, `VersionDelimiter`), listed in the -[API reference](https://4matic.github.io/trackparse/reference/parse/) and on -[docs.rs](https://docs.rs/trackparse). Each has `as_str()` (the name +Version types, junk kinds, warnings, roles and modes are enums +([`VersionType`](https://docs.rs/trackparse/latest/trackparse/enum.VersionType.html), [`JunkKind`](https://docs.rs/trackparse/latest/trackparse/enum.JunkKind.html), +[`Warning`](https://docs.rs/trackparse/latest/trackparse/enum.Warning.html), [`ArtistRole`](https://docs.rs/trackparse/latest/trackparse/enum.ArtistRole.html), +[`ArtistSource`](https://docs.rs/trackparse/latest/trackparse/enum.ArtistSource.html), [`Mode`](https://docs.rs/trackparse/latest/trackparse/enum.Mode.html), +[`ModeOption`](https://docs.rs/trackparse/latest/trackparse/enum.ModeOption.html), [`VersionDelimiter`](https://docs.rs/trackparse/latest/trackparse/enum.VersionDelimiter.html)), +listed in the [API reference](https://4matic.github.io/trackparse/reference/parse/) ([the 27 version types](https://4matic.github.io/trackparse/guides/versions/#the-27-types), +[junk kinds](https://4matic.github.io/trackparse/reference/parse/#junk-kinds)). Each has `as_str()` (the name used in the spec and in JSON), `from_name()`, `ALL`, `Display` and `FromStr`: ```rust @@ -262,7 +273,7 @@ warning, so a `match` on them needs a `_` arm. **Docs:** [Serializing to JSON](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json) -Every result type has `to_json()`, which writes compact JSON matching +Every result type has [`to_json()`](https://docs.rs/trackparse/latest/trackparse/struct.ParsedTrack.html#method.to_json), which writes compact JSON matching [`parsed-track.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/parsed-track.schema.json) and [`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/tracklist.schema.json) @@ -311,7 +322,8 @@ Reading options is strict: a missing key is the default, an unknown name such as **Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) -Splits a bare artist string (no title). `parse_artists_with` takes the same options as `parse_with`. +Splits a bare artist string (no title) ([R10](https://4matic.github.io/trackparse/reference/spec/#r10-parseartists)). +[`parse_artists_with`](https://docs.rs/trackparse/latest/trackparse/fn.parse_artists_with.html) takes the same options as `parse_with`. ```rust use trackparse::parse_artists; @@ -327,7 +339,9 @@ assert_eq!(credits, ["Sub Focus:primary", "Wilkinson:primary", "Dimension:primar **Docs:** [format](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/) -Renders a track back to a string. +Renders a track back to a string ([format options](https://4matic.github.io/trackparse/reference/options/#format-options), +[R11](https://4matic.github.io/trackparse/reference/spec/#r11-format)): [`format_track`](https://docs.rs/trackparse/latest/trackparse/fn.format_track.html), +[`format_track_with`](https://docs.rs/trackparse/latest/trackparse/fn.format_track_with.html), [`FormatOptions`](https://docs.rs/trackparse/latest/trackparse/struct.FormatOptions.html). | Option | Default | | |---|---|---| @@ -373,8 +387,9 @@ assert_eq!( **Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) 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. -Running it twice changes nothing. +removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed +([R1](https://4matic.github.io/trackparse/reference/spec/#r1-normalization)). Running it twice changes nothing +([`normalize`](https://docs.rs/trackparse/latest/trackparse/fn.normalize.html)). ```rust use trackparse::normalize; @@ -386,7 +401,8 @@ assert_eq!(normalize("Noisia\u{200b} – Stigma (VIP)"), "Noisia - Stigma (V **Docs:** [allArtists](https://4matic.github.io/trackparse/reference/functions/#allartiststrack) -Credits plus every remixer, deduplicated. +Credits plus every remixer, deduplicated ([R9](https://4matic.github.io/trackparse/reference/spec/#r9-assembly-and-dedup), +[`all_artists`](https://docs.rs/trackparse/latest/trackparse/fn.all_artists.html)). ```rust use trackparse::{all_artists, parse}; @@ -401,7 +417,8 @@ assert_eq!(credits, ["Wilkinson:primary", "Becky Hill:featured", "Sub Focus:remi **Docs:** [createParser](https://4matic.github.io/trackparse/reference/functions/#createparseroptions) -Resolves the options and builds the word tables once, for many calls. It is `Send + Sync`. +[`Parser`](https://docs.rs/trackparse/latest/trackparse/struct.Parser.html) resolves the options and builds the word tables once, for many +calls. It is `Send + Sync`. ```rust use trackparse::{KeywordOptions, ParseOptions, Parser, VersionType}; @@ -418,21 +435,23 @@ assert_eq!(track.versions[0].version_type, VersionType::Rework); ### `SPEC_VERSION` -The version of the spec this build implements. It equals the crate version: the crate, the npm +**Docs:** [SPEC_VERSION](https://4matic.github.io/trackparse/reference/functions/#spec_version) · [`SPEC_VERSION`](https://docs.rs/trackparse/latest/trackparse/constant.SPEC_VERSION.html) on docs.rs + +The version of the [spec](https://4matic.github.io/trackparse/reference/spec/) this build implements. It equals the crate version: the crate, the npm package, the PyPI package, the Go module and the spec are released together and always share one version number. ## Modes -**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) +**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) · [R2 in the spec](https://4matic.github.io/trackparse/reference/spec/#r2-mode-prelude) · [`ModeOption`](https://docs.rs/trackparse/latest/trackparse/enum.ModeOption.html) on docs.rs | Mode | For | Adds | |---|---|---| | `Clean` | Store metadata, tags | Only a spaced dash separates artist and title | -| `Youtube` | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | -| `Filename` | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | -| `Auto` | Anything | `Filename` for known extensions, `Youtube` when it sees junk, pipes or platform suffixes, `Clean` otherwise | -| `Tracklist` | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `Auto` | +| [`Youtube`](https://4matic.github.io/trackparse/guides/modes/#youtube-mode) | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | +| [`Filename`](https://4matic.github.io/trackparse/guides/modes/#filename-mode) | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | +| [`Auto`](https://4matic.github.io/trackparse/guides/modes/#how-auto-decides) | Anything | `Filename` for known extensions, `Youtube` when it sees junk, pipes or platform suffixes, `Clean` otherwise | +| [`Tracklist`](https://4matic.github.io/trackparse/guides/modes/#tracklist-mode) | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `Auto` | ```rust use trackparse::{parse, parse_with, Mode, ModeOption, ParseOptions, Warning}; @@ -453,23 +472,26 @@ let track = parse_with("Shelter", &youtube.uploader("Porter Robinson")); assert_eq!(track.artists[0].name, "Porter Robinson"); ``` +Try [`"Numb" by Linkin Park` in youtube mode](https://4matic.github.io/trackparse/playground/#track=%22Numb%22%20by%20Linkin%20Park&mode=youtube) or +[`07_Burial_-_Archangel.mp3`](https://4matic.github.io/trackparse/playground/#track=07_Burial_-_Archangel.mp3) in the playground. + ## Warnings -**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) +**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) · [`Warning`](https://docs.rs/trackparse/latest/trackparse/enum.Warning.html) on docs.rs The parser never fails, but it says when it had to guess. `track.warnings` is a `Vec`, empty when every decision was unambiguous. `as_str()` gives the name used in the spec and in JSON. | Warning | JSON name | Means | |---|---|---| -| `NoSeparator` | `noSeparator` | No artist/title separator was found. The whole string is the title | -| `AmbiguousSeparator` | `ambiguousSeparator` | A two-part pipe title with no dash was read as artist and title | -| `UnspacedDashSplit` | `unspacedDashSplit` | Split at a dash without spaces around it | -| `AsymmetricDashSplit` | `asymmetricDashSplit` | Split at a dash with a space on one side only | -| `BySplit` | `bySplit` | Read `"Title" by Artist` | -| `QuotedTitleSplit` | `quotedTitleSplit` | Took a quoted span as the title and the text before it as the artist | -| `AmbiguousMixCredit` | `ambiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough to be a style | -| `UnbalancedBrackets` | `unbalancedBrackets` | A bracket was opened and never closed | +| `NoSeparator` | [`noSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=noSeparator) | No artist/title separator was found. The whole string is the title | +| `AmbiguousSeparator` | [`ambiguousSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousSeparator) | A two-part pipe title with no dash was read as artist and title | +| `UnspacedDashSplit` | [`unspacedDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unspacedDashSplit) | Split at a dash without spaces around it | +| `AsymmetricDashSplit` | [`asymmetricDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=asymmetricDashSplit) | Split at a dash with a space on one side only | +| `BySplit` | [`bySplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=bySplit) | Read `"Title" by Artist` | +| `QuotedTitleSplit` | [`quotedTitleSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=quotedTitleSplit) | Took a quoted span as the title and the text before it as the artist | +| `AmbiguousMixCredit` | [`ambiguousMixCredit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousMixCredit) | ` Mix` was read as a remix, but the name is long enough to be a style | +| `UnbalancedBrackets` | [`unbalancedBrackets`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unbalancedBrackets) | A bracket was opened and never closed | ```rust use trackparse::{parse, Warning}; @@ -483,14 +505,14 @@ assert_eq!(track.warnings[0].as_str(), "noSeparator"); assert_eq!(parse("Noisia - Stigma (VIP").warnings, [Warning::UnbalancedBrackets]); ``` -Tracklists have their own warnings, with line numbers. They are listed under -[Tracklists](#tracklists). +Tracklists have their own [warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings), with line numbers. They are listed +under [Tracklists](#tracklists). ## Tracklists **Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) -`trackparse::tracklist` parses a whole tracklist, one entry per line, and checks it. Each entry +[`trackparse::tracklist`](https://docs.rs/trackparse/latest/trackparse/tracklist/index.html) 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. @@ -543,10 +565,12 @@ assert_eq!((stats.lines, stats.tracks, stats.markers, stats.timed), (9, 7, 1, 8) assert_eq!((stats.first_time, stats.last_time), (Some(2900.0), Some(4536.0))); ``` -The suggestion exists because exactly one time, one digit away from `00:11:02`, fits between its -neighbours. With several candidates or none, `suggestion` is `None`. +The [suggestion](https://4matic.github.io/trackparse/reference/warnings/#suggestions) exists because exactly one time, one digit away from `00:11:02`, +fits between its neighbours. With several candidates or none, `suggestion` is `None`. +[Open this list in the playground](https://4matic.github.io/trackparse/playground/#list=Hour%202%0A48%3A20%20Noisia%20-%20Stigma%0A52%3A47%20Mefjus%20%26%20Kasra%20-%20Bandwagon%20%28Phace%20Remix%29%0A56%3A05%20Black%20Sun%20Empire%20-%20ID%0A59%3A31%20Alix%20Perez%20-%20Fade%20Away%0A01%3A03%3A10%20Interview%20with%20Hybris%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20feat.%20Teddy%20Killerz%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top). -`apply_edits` takes a slice of `Edit` values and only rewrites the lines they name: +[`apply_edits`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.apply_edits.html) takes a slice of [`Edit`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.Edit.html) +values and only rewrites the lines they name: ```rust use trackparse::tracklist::{apply_edits, Edit, EditWarningCode}; @@ -570,9 +594,11 @@ assert_eq!(result.warnings[0].code, EditWarningCode::TimeClamped); 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`. +`time-clamped`. A bad edit changes nothing and warns `edit-invalid` +([edit warnings](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings), [editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/#times-keep-their-style)). -`TracklistOptions` has `mode` (default `ModeOption::Tracklist`), `known_artists`, `split_and`, +[`TracklistOptions`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.TracklistOptions.html) ([options](https://4matic.github.io/trackparse/reference/options/#tracklist-options)) +has `mode` (default `ModeOption::Tracklist`), `known_artists`, `split_and`, `keywords`, `audio_seconds` (enables `time-after-audio-end`) and `marker_words`: ```rust @@ -602,7 +628,7 @@ previous one ([Markdown](https://4matic.github.io/trackparse/guides/tracklists/#markdown), [layered tracks](https://4matic.github.io/trackparse/guides/tracklists/#layered-tracks)). -Warning codes (`WarningCode`): `time-missing`, `time-out-of-order`, `time-duplicate`, +[Warning codes](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) ([`WarningCode`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.WarningCode.html)): `time-missing`, `time-out-of-order`, `time-duplicate`, `no-start-at-zero`, `time-after-audio-end` (needs `audio_seconds`), `invalid-time`, `position-gap`, `position-duplicate`, `line-unparsed`. Edits: `Edit::set_time(line, seconds)`, `Edit::shift(seconds)` (all timed lines), `Edit::shift_from(seconds, from)`, @@ -610,10 +636,10 @@ Warning codes (`WarningCode`): `time-missing`, `time-out-of-order`, `time-duplic `Edit::insert(after, text)` (`after: 0` inserts at the top), `Edit::delete(line)`. The [Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each one, and the rules are in -[SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). +[R13 of the spec](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists). -Every line is parsed with `ModeOption::Tracklist`, where the first spaced dash always separates -artist and title. `parse_with` accepts it too: +Every line is parsed with [`ModeOption::Tracklist`](https://4matic.github.io/trackparse/guides/tracklists/#tracklist-mode), where the +first spaced dash always separates artist and title. `parse_with` accepts it too: ```rust use trackparse::{parse, parse_with, JunkKind, ModeOption, ParseOptions}; @@ -628,13 +654,14 @@ assert_eq!(parse_with("Electrosoul System - Liquid Metal", &options).title, "Liq ## Errors -No function returns a `Result` and none panics. `parse` gives a complete `ParsedTrack` for any +No function returns a `Result` and none panics ([R0.8](https://4matic.github.io/trackparse/reference/spec/#r0-portability)). `parse` gives a complete `ParsedTrack` for any `&str`, `""` included, and `parse_tracklist` and `apply_edits` return for any text. Options are typed, so a wrong value does not compile. `apply_edits` reports an edit it cannot apply (a line that does not exist, non-finite seconds) as an `EditWarningCode::EditInvalid` warning and leaves the text alone. -The only fallible calls are conversions from text: `FromStr` on the enums returns `UnknownName` +The only fallible calls are conversions from text: `FromStr` on the enums returns +[`UnknownName`](https://docs.rs/trackparse/latest/trackparse/struct.UnknownName.html) for a name the spec does not have, and with the `serde` feature, deserializing options or edits from JSON can fail as any `serde` type can. @@ -646,7 +673,7 @@ from JSON can fail as any `serde` type can. the rules), the spec's invariants for single tracks and for tracklists on generated input (no panic in any mode, `normalize` idempotent, the format round trip, no word lost, timing), and the API tests. The skip list is empty. -- `scripts/compare-ports.mjs` in the repository runs every fixture input through the JavaScript +- [`scripts/compare-ports.mjs`](https://github.com/4matic/trackparse/blob/main/scripts/compare-ports.mjs) in the repository runs every fixture input through the JavaScript package and this crate and compares the complete JSON output, every field of it, not only the ones a fixture asserts. The Python package and the Go module are checked the same way. - The Unicode facts the rules need (letters, uppercase letters, lowercase mapping) are tables @@ -661,7 +688,7 @@ from JSON can fail as any `serde` type can. ## Unicode version Normalization (NFC in `normalize`, NFD in the key that finds duplicate artists) comes from the -`unicode-normalization` crate and follows its Unicode version. This crate requires 0.1.26 or +[`unicode-normalization`](https://crates.io/crates/unicode-normalization) crate and follows its Unicode version. This crate requires 0.1.26 or later, which has the Unicode 18 tables; older releases have older tables and give other results for some strings, so Cargo will not select them. @@ -669,7 +696,8 @@ The JavaScript package normalizes with its runtime's tables, which are Unicode 1 Unicode 18 added 32 combining marks, so a string that contains one of them can come out with its marks in another order here than in JavaScript on that runtime, and than in the Go module, whose NFC and NFD tables are generated from Node 24. Strings without those marks are not affected, and -every shared fixture gives the same bytes. +every shared fixture gives the same bytes. More in +[what the Rust port taught](https://4matic.github.io/trackparse/project/ports/#what-the-rust-port-taught). ## Performance @@ -681,7 +709,8 @@ length (thousands of duplicate credits, bracket groups or junk phrases) under a **Changelog:** [rust/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) -The crate version is the spec version (`SPEC_VERSION`). While it is 0.x, a release that changes +The crate version is the spec version ([`SPEC_VERSION`](#spec_version)); every release is on +[crates.io](https://crates.io/crates/trackparse/versions). 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. Cargo's default requirement already stays within one minor version (`trackparse = "0.6"` means 0.6.x), so `cargo update` only brings fixes. Read the changelog before moving to the next minor. @@ -695,12 +724,12 @@ fixtures, are released together under one version number, and return identical J fixture input. You can parse in one language and read the result in another. The one known difference is described under [Unicode version](#unicode-version). -| Language | Package | Install | -|---|---|---| -| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | -| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | -| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | -| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | +| Language | Package | Install | Docs | +|---|---|---|---| +| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/js/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/python/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | [README](https://github.com/4matic/trackparse/blob/main/rust/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) · [API on docs.rs](https://docs.rs/trackparse) | +| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | [README](https://github.com/4matic/trackparse/blob/main/go/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/go/CHANGELOG.md) · [API on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go) | ## Limitations From d20ba10eb993a3edd3eef3d7ad44d044a7477962 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 06/11] docs(go): link every item to pkg.go.dev and to the site reference and spec rules, point the license at go/LICENSE, and add playground links and the other packages' docs --- go/README.md | 164 +++++++++++++++++++++++++++++---------------------- 1 file changed, 94 insertions(+), 70 deletions(-) diff --git a/go/README.md b/go/README.md index e0cfe13..24414df 100644 --- a/go/README.md +++ b/go/README.md @@ -3,9 +3,9 @@ [![Go Reference](https://pkg.go.dev/badge/github.com/4matic/trackparse/go.svg)](https://pkg.go.dev/github.com/4matic/trackparse/go) [![Go version](https://img.shields.io/github/go-mod/go-version/4matic/trackparse?filename=go%2Fgo.mod&logo=go&logoColor=white)](https://github.com/4matic/trackparse/blob/main/go/go.mod) [![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/go.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/go.yml) -[![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE) +[![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/go/LICENSE) -**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[API on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go)** +**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[API on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go)** · **[Changelog](https://github.com/4matic/trackparse/blob/main/go/CHANGELOG.md)** **Turn messy track names into structured data: who made it, who's featured, who remixed it, and what's just noise.** @@ -17,17 +17,18 @@ what's just noise.** 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. +doesn't recognize stays in the title, word for word +([try it in the playground](https://4matic.github.io/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D)). This is the Go port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is defined -by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and pinned by -13,130 fixtures. It passes all of them, and for every fixture input its output is byte-identical +by a [shared spec](https://4matic.github.io/trackparse/reference/spec/) and pinned by +[13,130 fixtures](https://4matic.github.io/trackparse/project/testing/). It passes all of them, and for every fixture input its output is byte-identical to the [JavaScript, Python and Rust packages](#other-languages). - 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 +- Never panics and never returns an error: any string gives a result ([Errors](#errors)) ## Install @@ -72,7 +73,8 @@ fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{ // 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.Marshal` gives the spec's JSON, with the same camelCase keys the JavaScript package uses +([JSON](#json) has the details): ```go track := trackparse.Parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus VIP Remix) [HD]") @@ -146,19 +148,24 @@ 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. +Tracklists are in the same package; there is no subpackage. Each function has a section below, an +entry on [pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go#pkg-index) and a page in the [API reference](https://4matic.github.io/trackparse/reference/functions/), +where every example has a Go tab. ### `Parse` and `ParseOptions` -**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) +**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/) · [`Parse`](https://pkg.go.dev/github.com/4matic/trackparse/go#Parse), [`ParseWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseWith) and [`ParseOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseOptions) on pkg.go.dev + +Parses one track string, running [rules R1 to R9](https://4matic.github.io/trackparse/reference/spec/#r1-normalization) of the +spec in order. | Field | Zero value means | | |---|---|---| -| `Mode` | `ModeAuto` | `ModeClean`, `ModeYouTube`, `ModeFilename`, `ModeTracklist`, or `ModeAuto` to detect from the string. See [Modes](#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 (`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) | +| [`Mode`](https://4matic.github.io/trackparse/guides/modes/) | `ModeAuto` | `ModeClean`, `ModeYouTube`, `ModeFilename`, `ModeTracklist`, or `ModeAuto` to detect from the string. See [Modes](#modes) | +| [`Uploader`](https://4matic.github.io/trackparse/guides/modes/#the-uploader-fallback) | none | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) | +| [`KnownArtists`](https://4matic.github.io/trackparse/guides/artists/#knownartists) | none | Names that are never split. There is no built-in list | +| [`SplitAnd`](https://4matic.github.io/trackparse/guides/artists/#and-is-special) | `SplitAndAuto` | `SplitAndAuto` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `SplitAndAlways`, `SplitAndNever` | +| [`Keywords`](https://4matic.github.io/trackparse/reference/options/#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. @@ -181,7 +188,8 @@ fmt.Println(names(trackparse.ParseWith("Simon and Garfunkel - Mrs. Robinson", tr }))) // [Simon Garfunkel] ``` -`Keywords` adds words to the built-in lists: +[`Keywords`](https://pkg.go.dev/github.com/4matic/trackparse/go#Keywords) adds words to the built-in lists +([your own words](https://4matic.github.io/trackparse/guides/versions/#your-own-words)): | Field | Type | | |---|---|---| @@ -216,7 +224,7 @@ a value someone may want to pass, the field is a pointer, and `nil` means "not s - `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: +[`trackparse.Ptr(v)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Ptr) 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)}`. @@ -231,7 +239,7 @@ on. Nothing panics. ### `Track` -**Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) +**Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack) · [`Track`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track) on pkg.go.dev | Field | Type | | |---|---|---| @@ -272,8 +280,10 @@ 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 value is the name used in +(`type VersionType string`) with one constant per spec name: [`VersionTypeRemix`](https://pkg.go.dev/github.com/4matic/trackparse/go#VersionType), +[`JunkKindVideo`](https://pkg.go.dev/github.com/4matic/trackparse/go#JunkKind), [`WarningNoSeparator`](https://pkg.go.dev/github.com/4matic/trackparse/go#Warning), +[`WarningCodeTimeOutOfOrder`](https://pkg.go.dev/github.com/4matic/trackparse/go#WarningCode) ([the 27 version types](https://4matic.github.io/trackparse/guides/versions/#the-27-types), +[junk kinds](https://4matic.github.io/trackparse/reference/parse/#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()`, ...): @@ -292,13 +302,13 @@ its type or kind, and the result keeps that string as given. **Docs:** [Serializing to JSON](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json) -Every result type has `MarshalJSON`, which writes compact JSON matching +Every result type has [`MarshalJSON`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track.MarshalJSON), which writes compact JSON matching [`parsed-track.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/parsed-track.schema.json) and [`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/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 +[`UnmarshalJSON`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track.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: @@ -328,7 +338,8 @@ methods. **Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/) -Splits a bare artist string (no title). `ParseArtistsWith` takes the same options as `ParseWith`. +Splits a bare artist string (no title) ([R10](https://4matic.github.io/trackparse/reference/spec/#r10-parseartists)). +[`ParseArtistsWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseArtistsWith) takes the same options as `ParseWith`. ```go for _, a := range trackparse.ParseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo") { @@ -344,7 +355,9 @@ for _, a := range trackparse.ParseArtists("Sub Focus, Wilkinson & Dimension feat **Docs:** [format](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/) -Renders a track back to a string. +Renders a track back to a string ([format options](https://4matic.github.io/trackparse/reference/options/#format-options), +[R11](https://4matic.github.io/trackparse/reference/spec/#r11-format)): [`Format`](https://pkg.go.dev/github.com/4matic/trackparse/go#Format), [`FormatWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#FormatWith), +[`FormatOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#FormatOptions). | Field | Zero value means | | |---|---|---| @@ -381,8 +394,8 @@ fmt.Println(trackparse.FormatWith(track, trackparse.FormatOptions{FeatMarker: tr **Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput) 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. -Running it twice changes nothing. +removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed +([R1](https://4matic.github.io/trackparse/reference/spec/#r1-normalization)). Running it twice changes nothing ([`Normalize`](https://pkg.go.dev/github.com/4matic/trackparse/go#Normalize)). ```go fmt.Println(trackparse.Normalize("Noisia\u200b – Stigma (VIP)")) // Noisia - Stigma (VIP) @@ -392,7 +405,8 @@ fmt.Println(trackparse.Normalize("Noisia\u200b – Stigma (VIP)")) // Noisia **Docs:** [allArtists](https://4matic.github.io/trackparse/reference/functions/#allartiststrack) -Credits plus every remixer, deduplicated. +Credits plus every remixer, deduplicated ([R9](https://4matic.github.io/trackparse/reference/spec/#r9-assembly-and-dedup), +[`AllArtists`](https://pkg.go.dev/github.com/4matic/trackparse/go#AllArtists)). ```go track := trackparse.Parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)") @@ -408,8 +422,8 @@ for _, a := range trackparse.AllArtists(track) { **Docs:** [createParser](https://4matic.github.io/trackparse/reference/functions/#createparseroptions) -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. +A [`Parser`](https://pkg.go.dev/github.com/4matic/trackparse/go#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. ```go parser := trackparse.NewParser(trackparse.ParseOptions{ @@ -431,21 +445,23 @@ default tables are built once, on first use. ### `SpecVersion` -The spec version this module implements. It equals the module version: the Go module, the npm +**Docs:** [SPEC_VERSION](https://4matic.github.io/trackparse/reference/functions/#spec_version) · [`SpecVersion`](https://pkg.go.dev/github.com/4matic/trackparse/go#SpecVersion) on pkg.go.dev + +The [spec](https://4matic.github.io/trackparse/reference/spec/) version this module implements. It equals the module version: the Go module, the npm package, the PyPI package, the Rust crate and the spec are released together and always share one version number. ## Modes -**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) +**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) · [R2 in the spec](https://4matic.github.io/trackparse/reference/spec/#r2-mode-prelude) · [`Mode`](https://pkg.go.dev/github.com/4matic/trackparse/go#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` | +| [`ModeYouTube`](https://4matic.github.io/trackparse/guides/modes/#youtube-mode) | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback | +| [`ModeFilename`](https://4matic.github.io/trackparse/guides/modes/#filename-mode) | Files | Strips the extension, `_` becomes a space, `01-Track` numbering | +| [`ModeAuto`](https://4matic.github.io/trackparse/guides/modes/#how-auto-decides) | Anything | `ModeFilename` for known extensions, `ModeYouTube` when it sees junk, pipes or platform suffixes, `ModeClean` otherwise | +| [`ModeTracklist`](https://4matic.github.io/trackparse/guides/modes/#tracklist-mode) | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `ModeAuto` | ```go youtube := trackparse.ParseOptions{Mode: trackparse.ModeYouTube} @@ -459,23 +475,26 @@ youtube.Uploader = "Porter Robinson" fmt.Println(trackparse.ParseWith("Shelter", youtube).Artists[0].Name) // Porter Robinson ``` +Try [`"Numb" by Linkin Park` in youtube mode](https://4matic.github.io/trackparse/playground/#track=%22Numb%22%20by%20Linkin%20Park&mode=youtube) or +[`07_Burial_-_Archangel.mp3`](https://4matic.github.io/trackparse/playground/#track=07_Burial_-_Archangel.mp3) in the playground. + ## Warnings -**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) +**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/) · [`Warning`](https://pkg.go.dev/github.com/4matic/trackparse/go#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` | ` 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 | +| `WarningNoSeparator` | [`noSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=noSeparator) | No artist/title separator was found. The whole string is the title | +| `WarningAmbiguousSeparator` | [`ambiguousSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousSeparator) | A two-part pipe title with no dash was read as artist and title | +| `WarningUnspacedDashSplit` | [`unspacedDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unspacedDashSplit) | Split at a dash without spaces around it | +| `WarningAsymmetricDashSplit` | [`asymmetricDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=asymmetricDashSplit) | Split at a dash with a space on one side only | +| `WarningBySplit` | [`bySplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=bySplit) | Read `"Title" by Artist` | +| `WarningQuotedTitleSplit` | [`quotedTitleSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=quotedTitleSplit) | Took a quoted span as the title and the text before it as the artist | +| `WarningAmbiguousMixCredit` | [`ambiguousMixCredit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousMixCredit) | ` Mix` was read as a remix, but the name is long enough to be a style | +| `WarningUnbalancedBrackets` | [`unbalancedBrackets`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unbalancedBrackets) | A bracket was opened and never closed | ```go track := trackparse.Parse("Around the World") @@ -485,14 +504,14 @@ 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). +Tracklists have their own [warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings), with line numbers. They are listed +under [Tracklists](#tracklists). ## Tracklists **Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) -`ParseTracklist` parses a whole tracklist, one entry per line, and checks it. Each entry keeps its +[`ParseTracklist`](https://pkg.go.dev/github.com/4matic/trackparse/go#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. @@ -540,10 +559,12 @@ 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 -neighbours. With several candidates or none, `Suggestion` is `nil`. +The [suggestion](https://4matic.github.io/trackparse/reference/warnings/#suggestions) exists because exactly one time, one digit away from `00:11:02`, +fits between its neighbours. With several candidates or none, `Suggestion` is `nil`. +[Open this list in the playground](https://4matic.github.io/trackparse/playground/#list=Hour%202%0A48%3A20%20Noisia%20-%20Stigma%0A52%3A47%20Mefjus%20%26%20Kasra%20-%20Bandwagon%20%28Phace%20Remix%29%0A56%3A05%20Black%20Sun%20Empire%20-%20ID%0A59%3A31%20Alix%20Perez%20-%20Fade%20Away%0A01%3A03%3A10%20Interview%20with%20Hybris%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20feat.%20Teddy%20Killerz%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top). -`ApplyEdits` takes a slice of `Edit` values and only rewrites the lines they name: +[`ApplyEdits`](https://pkg.go.dev/github.com/4matic/trackparse/go#ApplyEdits) takes a slice of [`Edit`](https://pkg.go.dev/github.com/4matic/trackparse/go#Edit) values and only rewrites the +lines they name: ```go text := "48:20 Noisia - Stigma\r\n59:31 Alix Perez - Fade Away\r\n00:03:10 Imanu - Sacrifice\r\n" @@ -567,15 +588,16 @@ 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`. +`time-clamped`. A bad edit changes nothing and warns `edit-invalid` +([edit warnings](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings), [editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/#times-keep-their-style)). -Edits are built with `SetTime(line, seconds)`, `Shift(seconds)` (all timed lines), +Edits ([reference](https://4matic.github.io/trackparse/reference/tracklist/#edits)) are built with [`SetTime(line, seconds)`](https://pkg.go.dev/github.com/4matic/trackparse/go#SetTime), `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` has `Mode` (zero value: `ModeTracklist`; `ModeAuto` picks a mode per line), +[`TracklistOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#TracklistOptions) ([options](https://4matic.github.io/trackparse/reference/options/#tracklist-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`: @@ -607,17 +629,17 @@ previous one ([Markdown](https://4matic.github.io/trackparse/guides/tracklists/#markdown), [layered tracks](https://4matic.github.io/trackparse/guides/tracklists/#layered-tracks)). -Warning codes (`WarningCode`): `time-missing`, `time-out-of-order`, `time-duplicate`, +[Warning codes](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings) ([`WarningCode`](https://pkg.go.dev/github.com/4matic/trackparse/go#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](https://4matic.github.io/trackparse/reference/tracklist/) explains each one, and the rules are in -[SPEC R13](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md#r13-tracklists). +[R13 of the spec](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists). -Every line is parsed with `ModeTracklist`, where the first spaced dash always separates artist and -title. `ParseWith` accepts it too: +Every line is parsed with [`ModeTracklist`](https://4matic.github.io/trackparse/guides/tracklists/#tracklist-mode), where the first +spaced dash always separates artist and title. `ParseWith` accepts it too: ```go track := trackparse.Parse("Electrosoul System - Liquid Metal") @@ -631,7 +653,7 @@ fmt.Println(track.Title) // Liquid Metal ## Errors -No function returns an `error` and none panics. `Parse` gives a complete `Track` for any string, +No function returns an `error` and none panics ([R0.8](https://4matic.github.io/trackparse/reference/spec/#r0-portability)). `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` @@ -667,8 +689,8 @@ fmt.Printf("%q\n", trackparse.Parse("Noisia - Sti\xffgma\xe2\x82").Title) // "St - 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. +- The `Example` functions in [`example_test.go`](https://github.com/4matic/trackparse/blob/main/go/example_test.go) are checked by `go test`, + so the [examples on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go#pkg-examples) run as shown. - [`scripts/compare-ports.mjs`](https://github.com/4matic/trackparse/blob/main/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 @@ -689,7 +711,8 @@ Go toolchain that builds the program: - `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. +So the output does not depend on the Go version you build with. More in +[what the Go port taught](https://4matic.github.io/trackparse/project/ports/#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 @@ -716,9 +739,10 @@ Other programs were running, so the numbers vary by about 20% between runs: **Changelog:** [go/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/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. +The module version is the spec version ([`SpecVersion`](#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](https://pkg.go.dev/github.com/4matic/trackparse/go?tab=versions). 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 @@ -733,12 +757,12 @@ same fixtures, are released together under one version number, and return identi every fixture input. You can parse in one language and read the result in another. The one known difference is described under [Unicode version](#unicode-version). -| Language | Package | Install | -|---|---|---| -| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | -| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | -| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | -| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | +| Language | Package | Install | Docs | +|---|---|---|---| +| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/js/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/python/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) | +| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | [README](https://github.com/4matic/trackparse/blob/main/rust/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) · [API on docs.rs](https://docs.rs/trackparse) | +| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | [README](https://github.com/4matic/trackparse/blob/main/go/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/go/CHANGELOG.md) · [API on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go) | ## Limitations @@ -789,4 +813,4 @@ spec, not here: see [AGENTS.md](https://github.com/4matic/trackparse/blob/main/A ## License -[MIT](https://github.com/4matic/trackparse/blob/main/LICENSE) +[MIT](https://github.com/4matic/trackparse/blob/main/go/LICENSE) From cf09bd5094ec234ad6fce9a4a6ffb1e82854aee0 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 07/11] docs(fixtures): link fn values, options and rule IDs to the reference and the spec, and the skip lists and port READMEs --- spec/fixtures/README.md | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/spec/fixtures/README.md b/spec/fixtures/README.md index 50a2273..f6079c8 100644 --- a/spec/fixtures/README.md +++ b/spec/fixtures/README.md @@ -1,7 +1,9 @@ # Fixtures -The shared test corpus: 13,130 cases, 1,203 written by hand and 11,927 generated. Every port -(JavaScript, Python, Rust and Go) runs every case here. The fixtures, not any one implementation, +The shared test corpus: 13,130 cases, [1,203 written by hand](https://4matic.github.io/trackparse/project/testing/#handwritten-1203-cases) +and [11,927 generated](https://4matic.github.io/trackparse/project/testing/#generated-11927-cases). Every port +([JavaScript](../../js/README.md), [Python](../../python/README.md), [Rust](../../rust/README.md) +and [Go](../../go/README.md)) runs every case here. The fixtures, not any one implementation, define correct behaviour. **Docs:** [How it's tested](https://4matic.github.io/trackparse/project/testing/) · [Contributing](https://4matic.github.io/trackparse/project/contributing/) @@ -16,6 +18,8 @@ Generated files use the same format in a compact form (per-file `defaults.option shorthand for the first primary artist). See [`../generator/README.md`](../generator/README.md). Each file validates against [`../schema/fixture-file.schema.json`](../schema/fixture-file.schema.json). +The rule IDs in `rules` are the ones in [`../SPEC.md`](../SPEC.md), also shown on the +[site](https://4matic.github.io/trackparse/reference/spec/) with an anchor per rule (`#r6-artisttitle-separator`, `#r132-times`). ## File format @@ -45,12 +49,12 @@ Each file validates against [`../schema/fixture-file.schema.json`](../schema/fix | Field | Meaning | |---|---| | `id` | Unique, stable, `[a-z0-9:._-]`. Handwritten: `-NNN`. Generated: `gen::`. | -| `fn` | `parse` (default), `parseArtists`, `format`, `normalize`, `parseTracklist`, `applyEdits` (SPEC R13). Can be set in `defaults` or on the case. | +| `fn` | [`parse`](https://4matic.github.io/trackparse/reference/parse/) (default), [`parseArtists`](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options), [`format`](https://4matic.github.io/trackparse/reference/functions/#formattrack-options), [`normalize`](https://4matic.github.io/trackparse/reference/functions/#normalizeinput), [`parseTracklist`](https://4matic.github.io/trackparse/reference/tracklist/#parsetracklisttext-options), [`applyEdits`](https://4matic.github.io/trackparse/reference/tracklist/#applyeditstext-edits-options) ([SPEC R13](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists)). Can be set in `defaults` or on the case. | | `input` | Input string. For `fn: "format"` the input is parsed first (with `options`), then formatted with `formatOptions`. For `parseTracklist` / `applyEdits` it is the whole (multi-line) text. | -| `edits` | `fn: "applyEdits"` only: the edit list (SPEC R13.9). | -| `options` | Parse options (tracklist options, SPEC R13.10, for `parseTracklist` / `applyEdits`). Merged over `defaults.options` (shallow). | -| `formatOptions` | Format options (fn `format` only). | -| `expected` | Partial expectation, see below. For `parse` an object, for `parseArtists` an array, for `format` / `normalize` a string, for `parseTracklist` a Tracklist, for `applyEdits` `{ text, changed, warnings }`. | +| `edits` | `fn: "applyEdits"` only: the edit list ([SPEC R13.9](https://4matic.github.io/trackparse/reference/spec/#r139-edits)). | +| `options` | [Parse options](https://4matic.github.io/trackparse/reference/options/) ([tracklist options](https://4matic.github.io/trackparse/reference/options/#tracklist-options), [SPEC R13.10](https://4matic.github.io/trackparse/reference/spec/#r1310-options), for `parseTracklist` / `applyEdits`). Merged over `defaults.options` (shallow). | +| `formatOptions` | [Format options](https://4matic.github.io/trackparse/reference/options/#format-options) (fn `format` only). | +| `expected` | Partial expectation, see [below](#matching-semantics-match-partial). For `parse` an object, for `parseArtists` an array, for `format` / `normalize` a string, for `parseTracklist` a Tracklist ([schema](../schema/tracklist.schema.json)), for `applyEdits` `{ text, changed, warnings }`. | | `match` | `partial` (default) or `exact`. | | `status` | `pass` (default), `xfail` (known wrong; the port must still fail it), `ambiguous` (several answers are acceptable; uses `expectedAny`). | | `expectedAny` | For `ambiguous`: the case passes if any entry matches. | @@ -86,8 +90,9 @@ unrelated fields: the case then survives changes elsewhere, and the exact cases - A case the reference port can't meet yet and that is out of scope for this release is `xfail` with a `note`. A port's runner fails if an `xfail` case unexpectedly passes, so the status gets promoted. -- Port-specific gaps go in that port's skip list (`js/test/skip.json`, `python/tests/skip.json`, - `rust/tests/skip.json`, `go/testdata/skip.json`), not here. A skip list can only shrink, and all +- Port-specific gaps go in that port's skip list ([`js/test/skip.json`](../../js/test/skip.json), + [`python/tests/skip.json`](../../python/tests/skip.json), [`rust/tests/skip.json`](../../rust/tests/skip.json), + [`go/testdata/skip.json`](../../go/testdata/skip.json)), not here. A skip list can only shrink, and all four are empty today. ## Running the fixtures @@ -114,6 +119,7 @@ pnpm conformance # after pnpm build: the complete output of all four ports, compared node scripts/compare-ports.mjs +node scripts/fuzz-ports.mjs # the same diff on random input # schema and repo-wide unique ids, for every fixture file pnpm --filter @trackparse/fixture-gen validate @@ -122,5 +128,6 @@ pnpm --filter @trackparse/fixture-gen validate ## Changing expectations Any change to an existing `expected` value is a behaviour change. Commit it as a `feat` (conventional -commits); release-please then bumps the spec minor version (0.x) and writes the changelog. See -[AGENTS.md](../../AGENTS.md#versioning-and-release). +commits); release-please then bumps the spec minor version (0.x) and writes the +[changelog](../CHANGELOG.md). See [AGENTS.md](../../AGENTS.md#versioning-and-release) and +[Contributing](https://4matic.github.io/trackparse/project/contributing/). From e179d42abbca1d7ac30a70345f9b409dc9074430 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:25:06 +0200 Subject: [PATCH 08/11] docs(generator): link the fixture format, the spec rules and the generator sources --- spec/generator/README.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/spec/generator/README.md b/spec/generator/README.md index 52009bf..4c14e18 100644 --- a/spec/generator/README.md +++ b/spec/generator/README.md @@ -3,9 +3,9 @@ Combinatorial fixture generator for the trackparse spec. It writes `spec/fixtures/generated/*.json`: 11,927 cases, about 7.7 MB (`test/generated.test.ts` caps the size at 7.8 MB). Every port (JavaScript, Python, Rust and Go) runs these files next to the 1,203 -handwritten fixtures. +handwritten fixtures. The case format is in [`../fixtures/README.md`](../fixtures/README.md). -**Docs:** [How it's tested: generated cases](https://4matic.github.io/trackparse/project/testing/#generated-11927-cases) +**Docs:** [How it's tested: generated cases](https://4matic.github.io/trackparse/project/testing/#generated-11927-cases) · [Spec](https://4matic.github.io/trackparse/reference/spec/) ## Oracle principle @@ -13,7 +13,7 @@ The generator is not a parser. Each case is a composition of hand-written *atoms artist, a joiner, a feat marker and placement, a title, a version, a junk phrase, a prefix, a mode, a Unicode transform…). Every atom carries two things: the text it renders, and the output it contributes to the parse result (for example `{R} Remix` → type `remix`, remixers = the credit). -`model.ts` renders the input string and computes the expected result from the atoms alone. +[`model.ts`](src/model.ts) renders the input string and computes the expected result from the atoms alone. It never runs a parser. That only works when a composition is unambiguous. `problem()` in `model.ts` rejects every @@ -29,6 +29,9 @@ Python, Rust and Go. ## Scenarios +The rule IDs are those of [`../SPEC.md`](../SPEC.md); on the [site](https://4matic.github.io/trackparse/reference/spec/) each rule group has an +anchor (`#r7-artist-side`, `#r13-tracklists`). + | Scenario | Focus (SPEC rules) | |---|---| | `artists-joiners` | main credit lists × every joiner × `splitAnd` (R7.3) | @@ -47,7 +50,7 @@ Python, Rust and Go. Scenarios whose product is at most `exhaustiveLimit` are exhaustive. The others use a greedy pairwise covering array (every pair of atom values from two dimensions appears in at least one valid case) plus a seeded random sample (`sample` per scenario, `kitchenSinkSample` in -`config.json`). Output is deterministic for a given `config.json` seed. +[`config.json`](config.json)). Output is deterministic for a given `config.json` seed. ## Output encoding (kept compact, still strict) @@ -78,7 +81,7 @@ pnpm --filter @trackparse/fixture-gen typecheck ## Adding an atom -1. Add it to the right pool in `src/atoms.ts` with a lowercase `[a-z0-9-]` id that is unique in +1. Add it to the right pool in [`src/atoms.ts`](src/atoms.ts) with a lowercase `[a-z0-9-]` id that is unique in its pool. Fill in its expected contribution (for a version: `type`, `modifiers`, `descriptor`, `year`, `unknownArtist`, plus `creditAsDescriptor` / `prefixForm` when those rules apply). @@ -91,5 +94,5 @@ pnpm --filter @trackparse/fixture-gen typecheck atom's expectation is wrong or the reference implementation disagrees with the spec. Fix the one that is wrong. Never edit generated files by hand. 5. Run the other ports on the new files (`cd python && uv run pytest`, `cd rust && cargo test`, - `cd go && go test ./...`), then `node scripts/compare-ports.mjs` from the repository root. It must print - `differences: 0`. + `cd go && go test ./...`), then [`node scripts/compare-ports.mjs`](../../scripts/compare-ports.mjs) + from the repository root. It must print `differences: 0`. From d656a778b7ad17bbf7a426542d832f9db7cb7a47 Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:27:42 +0200 Subject: [PATCH 09/11] docs(site): cross-reference every page: rule IDs to the spec, options, functions, types and warning codes to their reference or guide, docs.rs and pkg.go.dev items, playground links for the examples Also: Go and Rust differential runs and fuzz-ports.mjs on the testing and contributing pages, See also lists on contributing and roadmap, and a Parse options heading on reference/options. --- site/src/content/docs/guides/artists.mdx | 44 +++++-- .../docs/guides/editing-tracklists.mdx | 51 +++++--- site/src/content/docs/guides/formatting.mdx | 36 +++--- .../content/docs/guides/junk-and-flags.mdx | 33 ++++-- site/src/content/docs/guides/modes.mdx | 39 +++++-- site/src/content/docs/guides/tracklists.mdx | 55 ++++++--- site/src/content/docs/guides/versions.mdx | 46 +++++--- .../docs/guides/what-it-understands.md | 32 +++-- site/src/content/docs/project/contributing.md | 12 +- site/src/content/docs/project/how-it-works.md | 21 ++-- site/src/content/docs/project/ports.md | 14 ++- site/src/content/docs/project/roadmap.md | 8 +- site/src/content/docs/project/testing.md | 18 +-- site/src/content/docs/reference/functions.mdx | 52 +++++---- site/src/content/docs/reference/options.mdx | 70 +++++++---- site/src/content/docs/reference/parse.mdx | 105 +++++++++-------- site/src/content/docs/reference/tracklist.mdx | 110 ++++++++++-------- site/src/content/docs/reference/warnings.mdx | 62 +++++----- .../content/docs/start/getting-started.mdx | 19 +-- site/src/content/docs/start/introduction.mdx | 31 +++-- 20 files changed, 538 insertions(+), 320 deletions(-) diff --git a/site/src/content/docs/guides/artists.mdx b/site/src/content/docs/guides/artists.mdx index 9c76a2b..26fe4df 100644 --- a/site/src/content/docs/guides/artists.mdx +++ b/site/src/content/docs/guides/artists.mdx @@ -52,10 +52,12 @@ type Artist struct { `role` says what the person did. `joiner` is the text that introduced the name, exactly as written (`"&"`, `","`, `"ft."`, `"prod. by"`), and `null` for the first name of a list (`None` in Python and Rust, `nil` in Go, where `Joiner` is a `*string`). `source` says where the credit was found: left of the dash (`artist`), right of it (`title`), -or inside a version (`version`). In Rust, `role` and `source` are the enums `ArtistRole` and -`ArtistSource`; `as_str()` and `Display` give the lowercase names used here. In Go they are the -string types `Role` and `Source`, with constants such as `trackparse.RolePrimary` and -`trackparse.SourceTitle` whose values are those names. +or inside a version (`version`). In Rust, `role` and `source` are the enums +[`ArtistRole`](https://docs.rs/trackparse/latest/trackparse/enum.ArtistRole.html) and [`ArtistSource`](https://docs.rs/trackparse/latest/trackparse/enum.ArtistSource.html); +`as_str()` and `Display` give the lowercase names used here. In Go they are the string types +[`Role`](https://pkg.go.dev/github.com/4matic/trackparse/go#Role) and [`Source`](https://pkg.go.dev/github.com/4matic/trackparse/go#Source), with constants such as `trackparse.RolePrimary` +and `trackparse.SourceTitle` whose values are those names. The full field list is under +[`Artist`](/trackparse/reference/parse/#artist) in the reference. Remixers live inside `versions`, not in `artists`. Use [`allArtists(track)`](/trackparse/reference/functions/#allartiststrack) (`all_artists` in Python and Rust, `AllArtists` in Go) when you want everyone in one list. @@ -149,7 +151,10 @@ Some things look like joiners and aren't: [`no-split-before.json`](https://github.com/4matic/trackparse/blob/main/spec/data/no-split-before.json). - A comma between two digits (`1,000`) is part of the name. -The rules for the artist side are [R7](/trackparse/reference/spec/#r7-artist-side) in the spec. +The rules for the artist side are [R7](/trackparse/reference/spec/#r7-artist-side) in the spec, and +the splitting itself is [R7.3](/trackparse/reference/spec/#r7-artist-side:~:text=R7.3%20Credit%2Dlist%20splitting). Open the +[first example](/trackparse/playground/#track=Skrillex%20%26%20Diplo%20x%20Justin%20Bieber%20-%20Where%20Are%20%C3%9C%20Now) +in the playground to see every joiner. ### `and` is special @@ -203,7 +208,9 @@ fmt.Printf("%q\n", names(trackparse.ParseArtists("Crosby, Stills, Nash and Young -Set `splitAnd` (`split_and` in Python and Rust, `SplitAnd` in Go) to `"always"` or `"never"` to change that: +Set [`splitAnd`](/trackparse/reference/options/#parse-options) (`split_and` in Python and Rust, +`SplitAnd` in Go) to `"always"` or `"never"` to change that +([try it](/trackparse/playground/#track=Simon%20and%20Garfunkel%20-%20The%20Boxer&splitAnd=always)): @@ -260,7 +267,10 @@ fmt.Printf("%q\n", names(trackparse.ParseArtistsWith("Crosby, Stills, Nash and Y `feat.`, `ft.` and `featuring` work on either side of the dash and in brackets. `with` and `w/` only count at the start of a bracket, since "with" turns up in plenty of titles. All of these give -the second name the role `featured`: +the second name the role `featured`. In a bracket the rule is +[R5.2](/trackparse/reference/spec/#r5-group-classification:~:text=R5.2%20Feat), left of the dash +[R7.2](/trackparse/reference/spec/#r7-artist-side:~:text=R7.2%20Unbracketed%20feat) and right of it +[R8.3](/trackparse/reference/spec/#r8-title-side:~:text=R8.3%20Unbracketed%20feat): @@ -358,10 +368,17 @@ fmt.Printf("%q\n", names(trackparse.Parse("Noisia feat. Foreign Beggars - Shells Names are compared with full Unicode case folding and accents removed, so `Sigur Rós` and `SIGUR ROS` count as the same artist -([R9](/trackparse/reference/spec/#r9-assembly-and-dedup)). +([R9.2](/trackparse/reference/spec/#r9-assembly-and-dedup:~:text=R9.2%20Dedup)). [Try the +example](/trackparse/playground/#track=Noisia%20feat.%20Foreign%20Beggars%20-%20Shellshock%20%28feat.%20Foreign%20Beggars%29) +in the playground. ## Producers +`prod.`, `prod. by` and `produced by` credit a producer, in brackets +([R5.3](/trackparse/reference/spec/#r5-group-classification:~:text=R5.3%20Producer)) or after the title +([R8.3](/trackparse/reference/spec/#r8-title-side:~:text=R8.3%20Unbracketed%20feat)). The producer gets the role `producer` and +leaves the title: + @@ -464,11 +481,16 @@ parse a lot of strings with the same names, put them in [`createParser`](/trackparse/reference/functions/#createparseroptions) (`create_parser` in Python, `Parser::new` in Rust, `NewParser` in Go). You can try it in the [playground](/trackparse/playground/#track=Chase%20%26%20Status%20-%20Baddadan&known=Chase%20%26%20Status). +The option is listed under [Options](/trackparse/reference/options/#parse-options), and the +matching rule is [R7.3](/trackparse/reference/spec/#r7-artist-side:~:text=R7.3%20Credit%2Dlist%20splitting) (a). ## Unknown artists `ID` (and `Unknown`, `Untitled`, `?`, `???`) means the track hasn't been announced yet. It doesn't become a name. -The track gets `flags.unknownArtist: true` (`flags.unknown_artist` in Python and Rust, `Flags.UnknownArtist` in Go) instead, and the same goes for titles: +The track gets `flags.unknownArtist: true` (`flags.unknown_artist` in Python and Rust, +`Flags.UnknownArtist` in Go) instead, and the same goes for titles +([R7.5](/trackparse/reference/spec/#r7-artist-side:~:text=R7.5%20Drops%20and%20unknowns), [R8.6](/trackparse/reference/spec/#r8-title-side:~:text=R8.6%20Unknown%20title); +[open it in the playground](/trackparse/playground/#track=ID%20-%20ID%20%28ID%20Remix%29)): @@ -523,6 +545,6 @@ fmt.Println(t.Versions[0].UnknownArtist) // true - [`parseArtists`](/trackparse/reference/functions/#parseartistsinput-options) splits an artist string that has no title, and [`allArtists`](/trackparse/reference/functions/#allartiststrack) lists the remixers too. -- [Options](/trackparse/reference/options/) covers `knownArtists`, `splitAnd` and extra feat markers - in `keywords`. +- [Options](/trackparse/reference/options/) covers [`knownArtists`](/trackparse/reference/options/#parse-options), [`splitAnd`](/trackparse/reference/options/#parse-options) and extra feat markers + in [`keywords`](/trackparse/reference/options/#keywords). - [Versions and remixes](/trackparse/guides/versions/) is where the remixers go. diff --git a/site/src/content/docs/guides/editing-tracklists.mdx b/site/src/content/docs/guides/editing-tracklists.mdx index a88ba12..b18c649 100644 --- a/site/src/content/docs/guides/editing-tracklists.mdx +++ b/site/src/content/docs/guides/editing-tracklists.mdx @@ -5,7 +5,8 @@ description: Fix times, shift whole sections, sort, insert and delete lines, and import { Tabs, TabItem } from "@astrojs/starlight/components"; -`applyEdits(text, edits)` (`apply_edits` in Python and Rust, `ApplyEdits` in Go) takes a +[`applyEdits(text, edits)`](/trackparse/reference/tracklist/#applyeditstext-edits-options) +(`apply_edits` in Python and Rust, `ApplyEdits` in Go) takes a tracklist as text and returns new text. It's built for editors: you get back the lines it changed, and every other line keeps its bytes and its line ending. The rules are [R13.9](/trackparse/reference/spec/#r139-edits) in the spec. @@ -157,13 +158,15 @@ for _, line := range strings.Split(result.Text, "\r\n")[4:] { In JavaScript an edit is an object with an `op`. In Python it is a plain dict with the same keys, -`"from"` included. In Rust it is a value of the `Edit` enum, made with a function per edit: -`Edit::set_time(line, seconds)`, `Edit::shift_from(seconds, from)`. In Go it is an `Edit` struct, -made with a function per edit as well: `trackparse.SetTime(line, seconds)`, -`trackparse.ShiftFrom(seconds, from)`. +`"from"` included. In Rust it is a value of the [`Edit`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.Edit.html) enum, made +with a function per edit: `Edit::set_time(line, seconds)`, `Edit::shift_from(seconds, from)`. In Go +it is an [`Edit`](https://pkg.go.dev/github.com/4matic/trackparse/go#Edit) struct, made with a function per edit as well: +[`trackparse.SetTime(line, seconds)`](https://pkg.go.dev/github.com/4matic/trackparse/go#SetTime), [`trackparse.ShiftFrom(seconds, from)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ShiftFrom). -Lines 1 to 4 are untouched, CRLF included. Edits run in order, each on the text the previous one -produced, with line numbers as that text has them. +Lines 1 to 4 are untouched, CRLF included ([R13.9.1](/trackparse/reference/spec/#r139-edits:~:text=R13.9.1%20Locality)). Edits run in +order, each on the text the previous one produced, with line numbers as that text has them. The +[playground](/trackparse/playground/#list=Hour%202%0A48%3A20%20Noisia%20-%20Stigma%0A52%3A47%20Mefjus%20%26%20Kasra%20-%20Bandwagon%20%28Phace%20Remix%29%0A56%3A05%20Black%20Sun%20Empire%20-%20ID%0A59%3A31%20Alix%20Perez%20-%20Fade%20Away%0A01%3A03%3A10%20Interview%20with%20Hybris%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20feat.%20Teddy%20Killerz%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top) +does the same with buttons: the suggested fix, a shift and a sort, with undo. ## The edits @@ -177,12 +180,13 @@ and Go have a constructor for each: | `{ op: "shift", seconds, from }` | `Edit::shift_from(seconds, from)` | `ShiftFrom(seconds, from)` | The same, for every timed line from line `from` on | | `{ op: "shift", seconds, lines }` | `Edit::shift_lines(seconds, lines)` | `ShiftLines(seconds, lines...)` | The same, for the listed lines only | | `{ op: "sort-by-time" }` | `Edit::sort_by_time()` | `SortByTime()` | Reorder by time. Untimed lines move with the timed line above them, and lines before the first time stay on top | -| `{ op: "set-rest", line, rest }` | `Edit::set_rest(line, rest)` | `SetRest(line, rest)` | Replace everything after the time, for example with `format(track)` (`format_track`, Go `Format`) | +| `{ op: "set-rest", line, rest }` | `Edit::set_rest(line, rest)` | `SetRest(line, rest)` | Replace everything after the time, for example with `format(track)` ([`format_track`](/trackparse/reference/functions/#formattrack-options), Go `Format`) | | `{ op: "insert", after, text }` | `Edit::insert(after, text)` | `Insert(after, text)` | Insert a line after line `after` (`0` puts it at the top). It gets the text's usual line ending | | `{ op: "delete", line }` | `Edit::delete(line)` | `Delete(line)` | Remove a line | In Python the dict keys are quoted: `{"op": "set-time", "line": 3, "seconds": 90}`. Line numbers -start at 1. +start at 1. Sorting is [R13.9.4](/trackparse/reference/spec/#r139-edits:~:text=R13.9.4%20Sort), and inserting and deleting +[R13.9.5](/trackparse/reference/spec/#r139-edits:~:text=R13.9.5%20Insert%20and%20delete). This example sorts a list, rewrites one line's track text with [`format`](/trackparse/guides/formatting/), inserts a line and deletes one: @@ -281,16 +285,19 @@ after the insert the outro is line 4. ## Times keep their style A rewritten time looks like its neighbours. Hours or no hours, digit widths and fraction digits are -all kept, so `52:47` plus 45 seconds is `53:32`, not `00:53:32`. +all kept, so `52:47` plus 45 seconds is `53:32`, not `00:53:32` +([R13.9.2](/trackparse/reference/spec/#r139-edits:~:text=R13.9.2%20Time%20style)). When a time without hours crosses the hour, it gains hours in the style the rest of the list uses (`59:31` → `01:00:16`, or `1:00:16` if the list writes one-digit hours). The edit reports -`style-upgraded` so you know the line got longer. +[`style-upgraded`](/trackparse/reference/warnings/#edit-warnings:~:text=style%2Dupgraded) so you know +the line got longer. ## Bullets and Markdown stay -A list bullet or Markdown emphasis around a time sits in `lead` and `gap`, so a rewritten time keeps -it. Only the digits change: +A list bullet or Markdown emphasis around a time sits in `lead` and `gap` +([parts](/trackparse/guides/tracklists/#nothing-is-lost)), so a rewritten time keeps it. Only the +digits change: @@ -352,14 +359,16 @@ time is still read afterwards, because emphasis next to a time doesn't need a pa ## When an edit can't apply -Edits never throw or panic. A bad one changes nothing and reports why. In Rust the codes are the -enum `EditWarningCode` (`EditInvalid`, `TimeClamped`, `StyleUpgraded`), in Go the string type -`EditWarningCode` (`trackparse.EditWarningCodeEditInvalid` and so on): +Edits never throw or panic. A bad one changes nothing and reports why +([R13.9.6](/trackparse/reference/spec/#r139-edits:~:text=R13.9.6%20Totality)). In Rust the codes are the enum +[`EditWarningCode`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.EditWarningCode.html) (`EditInvalid`, `TimeClamped`, +`StyleUpgraded`), in Go the string type [`EditWarningCode`](https://pkg.go.dev/github.com/4matic/trackparse/go#EditWarningCode) +(`trackparse.EditWarningCodeEditInvalid` and so on): | Code | When | |---|---| | `edit-invalid` | missing line, no time on the line, `NaN` or infinity, a time too large to write, a line break inside `text` or `rest`, an unknown `op` | -| `time-clamped` | the time would go below zero, so it was set to zero | +| `time-clamped` | the time would go below zero, so it was set to zero ([R13.9.3](/trackparse/reference/spec/#r139-edits:~:text=R13.9.3%20Clamp)) | | `style-upgraded` | a time gained hours (see above) | Each edit warning is `{ code, edit, line }`, where `edit` is the index in your `edits` array and @@ -368,17 +377,21 @@ Each edit warning is `{ code, edit, line }`, where `edit` is the index in your ` ## Guarantees -The property tests check these on random text and random edit lists: +The [property tests](/trackparse/project/testing/#properties) check these on random text and +random edit lists: - `applyEdits(t, [])` returns `t`. - An edit never touches a line it doesn't name. - `shift(+s)` followed by `shift(-s)` gives back the original text, unless something was clamped - or upgraded on the way. + or upgraded on the way ([R13.9.7](/trackparse/reference/spec/#r139-edits:~:text=R13.9.7%20Round%20trip)). ## See also - [Tracklist API](/trackparse/reference/tracklist/#applyeditstext-edits-options) for the result fields and the `Edit` type in each language. - [Tracklists](/trackparse/guides/tracklists/) for parsing, line kinds and checks. +- [Warnings](/trackparse/reference/warnings/#edit-warnings) for the edit warnings in each + language. - [How it's tested](/trackparse/project/testing/#properties) for the property tests behind the guarantees. +- [Specification, R13.9](/trackparse/reference/spec/#r139-edits) for the exact edit rules. diff --git a/site/src/content/docs/guides/formatting.mdx b/site/src/content/docs/guides/formatting.mdx index 3a1a86e..261448a 100644 --- a/site/src/content/docs/guides/formatting.mdx +++ b/site/src/content/docs/guides/formatting.mdx @@ -5,11 +5,13 @@ description: Turn a ParsedTrack back into a string, in the style you want. import { Tabs, TabItem } from "@astrojs/starlight/components"; -`format(track, options?)` renders a parsed track back to a string. In Python it is -`format_track(track, **options)`. In Rust it is `format_track(&track)`, or -`format_track_with(&track, &options)` with options. In Go it is `trackparse.Format(track)`, or -`trackparse.FormatWith(track, options)`. Use it to bring a messy library to one style, -or to build a display title without the junk. +[`format(track, options?)`](/trackparse/reference/functions/#formattrack-options) renders a parsed +track back to a string. In Python it is `format_track(track, **options)`. In Rust it is +[`format_track(&track)`](https://docs.rs/trackparse/latest/trackparse/fn.format_track.html), or +[`format_track_with(&track, &options)`](https://docs.rs/trackparse/latest/trackparse/fn.format_track_with.html) with options. In Go it is +[`trackparse.Format(track)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Format), or [`trackparse.FormatWith(track, options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#FormatWith). +Use it to bring a messy library to one style, or to build a display title without the junk. The +rules are [R11](/trackparse/reference/spec/#r11-format) in the spec. @@ -74,22 +76,27 @@ fmt.Printf("%q\n", trackparse.Format(t)) -Junk is never written back. Everything else is, by default, the way it was written. +Junk is never written back. Everything else is, by default, the way it was written. The +[playground](/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D) has a `format()` panel with this track loaded. ## Options | Option | Values | Default | |---|---|---| -| `feat` | `"source"` keep features where they were, `"artist"` move them left of the dash, `"title"` move them into the title, `"omit"` drop them | `"source"` | +| `feat` | `"source"` keep features where they were, `"artist"` move them left of the dash, `"title"` move them into the title, `"omit"` drop them ([R11.2](/trackparse/reference/spec/#r11-format:~:text=R11.2%20Featured)) | `"source"` | | `featMarker` | the word to write before features | the one from the input | -| `joiners` | `"original"` as written, `"canonical"` normalized (`and` → `&`, `;` → `,`, `ft.` → `feat.`) | `"original"` | +| `joiners` | `"original"` as written, `"canonical"` normalized (`and` → `&`, `;` → `,`, `ft.` → `feat.`; [R11.5](/trackparse/reference/spec/#r11-format:~:text=R11.5%20canonical%20joiners)) | `"original"` | | `versions` | `"all"` or `"none"` | `"all"` | | `producers` | write `(prod. by …)` credits | `true` | | `position` | write the track number back | `false` | Python takes the options as keyword arguments, so `featMarker` is `feat_marker`. Rust takes a -`FormatOptions` value built with one setter per option, and the values are enums. Go takes a -`FormatOptions` struct whose zero value is the default, and the values are typed string constants. +[`FormatOptions`](https://docs.rs/trackparse/latest/trackparse/struct.FormatOptions.html) value built with one setter per option, and the +values are enums ([`FeatPlacement`](https://docs.rs/trackparse/latest/trackparse/enum.FeatPlacement.html), +[`JoinerStyle`](https://docs.rs/trackparse/latest/trackparse/enum.JoinerStyle.html), [`VersionsOption`](https://docs.rs/trackparse/latest/trackparse/enum.VersionsOption.html)). Go +takes a [`FormatOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#FormatOptions) struct whose zero value is the default, and the values +are typed string constants ([`FeatPlacement`](https://pkg.go.dev/github.com/4matic/trackparse/go#FeatPlacement), [`JoinerStyle`](https://pkg.go.dev/github.com/4matic/trackparse/go#JoinerStyle), +[`VersionsOption`](https://pkg.go.dev/github.com/4matic/trackparse/go#VersionsOption)); [`trackparse.Ptr`](https://pkg.go.dev/github.com/4matic/trackparse/go#Ptr) sets `FeatMarker`. Since a Go `bool` field defaults to `false`, `producers` becomes `OmitProducers`: | Option | Python | Rust | Go | @@ -209,7 +216,7 @@ fmt.Printf("%q\n", trackparse.FormatWith( Parsing the formatted string gives back the same artist names and roles, the same title and the same version types and remixers, as long as the first parse raised no warnings. The spec makes this -an invariant (R11.6, under [R11](/trackparse/reference/spec/#r11-format)), and the +an invariant ([R11.6](/trackparse/reference/spec/#r11-format:~:text=R11.6%20Round%2Dtrip)), and the [property tests](/trackparse/project/testing/#properties) check it on generated input: @@ -256,11 +263,14 @@ fmt.Printf("%q\n", again.FullTitle) // "Shellshock (Phace Remix)" The [playground](/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D) -has a `format()` panel if you want to try the options on this track or your own strings. +has a `format()` panel if you want to try the options on this track or your own strings. Its code +view writes the call for each language. ## See also -- [`format` in the reference](/trackparse/reference/functions/#formattrack-options). +- [`format` in the reference](/trackparse/reference/functions/#formattrack-options), and + [Format options](/trackparse/reference/options/#format-options) for how the options are typed in + each language. - [Editing tracklists](/trackparse/guides/editing-tracklists/#the-edits) uses `format` to rewrite the track text of a line. - [Artists and credits](/trackparse/guides/artists/) and diff --git a/site/src/content/docs/guides/junk-and-flags.mdx b/site/src/content/docs/guides/junk-and-flags.mdx index 54290a7..a9f99ed 100644 --- a/site/src/content/docs/guides/junk-and-flags.mdx +++ b/site/src/content/docs/guides/junk-and-flags.mdx @@ -77,10 +77,14 @@ fmt.Printf("%+v\n", t.Junk) // [{Raw:Official Music Video Kind:video} {Raw:HD The phrases are in [`junk.json`](https://github.com/4matic/trackparse/blob/main/spec/data/junk.json) (plus `genres.json` for the genre kind) and [`platform-suffixes.json`](https://github.com/4matic/trackparse/blob/main/spec/data/platform-suffixes.json). Seeing junk is also one of the ways `mode: "auto"` decides a string came from YouTube -(see [Modes](/trackparse/guides/modes/#how-auto-decides)). - -In Rust the kind is the enum `JunkKind` (`JunkKind::Video`, `JunkKind::Quality` and so on). Its -`as_str()` gives the lowercase names in the table. In Go the kind is the string type `JunkKind`, +(see [Modes](/trackparse/guides/modes/#how-auto-decides)). A bracket of junk is +[R5.1](/trackparse/reference/spec/#r5-group-classification:~:text=R5.1%20Junk), a platform suffix +[R2.2](/trackparse/reference/spec/#r2-mode-prelude:~:text=R2.2%20Platform%20suffixes), and unbracketed junk at the end of a +YouTube title [R8.4](/trackparse/reference/spec/#r8-title-side:~:text=R8.4%20Trailing%20junk). + +In Rust the kind is the enum [`JunkKind`](https://docs.rs/trackparse/latest/trackparse/enum.JunkKind.html) (`JunkKind::Video`, +`JunkKind::Quality` and so on). Its `as_str()` gives the lowercase names in the table. In Go the +kind is the string type [`JunkKind`](https://pkg.go.dev/github.com/4matic/trackparse/go#JunkKind), and its constants (`trackparse.JunkKindVideo`, `trackparse.JunkKindQuality`) hold those names. @@ -118,8 +122,10 @@ fmt.Printf("%+v\n", trackparse.Parse("Elektronomia - Sky High [NCS Release]").Ju -Catalog numbers like `[HOSP123]` are not junk yet. They stay in the title. See the -[roadmap](/trackparse/project/roadmap/). +Both lines are in the playground: [the platform +suffix](/trackparse/playground/#track=Porter%20Robinson%20-%20Shelter%20-%20YouTube) and [the +label](/trackparse/playground/#track=Elektronomia%20-%20Sky%20High%20%5BNCS%20Release%5D). Catalog numbers like `[HOSP123]` +are not junk yet. They stay in the title. See the [roadmap](/trackparse/project/roadmap/). To treat a phrase of your own as junk, add it with [`keywords.junk`](/trackparse/reference/options/#keywords). @@ -161,7 +167,8 @@ fmt.Printf("%+v\n", trackparse.Parse("Eminem - Without Me (Explicit)").Flags) -`explicit` and `clean` come from `(Explicit)`, `[Clean]` and the like. `unknownArtist` and +`explicit` and `clean` come from `(Explicit)`, `[Clean]` and the like +([R5.4](/trackparse/reference/spec/#r5-group-classification:~:text=R5.4%20Flag); [try it](/trackparse/playground/#track=Eminem%20-%20Without%20Me%20%28Explicit%29)). `unknownArtist` and `unknownTitle` (`unknown_artist` and `unknown_title` in Python and Rust, `UnknownArtist` and `UnknownTitle` in Go) are set when the artist or title is a placeholder such as `ID`. See @@ -169,7 +176,9 @@ or title is a placeholder such as `ID`. See ## Year -A year on its own in brackets, or as a dash suffix, goes into `year`: +A year on its own in brackets, or as a dash suffix, goes into `year` +([R5.5](/trackparse/reference/spec/#r5-group-classification:~:text=R5.5%20Year); if there are several, the first in the string +wins, [R9.6](/trackparse/reference/spec/#r9-assembly-and-dedup:~:text=R9.6%20Track%20year)): @@ -212,6 +221,7 @@ fmt.Println(*t.Year) // 2015 A year inside a version (`Remastered 2015`) belongs to that version instead, in `versions[i].year`. In Rust both are `Option`; in Go both are `*int`, `nil` when there is no year. +[Try it](/trackparse/playground/#track=Noisia%20-%20Stigma%20%282015%29) in the playground. ## Track numbers @@ -258,13 +268,16 @@ fmt.Println(trackparse.Parse("2 Unlimited - No Limit").Position == nil) // tr - in file names, also `07_Burial`, `01-Track` and `3 My Song.mp3`. A plain number before a word is part of the name: `2 Unlimited`, `50 Cent`, `808 State`. The rule -is [R4](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position). In a tracklist, a bare +is [R4.2](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position:~:text=R4.2%20Position), and the playground shows both +[`01. Aphex Twin`](/trackparse/playground/#track=01.%20Aphex%20Twin%20-%20Xtal) and [`2 Unlimited`](/trackparse/playground/#track=2%20Unlimited%20-%20No%20Limit). In a tracklist, a bare number can still count when the lines around it continue the sequence: see [Bare track numbers](/trackparse/guides/tracklists/#bare-track-numbers). ## Cue times -A time at the start becomes `timestamp`, with the seconds worked out for you: +A time at the start becomes `timestamp`, with the seconds worked out for you +([R4.1](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position:~:text=R4.1%20Timestamp); +[try it](/trackparse/playground/#track=%5B12%3A34%5D%20Noisia%20-%20Stigma)): diff --git a/site/src/content/docs/guides/modes.mdx b/site/src/content/docs/guides/modes.mdx index edba969..4d3abf6 100644 --- a/site/src/content/docs/guides/modes.mdx +++ b/site/src/content/docs/guides/modes.mdx @@ -18,9 +18,12 @@ source can take. | `tracklist` | one line of a tracklist | The first spaced dash always separates, and the words after it are never read as a version or genre suffix | | `auto` | anything (the default) | Picks `filename`, `youtube` or `clean` from the string. It never picks `tracklist` | -The resolved mode is in `track.mode`, so you can always see which one ran. In Rust the option is -the enum `ModeOption` and the resolved mode is `Mode`, which has no `Auto`. In Go both are the string type `Mode`: `trackparse.ModeAuto` (`"auto"`) asks for auto, an empty -`Mode` in `ParseOptions` means auto too, and `Track.Mode` is never `ModeAuto`. The mode rules are +The resolved mode is in `track.mode`, so you can always see which one ran. You pick one with the +[`mode` option](/trackparse/reference/options/#parse-options). In Rust the option is the enum +[`ModeOption`](https://docs.rs/trackparse/latest/trackparse/enum.ModeOption.html) and the resolved mode is [`Mode`](https://docs.rs/trackparse/latest/trackparse/enum.Mode.html), +which has no `Auto`. In Go both are the string type [`Mode`](https://pkg.go.dev/github.com/4matic/trackparse/go#Mode): +[`trackparse.ModeAuto`](https://pkg.go.dev/github.com/4matic/trackparse/go#ModeAuto) (`"auto"`) asks for auto, an empty `Mode` in `ParseOptions` +means auto too, and `Track.Mode` is never `ModeAuto`. The mode rules are [R2](/trackparse/reference/spec/#r2-mode-prelude) in the spec. ## How auto decides @@ -30,6 +33,10 @@ the enum `ModeOption` and the resolved mode is `Mode`, which has no `Auto`. In G 2. Junk, a `|`, or a platform suffix like `- YouTube` means `youtube`. 3. Anything else is `clean`. +That order is [R2.1](/trackparse/reference/spec/#r2-mode-prelude:~:text=R2.1%20Resolution). Open the +[file name](/trackparse/playground/#track=07_Burial_-_Archangel.mp3) or the [video title](/trackparse/playground/#track=Noisia%20-%20Stigma%20%7C%20Official%20Video) +in the playground to see the mode it picks. + @@ -100,7 +107,10 @@ fmt.Printf("%s %q %+v\n", t.Mode, t.Title, t.Junk) ## youtube mode Set it yourself when you know the strings are video titles. It takes guesses that `clean` -won't, and every guess shows up in [`warnings`](/trackparse/reference/warnings/#track-warnings): +won't, and every guess shows up in [`warnings`](/trackparse/reference/warnings/#track-warnings). The +three below are [R6.6](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.6%20by%20%28youtube%20only%29), +[R6.5](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.5%20Quoted%20title) and [R6.7](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.7%20Unspaced%20dash); pipes are +[R2.4](/trackparse/reference/spec/#r2-mode-prelude:~:text=R2.4%20youtube%20pipes): @@ -177,7 +187,7 @@ fmt.Printf("%q %q %v\n", t.Artists[0].Name, t.Title, t.Warnings) In `clean` mode the last one comes back with no artist, the whole string as the title and a -`noSeparator` warning. That's the safe answer when you can't be sure. Compare the two in the +[`noSeparator`](/trackparse/reference/warnings/#track-warnings:~:text=noSeparator) warning. That's the safe answer when you can't be sure. Compare the two in the playground: [youtube](/trackparse/playground/#track=Blink-182-All%20The%20Small%20Things&mode=youtube) and [clean](/trackparse/playground/#track=Blink-182-All%20The%20Small%20Things&mode=clean). @@ -185,8 +195,9 @@ playground: ### The uploader fallback Many music videos are titled with only the song name, and the artist is the channel. Pass the -channel as `uploader` and youtube mode uses it when there's no separator. Auto-generated suffixes -like `- Topic` and `VEVO` are dropped: +channel as [`uploader`](/trackparse/reference/options/#parse-options) and youtube mode uses it when there's no separator. Auto-generated suffixes +like `- Topic` and `VEVO` are dropped ([R6.8](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.8%20No%20separator); +[try it](/trackparse/playground/#track=Around%20the%20World&mode=youtube&uploader=Daft%20Punk%20-%20Topic)): @@ -228,6 +239,11 @@ fmt.Printf("%q %q\n", t.Artists[0].Name, t.Title) ## filename mode +The extension comes off first, and a name without spaces gets its underscores turned into spaces +([R2.3](/trackparse/reference/spec/#r2-mode-prelude:~:text=R2.3%20filename)). A leading number then +counts as a track number in more forms than elsewhere, such as `311 - ` and `01-Track` ([R4.2](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position:~:text=R4.2%20Position)). Try +[the first line](/trackparse/playground/#track=02_Aphex_Twin_-_Xtal.flac) in the playground. + @@ -272,7 +288,8 @@ number. Anywhere else, `311` could be a band. ## tracklist mode -Inside a tracklist almost every line is `Artist - Title`, so the first spaced dash can be trusted. +Inside a tracklist almost every line is `Artist - Title`, so the first spaced dash can be trusted +([R6.10](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.10%20Tracklist%20mode), [R13.6](/trackparse/reference/spec/#r136-tracklist-mode)). A single string doesn't get that benefit of the doubt: @@ -329,12 +346,14 @@ fmt.Printf("%q %q\n", t.Artists[0].Name, t.Title) [`parseTracklist`](/trackparse/guides/tracklists/) (`parse_tracklist` in Python and Rust, `ParseTracklist` in Go) uses this mode for every line. You only need to set it yourself when you parse tracklist lines one at a time. +The playground can show [this line in tracklist mode](/trackparse/playground/#track=Electrosoul%20System%20-%20Liquid%20Metal&mode=tracklist). [Tracklist mode](/trackparse/guides/tracklists/#tracklist-mode) in the tracklist guide has more lines that need it. ## See also -- [Options](/trackparse/reference/options/) for `mode`, `uploader` and the other options. -- [Warnings](/trackparse/reference/warnings/) for what each guess reports. +- [Options](/trackparse/reference/options/) for `mode`, [`uploader`](/trackparse/reference/options/#parse-options) and the other options. +- [Warnings](/trackparse/reference/warnings/#track-warnings) for what each guess reports. +- [Specification, R2](/trackparse/reference/spec/#r2-mode-prelude) for the exact mode rules. - [How it works](/trackparse/project/how-it-works/#finding-the-separator) for how the separator search differs between modes. diff --git a/site/src/content/docs/guides/tracklists.mdx b/site/src/content/docs/guides/tracklists.mdx index 0699d13..ffaf5e6 100644 --- a/site/src/content/docs/guides/tracklists.mdx +++ b/site/src/content/docs/guides/tracklists.mdx @@ -6,8 +6,9 @@ description: Parse the tracklist of a mix or podcast line by line, with start ti import { Tabs, TabItem } from "@astrojs/starlight/components"; Mixes and podcasts come with a tracklist: a block of text, one track per line, usually with a start -time in front. `parseTracklist` (`parse_tracklist` in Python and Rust, `ParseTracklist` in Go) reads the whole block. Every -line gets its kind, its time and a full [`ParsedTrack`](/trackparse/reference/parse/). The list as a +time in front. [`parseTracklist`](/trackparse/reference/tracklist/#parsetracklisttext-options) +(`parse_tracklist` in Python and Rust, `ParseTracklist` in Go) reads the whole block. Every line +gets its kind, its time and a full [`ParsedTrack`](/trackparse/reference/parse/). The list as a whole gets checks with line numbers. The rules are [R13](/trackparse/reference/spec/#r13-tracklists) in the spec, and every field is listed in the [Tracklist API](/trackparse/reference/tracklist/). @@ -48,8 +49,9 @@ import ( In JavaScript it's a separate entry point, `trackparse/tracklist`, about 8.4 KiB gzipped, so code that only parses single tracks never loads it. In Python it is the module `trackparse.tracklist`, -in Rust the module `trackparse::tracklist`. Go has no separate entry: `trackparse.ParseTracklist` -and `trackparse.ApplyEdits` are in the one package. +in Rust the module [`trackparse::tracklist`](https://docs.rs/trackparse/latest/trackparse/tracklist/index.html). Go has no separate entry: +[`trackparse.ParseTracklist`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseTracklist) and [`trackparse.ApplyEdits`](https://pkg.go.dev/github.com/4matic/trackparse/go#ApplyEdits) +are in the one package. Two things differ in Rust. Seconds are `f64`, since a time can carry a fraction, so `Debug` prints `3167.0` where JavaScript and Python print `3167`. `to_json()` writes `3167`, as JavaScript and @@ -253,7 +255,8 @@ fmt.Println(joined.String() == text) // true -`parts` cuts `raw` into four strings that join back into it: +`parts` cuts `raw` into four strings that join back into it +([R13.1.3](/trackparse/reference/spec/#r131-lines-and-the-lossless-guarantee:~:text=R13.1.3%20Parts)): | Part | Holds | |---|---| @@ -280,7 +283,7 @@ A list bullet in front is fine too, as in lists pasted from Discord or Reddit: bullet goes into `lead`. Something that looks like a time but can't be one, like `1:75` or `0:61:00`, stays in `rest` and -raises an `invalid-time` warning. The time forms are +raises an [`invalid-time`](/trackparse/reference/warnings/#tracklist-warnings:~:text=invalid%2Dtime) warning. The time forms are [R13.2](/trackparse/reference/spec/#r132-times). ## Markdown @@ -289,6 +292,7 @@ Lists copied from Discord, Reddit, Telegram or YouTube comments often keep their `**bold**`, `__underline__`, `*italic*` or `_italic_`, sometimes only around the time. trackparse reads through it. Emphasis next to the time goes into `lead` and `gap`, so an edit keeps it. Emphasis in the rest of the line stays in `rest`, but the parser reads the text without it. +Both lines below are in the [playground](/trackparse/playground/#list=%2A%2A%5B%2A%2A14%3A21%2A%2A%5D%2010.%20Nitepunk%20-%20ID%2A%2A%0A%2A%2018%3A02%20Noisia%20-%20_Stigma_). @@ -367,7 +371,10 @@ written. Runs of three or more, `~~`, `||` and backticks are never treated as Ma DJ tracklists mark a track played over the previous one, like an acapella on the second deck, with `w/` where the track number would go. Such a line gets `layered: true`. The `w/` stays in `rest` and is left out of the parsed track. An untimed layered line plays at the previous track's time, so it -doesn't warn `time-missing`, and it doesn't count as a neighbour for bare track numbers. +doesn't warn [`time-missing`](/trackparse/reference/warnings/#tracklist-warnings:~:text=time%2Dmissing), +and it doesn't count as a neighbour for bare track numbers. [Open the +example](/trackparse/playground/#list=00%3A00%20Noisia%20-%20Stigma%0Aw%2F%20Phace%20-%20Psycho%20%28Acapella%29%0A03%3A10%20Mefjus%20-%20Sleepless) in the +playground. @@ -451,16 +458,20 @@ whitespace and a track counts, so `00:30 w/ Phace - Psycho` is layered too. `w/` | `blank` | empty or only whitespace | Only `track` and `marker` entries have a `track`. No line is ever dropped. In Rust the kind is the -enum `EntryKind` (`EntryKind::Track`, `EntryKind::Marker` and so on), in Go the string type -`EntryKind` (`trackparse.EntryKindTrack`, `trackparse.EntryKindMarker`). The kinds are +enum [`EntryKind`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.EntryKind.html) (`EntryKind::Track`, `EntryKind::Marker` +and so on), in Go the string type [`EntryKind`](https://pkg.go.dev/github.com/4matic/trackparse/go#EntryKind) (`trackparse.EntryKindTrack`, +`trackparse.EntryKindMarker`). The marker words are in +[`marker-words.json`](https://github.com/4matic/trackparse/blob/main/spec/data/marker-words.json). The kinds are [R13.3](/trackparse/reference/spec/#r133-line-kinds). ## Options -`parseTracklist` takes the `parse` options `mode` (default `"tracklist"`), `knownArtists`, `splitAnd` -and `keywords`, plus two of its own (snake_case keyword arguments in Python, setters of -`TracklistOptions` in Rust, fields of `TracklistOptions` in Go). `audioSeconds` is the length of the audio, and turns on the check for times after the end. -`markerWords` adds marker words to the built-in ones: +`parseTracklist` takes the [`parse` options](/trackparse/reference/options/#parse-options) `mode` +(default `"tracklist"`), `knownArtists`, `splitAnd` and `keywords`, plus two of its own +(snake_case keyword arguments in Python, setters of [`TracklistOptions`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.TracklistOptions.html) +in Rust, fields of [`TracklistOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#TracklistOptions) in Go). `audioSeconds` is the length +of the audio, and turns on the check for times after the end. `markerWords` adds marker words to +the built-in ones ([R13.10](/trackparse/reference/spec/#r1310-options)): @@ -526,8 +537,11 @@ for _, w := range mix.Warnings { -Without `markerWords`, `03:00 Drop` is a track line with no separator, and it warns `line-unparsed`. -The options are listed under [Tracklist API](/trackparse/reference/tracklist/#options). +Without `markerWords`, `03:00 Drop` is a track line with no separator, and it warns [`line-unparsed`](/trackparse/reference/warnings/#tracklist-warnings:~:text=line%2Dunparsed). +The options are listed under [Tracklist API](/trackparse/reference/tracklist/#options). The +playground has a field for `audioSeconds` but none for `markerWords`, so +[this link](/trackparse/playground/#list=00%3A00%20Intro%0A03%3A00%20Drop%0A1%3A02%3A03%20Noisia%20-%20Stigma&audioSeconds=3600) shows +both warnings. ## Checks @@ -585,7 +599,9 @@ for _, w := range list.Warnings { `00:11:02` sits between `01:07:44` and `01:15:36`. Changing one digit gives exactly one time that fits, `01:11:02`, so the warning carries it as a suggestion. When several fixes would fit, or none -does, `suggestion` is `null` (`None`, `nil` in Go) and you only get the warning. +does, `suggestion` is `null` (`None`, `nil` in Go) and you only get the warning. The checks are +[R13.7](/trackparse/reference/spec/#r137-warnings), and [Suggestions](/trackparse/reference/warnings/#suggestions) +describes the search. Sometimes the typo is on the line before. In `01:22:21` followed by `01:03:55`, the second line is flagged, but the suggestion is to change the first one to `01:02:21`. All the codes are listed in @@ -596,7 +612,7 @@ each language. To apply a suggestion, see ## Bare track numbers Some lists number their lines without a dot: `1 Artist - Title`, `2 Artist - Title`. A single -`parse()` call would read `1 Artist` as the artist's name, and it should, because `2 Unlimited` +[`parse()`](/trackparse/reference/parse/) call would read `1 Artist` as the artist's name, and it should, because `2 Unlimited` exists. In a list, trackparse looks at the neighbours: a bare number counts as a position when the nearest line before or after it carries the next or previous number ([R13.5](/trackparse/reference/spec/#r135-bare-positions)). @@ -604,7 +620,7 @@ nearest line before or after it carries the next or previous number ## Tracklist mode Inside a tracklist, the first ` - ` is the separator on almost every line, so each line is -parsed with `mode: "tracklist"` ([Modes](/trackparse/guides/modes/#tracklist-mode)). These lines all go wrong with a plain `parse()` and right in a list: +parsed with `mode: "tracklist"` ([Modes](/trackparse/guides/modes/#tracklist-mode)). These lines all go wrong with a plain [`parse()`](/trackparse/reference/parse/) and right in a list: | Line | `parse(line)` | In a tracklist | |---|---|---| @@ -620,7 +636,7 @@ what a plain `parse()` makes of them. The last two need neighbours: the position ## JSON -A `Tracklist` serializes like a single track: `JSON.stringify(list)` in JavaScript, +A `Tracklist` ([R13.8](/trackparse/reference/spec/#r138-output)) serializes like a single track: `JSON.stringify(list)` in JavaScript, `tl.to_dict()` in Python, `list.to_json()` in Rust and `json.Marshal(list)` in Go give the same JSON, with camelCase keys such as `specVersion` and `firstTime`. See [Serializing to JSON](/trackparse/reference/parse/#serializing-to-json). @@ -631,3 +647,4 @@ as `specVersion` and `firstTime`. See delete lines. - [Tracklist API](/trackparse/reference/tracklist/): every field and option. - [Warnings](/trackparse/reference/warnings/#tracklist-warnings): every code and what to do with it. +- [Modes](/trackparse/guides/modes/#tracklist-mode): the single-line mode every entry is parsed in. diff --git a/site/src/content/docs/guides/versions.mdx b/site/src/content/docs/guides/versions.mdx index f8157f0..b6a9941 100644 --- a/site/src/content/docs/guides/versions.mdx +++ b/site/src/content/docs/guides/versions.mdx @@ -7,7 +7,9 @@ import { Tabs, TabItem } from "@astrojs/starlight/components"; A version is anything that says which take of a song this is: a remix, a VIP, a radio edit, a live recording, a remaster, a sped-up TikTok cut. trackparse reads them from brackets and from dash -suffixes, and puts each one in `versions`, left to right. +suffixes, and puts each one in `versions`, left to right +([R9.3](/trackparse/reference/spec/#r9-assembly-and-dedup:~:text=R9.3%20Versions%20order)). The fields are listed under +[`Version`](/trackparse/reference/parse/#version) in the reference. @@ -76,17 +78,19 @@ type Version struct { -`title` never includes versions. `fullTitle` (`full_title` in Python and Rust, `FullTitle` in Go) is the title with them +`title` never includes versions. [`fullTitle`](/trackparse/reference/parse/#parsedtrack) (`full_title` in Python and Rust, `FullTitle` in Go) is the title with them put back, in their original brackets. In Rust the type is the field `version_type`, because `type` is a reserved word, and its values are -enum variants (`VersionType::Remix`, `VersionType::SpedUp`). `as_str()` gives the names used on this +variants of the enum [`VersionType`](https://docs.rs/trackparse/latest/trackparse/enum.VersionType.html) (`VersionType::Remix`, +`VersionType::SpedUp`). `as_str()` gives the names used on this page (`"remix"`, `"spedUp"`), and so does `Display`. `modifiers` holds those names as strings. -`delimiter` is the enum `VersionDelimiter`: `Paren`, `Square`, `Curly` or `Dash`. +`delimiter` is the enum [`VersionDelimiter`](https://docs.rs/trackparse/latest/trackparse/enum.VersionDelimiter.html): `Paren`, `Square`, +`Curly` or `Dash`. -In Go the field is `Type`, of the string type `VersionType`. Its constants +In Go the field is `Type`, of the string type [`VersionType`](https://pkg.go.dev/github.com/4matic/trackparse/go#VersionType). Its constants (`trackparse.VersionTypeRemix`, `trackparse.VersionTypeSpedUp`) hold the names used on this page, so -they print as `remix` and `spedUp`. `Delimiter` is a string type too, holding the delimiter itself: +they print as `remix` and `spedUp`. [`Delimiter`](https://pkg.go.dev/github.com/4matic/trackparse/go#Delimiter) is a string type too, holding the delimiter itself: `trackparse.DelimiterParen` is `"("`. `Descriptor` and `Year` are pointers, `nil` when absent. ## The 27 types @@ -100,14 +104,15 @@ they print as `remix` and `spedUp`. `Delimiter` is a string type too, holding th The keywords behind them are in [`version-keywords.json`](https://github.com/4matic/trackparse/blob/main/spec/data/version-keywords.json). -In Rust, `VersionType::ALL` lists the 27 variants and `VersionType::from_name("spedUp")` reads a -name back. In Go, `trackparse.AllVersionTypes()` lists them, and since the type is a string, +In Rust, [`VersionType::ALL`](https://docs.rs/trackparse/latest/trackparse/enum.VersionType.html#associatedconstant.ALL) lists the 27 +variants and `VersionType::from_name("spedUp")` reads a name back. In Go, +[`trackparse.AllVersionTypes()`](https://pkg.go.dev/github.com/4matic/trackparse/go#AllVersionTypes) lists them, and since the type is a string, `trackparse.VersionType("spedUp")` is a conversion. ## Generic words borrow their meaning "Mix", "Edit" and "Version" don't say much on their own. trackparse looks at the word in front -([R5](/trackparse/reference/spec/#r5-group-classification) in the spec). Click an input to open it +([R5.7](/trackparse/reference/spec/#r5-group-classification:~:text=R5.7%20Version) in the spec). Click an input to open it in the playground: | Input | `type` | Why | @@ -175,7 +180,9 @@ fmt.Println(v.Delimiter) // ( ## Several versions -Two groups give two versions. So does a slash inside one group: +Two groups give two versions. So does a slash inside one group +([R5.6](/trackparse/reference/spec/#r5-group-classification:~:text=R5.6%20Multi%2Dversion); +[try it](/trackparse/playground/#track=Dimension%20-%20Offshore%20%28Mefjus%20Remix%20%2F%20Noisia%20Remix%29)): @@ -235,7 +242,8 @@ for _, v := range trackparse.Parse("Dimension - Offshore (Mefjus Remix / Noisia ## Dash suffixes Streaming services often write versions after a second dash. Those are read too, and the -delimiter is `-` (`VersionDelimiter::Dash` in Rust, `trackparse.DelimiterDash` in Go): +delimiter is `-` (`VersionDelimiter::Dash` in Rust, `trackparse.DelimiterDash` in Go; +[try it](/trackparse/playground/#track=The%20Beatles%20-%20Hey%20Jude%20-%20Remastered%202015)): @@ -286,18 +294,24 @@ fmt.Printf("%q\n", v.Raw) // "Remastered 2015" A dash suffix that isn't a version stays in the title. In a [tracklist](/trackparse/guides/tracklists/#tracklist-mode) the rule is stricter, because there the -first dash is almost always the separator. The suffix rules are part of -[R6](/trackparse/reference/spec/#r6-artisttitle-separator). +first dash is almost always the separator. The suffix rules are +[R6.2](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.2%20Suffix%20peeling) and +[R8.2](/trackparse/reference/spec/#r8-title-side:~:text=R8.2%20Dash%20suffixes). ## Unknown remixers `(ID Remix)` is a remix by someone not yet announced. You get the version with -`unknownArtist: true` (`unknown_artist` in Python and Rust, `UnknownArtist` in Go) and no artists. There is no artist -called "ID". [Unknown artists](/trackparse/guides/artists/#unknown-artists) has an example. +`unknownArtist: true` ([`unknown_artist`](/trackparse/guides/artists/#unknown-artists) in Python and Rust, `UnknownArtist` in Go) and no artists. There is no artist +called "ID". [Unknown artists](/trackparse/guides/artists/#unknown-artists) has an example, and +the [playground](/trackparse/playground/#track=ID%20-%20ID%20%28ID%20Remix%29) shows it. ## Your own words -If your catalog uses a word trackparse doesn't know, add it with `keywords.versionHeads` (`version_heads` in Python, `KeywordOptions::version_head` in Rust, `Keywords.VersionHeads` in Go): +If your catalog uses a word trackparse doesn't know, add it with +[`keywords.versionHeads`](/trackparse/reference/options/#keywords) (`version_heads` in Python, +[`KeywordOptions::version_head`](https://docs.rs/trackparse/latest/trackparse/struct.KeywordOptions.html#method.version_head) in Rust, +[`Keywords.VersionHeads`](https://pkg.go.dev/github.com/4matic/trackparse/go#Keywords) in Go). The playground has no field for keywords, so this +one runs only in code: diff --git a/site/src/content/docs/guides/what-it-understands.md b/site/src/content/docs/guides/what-it-understands.md index 51c1b41..fb96606 100644 --- a/site/src/content/docs/guides/what-it-understands.md +++ b/site/src/content/docs/guides/what-it-understands.md @@ -9,9 +9,11 @@ output. The results are the same in JavaScript, Python, Rust and Go, because all four follow one [spec](/trackparse/reference/spec/). The values are shown as they appear in JSON: `remix`, `bySplit`. -In Rust they are enum variants such as `VersionType::Remix` and `Warning::BySplit`. In Go they are -typed string constants such as `trackparse.VersionTypeRemix` and `trackparse.WarningBySplit`, whose -values are these same names. +In Rust they are enum variants such as [`VersionType::Remix`](https://docs.rs/trackparse/latest/trackparse/enum.VersionType.html) and +[`Warning::BySplit`](https://docs.rs/trackparse/latest/trackparse/enum.Warning.html). In Go they are typed string constants such as +[`trackparse.VersionTypeRemix`](https://pkg.go.dev/github.com/4matic/trackparse/go#VersionTypeRemix) and +[`trackparse.WarningBySplit`](https://pkg.go.dev/github.com/4matic/trackparse/go#WarningBySplit), whose values are these same names. The columns +are fields of [`ParsedTrack`](/trackparse/reference/parse/#parsedtrack). | Input | Artists | Title | Versions and other fields | |---|---|---|---| @@ -49,36 +51,42 @@ A few of these deserve a comment. **`2 Unlimited` is not track 2.** A leading number only counts as a track number when it's written like one: `01.` or `1)`, a zero-padded `01 `, `3 - Artist - Title`, or `07_` in a file name. A plain `2 ` in front of a word is part of the name, which is what you want for `2 Unlimited`, `50 Cent` and -`808 State`. The rule is [R4](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position), and +`808 State`. The rule is [R4.2](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position:~:text=R4.2%20Position), and [Track numbers](/trackparse/guides/junk-and-flags/#track-numbers) has more examples. **`Mumford & Sons` stays whole.** `&` is a joiner, but `& Sons`, `& Co.` or `& His Orchestra` never start a second artist. `& The` does split, on purpose: `Noisia & The Upbeats` is two -acts. `Chase & Status` splits too, because nothing in the string tells it apart from two artists. +acts ([R7.3](/trackparse/reference/spec/#r7-artist-side:~:text=R7.3%20Credit%2Dlist%20splitting), with the list in +[`no-split-before.json`](https://github.com/4matic/trackparse/blob/main/spec/data/no-split-before.json)). +`Chase & Status` splits too, because nothing in the string tells it apart from two artists. Names like that go in [`knownArtists`](/trackparse/guides/artists/#knownartists) (`known_artists` in Python and Rust, `KnownArtists` in Go). **The Rolling Stones keep their brackets.** `(I Can't Get No)` is not a version, a feat or junk, so -it stays in the title. That's the rule: anything unrecognized is left alone. +it stays in the title. That's the rule: anything unrecognized is left alone +([R5.8](/trackparse/reference/spec/#r5-group-classification:~:text=R5.8%20Unknown)). **Two rows needed `mode: "youtube"`.** `"Numb" by Linkin Park` and `Blink-182-All The Small Things` are fine guesses on YouTube and bad ones in a music library, so the default `clean` mode won't make -them. In `youtube` mode it does, and it tells you through `warnings`. In Python the option is -`mode="youtube"`, in Rust `ParseOptions::new().mode(ModeOption::Youtube)`, in Go -`trackparse.ParseOptions{Mode: trackparse.ModeYouTube}`. See -[Modes](/trackparse/guides/modes/#youtube-mode) and [Warnings](/trackparse/reference/warnings/). +them. In `youtube` mode it does, and it tells you through `warnings` +([`bySplit`](/trackparse/reference/warnings/#track-warnings:~:text=bySplit) and +[`unspacedDashSplit`](/trackparse/reference/warnings/#track-warnings:~:text=unspacedDashSplit)). In +Python the option is `mode="youtube"`, in Rust `ParseOptions::new().mode(ModeOption::Youtube)`, in +Go `trackparse.ParseOptions{Mode: trackparse.ModeYouTube}`. See +[Modes](/trackparse/guides/modes/#youtube-mode) and the [`mode` option](/trackparse/reference/options/#parse-options). ## In a tracklist Lines of a pasted tracklist go through -[`parseTracklist`](/trackparse/guides/tracklists/) (`parse_tracklist` in Python and Rust, `ParseTracklist` in Go), which +[`parseTracklist`](/trackparse/guides/tracklists/) (`parse_tracklist` in Python and Rust, +`ParseTracklist` in Go; the [Tracklist API](/trackparse/reference/tracklist/) has every field), which also reads list bullets, Markdown emphasis and `w/` lines. Each input below is one line; click it to open it in the playground's tracklist tab. | Line | Artists | Title | Other fields | |---|---|---|---| | [`* 00:00 Noisia - Stigma`](/trackparse/playground/#list=*%2000%3A00%20Noisia%20-%20Stigma) | Noisia | `Stigma` | time 0 s, bullet in `lead` | -| [`**[**00:00**] 10. Nitepunk - ID**`](/trackparse/playground/#list=**%5B**00%3A00**%5D%2010.%20Nitepunk%20-%20ID**) | Nitepunk | `ID` | time 0 s, position 10, `**` kept in `parts` | +| [`**[**00:00**] 10. Nitepunk - ID**`](/trackparse/playground/#list=**%5B**00%3A00**%5D%2010.%20Nitepunk%20-%20ID**) | Nitepunk | `ID` | time 0 s, position 10, `**` kept in [`parts`](/trackparse/guides/tracklists/#nothing-is-lost) | | [`00:00 **Noisia** - _Stigma_`](/trackparse/playground/#list=00%3A00%20**Noisia**%20-%20_Stigma_) | Noisia | `Stigma` | time 0 s | | [`w/ Nitepunk & Habstrakt - Point`](/trackparse/playground/#list=w%2F%20Nitepunk%20%26%20Habstrakt%20-%20Point) | Nitepunk, Habstrakt | `Point` | layered | | [`00:00 P*nk - Raise Your Glass`](/trackparse/playground/#list=00%3A00%20P*nk%20-%20Raise%20Your%20Glass) | P\*nk | `Raise Your Glass` | the star stays | diff --git a/site/src/content/docs/project/contributing.md b/site/src/content/docs/project/contributing.md index e144ce9..500c2b4 100644 --- a/site/src/content/docs/project/contributing.md +++ b/site/src/content/docs/project/contributing.md @@ -22,7 +22,8 @@ Behaviour starts in the spec, not in the code: 1. Add or amend a rule in [`spec/SPEC.md`](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md). Rule IDs are never renumbered or reused. -2. Add handwritten fixtures that cite the rule: the positive case, the near-miss that must not +2. Add handwritten fixtures that cite the rule + ([format](https://github.com/4matic/trackparse/blob/main/spec/fixtures/README.md)): the positive case, the near-miss that must not trigger, and one exact case if the rule touches many fields. 3. If the rule is combinatorial (a new joiner, a new version word), teach the generator the atom and regenerate. @@ -120,6 +121,7 @@ repository root. It runs every fixture through all four ports and compares the c pnpm build node scripts/compare-ports.mjs # must print "differences: 0" node scripts/compare-ports.mjs --only=rust # one port against JavaScript (or --only=python, --only=go) +node scripts/fuzz-ports.mjs # the same diff on random input ``` ## This website @@ -137,6 +139,14 @@ every command and the release process. Commits follow [Conventional Commits](https://www.conventionalcommits.org/), because the changelog is generated from them. The four packages and the spec are released together under one version number. +## See also + +- [How it works](/trackparse/project/how-it-works/) for the pipeline and the rule groups. +- [How it's tested](/trackparse/project/testing/) for the fixtures, the generator and the + cross-port diff. +- [Ports](/trackparse/project/ports/) for what a new language has to get right. +- [Limitations and roadmap](/trackparse/project/roadmap/) for what is planned. + ## License [MIT](https://github.com/4matic/trackparse/blob/main/LICENSE) © Maksim Maksimov. diff --git a/site/src/content/docs/project/how-it-works.md b/site/src/content/docs/project/how-it-works.md index 8e8e275..510e6d1 100644 --- a/site/src/content/docs/project/how-it-works.md +++ b/site/src/content/docs/project/how-it-works.md @@ -23,7 +23,9 @@ input └─ assemble dedupe credits, build the ParsedTrack (R9) ``` -Every port keeps one source file per step, with the same rule IDs in the comments: +The tree above runs inside [`parse`](/trackparse/reference/parse/); [`normalize`](/trackparse/reference/functions/#normalizeinput) +exposes its first step on its own. Every port keeps one source file per step, with the same rule +IDs in the comments: [`js/src`](https://github.com/4matic/trackparse/tree/main/js/src), [`python/src/trackparse`](https://github.com/4matic/trackparse/tree/main/python/src/trackparse), [`rust/src`](https://github.com/4matic/trackparse/tree/main/rust/src) and @@ -63,23 +65,24 @@ compile them into source at build time. No keyword is hard-coded in a scanner, w The spec opens with rule [R0](/trackparse/reference/spec/#r0-portability), which exists so that every port gives the same bytes: -- Whitespace is an explicit list of code points, never a language's `\s` or `trim()`. -- Keywords compare with ASCII-only lowercasing. Full Unicode folding is used only for - deduplicating names. -- Strings are walked by code point, not by UTF-16 unit or byte. +- Whitespace is an explicit list of code points, never a language's `\s` or `trim()` + ([R0.2](/trackparse/reference/spec/#r0-portability:~:text=R0.2%20Whitespace%20means)). +- Keywords compare with ASCII-only lowercasing ([R0.3](/trackparse/reference/spec/#r0-portability:~:text=R0.3%20Keyword%20comparison)). Full + Unicode folding is used only for deduplicating names ([R0.4](/trackparse/reference/spec/#r0-portability:~:text=R0.4%20Dedup%20key)). +- Strings are walked by code point, not by UTF-16 unit or byte ([R0.5](/trackparse/reference/spec/#r0-portability:~:text=R0.5%20Iterate%20by)). - A "digit" is `0` to `9` and nothing else. - "Letter" and "uppercase letter" mean the Unicode general categories L and Lu, not whatever a - language's `isalpha` accepts. -- Any string must produce a result. Nothing throws or panics. + language's `isalpha` accepts ([R0.6](/trackparse/reference/spec/#r0-portability:~:text=R0.6%20Letter%20means)). +- Any string must produce a result. Nothing throws or panics ([R0.8](/trackparse/reference/spec/#r0-portability:~:text=R0.8%20Parsing%20is)). [Ports](/trackparse/project/ports/) lists the places where a language's standard library disagreed with these rules. ## Tracklists on top -[Tracklists](/trackparse/guides/tracklists/) (R13) reuse the whole pipeline. The text is split into +[Tracklists](/trackparse/guides/tracklists/) ([R13](/trackparse/reference/spec/#r13-tracklists)) reuse the whole pipeline. The text is split into lines, keeping each line's terminator. A small scanner reads the time at the start of each line, and -the rest goes through `parse()` in tracklist mode. +the rest goes through [`parse()`](/trackparse/reference/parse/) in tracklist mode. Two decisions look across lines. A bare track number is only accepted when a neighbour continues the sequence. And an unspaced dash only splits when at least half the list uses spaced dashes. To diff --git a/site/src/content/docs/project/ports.md b/site/src/content/docs/project/ports.md index 5746aef..a428dfa 100644 --- a/site/src/content/docs/project/ports.md +++ b/site/src/content/docs/project/ports.md @@ -8,7 +8,7 @@ description: The JavaScript, Python, Rust and Go implementations, and what it ta | JavaScript / TypeScript | [`trackparse`](https://www.npmjs.com/package/trackparse) on npm | Reference implementation. 13,130 / 13,130 fixtures. Tracklists in `trackparse/tracklist` | | Python | [`trackparse`](https://pypi.org/project/trackparse/) on PyPI | 13,130 / 13,130 fixtures, output identical to JS. Tracklists in `trackparse.tracklist` | | Rust | [`trackparse`](https://crates.io/crates/trackparse) on crates.io, API docs on [docs.rs](https://docs.rs/trackparse) | 13,130 / 13,130 fixtures, output identical to JS. Tracklists in `trackparse::tracklist` | -| Go | [`github.com/4matic/trackparse/go`](https://pkg.go.dev/github.com/4matic/trackparse/go), API docs on pkg.go.dev | 13,130 / 13,130 fixtures, output identical to JS. Tracklists in the same package (`trackparse.ParseTracklist`) | +| Go | [`github.com/4matic/trackparse/go`](https://pkg.go.dev/github.com/4matic/trackparse/go), API docs on [pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go) | 13,130 / 13,130 fixtures, output identical to JS. Tracklists in the same package (`trackparse.ParseTracklist`) | | | JavaScript | Python | Rust | Go | |---|---|---|---|---| @@ -16,7 +16,7 @@ description: The JavaScript, Python, Rust and Go implementations, and what it ta | Needs | Node 18 or newer, or any ES2020 runtime | Python 3.9 or newer | Rust 1.74 or newer | Go 1.22 or newer | | Dependencies | none | none | `unicode-normalization`; `serde` is optional | none | | Types | TypeScript types included | `py.typed`, passes `mypy --strict` | structs and enums, no `unsafe` | structs and typed string constants, no `unsafe`, no cgo | -| Names | `parseArtists`, `fullTitle` | `parse_artists`, `full_title` | `parse_artists`, `full_title` | `ParseArtists`, `FullTitle` | +| Names | [`parseArtists`](/trackparse/reference/functions/#parseartistsinput-options), [`fullTitle`](/trackparse/reference/parse/#parsedtrack) | `parse_artists`, `full_title` | `parse_artists`, `full_title` | `ParseArtists`, `FullTitle` | | Options | one object | keyword arguments | `_with` functions and option builders | `With` functions and option structs | | On bad input | never throws on a string | `TypeError` if the input isn't a `str` | never panics, no `Result` | never panics, no `error` | | JSON | `JSON.stringify(track)` | `track.to_dict()` | `track.to_json()`, or `serde` | `json.Marshal(track)` | @@ -27,7 +27,9 @@ description: The JavaScript, Python, Rust and Go implementations, and what it ta All of them share one version number. The spec, the JavaScript package, the Python package, the Rust crate and the Go module are released together, from one release PR, and CI fails if their versions drift apart. The crate has been on crates.io since 0.4.0. A Go release is the tag -`go/vX.Y.Z`, which the Go module proxy reads. +`go/vX.Y.Z`, which the Go module proxy reads +([published versions](https://proxy.golang.org/github.com/4matic/trackparse/go/@v/list)). The +[changelogs](/trackparse/project/roadmap/#next) list what each release brought. ## Adding a language @@ -39,7 +41,7 @@ pipeline a port has to build. The checklist, in short: 1. Generate source from `spec/data` and `spec/VERSION`, with a check mode for CI. -2. Implement the R0 primitives: the whitespace set, word keys, dedup keys, code-point iteration. +2. Implement the [R0](/trackparse/reference/spec/#r0-portability) primitives: the whitespace set, word keys, dedup keys, code-point iteration. 3. Build the pipeline in the order of `js/src/parser.ts`, then tracklists as a separate module. 4. Write the fixture matcher (about 40 lines) and a runner over both fixture folders, with schema validation and a skip list that can only shrink. @@ -77,7 +79,7 @@ cross-port diff and in random differential runs against JavaScript: - **Normalization follows the crate.** `unicode-normalization` ships Unicode 18 while Node 24 has Unicode 17, so 32 new combining marks are ordered differently in NFC. - **Keyword values are arbitrary strings.** JavaScript passes any string given as a version type or - junk kind in `keywords` through to the output. A port with enums needs a string form inside the + junk kind in [`keywords`](/trackparse/reference/options/#keywords) through to the output. A port with enums needs a string form inside the pipeline to produce the same JSON. - **JavaScript's number formatting is part of the output.** Edit warnings echo the `line` of an edit, so a large or fractional number has to be written the way JavaScript's number-to-string does @@ -124,5 +126,5 @@ typing questions. What was new: ## See also - [How it's tested](/trackparse/project/testing/) for the fixtures and the cross-port diff. -- [The spec](/trackparse/reference/spec/#r0-portability): rule R0 is the portability contract. +- [The spec](/trackparse/reference/spec/#r0-portability): rule [R0](/trackparse/reference/spec/#r0-portability) is the portability contract. - [Contributing](/trackparse/project/contributing/) for the commands of each port. diff --git a/site/src/content/docs/project/roadmap.md b/site/src/content/docs/project/roadmap.md index e1656c9..9b9ac91 100644 --- a/site/src/content/docs/project/roadmap.md +++ b/site/src/content/docs/project/roadmap.md @@ -15,7 +15,7 @@ once. trailing time stays in the title. In a range only the start becomes the line's time; the end ends up in `track.timestamp` and nothing checks it. - Label and catalog numbers as fields. Catalog numbers like `[HOSP123]` stay in the title. - Only known label phrases (`[NCS Release]`) go to `junk` as `label`. + Only known label phrases (`[NCS Release]`) go to [`junk`](/trackparse/guides/junk-and-flags/#junk) as `label`. - Key and BPM (`8A`, `174 BPM`) stay in the title too. - An artist database. `Earth, Wind & Fire` splits unless you pass it in [`knownArtists`](/trackparse/guides/artists/#knownartists) (`known_artists` in Python and Rust, `KnownArtists` in Go), @@ -36,3 +36,9 @@ The changelogs list what has shipped so far: [Rust](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md), [Go](https://github.com/4matic/trackparse/blob/main/go/CHANGELOG.md) and the [spec](https://github.com/4matic/trackparse/blob/main/spec/CHANGELOG.md). + +## See also + +- [Tracklists](/trackparse/guides/tracklists/) for what tracklist parsing does today. +- [Compared to others](/trackparse/project/comparison/) for what other parsers cover. +- [Contributing](/trackparse/project/contributing/) to report a case or propose a rule. diff --git a/site/src/content/docs/project/testing.md b/site/src/content/docs/project/testing.md index 02c02ae..f057163 100644 --- a/site/src/content/docs/project/testing.md +++ b/site/src/content/docs/project/testing.md @@ -17,14 +17,14 @@ field, so nothing drifts unnoticed. |---|---:|---| | Regressions | 273 | Every test from two real-world parsers this library replaces, and the known failures of get-artist-title and friends | | Versions and brackets | 90 | Every version keyword, generic heads (`Radio Edit` → radio), multi-version groups, feat inside brackets | -| Artists | 76 | Joiners, guards (`AC/DC`, `Mumford & Sons`, `Malcolm X`), `knownArtists`, dedup | +| Artists | 76 | Joiners, guards (`AC/DC`, `Mumford & Sons`, `Malcolm X`), [`knownArtists`](/trackparse/reference/options/#parse-options), dedup | | Title credits and producers | 57 | `Title ft. X`, `(prod. by X)`, self-produced artists | | Separators and suffixes | 63 | Dash variants, `- Remastered 2015`, unspaced and asymmetric dashes | | Prefixes, junk, flags | 111 | Track numbers vs `2 Unlimited`, cue times, every junk kind, years, explicit/clean | | Modes | 65 | YouTube pipes, `"Title" by Artist`, uploader fallback, file names | | Unicode and normalization | 71 | NFC, zero-width characters, fullwidth brackets, Cyrillic, CJK, Turkish İ | -| `format`, `parseArtists`, unknown IDs | 94 | Round trips, canonical joiners, `ID - ID` | -| Tracklist mode | 67 | Real lines that single-line `parse()` gets wrong, real lines with no separator at all, Markdown around names, and names that keep their `*` and `_` | +| [`format`](/trackparse/reference/functions/#formattrack-options), [`parseArtists`](/trackparse/reference/functions/#parseartistsinput-options), unknown IDs | 94 | Round trips, canonical joiners, `ID - ID` | +| Tracklist mode | 67 | Real lines that single-line [`parse()`](/trackparse/reference/parse/) gets wrong, real lines with no separator at all, Markdown around names, and names that keep their `*` and `_` | | Tracklist lines and times | 104 | LF/CRLF/CR, trailing spaces, line kinds, every time form, brackets, gap separators, invalid times, list bullets, Markdown around times, `w/` lines | | Tracklist positions | 15 | A real 81-line list numbered without dots, and the `2 Unlimited` guard | | Tracklist warnings | 38 | Each code with its near-miss, and real out-of-order lists with their suggestions | @@ -54,7 +54,7 @@ Each port throws thousands of random strings at the parser to check the [fast-check](https://github.com/dubzzz/fast-check) and the Python suite uses [Hypothesis](https://hypothesis.works). The Rust and Go suites each have a small seeded generator of their own, so neither needs an extra test dependency. The Go module also has fuzz targets for -`Parse`, `ParseArtists`, `Format`, `ParseTracklist`, `ApplyEdits`, `Track.UnmarshalJSON` and the +`Parse`, [`ParseArtists`](/trackparse/reference/functions/#parseartistsinput-options), `Format`, [`ParseTracklist`](/trackparse/reference/tracklist/#parsetracklisttext-options), [`ApplyEdits`](/trackparse/reference/tracklist/#applyeditstext-edits-options), `Track.UnmarshalJSON` and the internal pipeline (`go test -fuzz`) that run the same checks on whatever the fuzzer finds, and a test that calls the parser, the tracklist functions and the edits from 16 goroutines at once under the race detector. @@ -66,7 +66,7 @@ the race detector. under a second in Python; the ceiling is loose so that a busy CI machine doesn't fail the run but a blowup does; -- `normalize` is idempotent; +- [`normalize`](/trackparse/reference/functions/#normalizeinput) is idempotent; - whitespace, dash and zero-width noise don't change the result; - every output validates against the JSON Schema (JavaScript, Python and Go; the Rust output is compared with JavaScript byte for byte instead, see below); @@ -90,9 +90,10 @@ A fixture only checks the fields it asserts. So every fixture input through all four ports, JavaScript, Python, Rust and Go, and diffs the complete JSON output, tracklists and edits included. The difference count is zero. -The Rust crate was also run against JavaScript on random input, which reaches places no fixture -does: about 500,000 random single-track cases and 290,000 random tracklists with edits, again with -zero differences. +[`fuzz-ports.mjs`](https://github.com/4matic/trackparse/blob/main/scripts/fuzz-ports.mjs) does the +same with random input, which reaches places no fixture does. The Rust crate and the Go module were +each run against JavaScript on about 500,000 random single-track cases and 290,000 random +tracklists with edits, again with zero differences. ## Real tracklists @@ -139,6 +140,7 @@ TRACKPARSE_REPORT=1 go test -run TestFixtures -v . # pass rate per file and pe cd .. pnpm build node scripts/compare-ports.mjs # must print "differences: 0" +node scripts/fuzz-ports.mjs # the same diff on random tracks and tracklists with edits ``` ## See also diff --git a/site/src/content/docs/reference/functions.mdx b/site/src/content/docs/reference/functions.mdx index cc9f39a..e58c77c 100644 --- a/site/src/content/docs/reference/functions.mdx +++ b/site/src/content/docs/reference/functions.mdx @@ -18,34 +18,36 @@ functions in snake_case, and the Go package in CamelCase. [`parse`](/trackparse/ | `allArtists` | `all_artists` | `all_artists` | `AllArtists` | | `createParser` | `create_parser` | `Parser::new` | `NewParser` | | `SPEC_VERSION` | `SPEC_VERSION` | `SPEC_VERSION` | `SpecVersion` | -| `parseTracklist`, `applyEdits` (from `trackparse/tracklist`) | `parse_tracklist`, `apply_edits` (from `trackparse.tracklist`) | `parse_tracklist`, `parse_tracklist_with`, `apply_edits`, `apply_edits_with` (from `trackparse::tracklist`) | `ParseTracklist`, `ParseTracklistWith`, `ApplyEdits`, `ApplyEditsWith` (same package) | +| [`parseTracklist`](/trackparse/reference/tracklist/#parsetracklisttext-options), [`applyEdits`](/trackparse/reference/tracklist/#applyeditstext-edits-options) (from `trackparse/tracklist`) | `parse_tracklist`, `apply_edits` (from `trackparse.tracklist`) | `parse_tracklist`, `parse_tracklist_with`, `apply_edits`, `apply_edits_with` (from `trackparse::tracklist`) | `ParseTracklist`, `ParseTracklistWith`, `ApplyEdits`, `ApplyEditsWith` (same package) | What to know for each language: -- **JavaScript.** Options are one object, the last argument. No function throws on a string. - The tracklist functions are in the separate entry `trackparse/tracklist`. -- **Python.** Options are keyword arguments, and fields are snake_case attributes (`full_title`, - `unknown_artist`). Every function that takes a string raises `TypeError` if the input isn't a - `str`. `format_track` and `all_artists` take a `ParsedTrack` and don't check it, so a wrong value +- **JavaScript** ([`trackparse` on npm](https://www.npmjs.com/package/trackparse)). Options are one object, the last argument. No + function throws on a string. The tracklist functions are in the separate entry + `trackparse/tracklist`. +- **Python** ([`trackparse` on PyPI](https://pypi.org/project/trackparse/)). Options are keyword arguments, and fields are + snake_case attributes (`full_title`, `unknown_artist`). Every function that takes a string raises `TypeError` if the input isn't a + `str`. `format_track` and `all_artists` take a [`ParsedTrack`](/trackparse/reference/parse/#parsedtrack) and don't check it, so a wrong value fails with `AttributeError`. Anything else, bad options included, falls back to defaults. -- **Rust.** There are no optional arguments, so each function that takes options comes in two +- **Rust** ([`trackparse` on crates.io](https://crates.io/crates/trackparse)). There are no optional arguments, so each function that takes options comes in two forms. The plain one uses the defaults, and the `_with` one takes a reference to an options struct (`parse_with(input, &options)`). Inputs are `&str`, fields are snake_case, results are returned by value with no `Result`, and no function panics. The signatures are on [docs.rs](https://docs.rs/trackparse). -- **Go.** Like Rust, each function that takes options comes in two forms: `Parse(input)` and +- **Go** ([`github.com/4matic/trackparse/go`](https://pkg.go.dev/github.com/4matic/trackparse/go)). Like Rust, each function that takes options comes in two forms: `Parse(input)` and `ParseWith(input, options)`. Options are structs passed by value, and their zero value means the defaults (the two fields whose zero value is also a real setting are pointers, set with - `trackparse.Ptr`). Fields are exported CamelCase (`FullTitle`, `UnknownArtist`), nullable fields are + [`trackparse.Ptr`](https://pkg.go.dev/github.com/4matic/trackparse/go#Ptr)). Fields are exported CamelCase (`FullTitle`, `UnknownArtist`), nullable fields are pointers, and results are returned by value with no `error`. No function panics, and input that is not valid UTF-8 is read with U+FFFD in place of each bad sequence. The tracklist functions - are in the same package. + are in the same package. Every function has an entry with examples on + [pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go#section-documentation). The options themselves are on the [Options](/trackparse/reference/options/) page. ## parseArtists(input, options?) -*(Python and Rust: `parse_artists`, Go: `ParseArtists`)* +*(Python: `parse_artists`. Rust: [`parse_artists`](https://docs.rs/trackparse/latest/trackparse/fn.parse_artists.html), [`parse_artists_with`](https://docs.rs/trackparse/latest/trackparse/fn.parse_artists_with.html). Go: [`ParseArtists`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseArtists), [`ParseArtistsWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseArtistsWith))* Splits a bare artist string, with no title, into credits. @@ -103,7 +105,7 @@ for _, a := range trackparse.ParseArtists("Sub Focus, Wilkinson & Dimension feat -Takes `knownArtists`, `splitAnd` and `keywords` (`known_artists`, `split_and`, `keywords`; in Rust +Takes [`knownArtists`](/trackparse/guides/artists/#knownartists), [`splitAnd`](/trackparse/guides/artists/#and-is-special) and [`keywords`](/trackparse/reference/options/#keywords) (`known_artists`, `split_and`, `keywords`; in Rust through `parse_artists_with`, in Go through `ParseArtistsWith`). Use it for the artist field of ID3 tags or a streaming API, where the title is already separate. The result is a list of [`Artist`](/trackparse/reference/parse/#artist) values (a `list` in Python, a `Vec` in Rust, a slice @@ -113,9 +115,9 @@ in Go), and the splitting rules are explained in ## format(track, options?) -*(Python and Rust: `format_track`, Go: `Format`)* +*(Python: `format_track`. Rust: [`format_track`](https://docs.rs/trackparse/latest/trackparse/fn.format_track.html), [`format_track_with`](https://docs.rs/trackparse/latest/trackparse/fn.format_track_with.html). Go: [`Format`](https://pkg.go.dev/github.com/4matic/trackparse/go#Format), [`FormatWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#FormatWith))* -Renders a `ParsedTrack` back to a string. Junk is left out. +Renders a [`ParsedTrack`](/trackparse/reference/parse/#parsedtrack) back to a string. Junk is left out. @@ -154,13 +156,15 @@ fmt.Printf("%q\n", trackparse.FormatWith(trackparse.Parse("Wilkinson ft. Becky H -The options are `feat`, `featMarker` (`feat_marker`), `joiners`, `versions`, `producers` and +The options are `feat`, [`featMarker`](/trackparse/guides/formatting/#options) (`feat_marker`), `joiners`, `versions`, `producers` and `position`. In Go they are the fields of `FormatOptions`, where `OmitProducers: true` stands for `producers: false`. [Formatting](/trackparse/guides/formatting/) has the table and an example of each. In the spec this is [R11](/trackparse/reference/spec/#r11-format). ## normalize(input) +*(Python: `normalize`. Rust: [`normalize`](https://docs.rs/trackparse/latest/trackparse/fn.normalize.html). Go: [`Normalize`](https://pkg.go.dev/github.com/4matic/trackparse/go#Normalize))* + The Unicode cleanup every function runs first. It applies NFC, removes invisible characters (zero-width spaces, BOMs, soft hyphens), turns dash, bracket and quote variants into their plain ASCII forms, and collapses whitespace. @@ -196,14 +200,18 @@ fmt.Printf("%q\n", trackparse.Normalize("Noisia\u200b — “Stigma”")) // " -You don't need to call it before `parse`. It's exported because it helps when you build lookup +You don't need to call it before [`parse`](/trackparse/reference/parse/). It's exported because it helps when you build lookup keys. The steps are [R1](/trackparse/reference/spec/#r1-normalization) in the spec. ## allArtists(track) -*(Python and Rust: `all_artists`, Go: `AllArtists`)* +*(Python: `all_artists`. Rust: [`all_artists`](https://docs.rs/trackparse/latest/trackparse/fn.all_artists.html). Go: [`AllArtists`](https://pkg.go.dev/github.com/4matic/trackparse/go#AllArtists))* Every credit of a track in one list: the artists, then every remixer, with duplicates removed. +Names are compared with the dedup key of +[R0.4](/trackparse/reference/spec/#r0-portability:~:text=R0.4%20Dedup%20key), so a remixer who is +also credited as an artist appears once, with their first role. [Artists and credits](/trackparse/guides/artists/) explains where each credit +comes from. @@ -247,10 +255,10 @@ for _, a := range trackparse.AllArtists(trackparse.Parse("Wilkinson ft. Becky Hi ## createParser(options) -*(Python: `create_parser`, Rust: `Parser::new`, Go: `NewParser`)* +*(Python: `create_parser`. Rust: [`Parser::new`](https://docs.rs/trackparse/latest/trackparse/struct.Parser.html). Go: [`NewParser`](https://pkg.go.dev/github.com/4matic/trackparse/go#NewParser), which returns a [`Parser`](https://pkg.go.dev/github.com/4matic/trackparse/go#Parser))* -Compiles options and keywords once and returns an object with `parse` and `parseArtists` -(`parse_artists`). Use it when you parse many strings with the same `knownArtists` or `keywords`. +Compiles options and keywords once and returns an object with [`parse`](/trackparse/reference/parse/) and `parseArtists` +(`parse_artists`). Use it when you parse many strings with the same [`knownArtists`](/trackparse/guides/artists/#knownartists) or [`keywords`](/trackparse/reference/options/#keywords). In JavaScript and Python the two methods still accept options, and per-call options are merged over the compiled ones: `parser.parse(s, { mode: "youtube" })`, `parser.parse(s, mode="youtube")`. @@ -324,6 +332,8 @@ fmt.Println(parser.Parse("Chase & Status x Camo & Krooked - Track (Alix Perez Re ## SPEC_VERSION +*(Rust: [`SPEC_VERSION`](https://docs.rs/trackparse/latest/trackparse/constant.SPEC_VERSION.html). Go: [`SpecVersion`](https://pkg.go.dev/github.com/4matic/trackparse/go#SpecVersion))* + The version of the [spec](/trackparse/reference/spec/) the package implements, as a string (`&str` in Rust, the constant `SpecVersion` in Go). The packages and the spec are released together, so it's the same as the package version. A parsed tracklist carries it too, as `specVersion` (`spec_version` in Python and Rust, @@ -333,6 +343,6 @@ A parsed tracklist carries it too, as `specVersion` (`spec_version` in Python an - [`parse` and `ParsedTrack`](/trackparse/reference/parse/) and [Options](/trackparse/reference/options/). -- [Tracklist API](/trackparse/reference/tracklist/) for `parseTracklist` and `applyEdits`. +- [Tracklist API](/trackparse/reference/tracklist/) for [`parseTracklist`](/trackparse/reference/tracklist/#parsetracklisttext-options) and [`applyEdits`](/trackparse/reference/tracklist/#applyeditstext-edits-options). - [Warnings](/trackparse/reference/warnings/) for the codes these functions report. - [Ports](/trackparse/project/ports/) for how the four packages are kept identical. diff --git a/site/src/content/docs/reference/options.mdx b/site/src/content/docs/reference/options.mdx index 617b371..fcf73fe 100644 --- a/site/src/content/docs/reference/options.mdx +++ b/site/src/content/docs/reference/options.mdx @@ -5,10 +5,12 @@ description: Every option of parse, parseArtists and createParser, including cus import { Tabs, TabItem } from "@astrojs/starlight/components"; -`parse`, `parseArtists` and `createParser` take the same options. JavaScript takes an object, +[`parse`](/trackparse/reference/parse/), [`parseArtists`](/trackparse/reference/functions/#parseartistsinput-options) and [`createParser`](/trackparse/reference/functions/#createparseroptions) take the same options. JavaScript takes an object, Python takes keyword arguments, Rust takes a `ParseOptions` value through the `_with` functions, and Go takes a `ParseOptions` struct through the `With` functions. +## Parse options + @@ -51,7 +53,8 @@ pub struct ParseOptions { } ``` -Start from the defaults and chain a setter per option: +Start from the defaults and chain a setter per option +([`ParseOptions` on docs.rs](https://docs.rs/trackparse/latest/trackparse/struct.ParseOptions.html)): ```rust use trackparse::{parse_with, ModeOption, ParseOptions, SplitAnd}; @@ -78,7 +81,8 @@ type ParseOptions struct { } ``` -Set the fields you need. The others keep their zero value, which is the default: +Set the fields you need. The others keep their zero value, which is the default +([`ParseOptions` on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseOptions)): ```go import ( @@ -106,15 +110,23 @@ fmt.Printf("%q\n", trackparse.ParseWith(input, options).Artists[0].Name) // "C | `knownArtists` | `known_artists` | `KnownArtists` | empty | Names that are never split, like `Chase & Status` or `Earth, Wind & Fire`. Matched case- and accent-insensitively. See [knownArtists](/trackparse/guides/artists/#knownartists) | | `uploader` | `uploader` | `Uploader` | none | The YouTube channel. In youtube mode it becomes the artist when there's no separator. `- Topic` and `VEVO` are dropped. See [the uploader fallback](/trackparse/guides/modes/#the-uploader-fallback) | | `splitAnd` | `split_and` | `SplitAnd` | `"auto"` | `auto` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. `always` and `never` do what they say. See [`and` is special](/trackparse/guides/artists/#and-is-special) | -| `keywords` | `keywords` | `Keywords` | none | Extra vocabulary, see below | +| `keywords` | `keywords` | `Keywords` | none | Extra vocabulary, see [keywords](#keywords) below | + +All five work the same in [`parse`](/trackparse/reference/parse/), +[`parseArtists`](/trackparse/reference/functions/#parseartistsinput-options) (which ignores `mode` +and `uploader`) and [`createParser`](/trackparse/reference/functions/#createparseroptions). The +playground has a field for each but `keywords`: +[this link](/trackparse/playground/#track=Chase%20%26%20Status%20-%20Baddadan&mode=youtube&splitAnd=never&known=Chase%20%26%20Status&uploader=Daft%20Punk%20-%20Topic) opens the example above with all four set. -In Rust the values are enums: `ModeOption::Auto`, `Clean`, `Youtube`, `Filename` or `Tracklist`, -and `SplitAnd::Auto`, `Always` or `Never`. The option structs are `#[non_exhaustive]`, so start +In Rust the values are enums: [`ModeOption`](https://docs.rs/trackparse/latest/trackparse/enum.ModeOption.html)`::Auto`, `Clean`, +`Youtube`, `Filename` or `Tracklist`, and [`SplitAnd`](https://docs.rs/trackparse/latest/trackparse/enum.SplitAnd.html)`::Auto`, `Always` +or `Never`. The option structs are `#[non_exhaustive]`, so start from `ParseOptions::new()` (or `default()`) and chain setters. The fields are public and can also be assigned. -In Go the values are typed strings with constants: `trackparse.ModeAuto`, `ModeClean`, -`ModeYouTube`, `ModeFilename` or `ModeTracklist`, and `SplitAndAuto`, `SplitAndAlways` or `SplitAndNever`. The zero +In Go the values are typed strings with constants: [`trackparse.ModeAuto`](https://pkg.go.dev/github.com/4matic/trackparse/go#ModeAuto), +`ModeClean`, `ModeYouTube`, `ModeFilename` or `ModeTracklist` (the type [`Mode`](https://pkg.go.dev/github.com/4matic/trackparse/go#Mode)), and +`SplitAndAuto`, `SplitAndAlways` or `SplitAndNever` (the type [`SplitAnd`](https://pkg.go.dev/github.com/4matic/trackparse/go#SplitAnd)). The zero value of `ParseOptions` is the defaults: an empty `Mode` is auto, an empty `SplitAnd` is auto and an empty `Uploader` is none. A string that is not one of the constants behaves as an unknown value does in JavaScript. @@ -132,12 +144,15 @@ a missing key is the default, an unknown name such as `"mode":"radio"` is an err ## keywords `keywords` adds words to the built-in vocabulary. It can't take any away. In Python its keys are -snake_case too: `version_heads`, `feat_markers`. In Rust, `KeywordOptions` has one setter per word, -and each call adds one entry. In Go, `Keywords` holds slices: the two maps of the JavaScript options -are ordered slices of `VersionHead` and `JunkPhrase`, because a Go map has no insertion order. They +snake_case too: `version_heads`, `feat_markers`. In Rust, +[`KeywordOptions`](https://docs.rs/trackparse/latest/trackparse/struct.KeywordOptions.html) has one setter per word, and each call adds one +entry. In Go, [`Keywords`](https://pkg.go.dev/github.com/4matic/trackparse/go#Keywords) holds slices: the two maps of the JavaScript options +are ordered slices of [`VersionHead`](https://pkg.go.dev/github.com/4matic/trackparse/go#VersionHead) and [`JunkPhrase`](https://pkg.go.dev/github.com/4matic/trackparse/go#JunkPhrase), because a Go map has no insertion order. They are read as JavaScript reads an object: a repeated key keeps its first place and takes the last value, and integer-like keys come first, in ascending order. The built-in lists are JSON files in -[`spec/data`](https://github.com/4matic/trackparse/tree/main/spec/data). +[`spec/data`](https://github.com/4matic/trackparse/tree/main/spec/data), and the keyword rules are +[R12](/trackparse/reference/spec/#r12-options). [Your own words](/trackparse/guides/versions/#your-own-words) in the +versions guide has another example. @@ -326,21 +341,23 @@ fmt.Printf("%+v\n", r.Junk) // [{Raw:Some Label Rip Kind:label}] ## Tracklist options -`parseTracklist` and `applyEdits` (`parse_tracklist` and `apply_edits` in Python and Rust, +[`parseTracklist`](/trackparse/reference/tracklist/#parsetracklisttext-options) and [`applyEdits`](/trackparse/reference/tracklist/#applyeditstext-edits-options) (`parse_tracklist` and `apply_edits` in Python and Rust, `ParseTracklist` and `ApplyEdits` in Go) take -`mode` (default `"tracklist"`), `knownArtists`, `splitAnd` and `keywords`, plus two of their own. -In Rust they are the setters of `TracklistOptions`, passed to `parse_tracklist_with` and -`apply_edits_with`. In Go they are the fields of the `TracklistOptions` struct, passed to -`ParseTracklistWith` and `ApplyEditsWith`: +`mode` (default `"tracklist"`), [`knownArtists`](/trackparse/guides/artists/#knownartists), [`splitAnd`](/trackparse/guides/artists/#and-is-special) and `keywords`, plus two of their own. +In Rust they are the setters of [`TracklistOptions`](/trackparse/reference/tracklist/#options), passed to `parse_tracklist_with` and +`apply_edits_with` ([`TracklistOptions` on docs.rs](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.TracklistOptions.html)). +In Go they are the fields of the [`TracklistOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#TracklistOptions) struct, passed to +[`ParseTracklistWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseTracklistWith) and [`ApplyEditsWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ApplyEditsWith). The +rules are [R13.10](/trackparse/reference/spec/#r1310-options): | JavaScript | Python and Rust | Go | Default | Description | |---|---|---|---|---| -| `audioSeconds` | `audio_seconds` | `AudioSeconds` | none | Length of the audio. Turns on the `time-after-audio-end` check | -| `markerWords` | `marker_words` | `MarkerWords` | empty | Extra marker words. With `["drop"]`, `03:00 Drop` is a marker, not a track | +| [`audioSeconds`](/trackparse/guides/tracklists/#options) | `audio_seconds` | `AudioSeconds` | none | Length of the audio. Turns on the [`time-after-audio-end`](/trackparse/reference/warnings/#tracklist-warnings:~:text=time%2Dafter%2Daudio%2Dend) check | +| [`markerWords`](/trackparse/guides/tracklists/#options) | `marker_words` | `MarkerWords` | empty | Extra marker words. With `["drop"]`, `03:00 Drop` is a marker, not a track | In Go the zero value of `TracklistOptions` is the defaults too: an empty `Mode` means `ModeTracklist`, and `ModeAuto` asks for auto mode on each line. `AudioSeconds` is a `*float64`, -so `nil` means no length and `trackparse.Ptr(0.0)` is an audio of length 0, as `audioSeconds: 0` +so `nil` means no length and [`trackparse.Ptr`](https://pkg.go.dev/github.com/4matic/trackparse/go#Ptr)`(0.0)` is an audio of length 0, as `audioSeconds: 0` is in JavaScript. [Tracklists](/trackparse/guides/tracklists/#options) has an example in each language, and the @@ -348,15 +365,20 @@ is in JavaScript. ## Format options -`format` has its own options (`feat`, `featMarker`, `joiners`, `versions`, `producers`, `position`). +[`format`](/trackparse/reference/functions/#formattrack-options) has its own options (`feat`, [`featMarker`](/trackparse/guides/formatting/#options), `joiners`, `versions`, `producers`, `position`). They are listed under [Formatting](/trackparse/guides/formatting/#options). In Go they are the -fields of `FormatOptions`; `producers: false` is `OmitProducers: true` there, so the zero value -keeps the producers, and `FeatMarker` is a `*string` (`nil` keeps the input's marker). +fields of [`FormatOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#FormatOptions); `producers: false` is `OmitProducers: true` there, so the zero value +keeps the producers, and `FeatMarker` is a `*string` (`nil` keeps the input's marker). In Rust +they are the setters of [`FormatOptions`](https://docs.rs/trackparse/latest/trackparse/struct.FormatOptions.html). The rules are +[R11](/trackparse/reference/spec/#r11-format). ## See also - [`parse` and `ParsedTrack`](/trackparse/reference/parse/) for what comes back. +- [Tracklist API](/trackparse/reference/tracklist/#options) for the tracklist options next to + `parseTracklist` and `applyEdits`. - [`createParser`](/trackparse/reference/functions/#createparseroptions) to resolve options once for many calls. - [Modes](/trackparse/guides/modes/) and [Artists and credits](/trackparse/guides/artists/) for - what `mode`, `uploader`, `knownArtists` and `splitAnd` change. + what `mode`, [`uploader`](/trackparse/guides/modes/#the-uploader-fallback), [`knownArtists`](/trackparse/guides/artists/#knownartists) and [`splitAnd`](/trackparse/guides/artists/#and-is-special) change. +- [Specification, R12](/trackparse/reference/spec/#r12-options) for the exact option rules. diff --git a/site/src/content/docs/reference/parse.mdx b/site/src/content/docs/reference/parse.mdx index 502fbed..0535e8e 100644 --- a/site/src/content/docs/reference/parse.mdx +++ b/site/src/content/docs/reference/parse.mdx @@ -49,20 +49,23 @@ func ParseWith(input string, options ParseOptions) Track `parse` never fails on a string. Any string gives a `ParsedTrack`, the empty string included, and unknown or malformed options fall back to their defaults. What differs between the languages: -- JavaScript: never throws on a string. -- Python: raises `TypeError` if `input` isn't a `str` (`parse() expects str input, got int`), and - nothing else. -- Rust: takes `&str`, returns the value itself (no `Result`), and never panics. Use `parse` for the - defaults and `parse_with` to pass options. -- Go: takes a `string`, returns the `Track` itself (no `error`), and never panics. Use `Parse` for - the defaults and `ParseWith` to pass options. Bytes that are not valid UTF-8 are read as U+FFFD, +- JavaScript ([`trackparse` on npm](https://www.npmjs.com/package/trackparse)): never throws on a string. +- Python ([`trackparse` on PyPI](https://pypi.org/project/trackparse/)): raises `TypeError` if `input` isn't a `str` + (`parse() expects str input, got int`), and nothing else. +- Rust: takes `&str`, returns the value itself (no `Result`), and never panics. Use + [`parse`](https://docs.rs/trackparse/latest/trackparse/fn.parse.html) for the defaults and [`parse_with`](https://docs.rs/trackparse/latest/trackparse/fn.parse_with.html) to pass + options. +- Go: takes a `string`, returns the [`Track`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track) itself (no `error`), and never panics. Use + [`Parse`](https://pkg.go.dev/github.com/4matic/trackparse/go#Parse) for the defaults and [`ParseWith`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseWith) to pass options. Bytes that are not valid UTF-8 are read as U+FFFD, one per maximal invalid sequence, as Rust's `String::from_utf8_lossy` and the browser's `TextDecoder` do. The options are on the [Options](/trackparse/reference/options/) page. The other functions -(`parseArtists`, `format`, `createParser`) are under +([`parseArtists`](/trackparse/reference/functions/#parseartistsinput-options), [`format`](/trackparse/reference/functions/#formattrack-options), [`createParser`](/trackparse/reference/functions/#createparseroptions)) are under [Other functions](/trackparse/reference/functions/), and the output model is -[defined in the spec](/trackparse/reference/spec/#output-model). +[defined in the spec](/trackparse/reference/spec/#output-model). To see the whole result for any +input, paste it into the [playground](/trackparse/playground/#track=Noisia%20-%20Stigma%20%282015%29) +and open its JSON view. ## ParsedTrack @@ -153,26 +156,27 @@ type Track struct { The table below uses the JavaScript and JSON names. Python has the same fields as attributes of a frozen dataclass, in snake_case (`full_title`, `flags.unknown_artist`), with tuples instead of -arrays and `None` instead of `null`. Rust has a struct with the same snake_case names as public +arrays and `None` instead of `null`. Rust has a struct +([`ParsedTrack`](https://docs.rs/trackparse/latest/trackparse/struct.ParsedTrack.html)) with the same snake_case names as public fields: `Vec` for arrays, `Option` where the table says `null`, and enums for `mode`, roles, -kinds and warnings. Go has a `Track` struct with exported CamelCase fields (`FullTitle`, +kinds and warnings. Go has a [`Track`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track) struct with exported CamelCase fields (`FullTitle`, `Flags.UnknownArtist`): slices for arrays, pointers where the table says `null`, and typed strings for `mode`, roles, kinds and warnings. | Field | Type | Description | |---|---|---| | `input` | `string` | The original string, untouched (not normalized) | -| `mode` | `"clean" \| "youtube" \| "filename" \| "tracklist"` | The mode that ran | -| `position` | `{ raw: string, number: number } \| null` | Track number. `raw` is the digits as written (`"01"`) | -| `timestamp` | `{ raw: string, seconds: number } \| null` | Leading cue time, `"1:02:03"` → 3723 | +| `mode` | `"clean" \| "youtube" \| "filename" \| "tracklist"` | The mode that ran ([R2](/trackparse/reference/spec/#r2-mode-prelude)) | +| `position` | `{ raw: string, number: number } \| null` | Track number. `raw` is the digits as written (`"01"`) ([R4](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position)) | +| [`timestamp`](/trackparse/guides/junk-and-flags/#cue-times) | `{ raw: string, seconds: number } \| null` | Leading cue time, `"1:02:03"` → 3723 ([R4](/trackparse/reference/spec/#r4-prefixes-timestamp-and-position)) | | `artists` | `Artist[]` | Primary, featured and producer credits. Remixers are in `versions` | -| `title` | `string` | The clean title. Brackets it doesn't recognize stay in | -| `fullTitle` | `string` | `title` with the versions put back in their original brackets | +| `title` | `string` | The clean title. Brackets it doesn't recognize stay in ([R8](/trackparse/reference/spec/#r8-title-side)) | +| `fullTitle` | `string` | `title` with the versions put back in their original brackets ([R9.4](/trackparse/reference/spec/#r9-assembly-and-dedup:~:text=R9.4%20fullTitle)) | | `versions` | `Version[]` | Remixes and versions, left to right | -| `year` | `number \| null` | From `(2015)` or `- 2015` | -| `flags` | `{ explicit, clean, unknownArtist, unknownTitle }` | All booleans | -| `junk` | `{ raw: string, kind: JunkKind }[]` | What was taken out of the title, and what kind of noise it was | -| `warnings` | `Warning[]` | Which heuristics fired. See [Warnings](/trackparse/reference/warnings/) | +| `year` | `number \| null` | From `(2015)` or `- 2015`, the first in text order ([R9.6](/trackparse/reference/spec/#r9-assembly-and-dedup:~:text=R9.6%20Track%20year)) | +| [`flags`](/trackparse/guides/junk-and-flags/#flags) | `{ explicit, clean, unknownArtist, unknownTitle }` | All booleans ([R5.4](/trackparse/reference/spec/#r5-group-classification:~:text=R5.4%20Flag), [R8.6](/trackparse/reference/spec/#r8-title-side:~:text=R8.6%20Unknown%20title)) | +| [`junk`](/trackparse/guides/junk-and-flags/#junk) | `{ raw: string, kind: JunkKind }[]` | What was taken out of the title, and what kind of noise it was ([R5.1](/trackparse/reference/spec/#r5-group-classification:~:text=R5.1%20Junk)) | +| [`warnings`](/trackparse/reference/warnings/) | `Warning[]` | Which heuristics fired. See [Warnings](/trackparse/reference/warnings/) | The guides show each field at work: [Modes](/trackparse/guides/modes/) for `mode`, [Junk, flags and prefixes](/trackparse/guides/junk-and-flags/) for `position`, `timestamp`, `year`, @@ -219,8 +223,10 @@ type Artist struct { Name string; Role Role; Joiner *string; Source Source } | `source` | `artist` (left of the dash), `title` (right of it), `version` (inside a version) | `&`, `x` and `vs.` are joiners, not roles. Everyone they join is `primary`. In Rust, `role` and -`source` are `ArtistRole::Primary`, `ArtistSource::Artist` and so on; in Go they are -`trackparse.RolePrimary`, `trackparse.SourceArtist` and so on. +`source` are [`ArtistRole`](https://docs.rs/trackparse/latest/trackparse/enum.ArtistRole.html)`::Primary`, +[`ArtistSource`](https://docs.rs/trackparse/latest/trackparse/enum.ArtistSource.html)`::Artist` and so on; in Go they are +[`trackparse.RolePrimary`](https://pkg.go.dev/github.com/4matic/trackparse/go#RolePrimary), [`trackparse.SourceArtist`](https://pkg.go.dev/github.com/4matic/trackparse/go#SourceArtist) and so +on. The splitting rules are [R7](/trackparse/reference/spec/#r7-artist-side). [Artists and credits](/trackparse/guides/artists/) has examples. ## Version @@ -300,13 +306,15 @@ type Version struct { | `modifiers` | type words that didn't become the type: `Extended VIP Mix` → `vip`, `["extended"]` | | `descriptor` | leftover words: `"Taylor's"`, `"at Wembley"`, `"D'n'B"` | | `year` | a year inside the version: `Remastered 2015` → 2015 | -| `unknownArtist` | `true` for `ID Remix` and the like | +| [`unknownArtist`](/trackparse/guides/artists/#unknown-artists) | `true` for `ID Remix` and the like | | `delimiter` | the bracket it was in, or `-` for a dash suffix | Python uses `unknown_artist`. Rust uses `unknown_artist` and `version_type`, because `type` is a -reserved word, and `delimiter` is `VersionDelimiter::Paren`, `Square`, `Curly` or `Dash`. Go uses -`Type`, `UnknownArtist` and the `Delimiter` constants `DelimiterParen`, `DelimiterSquare`, -`DelimiterCurly` and `DelimiterDash`. +reserved word, and `delimiter` is [`VersionDelimiter`](https://docs.rs/trackparse/latest/trackparse/enum.VersionDelimiter.html)`::Paren`, +`Square`, `Curly` or `Dash`. Go uses `Type` (a [`VersionType`](https://pkg.go.dev/github.com/4matic/trackparse/go#VersionType)), `UnknownArtist` +and the [`Delimiter`](https://pkg.go.dev/github.com/4matic/trackparse/go#Delimiter) constants `DelimiterParen`, `DelimiterSquare`, +`DelimiterCurly` and `DelimiterDash`. The version rules are +[R5.7](/trackparse/reference/spec/#r5-group-classification:~:text=R5.7%20Version). [Versions and remixes](/trackparse/guides/versions/) explains how the type is chosen. ## Junk kinds @@ -314,8 +322,8 @@ reserved word, and `delimiter` is `VersionDelimiter::Paren`, `Square`, `Curly` o `video`, `audio`, `lyrics`, `quality`, `promo`, `platform`, `label`, `genre`, `other`. Examples are in [Junk, flags and prefixes](/trackparse/guides/junk-and-flags/#junk). The vocabulary is in [`spec/data`](https://github.com/4matic/trackparse/tree/main/spec/data). In Rust the kind is the -enum `JunkKind` (`JunkKind::Video` and so on), in Go the typed string `JunkKind` -(`trackparse.JunkKindVideo` and so on). +enum [`JunkKind`](https://docs.rs/trackparse/latest/trackparse/enum.JunkKind.html) (`JunkKind::Video` and so on), in Go the typed string +[`JunkKind`](https://pkg.go.dev/github.com/4matic/trackparse/go#JunkKind) (`trackparse.JunkKindVideo` and so on). @@ -323,7 +331,7 @@ enum `JunkKind` (`JunkKind::Video` and so on), in Go the typed string `JunkKind` ## Serializing to JSON All four packages write the same JSON, byte for byte, on every fixture input. The keys are the -camelCase ones of the spec (`fullTitle`, `unknownArtist`), also in Python, Rust and Go. +camelCase ones of the spec (`fullTitle`, [`unknownArtist`](/trackparse/guides/artists/#unknown-artists)), also in Python, Rust and Go. @@ -379,7 +387,7 @@ serde_json::from_str::(&json).unwrap() == track; // true ``` The results are plain structs that derive `Debug`, `Clone`, `PartialEq` and `Eq`. Each has -`to_json()`, which writes the spec's JSON as a compact string and needs no feature and no extra +[`to_json()`](https://docs.rs/trackparse/latest/trackparse/trait.ToJson.html), which writes the spec's JSON as a compact string and needs no feature and no extra dependency. With the optional `serde` feature (`cargo add trackparse --features serde`) the result types, the options and the tracklist `Edit` implement `Serialize` and `Deserialize` with the same keys, so `serde_json` writes the same text and reads it back. @@ -407,9 +415,11 @@ err := json.Unmarshal(data, &back) fmt.Println(err, reflect.DeepEqual(back, track)) // true ``` -The results are plain structs with exported fields. Every result type has a `MarshalJSON` method +The results are plain structs with exported fields. Every result type has a +[`MarshalJSON`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track.MarshalJSON) method that writes the spec's JSON, the same bytes as `JSON.stringify` in JavaScript, so -`encoding/json` needs no struct tags or options. `Track` also has `UnmarshalJSON`, which reads +`encoding/json` needs no struct tags or options. `Track` also has +[`UnmarshalJSON`](https://pkg.go.dev/github.com/4matic/trackparse/go#Track.UnmarshalJSON), which reads that JSON back. Nullable fields are pointers (`*Position`, `*int`), and `json.Marshal` writes them as `null` when they are `nil`. @@ -417,30 +427,31 @@ as `null` when they are `nil`. Tracklist results serialize the same way: `JSON.stringify(list)`, `tl.to_dict()`, -`list.to_json()` and `json.Marshal(list)`. See the [Tracklist API](/trackparse/reference/tracklist/). +`list.to_json()` and `json.Marshal(list)`. See the [Tracklist API](/trackparse/reference/tracklist/) +and the [JSON section](/trackparse/guides/tracklists/#json) of the tracklist guide. ## Types -All of these are exported from `trackparse` as TypeScript types: +All of these are exported from [`trackparse`](https://www.npmjs.com/package/trackparse) as TypeScript types: `ParsedTrack`, `Artist`, `ArtistRole`, `ArtistSource`, `Version`, `VersionType`, `VersionDelimiter`, `Junk`, `JunkKind`, `Flags`, `Position`, `Timestamp`, `Warning`, `Mode`, -`ModeOption`, `ParseOptions`, `KeywordOptions`, `FormatOptions`, and `Parser`, the type -`createParser` returns. +`ModeOption`, [`ParseOptions`](/trackparse/reference/options/#parse-options), [`KeywordOptions`](/trackparse/reference/options/#keywords), [`FormatOptions`](/trackparse/guides/formatting/#options), and `Parser`, the type +[`createParser`](/trackparse/reference/functions/#createparseroptions) returns. -The package ships `py.typed` and passes `mypy --strict`. These are exported from `trackparse`: +The [package](https://pypi.org/project/trackparse/) ships `py.typed` and passes `mypy --strict`. These are exported from `trackparse`: - dataclasses: `ParsedTrack`, `Artist`, `Version`, `Junk`, `Flags`, `Position`, `Timestamp`; - `Literal` aliases: `ArtistRole`, `ArtistSource`, `VersionType`, `VersionDelimiter`, `JunkKind`, `Warning`, `Mode`, `ModeOption`; -- `TypedDict`s for options: `ParseOptions`, `KeywordOptions`, `FormatOptions`; -- `Parser`, the class `create_parser` returns. +- `TypedDict`s for options: [`ParseOptions`](/trackparse/reference/options/#parse-options), [`KeywordOptions`](/trackparse/reference/options/#keywords), [`FormatOptions`](/trackparse/guides/formatting/#options); +- `Parser`, the class [`create_parser`](/trackparse/reference/functions/#createparseroptions) returns. @@ -452,8 +463,8 @@ All of these are exported from the crate root (`use trackparse::…`): - enums: `ArtistRole`, `ArtistSource`, `VersionType`, `VersionDelimiter`, `JunkKind`, `Warning`, `Mode`. Each has `as_str()` (the spec's name, which `Display` prints too), `from_name()`, `FromStr` (its error is `UnknownName`) and `ALL`; -- options: `ParseOptions`, `KeywordOptions`, `FormatOptions`, with the enums `ModeOption`, - `SplitAnd`, `FeatPlacement`, `JoinerStyle` and `VersionsOption`; +- options: [`ParseOptions`](/trackparse/reference/options/#parse-options), [`KeywordOptions`](/trackparse/reference/options/#keywords), [`FormatOptions`](/trackparse/guides/formatting/#options), with the enums `ModeOption`, + [`SplitAnd`](/trackparse/guides/artists/#and-is-special), `FeatPlacement`, `JoinerStyle` and `VersionsOption`; - `Parser`. Every result type has `to_json()`. ```rust @@ -481,9 +492,9 @@ name `trackparse`): has a constant per value (`trackparse.RolePrimary`, `trackparse.VersionTypeSpedUp`) and a function that returns all values in the spec's order as a new slice (`AllRoles()`, `AllVersionTypes()`). The value is the spec's name, so `fmt` prints it as is and a plain conversion reads one; -- options: `ParseOptions`, `Keywords` (with `VersionHead` and `JunkPhrase`), `FormatOptions`, - with the typed strings `SplitAnd`, `FeatPlacement`, `JoinerStyle` and `VersionsOption`; -- `Parser`, the type `NewParser` returns. Every result type has `MarshalJSON`. +- options: [`ParseOptions`](/trackparse/reference/options/#parse-options), [`Keywords`](/trackparse/reference/options/#keywords) (with `VersionHead` and `JunkPhrase`), [`FormatOptions`](/trackparse/guides/formatting/#options), + with the typed strings [`SplitAnd`](/trackparse/guides/artists/#and-is-special), `FeatPlacement`, `JoinerStyle` and `VersionsOption`; +- `Parser`, the type [`NewParser`](/trackparse/reference/functions/#createparseroptions) returns. Every result type has `MarshalJSON`. ```go fmt.Println(trackparse.VersionTypeSpedUp) // spedUp @@ -504,8 +515,8 @@ The JSON shape is also published as a JSON Schema, ## See also - [Options](/trackparse/reference/options/): everything `parse` accepts. -- [Other functions](/trackparse/reference/functions/): `parseArtists`, `format`, `normalize`, - `allArtists`, `createParser`. +- [Other functions](/trackparse/reference/functions/): [`parseArtists`](/trackparse/reference/functions/#parseartistsinput-options), [`format`](/trackparse/reference/functions/#formattrack-options), [`normalize`](/trackparse/reference/functions/#normalizeinput), + [`allArtists`](/trackparse/reference/functions/#allartiststrack), [`createParser`](/trackparse/reference/functions/#createparseroptions). - [Warnings](/trackparse/reference/warnings/): every warning and how to check for it. -- [Tracklist API](/trackparse/reference/tracklist/): `parseTracklist` and `applyEdits`. +- [Tracklist API](/trackparse/reference/tracklist/): [`parseTracklist`](/trackparse/reference/tracklist/#parsetracklisttext-options) and [`applyEdits`](/trackparse/reference/tracklist/#applyeditstext-edits-options). - [What it understands](/trackparse/guides/what-it-understands/): results for real inputs. diff --git a/site/src/content/docs/reference/tracklist.mdx b/site/src/content/docs/reference/tracklist.mdx index 36e7074..80544c4 100644 --- a/site/src/content/docs/reference/tracklist.mdx +++ b/site/src/content/docs/reference/tracklist.mdx @@ -44,15 +44,15 @@ func ApplyEditsWith(text string, edits []Edit, options TracklistOptions) EditRes Neither function fails on string input. What to know for each language: -- **JavaScript.** The functions live in the entry `trackparse/tracklist`, so code that only uses - `parse` never loads them. Results are plain objects, and `JSON.stringify` gives the spec's JSON. -- **Python.** Results are frozen dataclasses with snake_case attributes (`spec_version`, +- **JavaScript** ([`trackparse` on npm](https://www.npmjs.com/package/trackparse)). The functions live in the entry `trackparse/tracklist`, so code that only uses + [`parse`](/trackparse/reference/parse/) never loads them. Results are plain objects, and `JSON.stringify` gives the spec's JSON. +- **Python** ([`trackparse` on PyPI](https://pypi.org/project/trackparse/)). Results are frozen dataclasses with snake_case attributes (`spec_version`, `first_time`) and a `to_dict()` that returns the spec's JSON shape. Edits are plain dicts with the same keys as in JavaScript, `"from"` included. A `text` that isn't a `str` raises `TypeError`. -- **Rust.** Results are structs with public snake_case fields and `to_json()`. Edits are values of +- **Rust** ([`trackparse::tracklist` on docs.rs](https://docs.rs/trackparse/latest/trackparse/tracklist/index.html)). Results are structs with public snake_case fields and `to_json()`. Edits are values of the `Edit` enum (listed under [Types](#types)). Options go through the `_with` functions, and nothing panics. -- **Go.** The functions are in the package `trackparse` itself, with no separate import. Results +- **Go** ([pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go)). The functions are in the package `trackparse` itself, with no separate import. Results are structs with exported fields (`SpecVersion`, `FirstTime`) whose `MarshalJSON` writes the spec's JSON. Edits are `Edit` structs made with a constructor per edit (listed under [Types](#types)). Options go through the `With` functions, and nothing panics. @@ -63,10 +63,13 @@ The guides [Tracklists](/trackparse/guides/tracklists/) and ## parseTracklist(text, options?) -*(Python: `parse_tracklist`. Rust: `parse_tracklist(text)` and `parse_tracklist_with(text, &options)`. -Go: `ParseTracklist(text)` and `ParseTracklistWith(text, options)`)* +*(Python: `parse_tracklist`. Rust: [`parse_tracklist(text)`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.parse_tracklist.html) and +[`parse_tracklist_with(text, &options)`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.parse_tracklist_with.html). +Go: [`ParseTracklist(text)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseTracklist) and [`ParseTracklistWith(text, options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseTracklistWith))* -Returns a `Tracklist`. Every key is always present. +Returns a `Tracklist` ([`Tracklist`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.Tracklist.html) in Rust, [`Tracklist`](https://pkg.go.dev/github.com/4matic/trackparse/go#Tracklist) in Go). Every key is +always present ([R13.8](/trackparse/reference/spec/#r138-output)). The [playground](/trackparse/playground/#list=00%3A00%20Noisia%20-%20Stigma%0A04%3A10%20Mefjus%20-%20Sleepless%20%28Phace%20Remix%29%0Aw%2F%20Phace%20-%20Psycho%20%28Acapella%29%0A09%3A30%20Outro) shows every entry of a list as a +table, with its JSON. @@ -122,22 +125,24 @@ type Tracklist struct { ### TracklistEntry One per line, in order. The table uses the JavaScript and JSON types. Python has `None` for -`null`. In Rust, `line` is a `usize`, `kind` and `eol` are the enums `EntryKind` and `Eol` -(`as_str()` gives the strings below), `time` is an `Option` whose `seconds` is an `f64`, -and `track` is an `Option`. Go calls the type `Entry`: `Kind` and `Eol` are string -types whose values are the strings below, `Time` is a `*TracklistTime` whose `Seconds` is a -`float64`, and `Track` is a `*Track`, `nil` where the table says `null`. +`null`. In Rust ([`TracklistEntry`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.TracklistEntry.html)), `line` is a `usize`, `kind` and `eol` are the +enums [`EntryKind`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.EntryKind.html) and [`Eol`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.Eol.html) (`as_str()` gives the strings below), `time` is +an `Option` (a [`TimeValue`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.TimeValue.html)) whose `seconds` is an `f64`, and `track` is an +`Option`. Go calls the type [`Entry`](https://pkg.go.dev/github.com/4matic/trackparse/go#Entry): `Kind` and `Eol` are string types +([`EntryKind`](https://pkg.go.dev/github.com/4matic/trackparse/go#EntryKind), [`Eol`](https://pkg.go.dev/github.com/4matic/trackparse/go#Eol)) whose values are the strings below, `Time` is a +[`*TracklistTime`](https://pkg.go.dev/github.com/4matic/trackparse/go#TracklistTime) whose `Seconds` is a `float64`, and `Track` is a `*Track`, +`nil` where the table says `null`. | Field | Type | Description | |---|---|---| | `line` | `number` | 1-based | -| `kind` | `"track" \| "marker" \| "header" \| "link" \| "note" \| "blank"` | See [line kinds](/trackparse/guides/tracklists/#line-kinds) | -| `eol` | `"\n" \| "\r\n" \| "\r" \| ""` | The line's own terminator. `""` on a last line without one | +| `kind` | `"track" \| "marker" \| "header" \| "link" \| "note" \| "blank"` | See [line kinds](/trackparse/guides/tracklists/#line-kinds) ([R13.3](/trackparse/reference/spec/#r133-line-kinds)) | +| `eol` | `"\n" \| "\r\n" \| "\r" \| ""` | The line's own terminator. `""` on a last line without one ([R13.1](/trackparse/reference/spec/#r131-lines-and-the-lossless-guarantee)) | | `raw` | `string` | The line exactly as written, never normalized | -| `parts` | `{ lead, time, gap, rest }` | `raw` cut into four strings that join back into it | -| `time` | `{ raw, seconds } \| null` | The start time | -| `track` | `ParsedTrack \| null` | Parsed from `rest` in tracklist mode, without its [Markdown emphasis](/trackparse/guides/tracklists/#markdown), a leading `w/` and a bare track number. Only `track` and `marker` lines have one | -| `layered` | `boolean` | The track text (after any time) starts with `w/` and a space: a [layered track](/trackparse/guides/tracklists/#layered-tracks), played over the previous one | +| [`parts`](/trackparse/guides/tracklists/#nothing-is-lost) | `{ lead, time, gap, rest }` | `raw` cut into four strings that join back into it ([R13.1.3](/trackparse/reference/spec/#r131-lines-and-the-lossless-guarantee:~:text=R13.1.3%20Parts)) | +| `time` | `{ raw, seconds } \| null` | The start time. See [Times](/trackparse/guides/tracklists/#times) ([R13.2](/trackparse/reference/spec/#r132-times)) | +| `track` | `ParsedTrack \| null` | Parsed from `rest` in tracklist mode, without its [Markdown emphasis](/trackparse/guides/tracklists/#markdown), a leading `w/` and a bare track number ([R13.4](/trackparse/reference/spec/#r134-the-track-part)). Only `track` and `marker` lines have one | +| `layered` | `boolean` | The track text (after any time) starts with `w/` and a space: a [layered track](/trackparse/guides/tracklists/#layered-tracks), played over the previous one ([R13.13](/trackparse/reference/spec/#r1313-layered-tracks)) | ### TracklistWarning @@ -183,8 +188,11 @@ type TracklistWarning struct { -Sorted by line. The codes are listed under [Warnings](/trackparse/reference/warnings/#tracklist-warnings). -Warnings from each line's own `ParsedTrack` stay on `entries[i].track.warnings` and aren't repeated +Sorted by line ([R13.7](/trackparse/reference/spec/#r137-warnings)). The codes are listed under [Warnings](/trackparse/reference/warnings/#tracklist-warnings), +and [Suggestions](/trackparse/reference/warnings/#suggestions) explains `suggestion`. In Rust the type +is [`TracklistWarning`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.TracklistWarning.html) with a [`WarningCode`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.WarningCode.html), in Go +[`TracklistWarning`](https://pkg.go.dev/github.com/4matic/trackparse/go#TracklistWarning) with a [`WarningCode`](https://pkg.go.dev/github.com/4matic/trackparse/go#WarningCode). +Warnings from each line's own [`ParsedTrack`](/trackparse/reference/parse/#parsedtrack) stay on `entries[i].track.warnings` and aren't repeated here. ### stats @@ -197,13 +205,14 @@ here. | `firstTime`, `lastTime` | seconds of the first and last time, or `null` | Python and Rust call the last two `first_time` and `last_time`. In Rust the counts are `usize` and -the two times are `Option`. In Go the fields are `FirstTime` and `LastTime`, of type -`*float64`. +the two times are `Option` ([`Stats`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.Stats.html)). In Go ([`Stats`](https://pkg.go.dev/github.com/4matic/trackparse/go#Stats)) the fields are +`FirstTime` and `LastTime`, of type `*float64`. ## applyEdits(text, edits, options?) -*(Python: `apply_edits`. Rust: `apply_edits(text, &edits)` and `apply_edits_with(text, &edits, &options)`. -Go: `ApplyEdits(text, edits)` and `ApplyEditsWith(text, edits, options)`)* +*(Python: `apply_edits`. Rust: [`apply_edits(text, &edits)`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.apply_edits.html) and +[`apply_edits_with(text, &edits, &options)`](https://docs.rs/trackparse/latest/trackparse/tracklist/fn.apply_edits_with.html). +Go: [`ApplyEdits(text, edits)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ApplyEdits) and [`ApplyEditsWith(text, edits, options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ApplyEditsWith))* Returns `{ text, changed, warnings }` (Python, Rust and Go: an `EditResult`). @@ -211,11 +220,13 @@ Returns `{ text, changed, warnings }` (Python, Rust and Go: an `EditResult`). |---|---| | `text` | the edited text | | `changed` | final line numbers of every line an edit wrote, ascending | -| `warnings` | `{ code, edit, line }[]`: `edit` is the index in `edits`, `line` may be `null` | +| [`warnings`](/trackparse/reference/warnings/) | `{ code, edit, line }[]`: `edit` is the index in `edits`, `line` may be `null` | -In Rust, `changed` is a `Vec` and each warning is an -`EditWarning { code: EditWarningCode, edit: usize, line: Option }`. In Go, `Changed` is an -`[]int` and each warning is an `EditWarning{Code EditWarningCode, Edit int, Line *int}`. +In Rust ([`EditResult`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.EditResult.html)), `changed` is a `Vec` and each warning is an +`EditWarning { code: EditWarningCode, edit: usize, line: Option }` +([`EditWarning`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.EditWarning.html)). In Go ([`EditResult`](https://pkg.go.dev/github.com/4matic/trackparse/go#EditResult)), `Changed` is an `[]int` and each warning +is an `EditWarning{Code EditWarningCode, Edit int, Line *int}` ([`EditWarning`](https://pkg.go.dev/github.com/4matic/trackparse/go#EditWarning)). The edit rules +are [R13.9](/trackparse/reference/spec/#r139-edits). ### Edits @@ -235,37 +246,37 @@ In Python an edit is a dict with quoted keys: `{"op": "shift", "seconds": 45, "f `json.Marshal`. Edits run in sequence, each on the result of the one before. Times are written in their line's -style, up to 100 hours (or 999 minutes for lists that never use hours). +style ([R13.9.2](/trackparse/reference/spec/#r139-edits:~:text=R13.9.2%20Time%20style)), up to 100 hours (or 999 minutes for lists that never use hours). [Editing tracklists](/trackparse/guides/editing-tracklists/) has examples of each edit. ### Edit warnings | Code | When | |---|---| -| `style-upgraded` | a time without hours passed one hour and gained them | -| `time-clamped` | a time would go below zero and was set to zero | -| `edit-invalid` | the edit could not apply and changed nothing | +| [`style-upgraded`](/trackparse/reference/warnings/#edit-warnings:~:text=style%2Dupgraded) | a time without hours passed one hour and gained them | +| [`time-clamped`](/trackparse/reference/warnings/#edit-warnings:~:text=time%2Dclamped) | a time would go below zero and was set to zero | +| [`edit-invalid`](/trackparse/reference/warnings/#edit-warnings:~:text=edit%2Dinvalid) | the edit could not apply and changed nothing | -In Rust the codes are `EditWarningCode::StyleUpgraded`, `TimeClamped` and `EditInvalid`. In Go -they are `EditWarningCodeStyleUpgraded`, `EditWarningCodeTimeClamped` and +In Rust the codes are [`EditWarningCode`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.EditWarningCode.html)`::StyleUpgraded`, `TimeClamped` and +`EditInvalid`. In Go they are [`EditWarningCodeStyleUpgraded`](https://pkg.go.dev/github.com/4matic/trackparse/go#EditWarningCodeStyleUpgraded), `EditWarningCodeTimeClamped` and `EditWarningCodeEditInvalid`. [Warnings](/trackparse/reference/warnings/#edit-warnings) shows how to check them. ## Options -Both functions take the same options. `applyEdits` accepts them for symmetry; edits don't depend on +Both functions take the same options ([R13.10](/trackparse/reference/spec/#r1310-options)). `applyEdits` accepts them for symmetry; edits don't depend on them. | JavaScript | Python and Rust | Go | Default | Description | |---|---|---|---|---| -| `mode` | `mode` | `Mode` | `"tracklist"` | Mode for each line's `parse()` | -| `knownArtists`, `splitAnd`, `keywords` | `known_artists`, `split_and`, `keywords` | `KnownArtists`, `SplitAnd`, `Keywords` | as for `parse` | As for [`parse()`](/trackparse/reference/options/) | -| `audioSeconds` | `audio_seconds` | `AudioSeconds` | none | Length of the audio. Enables `time-after-audio-end` | -| `markerWords` | `marker_words` | `MarkerWords` | empty | Extra marker words | +| `mode` | `mode` | `Mode` | `"tracklist"` | Mode for each line's [`parse()`](/trackparse/reference/parse/). See [Tracklist mode](/trackparse/guides/tracklists/#tracklist-mode) | +| [`knownArtists`](/trackparse/guides/artists/#knownartists), [`splitAnd`](/trackparse/guides/artists/#and-is-special), [`keywords`](/trackparse/reference/options/#keywords) | `known_artists`, `split_and`, `keywords` | `KnownArtists`, `SplitAnd`, `Keywords` | as for `parse` | As for [`parse()`](/trackparse/reference/options/) | +| [`audioSeconds`](/trackparse/guides/tracklists/#options) | `audio_seconds` | `AudioSeconds` | none | Length of the audio. Enables [`time-after-audio-end`](/trackparse/reference/warnings/#tracklist-warnings:~:text=time%2Dafter%2Daudio%2Dend) | +| [`markerWords`](/trackparse/guides/tracklists/#options) | `marker_words` | `MarkerWords` | empty | Extra marker words | -Python uses keyword arguments. Rust has a setter of the same name for each on `TracklistOptions`, +Python uses keyword arguments. Rust has a setter of the same name for each on [`TracklistOptions`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.TracklistOptions.html), for example `TracklistOptions::new().audio_seconds(3600.0).marker_words(["drop"])`, and passes it -to `parse_tracklist_with` or `apply_edits_with`. Go takes a `TracklistOptions` struct, for example +to `parse_tracklist_with` or `apply_edits_with`. Go takes a [`TracklistOptions`](https://pkg.go.dev/github.com/4matic/trackparse/go#TracklistOptions) struct, for example `trackparse.TracklistOptions{AudioSeconds: trackparse.Ptr(3600.0), MarkerWords: []string{"drop"}}`, in `ParseTracklistWith` or `ApplyEditsWith`. Its zero value is the defaults: an empty `Mode` means `ModeTracklist` (`ModeAuto` asks for auto), and a `nil` `AudioSeconds` means no length, while @@ -295,7 +306,7 @@ Exported from `trackparse.tracklist`: the dataclasses `Tracklist`, `TracklistEnt Exported from `trackparse::tracklist`: the structs `Tracklist`, `TracklistEntry`, `Parts`, `TimeValue`, `Suggestion`, `Stats`, `TracklistWarning`, `TracklistOptions`, `EditResult` and `EditWarning`, the enums `EntryKind`, `Eol`, `Severity`, `WarningCode` and `EditWarningCode`, and -the edits: +the edits ([`Edit`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.Edit.html) on docs.rs): ```rust #[non_exhaustive] @@ -320,7 +331,7 @@ Everything is in the package `trackparse`: the structs `Tracklist`, `Entry`, `Pa `TracklistTime`, `Suggestion`, `Stats`, `TracklistWarning`, `TracklistOptions`, `EditResult`, `EditWarning` and `Edit`, and the string types `EntryKind`, `Eol`, `Severity`, `WarningCode`, `EditWarningCode` and `EditOp`, each with its constants (`EntryKindTrack`, `EolCRLF`, -`WarningCodeTimeOutOfOrder`). An edit is a struct whose `Op` says which fields it reads: +`WarningCodeTimeOutOfOrder`). An edit is a struct ([`Edit`](https://pkg.go.dev/github.com/4matic/trackparse/go#Edit)) whose `Op` says which fields it reads: ```go type Edit struct { @@ -335,10 +346,10 @@ type Edit struct { } ``` -Build one with a constructor: `trackparse.SetTime(line, seconds)`, `trackparse.Shift(seconds)`, -`trackparse.ShiftFrom(seconds, from)`, `trackparse.ShiftLines(seconds, lines...)`, -`trackparse.SortByTime()`, `trackparse.SetRest(line, rest)`, `trackparse.Insert(after, text)` and -`trackparse.Delete(line)`. `json.Marshal` writes an edit in the spec's JSON form. +Build one with a constructor: [`trackparse.SetTime(line, seconds)`](https://pkg.go.dev/github.com/4matic/trackparse/go#SetTime), [`trackparse.Shift(seconds)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Shift), +[`trackparse.ShiftFrom(seconds, from)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ShiftFrom), [`trackparse.ShiftLines(seconds, lines...)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ShiftLines), +[`trackparse.SortByTime()`](https://pkg.go.dev/github.com/4matic/trackparse/go#SortByTime), [`trackparse.SetRest(line, rest)`](https://pkg.go.dev/github.com/4matic/trackparse/go#SetRest), [`trackparse.Insert(after, text)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Insert) and +[`trackparse.Delete(line)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Delete). `json.Marshal` writes an edit in the spec's JSON form. @@ -356,4 +367,5 @@ The Rust items are also on - [Warnings](/trackparse/reference/warnings/#tracklist-warnings): every code, and suggestions. - [`parse` and `ParsedTrack`](/trackparse/reference/parse/): the type of each entry's `track`, and [serializing to JSON](/trackparse/reference/parse/#serializing-to-json). -- [Options](/trackparse/reference/options/): the options shared with `parse`. +- [Options](/trackparse/reference/options/#tracklist-options): the options shared with `parse`. +- [Specification, R13](/trackparse/reference/spec/#r13-tracklists): the exact tracklist rules. diff --git a/site/src/content/docs/reference/warnings.mdx b/site/src/content/docs/reference/warnings.mdx index d964029..4fb7d8a 100644 --- a/site/src/content/docs/reference/warnings.mdx +++ b/site/src/content/docs/reference/warnings.mdx @@ -10,23 +10,26 @@ three kinds: on a single track, on a tracklist, and on an edit. In JavaScript and Python a warning code is a string. In Rust it is an enum variant, and `as_str()` or `Display` gives the same string. In Go it is a constant of a string type, whose value is the -string. The tables below give the string, the Rust variant and the Go constant for each code. +string. The tables below give the string, the Rust variant and the Go constant for each code, and +the rule of the [spec](/trackparse/reference/spec/) that raises it. ## Track warnings `ParsedTrack.warnings` is a list of codes: an array of strings in JavaScript, a tuple of strings in -Python, a `Vec` in Rust, a `[]Warning` in Go. An empty list means every decision was unambiguous. +Python, a `Vec` in Rust ([`Warning`](https://docs.rs/trackparse/latest/trackparse/enum.Warning.html)), a `[]Warning` in Go +([`Warning`](https://pkg.go.dev/github.com/4matic/trackparse/go#Warning)). An empty list means every decision was unambiguous. Click an example +to open it in the playground. | Warning | Rust | Go | Means | Example | |---|---|---|---|---| -| `noSeparator` | `Warning::NoSeparator` | `WarningNoSeparator` | No artist/title separator was found. The whole string is the title | `Around the World` | -| `ambiguousSeparator` | `Warning::AmbiguousSeparator` | `WarningAmbiguousSeparator` | A pipe-separated YouTube title had two parts and no dash, so they were read as artist and title | `Noisia \| Stigma` | -| `unspacedDashSplit` | `Warning::UnspacedDashSplit` | `WarningUnspacedDashSplit` | Split at a dash without spaces around it (youtube and filename modes, and timed tracklist lines) | `Blink-182-All The Small Things` | -| `asymmetricDashSplit` | `Warning::AsymmetricDashSplit` | `WarningAsymmetricDashSplit` | Split at a dash with a space on one side only | `Artist -Title` | -| `bySplit` | `Warning::BySplit` | `WarningBySplit` | Read `"Title" by Artist` (youtube mode) | `"Numb" by Linkin Park` | -| `quotedTitleSplit` | `Warning::QuotedTitleSplit` | `WarningQuotedTitleSplit` | Took a quoted span as the title and what came before it as the artist (youtube mode) | `Linkin Park: "Numb"` | -| `ambiguousMixCredit` | `Warning::AmbiguousMixCredit` | `WarningAmbiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough that it might be a style | `(Fonetick Lee & Sonic Art Space Drums Mix)` | -| `unbalancedBrackets` | `Warning::UnbalancedBrackets` | `WarningUnbalancedBrackets` | A bracket was opened and never closed | `Noisia - Stigma (VIP` | +| `noSeparator` | `Warning::NoSeparator` | `WarningNoSeparator` | No artist/title separator was found. The whole string is the title ([R6.8](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.8%20No%20separator)) | [`Around the World`](/trackparse/playground/#track=Around%20the%20World) | +| `ambiguousSeparator` | `Warning::AmbiguousSeparator` | `WarningAmbiguousSeparator` | A pipe-separated YouTube title had two parts and no dash, so they were read as artist and title ([R2.4](/trackparse/reference/spec/#r2-mode-prelude:~:text=R2.4%20youtube%20pipes)) | [`Noisia \| Stigma`](/trackparse/playground/#track=Noisia%20%7C%20Stigma&mode=youtube) | +| `unspacedDashSplit` | `Warning::UnspacedDashSplit` | `WarningUnspacedDashSplit` | Split at a dash without spaces around it (youtube and filename modes, and timed tracklist lines: [R6.7](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.7%20Unspaced%20dash), [R6.10](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.10%20Tracklist%20mode)) | [`Blink-182-All The Small Things`](/trackparse/playground/#track=Blink-182-All%20The%20Small%20Things&mode=youtube) | +| `asymmetricDashSplit` | `Warning::AsymmetricDashSplit` | `WarningAsymmetricDashSplit` | Split at a dash with a space on one side only ([R6.4](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.4%20Asymmetric%20dash)) | [`Artist -Title`](/trackparse/playground/#track=Artist%20-Title) | +| `bySplit` | `Warning::BySplit` | `WarningBySplit` | Read `"Title" by Artist` (youtube mode, [R6.6](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.6%20by%20%28youtube%20only%29)) | [`"Numb" by Linkin Park`](/trackparse/playground/#track=%22Numb%22%20by%20Linkin%20Park&mode=youtube) | +| `quotedTitleSplit` | `Warning::QuotedTitleSplit` | `WarningQuotedTitleSplit` | Took a quoted span as the title and what came before it as the artist (youtube mode, [R6.5](/trackparse/reference/spec/#r6-artisttitle-separator:~:text=R6.5%20Quoted%20title)) | [`Linkin Park: "Numb"`](/trackparse/playground/#track=Linkin%20Park%3A%20%22Numb%22&mode=youtube) | +| `ambiguousMixCredit` | `Warning::AmbiguousMixCredit` | `WarningAmbiguousMixCredit` | ` Mix` was read as a remix, but the name is long enough that it might be a style ([R5.7](/trackparse/reference/spec/#r5-group-classification:~:text=R5.7%20Version)) | [`(Fonetick Lee & Sonic Art Space Drums Mix)`](/trackparse/playground/#track=Artist%20-%20Title%20%28Fonetick%20Lee%20%26%20Sonic%20Art%20Space%20Drums%20Mix%29) | +| `unbalancedBrackets` | `Warning::UnbalancedBrackets` | `WarningUnbalancedBrackets` | A bracket was opened and never closed ([R3.3](/trackparse/reference/spec/#r3-group-scanner-and-skeleton:~:text=R3.3%20An%20opener)) | [`Noisia - Stigma (VIP`](/trackparse/playground/#track=Noisia%20-%20Stigma%20%28VIP) | What to do with them depends on your data. For a music library, a track with any warning is a good candidate for a human to look at. For scrobbling, most of them are fine to accept. @@ -128,10 +131,13 @@ for _, warning := range track.Warnings { ## Tracklist warnings -`Tracklist.warnings` holds objects: `{ code, line, severity, suggestion }`. They are sorted by line. -In Rust the code is a `WarningCode` and the severity is `Severity::Info` or `Severity::Warning`. -In Go they are a `WarningCode` and `SeverityInfo` or `SeverityWarning`, and `Suggestion` is a -pointer. +`Tracklist.warnings` holds objects: `{ code, line, severity, suggestion }` +([`TracklistWarning`](/trackparse/reference/tracklist/#tracklistwarning)). They are sorted by line. +In Rust the code is a [`WarningCode`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.WarningCode.html) and the severity is +[`Severity`](https://docs.rs/trackparse/latest/trackparse/tracklist/enum.Severity.html)`::Info` or `Severity::Warning`. In Go they are a +[`WarningCode`](https://pkg.go.dev/github.com/4matic/trackparse/go#WarningCode) and [`SeverityInfo`](https://pkg.go.dev/github.com/4matic/trackparse/go#SeverityInfo) or `SeverityWarning`, +and `Suggestion` is a pointer. All of them are +[R13.7](/trackparse/reference/spec/#r137-warnings) in the spec. | Code | Rust | Go | Severity | When | |---|---|---|---|---| @@ -139,7 +145,7 @@ pointer. | `time-out-of-order` | `WarningCode::TimeOutOfOrder` | `WarningCodeTimeOutOfOrder` | warning | Earlier than the previous timed line. May carry a `suggestion` | | `time-duplicate` | `WarningCode::TimeDuplicate` | `WarningCodeTimeDuplicate` | warning | Same time as the previous timed line | | `no-start-at-zero` | `WarningCode::NoStartAtZero` | `WarningCodeNoStartAtZero` | info | The first time isn't `0:00` | -| `time-after-audio-end` | `WarningCode::TimeAfterAudioEnd` | `WarningCodeTimeAfterAudioEnd` | warning | Later than `audioSeconds` (`audio_seconds`, `AudioSeconds`) | +| `time-after-audio-end` | `WarningCode::TimeAfterAudioEnd` | `WarningCodeTimeAfterAudioEnd` | warning | Later than [`audioSeconds`](/trackparse/guides/tracklists/#options) (`audio_seconds`, `AudioSeconds`) | | `invalid-time` | `WarningCode::InvalidTime` | `WarningCodeInvalidTime` | warning | Looks like a time but isn't one (`1:75`, `0:61:00`). The line keeps it in `rest` | | `position-gap` | `WarningCode::PositionGap` | `WarningCodePositionGap` | warning | A track number isn't the previous one plus 1 | | `position-duplicate` | `WarningCode::PositionDuplicate` | `WarningCodePositionDuplicate` | warning | Same track number as the previous one | @@ -241,8 +247,7 @@ fmt.Println(slices.ContainsFunc(list.Warnings, func(w trackparse.TracklistWarnin -Here line 3 has no suggestion, because more than one time would fit between its neighbours. The -checks are [R13.7](/trackparse/reference/spec/#r137-warnings) in the spec, and +Here line 3 has no suggestion, because more than one time would fit between its neighbours. [Tracklists](/trackparse/guides/tracklists/#checks) walks through a list that does get a suggestion. @@ -258,20 +263,23 @@ candidate fits, or none does, `suggestion` is `null` (`None` in Python and Rust, suggestion would be worse than none. To apply one, pass its `line` and `seconds` to a `set-time` edit. See -[Editing tracklists](/trackparse/guides/editing-tracklists/). +[Editing tracklists](/trackparse/guides/editing-tracklists/). In the +[playground](/trackparse/playground/#list=48%3A20%20Noisia%20-%20Stigma%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top), +a warning with a suggestion has a button that applies it. ## Edit warnings -`applyEdits` (`apply_edits` in Python and Rust, `ApplyEdits` in Go) returns `{ code, edit, line }` -objects. `edit` is -the index in your list of edits, and `line` is `null` (`None`, `nil` in Go) when the edit names no -line. +[`applyEdits`](/trackparse/reference/tracklist/#applyeditstext-edits-options) (`apply_edits` in Python and Rust, `ApplyEdits` in Go) returns `{ code, edit, line }` +objects ([`EditWarning`](https://docs.rs/trackparse/latest/trackparse/tracklist/struct.EditWarning.html) in Rust, +[`EditWarning`](https://pkg.go.dev/github.com/4matic/trackparse/go#EditWarning) in Go). `edit` is the index in your list of edits, and `line` is +`null` (`None`, `nil` in Go) when the edit names no line. The rules are +[R13.9](/trackparse/reference/spec/#r139-edits). | Code | Rust | Go | When | |---|---|---|---| -| `style-upgraded` | `EditWarningCode::StyleUpgraded` | `EditWarningCodeStyleUpgraded` | a time without hours passed one hour and gained them | -| `time-clamped` | `EditWarningCode::TimeClamped` | `EditWarningCodeTimeClamped` | a time would go below zero and was set to zero | -| `edit-invalid` | `EditWarningCode::EditInvalid` | `EditWarningCodeEditInvalid` | the edit could not apply and changed nothing | +| `style-upgraded` | `EditWarningCode::StyleUpgraded` | `EditWarningCodeStyleUpgraded` | a time without hours passed one hour and gained them ([R13.9.2](/trackparse/reference/spec/#r139-edits:~:text=R13.9.2%20Time%20style)) | +| `time-clamped` | `EditWarningCode::TimeClamped` | `EditWarningCodeTimeClamped` | a time would go below zero and was set to zero ([R13.9.3](/trackparse/reference/spec/#r139-edits:~:text=R13.9.3%20Clamp)) | +| `edit-invalid` | `EditWarningCode::EditInvalid` | `EditWarningCodeEditInvalid` | the edit could not apply and changed nothing ([R13.9.6](/trackparse/reference/spec/#r139-edits:~:text=R13.9.6%20Totality)) | @@ -362,4 +370,6 @@ makes an edit invalid. - [`parse` and `ParsedTrack`](/trackparse/reference/parse/) and the [Tracklist API](/trackparse/reference/tracklist/) for the types that carry the warnings. - [Modes](/trackparse/guides/modes/) for the guesses behind the track warnings. -- [Tracklists](/trackparse/guides/tracklists/#checks) for the list checks. +- [Tracklists](/trackparse/guides/tracklists/#checks) for the list checks, and + [Editing tracklists](/trackparse/guides/editing-tracklists/#when-an-edit-cant-apply) for the + edit warnings. diff --git a/site/src/content/docs/start/getting-started.mdx b/site/src/content/docs/start/getting-started.mdx index 6f0acd5..c04eefb 100644 --- a/site/src/content/docs/start/getting-started.mdx +++ b/site/src/content/docs/start/getting-started.mdx @@ -49,7 +49,8 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; -2. Parse a track. +2. Parse a track with [`parse`](/trackparse/reference/parse/) + ([try it in the playground](/trackparse/playground/#track=Noisia%20feat.%20Foreign%20Beggars%20-%20Shellshock)). @@ -107,7 +108,8 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; -3. Look at the versions and the noise. +3. Look at the [versions](/trackparse/guides/versions/) and the + [noise](/trackparse/guides/junk-and-flags/). @@ -159,7 +161,9 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; -4. Tell it about names that contain a joiner. +4. Tell it about names that contain a joiner with + [`knownArtists`](/trackparse/guides/artists/#knownartists) + ([try it](/trackparse/playground/#track=Chase%20%26%20Status%20-%20Baddadan&known=Chase%20%26%20Status)). @@ -210,7 +214,8 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; -5. Write it back, or turn it into JSON. +5. Write it back with [`format`](/trackparse/guides/formatting/), or turn it into + [JSON](/trackparse/reference/parse/#serializing-to-json). @@ -249,7 +254,7 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; -6. Parse a whole tracklist. +6. Parse a whole [tracklist](/trackparse/guides/tracklists/). @@ -303,8 +308,8 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; ## Where each task is explained diff --git a/site/src/content/docs/start/introduction.mdx b/site/src/content/docs/start/introduction.mdx index c1736ac..6e634f2 100644 --- a/site/src/content/docs/start/introduction.mdx +++ b/site/src/content/docs/start/introduction.mdx @@ -16,7 +16,11 @@ It comes as four packages with the same behaviour: `trackparse` on [crates.io](https://crates.io/crates/trackparse) for Rust, and the module [`github.com/4matic/trackparse/go`](https://pkg.go.dev/github.com/4matic/trackparse/go) for Go. Every example -on this site has a tab for each language. +on this site has a tab for each language. The API docs of the Rust crate are on +[docs.rs](https://docs.rs/trackparse), and those of the Go module on +[pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go). + +Here is what trackparse finds in one line ([try it in the playground](/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D)): ```text 01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video] @@ -39,12 +43,16 @@ away something you needed. The same rule shows up in smaller ways: -- `[Official Video]` leaves the title, but it lands in `junk` as `{ raw: "Official Video", kind: "video" }`. -- When the parser had to guess (an unspaced dash, a `"Title" by Artist` pattern), `warnings` says +- `[Official Video]` leaves the title, but it lands in [`junk`](/trackparse/guides/junk-and-flags/#junk) + as `{ raw: "Official Video", kind: "video" }`. An unknown bracket stays in the title as written + ([R5.8](/trackparse/reference/spec/#r5-group-classification:~:text=R5.8%20Unknown)). +- When the parser had to guess (an unspaced dash, a `"Title" by Artist` pattern), [`warnings`](/trackparse/reference/warnings/) says which guess it made. The codes are listed under [Warnings](/trackparse/reference/warnings/). -- Every key of the output is always present, so you never have to check whether a field exists. -- No string makes it fail. `parse` never throws in JavaScript or Python and never panics in Rust - or Go. +- Every key of the output is always present, so you never have to check whether a field exists + ([the output model](/trackparse/reference/spec/#output-model)). +- No string makes it fail. [`parse`](/trackparse/reference/parse/) never throws in JavaScript or + Python and never panics in Rust or Go + ([R0.8](/trackparse/reference/spec/#r0-portability:~:text=R0.8%20Parsing%20is)). ## What you get back @@ -129,7 +137,7 @@ struct with snake_case fields, and `to_json()` writes that JSON as a string. In with exported CamelCase fields, and `json.Marshal` writes that JSON. The [`parse` reference](/trackparse/reference/parse/) explains every field, and [Serializing to JSON](/trackparse/reference/parse/#serializing-to-json) shows the round trip in each -language. +language. [Try this track in the playground](/trackparse/playground/#track=Queen%20-%20Bohemian%20Rhapsody%20%28Live%20at%20Wembley%201986%29). ## Names in each language @@ -138,9 +146,9 @@ same things, and Go uses exported CamelCase: | | JavaScript | Python | Rust | Go | |---|---|---|---|---| -| Parse | `parse(s, options?)` | `parse(s, **options)` | `parse(s)`, `parse_with(s, &options)` | `Parse(s)`, `ParseWith(s, options)` | +| Parse | [`parse(s, options?)`](/trackparse/reference/parse/) | `parse(s, **options)` | [`parse(s)`](https://docs.rs/trackparse/latest/trackparse/fn.parse.html), [`parse_with(s, &options)`](https://docs.rs/trackparse/latest/trackparse/fn.parse_with.html) | [`Parse(s)`](https://pkg.go.dev/github.com/4matic/trackparse/go#Parse), [`ParseWith(s, options)`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseWith) | | A field | `track.fullTitle` | `track.full_title` | `track.full_title` | `track.FullTitle` | -| An option | `{ knownArtists: […] }` | `known_artists=[…]` | `ParseOptions::new().known_artists([…])` | `ParseOptions{KnownArtists: …}` | +| An option | [`{ knownArtists: […] }`](/trackparse/reference/options/) | `known_artists=[…]` | [`ParseOptions::new().known_artists([…])`](https://docs.rs/trackparse/latest/trackparse/struct.ParseOptions.html) | [`ParseOptions{KnownArtists: …}`](https://pkg.go.dev/github.com/4matic/trackparse/go#ParseOptions) | | A value | `"remix"`, `null` | `"remix"`, `None` | `VersionType::Remix`, `None` | `VersionTypeRemix`, `nil` | | Lists | arrays | tuples | `Vec` | slices | | JSON | `JSON.stringify(track)` | `track.to_dict()` | `track.to_json()`, or `serde` | `json.Marshal(track)` | @@ -150,7 +158,7 @@ same things, and Go uses exported CamelCase: ## Spec first Behaviour isn't defined by the JavaScript code. It's defined by a written -[spec](/trackparse/reference/spec/) with numbered rules, and by 13,130 fixtures that pin those rules +[spec](/trackparse/reference/spec/) with numbered rules (R0 to R13), and by 13,130 fixtures that pin those rules down. The JavaScript package is the reference implementation. The Python package, the Rust crate and the Go module pass the same fixtures and produce the same JSON, byte for byte. [How it's tested](/trackparse/project/testing/) and [Ports](/trackparse/project/ports/) have the @@ -166,12 +174,13 @@ If all you need is a cleaned-up string to send to a scrobbler, scope. trackparse is for when you need to know who did what. It also has no artist database. `&` is a joiner, so `Chase & Status` comes out as two artists unless -you pass it in `knownArtists` (`known_artists` in Python and Rust, `KnownArtists` in Go). More on that in +you pass it in [`knownArtists`](/trackparse/reference/options/#parse-options) (`known_artists` in Python and Rust, `KnownArtists` in Go). More on that in [Artists and credits](/trackparse/guides/artists/#knownartists). The other gaps are listed under [Limitations and roadmap](/trackparse/project/roadmap/). ## Next - [Getting started](/trackparse/start/getting-started/): install it and parse your first track. +- [How it works](/trackparse/project/how-it-works/): the pipeline behind the result. - [What it understands](/trackparse/guides/what-it-understands/): real inputs and their results. - [Playground](/trackparse/playground/): try your own strings in the browser. From 9d25eb1811260939eefcea3702c7160af040e65f Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:32:40 +0200 Subject: [PATCH 10/11] feat(site): the playground links its output to the docs and prints snippets as the formatters do - The generated code moves to src/lib/codegen.ts and comes out as Biome, Ruff, rustfmt and gofmt print it: sorted JS imports, the quote style with fewer escapes, one space before `//` in JS and two before `#` in Python, long calls and arrays broken as each formatter breaks them, `1e21` instead of `1e+21`, and a Python list that does not fit on a line as `lines = [...]`. The Go imports keep the goimports groups (standard library, blank line, module) and drop the empty group when there is no standard-library import. - Under each code panel, every function and type the snippet uses links to its API docs: docs.rs, pkg.go.dev, or the reference pages for JavaScript and Python. - Field names in the field list link to their row in the ParsedTrack table; roles, version types, modifiers, junk kinds, flags, year, position, cue time and mode link to their guide sections. Option labels link to their rows in the options tables, the tracklist columns to TracklistEntry and ParsedTrack, the line kinds to the guide. - The landing cards link their guides, and the stats line says the 0 differences are on the fixtures. --- site/src/components/Features.astro | 13 +- site/src/components/Playground.astro | 478 ++++++--------------- site/src/components/Stats.astro | 2 +- site/src/content/docs/index.mdx | 12 +- site/src/lib/codegen.ts | 601 +++++++++++++++++++++++++++ site/src/lib/trackview.ts | 109 ++++- site/src/styles/playground.css | 32 ++ 7 files changed, 874 insertions(+), 373 deletions(-) create mode 100644 site/src/lib/codegen.ts diff --git a/site/src/components/Features.astro b/site/src/components/Features.astro index f49f5fd..1743545 100644 --- a/site/src/components/Features.astro +++ b/site/src/components/Features.astro @@ -3,6 +3,8 @@ interface Item { title: string; body: string; + /** The guide that explains the item: the title links there. */ + href?: string; } const { items } = Astro.props as { items: Item[] }; --- @@ -12,7 +14,7 @@ const { items } = Astro.props as { items: Item[] }; items.map((it, i) => (
  • -

    {it.title}

    +

    {it.href ? {it.title} : it.title}

  • )) @@ -49,6 +51,15 @@ const { items } = Astro.props as { items: Item[] }; letter-spacing: -0.01em; color: var(--sl-color-white); } + h3 a { + color: inherit; + text-decoration: none; + } + h3 a:hover { + text-decoration: underline; + text-decoration-color: var(--sl-color-accent); + text-underline-offset: 0.2em; + } p { margin: 0.35rem 0 0; font-size: 0.92rem; diff --git a/site/src/components/Playground.astro b/site/src/components/Playground.astro index 2b5832d..3b3fbbc 100644 --- a/site/src/components/Playground.astro +++ b/site/src/components/Playground.astro @@ -4,11 +4,38 @@ import Copy from "@lucide/astro/icons/copy"; import Timer from "@lucide/astro/icons/timer"; import Redo2 from "@lucide/astro/icons/redo-2"; import Undo2 from "@lucide/astro/icons/undo-2"; +import { fieldUrl, textFragment as frag } from "../lib/trackview"; import "../styles/playground.css"; // Docs links next to the controls they explain. const base = import.meta.env.BASE_URL.replace(/\/$/, ""); const doc = (path: string) => `${base}/${path}`; +// Each option name links to its row in an options table: the JavaScript name, then the Python +// and Rust name and the Go name in the next cells, so the text fragment finds that row only. +const opt = (js: string, py: string, go: string, section = "") => doc(`reference/options/#${section}${frag(py, go, js)}`); +const ref = { + mode: opt("mode", "mode", "Mode"), + splitAnd: opt("splitAnd", "split_and", "SplitAnd"), + knownArtists: opt("knownArtists", "known_artists", "KnownArtists"), + uploader: opt("uploader", "uploader", "Uploader"), + audioSeconds: opt("audioSeconds", "audio_seconds", "AudioSeconds", "tracklist-options"), + // The format options are listed in the formatting guide, name then values. + feat: doc(`guides/formatting/#options${frag("feat", '"source"')}`), + joiners: doc(`guides/formatting/#options${frag("joiners", '"original"')}`), + versions: doc(`guides/formatting/#options${frag("versions", '"all"')}`), + shift: doc(`reference/tracklist/#edits${frag("Edit::shift_from")}`), + edits: doc("guides/editing-tracklists/#the-edits"), +}; +// The tracklist table's columns: entry fields in reference/tracklist, track fields in reference/parse. +const entry = (field: string, type: string) => doc(`reference/tracklist/#tracklistentry${frag(field, type)}`); +const columns: { label: string; href: string; title: string }[] = [ + { label: "#", href: entry("line", "number"), title: "line: the 1-based line number" }, + { label: "kind", href: entry("kind", '"track"'), title: "kind: what the line is" }, + { label: "time", href: entry("time", "{ raw"), title: "time: the start time" }, + { label: "artists", href: fieldUrl(base, "artists"), title: "track.artists" }, + { label: "title", href: fieldUrl(base, "title"), title: "track.title" }, + { label: "versions", href: fieldUrl(base, "versions"), title: "track.versions" }, +]; const trackExamples = [ "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]", @@ -110,7 +137,7 @@ const listExamples: { label: string; title: string; text: string }[] = [
    - +
    - +
    - +
    - +
    @@ -159,7 +186,7 @@ const listExamples: { label: string; title: string; text: string }[] = [
    - +
    - +
    - +
    - +
    - Edit the text + Edit the text
    - +
    - +
    @@ -285,10 +313,11 @@ const listExamples: { label: string; title: string; text: string }[] = [ +
    - + {columns.map((c) => )}
    #kindtimeartiststitleversions
    {c.label}
    @@ -409,6 +438,49 @@ const listExamples: { label: string; title: string; text: string }[] = [ .pg-doc { font-size: 0.78rem; } + /* Option names and column heads link to their reference rows: the label colour, a quiet + dotted rule, the accent on hover. */ + .pg-opt, + .tl-table th a, + .tl-table :global(.tl-kind a) { + color: inherit; + text-decoration: underline dotted; + text-decoration-color: var(--tp-border-strong); + text-underline-offset: 0.25em; + } + .pg-opt:hover, + .tl-table th a:hover, + .tl-table :global(.tl-kind a:hover) { + color: var(--sl-color-white); + text-decoration-style: solid; + text-decoration-color: var(--sl-color-accent); + } + /* Every row has a kind: its link shows only on hover, so the column stays quiet. */ + .tl-table :global(.tl-kind a) { + text-decoration-line: none; + } + .tl-table :global(.tl-kind a:hover) { + text-decoration-line: underline; + } + /* The API names under a code panel. */ + .pg-api :global(a) { + text-decoration: none; + } + .pg-api :global(a code) { + color: var(--sl-color-gray-2); + border-bottom: 1px solid var(--tp-border-strong); + border-radius: 4px 4px 0 0; + } + .pg-api :global(a:hover code) { + color: var(--sl-color-white); + border-bottom-color: var(--sl-color-accent); + } + .pg-api[hidden] { + display: none; + } + .pg-api:empty { + display: none; + } /* Generated Go is indented with tabs, as gofmt writes it. */ .tp-code { tab-size: 4; @@ -624,7 +696,8 @@ const listExamples: { label: string; title: string; text: string }[] = [ import { applyEdits, parseTracklist, type Edit, type Tracklist, type TracklistEntry, type TracklistOptions } from "trackparse/tracklist"; import { icon } from "../lib/icons"; import { getLang, PACKAGE, setLang, type Lang } from "../lib/lang"; - import { chip, codeHtml, escapeHtml, fieldsHtml, highlight, jsonHtml, KIND_LABEL, roleKind, segmentsHtml, type Kind } from "../lib/trackview"; + import { apiUrl, listCode, trackCode, type Snippet } from "../lib/codegen"; + import { chip, codeHtml, GUIDE, escapeHtml, fieldsHtml, highlight, jsonHtml, KIND_LABEL, roleKind, segmentsHtml, type Kind } from "../lib/trackview"; const $ = (id: string) => document.getElementById(id) as T; /** The site base (`/trackparse`), for links into the docs. */ @@ -752,144 +825,24 @@ const listExamples: { label: string; title: string; text: string }[] = [ `Install: ${escapeHtml(p.install)}` + `Getting started` + `${p.registry}` + - (lang === "rs" ? 'docs.rs' : ""); + // The API docs: docs.rs for the crate, pkg.go.dev (the link above) for the module, and + // this site's reference for the npm and PyPI packages. + (lang === "rs" + ? 'docs.rs' + : lang === "go" + ? "" + : `API reference`); for (const el of document.querySelectorAll("[data-install]")) el.innerHTML = html; } - // ---- Rust literals for the generated code ------------------------------------------------- - /** Control, invisible and bidi characters, written as escapes in the generated literals. */ - function invisible(cp: number): boolean { - return ( - cp < 0x20 || - (cp >= 0x7f && cp <= 0x9f) || - cp === 0xad || - cp === 0x34f || - cp === 0x61c || - cp === 0x180e || - (cp >= 0x200b && cp <= 0x200f) || - (cp >= 0x2028 && cp <= 0x202e) || - (cp >= 0x2060 && cp <= 0x206f) || - cp === 0xfeff || - (cp >= 0xfff9 && cp <= 0xfffb) - ); - } - /** A JavaScript or Python string literal: JSON, plus `\uXXXX` for invisible characters. */ - function jsStr(s: string): string { - let out = ""; - for (const ch of JSON.stringify(s)) { - const cp = ch.codePointAt(0)!; - out += cp >= 0x7f && invisible(cp) ? `\\u${cp.toString(16).padStart(4, "0")}` : ch; - } - return out; - } - /** A Rust string literal. Control, invisible and bidi characters are written as `\u{…}`. */ - function rsStr(s: string): string { - let out = '"'; - for (const ch of s) { - const cp = ch.codePointAt(0)!; - if (ch === '"' || ch === "\\") out += `\\${ch}`; - else if (ch === "\n") out += "\\n"; - else if (ch === "\r") out += "\\r"; - else if (ch === "\t") out += "\\t"; - // A lone surrogate cannot be in a Rust string: U+FFFD, as a lossy conversion would give. - else if (cp >= 0xd800 && cp <= 0xdfff) out += "\\u{fffd}"; - else if (invisible(cp)) - out += `\\u{${cp.toString(16)}}`; - else out += ch; - } - return `${out}"`; - } - /** An `f64` literal: `45.0`, `7.5`, `1e21`. */ - function rsNum(n: number): string { - if (!Number.isFinite(n)) return Number.isNaN(n) ? "f64::NAN" : n > 0 ? "f64::INFINITY" : "f64::NEG_INFINITY"; - const s = String(n).replace("e+", "e"); - return /[.e]/.test(s) ? s : `${s}.0`; - } - /** `youtube` → `Youtube`: the enum variant of an option value. */ - const variant = (v: unknown) => String(v).charAt(0).toUpperCase() + String(v).slice(1); - /** `use` items in rustfmt order: functions first, then types. */ - function rsUse(path: string, names: string[]): string { - const lower = (n: string) => n[0] === n[0].toLowerCase(); - const sorted = [...names.filter(lower).sort(), ...names.filter((n) => !lower(n)).sort()]; - const line = `use ${path}::${sorted.length === 1 ? sorted[0] : `{${sorted.join(", ")}}`};`; - if (line.length <= 100) return line; - // Too long: the names fill lines of at most 100 columns inside braces. - const rows: string[] = []; - for (const n of sorted) { - const last = rows.length - 1; - if (last >= 0 && `${rows[last]} ${n},`.length <= 100) rows[last] += ` ${n},`; - else rows.push(` ${n},`); - } - return `use ${path}::{\n${rows.join("\n")}\n};`; - } - // rustfmt's main width rules, so the common programs come out as `cargo fmt` writes them. - /** Columns a line takes: wide characters (emoji, CJK) count two. */ - function rsWidth(s: string): number { - let w = 0; - for (const ch of s) { - const cp = ch.codePointAt(0)!; - w += (cp >= 0x1100 && cp <= 0x115f) || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) || (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe30 && cp <= 0xfe4f) || (cp >= 0xff00 && cp <= 0xff60) || (cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1faff) || cp >= 0x20000 ? 2 : 1; - } - return w; - } - /** `let x = Root::new().a().b();`: a chain wider than 60 columns gets one call per line. */ - function rsChain(lhs: string, root: string, calls: string[], indent = " "): string { - const chain = root + calls.join(""); - if (calls.length < 2 || rsWidth(chain) <= 60) return `${lhs}${chain};`; - return `${lhs}${root}\n${calls.map((c) => `${indent} ${c}`).join("\n")};`; - } - /** `let x = f(a, b);`: arguments wider than 60 columns go one per line, if each then fits. */ - function rsCall(lhs: string, fn: string, args: string[], indent = " "): string { - const flat = `${lhs}${fn}(${args.join(", ")});`; - const fits = args.every((a) => indent.length + 4 + rsWidth(a) + 1 <= 100); - if (rsWidth(args.join(", ")) <= 60 || !fits) return flat; - return `${lhs}${fn}(\n${args.map((a) => `${indent} ${a},`).join("\n")}\n${indent});`; - } - - // ---- Go literals for the generated code --------------------------------------------------- - /** A Go string literal. Control, invisible and bidi characters are written as escapes. */ - function goStr(s: string): string { - let out = '"'; - for (const ch of s) { - const cp = ch.codePointAt(0)!; - if (ch === '"' || ch === "\\") out += `\\${ch}`; - else if (ch === "\n") out += "\\n"; - else if (ch === "\r") out += "\\r"; - else if (ch === "\t") out += "\\t"; - // A Go string cannot spell a lone surrogate: U+FFFD, as the module reads invalid UTF-8. - else if (cp >= 0xd800 && cp <= 0xdfff) out += "\\ufffd"; - else if (invisible(cp)) - out += `\\u${cp.toString(16).padStart(4, "0")}`; - else out += ch; - } - return `${out}"`; - } - /** A float64 constant: `45`, `7.5`, `1e+21`; `math.Inf(1)` and `math.NaN()` need the math import. */ - function goNum(n: number): string { - if (!Number.isFinite(n)) return Number.isNaN(n) ? "math.NaN()" : n > 0 ? "math.Inf(1)" : "math.Inf(-1)"; - return String(n); - } - /** A float64 value for trackparse.Ptr: `3600.0`, `7.5`, so the type parameter is float64, not int. */ - function goFloat(n: number): string { - const s = goNum(n); - return /^-?\d+$/.test(s) ? `${s}.0` : s; - } - /** The exported constant of an option value: `youtube` → `ModeYouTube`, `never` → `SplitAndNever`. */ - function goConst(prefix: string, v: unknown): string { - const name = String(v) === "youtube" ? "YouTube" : variant(v); - return `trackparse.${prefix}${name}`; - } - /** A struct literal as gofmt writes it: one line for one field, else one aligned field per line. */ - function goStruct(type: string, fields: [string, string][], indent: string): string { - if (fields.length === 0) return `trackparse.${type}{}`; - if (fields.length === 1) return `trackparse.${type}{${fields[0][0]}: ${fields[0][1]}}`; - const w = Math.max(...fields.map(([k]) => k.length)); - return `trackparse.${type}{\n${fields.map(([k, v]) => `${indent}\t${`${k}:`.padEnd(w + 2)}${v},`).join("\n")}\n${indent}}`; - } - /** A Go program around `body` (lines, one tab of indentation added). */ - function goMain(body: string[], extra: string[] = []): string { - const std = ['"fmt"', ...extra].sort(); - return `package main\n\nimport (\n${std.map((x) => `\t${x}`).join("\n")}\n\n\t"github.com/4matic/trackparse/go"\n)\n\nfunc main() {\n${body.map((l) => (l ? `\t${l}` : "")).join("\n")}\n}`; + /** Under a code panel: each function and type the snippet uses, linked to its API docs. */ + function apiHtml(snippet: Snippet): string { + const where = lang === "rs" ? "docs.rs" : lang === "go" ? "pkg.go.dev" : "the reference"; + const links = snippet.api + .map((name) => [name, apiUrl(lang, name, base)] as const) + .filter(([, url]) => url) + .map(([name, url]) => `${escapeHtml(name)}`); + return links.length ? `API docs:${links.join("")}` : ""; } function options(): ParseOptions { @@ -902,85 +855,6 @@ const listExamples: { label: string; title: string; text: string }[] = [ return o; } - function code(s: string, o: ParseOptions, f: Record): string { - const q = jsStr; - if (lang === "js") { - // JS literal: unquoted keys, spaces after commas and colons. - const js = (v: unknown): string => - Array.isArray(v) - ? `[${v.map(js).join(", ")}]` - : v && typeof v === "object" - ? `{ ${Object.entries(v).map(([k, x]) => `${k}: ${js(x)}`).join(", ")} }` - : typeof v === "string" - ? jsStr(v) - : JSON.stringify(v); - const opts = Object.keys(o).length ? `, ${js(o)}` : ""; - const fopts = Object.keys(f).length ? `, ${js(f)}` : ""; - return `import { parse, format } from "trackparse";\n\nconst track = parse(${q(s)}${opts});\nformat(track${fopts});`; - } - if (lang === "rs") { - // A whole program: options are builders, and the `_with` functions take them by reference. - const names: string[] = []; - const popts: string[] = []; - if (o.mode) popts.push(`.mode(ModeOption::${variant(o.mode)})`); - if (o.knownArtists) popts.push(`.known_artists([${o.knownArtists.map(rsStr).join(", ")}])`); - if (o.uploader) popts.push(`.uploader(${rsStr(o.uploader)})`); - if (o.splitAnd) popts.push(`.split_and(SplitAnd::${variant(o.splitAnd)})`); - if (o.mode) names.push("ModeOption"); - if (o.splitAnd) names.push("SplitAnd"); - const fopts: string[] = []; - if (f.feat) fopts.push(`.feat(FeatPlacement::${variant(f.feat)})`); - if (f.joiners) fopts.push(`.joiners(JoinerStyle::${variant(f.joiners)})`); - if (f.versions) fopts.push(`.versions(VersionsOption::${variant(f.versions)})`); - if (f.feat) names.push("FeatPlacement"); - if (f.joiners) names.push("JoinerStyle"); - if (f.versions) names.push("VersionsOption"); - const body: string[] = []; - if (popts.length) { - names.push("parse_with", "ParseOptions"); - body.push(rsChain("let options = ", "ParseOptions::new()", popts), rsCall("let track = ", "parse_with", [rsStr(s), "&options"])); - } else { - names.push("parse"); - body.push(`let track = parse(${rsStr(s)});`); - } - if (fopts.length) { - names.push("format_track_with", "FormatOptions"); - body.push(rsChain("let format = ", "FormatOptions::new()", fopts), 'println!("{}", format_track_with(&track, &format));'); - } else { - names.push("format_track"); - body.push('println!("{}", format_track(&track));'); - } - return `${rsUse("trackparse", names)}\n\nfn main() {\n${body.map((l) => ` ${l}`).join("\n")}\n}`; - } - if (lang === "go") { - // A whole program: options are structs whose zero value means the default. - const popts: [string, string][] = []; - if (o.mode) popts.push(["Mode", goConst("Mode", o.mode)]); - if (o.uploader) popts.push(["Uploader", goStr(o.uploader)]); - if (o.knownArtists) popts.push(["KnownArtists", `[]string{${o.knownArtists.map(goStr).join(", ")}}`]); - if (o.splitAnd) popts.push(["SplitAnd", goConst("SplitAnd", o.splitAnd)]); - const fopts: [string, string][] = []; - if (f.feat) fopts.push(["Feat", goConst("Feat", f.feat)]); - if (f.joiners) fopts.push(["Joiners", goConst("Joiners", f.joiners)]); - if (f.versions) fopts.push(["Versions", goConst("Versions", f.versions)]); - const body = [ - popts.length - ? `track := trackparse.ParseWith(${goStr(s)}, ${goStruct("ParseOptions", popts, "\t")})` - : `track := trackparse.Parse(${goStr(s)})`, - fopts.length - ? `fmt.Println(trackparse.FormatWith(track, ${goStruct("FormatOptions", fopts, "\t")}))` - : "fmt.Println(trackparse.Format(track))", - ]; - return goMain(body); - } - const snake = (k: string) => k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`); - const py = (v: unknown): string => - Array.isArray(v) ? `[${v.map(py).join(", ")}]` : typeof v === "boolean" ? (v ? "True" : "False") : typeof v === "string" ? jsStr(v) : JSON.stringify(v); - const kw = (obj: Record) => - Object.entries(obj).map(([k, v]) => `, ${snake(k)}=${py(v)}`).join(""); - return `from trackparse import format_track, parse\n\ntrack = parse(${q(s)}${kw(o as Record)})\nformat_track(track${kw(f)})`; - } - function renderTrack() { const s = input.value; const o = options(); @@ -996,7 +870,9 @@ const listExamples: { label: string; title: string; text: string }[] = [ if (joiners.value !== "original") f.joiners = joiners.value; if (versions.value !== "all") f.versions = versions.value; $("pg-formatted").textContent = format(track, f) || "–"; - $("pg-code").innerHTML = codeHtml(code(s, o, f), lang); + const snippet = trackCode(lang, s, o, f); + $("pg-code").innerHTML = codeHtml(snippet.src, lang); + $("pg-api").innerHTML = apiHtml(snippet); for (const b of document.querySelectorAll("#panel-track [data-example]")) { b.setAttribute("aria-pressed", String(b.dataset.example === s)); } @@ -1091,14 +967,20 @@ const listExamples: { label: string; title: string; text: string }[] = [ function row(e: TracklistEntry, warn: boolean): string { const t = e.track; - const artists = t ? t.artists.map((a) => (a.role !== "primary" ? `${escapeHtml(a.name)} ${chip(a.role, roleKind(a))}` : escapeHtml(a.name))).join(", ") : ""; + const artists = t + ? t.artists + .map((a) => (a.role !== "primary" ? `${escapeHtml(a.name)} ${chip(a.role, roleKind(a), `The ${a.role} role`, `${base}/${GUIDE.role[a.role]}`)}` : escapeHtml(a.name))) + .join(", ") + : ""; const title = t ? escapeHtml(t.title) : `${escapeHtml(e.raw.trim())}`; - const vers = t ? t.versions.map((v) => chip(v.artists[0] ? `${v.type} · ${v.artists[0].name}` : v.type, "version")).join(" ") : ""; - const pos = t?.position ? `${chip(`#${t.position.number}`, "position")} ` : ""; + const vers = t + ? t.versions.map((v) => chip(v.artists[0] ? `${v.type} · ${v.artists[0].name}` : v.type, "version", "The version types", `${base}/${GUIDE.versionType}`)).join(" ") + : ""; + const pos = t?.position ? `${chip(`#${t.position.number}`, "position", "Track numbers in a tracklist", `${base}/guides/tracklists/#bare-track-numbers`)} ` : ""; // R13.13: a `w/` line plays over the previous track. - const layered = e.layered ? `${chip("w/", "layered", "Layered: played over the previous track")} ` : ""; + const layered = e.layered ? `${chip("w/", "layered", "Layered: played over the previous track", `${base}/guides/tracklists/#layered-tracks`)} ` : ""; const cls = [warn ? "is-warn" : "", changed.has(e.line) ? "is-changed" : ""].join(" ").trim(); - return `${e.line}${e.kind}${e.time ? escapeHtml(e.time.raw) : ""}${layered}${pos}${artists}${title}${vers}`; + return `${e.line}${e.kind}${e.time ? escapeHtml(e.time.raw) : ""}${layered}${pos}${artists}${title}${vers}`; } function plural(n: number, word: string): string { @@ -1138,120 +1020,6 @@ const listExamples: { label: string; title: string; text: string }[] = [ type View = "table" | "json" | "code"; let view: View = "table"; - /** JS / Python / Rust / Go for the current text, options and edit inputs. */ - function listCode(text: string, list: Tracklist): string { - const q = jsStr; - const lines = text.split("\n"); - // Lists without CR line endings are written one line per row; anything else as one string. - const literal = (indent: string, open: string, close: string) => - text.includes("\r") || lines.length < 2 - ? q(text) - : `${open}\n${lines.map((l) => `${indent}${q(l)},`).join("\n")}\n${close}`; - const { audioSeconds, knownArtists } = listOptions(); - const hasOptions = audioSeconds !== undefined || knownArtists !== undefined; - const seconds = shiftSeconds(); - const from = shiftFrom(); - const fix = list.warnings.find((w) => w.suggestion)?.suggestion; - if (lang === "js") { - const jsOpts: string[] = []; - if (audioSeconds !== undefined) jsOpts.push(`audioSeconds: ${audioSeconds}`); - if (knownArtists) jsOpts.push(`knownArtists: [${knownArtists.map(q).join(", ")}]`); - const out = [ - 'import { applyEdits, parseTracklist } from "trackparse/tracklist";', - "", - `const text = ${literal(" ", "[", '].join("\\n")')};`, - "", - `const list = parseTracklist(text${hasOptions ? `, { ${jsOpts.join(", ")} }` : ""});`, - "list.entries; // one entry per line", - "list.warnings; // the checks, with line numbers", - "", - `applyEdits(text, [{ op: "shift", seconds: ${seconds}, from: ${from} }]);`, - 'applyEdits(text, [{ op: "sort-by-time" }]);', - ]; - if (fix) out.push(`applyEdits(text, [{ op: "set-time", line: ${fix.line}, seconds: ${fix.seconds} }]); // the suggested fix`); - return out.join("\n"); - } - if (lang === "rs") { - // A whole program. A list without CR line endings is an array of lines joined into a String. - const joined = !(text.includes("\r") || lines.length < 2); - const t = joined ? "&text" : "text"; - const names = ["apply_edits", "Edit", hasOptions ? "parse_tracklist_with" : "parse_tracklist"]; - if (hasOptions) names.push("TracklistOptions"); - const rsOpts: string[] = []; - if (audioSeconds !== undefined) rsOpts.push(`.audio_seconds(${rsNum(audioSeconds)})`); - if (knownArtists) rsOpts.push(`.known_artists([${knownArtists.map(rsStr).join(", ")}])`); - // rustfmt keeps an array on one line when it is at most 60 columns wide. - const items = lines.map(rsStr); - const array = `[${items.join(", ")}]`; - const body = [ - !joined - ? `let text = ${rsStr(text)};` - : rsWidth(array) <= 60 - ? `let text = ${array}.join("\\n");` - : `let text = [\n${items.map((l) => ` ${l},`).join("\n")}\n ]\n .join("\\n");`, - "", - hasOptions - ? `${rsChain("let options = ", "TracklistOptions::new()", rsOpts)}\n let list = parse_tracklist_with(${t}, &options);` - : `let list = parse_tracklist(${t});`, - 'println!("{:#?}", list.entries); // one entry per line', - 'println!("{:#?}", list.warnings); // the checks, with line numbers', - "", - `let shifted = apply_edits(${t}, &[Edit::shift_from(${rsNum(seconds)}, ${from})]);`, - `let sorted = apply_edits(${t}, &[Edit::sort_by_time()]);`, - ]; - if (fix) body.push(`let fixed = apply_edits(${t}, &[Edit::set_time(${fix.line}, ${rsNum(fix.seconds)})]); // the suggested fix`); - body.push(`println!("{}\\n\\n{}${fix ? "\\n\\n{}" : ""}", shifted.text, sorted.text${fix ? ", fixed.text" : ""});`); - return `${rsUse("trackparse::tracklist", names)}\n\nfn main() {\n${body.map((l) => (l ? ` ${l}` : "")).join("\n")}\n}`; - } - if (lang === "go") { - // A whole program. A list without CR line endings is a slice of lines joined with "\n". - const joined = !(text.includes("\r") || lines.length < 2); - const opts: [string, string][] = []; - // AudioSeconds is a *float64: nil is unknown, a pointer to 0 an audio of length 0. - if (audioSeconds !== undefined) opts.push(["AudioSeconds", `trackparse.Ptr(${goFloat(audioSeconds)})`]); - if (knownArtists) opts.push(["KnownArtists", `[]string{${knownArtists.map(goStr).join(", ")}}`]); - const nums = [audioSeconds ?? 0, seconds, fix?.seconds ?? 0]; - const extra = ['"encoding/json"', '"os"']; - if (joined) extra.push('"strings"'); - if (nums.some((n) => !Number.isFinite(n))) extra.push('"math"'); - const body = [ - joined ? `text := strings.Join([]string{\n${lines.map((l) => `\t${goStr(l)},`).join("\n")}\n}, "\\n")` : `text := ${goStr(text)}`, - "", - hasOptions - ? `list := trackparse.ParseTracklistWith(text, ${goStruct("TracklistOptions", opts, "")})` - : "list := trackparse.ParseTracklist(text)", - "enc := json.NewEncoder(os.Stdout)", - 'enc.SetIndent("", " ")', - "enc.SetEscapeHTML(false) // & < > as written, as JSON.stringify does", - "enc.Encode(list.Entries) // one entry per line", - "enc.Encode(list.Warnings) // the checks, with line numbers", - "", - `shifted := trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.ShiftFrom(${goNum(seconds)}, ${from})})`, - "sorted := trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.SortByTime()})", - ]; - if (fix) body.push(`fixed := trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.SetTime(${fix.line}, ${goNum(fix.seconds)})}) // the suggested fix`); - body.push(`fmt.Print(shifted.Text, "\\n\\n", sorted.Text${fix ? ', "\\n\\n", fixed.Text' : ""}, "\\n")`); - return goMain(body.flatMap((l) => l.split("\n")), extra); - } - const pyOpts = - (audioSeconds !== undefined ? `, audio_seconds=${audioSeconds}` : "") + - (knownArtists ? `, known_artists=[${knownArtists.map(q).join(", ")}]` : ""); - const out = [ - "from trackparse.tracklist import apply_edits, parse_tracklist", - "", - `text = ${literal(" ", '"\\n".join([', "])")}`, - "", - `tl = parse_tracklist(text${pyOpts})`, - "tl.entries # one entry per line", - "tl.warnings # the checks, with line numbers", - "", - `apply_edits(text, [{"op": "shift", "seconds": ${seconds}, "from": ${from}}])`, - 'apply_edits(text, [{"op": "sort-by-time"}])', - ]; - if (fix) out.push(`apply_edits(text, [{"op": "set-time", "line": ${fix.line}, "seconds": ${fix.seconds}}]) # the suggested fix`); - return out.join("\n"); - } - function showView() { for (const b of document.querySelectorAll("[data-view]")) b.setAttribute("aria-pressed", String(b.dataset.view === view)); $("tl-tablebox").hidden = view !== "table"; @@ -1259,6 +1027,7 @@ const listExamples: { label: string; title: string; text: string }[] = [ $("tl-code").hidden = view !== "code"; $("tl-lang").hidden = view !== "code"; $("tl-install").hidden = view !== "code"; + $("tl-api").hidden = view !== "code"; $("tl-copy-out").hidden = view === "table"; } @@ -1271,7 +1040,18 @@ const listExamples: { label: string; title: string; text: string }[] = [ $("tl-rows").innerHTML = list.entries.map((e) => row(e, warned.has(e.line))).join(""); // Only the visible view is rendered: JSON of a long list is large. if (view === "json") $("tl-json").innerHTML = jsonHtml(list); - if (view === "code") $("tl-code").innerHTML = codeHtml(listCode(text, list), lang); + if (view === "code") { + const fix = list.warnings.find((w) => w.suggestion)?.suggestion; + const snippet = listCode(lang, { + text, + ...listOptions(), + seconds: shiftSeconds(), + from: shiftFrom(), + fix: fix && { line: fix.line, seconds: fix.seconds }, + }); + $("tl-code").innerHTML = codeHtml(snippet.src, lang); + $("tl-api").innerHTML = apiHtml(snippet); + } for (const b of document.querySelectorAll("[data-list-example]")) b.setAttribute("aria-pressed", String(b.dataset.listExample === text)); const st = list.stats; diff --git a/site/src/components/Stats.astro b/site/src/components/Stats.astro index fa7b3bc..c784f84 100644 --- a/site/src/components/Stats.astro +++ b/site/src/components/Stats.astro @@ -4,7 +4,7 @@ const stats = [ { n: "13,130", label: "shared fixtures, 100% passing in all four ports" }, { n: "0", label: "runtime dependencies in JavaScript, Python and Go, one in Rust" }, { n: "27", label: "version types, remix to nightcore" }, - { n: "0", label: "differences between JS, Python, Rust and Go output" }, + { n: "0", label: "differences between JS, Python, Rust and Go output on the fixtures" }, ]; --- diff --git a/site/src/content/docs/index.mdx b/site/src/content/docs/index.mdx index 3212002..692cf5f 100644 --- a/site/src/content/docs/index.mdx +++ b/site/src/content/docs/index.mdx @@ -43,12 +43,12 @@ in the title, word for word. Skrillex & Diplo x Justin Bieber is three artists; with knownArtists, Chase & Status stays one." }, - { title: "27 version types", body: "Remix, VIP, bootleg, extended, radio edit, live, remaster, sped up, slowed and the rest, each with its remixers, modifiers and year." }, - { title: "Noise, labeled", body: "[Official Video], [HD], - YouTube and [NCS Release] leave the title but land in junk with a kind, instead of disappearing." }, - { title: "Whole tracklists", body: "Paste the tracklist of a mix: every line is parsed, times are checked, and an out-of-order time often comes with the fix. Edits rewrite only the lines you name." }, - { title: "One spec, four languages", body: "The npm package, the PyPI package, the Rust crate and the Go module pass the same 13,130 fixtures and return byte-identical JSON on every fixture input. The ports page has the one known Unicode difference." }, - { title: "Small and total", body: "The JavaScript package is about 18 kB gzipped. It, the Python package and the Go module have no dependencies; the Rust crate has one, unicode-normalization. The scanners are written by hand and no regex backtracks, so a 10,000-code-point input takes at most tens of milliseconds in JavaScript, Rust and Go, and well under a second in Python. No string makes it throw or panic, and bad options fall back to defaults." }, + { title: "Credits with roles", href: "/trackparse/guides/artists/", body: "Primary artists, features, producers and remixers, each with the joiner it was written with. Skrillex & Diplo x Justin Bieber is three artists; with knownArtists, Chase & Status stays one." }, + { title: "27 version types", href: "/trackparse/guides/versions/#the-27-types", body: "Remix, VIP, bootleg, extended, radio edit, live, remaster, sped up, slowed and the rest, each with its remixers, modifiers and year." }, + { title: "Noise, labeled", href: "/trackparse/guides/junk-and-flags/#junk", body: "[Official Video], [HD], - YouTube and [NCS Release] leave the title but land in junk with a kind, instead of disappearing." }, + { title: "Whole tracklists", href: "/trackparse/guides/tracklists/", body: "Paste the tracklist of a mix: every line is parsed, times are checked, and an out-of-order time often comes with the fix. Edits rewrite only the lines you name." }, + { title: "One spec, four languages", href: "/trackparse/project/ports/", body: "The npm package, the PyPI package, the Rust crate and the Go module pass the same 13,130 fixtures and return byte-identical JSON on every fixture input. The ports page has the one known Unicode difference." }, + { title: "Small and total", href: "/trackparse/project/how-it-works/", body: "The JavaScript package is about 18 kB gzipped. It, the Python package and the Go module have no dependencies; the Rust crate has one, unicode-normalization. The scanners are written by hand and no regex backtracks, so a 10,000-code-point input takes at most tens of milliseconds in JavaScript, Rust and Go, and well under a second in Python. No string makes it throw or panic, and bad options fall back to defaults." }, ]} /> diff --git a/site/src/lib/codegen.ts b/site/src/lib/codegen.ts new file mode 100644 index 0000000..e1343fd --- /dev/null +++ b/site/src/lib/codegen.ts @@ -0,0 +1,601 @@ +// The code panels of the playground: the same calls in JavaScript, Python, Rust and Go, laid out +// as each language's formatter prints them (Biome at 100 columns, Ruff at 100 columns, rustfmt +// and gofmt), plus a link to the API docs of every function and type a snippet uses. +// Pure functions: the playground passes in what its controls hold. + +import type { Lang } from "./lang"; + +/** A generated program or snippet, and the API names it uses, in order of first use. */ +export interface Snippet { + src: string; + api: string[]; +} + +/** The parse options the playground can set. */ +export interface TrackOptions { + mode?: string; + splitAnd?: string; + knownArtists?: string[]; + uploader?: string; +} + +/** The format options the playground can set (only the ones that differ from the default). */ +export interface FormatChoice { + feat?: string; + joiners?: string; + versions?: string; +} + +/** What the tracklist panel shows in code: the text, its options and the edit inputs. */ +export interface ListInput { + text: string; + audioSeconds?: number; + knownArtists?: string[]; + seconds: number; + from: number; + /** The suggested fix of the first warning that has one. */ + fix?: { line: number; seconds: number }; +} + +const WIDTH = 100; + +// ---- shared ------------------------------------------------------------------------------------- + +/** Control, invisible and bidi characters, written as escapes in the generated literals. */ +function invisible(cp: number): boolean { + return ( + cp < 0x20 || + (cp >= 0x7f && cp <= 0x9f) || + cp === 0xad || + cp === 0x34f || + cp === 0x61c || + cp === 0x180e || + (cp >= 0x200b && cp <= 0x200f) || + (cp >= 0x2028 && cp <= 0x202e) || + (cp >= 0x2060 && cp <= 0x206f) || + cp === 0xfeff || + (cp >= 0xfff9 && cp <= 0xfffb) + ); +} + +/** Columns a line takes, as the formatters count them: wide characters (emoji, CJK) count two. */ +export function cols(s: string): number { + let w = 0; + for (const ch of s) { + const cp = ch.codePointAt(0) ?? 0; + const wide = + (cp >= 0x1100 && cp <= 0x115f) || + (cp >= 0x2e80 && cp <= 0xa4cf) || + (cp >= 0xac00 && cp <= 0xd7a3) || + (cp >= 0xf900 && cp <= 0xfaff) || + (cp >= 0xfe30 && cp <= 0xfe4f) || + (cp >= 0xff00 && cp <= 0xff60) || + (cp >= 0xffe0 && cp <= 0xffe6) || + (cp >= 0x1f300 && cp <= 0x1faff) || + cp >= 0x20000; + w += wide ? 2 : 1; + } + return w; +} +/** The widest line of a block of text. */ +const widest = (s: string) => Math.max(...s.split("\n").map(cols)); + +/** + * A JavaScript or Python string literal. Double quotes, unless the string holds more double + * quotes than single ones (Biome, Prettier and Ruff all choose that way). Control, invisible + * and bidi characters, and lone surrogates, are written as `\uXXXX`. + */ +export function strLit(s: string): string { + let dq = 0; + let sq = 0; + for (const ch of s) { + if (ch === '"') dq++; + else if (ch === "'") sq++; + } + const quote = dq > sq ? "'" : '"'; + let out = quote; + for (const ch of s) { + const cp = ch.codePointAt(0) ?? 0; + if (ch === quote || ch === "\\") out += `\\${ch}`; + else if (ch === "\n") out += "\\n"; + else if (ch === "\r") out += "\\r"; + else if (ch === "\t") out += "\\t"; + else if (invisible(cp) || (cp >= 0xd800 && cp <= 0xdfff)) out += `\\u${cp.toString(16).padStart(4, "0")}`; + else out += ch; + } + return out + quote; +} + +/** A number as JavaScript and Python print it in source: `1e21`, not `1e+21`. */ +const numLit = (n: number) => String(n).replace("e+", "e"); + +// ---- JavaScript --------------------------------------------------------------------------------- + +/** A variable name in generated code, where a value would be written as a literal. */ +const IDENT = Symbol("ident"); +interface Ident { + [IDENT]: string; +} +const ident = (name: string): Ident => ({ [IDENT]: name }); +const isIdent = (v: Value): v is Ident => typeof v === "object" && IDENT in v; +type Value = string | number | boolean | Ident | Value[] | { [key: string]: Value }; +const composite = (v: Value): v is Value[] | { [key: string]: Value } => typeof v === "object" && !isIdent(v); + +function jsFlat(v: Value): string { + if (isIdent(v)) return v[IDENT]; + if (Array.isArray(v)) return `[${v.map(jsFlat).join(", ")}]`; + if (typeof v === "object") { + const e = Object.entries(v); + return e.length ? `{ ${e.map(([k, x]) => `${k}: ${jsFlat(x)}`).join(", ")} }` : "{}"; + } + return typeof v === "string" ? strLit(v) : typeof v === "number" ? numLit(v) : String(v); +} + +/** `v` after `before` on a line that ends with `after`: flat if it fits, else one item per line. */ +function jsLay(v: Value, indent: string, before: string, after: string): string { + const flat = jsFlat(v); + if (!composite(v) || cols(before + flat + after) <= WIDTH) return flat; + const inner = `${indent} `; + if (Array.isArray(v)) { + if (!v.length) return flat; + return `[\n${v.map((x) => `${inner}${jsLay(x, inner, inner, ",")},`).join("\n")}\n${indent}]`; + } + const e = Object.entries(v); + if (!e.length) return flat; + return `{\n${e.map(([k, x]) => `${inner}${k}: ${jsLay(x, inner, `${inner}${k}: `, ",")},`).join("\n")}\n${indent}}`; +} + +/** `lhs fn(args);` as Biome prints it: flat, else the last object hugged, else one argument per line. */ +function jsCall(lhs: string, fn: string, args: Value[]): string { + const flat = `${lhs}${fn}(${args.map(jsFlat).join(", ")});`; + if (cols(flat) <= WIDTH) return flat; + const last = args[args.length - 1]; + const head = `${lhs}${fn}(${args.slice(0, -1).map((a) => `${jsFlat(a)}, `).join("")}`; + if (composite(last) && cols(`${head}{`) <= WIDTH) return `${head}${jsLay(last, "", head, ");")});`; + return `${lhs}${fn}(\n${args.map((a) => ` ${jsLay(a, " ", " ", ",")},`).join("\n")}\n);`; +} + +// ---- Python ------------------------------------------------------------------------------------- + +function pyFlat(v: Value): string { + if (isIdent(v)) return v[IDENT]; + if (Array.isArray(v)) return `[${v.map(pyFlat).join(", ")}]`; + if (typeof v === "object") return `{${Object.entries(v).map(([k, x]) => `${strLit(k)}: ${pyFlat(x)}`).join(", ")}}`; + if (typeof v === "boolean") return v ? "True" : "False"; + return typeof v === "string" ? strLit(v) : numLit(v); +} + +/** A list after `before` on a line that ends with `after`: flat if it fits, else one item per line. */ +function pyLay(v: Value, indent: string, before: string, after: string): string { + const flat = pyFlat(v); + if (!Array.isArray(v) || !v.length || cols(before + flat + after) <= WIDTH) return flat; + const inner = `${indent} `; + return `[\n${v.map((x) => `${inner}${pyLay(x, inner, inner, ",")},`).join("\n")}\n${indent}]`; +} + +/** + * `lhs fn(args)` as Ruff prints it: flat; else the arguments together on one indented line + * (or a lone argument that can't be split); else one argument per line with a trailing comma. + */ +function pyCall(lhs: string, fn: string, args: [string | null, Value][]): string { + const parts = args.map(([k, v]) => `${k ? `${k}=` : ""}${pyFlat(v)}`); + const flat = `${lhs}${fn}(${parts.join(", ")})`; + if (cols(flat) <= WIDTH) return flat; + const lone = args.length === 1 && !composite(args[0][1]); + if (lone || cols(` ${parts.join(", ")}`) <= WIDTH) return `${lhs}${fn}(\n ${parts.join(", ")}\n)`; + const lines = args.map(([k, v]) => { + const pre = ` ${k ? `${k}=` : ""}`; + return `${pre}${pyLay(v, " ", pre, ",")},`; + }); + return `${lhs}${fn}(\n${lines.join("\n")}\n)`; +} + +// ---- Rust --------------------------------------------------------------------------------------- + +/** A Rust string literal. Control, invisible and bidi characters are written as `\u{…}`. */ +export function rsStr(s: string): string { + let out = '"'; + for (const ch of s) { + const cp = ch.codePointAt(0) ?? 0; + if (ch === '"' || ch === "\\") out += `\\${ch}`; + else if (ch === "\n") out += "\\n"; + else if (ch === "\r") out += "\\r"; + else if (ch === "\t") out += "\\t"; + // A lone surrogate cannot be in a Rust string: U+FFFD, as a lossy conversion would give. + else if (cp >= 0xd800 && cp <= 0xdfff) out += "\\u{fffd}"; + else if (invisible(cp)) out += `\\u{${cp.toString(16)}}`; + else out += ch; + } + return `${out}"`; +} +/** An `f64` literal: `45.0`, `7.5`, `1e21`. */ +function rsNum(n: number): string { + if (!Number.isFinite(n)) return Number.isNaN(n) ? "f64::NAN" : n > 0 ? "f64::INFINITY" : "f64::NEG_INFINITY"; + const s = String(n).replace("e+", "e"); + return /[.e]/.test(s) ? s : `${s}.0`; +} +/** `youtube` → `Youtube`: the enum variant of an option value. */ +const variant = (v: string) => v.charAt(0).toUpperCase() + v.slice(1); + +/** `use` items in rustfmt order: functions first, then types. */ +function rsUse(path: string, names: string[]): string { + const lower = (n: string) => n[0] === n[0].toLowerCase(); + const sorted = [...names.filter(lower).sort(), ...names.filter((n) => !lower(n)).sort()]; + const line = `use ${path}::${sorted.length === 1 ? sorted[0] : `{${sorted.join(", ")}}`};`; + if (line.length <= WIDTH) return line; + // Too long: the names fill lines of at most 100 columns inside braces. + const rows: string[] = []; + for (const n of sorted) { + const last = rows.length - 1; + if (last >= 0 && `${rows[last]} ${n},`.length <= WIDTH) rows[last] += ` ${n},`; + else rows.push(` ${n},`); + } + return `use ${path}::{\n${rows.join("\n")}\n};`; +} + +/** + * An array argument, `.known_artists([…])` at `indent`: on one line up to 60 columns + * (rustfmt's array width), else short items (10 columns at most) fill lines and longer ones + * get a line each. + */ +function rsArrayCall(method: string, items: string[], indent: string): string { + const flat = `[${items.join(", ")}]`; + if (cols(flat) <= 60) return `${method}(${flat})`; + const inner = `${indent} `; + if (items.every((x) => cols(x) <= 10)) { + const rows: string[] = []; + for (const x of items) { + const last = rows.length - 1; + if (last >= 0 && cols(`${rows[last]} ${x},`) <= WIDTH) rows[last] += ` ${x},`; + else rows.push(`${inner}${x},`); + } + return `${method}([\n${rows.join("\n")}\n${indent}])`; + } + return `${method}([\n${items.map((x) => `${inner}${x},`).join("\n")}\n${indent}])`; +} + +/** + * `let x = Root::new().a().b();`: on one line when the chain is at most 60 columns and every call + * is on one line, else one call per line. `calls` render each call at a given indent. + */ +function rsChain(lhs: string, root: string, calls: ((indent: string) => string)[], indent = " "): string { + const one = calls.map((c) => c(indent)); + const chain = root + one.join(""); + if (!chain.includes("\n") && (calls.length < 2 || cols(chain) <= 60) && cols(`${indent}${lhs}${chain};`) <= WIDTH) + return `${lhs}${chain};`; + if (calls.length === 1) return `${lhs}${chain};`; + // The last call may run over several lines (a long array) when the chain up to its first line + // is on one line and at most 60 columns. + const init = one.slice(0, -1).join(""); + const last = one[one.length - 1]; + if (!init.includes("\n") && last.includes("\n") && cols(`${root}${init}${last.split("\n")[0]}`) <= 60) + return `${lhs}${chain};`; + return `${lhs}${root}\n${calls.map((c) => `${indent} ${c(`${indent} `)}`).join("\n")};`; +} + +/** `let x = f(a, b);`: arguments wider than 60 columns go one per line, if each then fits. */ +function rsCall(lhs: string, fn: string, args: string[], indent = " "): string { + const flat = `${lhs}${fn}(${args.join(", ")});`; + const fits = args.every((a) => indent.length + 4 + cols(a) + 1 <= WIDTH); + // One string argument stays on the line as long as the line fits. + const narrow = args.length === 1 ? cols(indent + flat) <= WIDTH : cols(args.join(", ")) <= 60; + if (narrow || !fits) return flat; + return `${lhs}${fn}(\n${args.map((a) => `${indent} ${a},`).join("\n")}\n${indent});`; +} + +// ---- Go ----------------------------------------------------------------------------------------- + +/** A Go string literal. Control, invisible and bidi characters are written as escapes. */ +export function goStr(s: string): string { + let out = '"'; + for (const ch of s) { + const cp = ch.codePointAt(0) ?? 0; + if (ch === '"' || ch === "\\") out += `\\${ch}`; + else if (ch === "\n") out += "\\n"; + else if (ch === "\r") out += "\\r"; + else if (ch === "\t") out += "\\t"; + // A Go string cannot spell a lone surrogate: U+FFFD, as the module reads invalid UTF-8. + else if (cp >= 0xd800 && cp <= 0xdfff) out += "\\ufffd"; + else if (invisible(cp)) out += `\\u${cp.toString(16).padStart(4, "0")}`; + else out += ch; + } + return `${out}"`; +} +/** A float64 constant: `45`, `7.5`, `1e+21`; `math.Inf(1)` and `math.NaN()` need the math import. */ +function goNum(n: number): string { + if (!Number.isFinite(n)) return Number.isNaN(n) ? "math.NaN()" : n > 0 ? "math.Inf(1)" : "math.Inf(-1)"; + return String(n); +} +/** A float64 value for trackparse.Ptr: `3600.0`, `7.5`, so the type parameter is float64, not int. */ +function goFloat(n: number): string { + const s = goNum(n); + return /^-?\d+$/.test(s) ? `${s}.0` : s; +} +/** The exported constant of an option value: `youtube` → `ModeYouTube`, `never` → `SplitAndNever`. */ +function goConst(prefix: string, v: string): string { + return `trackparse.${prefix}${v === "youtube" ? "YouTube" : variant(v)}`; +} +/** A struct literal as gofmt writes it: one line for one field, else one aligned field per line. */ +function goStruct(type: string, fields: [string, string][], indent: string): string { + if (fields.length === 0) return `trackparse.${type}{}`; + if (fields.length === 1) return `trackparse.${type}{${fields[0][0]}: ${fields[0][1]}}`; + const w = Math.max(...fields.map(([k]) => k.length)); + return `trackparse.${type}{\n${fields.map(([k, v]) => `${indent}\t${`${k}:`.padEnd(w + 2)}${v},`).join("\n")}\n${indent}}`; +} +/** + * A Go program around `body` (lines, one tab of indentation added). The imports are in two + * groups, as goimports writes them: the standard library, a blank line, then the module. + */ +function goMain(body: string[], std: string[]): string { + const mod = '"github.com/4matic/trackparse/go"'; + const groups = [[...new Set(std)].sort(), [mod]].filter((g) => g.length); + const imports = + std.length === 0 ? `import ${mod}` : `import (\n${groups.map((g) => g.map((x) => `\t${x}`).join("\n")).join("\n\n")}\n)`; + return `package main\n\n${imports}\n\nfunc main() {\n${body.map((l) => (l ? `\t${l}` : "")).join("\n")}\n}`; +} + +// ---- one track ---------------------------------------------------------------------------------- + +/** `parse` and `format` with the playground's options, in one language. */ +export function trackCode(lang: Lang, s: string, o: TrackOptions, f: FormatChoice): Snippet { + if (lang === "js") { + const po: { [k: string]: Value } = {}; + if (o.mode) po.mode = o.mode; + if (o.splitAnd) po.splitAnd = o.splitAnd; + if (o.knownArtists) po.knownArtists = o.knownArtists; + if (o.uploader) po.uploader = o.uploader; + const fo = { ...f } as { [k: string]: Value }; + const src = [ + 'import { format, parse } from "trackparse";', + "", + jsCall("const track = ", "parse", Object.keys(po).length ? [s, po] : [s]), + jsCall("", "format", Object.keys(fo).length ? [ident("track"), fo] : [ident("track")]), + ].join("\n"); + return { src, api: ["parse", "format"] }; + } + if (lang === "py") { + const args: [string | null, Value][] = [[null, s]]; + if (o.mode) args.push(["mode", o.mode]); + if (o.splitAnd) args.push(["split_and", o.splitAnd]); + if (o.knownArtists) args.push(["known_artists", o.knownArtists]); + if (o.uploader) args.push(["uploader", o.uploader]); + const fargs = Object.entries(f).map(([k, v]) => `, ${k}=${strLit(String(v))}`).join(""); + const src = ["from trackparse import format_track, parse", "", pyCall("track = ", "parse", args), `format_track(track${fargs})`].join("\n"); + return { src, api: ["parse", "format_track"] }; + } + if (lang === "rs") { + // A whole program: options are builders, and the `_with` functions take them by reference. + const names: string[] = []; + const popts: ((indent: string) => string)[] = []; + if (o.mode) popts.push(() => `.mode(ModeOption::${variant(o.mode ?? "")})`); + if (o.knownArtists) { + const items = o.knownArtists.map(rsStr); + popts.push((indent) => rsArrayCall(".known_artists", items, indent)); + } + if (o.uploader) popts.push(() => `.uploader(${rsStr(o.uploader ?? "")})`); + if (o.splitAnd) popts.push(() => `.split_and(SplitAnd::${variant(o.splitAnd ?? "")})`); + if (o.mode) names.push("ModeOption"); + if (o.splitAnd) names.push("SplitAnd"); + const fopts: ((indent: string) => string)[] = []; + if (f.feat) fopts.push(() => `.feat(FeatPlacement::${variant(f.feat ?? "")})`); + if (f.joiners) fopts.push(() => `.joiners(JoinerStyle::${variant(f.joiners ?? "")})`); + if (f.versions) fopts.push(() => `.versions(VersionsOption::${variant(f.versions ?? "")})`); + if (f.feat) names.push("FeatPlacement"); + if (f.joiners) names.push("JoinerStyle"); + if (f.versions) names.push("VersionsOption"); + const body: string[] = []; + const api: string[] = []; + if (popts.length) { + names.push("parse_with", "ParseOptions"); + api.push("parse_with", "ParseOptions"); + body.push(rsChain("let options = ", "ParseOptions::new()", popts), rsCall("let track = ", "parse_with", [rsStr(s), "&options"])); + } else { + names.push("parse"); + api.push("parse"); + body.push(rsCall("let track = ", "parse", [rsStr(s)])); + } + if (fopts.length) { + names.push("format_track_with", "FormatOptions"); + api.push("format_track_with", "FormatOptions"); + body.push(rsChain("let format = ", "FormatOptions::new()", fopts), 'println!("{}", format_track_with(&track, &format));'); + } else { + names.push("format_track"); + api.push("format_track"); + body.push('println!("{}", format_track(&track));'); + } + // The option enums after the functions and their option types. + for (const n of ["ModeOption", "SplitAnd", "FeatPlacement", "JoinerStyle", "VersionsOption"]) if (names.includes(n)) api.push(n); + const src = `${rsUse("trackparse", names)}\n\nfn main() {\n${body.map((l) => ` ${l}`).join("\n")}\n}`; + return { src, api }; + } + // Go: a whole program. Options are structs whose zero value means the default. + const popts: [string, string][] = []; + if (o.mode) popts.push(["Mode", goConst("Mode", o.mode)]); + if (o.uploader) popts.push(["Uploader", goStr(o.uploader)]); + if (o.knownArtists) popts.push(["KnownArtists", `[]string{${o.knownArtists.map(goStr).join(", ")}}`]); + if (o.splitAnd) popts.push(["SplitAnd", goConst("SplitAnd", o.splitAnd)]); + const fopts: [string, string][] = []; + if (f.feat) fopts.push(["Feat", goConst("Feat", f.feat)]); + if (f.joiners) fopts.push(["Joiners", goConst("Joiners", f.joiners)]); + if (f.versions) fopts.push(["Versions", goConst("Versions", f.versions)]); + const body = [ + popts.length + ? `track := trackparse.ParseWith(${goStr(s)}, ${goStruct("ParseOptions", popts, "\t")})` + : `track := trackparse.Parse(${goStr(s)})`, + fopts.length + ? `fmt.Println(trackparse.FormatWith(track, ${goStruct("FormatOptions", fopts, "\t")}))` + : "fmt.Println(trackparse.Format(track))", + ]; + const api = [...(popts.length ? ["ParseWith", "ParseOptions"] : ["Parse"]), ...(fopts.length ? ["FormatWith", "FormatOptions"] : ["Format"])]; + return { src: goMain(body, ['"fmt"']), api }; +} + +// ---- tracklist ---------------------------------------------------------------------------------- + +/** `parseTracklist` and `applyEdits` for the playground's text, options and edit inputs. */ +export function listCode(lang: Lang, x: ListInput): Snippet { + const { text, audioSeconds, knownArtists, seconds, from, fix } = x; + const lines = text.split("\n"); + // Lists without CR line endings are written one line per row; anything else as one string. + const joined = !(text.includes("\r") || lines.length < 2); + const hasOptions = audioSeconds !== undefined || knownArtists !== undefined; + if (lang === "js") { + const opts: { [k: string]: Value } = {}; + if (audioSeconds !== undefined) opts.audioSeconds = audioSeconds; + if (knownArtists) opts.knownArtists = knownArtists; + const head = "const text = "; + const textLine = joined ? `${head}${jsLay(lines, "", head, '.join("\\n");')}.join("\\n");` : `${head}${strLit(text)};`; + const out = [ + 'import { applyEdits, parseTracklist } from "trackparse/tracklist";', + "", + textLine, + "", + jsCall("const list = ", "parseTracklist", hasOptions ? [ident("text"), opts] : [ident("text")]), + "list.entries; // one entry per line", + "list.warnings; // the checks, with line numbers", + "", + `applyEdits(text, [{ op: "shift", seconds: ${numLit(seconds)}, from: ${from} }]);`, + 'applyEdits(text, [{ op: "sort-by-time" }]);', + ]; + if (fix) out.push(`applyEdits(text, [{ op: "set-time", line: ${fix.line}, seconds: ${numLit(fix.seconds)} }]); // the suggested fix`); + return { src: out.join("\n"), api: ["parseTracklist", "applyEdits"] }; + } + if (lang === "py") { + const flatText = `text = "\\n".join(${pyFlat(lines)})`; + const textLines = !joined + ? [`text = ${strLit(text)}`] + : cols(flatText) <= WIDTH + ? [flatText] + : [`lines = ${pyLay(lines, "", "lines = ", "")}`, 'text = "\\n".join(lines)']; + const args: [string | null, Value][] = [[null, ident("text")]]; + if (audioSeconds !== undefined) args.push(["audio_seconds", audioSeconds]); + if (knownArtists) args.push(["known_artists", knownArtists]); + const out = [ + "from trackparse.tracklist import apply_edits, parse_tracklist", + "", + ...textLines, + "", + pyCall("tl = ", "parse_tracklist", args), + "tl.entries # one entry per line", + "tl.warnings # the checks, with line numbers", + "", + `apply_edits(text, [{"op": "shift", "seconds": ${numLit(seconds)}, "from": ${from}}])`, + 'apply_edits(text, [{"op": "sort-by-time"}])', + ]; + if (fix) out.push(`apply_edits(text, [{"op": "set-time", "line": ${fix.line}, "seconds": ${numLit(fix.seconds)}}]) # the suggested fix`); + return { src: out.join("\n"), api: ["parse_tracklist", "apply_edits"] }; + } + if (lang === "rs") { + // A whole program. A list without CR line endings is an array of lines joined into a String. + const t = joined ? "&text" : "text"; + const parseFn = hasOptions ? "parse_tracklist_with" : "parse_tracklist"; + const names = ["apply_edits", "Edit", parseFn]; + if (hasOptions) names.push("TracklistOptions"); + const rsOpts: ((indent: string) => string)[] = []; + if (audioSeconds !== undefined) rsOpts.push(() => `.audio_seconds(${rsNum(audioSeconds)})`); + if (knownArtists) { + const items = knownArtists.map(rsStr); + rsOpts.push((indent) => rsArrayCall(".known_artists", items, indent)); + } + // rustfmt keeps an array on one line when it is at most 60 columns wide. + const items = lines.map(rsStr); + const array = `[${items.join(", ")}]`; + const body = [ + !joined + ? `let text = ${rsStr(text)};` + : cols(array) <= 60 + ? `let text = ${array}.join("\\n");` + : `let text = [\n${items.map((l) => ` ${l},`).join("\n")}\n ]\n .join("\\n");`, + "", + hasOptions + ? `${rsChain("let options = ", "TracklistOptions::new()", rsOpts)}\n let list = parse_tracklist_with(${t}, &options);` + : `let list = parse_tracklist(${t});`, + 'println!("{:#?}", list.entries); // one entry per line', + 'println!("{:#?}", list.warnings); // the checks, with line numbers', + "", + `let shifted = apply_edits(${t}, &[Edit::shift_from(${rsNum(seconds)}, ${from})]);`, + `let sorted = apply_edits(${t}, &[Edit::sort_by_time()]);`, + ]; + if (fix) body.push(`let fixed = apply_edits(${t}, &[Edit::set_time(${fix.line}, ${rsNum(fix.seconds)})]); // the suggested fix`); + body.push(`println!("{}\\n\\n{}${fix ? "\\n\\n{}" : ""}", shifted.text, sorted.text${fix ? ", fixed.text" : ""});`); + const src = `${rsUse("trackparse::tracklist", names)}\n\nfn main() {\n${body.map((l) => (l ? ` ${l}` : "")).join("\n")}\n}`; + return { src, api: [parseFn, ...(hasOptions ? ["TracklistOptions"] : []), "apply_edits", "Edit"] }; + } + // Go: a whole program. A list without CR line endings is a slice of lines joined with "\n". + const opts: [string, string][] = []; + // AudioSeconds is a *float64: nil is unknown, a pointer to 0 an audio of length 0. + if (audioSeconds !== undefined) opts.push(["AudioSeconds", `trackparse.Ptr(${goFloat(audioSeconds)})`]); + if (knownArtists) opts.push(["KnownArtists", `[]string{${knownArtists.map(goStr).join(", ")}}`]); + const nums = [audioSeconds ?? 0, seconds, fix?.seconds ?? 0]; + const std = ['"encoding/json"', '"fmt"', '"os"']; + if (joined) std.push('"strings"'); + if (nums.some((n) => !Number.isFinite(n))) std.push('"math"'); + const body = [ + joined ? `text := strings.Join([]string{\n${lines.map((l) => `\t${goStr(l)},`).join("\n")}\n}, "\\n")` : `text := ${goStr(text)}`, + "", + hasOptions ? `list := trackparse.ParseTracklistWith(text, ${goStruct("TracklistOptions", opts, "")})` : "list := trackparse.ParseTracklist(text)", + "enc := json.NewEncoder(os.Stdout)", + 'enc.SetIndent("", " ")', + "enc.SetEscapeHTML(false) // & < > as written, as JSON.stringify does", + "enc.Encode(list.Entries) // one entry per line", + "enc.Encode(list.Warnings) // the checks, with line numbers", + "", + `shifted := trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.ShiftFrom(${goNum(seconds)}, ${from})})`, + "sorted := trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.SortByTime()})", + ]; + if (fix) body.push(`fixed := trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.SetTime(${fix.line}, ${goNum(fix.seconds)})}) // the suggested fix`); + body.push(`fmt.Print(shifted.Text, "\\n\\n", sorted.Text${fix ? ', "\\n\\n", fixed.Text' : ""}, "\\n")`); + const api = [ + hasOptions ? "ParseTracklistWith" : "ParseTracklist", + ...(hasOptions ? ["TracklistOptions"] : []), + ...(audioSeconds !== undefined ? ["Ptr"] : []), + "ApplyEdits", + "ShiftFrom", + "SortByTime", + ...(fix ? ["SetTime"] : []), + ]; + return { src: goMain(body.flatMap((l) => l.split("\n")), std), api }; +} + +// ---- API docs ----------------------------------------------------------------------------------- + +const DOCS_RS = "https://docs.rs/trackparse/latest/trackparse/"; +const PKG_GO = "https://pkg.go.dev/github.com/4matic/trackparse/go"; + +/** Rust items by kind and module, as docs.rs names their pages. */ +const RS_ITEM: Record = { + parse: "fn.parse.html", + parse_with: "fn.parse_with.html", + format_track: "fn.format_track.html", + format_track_with: "fn.format_track_with.html", + ParseOptions: "struct.ParseOptions.html", + FormatOptions: "struct.FormatOptions.html", + ModeOption: "enum.ModeOption.html", + SplitAnd: "enum.SplitAnd.html", + FeatPlacement: "enum.FeatPlacement.html", + JoinerStyle: "enum.JoinerStyle.html", + VersionsOption: "enum.VersionsOption.html", + parse_tracklist: "tracklist/fn.parse_tracklist.html", + parse_tracklist_with: "tracklist/fn.parse_tracklist_with.html", + apply_edits: "tracklist/fn.apply_edits.html", + TracklistOptions: "tracklist/struct.TracklistOptions.html", + Edit: "tracklist/enum.Edit.html", +}; + +/** The site's reference sections, which are the API docs of the JavaScript and Python packages. */ +const SITE_REF: Record = { + parse: "reference/parse/", + format: "reference/functions/#formattrack-options", + format_track: "reference/functions/#formattrack-options", + parseTracklist: "reference/tracklist/#parsetracklisttext-options", + parse_tracklist: "reference/tracklist/#parsetracklisttext-options", + applyEdits: "reference/tracklist/#applyeditstext-edits-options", + apply_edits: "reference/tracklist/#applyeditstext-edits-options", +}; + +/** Where `name` is documented for `lang`: docs.rs, pkg.go.dev, or the site's reference. */ +export function apiUrl(lang: Lang, name: string, base: string): string | null { + if (lang === "rs") return RS_ITEM[name] ? DOCS_RS + RS_ITEM[name] : null; + if (lang === "go") return `${PKG_GO}#${name}`; + return SITE_REF[name] ? `${base}/${SITE_REF[name]}` : null; +} diff --git a/site/src/lib/trackview.ts b/site/src/lib/trackview.ts index 1e465b6..36cef8c 100644 --- a/site/src/lib/trackview.ts +++ b/site/src/lib/trackview.ts @@ -127,37 +127,105 @@ export function segmentsHtml(segs: Segment[]): string { .join(""); } -export function chip(text: string, kind: string, title?: string): string { +export function chip(text: string, kind: string, title?: string, href?: string): string { const t = title ? ` title="${escapeHtml(title)}"` : ""; + if (href) return `${escapeHtml(text)}`; return `${escapeHtml(text)}`; } -function versionLine(v: Version): string { - const bits: string[] = [chip(v.type, "version")]; +// ---- links into the docs ---------------------------------------------------------------------- +// The output names things the docs explain. With the site base (`/trackparse`), the playground +// and the landing demo link each field name to its row in the reference and each value (a role, +// a version type, a junk kind) to the guide section that explains it. + +/** A text fragment (`:~:text=start,-suffix`): the browser scrolls to and marks that text. */ +export function textFragment(start: string, suffix?: string, prefix?: string): string { + const enc = (x: string) => encodeURIComponent(x).replace(/-/g, "%2D"); + return `:~:text=${prefix ? `${enc(prefix)}-,` : ""}${enc(start)}${suffix ? `,-${enc(suffix)}` : ""}`; +} + +/** + * Each ParsedTrack field and the text that follows its name in the ParsedTrack table of + * reference/parse (the start of the type column), so the fragment lands on that row. + */ +const FIELD_ROW: Record = { + artists: "Artist[]", + title: "string", + versions: "Version[]", + junk: "{ raw", + position: "{ raw", + timestamp: "{ raw", + year: "number", + flags: "{ explicit", + mode: '"clean"', + warnings: "Warning[]", +}; + +/** The row of a ParsedTrack field in the reference. */ +export function fieldUrl(base: string, field: string): string { + const suffix = FIELD_ROW[field]; + return `${base}/reference/parse/#parsedtrack${suffix ? textFragment(field, suffix) : ""}`; +} + +/** Guide sections, relative to the site base. */ +export const GUIDE = { + role: { + primary: "guides/artists/#joiners", + featured: "guides/artists/#features", + producer: "guides/artists/#producers", + remixer: "guides/versions/", + } as Record, + versionType: "guides/versions/#the-27-types", + modifiers: "guides/versions/#generic-words-borrow-their-meaning", + unknownRemixer: "guides/versions/#unknown-remixers", + unknownArtist: "guides/artists/#unknown-artists", + junk: "guides/junk-and-flags/#junk", + flags: "guides/junk-and-flags/#flags", + year: "guides/junk-and-flags/#year", + position: "guides/junk-and-flags/#track-numbers", + timestamp: "guides/junk-and-flags/#cue-times", + mode: { + clean: "guides/modes/#how-auto-decides", + youtube: "guides/modes/#youtube-mode", + filename: "guides/modes/#filename-mode", + tracklist: "guides/modes/#tracklist-mode", + } as Record, +}; + +/** `path` under the site base, or nothing when there is no base (no links wanted). */ +const at = (base: string | undefined, path: string | undefined) => + base === undefined || path === undefined ? undefined : `${base}/${path}`; + +function versionLine(v: Version, base?: string): string { + const bits: string[] = [chip(v.type, "version", "The version types", at(base, GUIDE.versionType))]; for (const a of v.artists) bits.push(`by ${escapeHtml(a.name)}`); - for (const m of v.modifiers) bits.push(chip(`+${m}`, "version")); + for (const m of v.modifiers) bits.push(chip(`+${m}`, "version", "Modifiers: type words that didn't win", at(base, GUIDE.modifiers))); if (v.descriptor) bits.push(`${escapeHtml(v.descriptor)}`); if (v.year !== null) bits.push(chip(String(v.year), "year")); - if (v.unknownArtist) bits.push(chip("unknown remixer", "junk")); + if (v.unknownArtist) bits.push(chip("unknown remixer", "junk", "Unknown remixers", at(base, GUIDE.unknownRemixer))); return bits.join(" "); } /** * The field cards shown under the highlighted string. `base` is the site base (`/trackparse`): - * with it, each warning links to its row in the warnings reference. + * with it, each field name links to its row in the reference, each value to the guide that + * explains it, and each warning to its row in the warnings reference. */ export function fieldsHtml(t: ParsedTrack, base?: string): string { const rows: [string, string][] = []; + const role = (a: Artist) => chip(a.role, roleKind(a), `The ${a.role} role`, at(base, GUIDE.role[a.role])); rows.push([ "Artists", t.artists.length ? t.artists .map( (a) => - `${a.joiner ? `${escapeHtml(a.joiner)}` : ""}${escapeHtml(a.name)} ${chip(a.role, roleKind(a))}`, + `${a.joiner ? `${escapeHtml(a.joiner)}` : ""}${escapeHtml(a.name)} ${role(a)}`, ) .join("") - : `${t.flags.unknownArtist ? "unknown (ID)" : "none"}`, + : t.flags.unknownArtist + ? chip("unknown (ID)", "junk", "Unknown artists", at(base, GUIDE.unknownArtist)) + : `none`, ]); rows.push([ "Title", @@ -166,19 +234,25 @@ export function fieldsHtml(t: ParsedTrack, base?: string): string { : `empty`, ]); if (t.versions.length) - rows.push(["Versions", t.versions.map((v) => `
    ${versionLine(v)}
    `).join("")]); + rows.push(["Versions", t.versions.map((v) => `
    ${versionLine(v, base)}
    `).join("")]); if (t.junk.length) rows.push([ "Junk", - t.junk.map((j) => `${chip(j.kind, "junk")} ${escapeHtml(j.raw)}`).join("
    "), + t.junk + .map((j) => `${chip(j.kind, "junk", "The junk kinds", at(base, GUIDE.junk))} ${escapeHtml(j.raw)}`) + .join("
    "), ]); - if (t.position) rows.push(["Position", chip(`#${t.position.number}`, "position")]); + if (t.position) rows.push(["Position", chip(`#${t.position.number}`, "position", "Track numbers", at(base, GUIDE.position))]); if (t.timestamp) - rows.push(["Timestamp", chip(`${t.timestamp.raw} = ${t.timestamp.seconds} s`, "position")]); - if (t.year !== null) rows.push(["Year", chip(String(t.year), "year")]); + rows.push([ + "Timestamp", + chip(`${t.timestamp.raw} = ${t.timestamp.seconds} s`, "position", "Cue times", at(base, GUIDE.timestamp)), + ]); + if (t.year !== null) rows.push(["Year", chip(String(t.year), "year", "Years", at(base, GUIDE.year))]); const flags = (["explicit", "clean"] as const).filter((f) => t.flags[f]); - if (flags.length) rows.push(["Flags", flags.map((f) => chip(f, "year")).join(" ")]); - rows.push(["Mode", `${t.mode}`]); + if (flags.length) rows.push(["Flags", flags.map((f) => chip(f, "year", "Flags", at(base, GUIDE.flags))).join(" ")]); + const mode = at(base, GUIDE.mode[t.mode]); + rows.push(["Mode", mode ? `${t.mode}` : `${t.mode}`]); if (t.warnings.length) rows.push([ "Warnings", @@ -191,8 +265,11 @@ export function fieldsHtml(t: ParsedTrack, base?: string): string { }) .join(" "), ]); + // The field name links to its row in the ParsedTrack reference. + const dt = (k: string) => + base === undefined ? k : `${k}`; return `
    ${rows - .map(([k, v]) => `
    ${k}
    ${v}
    `) + .map(([k, v]) => `
    ${dt(k)}
    ${v}
    `) .join("")}
    `; } diff --git a/site/src/styles/playground.css b/site/src/styles/playground.css index 6693684..8ff958d 100644 --- a/site/src/styles/playground.css +++ b/site/src/styles/playground.css @@ -201,6 +201,38 @@ select.tp-input option { color: var(--sl-color-gray-3); margin: 0; } +/* A field name links to its row in the ParsedTrack reference. */ +.tp-field dt a { + color: inherit; + text-decoration: underline dotted; + text-decoration-color: var(--tp-border-strong); + text-underline-offset: 0.25em; +} +.tp-field dt a:hover { + color: var(--sl-color-white); + text-decoration-style: solid; + text-decoration-color: var(--sl-color-accent); +} +/* Values that link to the guide explaining them (a role, a version type, a junk kind): the chip + stays as it is, its border firms up on hover. */ +a.tp-chip { + text-decoration: none; + transition: border-color 0.12s; +} +a.tp-chip:hover { + border-color: color-mix(in srgb, var(--tp-c) 70%, transparent); +} +a.tp-mode { + color: inherit; + text-decoration: none; +} +a.tp-mode code { + color: var(--sl-color-gray-1); + border-bottom: 1px dotted var(--tp-border-strong); +} +a.tp-mode:hover code { + border-bottom: 1px solid var(--sl-color-accent); +} .tp-field dd { margin: 0; font-size: 0.9rem; From e837813936ea67969d1121561527712df03bc51b Mon Sep 17 00:00:00 2001 From: 4matic Date: Sat, 14 Nov 2026 04:33:38 +0200 Subject: [PATCH 11/11] docs(site): Go examples indented with tabs, as gofmt writes them --- site/src/content/docs/guides/artists.mdx | 42 +++---- .../docs/guides/editing-tracklists.mdx | 30 ++--- site/src/content/docs/guides/formatting.mdx | 14 +-- .../content/docs/guides/junk-and-flags.mdx | 4 +- site/src/content/docs/guides/modes.mdx | 4 +- site/src/content/docs/guides/tracklists.mdx | 46 ++++---- site/src/content/docs/guides/versions.mdx | 30 ++--- site/src/content/docs/index.mdx | 34 +++--- site/src/content/docs/reference/functions.mdx | 16 +-- site/src/content/docs/reference/options.mdx | 42 +++---- site/src/content/docs/reference/parse.mdx | 48 ++++---- site/src/content/docs/reference/tracklist.mdx | 32 ++--- site/src/content/docs/reference/warnings.mdx | 42 +++---- .../content/docs/start/getting-started.mdx | 110 +++++++++--------- site/src/content/docs/start/introduction.mdx | 6 +- 15 files changed, 250 insertions(+), 250 deletions(-) diff --git a/site/src/content/docs/guides/artists.mdx b/site/src/content/docs/guides/artists.mdx index 26fe4df..5ccaff2 100644 --- a/site/src/content/docs/guides/artists.mdx +++ b/site/src/content/docs/guides/artists.mdx @@ -39,10 +39,10 @@ pub struct Artist { ```go type Artist struct { - Name string - Role Role // RolePrimary | RoleFeatured | RoleRemixer | RoleProducer - Joiner *string // nil for the first name of a list - Source Source // SourceArtist | SourceTitle | SourceVersion + Name string + Role Role // RolePrimary | RoleFeatured | RoleRemixer | RoleProducer + Joiner *string // nil for the first name of a list + Source Source // SourceArtist | SourceTitle | SourceVersion } ``` @@ -112,25 +112,25 @@ parse("Kanye West vs. Daft Punk - Stronger").artists.iter().map(|a| &a.name).col ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) names := func(artists []trackparse.Artist) []string { - out := []string{} - for _, a := range artists { - out = append(out, a.Name) - } - return out + out := []string{} + for _, a := range artists { + out = append(out, a.Name) + } + return out } for _, a := range trackparse.Parse("Skrillex & Diplo x Justin Bieber - Where Are Ü Now").Artists { - if a.Joiner == nil { - fmt.Println(a.Name, "(joiner nil),", a.Role) - } else { - fmt.Printf("%s (joiner %q), %s\n", a.Name, *a.Joiner, a.Role) - } + if a.Joiner == nil { + fmt.Println(a.Name, "(joiner nil),", a.Role) + } else { + fmt.Printf("%s (joiner %q), %s\n", a.Name, *a.Joiner, a.Role) + } } // Skrillex (joiner nil), primary // Diplo (joiner "&"), primary @@ -313,12 +313,12 @@ parse("Silk City - Electricity (with Dua Lipa)").artists[1] ```go for _, s := range []string{ - "Noisia feat. Foreign Beggars - Shellshock", - "Noisia - Shellshock ft. Foreign Beggars", - "Silk City - Electricity (with Dua Lipa)", + "Noisia feat. Foreign Beggars - Shellshock", + "Noisia - Shellshock ft. Foreign Beggars", + "Silk City - Electricity (with Dua Lipa)", } { - a := trackparse.Parse(s).Artists[1] - fmt.Printf("%q %s %q %s\n", a.Name, a.Role, *a.Joiner, a.Source) + a := trackparse.Parse(s).Artists[1] + fmt.Printf("%q %s %q %s\n", a.Name, a.Role, *a.Joiner, a.Source) } // "Foreign Beggars" featured "feat." artist // "Foreign Beggars" featured "ft." title diff --git a/site/src/content/docs/guides/editing-tracklists.mdx b/site/src/content/docs/guides/editing-tracklists.mdx index b18c649..a237fee 100644 --- a/site/src/content/docs/guides/editing-tracklists.mdx +++ b/site/src/content/docs/guides/editing-tracklists.mdx @@ -37,9 +37,9 @@ use trackparse::tracklist::{apply_edits, parse_tracklist, Edit}; ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) ``` @@ -125,27 +125,27 @@ import "strings" // text is the list from the previous page. 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", - "01:15:36 Hybris - Spinning Top", + "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", + "01:15:36 Hybris - Spinning Top", }, "\r\n") fix := *trackparse.ParseTracklist(text).Warnings[1].Suggestion fmt.Printf("%+v\n", fix) // {Line:8 Raw:01:11:02 Seconds:4262} result := trackparse.ApplyEdits(text, []trackparse.Edit{ - trackparse.SetTime(fix.Line, fix.Seconds), - trackparse.ShiftFrom(45, 5), + trackparse.SetTime(fix.Line, fix.Seconds), + trackparse.ShiftFrom(45, 5), }) fmt.Println(result.Changed) // [5 6 7 8 9] for _, w := range result.Warnings { - fmt.Println(w.Code, w.Edit, *w.Line) + fmt.Println(w.Code, w.Edit, *w.Line) } // style-upgraded 1 5 for _, line := range strings.Split(result.Text, "\r\n")[4:] { - fmt.Println(line) + fmt.Println(line) } // 01:00:16 Alix Perez - Fade Away // 01:03:55 Interview with Hybris @@ -266,10 +266,10 @@ rest := trackparse.FormatWith(track, trackparse.FormatOptions{Joiners: trackpars fmt.Printf("%q\n", rest) // "Mefjus feat. Phace - Sleepless" tidy := trackparse.ApplyEdits(messy, []trackparse.Edit{ - trackparse.SortByTime(), - trackparse.SetRest(2, rest), - trackparse.Insert(2, "06:45 Phace - Psycho"), - trackparse.Delete(4), + trackparse.SortByTime(), + trackparse.SetRest(2, rest), + trackparse.Insert(2, "06:45 Phace - Psycho"), + trackparse.Delete(4), }) fmt.Printf("%q\n", tidy.Text) // "00:00 Noisia - Stigma\n04:10 Mefjus feat. Phace - Sleepless\n06:45 Phace - Psycho" @@ -345,7 +345,7 @@ result = trackparse.ApplyEdits(text, []trackparse.Edit{trackparse.Shift(45)}) fmt.Printf("%q\n", result.Text) // "**[**53:32**] Mefjus - Bandwagon**\n**[**01:00:16**] Alix Perez - Fade Away**" for _, w := range result.Warnings { - fmt.Println(w.Code, w.Edit, *w.Line) + fmt.Println(w.Code, w.Edit, *w.Line) } // style-upgraded 0 2 ``` diff --git a/site/src/content/docs/guides/formatting.mdx b/site/src/content/docs/guides/formatting.mdx index 261448a..294e53c 100644 --- a/site/src/content/docs/guides/formatting.mdx +++ b/site/src/content/docs/guides/formatting.mdx @@ -60,13 +60,13 @@ format_track(&t); ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) t := trackparse.Parse( - "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]", + "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]", ) fmt.Printf("%q\n", trackparse.Format(t)) @@ -187,8 +187,8 @@ fmt.Printf("%q\n", trackparse.FormatWith(t, trackparse.FormatOptions{Feat: track // "Wilkinson - Afterglow (ft. Becky Hill & Tom Cane) (Sub Focus VIP Remix)" fmt.Printf("%q\n", trackparse.FormatWith(t, trackparse.FormatOptions{ - Feat: trackparse.FeatTitle, - Joiners: trackparse.JoinersCanonical, + Feat: trackparse.FeatTitle, + Joiners: trackparse.JoinersCanonical, })) // "Wilkinson - Afterglow (feat. Becky Hill & Tom Cane) (Sub Focus VIP Remix)" @@ -203,8 +203,8 @@ fmt.Printf("%q\n", trackparse.FormatWith(t, trackparse.FormatOptions{Position: t // "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)" fmt.Printf("%q\n", trackparse.FormatWith( - trackparse.Parse("Future - Mask Off (prod. by Metro Boomin)"), - trackparse.FormatOptions{OmitProducers: true}, + trackparse.Parse("Future - Mask Off (prod. by Metro Boomin)"), + trackparse.FormatOptions{OmitProducers: true}, )) // "Future - Mask Off" ``` diff --git a/site/src/content/docs/guides/junk-and-flags.mdx b/site/src/content/docs/guides/junk-and-flags.mdx index a9f99ed..66cb3c2 100644 --- a/site/src/content/docs/guides/junk-and-flags.mdx +++ b/site/src/content/docs/guides/junk-and-flags.mdx @@ -49,9 +49,9 @@ let t = parse("Daft Punk - One More Time (Official Music Video) [HD]"); ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) t := trackparse.Parse("Daft Punk - One More Time (Official Music Video) [HD]") diff --git a/site/src/content/docs/guides/modes.mdx b/site/src/content/docs/guides/modes.mdx index 4d3abf6..9bf0a8a 100644 --- a/site/src/content/docs/guides/modes.mdx +++ b/site/src/content/docs/guides/modes.mdx @@ -87,9 +87,9 @@ let video = parse("Noisia - Stigma | Official Video"); ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) t := trackparse.Parse("07_Burial_-_Archangel.mp3") diff --git a/site/src/content/docs/guides/tracklists.mdx b/site/src/content/docs/guides/tracklists.mdx index ffaf5e6..6c4c35a 100644 --- a/site/src/content/docs/guides/tracklists.mdx +++ b/site/src/content/docs/guides/tracklists.mdx @@ -38,9 +38,9 @@ use trackparse::tracklist::parse_tracklist; ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) ``` @@ -169,22 +169,22 @@ list.entries[3].track.as_ref().unwrap().flags.unknown_title; // true (the ID) import "strings" 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: should be 01:11:02 - "01:15:36 Hybris - Spinning Top", + "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: should be 01:11:02 + "01:15:36 Hybris - Spinning Top", }, "\r\n") list := trackparse.ParseTracklist(text) kinds := []trackparse.EntryKind{} for _, e := range list.Entries { - kinds = append(kinds, e.Kind) + kinds = append(kinds, e.Kind) } fmt.Println(kinds) // [header track track track track marker track track track] @@ -194,11 +194,11 @@ fmt.Printf("%#v\n", bandwagon.Parts) // trackparse.Parts{Lead:"", Time:"52:47", Gap:" ", Rest:"Mefjus & Kasra - Bandwagon (Phace Remix)"} names := []string{} for _, a := range bandwagon.Track.Artists { - names = append(names, a.Name) + names = append(names, a.Name) } fmt.Printf("%q\n", names) // ["Mefjus" "Kasra"] for _, v := range bandwagon.Track.Versions { - fmt.Println(v.Type, "by", v.Artists[0].Name) + fmt.Println(v.Type, "by", v.Artists[0].Name) } // remix by Phace fmt.Println(list.Entries[3].Track.Flags.UnknownTitle) // true @@ -247,7 +247,7 @@ list.entries.iter().map(|e| format!("{}{}", e.raw, e.eol)).collect::() = ```go var joined strings.Builder for _, e := range list.Entries { - joined.WriteString(e.Raw + string(e.Eol)) + joined.WriteString(e.Raw + string(e.Eol)) } fmt.Println(joined.String() == text) // true ``` @@ -348,7 +348,7 @@ fmt.Printf("%#v\n", a.Parts) // trackparse.Parts{Lead:"**[**", Time:"14:21", Gap:"**] ", Rest:"10. Nitepunk - ID**"} names = nil for _, x := range a.Track.Artists { - names = append(names, x.Name) + names = append(names, x.Name) } fmt.Printf("%q\n", names) // ["Nitepunk"] fmt.Printf("%q\n", a.Track.Title) // "ID" @@ -430,7 +430,7 @@ fmt.Println(e.Layered) // true fmt.Println(e.Time == nil) // true names = nil for _, a := range e.Track.Artists { - names = append(names, a.Name) + names = append(names, a.Name) } fmt.Printf("%q\n", names) // ["Phace"] fmt.Printf("%q\n", e.Track.Title) // "Psycho" @@ -525,11 +525,11 @@ mix := trackparse.ParseTracklistWith("00:00 Intro\n03:00 Drop\n1:02:03 Noisia - kinds = nil for _, e := range mix.Entries { - kinds = append(kinds, e.Kind) + kinds = append(kinds, e.Kind) } fmt.Println(kinds) // [marker marker track] for _, w := range mix.Warnings { - fmt.Println(w.Code, w.Line, w.Severity, w.Suggestion == nil) + fmt.Println(w.Code, w.Line, w.Severity, w.Suggestion == nil) } // time-after-audio-end 3 warning true ``` @@ -584,10 +584,10 @@ tl.warnings ```go for _, w := range list.Warnings { - fmt.Println(w.Code, w.Line, w.Severity) - if w.Suggestion != nil { - fmt.Printf("%+v\n", *w.Suggestion) - } + fmt.Println(w.Code, w.Line, w.Severity) + if w.Suggestion != nil { + fmt.Printf("%+v\n", *w.Suggestion) + } } // no-start-at-zero 2 info // time-out-of-order 8 warning diff --git a/site/src/content/docs/guides/versions.mdx b/site/src/content/docs/guides/versions.mdx index b6a9941..b11801e 100644 --- a/site/src/content/docs/guides/versions.mdx +++ b/site/src/content/docs/guides/versions.mdx @@ -64,14 +64,14 @@ pub struct Version { ```go type Version struct { - Type VersionType // VersionTypeRemix, VersionTypeVIP, VersionTypeRadio, … - Raw string // the text as written, without brackets: "Sub Focus VIP Remix" - Artists []Artist // remixers, role RoleRemixer - Modifiers []string // other type words that didn't win: ["extended"] - Descriptor *string // leftover words: "Taylor's", "at Wembley" - Year *int - UnknownArtist bool // "ID Remix" - Delimiter Delimiter // DelimiterParen | DelimiterSquare | DelimiterCurly | DelimiterDash + Type VersionType // VersionTypeRemix, VersionTypeVIP, VersionTypeRadio, … + Raw string // the text as written, without brackets: "Sub Focus VIP Remix" + Artists []Artist // remixers, role RoleRemixer + Modifiers []string // other type words that didn't win: ["extended"] + Descriptor *string // leftover words: "Taylor's", "at Wembley" + Year *int + UnknownArtist bool // "ID Remix" + Delimiter Delimiter // DelimiterParen | DelimiterSquare | DelimiterCurly | DelimiterDash } ``` @@ -161,9 +161,9 @@ use trackparse::parse; ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) v := trackparse.Parse("Pendulum - Watercolour (Extended VIP Mix)").Versions[0] @@ -224,13 +224,13 @@ parse("Dimension - Offshore (Mefjus Remix / Noisia Remix)") ```go for _, v := range trackparse.Parse("Avicii - Levels (Skrillex Remix) [Radio Edit]").Versions { - fmt.Println(v.Type) + fmt.Println(v.Type) } // remix // radio for _, v := range trackparse.Parse("Dimension - Offshore (Mefjus Remix / Noisia Remix)").Versions { - fmt.Println(v.Artists[0].Name) + fmt.Println(v.Artists[0].Name) } // Mefjus // Noisia @@ -352,9 +352,9 @@ parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versi ```go parser := trackparse.NewParser(trackparse.ParseOptions{ - Keywords: trackparse.Keywords{ - VersionHeads: []trackparse.VersionHead{{Key: "rerub", Type: trackparse.VersionTypeRework}}, - }, + Keywords: trackparse.Keywords{ + VersionHeads: []trackparse.VersionHead{{Key: "rerub", Type: trackparse.VersionTypeRework}}, + }, }) fmt.Println(parser.Parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").Versions[0].Type) // rework diff --git a/site/src/content/docs/index.mdx b/site/src/content/docs/index.mdx index 692cf5f..bd8bc76 100644 --- a/site/src/content/docs/index.mdx +++ b/site/src/content/docs/index.mdx @@ -95,23 +95,23 @@ in the title, word for word. ```go - import ( - "fmt" - - "github.com/4matic/trackparse/go" - ) - - track := trackparse.Parse("Noisia feat. Foreign Beggars - Shellshock") - for _, a := range track.Artists { - fmt.Printf("%s (%s)\n", a.Name, a.Role) - } - // Noisia (primary) - // Foreign Beggars (featured) - - v := trackparse.Parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").Versions[0] - fmt.Println(v.Type, *v.Descriptor, *v.Year) - // live at Wembley 1986 - ``` + import ( + "fmt" + + "github.com/4matic/trackparse/go" + ) + + track := trackparse.Parse("Noisia feat. Foreign Beggars - Shellshock") + for _, a := range track.Artists { + fmt.Printf("%s (%s)\n", a.Name, a.Role) + } + // Noisia (primary) + // Foreign Beggars (featured) + + v := trackparse.Parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").Versions[0] + fmt.Println(v.Type, *v.Descriptor, *v.Year) + // live at Wembley 1986 + ``` diff --git a/site/src/content/docs/reference/functions.mdx b/site/src/content/docs/reference/functions.mdx index e58c77c..7775f53 100644 --- a/site/src/content/docs/reference/functions.mdx +++ b/site/src/content/docs/reference/functions.mdx @@ -88,13 +88,13 @@ parse_artists("Sub Focus, Wilkinson & Dimension feat. Kojo") ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) for _, a := range trackparse.ParseArtists("Sub Focus, Wilkinson & Dimension feat. Kojo") { - fmt.Printf("%s:%s\n", a.Name, a.Role) + fmt.Printf("%s:%s\n", a.Name, a.Role) } // Sub Focus:primary // Wilkinson:primary @@ -243,7 +243,7 @@ all_artists(&parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)")) ```go for _, a := range trackparse.AllArtists(trackparse.Parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)")) { - fmt.Printf("%s:%s\n", a.Name, a.Role) + fmt.Printf("%s:%s\n", a.Name, a.Role) } // Wilkinson:primary // Becky Hill:featured @@ -317,10 +317,10 @@ parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versi ```go parser := trackparse.NewParser(trackparse.ParseOptions{ - KnownArtists: []string{"Chase & Status", "Camo & Krooked"}, - Keywords: trackparse.Keywords{ - VersionHeads: []trackparse.VersionHead{{Key: "rerub", Type: trackparse.VersionTypeRework}}, - }, + KnownArtists: []string{"Chase & Status", "Camo & Krooked"}, + Keywords: trackparse.Keywords{ + VersionHeads: []trackparse.VersionHead{{Key: "rerub", Type: trackparse.VersionTypeRework}}, + }, }) fmt.Println(parser.Parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").Versions[0].Type) diff --git a/site/src/content/docs/reference/options.mdx b/site/src/content/docs/reference/options.mdx index fcf73fe..d890c93 100644 --- a/site/src/content/docs/reference/options.mdx +++ b/site/src/content/docs/reference/options.mdx @@ -73,11 +73,11 @@ let options = ParseOptions::new() ```go type ParseOptions struct { - Mode Mode // ModeAuto | ModeClean | ModeYouTube | ModeFilename | ModeTracklist; "" means auto - Uploader string // empty means none - KnownArtists []string - SplitAnd SplitAnd // SplitAndAuto | SplitAndAlways | SplitAndNever; "" means auto - Keywords Keywords + Mode Mode // ModeAuto | ModeClean | ModeYouTube | ModeFilename | ModeTracklist; "" means auto + Uploader string // empty means none + KnownArtists []string + SplitAnd SplitAnd // SplitAndAuto | SplitAndAlways | SplitAndNever; "" means auto + Keywords Keywords } ``` @@ -86,17 +86,17 @@ Set the fields you need. The others keep their zero value, which is the default ```go import ( - "fmt" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) input := "Chase & Status - Baddadan" options := trackparse.ParseOptions{ - Mode: trackparse.ModeYouTube, - KnownArtists: []string{"Chase & Status"}, - Uploader: "Daft Punk - Topic", - SplitAnd: trackparse.SplitAndNever, + Mode: trackparse.ModeYouTube, + KnownArtists: []string{"Chase & Status"}, + Uploader: "Daft Punk - Topic", + SplitAnd: trackparse.SplitAndNever, } fmt.Printf("%q\n", trackparse.ParseWith(input, options).Artists[0].Name) // "Chase & Status" ``` @@ -198,11 +198,11 @@ pub struct KeywordOptions { ```go type Keywords struct { - VersionHeads []VersionHead // {Key: "rerub", Type: VersionTypeRework} - Descriptors []string // extra style words, like the built-in "D'n'B" - Genres []string // extra genre names (junk kind genre) - Junk []JunkPhrase // {Phrase: "live stream", Kind: JunkKindOther} - FeatMarkers []string // extra feat markers + VersionHeads []VersionHead // {Key: "rerub", Type: VersionTypeRework} + Descriptors []string // extra style words, like the built-in "D'n'B" + Genres []string // extra genre names (junk kind genre) + Junk []JunkPhrase // {Phrase: "live stream", Kind: JunkKindOther} + FeatMarkers []string // extra feat markers } ``` @@ -265,10 +265,10 @@ t.versions[0].version_type; // Rework ```go parser := trackparse.NewParser(trackparse.ParseOptions{ - KnownArtists: []string{"Chase & Status", "Camo & Krooked"}, - Keywords: trackparse.Keywords{ - VersionHeads: []trackparse.VersionHead{{Key: "rerub", Type: trackparse.VersionTypeRework}}, - }, + KnownArtists: []string{"Chase & Status", "Camo & Krooked"}, + Keywords: trackparse.Keywords{ + VersionHeads: []trackparse.VersionHead{{Key: "rerub", Type: trackparse.VersionTypeRework}}, + }, }) t := parser.Parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)") @@ -329,7 +329,7 @@ let r = parse_with("Artist - Song [Some Label Rip]", &ParseOptions::new().keywor fmt.Printf("%q\n", trackparse.Parse("Artist - Song [Some Label Rip]").Title) // "Song [Some Label Rip]" keywords := trackparse.Keywords{ - Junk: []trackparse.JunkPhrase{{Phrase: "some label rip", Kind: trackparse.JunkKindLabel}}, + Junk: []trackparse.JunkPhrase{{Phrase: "some label rip", Kind: trackparse.JunkKindLabel}}, } r := trackparse.ParseWith("Artist - Song [Some Label Rip]", trackparse.ParseOptions{Keywords: keywords}) fmt.Printf("%q\n", r.Title) // "Song" diff --git a/site/src/content/docs/reference/parse.mdx b/site/src/content/docs/reference/parse.mdx index 0535e8e..d2df5e5 100644 --- a/site/src/content/docs/reference/parse.mdx +++ b/site/src/content/docs/reference/parse.mdx @@ -136,18 +136,18 @@ pub struct ParsedTrack { ```go type Track struct { - Input string - Mode Mode - Position *Position // Position{Raw string; Number int} - Timestamp *Timestamp // Timestamp{Raw string; Seconds int} - Artists []Artist - Title string - FullTitle string - Versions []Version - Year *int - Flags Flags // Flags{Explicit, Clean, UnknownArtist, UnknownTitle bool} - Junk []Junk // Junk{Raw string; Kind JunkKind} - Warnings []Warning + Input string + Mode Mode + Position *Position // Position{Raw string; Number int} + Timestamp *Timestamp // Timestamp{Raw string; Seconds int} + Artists []Artist + Title string + FullTitle string + Versions []Version + Year *int + Flags Flags // Flags{Explicit, Clean, UnknownArtist, UnknownTitle bool} + Junk []Junk // Junk{Raw string; Kind JunkKind} + Warnings []Warning } ``` @@ -284,14 +284,14 @@ pub struct Version { ```go type Version struct { - Type VersionType - Raw string - Artists []Artist - Modifiers []string - Descriptor *string - Year *int - UnknownArtist bool - Delimiter Delimiter + Type VersionType + Raw string + Artists []Artist + Modifiers []string + Descriptor *string + Year *int + UnknownArtist bool + Delimiter Delimiter } ``` @@ -397,11 +397,11 @@ keys, so `serde_json` writes the same text and reads it back. ```go import ( - "encoding/json" - "fmt" - "reflect" + "encoding/json" + "fmt" + "reflect" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) track := trackparse.Parse("Noisia - Stigma (2015)") diff --git a/site/src/content/docs/reference/tracklist.mdx b/site/src/content/docs/reference/tracklist.mdx index 80544c4..bdb3c4a 100644 --- a/site/src/content/docs/reference/tracklist.mdx +++ b/site/src/content/docs/reference/tracklist.mdx @@ -112,10 +112,10 @@ pub struct Tracklist { ```go type Tracklist struct { - SpecVersion string - Entries []Entry - Warnings []TracklistWarning - Stats Stats // Lines, Tracks, Markers, Timed, FirstTime, LastTime + SpecVersion string + Entries []Entry + Warnings []TracklistWarning + Stats Stats // Lines, Tracks, Markers, Timed, FirstTime, LastTime } ``` @@ -178,10 +178,10 @@ pub struct TracklistWarning { ```go type TracklistWarning struct { - Code WarningCode - Line int - Severity Severity // SeverityInfo | SeverityWarning - Suggestion *Suggestion // Suggestion{Line int, Raw string, Seconds float64} + Code WarningCode + Line int + Severity Severity // SeverityInfo | SeverityWarning + Suggestion *Suggestion // Suggestion{Line int, Raw string, Seconds float64} } ``` @@ -335,14 +335,14 @@ Everything is in the package `trackparse`: the structs `Tracklist`, `Entry`, `Pa ```go type Edit struct { - Op EditOp // EditOpSetTime, EditOpShift, EditOpSortByTime, EditOpSetRest, EditOpInsert, EditOpDelete - Line int // set-time, set-rest, delete - Seconds float64 // set-time, shift - Lines []int // shift: nil means not given - From *int // shift: nil means not given - Rest string // set-rest - After int // insert - Text string // insert + Op EditOp // EditOpSetTime, EditOpShift, EditOpSortByTime, EditOpSetRest, EditOpInsert, EditOpDelete + Line int // set-time, set-rest, delete + Seconds float64 // set-time, shift + Lines []int // shift: nil means not given + From *int // shift: nil means not given + Rest string // set-rest + After int // insert + Text string // insert } ``` diff --git a/site/src/content/docs/reference/warnings.mdx b/site/src/content/docs/reference/warnings.mdx index 4fb7d8a..0b7c88e 100644 --- a/site/src/content/docs/reference/warnings.mdx +++ b/site/src/content/docs/reference/warnings.mdx @@ -96,11 +96,11 @@ a warning. `Warning::ALL` lists the variants, and `Warning::from_name("bySplit") ```go import ( - "fmt" - "slices" - "strings" + "fmt" + "slices" + "strings" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) track := trackparse.ParseWith("Blink-182-All The Small Things", trackparse.ParseOptions{Mode: trackparse.ModeYouTube}) @@ -110,14 +110,14 @@ fmt.Println(slices.Contains(track.Warnings, trackparse.WarningUnspacedDashSplit) fmt.Println(len(track.Warnings) == 0) // false for _, warning := range track.Warnings { - switch warning { - case trackparse.WarningNoSeparator: - fmt.Println("no artist") - case trackparse.WarningUnspacedDashSplit, trackparse.WarningAsymmetricDashSplit: - fmt.Println("check the dash") - default: - fmt.Println(warning) // the code itself, such as bySplit - } + switch warning { + case trackparse.WarningNoSeparator: + fmt.Println("no artist") + case trackparse.WarningUnspacedDashSplit, trackparse.WarningAsymmetricDashSplit: + fmt.Println("check the dash") + default: + fmt.Println(warning) // the code itself, such as bySplit + } } // check the dash ``` @@ -224,21 +224,21 @@ text := "00:00 Noisia - Stigma\n04:10 Mefjus - Sleepless\n03:55 Phace - Psycho\n list := trackparse.ParseTracklist(text) for _, w := range list.Warnings { - fmt.Println(w.Code, w.Line, w.Severity, w.Suggestion == nil) + fmt.Println(w.Code, w.Line, w.Severity, w.Suggestion == nil) } // time-out-of-order 3 warning true // line-unparsed 4 warning true for _, w := range list.Warnings { - if w.Severity == trackparse.SeverityWarning { - fmt.Printf("line %d: %s\n", w.Line, w.Code) - } + if w.Severity == trackparse.SeverityWarning { + fmt.Printf("line %d: %s\n", w.Line, w.Code) + } } // line 3: time-out-of-order // line 4: line-unparsed fmt.Println(slices.ContainsFunc(list.Warnings, func(w trackparse.TracklistWarning) bool { - return w.Code == trackparse.WarningCodeTimeOutOfOrder + return w.Code == trackparse.WarningCodeTimeOutOfOrder })) // true ``` @@ -339,12 +339,12 @@ result.warnings.iter().any(|w| w.code == EditWarningCode::EditInvalid); // tru ```go result := trackparse.ApplyEdits(text, []trackparse.Edit{ - trackparse.SetTime(9, 60), // there is no line 9 - trackparse.ShiftLines(-300, 2), // 04:10 minus five minutes + trackparse.SetTime(9, 60), // there is no line 9 + trackparse.ShiftLines(-300, 2), // 04:10 minus five minutes }) for _, w := range result.Warnings { - fmt.Println(w.Code, w.Edit, *w.Line) + fmt.Println(w.Code, w.Edit, *w.Line) } // edit-invalid 0 9 // time-clamped 1 2 @@ -352,7 +352,7 @@ fmt.Println(result.Changed) // [2] fmt.Printf("%q\n", strings.Split(result.Text, "\n")[1]) // "00:00 Mefjus - Sleepless" fmt.Println(slices.ContainsFunc(result.Warnings, func(w trackparse.EditWarning) bool { - return w.Code == trackparse.EditWarningCodeEditInvalid + return w.Code == trackparse.EditWarningCodeEditInvalid })) // true ``` diff --git a/site/src/content/docs/start/getting-started.mdx b/site/src/content/docs/start/getting-started.mdx index c04eefb..07854f2 100644 --- a/site/src/content/docs/start/getting-started.mdx +++ b/site/src/content/docs/start/getting-started.mdx @@ -89,22 +89,22 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; ```go - import ( - "fmt" - - "github.com/4matic/trackparse/go" - ) - - track := trackparse.Parse("Noisia feat. Foreign Beggars - Shellshock") - - fmt.Printf("%q\n", track.Title) // "Shellshock" - names := []string{} - for _, a := range track.Artists { - names = append(names, a.Name) - } - fmt.Printf("%q\n", names) // ["Noisia" "Foreign Beggars"] - fmt.Println(track.Artists[1].Role) // featured - ``` + import ( + "fmt" + + "github.com/4matic/trackparse/go" + ) + + track := trackparse.Parse("Noisia feat. Foreign Beggars - Shellshock") + + fmt.Printf("%q\n", track.Title) // "Shellshock" + names := []string{} + for _, a := range track.Artists { + names = append(names, a.Name) + } + fmt.Printf("%q\n", names) // ["Noisia" "Foreign Beggars"] + fmt.Println(track.Artists[1].Role) // featured + ``` @@ -147,17 +147,17 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; ```go - t := trackparse.Parse("Daft Punk - One More Time (Official Music Video) [HD]") - fmt.Printf("%q\n", t.Title) // "One More Time" - fmt.Printf("%+v\n", t.Junk) // [{Raw:Official Music Video Kind:video} {Raw:HD Kind:quality}] - - r := trackparse.Parse("Dimension - Offshore (Mefjus Remix / Noisia Remix)") - for _, v := range r.Versions { - fmt.Println(v.Type, "by", v.Artists[0].Name) - } - // remix by Mefjus - // remix by Noisia - ``` + t := trackparse.Parse("Daft Punk - One More Time (Official Music Video) [HD]") + fmt.Printf("%q\n", t.Title) // "One More Time" + fmt.Printf("%+v\n", t.Junk) // [{Raw:Official Music Video Kind:video} {Raw:HD Kind:quality}] + + r := trackparse.Parse("Dimension - Offshore (Mefjus Remix / Noisia Remix)") + for _, v := range r.Versions { + fmt.Println(v.Type, "by", v.Artists[0].Name) + } + // remix by Mefjus + // remix by Noisia + ``` @@ -198,19 +198,19 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; ```go - names = nil - for _, a := range trackparse.Parse("Chase & Status - Baddadan").Artists { - names = append(names, a.Name) - } - fmt.Printf("%q\n", names) // ["Chase" "Status"] - - options := trackparse.ParseOptions{KnownArtists: []string{"Chase & Status"}} - names = nil - for _, a := range trackparse.ParseWith("Chase & Status - Baddadan", options).Artists { - names = append(names, a.Name) - } - fmt.Printf("%q\n", names) // ["Chase & Status"] - ``` + names = nil + for _, a := range trackparse.Parse("Chase & Status - Baddadan").Artists { + names = append(names, a.Name) + } + fmt.Printf("%q\n", names) // ["Chase" "Status"] + + options := trackparse.ParseOptions{KnownArtists: []string{"Chase & Status"}} + names = nil + for _, a := range trackparse.ParseWith("Chase & Status - Baddadan", options).Artists { + names = append(names, a.Name) + } + fmt.Printf("%q\n", names) // ["Chase & Status"] + ``` @@ -245,12 +245,12 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; ```go - import "encoding/json" + import "encoding/json" - fmt.Println(trackparse.Format(t)) // Daft Punk - One More Time - data, _ := json.Marshal(t) - fmt.Println(string(data)) // {"input":"Daft Punk - One More Time (Official Music Video) [HD]","mode":"youtube",…} - ``` + fmt.Println(trackparse.Format(t)) // Daft Punk - One More Time + data, _ := json.Marshal(t) + fmt.Println(string(data)) // {"input":"Daft Punk - One More Time (Official Music Video) [HD]","mode":"youtube",…} + ``` @@ -290,16 +290,16 @@ import { Aside, Steps, Tabs, TabItem } from "@astrojs/starlight/components"; ```go - list := trackparse.ParseTracklist("00:00 Noisia - Stigma\n04:10 Mefjus - Sleepless (Phace Remix)") - for _, e := range list.Entries { - if e.Time != nil && e.Track != nil { - fmt.Printf("%vs %s\n", e.Time.Seconds, e.Track.Title) - } - } - // 0s Stigma - // 250s Sleepless - fmt.Println(len(list.Warnings)) // 0 - ``` + list := trackparse.ParseTracklist("00:00 Noisia - Stigma\n04:10 Mefjus - Sleepless (Phace Remix)") + for _, e := range list.Entries { + if e.Time != nil && e.Track != nil { + fmt.Printf("%vs %s\n", e.Time.Seconds, e.Track.Title) + } + } + // 0s Stigma + // 250s Sleepless + fmt.Println(len(list.Warnings)) // 0 + ``` `Time` and `Track` are pointers in Go, `nil` on a blank line or a note. diff --git a/site/src/content/docs/start/introduction.mdx b/site/src/content/docs/start/introduction.mdx index 6e634f2..a2bf71e 100644 --- a/site/src/content/docs/start/introduction.mdx +++ b/site/src/content/docs/start/introduction.mdx @@ -88,10 +88,10 @@ parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").to_json(); ```go import ( - "encoding/json" - "fmt" + "encoding/json" + "fmt" - "github.com/4matic/trackparse/go" + "github.com/4matic/trackparse/go" ) data, _ := json.Marshal(trackparse.Parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)"))