Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Trying to support non cli #22

Closed
wants to merge 51 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
a211d30
trying to test non cli
Jun 19, 2020
9d892b5
lets try this
Jun 19, 2020
2f81d1a
addeding a log to test
Jun 19, 2020
52cf554
Trying-To-Support-non-cli: Merge branch 'Trying-To-Support-non-cli' o…
Jun 19, 2020
94adce3
lets just try using lib
Jun 19, 2020
4a75de5
* added the ability to simply call run
Jun 19, 2020
8113b0c
added readme change
Jun 19, 2020
ccf627a
one more readme modifcaiton
Jun 19, 2020
522d8d3
revert removal of new line
Jun 19, 2020
169bf72
added constants to support the specification of target from nodejs side
Jun 19, 2020
8bcf0cd
readme update
Jun 19, 2020
c8636cd
fix to how i defined constants
Jun 19, 2020
d077c7f
* added editorconfig
Jun 20, 2020
2e95ed8
* added a change to attempt to see if we can use require now
Jun 20, 2020
eb051d0
and the file change itself
Jun 20, 2020
5330db5
so it turns out a - breaks npm install haha
Jun 20, 2020
aac19ec
missed line opps
Jun 20, 2020
a20a4c4
alright?.. lets try a roll back
Jun 20, 2020
2af5ad1
hmm
Jun 20, 2020
cf6b811
ah.. opps my cheery pick of line borked package json
Jun 20, 2020
a1fcc18
adding inital tests
Jun 20, 2020
ea876d7
added linting changes
Jun 20, 2020
22a6c23
* npm ignore updates
Jun 20, 2020
9545544
* committing initial tests before testing the removal incase i lose s…
Jun 20, 2020
c49936e
*tear down fixed
Jun 20, 2020
b6eeeb6
final iteration of the index.js top level test
Jun 21, 2020
2193b08
* added another refactor to make tests look cleaner
Jun 21, 2020
84944cc
added cli mocking inital files
Jun 21, 2020
2d4de75
moved around tests for cleaner postioning
Jun 21, 2020
0aa9192
disable failing trest
Jun 21, 2020
c88c5fd
Files tests
Jun 22, 2020
dc4d700
added another return to avoid the race conditions occurring during te…
Jun 22, 2020
37a6ece
small change to add commit message for draft pr
Jun 22, 2020
556305f
npmignore rejig
Jun 22, 2020
af8a420
readme fix
Jun 22, 2020
4a1e282
simplification of random filename as its not needed to be so complex
Jun 22, 2020
74d32fc
unneeded anon func?
Jun 22, 2020
f7fd558
* removal of argv mock
Jul 6, 2020
aa83793
* slight refactors to utils
Jul 6, 2020
3f17809
Trying-To-Support-non-cli: adding linting fixes
phyzical Oct 26, 2020
a986cc7
Trying-To-Support-non-cli: more liniting
phyzical Oct 26, 2020
ac8ea00
Trying-To-Support-non-cli: changed to es6 exports, more linting
phyzical Oct 26, 2020
8093f27
Update README.md
phyzical Oct 27, 2020
cdeb6a4
Trying-To-Support-non-cli: rollback the export change
phyzical Oct 27, 2020
4d5fe7e
Trying-To-Support-non-cli: Merge branch 'Trying-To-Support-non-cli' o…
phyzical Oct 27, 2020
9071cd4
Trying-To-Support-non-cli: add readme fix
phyzical Oct 27, 2020
6b45606
Trying-To-Support-non-cli: adding inital typescript funtionailty
phyzical Oct 27, 2020
5964cd9
Trying-To-Support-non-cli: updated the typescripting to support index
phyzical Oct 28, 2020
829032c
Trying-To-Support-non-cli: added logic to mimic a cli usage added log…
phyzical Oct 30, 2020
064b7a7
Trying-To-Support-non-cli: fixed a bug in the regex tester not workin…
phyzical Oct 30, 2020
379dfd6
Trying-To-Support-non-cli: finished cli context tests
phyzical Oct 30, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[*]
indent_size = 2
indent_style = space
tab_width = 2
insert_final_newline = true
24 changes: 24 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = {
extends: ['eslint:recommended', 'prettier'], // extending recommended config and config derived from eslint-config-prettier
plugins: ['prettier'], // extending recommended config and config derived from eslint-config-prettier
env: {
browser: true,
node: true,
amd: true,
es6: true,
commonjs: true,
jest: true,
},
parser: 'babel-eslint',
rules: {
'prettier/prettier': [
// customizing prettier rules (unfortunately not many of them are customizable)
'error',
{
singleQuote: true,
tabWidth: 2,
},
],
eqeqeq: ['error', 'always'], // adding some custom ESLint rules
},
};
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ ISSUE_TEMPLATE.md
PULL_REQUEST_TEMPLATE.md
yarn.lock
package-lock.json
.editorconfig
.eslintrc.js
tests
5 changes: 5 additions & 0 deletions PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,8 @@ Fixes #
-
-
-

## Checklist
make sure you have run the following before requesting a review
* npm run lint
* npm run typescript
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ $ npm install add-dependencies [-g]

### Usage

Run:
Run (for `nodejs` see Example):

```sh
$ add-dependencies [package_file] <dependencies> [target] [--no-overwrite]
Expand All @@ -35,7 +35,7 @@ If no `package_file` argument passed, the script searches for a `package.json` f

Use `--no-overwrite` flag to prevent already existing packages in `package.json` from being overwritten.

Example:
Example:

```sh
$ add-dependencies /home/user/project/package.json [email protected] [email protected] redux eslint --dev
Expand All @@ -46,3 +46,24 @@ or with `npx`:
```sh
$ npx add-dependencies /home/user/project/package.json [email protected] [email protected] redux eslint --dev
```

or via nodejs

```js
const npmAdd = require('add-dependencies');
//OR
// Note: to use import you must have `"type": "module"` in your projects package.json
import npmAdd from 'add-dependencies';

const dependencies = [
'package1',
'package2',
'package3',
];
const target = npmAdd.CONSTANTS.DEPENDENCIES;
const overwrite = false;
const packageFilePath = 'package.json';
new npmAdd(dependencies, target, overwrite, packageFilePath)
.run()
.then(() => console.log('completed'));
```
15 changes: 15 additions & 0 deletions cli-index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node

const AddDependencies = require('./lib/AddDependencies');

console.log(
'\x1b[33m%s\x1b[0m',
'This script adds dependencies (latest or specified versions) to the package.json file skipping the installation process.'
);

const app = new AddDependencies();

app.run().catch((error) => {
console.error('\x1b[31m%s\x1b[0m', error);
process.exit(1);
});
10 changes: 1 addition & 9 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,3 @@
#!/usr/bin/env node
const AddDependencies = require('./lib/AddDependencies');

console.log('\x1b[33m%s\x1b[0m', 'This script adds dependencies (latest or specified versions) to the package.json file skipping the installation process.');

const app = new AddDependencies();

app.addDependencies().then(app.saveToPackage.bind(app)).catch((error) => {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was one change i was unsure of, as to why app.saveToPackage.bind(app) was being done?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Obviously, because saveToPackage method is supposed to use the class context.

Copy link
Author

@phyzical phyzical Jun 23, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but why does it not have the class context from within itself already? or was this something todo with the asyncy nature of the package

console.error('\x1b[31m%s\x1b[0m', error);
process.exit(1);
});
module.exports = require('./lib/AddDependencies');
5 changes: 5 additions & 0 deletions index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env node

import AddDependencies from './lib/AddDependencies.js';

export default AddDependencies;
155 changes: 109 additions & 46 deletions lib/AddDependencies.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ const npmRun = require('npm-run');
const semver = require('semver');
const Files = require('./Files');

class AddDependencies {
constructor() {
module.exports = class AddDependencies {
constructor(
dependencies = [],
target = 'dependencies',
overwrite = true,
packageFilePath = './package.json'
) {
this.result = {};
this.dependencies = [];
this.target = 'dependencies';
this.overwrite = true;
this.packageFilePath = './package.json';
this.dependencies = dependencies;
this.target = target;
this.overwrite = overwrite;
this.packageFilePath = packageFilePath;
}

addDependencies() {
Expand Down Expand Up @@ -38,7 +43,7 @@ class AddDependencies {
break;
}
default: {
if (/package\.json/.test(val)) {
phyzical marked this conversation as resolved.
Show resolved Hide resolved
if (val.includes('package.json')) {
this.packageFilePath = val;
} else if (!/^-/.test(val)) {
this.dependencies.push(val);
Expand All @@ -59,9 +64,21 @@ class AddDependencies {
return Promise.all(this.dependencies.map((dep) => this.runNpmShow(dep)));
}

run() {
return this.addDependencies().then(() => this.saveToPackage());
}

runNpmShow(dep) {
if (!dep) {
console.error(
'\x1b[31m%s\x1b[0m',
`No Dependency Provided to runNpmShow()`
);
return new Promise((resolve) => resolve());
}
const depSplit = dep.split('@');
const [depName, depVersion] = dep.charAt(0) !== '@' ? depSplit : [`@${depSplit[1]}`, depSplit[2]];
const [depName, depVersion] =
dep.charAt(0) !== '@' ? depSplit : [`@${depSplit[1]}`, depSplit[2]];

if (depVersion) {
const depRange = semver.validRange(depVersion) || '';
Expand All @@ -80,22 +97,37 @@ class AddDependencies {
this.result[depName] = `${depVersion}`;
break;
}
} else if (operators.length > 1 && specifiedVersions.length > 1) {
if (semver.cmp(version, operators[0], specifiedVersions[0]) && semver.cmp(version, operators[1], specifiedVersions[1])) {
} else if (
operators.length > 1 &&
specifiedVersions.length > 1
) {
if (
semver.cmp(version, operators[0], specifiedVersions[0]) &&
semver.cmp(version, operators[1], specifiedVersions[1])
) {
this.result[depName] = `${depVersion}`;
break;
}
}
}
// eslint-disable-next-line
} catch (e) {}

if (undefined === this.result[depName]) {
console.error('\x1b[31m%s\x1b[0m', `Could not obtain the specified version for: ${depName}. Skip.`);
console.error(
'\x1b[31m%s\x1b[0m',
`Could not obtain the specified version for: ${depName}. Skip.`
);
} else {
console.log(`Processed: ${depName}, specified version: ${depVersion}`);
console.log(
`Processed: ${depName}, specified version: ${depVersion}`
);
}
} else {
console.error('\x1b[31m%s\x1b[0m', `Could not fetch version info for: ${depName}. Skip.`);
console.error(
'\x1b[31m%s\x1b[0m',
`Could not fetch version info for: ${depName}. Skip.`
);
}

return resolve();
Expand All @@ -109,14 +141,20 @@ class AddDependencies {
const parsed = stdout.match(/latest: '(.*?)'/i);

if (!parsed || undefined === parsed[1]) {
console.error('\x1b[31m%s\x1b[0m', `Could not obtain the latest version for: ${depName}. Skip.`);
console.error(
'\x1b[31m%s\x1b[0m',
`Could not obtain the latest version for: ${depName}. Skip.`
);
} else {
this.result[depName] = `^${parsed[1]}`;

console.log(`Processed: ${depName}, latest version: ${parsed[1]}`);
}
} else {
console.error('\x1b[31m%s\x1b[0m', `Could not fetch version info for: ${depName}. Skip.`);
console.error(
'\x1b[31m%s\x1b[0m',
`Could not fetch version info for: ${depName}. Skip.`
);
}

return resolve();
Expand All @@ -125,39 +163,64 @@ class AddDependencies {
}

saveToPackage() {
Files.readFromFile(this.packageFilePath).then(async (data) => {
let json;

try {
json = JSON.parse(data);
} catch (e) {
console.error('\x1b[31m%s\x1b[0m', `Could not parse ${this.packageFilePath}. Stop.`);
process.exit(1);
}

this.result = this.overwrite
? Object.assign(json[this.target] || {}, this.result)
: Object.assign(this.result, json[this.target] || {});

this.result = Object.keys(this.result).sort().reduce((res, key) => {
res[key] = this.result[key];

return res;
}, {});

json[this.target] = this.result;
return Files.readFromFile(this.packageFilePath)
.then(async (data) => {
let json;

try {
json = JSON.parse(data);
} catch (e) {
console.error(
'\x1b[31m%s\x1b[0m',
`Could not parse ${this.packageFilePath}. Stop.`
);
process.exit(1);
}

Files.writeToFile(this.packageFilePath, JSON.stringify(json, null, 2)).then(() => {
console.log('\x1b[32m%s\x1b[0m', 'Done.');
}).catch(() => {
console.error('\x1b[31m%s\x1b[0m', `Could not write to ${this.packageFilePath}. Stop.`);
this.result = this.overwrite ?
Object.assign(json[this.target] || {}, this.result) :
Object.assign(this.result, json[this.target] || {});

this.result = Object.keys(this.result)
.sort()
.reduce((res, key) => {
res[key] = this.result[key];

return res;
}, {});

json[this.target] = this.result;

return Files.writeToFile(
this.packageFilePath,
JSON.stringify(json, null, 2)
)
.then(() => {
console.log('\x1b[32m%s\x1b[0m', 'Done.');
})
.catch(() => {
console.error(
'\x1b[31m%s\x1b[0m',
`Could not write to ${this.packageFilePath}. Stop.`
);
process.exit(1);
});
})
.catch(() => {
console.error(
'\x1b[31m%s\x1b[0m',
`Could not read from ${this.packageFilePath}. Stop.`
);
process.exit(1);
});
}).catch(() => {
console.error('\x1b[31m%s\x1b[0m', `Could not read from ${this.packageFilePath}. Stop.`);
process.exit(1);
});
}
}

module.exports = AddDependencies;
static get CONSTANTS() {
return {
DEPENDENCIES: 'dependencies',
DEV_DEPENDENCIES: 'devDependencies',
PEER_DEPENDENCIES: 'peerDependencies',
OPTIONAL_DEPENDENCIES: 'optionalDependencies',
};
}
};
4 changes: 2 additions & 2 deletions lib/Files.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class Files {
return new Promise((resolve, reject) => {
fs.readFile(filePath, (err, data) => {
if (err) {
return reject();
return reject(err);
}

return resolve(data.toString());
Expand All @@ -17,7 +17,7 @@ class Files {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, fileContent, (err) => {
if (err) {
return reject();
return reject(err);
}

return resolve();
Expand Down
21 changes: 18 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
},
"homepage": "https://github.com/arfeo/npm-add-dependencies#readme",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "jest --config ./tests/jest.config.js",
"lint": "eslint --fix --ext js lib/**.js index.js cli-index.js",
"typescript": "tsc"
},
"keywords": [
"dependencies",
Expand All @@ -23,10 +25,23 @@
"license": "MIT",
"preferGlobal": true,
"bin": {
"add-dependencies": "index.js"
"add-dependencies": "cli-index.js"
},
"dependencies": {
"npm-run": "^5.0.1",
"semver": "^6.3.0"
},
"devDependencies": {
"blueimp-md5": "^2.16.0",
"mock-argv": "^1.1.7",
"jest": "^26.0.1",
"eslint": "^7.3.0",
"babel-eslint": "^10.1.0",
"typescript": "^4.0.5",
"eslint-config-prettier": "^3.3.0",
"eslint-plugin-prettier": "^3.0.0",
"prettier": "^2.0.5",
"concat-stream": "^2.0.0",
"child_process": "^1.0.2"
}
}
}
Loading