From a40ab434cadd024a6d51cf37894c6f011fbd735c Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Thu, 19 Nov 2020 15:57:47 +0000 Subject: [PATCH] Generator: Merge package.json when updating plugin framework --- .../generator-joplin/generators/app/index.js | 51 ++++++++++++++++--- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/packages/generator-joplin/generators/app/index.js b/packages/generator-joplin/generators/app/index.js index 042ea5e01..520bb496c 100644 --- a/packages/generator-joplin/generators/app/index.js +++ b/packages/generator-joplin/generators/app/index.js @@ -4,6 +4,29 @@ const Generator = require('yeoman-generator'); const chalk = require('chalk'); const yosay = require('yosay'); +function mergePackageKey(parentKey, source, dest) { + const output = Object.assign({}, dest); + + for (const k in source) { + if (!(k in output)) { + // If the key doesn't exist in the destination, add it + output[k] = source[k]; + } else if (parentKey === 'devDependencies') { + // If we are dealing with the dependencies, overwrite with the + // version from source. + output[k] = source[k]; + } else if (typeof source[k] === 'object' && !Array.isArray(k) && source[k] !== null) { + // If it's an object, recursively process it + output[k] = mergePackageKey(k, source[k], output[k]); + } else { + // Otherwise, the default is to preserve the destination key + output[k] = dest[k]; + } + } + + return output; +} + module.exports = class extends Generator { constructor(args, opts) { @@ -18,8 +41,6 @@ module.exports = class extends Generator { } } - - async prompting() { this.log(yosay(`Welcome to the fine ${chalk.red('generator-joplin')} generator!`)); @@ -110,12 +131,28 @@ module.exports = class extends Generator { if (this.options.update && noUpdateFiles.includes(file)) continue; const destFile = file.replace(/_TEMPLATE/, ''); + const destFilePath = this.destinationPath(destFile); - this.fs.copyTpl( - this.templatePath(file), - this.destinationPath(destFile), - this.props - ); + if (this.options.update && destFile === 'package.json' && this.fs.exists(destFilePath)) { + const destContent = this.fs.readJSON(destFilePath); + + this.fs.copy( + this.templatePath(file), + destFilePath, { + process: (sourceBuffer) => { + const sourceContent = JSON.parse(sourceBuffer.toString()); + const newContent = mergePackageKey(null, sourceContent, destContent); + return JSON.stringify(newContent, null, 2); + }, + } + ); + } else { + this.fs.copyTpl( + this.templatePath(file), + destFilePath, + this.props + ); + } } this.fs.copy(