Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .github/workflows/reference-checks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
name: Reference checks
on:
pull_request:
schedule:
- cron: '0 6 * * 1'
workflow_dispatch:

permissions:
contents: read

jobs:
cli-commands:
name: CLI command reference
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Setup Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 24

- name: Download the latest v3 CLI
env:
GH_TOKEN: ${{ github.token }}
run: |
tag=$(gh release list -R spicetify/cli --exclude-drafts --limit 100 \
--json tagName --jq '[.[] | select(.tagName | startswith("v3."))][0].tagName')
if [ -z "$tag" ]; then echo "No v3 release found" >&2; exit 1; fi
echo "Using spicetify/cli $tag"
asset="spicetify-${tag#v}-linux-x86_64.tar.zst"
mkdir -p "$RUNNER_TEMP/cli"
cd "$RUNNER_TEMP/cli"
gh release download "$tag" -R spicetify/cli -p "$asset" -p "$asset.sha256"
echo "$(cat "$asset.sha256") $asset" | sha256sum -c -
tar --zstd -xf "$asset" spicetify

- name: Check CLI command reference
run: node scripts/check-cli-commands.mjs "$RUNNER_TEMP/cli/spicetify"

api-wrapper:
name: API wrapper reference
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Setup pnpm
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0

- name: Setup Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 24
cache: pnpm

- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Check API wrapper reference
run: pnpm run check:api-wrapper
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@ pnpm dev
```

To fix or add a page, open an issue or a pull request.

## Reference checks

Two scripts check that the reference pages match the code, and the `Reference checks` workflow runs them on every pull request and weekly:

- `pnpm run check:cli-commands <path-to-spicetify>` compares `src/content/docs/cli/commands.md` with the commands in the binary's `--help`. CI uses the Linux x86_64 build of the newest v3 release, which includes the Linux-only `spotify` commands.
- `pnpm run check:api-wrapper [path-or-url]` compares the `development/api-wrapper` pages with the members of `declare namespace Spicetify` in the CLI's `globals.d.ts`, fetched from the `v3-beta` branch by default.

The rules each check uses, and their allowlists, are at the top of the scripts in `scripts/`.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"lint": "oxlint",
"lint:fix": "oxlint --fix",
"format": "oxfmt",
"format:check": "oxfmt --check"
"format:check": "oxfmt --check",
"check:cli-commands": "node scripts/check-cli-commands.mjs",
"check:api-wrapper": "node scripts/check-api-wrapper.mjs"
},
"dependencies": {
"@astrojs/mdx": "^5.0.3",
Expand Down
186 changes: 186 additions & 0 deletions scripts/check-api-wrapper.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// Compares the top-level members of `declare namespace Spicetify` in the
// CLI's globals.d.ts with the API wrapper reference.
//
// Usage: node scripts/check-api-wrapper.mjs [path-or-url-to-globals.d.ts]
// (defaults to the v3-beta branch of spicetify/cli)
//
// Members are the namespaces, functions, classes, enums and consts declared
// directly in the namespace. Type aliases and interfaces are types and are
// not checked. Members tagged @deprecated and members whose name starts with
// an underscore are skipped.
//
// A member counts as documented when, under development/api-wrapper (outside
// types/):
// - a page's frontmatter title is the member name, such as `title: Player`
// - a heading is a code span naming it, such as ## `Spicetify.Daemon`
// - a table row's first cell names it, such as | `Spicetify.React` | ... |
// Pages and headings that name something globals.d.ts does not declare fail
// as stale. Pages under legacy/ live outside this directory.

import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import ts from 'typescript';

const DEFAULT_SOURCE =
'https://raw.githubusercontent.com/spicetify/cli/v3-beta/globals.d.ts';
const DOCS_DIR = 'src/content/docs/development/api-wrapper';
const INDEX_PAGES = new Set(['index.md', 'modules.md']);

// Members that are intentionally left out of the reference.
const ALLOWLIST = new Map([
['test', 'debug helper that logs missing wrapper members'],
]);

async function readSource(source) {
if (!/^https?:\/\//.test(source)) return readFileSync(source, 'utf8');
const response = await fetch(source);
if (!response.ok) {
throw new Error(`Fetching ${source} failed: ${response.status}`);
}
return response.text();
}

function isDeprecated(node) {
return ts.getJSDocTags(node).some((tag) => tag.tagName.text === 'deprecated');
}

function declaredMembers(sourceText) {
const file = ts.createSourceFile(
'globals.d.ts',
sourceText,
ts.ScriptTarget.Latest,
true,
);
const members = new Map();
const add = (name, node) => {
const deprecated = isDeprecated(node);
const previous = members.get(name);
members.set(name, {
deprecated: previous ? previous.deprecated && deprecated : deprecated,
});
};

let found = false;
for (const statement of file.statements) {
if (
!ts.isModuleDeclaration(statement) ||
statement.name.text !== 'Spicetify' ||
!statement.body ||
!ts.isModuleBlock(statement.body)
) {
continue;
}
found = true;
for (const node of statement.body.statements) {
if (ts.isVariableStatement(node)) {
for (const declaration of node.declarationList.declarations) {
if (ts.isIdentifier(declaration.name)) {
add(declaration.name.text, node);
}
}
} else if (
(ts.isFunctionDeclaration(node) ||
ts.isClassDeclaration(node) ||
ts.isEnumDeclaration(node) ||
ts.isModuleDeclaration(node)) &&
node.name
) {
add(node.name.text, node);
}
}
}
if (!found) throw new Error('No `declare namespace Spicetify` block found');
return members;
}

function markdownFiles(dir) {
return readdirSync(dir, { recursive: true })
.map(String)
.filter(
(file) => /\.mdx?$/.test(file) && !file.startsWith(`types${path.sep}`),
);
}

function documentedMembers(root) {
const pages = new Map();
const headings = new Map();
const tableRows = new Map();
const memberRef = /^`Spicetify\.([A-Za-z_$][\w$]*)[^`]*`$/;

for (const file of markdownFiles(path.join(root, DOCS_DIR))) {
const where = path.join(DOCS_DIR, file);
const text = readFileSync(path.join(root, DOCS_DIR, file), 'utf8');

if (!INDEX_PAGES.has(file)) {
const frontmatter = /^---\n([\s\S]*?)\n---/.exec(text)?.[1] ?? '';
const title = /^title:\s*['"]?(.+?)['"]?\s*$/m.exec(frontmatter)?.[1];
if (title) pages.set(title.replace(/^Spicetify\./, ''), where);
}

let inFence = false;
for (const line of text.split('\n')) {
if (/^\s*(`{3,}|~{3,})/.test(line)) {
inFence = !inFence;
continue;
}
if (inFence) continue;
const heading = /^#{1,6}\s+(`[^`]+`)\s*$/.exec(line);
const headingMember = heading && memberRef.exec(heading[1]);
if (headingMember) headings.set(headingMember[1], where);
const cell = /^\|\s*(`[^`]+`)\s*\|/.exec(line);
const cellMember = cell && memberRef.exec(cell[1]);
if (cellMember) tableRows.set(cellMember[1], where);
}
}
return { pages, headings, tableRows };
}

async function main() {
const source = process.argv[2] ?? DEFAULT_SOURCE;
const members = declaredMembers(await readSource(source));
const { pages, headings, tableRows } = documentedMembers(process.cwd());
const documented = (name) =>
pages.has(name) || headings.has(name) || tableRows.has(name);

const skipped = [];
const missing = [];
for (const [name, { deprecated }] of members) {
if (documented(name)) continue;
if (name.startsWith('_') || ALLOWLIST.has(name)) continue;
if (deprecated) skipped.push(name);
else missing.push(name);
}

const stale = [];
for (const [kind, entries] of [
['page', pages],
['heading', headings],
]) {
for (const [name, where] of entries) {
if (!members.has(name)) stale.push(`${name} (${kind} in ${where})`);
}
}

for (const name of ALLOWLIST.keys()) {
if (members.has(name) && documented(name)) {
console.warn(`warning: allowlisted member "${name}" is documented`);
}
}
if (skipped.length > 0) {
console.log(`Skipped deprecated members: ${skipped.sort().join(', ')}`);
}

console.log(`Spicetify members in ${source}: ${members.size}`);
if (missing.length > 0) {
console.error(`\nUndocumented in ${DOCS_DIR}:`);
for (const name of missing.sort()) console.error(` Spicetify.${name}`);
}
if (stale.length > 0) {
console.error('\nDocumented but not declared in globals.d.ts:');
for (const entry of stale.sort()) console.error(` Spicetify.${entry}`);
}
if (missing.length > 0 || stale.length > 0) process.exit(1);
console.log('API wrapper reference is in sync.');
}

await main();
Loading
Loading