Skip to content

Commit

Permalink
Add fix script to fix property order (#16052)
Browse files Browse the repository at this point in the history
* Add fix script to fix property order

* Migrate to ESM

* Fix imports

* Update comment
  • Loading branch information
queengooborg authored Jun 4, 2022
1 parent c722520 commit b2465be
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
2 changes: 2 additions & 0 deletions scripts/fix/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import esMain from 'es-main';

import fixBrowserOrder from './browser-order.js';
import fixFeatureOrder from './feature-order.js';
import fixPropertyOrder from './property-order.js';
import fixStatementOrder from './statement-order.js';
import fixLinks from './links.js';
import fixStatus from './status.js';
Expand Down Expand Up @@ -35,6 +36,7 @@ function load(...files) {
if (path.extname(file) === '.json') {
fixBrowserOrder(file);
fixFeatureOrder(file);
fixPropertyOrder(file);
fixStatementOrder(file);
fixLinks(file);
fixStatus(file);
Expand Down
69 changes: 69 additions & 0 deletions scripts/fix/property-order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/* This file is a part of @mdn/browser-compat-data
* See LICENSE file for more information. */

'use strict';

import fs from 'node:fs';

import { IS_WINDOWS } from '../../test/utils.js';

const propOrder = {
__compat: [
'description',
'mdn_url',
'spec_url',
'matches',
'support',
'status',
],
status: ['experimental', 'standard_track', 'deprecated'],
};

function doOrder(value, order) {
return order.reduce((result, key) => {
if (key in value) result[key] = value[key];
return result;
}, {});
}

/**
* Return a new feature object whose first-level properties have been
* ordered according to doOrder, and so will be stringified in that
* order as well. This relies on guaranteed "own" property ordering,
* which is insertion order for non-integer keys (which is our case).
*
* @param {string} key The key in the object
* @param {*} value The value of the key
*
* @returns {*} The new value
*/
function orderProperties(key, value) {
if (value instanceof Object && '__compat' in value) {
value.__compat = doOrder(value.__compat, propOrder.__compat);

if ('status' in value.__compat) {
value.__compat.status = doOrder(value.__compat.status, propOrder.status);
}
}
return value;
}

/**
* @param {string} filename
*/
const fixPropertyOrder = (filename) => {
let actual = fs.readFileSync(filename, 'utf-8').trim();
let expected = JSON.stringify(JSON.parse(actual, orderProperties), null, 2);

if (IS_WINDOWS) {
// prevent false positives from git.core.autocrlf on Windows
actual = actual.replace(/\r/g, '');
expected = expected.replace(/\r/g, '');
}

if (actual !== expected) {
fs.writeFileSync(filename, expected + '\n', 'utf-8');
}
};

export default fixPropertyOrder;

0 comments on commit b2465be

Please sign in to comment.