From 1e77ddf2127f21ea86b72faea37894e277ee6078 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Fri, 24 May 2024 14:44:19 +0100 Subject: [PATCH 01/13] feat: Add script to update version --- package-lock.json | 468 +++++++++------------------------------- package.json | 1 + src/commands/version.js | 276 ++++++++++++++++++++++++ 3 files changed, 373 insertions(+), 372 deletions(-) create mode 100644 src/commands/version.js diff --git a/package-lock.json b/package-lock.json index 58cec37..d986b60 100644 --- a/package-lock.json +++ b/package-lock.json @@ -55,6 +55,7 @@ "rework-visit": "^1.0.0", "sass": "^1.55.0", "sass-loader": "^12.1.0", + "semver": "^7.6.2", "stylelint": "15.0.0", "stylelint-scss": "^5.3.2", "stylelint-webpack-plugin": "^4.1.1", @@ -148,6 +149,14 @@ "url": "https://opencollective.com/babel" } }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/@babel/eslint-parser": { "version": "7.23.3", "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.23.3.tgz", @@ -165,6 +174,14 @@ "eslint": "^7.5.0 || ^8.0.0" } }, + "node_modules/@babel/eslint-parser/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/@babel/eslint-plugin": { "version": "7.23.5", "resolved": "https://registry.npmjs.org/@babel/eslint-plugin/-/eslint-plugin-7.23.5.tgz", @@ -231,6 +248,14 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/@babel/helper-create-class-features-plugin": { "version": "7.23.7", "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.23.7.tgz", @@ -253,6 +278,14 @@ "@babel/core": "^7.0.0" } }, + "node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/@babel/helper-create-regexp-features-plugin": { "version": "7.22.15", "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.22.15.tgz", @@ -269,6 +302,14 @@ "@babel/core": "^7.0.0" } }, + "node_modules/@babel/helper-create-regexp-features-plugin/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/@babel/helper-define-polyfill-provider": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.4.4.tgz", @@ -1764,6 +1805,14 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/preset-env/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/@babel/preset-modules": { "version": "0.1.6-no-external-plugins", "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz", @@ -3393,36 +3442,6 @@ } } }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/@typescript-eslint/parser": { "version": "6.18.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.18.1.tgz", @@ -3532,36 +3551,6 @@ } } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/@typescript-eslint/utils": { "version": "6.18.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.18.1.tgz", @@ -3586,36 +3575,6 @@ "eslint": "^7.0.0 || ^8.0.0" } }, - "node_modules/@typescript-eslint/utils/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/utils/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/utils/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/@typescript-eslint/visitor-keys": { "version": "6.18.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.18.1.tgz", @@ -4405,6 +4364,15 @@ "node": ">=8" } }, + "node_modules/babel-plugin-istanbul/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/babel-plugin-jest-hoist": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", @@ -4433,6 +4401,14 @@ "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" } }, + "node_modules/babel-plugin-polyfill-corejs2/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/babel-plugin-polyfill-corejs3": { "version": "0.8.7", "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.8.7.tgz", @@ -5375,36 +5351,6 @@ "webpack": "^5.0.0" } }, - "node_modules/css-loader/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/css-loader/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/css-loader/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/css-select": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/css-select/-/css-select-4.3.0.tgz", @@ -6379,6 +6325,14 @@ "node": "*" } }, + "node_modules/eslint-plugin-import/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/eslint-plugin-jsdoc": { "version": "39.9.1", "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-39.9.1.tgz", @@ -6410,36 +6364,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint-plugin-jsdoc/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/eslint-plugin-jsdoc/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/eslint-plugin-jsdoc/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/eslint-plugin-jsx-a11y": { "version": "6.8.0", "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.8.0.tgz", @@ -6596,6 +6520,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/eslint-plugin-react/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/eslint-rule-composer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/eslint-rule-composer/-/eslint-rule-composer-0.3.0.tgz", @@ -6840,17 +6772,6 @@ "node": ">= 4" } }, - "node_modules/eslint/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/eslint/node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -6862,20 +6783,6 @@ "node": "*" } }, - "node_modules/eslint/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/eslint/node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -6898,11 +6805,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/espree": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.1.tgz", @@ -8701,39 +8603,6 @@ "node": ">=10" } }, - "node_modules/istanbul-lib-instrument/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, "node_modules/istanbul-lib-report": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", @@ -8757,18 +8626,6 @@ "node": ">=8" } }, - "node_modules/istanbul-lib-report/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/istanbul-lib-report/node_modules/make-dir": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", @@ -8784,21 +8641,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/istanbul-lib-report/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/istanbul-lib-report/node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -8811,12 +8653,6 @@ "node": ">=8" } }, - "node_modules/istanbul-lib-report/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, "node_modules/istanbul-lib-source-maps": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", @@ -10143,33 +9979,6 @@ "node": ">=8" } }, - "node_modules/jest-snapshot/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/jest-snapshot/node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -10182,12 +9991,6 @@ "node": ">=8" } }, - "node_modules/jest-snapshot/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, "node_modules/jest-util": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", @@ -10856,6 +10659,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/makeerror": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", @@ -11315,36 +11126,6 @@ "node": ">=10" } }, - "node_modules/normalize-package-data/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/normalize-package-data/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/normalize-package-data/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -12075,36 +11856,6 @@ "webpack": "^5.0.0" } }, - "node_modules/postcss-loader/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/postcss-loader/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/postcss-loader/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/postcss-media-query-parser": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/postcss-media-query-parser/-/postcss-media-query-parser-0.2.3.tgz", @@ -13571,11 +13322,14 @@ } }, "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "7.6.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", + "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", "bin": { "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, "node_modules/serialize-javascript": { @@ -15360,31 +15114,6 @@ "node": ">=8" } }, - "node_modules/ts-loader/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/ts-loader/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/ts-loader/node_modules/source-map": { "version": "0.7.4", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.4.tgz", @@ -15404,11 +15133,6 @@ "node": ">=8" } }, - "node_modules/ts-loader/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/tsconfig-paths": { "version": "3.15.0", "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", diff --git a/package.json b/package.json index 2bff85f..91a0a99 100644 --- a/package.json +++ b/package.json @@ -84,6 +84,7 @@ "rework-visit": "^1.0.0", "sass": "^1.55.0", "sass-loader": "^12.1.0", + "semver": "^7.6.2", "stylelint": "15.0.0", "stylelint-scss": "^5.3.2", "stylelint-webpack-plugin": "^4.1.1", diff --git a/src/commands/version.js b/src/commands/version.js new file mode 100644 index 0000000..56859e6 --- /dev/null +++ b/src/commands/version.js @@ -0,0 +1,276 @@ +const dirsExist = require('../utils/dirs-exist'); +const { terminal } = require('terminal-kit'); +const fs = require('fs'); +const path = require('path'); // Path module +const semver = require('semver'); + +exports.command = 'version [type] [projects]'; +exports.desc = 'Run an npm version bump process.'; +exports.builder = (yargs) => { + yargs.option('type', { + describe: 'type of version to bump.', + default: 'string', + type: 'string', + }); + + yargs.positional('projects', { + describe: 'Comma separated list of projects to compile.', + type: 'string', + default: '', + }); + + yargs.option('site', { + describe: `Run the process from the root of a site, such as from wp-content.`, + default: false, + type: 'boolean', + }); +}; +exports.handler = async ({ type = '', projects = '', site = false }) => { + // with no projects listed it returns a empty array + const projectsList = projects.split(',').filter((item) => item.length > 0); + const excludeDirs = ['node_modules', 'dist', 'build', 'vendor', 'vendor_prefixed']; + const targetFiles = ['package.json', 'style.css', 'plugin.php']; + + const hasTargetDirs = dirsExist(targetDirs); + + const isAllProjects = (site || hasTargetDirs) && !projects; + + /** + * Function to search for all files which are not in the excluded directories + * + * @param {string} basePath - The base directory to start searching from. + * @param {Array} directoryNames - An array of directory names to match. + * @returns {Array} - An array of matching directory paths. + */ + const getAllFiles = (dirPath, arrayOfFiles) => { + const files = fs.readdirSync(dirPath); + + arrayOfFiles = arrayOfFiles || []; + + files.forEach((file) => { + const filePath = path.join(dirPath, file); + if (fs.statSync(filePath).isDirectory()) { + if (!excludeDirs.includes(file)) { + arrayOfFiles = getAllFiles(filePath, arrayOfFiles); + } + } else { + arrayOfFiles.push(filePath); + } + }); + + return arrayOfFiles; + }; + + /** + * Function to find the files we want to use. + * @param {string} baseDirs - Base directory to search from. + * @param {Array} targets - Files we want to find + */ + const findTargetFiles = (baseDirs, targets) => { + baseDirs.forEach((baseDir) => { + if (fs.existsSync(baseDir) && fs.statSync(baseDir).isDirectory()) { + const allFiles = getAllFiles(baseDir); + allFiles.forEach((filePath) => { + const fileName = path.basename(filePath); + if (targets.includes(fileName)) { + incrementVersionNumber(fileName, filePath, type); + } + }); + } else { + console.error(`Directory not found: ${baseDir}`); + } + }); + }; + + /** + * Recursively searches for directories matching given names. + * @param {string} basePath - The base directory to start searching from. + * @param {Array} directoryNames - An array of directory names to match. + * @returns {Array} - An array of matching directory paths. + */ + function findMatchingDirectories(basePath, directoryNames) { + let matchingDirectories = []; + searchDirectory(basePath, directoryNames, matchingDirectories); + return matchingDirectories; + } + + /** + * Helper function to search directories recursively. + * @param {string} currentPath - The current directory path. + * @param {Array} directoryNames - An array of directory names to match. + * @param {Array} matchingDirectories - The array where matching directories are stored. + */ + function searchDirectory(currentPath, directoryNames, matchingDirectories) { + let items; + try { + items = fs.readdirSync(currentPath); + } catch (err) { + console.error(`Error reading directory ${currentPath}: ${err.message}`); + return; + } + + items.forEach((item) => { + const itemPath = path.join(currentPath, item); + let stats; + try { + stats = fs.statSync(itemPath); + } catch (err) { + console.error(`Error getting stats of item ${itemPath}: ${err.message}`); + return; + } + + if (stats.isDirectory()) { + if (directoryNames.includes(item)) { + matchingDirectories.push(itemPath); + } + // Recursively search inside this directory + searchDirectory(itemPath, directoryNames, matchingDirectories); + } + }); + } + + /** + * Function to increment the version in a package.json file. + * @param {string} dir - File path + * @param {string} type - increment type + */ + function incrementPackageJsonVersion(dir, type) { + if (fs.existsSync(dir)) { + try { + const packageJson = JSON.parse(fs.readFileSync(dir, 'utf-8')); + const oldVersion = packageJson.version; + const newVersion = incrementVersionString(oldVersion, type); + packageJson.version = newVersion; + fs.writeFileSync(dir, JSON.stringify(packageJson, null, 2), 'utf-8'); + terminal(`#${dir}: ${oldVersion} -> ${newVersion}\n`); + } catch (err) { + console.error(`Error incrementing version in ${dir}: ${err.message}`); + } + } + } + /** + * Function to increment the version in a css file + * @param {string} dir - File path + * @param {string} type - Increment type. + */ + function incrementStylesCssVersion(dir, type) { + if (fs.existsSync(dir)) { + try { + let content = fs.readFileSync(dir, 'utf-8'); + const versionRegex = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; + const match = content.match(versionRegex); + if (match) { + const oldVersion = match[1]; + const newVersion = incrementVersionString(oldVersion, type); + content = content.replace(versionRegex, `Version: ${newVersion}`); + fs.writeFileSync(dir, content, 'utf-8'); + terminal(`#${dir}: ${oldVersion} -> ${newVersion}\n`); + } + } catch (err) { + console.error(`Error incrementing version in ${dir}: ${err.message}`); + } + } + } + + /** + * Function to increment the version in a php file + * @param {string} dir - File path + * @param {string} type - Increment type. + */ + function incrementPluginPhpVersion(dir, type) { + if (fs.existsSync(dir)) { + try { + let content = fs.readFileSync(dir, 'utf-8'); + const versionRegex = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; + const match = content.match(versionRegex); + if (match) { + const oldVersion = match[1]; + const newVersion = incrementVersionString(oldVersion, type); + content = content.replace(versionRegex, `Version: ${newVersion}`); + fs.writeFileSync(dir, content, 'utf-8'); + terminal(`#${dir}: ${oldVersion} -> ${newVersion}\n`); + } + } catch (err) { + console.error(`Error incrementing version in ${dir}: ${err.message}`); + } + } + } + + /** + * Function to increment the current version. + * @param {string} version - current version + * @param {string} type - type of version to increase. + * @returns {string} version - updated version + */ + function incrementVersionString(version, type) { + console.log(typeof version); + if (!semver.valid(version)) { + throw new Error(`Invalid version: ${version}`); + } + const [baseType, prerelease] = type.split(':'); + if (type === 'beta' && semver.prerelease(version)) { + return semver.inc(version, 'prerelease', 'beta'); + } + if (prerelease === 'beta') { + // Handle pre-release increment + if (semver.prerelease(version)) { + switch (baseType) { + case 'major': + return semver.inc(version, 'premajor', 'beta'); + case 'minor': + return semver.inc(version, 'preminor', 'beta'); + case 'patch': + return semver.inc(version, 'prepatch', 'beta'); + default: + throw new Error(`Could not change prerelease version`); + } + } + // Convert stable version to pre-release + return semver.inc(`${semver.inc(version, baseType)}-beta.0`, 'prerelease', 'beta'); + } else { + // Handle stable version increment + return semver.inc(version, baseType); + } + } + + /** + * Function to increase the version number depending on which file is found. + * @param {string} file - file name + * @param {string} path - file path + * @param {string} type - type of version to increment. + */ + function incrementVersionNumber(file, path, type) { + switch (file) { + case 'package.json': + incrementPackageJsonVersion(path, type); + break; + case 'plugin.php': + incrementPluginPhpVersion(path, type); + break; + case 'style.css': + incrementStylesCssVersion(path, type); + break; + default: + throw new Error(`Invalid file: ${file}`); + } + } + + try { + if (projectsList.length === 0 && !isAllProjects) { + terminal('No Projects Found\n'); + } else if (isAllProjects) { + terminal('searching all projects.....\n'); + findTargetFiles(targetDirs, targetFiles); + } else { + terminal('finding all projects to increment....\n'); + const directoriesToSearch = findMatchingDirectories( + path.resolve(process.cwd()), + projectsList, + ); + findTargetFiles(directoriesToSearch, targetFiles); + } + } catch (e) { + terminal.red(e); + process.exit(1); + } +}; From 9637f567f6dc7c918c4f07a7393c6c0725a1fbcd Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Fri, 24 May 2024 14:49:29 +0100 Subject: [PATCH 02/13] 1.4.0 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index d986b60..6456039 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@bigbite/build-tools", - "version": "1.3.2", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@bigbite/build-tools", - "version": "1.3.2", + "version": "1.4.0", "license": "MIT", "dependencies": { "@babel/core": "^7.14.8", diff --git a/package.json b/package.json index 91a0a99..8ed2a37 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bigbite/build-tools", - "version": "1.3.2", + "version": "1.4.0", "description": "Provides configuration for the Big Bite Build Tools.", "author": "Paul Taylor (https://github.com/ampersarnie)", "engines": { From 6e7e152b7941c5af0a3a1b30d42dc32c08b14ba5 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Fri, 24 May 2024 15:22:38 +0100 Subject: [PATCH 03/13] fix: remove type of console log --- src/commands/version.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/commands/version.js b/src/commands/version.js index 56859e6..138ccdf 100644 --- a/src/commands/version.js +++ b/src/commands/version.js @@ -203,7 +203,6 @@ exports.handler = async ({ type = '', projects = '', site = false }) => { * @returns {string} version - updated version */ function incrementVersionString(version, type) { - console.log(typeof version); if (!semver.valid(version)) { throw new Error(`Invalid version: ${version}`); } From 2eed3b4f1e99460c7081ad47eaaf79b03d12c087 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Tue, 18 Jun 2024 16:32:17 +0100 Subject: [PATCH 04/13] refactor: use enum instead of switch --- src/commands/version.js | 46 +++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/src/commands/version.js b/src/commands/version.js index 138ccdf..105ddbf 100644 --- a/src/commands/version.js +++ b/src/commands/version.js @@ -28,7 +28,7 @@ exports.builder = (yargs) => { exports.handler = async ({ type = '', projects = '', site = false }) => { // with no projects listed it returns a empty array const projectsList = projects.split(',').filter((item) => item.length > 0); - const excludeDirs = ['node_modules', 'dist', 'build', 'vendor', 'vendor_prefixed']; + const excludeDirs = ['node_modules', 'dist', 'build', 'vendor', 'vendor_prefixed', '.yalc']; const targetFiles = ['package.json', 'style.css', 'plugin.php']; const hasTargetDirs = dirsExist(targetDirs); @@ -115,7 +115,7 @@ exports.handler = async ({ type = '', projects = '', site = false }) => { try { stats = fs.statSync(itemPath); } catch (err) { - console.error(`Error getting stats of item ${itemPath}: ${err.message}`); + console.error(`Error getting item ${itemPath}: ${err.message}`); return; } @@ -131,20 +131,20 @@ exports.handler = async ({ type = '', projects = '', site = false }) => { /** * Function to increment the version in a package.json file. - * @param {string} dir - File path + * @param {string} file - File to increment * @param {string} type - increment type */ - function incrementPackageJsonVersion(dir, type) { - if (fs.existsSync(dir)) { + function incrementPackageJsonVersion(file, type) { + if (fs.existsSync(file)) { try { - const packageJson = JSON.parse(fs.readFileSync(dir, 'utf-8')); + const packageJson = JSON.parse(fs.readFileSync(file, 'utf-8')); const oldVersion = packageJson.version; const newVersion = incrementVersionString(oldVersion, type); packageJson.version = newVersion; - fs.writeFileSync(dir, JSON.stringify(packageJson, null, 2), 'utf-8'); - terminal(`#${dir}: ${oldVersion} -> ${newVersion}\n`); + fs.writeFileSync(file, JSON.stringify(packageJson, null, 2), 'utf-8'); + terminal(`#${file}: ${oldVersion} -> ${newVersion}\n`); } catch (err) { - console.error(`Error incrementing version in ${dir}: ${err.message}`); + console.error(`Error incrementing version in ${file}: ${err.message}`); } } } @@ -213,25 +213,21 @@ exports.handler = async ({ type = '', projects = '', site = false }) => { if (prerelease === 'beta') { // Handle pre-release increment if (semver.prerelease(version)) { - switch (baseType) { - case 'major': - return semver.inc(version, 'premajor', 'beta'); - case 'minor': - return semver.inc(version, 'preminor', 'beta'); - case 'patch': - return semver.inc(version, 'prepatch', 'beta'); - default: - throw new Error(`Could not change prerelease version`); - } + const releaseEnum = Object.freeze({ + major: 'premajor', + minor: 'preminor', + patch: 'prepatch', + }); + const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; + semver.inc(version, releaseType, prerelease); + // Convert stable version to pre-release + return semver.inc(`${semver.inc(version, baseType)}-beta.0`, 'prerelease', 'beta'); + } else { + // Handle stable version increment + return semver.inc(version, baseType); } - // Convert stable version to pre-release - return semver.inc(`${semver.inc(version, baseType)}-beta.0`, 'prerelease', 'beta'); - } else { - // Handle stable version increment - return semver.inc(version, baseType); } } - /** * Function to increase the version number depending on which file is found. * @param {string} file - file name From 51dc3d97525ef0e958c5988352cfc35ddcb86eb1 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Thu, 27 Jun 2024 11:41:36 +0100 Subject: [PATCH 05/13] feat: refactor of existing + added RC functionality --- src/commands/version.js | 264 ++++++++++++--------------------- src/utils/increment-version.js | 150 +++++++++++++++++++ 2 files changed, 242 insertions(+), 172 deletions(-) create mode 100644 src/utils/increment-version.js diff --git a/src/commands/version.js b/src/commands/version.js index 105ddbf..b11496d 100644 --- a/src/commands/version.js +++ b/src/commands/version.js @@ -1,15 +1,18 @@ const dirsExist = require('../utils/dirs-exist'); const { terminal } = require('terminal-kit'); const fs = require('fs'); -const path = require('path'); // Path module -const semver = require('semver'); +const path = require('path'); +const { + incrementPackageJsonVersion, + incrementVersionNumber, +} = require('./../utils/increment-version'); exports.command = 'version [type] [projects]'; exports.desc = 'Run an npm version bump process.'; exports.builder = (yargs) => { yargs.option('type', { describe: 'type of version to bump.', - default: 'string', + default: '', type: 'string', }); @@ -18,23 +21,14 @@ exports.builder = (yargs) => { type: 'string', default: '', }); - - yargs.option('site', { - describe: `Run the process from the root of a site, such as from wp-content.`, - default: false, - type: 'boolean', - }); }; -exports.handler = async ({ type = '', projects = '', site = false }) => { - // with no projects listed it returns a empty array +exports.handler = async ({ type = '', projects = '' }) => { const projectsList = projects.split(',').filter((item) => item.length > 0); const excludeDirs = ['node_modules', 'dist', 'build', 'vendor', 'vendor_prefixed', '.yalc']; - const targetFiles = ['package.json', 'style.css', 'plugin.php']; - + const docCommentPattern = /\bVersion:\s*([^\r\n]*)/; const hasTargetDirs = dirsExist(targetDirs); - - const isAllProjects = (site || hasTargetDirs) && !projects; - + const isAllProjects = hasTargetDirs && !projects; + const incrementType = type.toLowerCase(); /** * Function to search for all files which are not in the excluded directories * @@ -42,11 +36,9 @@ exports.handler = async ({ type = '', projects = '', site = false }) => { * @param {Array} directoryNames - An array of directory names to match. * @returns {Array} - An array of matching directory paths. */ - const getAllFiles = (dirPath, arrayOfFiles) => { + const getAllFiles = (dirPath, arrayOfFiles = []) => { const files = fs.readdirSync(dirPath); - arrayOfFiles = arrayOfFiles || []; - files.forEach((file) => { const filePath = path.join(dirPath, file); if (fs.statSync(filePath).isDirectory()) { @@ -62,50 +54,96 @@ exports.handler = async ({ type = '', projects = '', site = false }) => { }; /** - * Function to find the files we want to use. - * @param {string} baseDirs - Base directory to search from. - * @param {Array} targets - Files we want to find + * Function to find target files to increment + * + * @param {array} baseDirs - Directories to search + * @param {string} releaseType - version type to increment. */ - const findTargetFiles = (baseDirs, targets) => { + const findTargetFiles = (baseDirs, releaseType) => { + if (projectsList.length === 0) { + const currentDir = process.cwd(); + searchDirectoryForVersionComment(currentDir, releaseType); + } + baseDirs.forEach((baseDir) => { if (fs.existsSync(baseDir) && fs.statSync(baseDir).isDirectory()) { const allFiles = getAllFiles(baseDir); allFiles.forEach((filePath) => { const fileName = path.basename(filePath); - if (targets.includes(fileName)) { - incrementVersionNumber(fileName, filePath, type); + + if (containsVersion(filePath)) { + incrementVersionNumber(filePath, releaseType); + } + + if (fileName === 'package.json') { + incrementPackageJsonVersion(filePath, releaseType); } }); } else { - console.error(`Directory not found: ${baseDir}`); + console.error(`\x1b[31mDirectory not found: ${baseDir}\x1b[0m`); } }); }; /** - * Recursively searches for directories matching given names. - * @param {string} basePath - The base directory to start searching from. - * @param {Array} directoryNames - An array of directory names to match. - * @returns {Array} - An array of matching directory paths. + * Function to search file for version in doc comment + * + * @param {string} currentDir - Current directory + * @param {string} releaseType - version type to increment. */ - function findMatchingDirectories(basePath, directoryNames) { + const searchDirectoryForVersionComment = (currentDir, releaseType) => { + const files = fs.readdirSync(currentDir); + + files.forEach((file) => { + const filePath = path.join(currentDir, file); + + if (fs.statSync(filePath).isFile() && containsVersion(filePath)) { + incrementVersionNumber(filePath, releaseType); + } + if (file === 'package.json') { + incrementPackageJsonVersion(filePath, releaseType); + } + }); + }; + + /** + * Function to check if a file contains the version + * @param {string} filePath - file path to file being checked. + * @returns {boolean} - true or false if version exists. + */ + const containsVersion = (filePath) => { + try { + const content = fs.readFileSync(filePath, 'utf8'); + return docCommentPattern.test(content); + } catch (err) { + console.error(`\x1b[31mError reading file ${filePath}: ${err.message}\x1b[0m`); + return false; + } + }; + + /** + * Function to find matching directories + * @param {string} basePath - Current location + * @returns {array} - array of directories to search + */ + const findMatchingDirectories = (basePath, projectName) => { let matchingDirectories = []; - searchDirectory(basePath, directoryNames, matchingDirectories); + searchDirectory(basePath, projectName, matchingDirectories); return matchingDirectories; - } + }; /** - * Helper function to search directories recursively. - * @param {string} currentPath - The current directory path. - * @param {Array} directoryNames - An array of directory names to match. - * @param {Array} matchingDirectories - The array where matching directories are stored. + * Function to search specific directory + * @param {string} currentPath - Current location + * @param {string} projectName - Project to search + * @param {array} matchingDirectories - Directories to search */ - function searchDirectory(currentPath, directoryNames, matchingDirectories) { + const searchDirectory = (currentPath, projectName, matchingDirectories) => { let items; try { items = fs.readdirSync(currentPath); } catch (err) { - console.error(`Error reading directory ${currentPath}: ${err.message}`); + console.error(`\x1b[31mError reading directory ${currentPath}: ${err.message}\x1b[0m`); return; } @@ -115,154 +153,36 @@ exports.handler = async ({ type = '', projects = '', site = false }) => { try { stats = fs.statSync(itemPath); } catch (err) { - console.error(`Error getting item ${itemPath}: ${err.message}`); + console.error(`\x1b[31mError getting item ${itemPath}: ${err.message}\x1b[0m`); return; } if (stats.isDirectory()) { - if (directoryNames.includes(item)) { + if (item.includes(projectName)) { matchingDirectories.push(itemPath); } // Recursively search inside this directory - searchDirectory(itemPath, directoryNames, matchingDirectories); + searchDirectory(itemPath, projectName, matchingDirectories); } }); - } - - /** - * Function to increment the version in a package.json file. - * @param {string} file - File to increment - * @param {string} type - increment type - */ - function incrementPackageJsonVersion(file, type) { - if (fs.existsSync(file)) { - try { - const packageJson = JSON.parse(fs.readFileSync(file, 'utf-8')); - const oldVersion = packageJson.version; - const newVersion = incrementVersionString(oldVersion, type); - packageJson.version = newVersion; - fs.writeFileSync(file, JSON.stringify(packageJson, null, 2), 'utf-8'); - terminal(`#${file}: ${oldVersion} -> ${newVersion}\n`); - } catch (err) { - console.error(`Error incrementing version in ${file}: ${err.message}`); - } - } - } - /** - * Function to increment the version in a css file - * @param {string} dir - File path - * @param {string} type - Increment type. - */ - function incrementStylesCssVersion(dir, type) { - if (fs.existsSync(dir)) { - try { - let content = fs.readFileSync(dir, 'utf-8'); - const versionRegex = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; - const match = content.match(versionRegex); - if (match) { - const oldVersion = match[1]; - const newVersion = incrementVersionString(oldVersion, type); - content = content.replace(versionRegex, `Version: ${newVersion}`); - fs.writeFileSync(dir, content, 'utf-8'); - terminal(`#${dir}: ${oldVersion} -> ${newVersion}\n`); - } - } catch (err) { - console.error(`Error incrementing version in ${dir}: ${err.message}`); - } - } - } - - /** - * Function to increment the version in a php file - * @param {string} dir - File path - * @param {string} type - Increment type. - */ - function incrementPluginPhpVersion(dir, type) { - if (fs.existsSync(dir)) { - try { - let content = fs.readFileSync(dir, 'utf-8'); - const versionRegex = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; - const match = content.match(versionRegex); - if (match) { - const oldVersion = match[1]; - const newVersion = incrementVersionString(oldVersion, type); - content = content.replace(versionRegex, `Version: ${newVersion}`); - fs.writeFileSync(dir, content, 'utf-8'); - terminal(`#${dir}: ${oldVersion} -> ${newVersion}\n`); - } - } catch (err) { - console.error(`Error incrementing version in ${dir}: ${err.message}`); - } - } - } - - /** - * Function to increment the current version. - * @param {string} version - current version - * @param {string} type - type of version to increase. - * @returns {string} version - updated version - */ - function incrementVersionString(version, type) { - if (!semver.valid(version)) { - throw new Error(`Invalid version: ${version}`); - } - const [baseType, prerelease] = type.split(':'); - if (type === 'beta' && semver.prerelease(version)) { - return semver.inc(version, 'prerelease', 'beta'); - } - if (prerelease === 'beta') { - // Handle pre-release increment - if (semver.prerelease(version)) { - const releaseEnum = Object.freeze({ - major: 'premajor', - minor: 'preminor', - patch: 'prepatch', - }); - const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; - semver.inc(version, releaseType, prerelease); - // Convert stable version to pre-release - return semver.inc(`${semver.inc(version, baseType)}-beta.0`, 'prerelease', 'beta'); - } else { - // Handle stable version increment - return semver.inc(version, baseType); - } - } - } - /** - * Function to increase the version number depending on which file is found. - * @param {string} file - file name - * @param {string} path - file path - * @param {string} type - type of version to increment. - */ - function incrementVersionNumber(file, path, type) { - switch (file) { - case 'package.json': - incrementPackageJsonVersion(path, type); - break; - case 'plugin.php': - incrementPluginPhpVersion(path, type); - break; - case 'style.css': - incrementStylesCssVersion(path, type); - break; - default: - throw new Error(`Invalid file: ${file}`); - } - } + }; try { if (projectsList.length === 0 && !isAllProjects) { - terminal('No Projects Found\n'); + // Increment projects in current directory + terminal('\x1b[1mIncrementing Projects In \x1b[4mDirectory\x1b[0m...\n'); + searchDirectoryForVersionComment(path.resolve(process.cwd()), incrementType); } else if (isAllProjects) { - terminal('searching all projects.....\n'); - findTargetFiles(targetDirs, targetFiles); + // Increment all projects i.e from wp-content folder + terminal('\x1b[1mIncrementing \x1b[4mAll Projects\x1b[0m...\n'); + findTargetFiles(targetDirs, incrementType); } else { - terminal('finding all projects to increment....\n'); - const directoriesToSearch = findMatchingDirectories( - path.resolve(process.cwd()), - projectsList, + // Increment specified projects + terminal('\x1b[1mIncrementing \x1b[4mList of Projects\x1b[0m...\n'); + const directoriesToSearch = projectsList.flatMap((projectName) => + findMatchingDirectories(path.resolve(process.cwd()), projectName), ); - findTargetFiles(directoriesToSearch, targetFiles); + findTargetFiles(directoriesToSearch, incrementType); } } catch (e) { terminal.red(e); diff --git a/src/utils/increment-version.js b/src/utils/increment-version.js new file mode 100644 index 0000000..343ba2d --- /dev/null +++ b/src/utils/increment-version.js @@ -0,0 +1,150 @@ +const fs = require('fs'); +const { terminal } = require('terminal-kit'); +const semver = require('semver'); +const path = require('path'); + +/** + * Function to normalize a version number to the format MAJOR.MINOR.PATCH. + * @param {string} version - The version number to normalize. + * @returns {string} - The normalized version number. + */ +function normalizeVersion(version) { + const parts = version.split('.'); + + while (parts.length < 3) { + parts.push('0'); + } + + return parts.join('.'); +} + +/** + * Function to increment the current version. + * @param {string} version - current version + * @param {string} type - type of version to increase. + * @returns {string} version - updated version + */ +function incrementVersion(version, type) { + let currentVersion = version; + let normalisedVersion = version.split('.'); + if (normalisedVersion.length < 3) { + currentVersion = normalizeVersion(version); + } + + if (!semver.valid(currentVersion)) { + throw new Error(`Invalid version: ${currentVersion}`); + } + + const [baseType, prerelease] = type.split(':'); + + if (prerelease === 'beta' || prerelease === 'rc') { + if (semver.prerelease(currentVersion)) { + const releaseEnum = Object.freeze({ + major: 'premajor', + minor: 'preminor', + patch: 'prepatch', + }); + const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; + semver.inc(version, releaseType, prerelease); + } + return semver.inc(`${semver.inc(currentVersion, baseType)}-beta.0`, 'prerelease', 'beta'); + } else { + return semver.inc(currentVersion, baseType); + } +} + +/** + * Function to get the version and then save it back to the file. + * @param {string} filePath - file path. + * @param {string} releaseType - type of version to increment. + */ +const incrementVersionNumber = (filePath, releaseType) => { + if (fs.existsSync(filePath)) { + try { + let content = fs.readFileSync(filePath, 'utf-8'); + const versionRegex = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; + const match = content.match(versionRegex); + if (match) { + const oldVersion = match[1]; + let newVersion; + + if (releaseType === '') { + newVersion = determineNextVersion(oldVersion); + } else { + newVersion = incrementVersion(oldVersion, releaseType); + } + + content = content.replace(versionRegex, `Version: ${newVersion}`); + fs.writeFileSync(filePath, content, 'utf-8'); + terminal(`#${filePath}: \x1b[31m${oldVersion} -> \x1b[32m${newVersion}\x1b[0m\n`); + } + } catch (err) { + console.error(`\x1b[31mError incrementing version in ${filePath}: ${err.message}\x1b[0m`); + } + } +}; + +/** + * Function to decide the next version if no version is provided. + * @param {string} version - Current version. + */ +const determineNextVersion = (version) => { + if (!semver.valid(version)) { + throw new Error(`\x1b[31mInvalid version: ${version}\x1b[0m`); + } + if (semver.prerelease(version)) { + return semver.inc(version, 'prerelease'); + } + return semver.inc(version, 'patch'); // Automatically bump to the next patch version. +}; + +/** + * Function to update the package lock to match package.json file + * @param {string} packageJsonPath - file path to package lock file. + */ +const updatePackageLockVersion = (packageJsonPath) => { + const packageLockPath = path.join(path.dirname(packageJsonPath), 'package-lock.json'); + if (fs.existsSync(packageLockPath)) { + try { + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); + const packageLock = JSON.parse(fs.readFileSync(packageLockPath, 'utf8')); + const oldVersion = packageLock.version; + packageLock.version = packageJson.version; + fs.writeFileSync(packageLockPath, JSON.stringify(packageLock, null, 2), 'utf8'); + terminal( + `#${packageLockPath}: \x1b[31m${oldVersion} -> \x1b[32m${packageLock.version}\x1b[0m\n`, + ); + } catch (err) { + console.error(`\x1b[31mError updating version in ${packageLockPath}: ${err.message}\x1b[0m`); + } + } +}; + +/** + * Function to update the version in the package.json files. + * @param {string} filePath - file path. + * @param {string} releaseType - type of version to increment. + */ +const incrementPackageJsonVersion = (filePath, releaseType) => { + try { + const packageJson = JSON.parse(fs.readFileSync(filePath, 'utf8')); + const oldVersion = packageJson.version; + let newVersion; + if (releaseType === '') { + newVersion = determineNextVersion(oldVersion); + } else { + newVersion = incrementVersion(oldVersion, releaseType); + } + packageJson.version = newVersion; + fs.writeFileSync(filePath, JSON.stringify(packageJson, null, 2), 'utf8'); + terminal(`#${filePath}: \x1b[31m${oldVersion} -> \x1b[32m${newVersion}\x1b[0m\n`); + updatePackageLockVersion(filePath); + } catch (err) { + console.error(`\x1b[31mError updating version in file ${filePath}: ${err.message}\x1b[0m`); + } +}; + +module.exports = { + incrementPackageJsonVersion, + incrementVersionNumber, +}; From ef9a075d7763e7bcfd68e38fd9b7cd49000d9f98 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Thu, 27 Jun 2024 14:18:21 +0100 Subject: [PATCH 06/13] refactor: use semver inc --- src/utils/increment-version.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/increment-version.js b/src/utils/increment-version.js index 343ba2d..825a292 100644 --- a/src/utils/increment-version.js +++ b/src/utils/increment-version.js @@ -45,9 +45,9 @@ function incrementVersion(version, type) { patch: 'prepatch', }); const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; - semver.inc(version, releaseType, prerelease); + semver.inc(currentVersion, releaseType, prerelease); } - return semver.inc(`${semver.inc(currentVersion, baseType)}-beta.0`, 'prerelease', 'beta'); + return semver.inc(currentVersion, 'prerelease', prerelease, 0); } else { return semver.inc(currentVersion, baseType); } From aec92ac0761f68ca36711abb05965b6f13a4ba92 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Fri, 5 Jul 2024 11:45:54 +0100 Subject: [PATCH 07/13] refactor: change way of getting files --- src/commands/version.js | 174 +++++-------------------- src/utils/get-package-version.js | 66 ++++++++++ src/utils/get-version-project-paths.js | 75 +++++++++++ src/utils/increment-version.js | 61 ++++----- 4 files changed, 200 insertions(+), 176 deletions(-) create mode 100644 src/utils/get-package-version.js create mode 100644 src/utils/get-version-project-paths.js diff --git a/src/commands/version.js b/src/commands/version.js index b11496d..dea7a94 100644 --- a/src/commands/version.js +++ b/src/commands/version.js @@ -6,6 +6,9 @@ const { incrementPackageJsonVersion, incrementVersionNumber, } = require('./../utils/increment-version'); +const { validateProject } = require('./../utils/projectpaths'); +const { getPackageVersion } = require('./../utils/get-package-version'); +const { findAllProjectPaths } = require('./../utils/get-version-project-paths'); exports.command = 'version [type] [projects]'; exports.desc = 'Run an npm version bump process.'; @@ -24,146 +27,19 @@ exports.builder = (yargs) => { }; exports.handler = async ({ type = '', projects = '' }) => { const projectsList = projects.split(',').filter((item) => item.length > 0); - const excludeDirs = ['node_modules', 'dist', 'build', 'vendor', 'vendor_prefixed', '.yalc']; - const docCommentPattern = /\bVersion:\s*([^\r\n]*)/; const hasTargetDirs = dirsExist(targetDirs); const isAllProjects = hasTargetDirs && !projects; const incrementType = type.toLowerCase(); - /** - * Function to search for all files which are not in the excluded directories - * - * @param {string} basePath - The base directory to start searching from. - * @param {Array} directoryNames - An array of directory names to match. - * @returns {Array} - An array of matching directory paths. - */ - const getAllFiles = (dirPath, arrayOfFiles = []) => { - const files = fs.readdirSync(dirPath); - files.forEach((file) => { - const filePath = path.join(dirPath, file); - if (fs.statSync(filePath).isDirectory()) { - if (!excludeDirs.includes(file)) { - arrayOfFiles = getAllFiles(filePath, arrayOfFiles); - } - } else { - arrayOfFiles.push(filePath); - } - }); + let packages = []; - return arrayOfFiles; - }; - - /** - * Function to find target files to increment - * - * @param {array} baseDirs - Directories to search - * @param {string} releaseType - version type to increment. - */ - const findTargetFiles = (baseDirs, releaseType) => { - if (projectsList.length === 0) { - const currentDir = process.cwd(); - searchDirectoryForVersionComment(currentDir, releaseType); - } - - baseDirs.forEach((baseDir) => { - if (fs.existsSync(baseDir) && fs.statSync(baseDir).isDirectory()) { - const allFiles = getAllFiles(baseDir); - allFiles.forEach((filePath) => { - const fileName = path.basename(filePath); - - if (containsVersion(filePath)) { - incrementVersionNumber(filePath, releaseType); - } - - if (fileName === 'package.json') { - incrementPackageJsonVersion(filePath, releaseType); - } - }); - } else { - console.error(`\x1b[31mDirectory not found: ${baseDir}\x1b[0m`); - } - }); - }; - - /** - * Function to search file for version in doc comment - * - * @param {string} currentDir - Current directory - * @param {string} releaseType - version type to increment. - */ - const searchDirectoryForVersionComment = (currentDir, releaseType) => { - const files = fs.readdirSync(currentDir); - - files.forEach((file) => { - const filePath = path.join(currentDir, file); - - if (fs.statSync(filePath).isFile() && containsVersion(filePath)) { - incrementVersionNumber(filePath, releaseType); - } - if (file === 'package.json') { - incrementPackageJsonVersion(filePath, releaseType); - } - }); - }; - - /** - * Function to check if a file contains the version - * @param {string} filePath - file path to file being checked. - * @returns {boolean} - true or false if version exists. - */ - const containsVersion = (filePath) => { - try { - const content = fs.readFileSync(filePath, 'utf8'); - return docCommentPattern.test(content); - } catch (err) { - console.error(`\x1b[31mError reading file ${filePath}: ${err.message}\x1b[0m`); - return false; - } - }; - - /** - * Function to find matching directories - * @param {string} basePath - Current location - * @returns {array} - array of directories to search - */ - const findMatchingDirectories = (basePath, projectName) => { - let matchingDirectories = []; - searchDirectory(basePath, projectName, matchingDirectories); - return matchingDirectories; - }; - - /** - * Function to search specific directory - * @param {string} currentPath - Current location - * @param {string} projectName - Project to search - * @param {array} matchingDirectories - Directories to search - */ - const searchDirectory = (currentPath, projectName, matchingDirectories) => { - let items; - try { - items = fs.readdirSync(currentPath); - } catch (err) { - console.error(`\x1b[31mError reading directory ${currentPath}: ${err.message}\x1b[0m`); - return; - } - - items.forEach((item) => { - const itemPath = path.join(currentPath, item); - let stats; - try { - stats = fs.statSync(itemPath); - } catch (err) { - console.error(`\x1b[31mError getting item ${itemPath}: ${err.message}\x1b[0m`); - return; - } - - if (stats.isDirectory()) { - if (item.includes(projectName)) { - matchingDirectories.push(itemPath); - } - // Recursively search inside this directory - searchDirectory(itemPath, projectName, matchingDirectories); - } + const updateVersionsInPackages = (packages, incrementType) => { + packages.forEach((pkg) => { + const { verifiedPackageJson, verifiedPackageLock, versionFilePaths } = pkg; + incrementPackageJsonVersion(verifiedPackageJson, verifiedPackageLock, incrementType); + versionFilePaths.forEach((filePath) => { + incrementVersionNumber(filePath, incrementType); + }); }); }; @@ -171,21 +47,39 @@ exports.handler = async ({ type = '', projects = '' }) => { if (projectsList.length === 0 && !isAllProjects) { // Increment projects in current directory terminal('\x1b[1mIncrementing Projects In \x1b[4mDirectory\x1b[0m...\n'); - searchDirectoryForVersionComment(path.resolve(process.cwd()), incrementType); + packages.push(getPackageVersion(path.resolve('./'))); } else if (isAllProjects) { // Increment all projects i.e from wp-content folder terminal('\x1b[1mIncrementing \x1b[4mAll Projects\x1b[0m...\n'); - findTargetFiles(targetDirs, incrementType); + packages = findAllProjectPaths(targetDirs).map((path) => getPackageVersion(path)); } else { // Increment specified projects terminal('\x1b[1mIncrementing \x1b[4mList of Projects\x1b[0m...\n'); - const directoriesToSearch = projectsList.flatMap((projectName) => - findMatchingDirectories(path.resolve(process.cwd()), projectName), + packages = findAllProjectPaths(targetDirs, projectsList).map((path) => + getPackageVersion(path), ); - findTargetFiles(directoriesToSearch, incrementType); + + const packageNames = packages.map((pkg) => pkg.name); + projectsList.map((projectName) => { + if (!packageNames.includes(projectName)) { + terminal.red(`Error: Project ${projectName} does not exist.\n`); + } + packageNames.includes(projectName); + }); } } catch (e) { terminal.red(e); process.exit(1); } + + let validProjects; + + validProjects = packages.filter((pkg) => validateProject(pkg)); + + if (validProjects.length === 0) { + terminal.red(`Error: No projects found\n`); + process.exit(1); + } + + updateVersionsInPackages(validProjects, incrementType); }; diff --git a/src/utils/get-package-version.js b/src/utils/get-package-version.js new file mode 100644 index 0000000..c218815 --- /dev/null +++ b/src/utils/get-package-version.js @@ -0,0 +1,66 @@ +const fs = require('fs'); + +/** + * Function to get the package details from a given path. + * @param {string} projectPath - The path to the project directory. + * @returns {object|boolean} - The package details object or false if not found. + */ +const getPackageVersion = (projectPath) => { + let verifiedPackageJson = false; + let verifiedPackageLock = false; + let name; + const packageJsonPath = `${projectPath}/package.json`; + const packageLockJsonPath = `${projectPath}/package-lock.json`; + + // // Check if already cached + if (packageList[projectPath]) { + return packageList[projectPath]; + } + + // Check for package.json or package-lock.json + let json = {}; + if (fs.existsSync(packageJsonPath)) { + json = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); + verifiedPackageJson = packageJsonPath; + const packageObject = json === Object(json) ? json : {}; + const packageNames = packageObject?.name?.split('/'); + name = packageNames?.[packageNames.length - 1] || ''; + } + + if (fs.existsSync(packageLockJsonPath)) { + verifiedPackageLock = packageLockJsonPath; + } + + // Check for other files with "Version:" + let versionFilePaths = []; + + const files = fs.readdirSync(projectPath); + for (const file of files) { + const filePath = `${projectPath}/${file}`; + if (fs.lstatSync(filePath).isFile()) { + const content = fs.readFileSync(filePath, 'utf8'); + const match = content.match(/Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i); + if (match) { + versionFilePaths.push(filePath); + } + } + } + + // Prepare the package details object + const packageValues = { + path: projectPath, + verifiedPackageJson, + verifiedPackageLock, + versionFilePaths, + name, + }; + + // Cache the result + packageList[projectPath] = packageValues; + + return packageValues; +}; + +module.exports = { + getPackageVersion, +}; diff --git a/src/utils/get-version-project-paths.js b/src/utils/get-version-project-paths.js new file mode 100644 index 0000000..4066a29 --- /dev/null +++ b/src/utils/get-version-project-paths.js @@ -0,0 +1,75 @@ +const fs = require('fs'); + +/** + * Check if a directory exists. + * @param {string} directory - The directory path to check. + * @returns {boolean} - True if the directory exists, otherwise false. + */ +const directoryExists = (directory) => + fs.existsSync(directory) && fs.lstatSync(directory).isDirectory(); + +/** + * Check if a project directory contains relevant files. + * @param {string} projectPath - The path to the project directory. + * @param {string[]} [projectsList] - The list of specific project names to look for. + * @returns {boolean} - True if the project directory contains relevant files, otherwise false. + */ +const isValidProjectDirectory = (projectPath, projectsList) => { + const packageJsonExists = fs.existsSync(`${projectPath}/package.json`); + const packageLockJsonExists = fs.existsSync(`${projectPath}/package-lock.json`); + const versionFileExists = fs.readdirSync(projectPath).some((file) => { + const filePath = `${projectPath}/${file}`; + if (fs.lstatSync(filePath).isFile()) { + const content = fs.readFileSync(filePath, 'utf8'); + return /\bVersion:\s*([^\r\n]*)/.test(content); + } + return false; + }); + + return packageJsonExists || packageLockJsonExists || versionFileExists; +}; + +/** + * Find all project paths within the specified directories, including the current directory. + * @param {string[]} directories - The list of directories to search. + * @param {string[]} [projectsList] - The list of specific project names to look for. + * @returns {string[]} - An array of project paths. + */ +const findAllProjectPaths = (directories, projectsList) => { + let projects = []; + + directories.filter(directoryExists).forEach((directory) => { + fs.readdirSync(directory, { withFileTypes: true }) + .filter((dirent) => dirent.isDirectory()) // Only process directories + .forEach((dirent) => { + const projectPath = path.resolve(directory, dirent.name); + if (!projectsList || projectsList.includes(dirent.name)) { + if (isValidProjectDirectory(projectPath, projectsList)) { + projects.push(projectPath); + } + } + }); + }); + + // Only get current directory if no projects are specified. + if (projectsList.length === 0) { + // Include current directory in the search + const currentDirectory = '.'; + if ( + directoryExists(currentDirectory) && + isValidProjectDirectory(currentDirectory, projectsList) + ) { + projects.push(currentDirectory); + } + } + + if (projects.length <= 0) { + throw new Error('Cannot find any projects.\n'); + } + + return projects; +}; + +module.exports = { + findAllProjectPaths, +}; diff --git a/src/utils/increment-version.js b/src/utils/increment-version.js index 825a292..53d33c4 100644 --- a/src/utils/increment-version.js +++ b/src/utils/increment-version.js @@ -47,7 +47,7 @@ function incrementVersion(version, type) { const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; semver.inc(currentVersion, releaseType, prerelease); } - return semver.inc(currentVersion, 'prerelease', prerelease, 0); + return semver.inc(currentVersion, 'prerelease', prerelease, 1); } else { return semver.inc(currentVersion, baseType); } @@ -98,49 +98,38 @@ const determineNextVersion = (version) => { return semver.inc(version, 'patch'); // Automatically bump to the next patch version. }; -/** - * Function to update the package lock to match package.json file - * @param {string} packageJsonPath - file path to package lock file. - */ -const updatePackageLockVersion = (packageJsonPath) => { - const packageLockPath = path.join(path.dirname(packageJsonPath), 'package-lock.json'); - if (fs.existsSync(packageLockPath)) { - try { - const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - const packageLock = JSON.parse(fs.readFileSync(packageLockPath, 'utf8')); - const oldVersion = packageLock.version; - packageLock.version = packageJson.version; - fs.writeFileSync(packageLockPath, JSON.stringify(packageLock, null, 2), 'utf8'); - terminal( - `#${packageLockPath}: \x1b[31m${oldVersion} -> \x1b[32m${packageLock.version}\x1b[0m\n`, - ); - } catch (err) { - console.error(`\x1b[31mError updating version in ${packageLockPath}: ${err.message}\x1b[0m`); - } - } -}; - /** * Function to update the version in the package.json files. * @param {string} filePath - file path. * @param {string} releaseType - type of version to increment. */ -const incrementPackageJsonVersion = (filePath, releaseType) => { +const incrementPackageJsonVersion = (packageJsonPath, packageLockPath, releaseType) => { try { - const packageJson = JSON.parse(fs.readFileSync(filePath, 'utf8')); - const oldVersion = packageJson.version; - let newVersion; - if (releaseType === '') { - newVersion = determineNextVersion(oldVersion); - } else { - newVersion = incrementVersion(oldVersion, releaseType); + if (fs.existsSync(packageJsonPath)) { + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); + let path = packageJsonPath; + const oldVersion = packageJson.version; + let newVersion; + if (releaseType === '') { + newVersion = determineNextVersion(oldVersion); + } else { + newVersion = incrementVersion(oldVersion, releaseType); + } + packageJson.version = newVersion; + fs.writeFileSync(path, JSON.stringify(packageJson, null, 2), 'utf8'); + terminal(`#${path}: \x1b[31m${oldVersion} -> \x1b[32m${newVersion}\x1b[0m\n`); + if (!fs.existsSync(packageLockPath)) { + return; + } + path = packageLockPath; + const packageJsonLock = JSON.parse(fs.readFileSync(path, 'utf8')); + const lockoldVersion = packageJsonLock.version; + packageJsonLock.version = packageJson.version; + fs.writeFileSync(path, JSON.stringify(packageJsonLock, null, 2), 'utf8'); + terminal(`#${path}: \x1b[31m${lockoldVersion} -> \x1b[32m${newVersion}\x1b[0m\n`); } - packageJson.version = newVersion; - fs.writeFileSync(filePath, JSON.stringify(packageJson, null, 2), 'utf8'); - terminal(`#${filePath}: \x1b[31m${oldVersion} -> \x1b[32m${newVersion}\x1b[0m\n`); - updatePackageLockVersion(filePath); } catch (err) { - console.error(`\x1b[31mError updating version in file ${filePath}: ${err.message}\x1b[0m`); + console.error(`\x1b[31mError updating version in file ${path}: ${err.message}\x1b[0m`); } }; From 3d49247d95863ea4205de470375565777002d10a Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Fri, 5 Jul 2024 14:26:17 +0100 Subject: [PATCH 08/13] fix: change imports --- src/commands/version.js | 1 - src/utils/get-version-project-paths.js | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/commands/version.js b/src/commands/version.js index dea7a94..da4da1e 100644 --- a/src/commands/version.js +++ b/src/commands/version.js @@ -1,6 +1,5 @@ const dirsExist = require('../utils/dirs-exist'); const { terminal } = require('terminal-kit'); -const fs = require('fs'); const path = require('path'); const { incrementPackageJsonVersion, diff --git a/src/utils/get-version-project-paths.js b/src/utils/get-version-project-paths.js index 4066a29..0cb2693 100644 --- a/src/utils/get-version-project-paths.js +++ b/src/utils/get-version-project-paths.js @@ -1,5 +1,5 @@ const fs = require('fs'); - +const path = require('path'); /** * Check if a directory exists. * @param {string} directory - The directory path to check. From 68c5ab6b17e6706e06c6ac7e3758327cda54d61e Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Fri, 5 Jul 2024 15:14:14 +0100 Subject: [PATCH 09/13] fix: don't use length when variable doesn't exist --- src/utils/get-version-project-paths.js | 2 +- src/utils/increment-version.js | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/utils/get-version-project-paths.js b/src/utils/get-version-project-paths.js index 0cb2693..67bc992 100644 --- a/src/utils/get-version-project-paths.js +++ b/src/utils/get-version-project-paths.js @@ -52,7 +52,7 @@ const findAllProjectPaths = (directories, projectsList) => { }); // Only get current directory if no projects are specified. - if (projectsList.length === 0) { + if (!projectsList) { // Include current directory in the search const currentDirectory = '.'; if ( diff --git a/src/utils/increment-version.js b/src/utils/increment-version.js index 53d33c4..6495d42 100644 --- a/src/utils/increment-version.js +++ b/src/utils/increment-version.js @@ -47,6 +47,8 @@ function incrementVersion(version, type) { const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; semver.inc(currentVersion, releaseType, prerelease); } + console.log(currentVersion, 'current version'); + console.log(prerelease, 'pre release'); return semver.inc(currentVersion, 'prerelease', prerelease, 1); } else { return semver.inc(currentVersion, baseType); From a0266c69dd7dd3894c88cb71d33249ac0fe12b15 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Mon, 8 Jul 2024 11:57:52 +0100 Subject: [PATCH 10/13] fix: increment rc properly --- src/utils/increment-version.js | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/utils/increment-version.js b/src/utils/increment-version.js index 6495d42..87a1dd4 100644 --- a/src/utils/increment-version.js +++ b/src/utils/increment-version.js @@ -38,18 +38,14 @@ function incrementVersion(version, type) { const [baseType, prerelease] = type.split(':'); if (prerelease === 'beta' || prerelease === 'rc') { - if (semver.prerelease(currentVersion)) { - const releaseEnum = Object.freeze({ - major: 'premajor', - minor: 'preminor', - patch: 'prepatch', - }); - const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; - semver.inc(currentVersion, releaseType, prerelease); - } - console.log(currentVersion, 'current version'); - console.log(prerelease, 'pre release'); - return semver.inc(currentVersion, 'prerelease', prerelease, 1); + const releaseEnum = Object.freeze({ + major: 'premajor', + minor: 'preminor', + patch: 'prepatch', + prerelease: 'prerelease', + }); + const releaseType = releaseEnum[baseType] ? releaseEnum[baseType] : false; + return semver.inc(currentVersion, releaseType, prerelease, 1); } else { return semver.inc(currentVersion, baseType); } @@ -63,6 +59,7 @@ function incrementVersion(version, type) { const incrementVersionNumber = (filePath, releaseType) => { if (fs.existsSync(filePath)) { try { + console.log('hereee'); let content = fs.readFileSync(filePath, 'utf-8'); const versionRegex = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; const match = content.match(versionRegex); @@ -79,6 +76,8 @@ const incrementVersionNumber = (filePath, releaseType) => { content = content.replace(versionRegex, `Version: ${newVersion}`); fs.writeFileSync(filePath, content, 'utf-8'); terminal(`#${filePath}: \x1b[31m${oldVersion} -> \x1b[32m${newVersion}\x1b[0m\n`); + } else { + console.log('no version found'); } } catch (err) { console.error(`\x1b[31mError incrementing version in ${filePath}: ${err.message}\x1b[0m`); @@ -108,9 +107,13 @@ const determineNextVersion = (version) => { const incrementPackageJsonVersion = (packageJsonPath, packageLockPath, releaseType) => { try { if (fs.existsSync(packageJsonPath)) { + console.log(releaseType, 'release type'); const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); let path = packageJsonPath; const oldVersion = packageJson.version; + if (!packageJson.version) { + return console.error(`\x1b[31mNo version set in ${path} unable to increment\x1b[0m`); + } let newVersion; if (releaseType === '') { newVersion = determineNextVersion(oldVersion); From 61eb285a77ec5d177395691a2085231fbc975466 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Mon, 8 Jul 2024 12:10:52 +0100 Subject: [PATCH 11/13] fix: tidy up console logs --- example-site/package.json | 1 + src/utils/increment-version.js | 4 ---- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/example-site/package.json b/example-site/package.json index 1d39084..7e7254d 100644 --- a/example-site/package.json +++ b/example-site/package.json @@ -1,5 +1,6 @@ { "name": "test-project", + "version": "1.0.0", "prettier": "./../configs/prettier", "eslintConfig": { "extends": "./../configs/eslint" diff --git a/src/utils/increment-version.js b/src/utils/increment-version.js index 87a1dd4..38718e8 100644 --- a/src/utils/increment-version.js +++ b/src/utils/increment-version.js @@ -59,7 +59,6 @@ function incrementVersion(version, type) { const incrementVersionNumber = (filePath, releaseType) => { if (fs.existsSync(filePath)) { try { - console.log('hereee'); let content = fs.readFileSync(filePath, 'utf-8'); const versionRegex = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; const match = content.match(versionRegex); @@ -76,8 +75,6 @@ const incrementVersionNumber = (filePath, releaseType) => { content = content.replace(versionRegex, `Version: ${newVersion}`); fs.writeFileSync(filePath, content, 'utf-8'); terminal(`#${filePath}: \x1b[31m${oldVersion} -> \x1b[32m${newVersion}\x1b[0m\n`); - } else { - console.log('no version found'); } } catch (err) { console.error(`\x1b[31mError incrementing version in ${filePath}: ${err.message}\x1b[0m`); @@ -107,7 +104,6 @@ const determineNextVersion = (version) => { const incrementPackageJsonVersion = (packageJsonPath, packageLockPath, releaseType) => { try { if (fs.existsSync(packageJsonPath)) { - console.log(releaseType, 'release type'); const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); let path = packageJsonPath; const oldVersion = packageJson.version; From df56102331b2b08b38979055bceafa1fdf3524c5 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Mon, 22 Jul 2024 13:36:11 +0100 Subject: [PATCH 12/13] refactor: re-use exisiting functions --- src/commands/version.js | 32 +++--- src/utils/get-package-version.js | 66 ----------- src/utils/get-package.js | 146 +++++++++++++++++++++---- src/utils/get-version-project-paths.js | 75 ------------- src/utils/projectpaths.js | 30 ++++- 5 files changed, 168 insertions(+), 181 deletions(-) delete mode 100644 src/utils/get-package-version.js delete mode 100644 src/utils/get-version-project-paths.js diff --git a/src/commands/version.js b/src/commands/version.js index da4da1e..549319c 100644 --- a/src/commands/version.js +++ b/src/commands/version.js @@ -5,9 +5,9 @@ const { incrementPackageJsonVersion, incrementVersionNumber, } = require('./../utils/increment-version'); -const { validateProject } = require('./../utils/projectpaths'); -const { getPackageVersion } = require('./../utils/get-package-version'); -const { findAllProjectPaths } = require('./../utils/get-version-project-paths'); + +const { findAllProjectPaths, validateProject } = require('./../utils/projectpaths'); +const { getPackage } = require('./../utils/get-package'); exports.command = 'version [type] [projects]'; exports.desc = 'Run an npm version bump process.'; @@ -34,11 +34,18 @@ exports.handler = async ({ type = '', projects = '' }) => { const updateVersionsInPackages = (packages, incrementType) => { packages.forEach((pkg) => { - const { verifiedPackageJson, verifiedPackageLock, versionFilePaths } = pkg; - incrementPackageJsonVersion(verifiedPackageJson, verifiedPackageLock, incrementType); - versionFilePaths.forEach((filePath) => { - incrementVersionNumber(filePath, incrementType); + incrementPackageJsonVersion( + pkg?.package.absolutePath, + pkg?.package_lock.absolutePath, + incrementType, + ); + const fileNames = Object.keys(pkg); + Object.values(pkg).forEach((file, key) => { + if (fileNames[key] !== 'package' && fileNames[key] !== 'package_lock') { + incrementVersionNumber(file.absolutePath, incrementType); + } }); + 8; }); }; @@ -46,16 +53,17 @@ exports.handler = async ({ type = '', projects = '' }) => { if (projectsList.length === 0 && !isAllProjects) { // Increment projects in current directory terminal('\x1b[1mIncrementing Projects In \x1b[4mDirectory\x1b[0m...\n'); - packages.push(getPackageVersion(path.resolve('./'))); + packages.push(getPackage(path.resolve('./'), true)); } else if (isAllProjects) { // Increment all projects i.e from wp-content folder terminal('\x1b[1mIncrementing \x1b[4mAll Projects\x1b[0m...\n'); - packages = findAllProjectPaths(targetDirs).map((path) => getPackageVersion(path)); + packages = findAllProjectPaths(targetDirs, false, true).map((path) => getPackage(path, true)); } else { // Increment specified projects terminal('\x1b[1mIncrementing \x1b[4mList of Projects\x1b[0m...\n'); + packages = findAllProjectPaths(targetDirs, projectsList).map((path) => - getPackageVersion(path), + getPackage(path, true), ); const packageNames = packages.map((pkg) => pkg.name); @@ -71,9 +79,7 @@ exports.handler = async ({ type = '', projects = '' }) => { process.exit(1); } - let validProjects; - - validProjects = packages.filter((pkg) => validateProject(pkg)); + const validProjects = packages.filter((pkg) => validateProject(pkg, true)); if (validProjects.length === 0) { terminal.red(`Error: No projects found\n`); diff --git a/src/utils/get-package-version.js b/src/utils/get-package-version.js deleted file mode 100644 index c218815..0000000 --- a/src/utils/get-package-version.js +++ /dev/null @@ -1,66 +0,0 @@ -const fs = require('fs'); - -/** - * Function to get the package details from a given path. - * @param {string} projectPath - The path to the project directory. - * @returns {object|boolean} - The package details object or false if not found. - */ -const getPackageVersion = (projectPath) => { - let verifiedPackageJson = false; - let verifiedPackageLock = false; - let name; - const packageJsonPath = `${projectPath}/package.json`; - const packageLockJsonPath = `${projectPath}/package-lock.json`; - - // // Check if already cached - if (packageList[projectPath]) { - return packageList[projectPath]; - } - - // Check for package.json or package-lock.json - let json = {}; - if (fs.existsSync(packageJsonPath)) { - json = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - verifiedPackageJson = packageJsonPath; - const packageObject = json === Object(json) ? json : {}; - const packageNames = packageObject?.name?.split('/'); - name = packageNames?.[packageNames.length - 1] || ''; - } - - if (fs.existsSync(packageLockJsonPath)) { - verifiedPackageLock = packageLockJsonPath; - } - - // Check for other files with "Version:" - let versionFilePaths = []; - - const files = fs.readdirSync(projectPath); - for (const file of files) { - const filePath = `${projectPath}/${file}`; - if (fs.lstatSync(filePath).isFile()) { - const content = fs.readFileSync(filePath, 'utf8'); - const match = content.match(/Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i); - if (match) { - versionFilePaths.push(filePath); - } - } - } - - // Prepare the package details object - const packageValues = { - path: projectPath, - verifiedPackageJson, - verifiedPackageLock, - versionFilePaths, - name, - }; - - // Cache the result - packageList[projectPath] = packageValues; - - return packageValues; -}; - -module.exports = { - getPackageVersion, -}; diff --git a/src/utils/get-package.js b/src/utils/get-package.js index 4e5fd97..d5e5ed8 100644 --- a/src/utils/get-package.js +++ b/src/utils/get-package.js @@ -1,4 +1,87 @@ const fs = require('fs'); +const path = require('path'); +const versionPattern = /Version:\s*([\d]+\.[\d]+\.[\d]+(?:-[a-z]+\.[\d]+)?)/i; + +/** + * Retrieves the names of all files in the specified directory. + * + * This function reads the contents of the given directory, filters out the directories, + * and returns an array containing the names of all the files in the directory. + * + * @param {string} dirPath - The path to the directory to read. + * @returns {array} An array of file names in the specified directory. + **/ + +const getFilesInDirectory = (dirPath) => { + return fs.readdirSync(dirPath).filter((file) => fs.statSync(path.join(dirPath, file)).isFile()); +}; + +/** + * Function to check if a file has a specified extension. + * @param {string} filePath - The path to the file. + * @param {string} extension - The extension to check for (e.g., '.json'). + * @returns {boolean} - Returns true if the file has the specified extension, otherwise false. + */ +const hasExtension = (filePath, extension) => { + return path.extname(filePath).toLowerCase() === extension.toLowerCase(); +}; + +/** + * Converts a filename into a variable-friendly name by replacing non-alphanumeric characters with underscores + * and removing the extension. + * + * @param {string} filename - The filename to convert. + * @returns {string} - The converted variable-friendly name. + */ +const convertToVariableFriendlyName = (filename) => { + // Remove the extension + const baseName = filename.split('.').slice(0, -1).join('.'); + // Replace any non-alphanumeric characters with underscores + return baseName.replace(/[^a-zA-Z0-9]/g, '_'); +}; + +/** + * Checks if the specified file contains a version string matching a given pattern. + * + * This function reads the content of the file at the given path and tests it against + * a predefined version pattern. + * + * @param {string} filePath - The path to the file to check for a version string. + * @returns {boolean} True if the file contains a version string matching the pattern, false otherwise. + */ +const containsVersion = (filePath) => { + try { + const content = fs.readFileSync(filePath, 'utf8'); + return versionPattern.test(content); + } catch (err) { + console.error(`Error reading file ${filePath}: ${err.message}`); + return false; + } +}; + +/** + * Finds and returns an array of target files within the specified base directory. + * + * This function searches for files in the given base directory that either contain a version string, + * or are named 'package.json' or 'package-lock.json'. It then returns an array of these file names, + * ensuring there are no duplicate entries. + * + * @param {string} baseDir - The base directory to search for target files. + * @returns {array} An array of target file names found in the base directory, with duplicates removed. + */ +const findTargetFiles = (baseDir) => { + const files = getFilesInDirectory(baseDir); + const targetFiles = files + .filter((fileName) => { + const filePath = path.join(baseDir, fileName); + return ( + containsVersion(filePath) || fileName === 'package.json' || fileName === 'package-lock.json' + ); + }) + .map((fileName) => fileName); + // filter out duplicates + return [...new Set(targetFiles)]; +}; /** * Retrieves the package.json file from a given directory and compiles it @@ -8,35 +91,56 @@ const fs = require('fs'); * @param {boolean} throwError Whether to throw errors when package.json does not exist. * @returns */ -const getPackage = (path) => { - const absolutePath = `${path}/package.json`; +const getPackage = (path, version = false) => { + let files = []; + let packageValues = {}; - if (packageList[absolutePath]) { - return packageList[absolutePath]; + if (!version) { + files = ['package.json']; + } else { + files = findTargetFiles(path); } - if (!fs.existsSync(absolutePath)) { - return false; - } + files.forEach((file) => { + const absolutePath = `${path}/${file}`; + + if (packageList[absolutePath]) { + return packageList[absolutePath]; + } + + if (!fs.existsSync(absolutePath)) { + return false; + } - const json = JSON.parse(fs.readFileSync(absolutePath)); - const packageObject = json === Object(json) ? json : {}; - const packageNames = packageObject?.name?.split('/'); - const name = packageNames?.[packageNames.length - 1] || ''; + let fileData = { + path, + absolutePath, + }; - const regexDirs = targetDirs.join('|'); - const packagePath = absolutePath.match(`((${regexDirs})\/)?([^\/]+)\/package.json$`); + if (hasExtension(absolutePath, '.json')) { + const json = JSON.parse(fs.readFileSync(absolutePath)); + const packageObject = json === Object(json) ? json : {}; + const packageNames = packageObject?.name?.split('/'); + const name = packageNames?.[packageNames.length - 1] || ''; - const packageValues = { - path, - absolutePath, - relativePath: packagePath[0], - name, - json, - }; + const regexDirs = targetDirs.join('|'); + const packagePath = absolutePath.match(`((${regexDirs})\/)?([^\/]+)\/${file}$`); - packageList[absolutePath] = packageValues; + fileData = { + ...fileData, + relativePath: packagePath ? packagePath[0] : '', + name, + json, + }; + } + if (version) { + packageValues[convertToVariableFriendlyName(file)] = fileData; + } else { + packageValues = fileData; + } + packageList[absolutePath] = fileData; + }); return packageValues; }; diff --git a/src/utils/get-version-project-paths.js b/src/utils/get-version-project-paths.js deleted file mode 100644 index 67bc992..0000000 --- a/src/utils/get-version-project-paths.js +++ /dev/null @@ -1,75 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -/** - * Check if a directory exists. - * @param {string} directory - The directory path to check. - * @returns {boolean} - True if the directory exists, otherwise false. - */ -const directoryExists = (directory) => - fs.existsSync(directory) && fs.lstatSync(directory).isDirectory(); - -/** - * Check if a project directory contains relevant files. - * @param {string} projectPath - The path to the project directory. - * @param {string[]} [projectsList] - The list of specific project names to look for. - * @returns {boolean} - True if the project directory contains relevant files, otherwise false. - */ -const isValidProjectDirectory = (projectPath, projectsList) => { - const packageJsonExists = fs.existsSync(`${projectPath}/package.json`); - const packageLockJsonExists = fs.existsSync(`${projectPath}/package-lock.json`); - const versionFileExists = fs.readdirSync(projectPath).some((file) => { - const filePath = `${projectPath}/${file}`; - if (fs.lstatSync(filePath).isFile()) { - const content = fs.readFileSync(filePath, 'utf8'); - return /\bVersion:\s*([^\r\n]*)/.test(content); - } - return false; - }); - - return packageJsonExists || packageLockJsonExists || versionFileExists; -}; - -/** - * Find all project paths within the specified directories, including the current directory. - * @param {string[]} directories - The list of directories to search. - * @param {string[]} [projectsList] - The list of specific project names to look for. - * @returns {string[]} - An array of project paths. - */ -const findAllProjectPaths = (directories, projectsList) => { - let projects = []; - - directories.filter(directoryExists).forEach((directory) => { - fs.readdirSync(directory, { withFileTypes: true }) - .filter((dirent) => dirent.isDirectory()) // Only process directories - .forEach((dirent) => { - const projectPath = path.resolve(directory, dirent.name); - if (!projectsList || projectsList.includes(dirent.name)) { - if (isValidProjectDirectory(projectPath, projectsList)) { - projects.push(projectPath); - } - } - }); - }); - - // Only get current directory if no projects are specified. - if (!projectsList) { - // Include current directory in the search - const currentDirectory = '.'; - if ( - directoryExists(currentDirectory) && - isValidProjectDirectory(currentDirectory, projectsList) - ) { - projects.push(currentDirectory); - } - } - - if (projects.length <= 0) { - throw new Error('Cannot find any projects.\n'); - } - - return projects; -}; - -module.exports = { - findAllProjectPaths, -}; diff --git a/src/utils/projectpaths.js b/src/utils/projectpaths.js index a74bb9f..e59edf1 100644 --- a/src/utils/projectpaths.js +++ b/src/utils/projectpaths.js @@ -22,7 +22,7 @@ const directoryExists = (directory) => { * @returns {string[]} the complete paths to all project directories * @throws if no projects have been discovered */ -const findAllProjectPaths = (directories, projectsList) => { +const findAllProjectPaths = (directories, projectsList, version = false) => { let projects = []; directories.filter(directoryExists).forEach((directory) => { @@ -40,6 +40,11 @@ const findAllProjectPaths = (directories, projectsList) => { ); }); + // Check the current directory separately + if (fs.existsSync('./package.json') && !projectsList && version) { + projects.push(path.resolve(process.cwd(), '.')); + } + if (projects.length <= 0) { throw new Error('Cannot find any projects.\n'); } @@ -49,13 +54,26 @@ const findAllProjectPaths = (directories, projectsList) => { /** * Confirms the given package.json is a valid build-tools project - * by looking for src/entrypoints + * by looking for src/entrypoints and checking the root directory contains a package.json. */ -const validateProject = (pkg) => { - if (fs.existsSync(`${pkg.path}/src/entrypoints`)) { - return true; +const validateProject = (pkg, version = false) => { + if (version) { + const files = Object.values(pkg); + return files.some((file) => { + if ( + fs.existsSync(`${file.path}/src/entrypoints`) || + fs.existsSync(`${file.path}/package.json`) + ) { + return true; + } + return false; + }); + } else { + if (fs.existsSync(`${pkg.path}/src/entrypoints`)) { + return true; + } + return false; } - return false; }; module.exports = { From 6b1440527c1a07c282be4cff6cf32d3df02508e3 Mon Sep 17 00:00:00 2001 From: Jordan Harris Date: Mon, 22 Jul 2024 15:23:02 +0100 Subject: [PATCH 13/13] fix: return false if empty object --- src/utils/get-package.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/utils/get-package.js b/src/utils/get-package.js index d5e5ed8..fa66ded 100644 --- a/src/utils/get-package.js +++ b/src/utils/get-package.js @@ -141,6 +141,12 @@ const getPackage = (path, version = false) => { packageList[absolutePath] = fileData; }); + + // if packageValues is empty return false instead of empty object. + if (Object.keys(packageValues).length === 0) { + return false; + } + return packageValues; };