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
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ run-https: tmp/$(HOST)-$(PORT).key tmp/$(HOST)-$(PORT).crt ## Runs the developme
normalize_yaml: ## Normalizes YAML files (alphabetizes keys, fixes line length, smart quotes)
yarn normalize-yaml .rubocop.yml --disable-sort-keys --disable-smart-punctuation
find ./config/locales/transliterate -type f -name '*.yml' -exec yarn normalize-yaml --disable-sort-keys --disable-smart-punctuation {} \;
yarn normalize-yaml --disable-sort-keys --disable-smart-punctuation config/application.yml.default
yarn normalize-yaml --disable-smart-punctuation --ignore-key-sort development,production,test config/application.yml.default
find ./config/locales/telephony -type f -name '*.yml' | xargs yarn normalize-yaml --disable-smart-punctuation
find ./config/locales -not \( -path "./config/locales/telephony*" -o -path "./config/locales/transliterate/*" \) -type f -name '*.yml' | \
xargs yarn normalize-yaml \
Expand Down
1 change: 1 addition & 0 deletions app/javascript/packages/normalize-yaml/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
### New Features

- Added new punctuation formatter to collapse multiple spaces to a single space.
- Added new option `--ignore-key-sort` to preserve ordering of keys.

## v2.0.0

Expand Down
4 changes: 3 additions & 1 deletion app/javascript/packages/normalize-yaml/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ yarn add @18f/identity-normalize-yaml prettier

### CLI

The included `normalize-yaml` binary receives files as an argument, with optional flags:
The included `normalize-yaml` binary receives files as an argument, with optional configuration:

- `--disable-sort-keys`: Disable the default behavior to sort keys.
- `--disable-smart-punctuation`: Disable the default behavior to apply smart punctuation.
- `--disable-collapse-spacing`: Disable the default behavior to collapse multiple spaces to a single space.
- `--ignore-key-sort`: Specify key(s) whose ordering should be preserved as-is. This can be passed multiple times, or as a comma-separated value.

**Example:**

Expand All @@ -59,6 +60,7 @@ Given an input YAML string and optional options, resolves to a normalized YAML s

- `prettierConfig` (`Record<string, any>`): Optional Prettier configuration object.
- `exclude` (`Formatter[]`) Formatters to exclude.
- `ignoreKeySort` (`string[]`) Keys whose order should be preserved in sorting.

## License

Expand Down
29 changes: 21 additions & 8 deletions app/javascript/packages/normalize-yaml/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

/* eslint-disable no-console */

import { promises as fsPromises } from 'fs';
import { join } from 'path';
import { parseArgs } from 'node:util';
import { promises as fsPromises } from 'node:fs';
import { join } from 'node:path';
import prettier from 'prettier';
import normalize from './index.js';

Expand All @@ -12,20 +13,32 @@ const { readFile, writeFile } = fsPromises;
/** @type {Record<string,any>=} */
const prettierConfig = (await prettier.resolveConfig(process.cwd())) || undefined;

const args = process.argv.slice(2);
const files = args.filter((arg) => !arg.startsWith('-'));
const flags = args.filter((arg) => arg.startsWith('-'));
const { values: config, positionals: files } = parseArgs({
allowPositionals: true,
options: {
'disable-collapse-spacing': { type: 'boolean' },
'disable-sort-keys': { type: 'boolean' },
'disable-smart-punctuation': { type: 'boolean' },
'ignore-key-sort': { type: 'string', multiple: true },
},
});

let ignoreKeySort = config['ignore-key-sort'];
if (ignoreKeySort) {
ignoreKeySort = ignoreKeySort.flatMap((value) => value.split(','));
}

/** @type {import('./index').NormalizeOptions} */
const options = {
prettierConfig,
exclude: /** @type {import('./index').Formatter[]} */ (
[
flags.includes('--disable-sort-keys') && 'sortKeys',
flags.includes('--disable-smart-punctuation') && 'smartPunctuation',
flags.includes('--disable-collapse-spacing') && 'collapseSpacing',
config['disable-collapse-spacing'] && 'collapseSpacing',
config['disable-sort-keys'] && 'sortKeys',
config['disable-smart-punctuation'] && 'smartPunctuation',
].filter(Boolean)
),
ignoreKeySort,
};

let exitCode = 0;
Expand Down
6 changes: 4 additions & 2 deletions app/javascript/packages/normalize-yaml/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { getUnifiedVisitor } from './visitors/index.js';
*
* @prop {Record<string,any>=} prettierConfig Optional Prettier configuration object.
* @prop {Array<Formatter>=} exclude Formatters to exclude.
* @prop {Array<string>=} ignoreKeySort Keys to ignore for sorting.
*/

/**
Expand All @@ -19,9 +20,10 @@ import { getUnifiedVisitor } from './visitors/index.js';
*
* @return {Promise<string>} Normalized content.
*/
function normalize(content, { prettierConfig, exclude } = {}) {
function normalize(content, options = {}) {
const { prettierConfig } = options;
const document = YAML.parseDocument(content);
YAML.visit(document, getUnifiedVisitor({ exclude }));
YAML.visit(document, getUnifiedVisitor(options));
return prettier.format(document.toString(), { ...prettierConfig, parser: 'yaml' });
}

Expand Down
16 changes: 16 additions & 0 deletions app/javascript/packages/normalize-yaml/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,20 @@ describe('normalize', () => {

expect(await normalize(original, { exclude: ['smartPunctuation'] })).to.equal(expected);
});

it('allows ignoring specific keys for sorting', async () => {
const original = `---
a: 1
c: 3
d: 4
b: 2`;
const expected = `---
a: 1
c: 3
b: 2
d: 4
`;

expect(await normalize(original, { ignoreKeySort: ['c'] })).to.equal(expected);
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default /** @type {import('yaml').visitor} */ ({
export default /** @type {import('./').Visitor} */ (_options) => ({
Scalar(_key, node) {
if (typeof node.value === 'string') {
node.value = node.value.replace(/ {2,}/g, ' ');
Expand Down
19 changes: 12 additions & 7 deletions app/javascript/packages/normalize-yaml/visitors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import smartPunctuation from './smart-punctuation.js';
import sortKeys from './sort-keys.js';
import collapseSpacing from './collapse-spacing.js';

/** @typedef {import('yaml').visitor} Visitor */
/** @typedef {import('../').NormalizeOptions} NormalizeOptions */
/** @typedef {(options: NormalizeOptions) => YAMLVisitor} Visitor */
/** @typedef {import('yaml').visitor} YAMLVisitor */
/** @typedef {import('../').Formatter} Formatter */

/** @type {Record<Formatter, Visitor>} */
Expand All @@ -15,18 +17,21 @@ const over =
callbacks.forEach((callback) => callback(...args));

/**
* @param {{ exclude?: Formatter[] }} exclude
* @param {NormalizeOptions} options
*
* @return {Visitor}
* @return {YAMLVisitor}
*/
export const getUnifiedVisitor = ({ exclude = [] }) =>
Object.entries(DEFAULT_VISITORS)
export function getUnifiedVisitor(options) {
const { exclude = [] } = options;
return Object.entries(DEFAULT_VISITORS)
.filter(([formatter]) => !exclude.includes(/** @type {Formatter} */ (formatter)))
.map(([_formatter, visitor]) => visitor)
.reduce((result, visitor) => {
Object.entries(visitor).forEach(([key, callback]) => {
const yamlVisitor = visitor(options);
Object.entries(yamlVisitor).forEach(([key, callback]) => {
result[key] = result[key] ? over(result[key], callback) : callback;
});

return result;
}, /** @type {Visitor} */ ({}));
}, /** @type {YAMLVisitor} */ ({}));
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function replaceInHTMLContent(html, replacer) {
*/
export const ellipses = (string) => string.replace(/\.\.\./g, '…');

export default /** @type {import('yaml').visitor} */ ({
export default /** @type {import('./').Visitor} */ (_options) => ({
Scalar(_key, node) {
if (typeof node.value === 'string') {
node.value = replaceInHTMLContent(node.value, (string) => ellipses(smartquotes(string)));
Expand Down
13 changes: 11 additions & 2 deletions app/javascript/packages/normalize-yaml/visitors/sort-keys.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
export default /** @type {import('yaml').visitor} */ ({
export default /** @type {import('./').Visitor} */ ({ ignoreKeySort }) => ({
Map(_key, node) {
node.items.sort(
/**
* @param {import('yaml').Pair<any>} a
* @param {import('yaml').Pair<any>} b
* @return {number}
*/
(a, b) => a.key.toString().localeCompare(b.key.toString()),
(a, b) => {
const aKey = a.key.toString();
const bKey = b.key.toString();

if (ignoreKeySort && (ignoreKeySort.includes(aKey) || ignoreKeySort.includes(bKey))) {
return 0;
}

return aKey.localeCompare(bKey);
},
);
},
});
Loading