Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Load converters on-demand #8471

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
67 changes: 67 additions & 0 deletions build-models-index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* This module's only purpose is to build the models index for zigbee-herdsman-converters.
*/

import {cpSync, existsSync, readdirSync, writeFileSync} from 'fs';
import path from 'path';

const SOURCE_DIR = 'devices';

if (!existsSync(SOURCE_DIR)) {
process.exit(1);
}

const OUT_FILENAME = 'models-index.json';
// output in `src` by default (next to `index.ts`), provides access for uncompiled executions
const OUT_FILEPATH = path.join('src', OUT_FILENAME);

const lookup = {};
let totalDefinitions = 0;

function addToLookup(zigbeeModel, index) {
zigbeeModel = zigbeeModel ? zigbeeModel.toLowerCase() : null;

if (!lookup[zigbeeModel]) {
lookup[zigbeeModel] = [];
}

if (!lookup[zigbeeModel].some((z) => z[0] === index[0] && z[1] === index[1])) {
lookup[zigbeeModel].splice(0, 0, index);
}
}

for (const module of readdirSync(SOURCE_DIR)) {
if (module === 'index.js' || !module.endsWith('.js')) {
continue;
}

const filePath = path.join(SOURCE_DIR, module);

const {definitions} = await import(`./${SOURCE_DIR}/${module}`);
console.log(`Processing ${filePath}, ${definitions.length} converters`);

for (let i = 0; i < definitions.length; i++) {
const definition = definitions[i];

if (definition.fingerprint) {
for (const fingerprint of definition.fingerprint) {
// type `modelID?: string;` means modelID can be undefined, ends up under index "null"
addToLookup(fingerprint.modelID, [module, i]);
}
}

if (definition.zigbeeModel) {
for (const zigbeeModel of definition.zigbeeModel) {
addToLookup(zigbeeModel, [module, i]);
}
}
}

totalDefinitions += definitions.length;
}

writeFileSync(OUT_FILEPATH, JSON.stringify(lookup), 'utf8');
// also copy in main dir to follow `index.ts` > `index.js` build (since this is run post-build)
cpSync(OUT_FILEPATH, path.join('models-index.json'));

console.log(`\nProcessed ${totalDefinitions} definitions`);
1 change: 1 addition & 0 deletions models-index.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
75 changes: 75 additions & 0 deletions scripts/step1-standardize-exports.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import {exec} from 'child_process';
import {createReadStream, readdirSync, writeFileSync} from 'fs';
import path from 'path';
import {createInterface} from 'readline';

const DIR = path.join('src', 'devices');
const START = /^const definitions.* = \[$/;
const EXPORT_DEFAULT = /^export default/;
const MODULE_EXPORTS = /^module.exports =/;
const EXPORT = 'export ';

async function execute(command) {
return await new Promise((resolve, reject) => {
exec(command, (error, stdout) => {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
});
}

async function processLineByLine(filePath) {
let output = '';
const fileStream = createReadStream(filePath);
const rl = createInterface({
input: fileStream,
crlfDelay: Infinity,
});

for await (const line of rl) {
let remove = false;

// skip lines before definitions start
if (line.match(START)) {
output += EXPORT + line;
} else if (line.match(EXPORT_DEFAULT)) {
remove = true;
} else if (line.match(MODULE_EXPORTS)) {
remove = true;
} else {
output += line;
}

if (!remove) {
output += '\n';
}
}

rl.close();
fileStream.close();
writeFileSync(filePath, output, 'utf8');

if (process.env.TEST) {
await execute(`prettier --write ${filePath}`);
}
}

for (const module of process.env.TEST ? ['awox', 'datek.ts', 'weten.ts'] : readdirSync(DIR)) {
if (module === 'index.ts' || !module.endsWith('.ts')) {
continue;
}

const filePath = path.join(DIR, module);
console.log(`Processing ${filePath}`);

await processLineByLine(filePath);
}

rmSync(path.join(DIR, 'index.ts'));

if (!process.env.TEST) {
await execute(`prettier --write ${DIR.replaceAll('\\', '/')}`);
}
116 changes: 116 additions & 0 deletions scripts/step2-find-out-of-order.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import {existsSync, readdirSync, readFileSync} from 'fs';
import path from 'path';

const SOURCE_DIR = path.join('src', 'devices');
const DIST_DIR = 'devices';

if (!existsSync(SOURCE_DIR) || !existsSync(DIST_DIR)) {
console.log('Source or dist dir do not exist');
process.exit(1);
}

function arrayStrictEquals(as, bs) {
if (as.length !== bs.length) {
return false;
}

for (let i = 0; i < as.length; i++) {
if (as[i] !== bs[i]) {
return false;
}
}

return true;
}

/**
* If present, `whiteLabel` is expected to come right after in each case.
*/
const PROPER_ORDERS = [
['zigbeeModel', 'fingerprint', 'model', 'vendor', 'description'],
['fingerprint', 'zigbeeModel', 'model', 'vendor', 'description'],
['zigbeeModel', 'model', 'vendor', 'description'],
['fingerprint', 'model', 'vendor', 'description'],
];

let total = 0;
let invalid = 0;
let invalidWhiteLabel = 0;
let invalidDefinitions = [];

for (const module of readdirSync(SOURCE_DIR)) {
if (module === 'index.ts' || !module.endsWith('.ts')) {
continue;
}

const filePath = path.join(SOURCE_DIR, module);
const fileCode = readFileSync(filePath, 'utf8');
const descriptions = fileCode.match(/^[ ]{8}description:(.*)$/gm);

if (descriptions) {
// `description` not on single line
for (const description of descriptions) {
if (!description.endsWith(`,`)) {
console.log(`[${module}] multi-line description ${filePath}`);
}
}
}

const {definitions} = await import(`../${DIST_DIR}/${module.replace('.ts', '.js')}`);

for (let i = 0; i < definitions.length; i++) {
const definition = definitions[i];
const keys = Object.keys(definition);
let proper = -1;
let j = 0;

for (const order of PROPER_ORDERS) {
const keysSub = keys.slice(0, order.length);

if (arrayStrictEquals(order, keysSub)) {
proper = j;

break;
}

j++;
}

if (proper > -1) {
if (keys.includes('whiteLabel')) {
// ending with `whiteLabel` (no config/features)
if (keys.length === PROPER_ORDERS[proper].length + 1) {
invalidDefinitions.push(definition.model);
}

if (keys[PROPER_ORDERS[proper].length] !== 'whiteLabel') {
proper = -1;
invalidWhiteLabel++;
}
} else {
// ending with `description` (no config/features)
if (keys.length === PROPER_ORDERS[proper].length) {
invalidDefinitions.push(definition.model);
}
}
}

if (proper === -1) {
invalid++;

const newFileIndex = fileCode.indexOf(` model: '${definition.model}'`);
const newlineCount = (fileCode.slice(0, newFileIndex).match(/\n/g) || []).length;

console.log(`[${module}] ${definition.model} (index: ${i}) ${filePath}:${newlineCount + 1}`);
}

total++;
}
}

console.log(`\nInvalid: ${invalid} (from White Label: ${invalidWhiteLabel})`);
console.log(`Invalid definitions: ${invalidDefinitions.join(', ') || 'none'}`);
console.log(`Total: ${total}`);
console.log(
`/!\\ DO NOT prettier AFTER FIXING THESE until refactor-definition-lambda.mjs executed (avoid creating new description multi-line issues)`,
);
Loading
Loading