Skip to content

Commit

Permalink
feat: Add filetype detection package. (#6103)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason3S committed Aug 16, 2024
1 parent 55cf9c3 commit 3c8012e
Show file tree
Hide file tree
Showing 31 changed files with 926 additions and 406 deletions.
5 changes: 4 additions & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
}
},
{
"files": "**/src/GlobMatcher.test.ts",
"files": [
"**/src/GlobMatcher.test.ts",
"packages/cspell-filetypes/**/definitions.ts"
],
"options": {
"printWidth": 180
}
Expand Down
1 change: 1 addition & 0 deletions cspell.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
{ "path": "packages/cspell-config-lib" },
{ "path": "packages/cspell-dictionary" },
{ "path": "packages/cspell-eslint-plugin" },
{ "path": "packages/cspell-filetypes" },
{ "path": "packages/cspell-gitignore" },
{ "path": "packages/cspell-glob" },
{ "path": "packages/cspell-grammar" },
Expand Down
5 changes: 2 additions & 3 deletions integration-tests/snapshots/RustPython/RustPython/report.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Url: https://github.com/RustPython/RustPython.git
Args: '["**"]'
Summary:
files: 621
filesWithIssues: 327
issues: 2971
filesWithIssues: 326
issues: 2968
errors: 0
Errors: []

Expand Down Expand Up @@ -100,7 +100,6 @@ issues:
- "DEVELOPMENT.md:24:20 rustup U - If you have `rustup` on your system, enter"
- "DEVELOPMENT.md:113:5 speedscope U The speedscope json format (default"
- "DEVELOPMENT.md:131:26 subcrates U src`: using the other subcrates to bring rustpython"
- "Dockerfile.bin:3:1 WORKDIR U WORKDIR /rustpython"
- "Dockerfile.bin:13:5 RUSTPYTHONPATH U ENV RUSTPYTHONPATH /usr/lib/rustpython"
- "example_projects/aheui-rust.md:1:3 aheui U # aheui-rust"
- "example_projects/aheui-rust.md:4:14 frozenlib U - Creating a frozenlib: https://github.com"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Repository: RustPython/RustPython
Url: "https://github.com/RustPython/RustPython.git"
Args: ["**"]
Lines:
CSpell: Files checked: 621, Issues found: 2971 in 327 files.
CSpell: Files checked: 621, Issues found: 2968 in 326 files.
exit code: 1
Cargo.toml:150:1 - Unknown word (getrandom) -- getrandom = "0.2.12"
Cargo.toml:160:119 - Unknown word (zerocopy) -- "socket", "sched", "zerocopy", "dir", "hostname"
Expand All @@ -18,7 +18,6 @@ DEVELOPMENT.md:113:5 - Unknown word (speedscope) -- The speedscope json form
DEVELOPMENT.md:131:26 - Unknown word (subcrates) -- src`: using the other subcrates to bring rustpython
DEVELOPMENT.md:24:20 - Unknown word (rustup) -- - If you have `rustup` on your system, enter
Dockerfile.bin:13:5 - Unknown word (RUSTPYTHONPATH) -- ENV RUSTPYTHONPATH /usr/lib/rustpython
Dockerfile.bin:3:1 - Unknown word (WORKDIR) -- WORKDIR /rustpython
LICENSE-logo:139:15 - Unknown word (sublicensable) -- non-sublicensable, non-exclusive, irrevocable
LICENSE-logo:205:34 - Unknown word (waivable) -- under any voluntary or waivable statutory or compulsory
LICENSE-logo:36:7 - Unknown word (creativecommons) -- wiki.creativecommons.org/Considerations_for
Expand Down
6 changes: 3 additions & 3 deletions integration-tests/snapshots/eslint/eslint/report.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Url: https://github.com/eslint/eslint
Args: '[".","--config=../../../config/eslint/cspell.config.yaml","--issues-summary-report","--exclude=bin/**","--exclude=CHANGELOG.md","--exclude=_data","--exclude=tests/bench/large.js","--exclude=docs/src/_includes","--exclude=docs/src/assets/{fonts,s?css,images}"]'
Summary:
files: 1981
filesWithIssues: 330
issues: 1774
filesWithIssues: 329
issues: 1773
errors: 0
Errors: []

Expand Down Expand Up @@ -686,7 +686,7 @@ issuesSummary:
- "text: egal, count: 2, files: 1,"
- "text: elapseds, count: 1, files: 1,"
- "text: ELEVENTEEN, count: 2, files: 1,"
- "text: eleventy, count: 4, files: 4,"
- "text: eleventy, count: 3, files: 3,"
- "text: embertest, count: 1, files: 1,"
- "text: emtpy, count: 1, files: 1,"
- "text: endfor, count: 8, files: 4,"
Expand Down
2 changes: 1 addition & 1 deletion integration-tests/snapshots/eslint/eslint/snapshot.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Repository: eslint/eslint
Url: "https://github.com/eslint/eslint"
Args: [".","--config=../../../config/eslint/cspell.config.yaml","--issues-summary-report","--exclude=bin/**","--exclude=CHANGELOG.md","--exclude=_data","--exclude=tests/bench/large.js","--exclude=docs/src/_includes","--exclude=docs/src/assets/{fonts,s?css,images}"]
Lines:
CSpell: Files checked: 1981, Issues found: 1774 in 330 files.
CSpell: Files checked: 1981, Issues found: 1773 in 329 files.
exit code: 1
Makefile.js:132:88 - Unknown word (ined) -- followed by the string "ined".
Makefile.js:343:12 - Unknown word (gensite) -- target.gensite();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Url: https://github.com/googleapis/google-cloud-cpp.git
Args: '["--config=${repoConfig}/cspell.json","**/*","-e","{*.BUILD,BUILD,CHANGELOG.md,*.sh,*.cfg,*.ps1,Dockerfile.*,*.Dockerfile,*.{yaml,xml,json,cmake}}"]'
Summary:
files: 19462
filesWithIssues: 12311
issues: 99911
filesWithIssues: 12310
issues: 99907
errors: 0
Errors: []

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Repository: googleapis/google-cloud-cpp
Url: "https://github.com/googleapis/google-cloud-cpp.git"
Args: ["--config=../../../../config/repositories/googleapis/google-cloud-cpp/cspell.json","**/*","-e","{*.BUILD,BUILD,CHANGELOG.md,*.sh,*.cfg,*.ps1,Dockerfile.*,*.Dockerfile,*.{yaml,xml,json,cmake}}"]
Lines:
CSpell: Files checked: 19462, Issues found: 99911 in 12311 files.
CSpell: Files checked: 19462, Issues found: 99907 in 12310 files.
exit code: 1
ARCHITECTURE.md:110:20 - Unknown word (bigtable) -- - Bigtable has a [`bigtable::DataClient`](/google
ARCHITECTURE.md:110:3 - Unknown word (Bigtable) -- - Bigtable has a [`bigtable::DataClient
Expand Down
4 changes: 4 additions & 0 deletions packages/cspell-filetypes/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Change Log

All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
21 changes: 21 additions & 0 deletions packages/cspell-filetypes/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Jason Dent

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
17 changes: 17 additions & 0 deletions packages/cspell-filetypes/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# `@cspell/filetypes`

A library to help determine the type of a file.

## Install

```sh
npm install -S @cspell/filetypes
```

## Usage

```ts
import { findMatchingFileTypes } from '@cspell/filetypes';

console.log(findMatchingFileTypes('code.js')); // outputs: [ 'javascript' ]
```
51 changes: 51 additions & 0 deletions packages/cspell-filetypes/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@cspell/filetypes",
"version": "8.13.3",
"description": "Library to determine file types based upon the file name.",
"keywords": [
"cspell",
"filetypes"
],
"author": "Jason Dent <jason@streetsidesoftware.nl>",
"homepage": "https://github.com/streetsidesoftware/cspell/tree/main/packages/cspell-filetypes#readme",
"license": "MIT",
"type": "module",
"sideEffects": false,
"exports": {
".": "./dist/index.js"
},
"directories": {
"dist": "dist"
},
"typings": "dist/index.d.ts",
"files": [
"dist",
"!**/*.tsbuildInfo",
"!**/__mocks__",
"!**/*.test.*",
"!**/*.spec.*",
"!**/*.map"
],
"scripts": {
"build": "tsc -p .",
"watch": "tsc -p . -w",
"clean": "shx rm -rf dist temp coverage \"*.tsbuildInfo\"",
"clean-build": "pnpm run clean && pnpm run build",
"sort-filetypes": "pnpm build && node scripts/sortFileTypes.js && prettier --write src/definitions.ts",
"coverage": "vitest run --coverage",
"test-watch": "vitest",
"test": "vitest run"
},
"repository": {
"type": "git",
"url": "https://github.com/streetsidesoftware/cspell.git",
"directory": "packages/cspell-filetypes"
},
"bugs": {
"url": "https://github.com/streetsidesoftware/cspell/labels/filetype"
},
"engines": {
"node": ">=18"
},
"dependencies": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { readFile } from 'node:fs/promises';

async function processFiles(files) {
const defs = [];

for (const file of files) {
const content = await readFile(file, 'utf8');
const pkg = JSON.parse(content);

const languages = pkg.contributes?.languages;
if (!languages?.length) {
continue;
}

for (const def of languages) {
if (!def.id) {
continue;
}
const filenames = [...(def.filenamePatterns || []), ...(def.filenames || [])];
defs.push({
id: def.id,
extensions: def.extensions || [],
filenames: filenames.length ? filenames : undefined,
});
}
}

return defs;
}

const packageFiles = process.argv.slice(2);

const defs = await processFiles(packageFiles);

console.log(JSON.stringify(defs, undefined, 2));
76 changes: 76 additions & 0 deletions packages/cspell-filetypes/scripts/sortFileTypes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { readFile, writeFile } from 'node:fs/promises';

import { definitions } from '../dist/definitions.js';

const urlFile = new URL('../src/definitions.ts', import.meta.url);

/**
* @typedef {import('../dist/types.js').FileTypeDefinition} FileTypeDefinition
*/

/**
*
* @param {FileTypeDefinition} a
* @param {FileTypeDefinition} b
*/
function compare(a, b) {
if (a.format !== b.format) {
return !a.format || a.format === 'Text' ? -1 : 1;
}
return a.id.localeCompare(b.id);
}

const fieldOrder = ['id', 'extensions', 'filenames', 'format', 'description', 'comment'];

/**
*
* @param {FileTypeDefinition} def
* @returns {FileTypeDefinition}
*/
function normalizeDef(def) {
const entries = Object.entries(def).sort(([a], [b]) => fieldOrder.indexOf(a) - fieldOrder.indexOf(b));
def = Object.fromEntries(entries);
def.extensions = [...new Set(def.extensions.map((a) => (a.startsWith('.') ? a : '.' + a)).sort())];
def.filenames = def.filenames ? [...new Set(def.filenames.sort())] : undefined;
return def;
}

const defs = dedupe(definitions).sort(compare).map(normalizeDef);

async function updateFile() {
const content = await readFile(urlFile, 'utf8');
const newLines = `export const definitions: FileTypeDefinitions = ${JSON.stringify(defs)};\n`;
const start = content.indexOf('export const definitions:');
const end = content.indexOf('];\n', start);
const output = content.slice(0, start) + newLines + content.slice(end + 3);
await writeFile(urlFile, output, 'utf8');
}

/**
*
* @param {FileTypeDefinition[]} defs
* @returns {FileTypeDefinition[]}
*/
function dedupe(defs) {
/** @type {Map<string, FileTypeDefinition>} */
const map = new Map();
for (const def of defs) {
const key = def.id;
const existing = map.get(key);
if (!existing) {
map.set(key, def);
} else {
existing.extensions = [...existing.extensions, ...def.extensions];
existing.filenames = [...(existing.filenames || []), ...(def.filenames || [])];
if (!existing.filenames.length) {
delete existing.filenames;
}
existing.format ??= def.format;
existing.description ??= def.description;
existing.comment ??= def.comment;
}
}
return [...map.values()];
}

updateFile();
Loading

0 comments on commit 3c8012e

Please sign in to comment.