@itentialopensource/adapter-tufin_secureapp 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.eslintignore +1 -0
  2. package/AUTH.md +39 -0
  3. package/BROKER.md +199 -0
  4. package/CALLS.md +169 -0
  5. package/CHANGELOG.md +39 -8
  6. package/CODE_OF_CONDUCT.md +12 -17
  7. package/CONTRIBUTING.md +88 -74
  8. package/ENHANCE.md +69 -0
  9. package/PROPERTIES.md +641 -0
  10. package/README.md +228 -420
  11. package/SUMMARY.md +9 -0
  12. package/SYSTEMINFO.md +11 -0
  13. package/TROUBLESHOOT.md +47 -0
  14. package/adapter.js +1628 -170
  15. package/adapterBase.js +1270 -238
  16. package/entities/.generic/action.json +214 -0
  17. package/entities/.generic/schema.json +28 -0
  18. package/error.json +12 -0
  19. package/package.json +41 -18
  20. package/pronghorn.json +577 -2
  21. package/propertiesDecorators.json +14 -0
  22. package/propertiesSchema.json +472 -4
  23. package/refs?service=git-upload-pack +0 -0
  24. package/report/adapterInfo.json +10 -0
  25. package/report/updateReport1615840744335.json +95 -0
  26. package/report/updateReport1653613470041.json +120 -0
  27. package/sampleProperties.json +102 -5
  28. package/test/integration/adapterTestBasicGet.js +85 -0
  29. package/test/integration/adapterTestConnectivity.js +93 -0
  30. package/test/integration/adapterTestIntegration.js +29 -98
  31. package/test/unit/adapterBaseTestUnit.js +949 -0
  32. package/test/unit/adapterTestUnit.js +642 -109
  33. package/utils/adapterInfo.js +206 -0
  34. package/utils/addAuth.js +94 -0
  35. package/utils/basicGet.js +50 -0
  36. package/utils/checkMigrate.js +63 -0
  37. package/utils/entitiesToDB.js +179 -0
  38. package/utils/findPath.js +74 -0
  39. package/utils/modify.js +154 -0
  40. package/utils/packModificationScript.js +1 -1
  41. package/utils/patches2bundledDeps.js +90 -0
  42. package/utils/pre-commit.sh +3 -0
  43. package/utils/removeHooks.js +20 -0
  44. package/utils/tbScript.js +184 -0
  45. package/utils/tbUtils.js +469 -0
  46. package/utils/testRunner.js +16 -16
  47. package/utils/troubleshootingAdapter.js +190 -0
  48. package/img/adapter.png +0 -0
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env node
2
+ /* @copyright Itential, LLC 2019 */
3
+ /* eslint global-require:warn */
4
+ /* eslint import/no-dynamic-require:warn */
5
+ /* eslint prefer-destructuring:warn */
6
+
7
+ const fs = require('fs-extra');
8
+ const path = require('path');
9
+
10
+ /**
11
+ * This script will determine the information about the adapter and store
12
+ * it into a file in the adapter.
13
+ */
14
+
15
+ /**
16
+ * get adapter information
17
+ */
18
+ function adapterInfo() {
19
+ // set the base pase of the adapter - tool shoud be one level up in utils
20
+ let adaptdir = __dirname;
21
+ const infoRes = {};
22
+
23
+ if (adaptdir.endsWith('/utils')) {
24
+ adaptdir = adaptdir.substring(0, adaptdir.length - 6);
25
+ }
26
+ const pack = require(`${adaptdir}/package.json`);
27
+ infoRes.version = pack.version;
28
+
29
+ let configCount = 0;
30
+ if (fs.existsSync(`${adaptdir}/pronghorn.json`)) {
31
+ const cFile = fs.readFileSync(`${adaptdir}/pronghorn.json`, 'utf8');
32
+ configCount += cFile.split('\n').length;
33
+ } else {
34
+ console.log('Missing - pronghorn.json');
35
+ }
36
+ if (fs.existsSync(`${adaptdir}/propertiesSchema.json`)) {
37
+ const cFile = fs.readFileSync(`${adaptdir}/propertiesSchema.json`, 'utf8');
38
+ configCount += cFile.split('\n').length;
39
+ } else {
40
+ console.log('Missing - propertiesSchema.json');
41
+ }
42
+ if (fs.existsSync(`${adaptdir}/error.json`)) {
43
+ const cFile = fs.readFileSync(`${adaptdir}/error.json`, 'utf8');
44
+ configCount += cFile.split('\n').length;
45
+ } else {
46
+ console.log('Missing - error.json');
47
+ }
48
+ const entitydir = path.join(adaptdir, '/entities');
49
+ if (fs.existsSync(entitydir) && fs.statSync(entitydir).isDirectory()) {
50
+ const entities = fs.readdirSync(entitydir);
51
+ // need to go through each entity in the entities directory
52
+ for (let e = 0; e < entities.length; e += 1) {
53
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
54
+ const cfiles = fs.readdirSync(entitydir);
55
+ for (let c = 0; c < cfiles.length; c += 1) {
56
+ if (cfiles[c].endsWith('.json')) {
57
+ const ccFile = fs.readFileSync(`${entitydir}/${entities[e]}/${cfiles[c]}`, 'utf8');
58
+ configCount += ccFile.split('\n').length;
59
+ }
60
+ }
61
+ }
62
+ }
63
+ } else {
64
+ console.log('Could not find the entities directory');
65
+ }
66
+ infoRes.configLines = configCount;
67
+
68
+ let scodeCount = 0;
69
+ if (fs.existsSync(`${adaptdir}/utils/artifactize.js`)) {
70
+ const sFile = fs.readFileSync(`${adaptdir}/utils/artifactize.js`, 'utf8');
71
+ scodeCount += sFile.split('\n').length;
72
+ } else {
73
+ console.log('Missing - utils/artifactize.js');
74
+ }
75
+ if (fs.existsSync(`${adaptdir}/utils/basicGet.js`)) {
76
+ const sFile = fs.readFileSync(`${adaptdir}/utils/basicGet.js`, 'utf8');
77
+ scodeCount += sFile.split('\n').length;
78
+ } else {
79
+ console.log('Missing - utils/basicGet.js');
80
+ }
81
+ if (fs.existsSync(`${adaptdir}/utils/checkMigrate.js`)) {
82
+ const sFile = fs.readFileSync(`${adaptdir}/utils/checkMigrate.js`, 'utf8');
83
+ scodeCount += sFile.split('\n').length;
84
+ } else {
85
+ console.log('Missing - utils/checkMigrate.js');
86
+ }
87
+ if (fs.existsSync(`${adaptdir}/utils/findPath.js`)) {
88
+ const sFile = fs.readFileSync(`${adaptdir}/utils/findPath.js`, 'utf8');
89
+ scodeCount += sFile.split('\n').length;
90
+ } else {
91
+ console.log('Missing - utils/findPath.js');
92
+ }
93
+ if (fs.existsSync(`${adaptdir}/utils/modify.js`)) {
94
+ const sFile = fs.readFileSync(`${adaptdir}/utils/modify.js`, 'utf8');
95
+ scodeCount += sFile.split('\n').length;
96
+ } else {
97
+ console.log('Missing - utils/modify.js');
98
+ }
99
+ if (fs.existsSync(`${adaptdir}/utils/packModificationScript.js`)) {
100
+ const sFile = fs.readFileSync(`${adaptdir}/utils/packModificationScript.js`, 'utf8');
101
+ scodeCount += sFile.split('\n').length;
102
+ } else {
103
+ console.log('Missing - utils/packModificationScript.js');
104
+ }
105
+ if (fs.existsSync(`${adaptdir}/utils/setup.js`)) {
106
+ const sFile = fs.readFileSync(`${adaptdir}/utils/setup.js`, 'utf8');
107
+ scodeCount += sFile.split('\n').length;
108
+ } else {
109
+ console.log('Missing - utils/setup.js');
110
+ }
111
+ if (fs.existsSync(`${adaptdir}/utils/tbScript.js`)) {
112
+ const sFile = fs.readFileSync(`${adaptdir}/utils/tbScript.js`, 'utf8');
113
+ scodeCount += sFile.split('\n').length;
114
+ } else {
115
+ console.log('Missing - utils/tbScript.js');
116
+ }
117
+ if (fs.existsSync(`${adaptdir}/utils/tbUtils.js`)) {
118
+ const sFile = fs.readFileSync(`${adaptdir}/utils/tbUtils.js`, 'utf8');
119
+ scodeCount += sFile.split('\n').length;
120
+ } else {
121
+ console.log('Missing - utils/tbUtils.js');
122
+ }
123
+ if (fs.existsSync(`${adaptdir}/utils/testRunner.js`)) {
124
+ const sFile = fs.readFileSync(`${adaptdir}/utils/testRunner.js`, 'utf8');
125
+ scodeCount += sFile.split('\n').length;
126
+ } else {
127
+ console.log('Missing - utils/testRunner.js');
128
+ }
129
+ if (fs.existsSync(`${adaptdir}/utils/troubleshootingAdapter.js`)) {
130
+ const sFile = fs.readFileSync(`${adaptdir}/utils/troubleshootingAdapter.js`, 'utf8');
131
+ scodeCount += sFile.split('\n').length;
132
+ } else {
133
+ console.log('Missing - utils/troubleshootingAdapter.js');
134
+ }
135
+ infoRes.scriptLines = scodeCount;
136
+
137
+ let codeCount = 0;
138
+ if (fs.existsSync(`${adaptdir}/adapter.js`)) {
139
+ const aFile = fs.readFileSync(`${adaptdir}/adapter.js`, 'utf8');
140
+ codeCount += aFile.split('\n').length;
141
+ } else {
142
+ console.log('Missing - utils/adapter.js');
143
+ }
144
+ if (fs.existsSync(`${adaptdir}/adapterBase.js`)) {
145
+ const aFile = fs.readFileSync(`${adaptdir}/adapterBase.js`, 'utf8');
146
+ codeCount += aFile.split('\n').length;
147
+ } else {
148
+ console.log('Missing - utils/adapterBase.js');
149
+ }
150
+ infoRes.codeLines = codeCount;
151
+
152
+ let tcodeCount = 0;
153
+ let ttestCount = 0;
154
+ if (fs.existsSync(`${adaptdir}/test/integration/adapterTestBasicGet.js`)) {
155
+ const tFile = fs.readFileSync(`${adaptdir}/test/integration/adapterTestBasicGet.js`, 'utf8');
156
+ tcodeCount += tFile.split('\n').length;
157
+ ttestCount += tFile.split('it(\'').length;
158
+ } else {
159
+ console.log('Missing - test/integration/adapterTestBasicGet.js');
160
+ }
161
+ if (fs.existsSync(`${adaptdir}/test/integration/adapterTestConnectivity.js`)) {
162
+ const tFile = fs.readFileSync(`${adaptdir}/test/integration/adapterTestConnectivity.js`, 'utf8');
163
+ tcodeCount += tFile.split('\n').length;
164
+ ttestCount += tFile.split('it(\'').length;
165
+ } else {
166
+ console.log('Missing - test/integration/adapterTestConnectivity.js');
167
+ }
168
+ if (fs.existsSync(`${adaptdir}/test/integration/adapterTestIntegration.js`)) {
169
+ const tFile = fs.readFileSync(`${adaptdir}/test/integration/adapterTestIntegration.js`, 'utf8');
170
+ tcodeCount += tFile.split('\n').length;
171
+ ttestCount += tFile.split('it(\'').length;
172
+ } else {
173
+ console.log('Missing - test/integration/adapterTestIntegration.js');
174
+ }
175
+ if (fs.existsSync(`${adaptdir}/test/unit/adapterBaseTestUnit.js`)) {
176
+ const tFile = fs.readFileSync(`${adaptdir}/test/unit/adapterBaseTestUnit.js`, 'utf8');
177
+ tcodeCount += tFile.split('\n').length;
178
+ ttestCount += tFile.split('it(\'').length;
179
+ } else {
180
+ console.log('Missing - test/unit/adapterBaseTestUnit.js');
181
+ }
182
+ if (fs.existsSync(`${adaptdir}/test/unit/adapterTestUnit.js`)) {
183
+ const tFile = fs.readFileSync(`${adaptdir}/test/unit/adapterTestUnit.js`, 'utf8');
184
+ tcodeCount += tFile.split('\n').length;
185
+ ttestCount += tFile.split('it(\'').length;
186
+ } else {
187
+ console.log('Missing - test/unit/adapterTestUnit.js');
188
+ }
189
+ infoRes.testLines = tcodeCount;
190
+ infoRes.testCases = ttestCount;
191
+ infoRes.totalCodeLines = scodeCount + codeCount + tcodeCount;
192
+
193
+ if (fs.existsSync(`${adaptdir}/pronghorn.json`)) {
194
+ // Read the entity schema from the file system
195
+ const phFile = path.join(adaptdir, '/pronghorn.json');
196
+ const prong = require(phFile);
197
+ infoRes.wfTasks = prong.methods.length;
198
+ } else {
199
+ console.log('Missing - pronghorn.json');
200
+ }
201
+
202
+ console.log(JSON.stringify(infoRes));
203
+ fs.writeFileSync(`${adaptdir}/report/adapterInfo.json`, JSON.stringify(infoRes, null, 2));
204
+ }
205
+
206
+ adapterInfo();
@@ -0,0 +1,94 @@
1
+ /* eslint-disable no-plusplus */
2
+ /* eslint global-require: warn */
3
+ /* eslint import/no-dynamic-require: warn */
4
+
5
+ const rls = require('readline-sync');
6
+ const path = require('path');
7
+ const fs = require('fs');
8
+
9
+ function getQuestions(props, obj) {
10
+ const questions = props.map((p) => `${p}: ${(obj[p] !== undefined) ? `(${obj[p]})` : ''} `);
11
+ return questions;
12
+ }
13
+
14
+ // function outputs each property for user to edit/confirm
15
+ // props are the fields that need to be changed depending on what the user selects
16
+ // obj is the JSON object that's being updated
17
+ function confirm(props, obj) {
18
+ // create array of questions
19
+ const updatedObj = obj;
20
+ getQuestions(props, obj).forEach((q) => {
21
+ const answer = rls.question(q);
22
+ // only update the field if the answer is NOT and empty string
23
+ if (answer) {
24
+ updatedObj[q.split(':')[0].trim()] = answer;
25
+ }
26
+ });
27
+ return updatedObj;
28
+ }
29
+
30
+ const updateBasicAuth = (auth) => {
31
+ const propsToUpdate = ['username', 'password', 'auth_field', 'auth_field_format'];
32
+ return confirm(propsToUpdate, auth);
33
+ };
34
+
35
+ const updateStaticTokenAuth = (auth) => {
36
+ const propsToUpdate = ['token', 'auth_field', 'auth_field_format'];
37
+ return confirm(propsToUpdate, auth);
38
+ };
39
+
40
+ function updateTokenSchemas(user, pw, token) {
41
+ let schemaPath = path.join(__dirname, '..', 'entities/.system/schemaTokenReq.json');
42
+ const reqSchema = require(schemaPath);
43
+ reqSchema.properties.username.external_name = user;
44
+ reqSchema.properties.password.external_name = pw;
45
+ fs.writeFileSync(schemaPath, JSON.stringify(reqSchema, null, 2));
46
+ schemaPath = path.join(__dirname, '..', 'entities/.system/schemaTokenResp.json');
47
+ const respSchema = require(schemaPath);
48
+ respSchema.properties.token.external_name = token;
49
+ fs.writeFileSync(schemaPath, JSON.stringify(respSchema, null, 2));
50
+ }
51
+
52
+ function updateRequestToken(auth) {
53
+ const propsToUpdate = [
54
+ 'username',
55
+ 'password',
56
+ 'auth_field',
57
+ 'auth_field_format',
58
+ 'token_user_field',
59
+ 'token_password_field',
60
+ 'token_result_field',
61
+ 'token_URI_path'
62
+ ];
63
+ const newAuth = confirm(propsToUpdate, auth);
64
+ updateTokenSchemas(newAuth.token_user_field, newAuth.token_password_field, newAuth.token_result_field);
65
+
66
+ return newAuth;
67
+ }
68
+
69
+ // prompt users to pick an auth method from the list above
70
+ const addAuthInfo = (props) => {
71
+ const authOptions = [
72
+ 'basic user_password',
73
+ 'static_token',
74
+ 'request_token',
75
+ 'no_authentication'
76
+ ];
77
+ const newProps = confirm(['host', 'port', 'base_path'], props);
78
+
79
+ const newAuthMethod = authOptions[rls.keyInSelect(authOptions, 'Which authentication method?')];
80
+ newProps.authentication.auth_method = newAuthMethod;
81
+
82
+ if (newAuthMethod === 'basic user_password') {
83
+ newProps.authentication = updateBasicAuth(newProps.authentication);
84
+ } else if (newAuthMethod === 'static_token') {
85
+ newProps.authentication = updateStaticTokenAuth(newProps.authentication);
86
+ } else if (newAuthMethod === 'request_token') {
87
+ newProps.authentication = updateRequestToken(newProps.authentication);
88
+ }
89
+ console.log('Connectivity and authentication properties have been configured');
90
+ console.log('If you want to make changes, rerun this script to reinstall the adapter');
91
+ return newProps;
92
+ };
93
+
94
+ module.exports = { addAuthInfo };
@@ -0,0 +1,50 @@
1
+ /* @copyright Itential, LLC 2020 */
2
+
3
+ /* eslint object-shorthand: warn */
4
+ /* eslint import/no-extraneous-dependencies: warn */
5
+ /* eslint global-require: warn */
6
+ /* eslint import/no-unresolved: warn */
7
+ /* eslint import/no-dynamic-require: warn */
8
+
9
+ const winston = require('winston');
10
+
11
+ const logLevel = 'none';
12
+ const myCustomLevels = {
13
+ levels: {
14
+ spam: 6,
15
+ trace: 5,
16
+ debug: 4,
17
+ info: 3,
18
+ warn: 2,
19
+ error: 1,
20
+ none: 0
21
+ }
22
+ };
23
+
24
+ const basicGet = {
25
+ /**
26
+ * @summary create Adapter instance
27
+ *
28
+ * @function getAdapterInstance
29
+ * @param {Object} adapter - adaper configuration object required by IAP
30
+ */
31
+ getAdapterInstance: (adapter) => {
32
+ const Adapter = require('../adapter');
33
+ const adapterProps = JSON.parse(JSON.stringify(adapter.properties.properties));
34
+ adapterProps.stub = false;
35
+ // need to set global logging
36
+ global.log = winston.createLogger({
37
+ level: logLevel,
38
+ levels: myCustomLevels.levels,
39
+ transports: [
40
+ new winston.transports.Console()
41
+ ]
42
+ });
43
+ return new Adapter(
44
+ adapter.id,
45
+ adapterProps
46
+ );
47
+ }
48
+ };
49
+
50
+ module.exports = basicGet;
@@ -0,0 +1,63 @@
1
+ const { execSync } = require('child_process');
2
+ const semver = require('semver');
3
+ const axios = require('axios');
4
+ const fs = require('fs');
5
+ const packageJson = require('../package.json');
6
+
7
+ const localEngineVer = packageJson.engineVersion;
8
+ const localUtils = execSync('npm list @itentialopensource/adapter-utils', { encoding: 'utf-8' });
9
+ const localUtilsVer = localUtils.split('@').pop().replace(/(\r\n|\n|\r| )/gm, '');
10
+
11
+ /**
12
+ * @summary Makes a GET call using axios
13
+ *
14
+ * @function get
15
+ * @param {String} url - url to make the call to
16
+ */
17
+ function get(url) {
18
+ const config = {
19
+ method: 'get',
20
+ url
21
+ };
22
+ return axios(config);
23
+ }
24
+
25
+ /**
26
+ * @summary Checks if adapter can be migrated using migration package
27
+ *
28
+ * @function migratePossible
29
+ */
30
+ function migratePossible() {
31
+ const adapterTestUnit = fs.readFileSync('./test/unit/adapterTestUnit.js', { encoding: 'utf-8' });
32
+ const readme = fs.readFileSync('./README.md', { encoding: 'utf-8' });
33
+ return packageJson.keywords !== null && adapterTestUnit.indexOf('DO NOT REMOVE THIS COMMENT BLOCK') !== -1
34
+ && readme.indexOf('available at ') !== -1 && readme.indexOf('You will need to change the credentials and possibly the host information below.') !== -1;
35
+ }
36
+
37
+ /**
38
+ * @summary Checks if adapter is up-to-date or if migration is needed
39
+ *
40
+ * @function migrateNeeded
41
+ */
42
+ async function migrateNeeded() {
43
+ const engineUrl = 'https://adapters.itential.io/engineVersion';
44
+ const utilsUrl = 'https://registry.npmjs.org/@itentialopensource/adapter-utils';
45
+ const latestEngineVer = (await get(engineUrl)).data;
46
+ const latestUtilsVer = (await get(utilsUrl)).data['dist-tags'].latest;
47
+ return semver.lt(localEngineVer, latestEngineVer) || semver.lt(localUtilsVer, latestUtilsVer);
48
+ }
49
+
50
+ // Main Script
51
+ if (migratePossible()) {
52
+ migrateNeeded().then((needed) => {
53
+ if (needed) {
54
+ console.log('Migration is needed and possible -- go to dev site to download migration package');
55
+ } else {
56
+ console.log('Migration is possible but not needed at the current time.');
57
+ }
58
+ }).catch((error) => {
59
+ console.log('Could not get latest engine or utils version.', error.message);
60
+ });
61
+ } else {
62
+ console.log('Migration is not possible. Please contact Itential support for assistance');
63
+ }
@@ -0,0 +1,179 @@
1
+ /* @copyright Itential, LLC 2021 */
2
+
3
+ // Set globals
4
+ /* global log */
5
+
6
+ /* eslint import/no-dynamic-require: warn */
7
+ /* eslint global-require: warn */
8
+ /* eslint no-unused-vars: warn */
9
+ /* eslint import/no-unresolved: warn */
10
+
11
+ /**
12
+ * This script is used to read through an adapter's entities files
13
+ * and then creates documents and enters them into the IAP mongodb
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const utils = require('./tbUtils');
19
+
20
+ // get the pronghorn database information
21
+ const getPronghornProps = async (iapDir) => {
22
+ log.trace('Retrieving properties.json file...');
23
+ const rawProps = require(path.join(iapDir, 'properties.json'));
24
+ log.trace('Decrypting properties...');
25
+ const { PropertyEncryption } = require('@itential/itential-utils');
26
+ const propertyEncryption = new PropertyEncryption();
27
+ const pronghornProps = await propertyEncryption.decryptProps(rawProps);
28
+ log.trace('Found properties.\n');
29
+ return pronghornProps;
30
+ };
31
+
32
+ /**
33
+ * Function used to take a file path to a entity directory and build
34
+ * a document that corresponds to the entity files.
35
+ */
36
+ const buildDoc = (pathstring) => {
37
+ let files = fs.readdirSync(pathstring);
38
+
39
+ // load the mockdatafiles
40
+ const mockdatafiles = {};
41
+ if (files.includes('mockdatafiles') && fs.lstatSync(`${pathstring}/mockdatafiles`).isDirectory()) {
42
+ fs.readdirSync(`${pathstring}/mockdatafiles`).forEach((file) => {
43
+ if (file.split('.').pop() === 'json') {
44
+ const mockpath = `${pathstring}/mockdatafiles/${file}`;
45
+ const data = JSON.parse(fs.readFileSync(mockpath));
46
+ mockdatafiles[mockpath.split('/').pop()] = data;
47
+ }
48
+ });
49
+ }
50
+
51
+ // load the action data
52
+ let actions;
53
+ if (files.includes('action.json')) {
54
+ actions = JSON.parse(fs.readFileSync(`${pathstring}/action.json`));
55
+ }
56
+
57
+ // Load schema.json and other schemas in remaining json files
58
+ files = files.filter((f) => (f !== 'action.json') && f.endsWith('.json'));
59
+ const schema = [];
60
+ files.forEach((file) => {
61
+ const data = JSON.parse(fs.readFileSync(`${pathstring}/${file}`));
62
+ schema.push({
63
+ name: file,
64
+ schema: data
65
+ });
66
+ });
67
+
68
+ // return the data
69
+ return {
70
+ actions: actions.actions,
71
+ schema,
72
+ mockdatafiles
73
+ };
74
+ };
75
+
76
+ /**
77
+ * Function used to get the database from the options or a provided directory
78
+ */
79
+ const optionsHandler = (options) => {
80
+ // if the database properties were provided in the options - return them
81
+ if (options.pronghornProps) {
82
+ if (typeof options.pronghornProps === 'string') {
83
+ return JSON.parse(options.pronghornProps);
84
+ }
85
+ return new Promise((resolve, reject) => resolve(options.pronghornProps));
86
+ }
87
+
88
+ // if the directory was provided, get the pronghorn props from the directory
89
+ if (options.iapDir) {
90
+ return getPronghornProps(options.iapDir);
91
+ }
92
+
93
+ // if nothing was provided, error
94
+ return new Promise((resolve, reject) => reject(new Error('Neither pronghornProps nor iapDir defined in options!')));
95
+ };
96
+
97
+ /**
98
+ * Function used to put the adapter configuration into the provided database
99
+ */
100
+ const moveEntitiesToDB = async (targetPath, options) => {
101
+ // set local variables
102
+ let myOpts = options;
103
+ let myPath = targetPath;
104
+
105
+ // if we got a string parse into a JSON object
106
+ if (typeof myOpts === 'string') {
107
+ myOpts = JSON.parse(myOpts);
108
+ }
109
+
110
+ // if there is no target collection - set the collection to the default
111
+ if (!myOpts.targetCollection) {
112
+ myOpts.targetCollection = 'adapter_configs';
113
+ }
114
+
115
+ // if there is no id error since we need an id for the entities
116
+ if (!myOpts.id) {
117
+ throw new Error('Adapter ID required!');
118
+ }
119
+
120
+ // get the pronghorn database properties
121
+ return optionsHandler(options).then(async (currentProps) => {
122
+ // Check valid filepath provided
123
+ if (!myPath) {
124
+ // if no path use the current directory without the utils
125
+ myPath = path.join(__dirname, '../');
126
+ } else if (myPath.slice(-1) === '/') {
127
+ myPath = myPath.slice(0, -1);
128
+ }
129
+
130
+ // verify set the entity path
131
+ const entitiesPath = `${myPath}/entities`;
132
+ if (!fs.existsSync(entitiesPath)) {
133
+ throw new Error(`Entities path does not exist in filesystem: ${entitiesPath}`);
134
+ } else {
135
+ log.trace('Target found on filesystem');
136
+ }
137
+
138
+ // Get adapter details
139
+ if (!fs.existsSync(`${myPath}/pronghorn.json`)) {
140
+ throw new Error(`pronghorn.json does not exist in path: ${myPath}`);
141
+ } else {
142
+ log.trace('pronghorn.json found on filesystem');
143
+ }
144
+ const adapterData = JSON.parse(fs.readFileSync(`${myPath}/pronghorn.json`));
145
+
146
+ // Load files from the filesystem
147
+ const docs = [];
148
+ const entities = fs.readdirSync(entitiesPath);
149
+ entities.forEach((entity) => {
150
+ const entityPath = `${entitiesPath}/${entity}`;
151
+ const isDir = fs.lstatSync(entitiesPath).isDirectory();
152
+
153
+ // Build doc for entity
154
+ if (isDir) {
155
+ let doc = buildDoc(entityPath);
156
+ doc = {
157
+ id: myOpts.id,
158
+ type: adapterData.id,
159
+ entity,
160
+ ...doc
161
+ };
162
+ docs.push(doc);
163
+ }
164
+ });
165
+
166
+ // Upload documents to db collection
167
+ const iapDir = utils.getIAPHome();
168
+ const db = await utils.connect(iapDir, currentProps).catch((err) => { console.error(err); throw err; });
169
+ if (!db) {
170
+ console.error('Error occured when connectiong to database', currentProps);
171
+ throw new Error('Database not found');
172
+ }
173
+ const collection = db.collection(myOpts.targetCollection);
174
+ const res = await collection.insertMany(docs, { checkKeys: false }).catch((err) => { console.error(err); throw err; });
175
+ return res;
176
+ });
177
+ };
178
+
179
+ module.exports = { moveEntitiesToDB };
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ /* @copyright Itential, LLC 2019 */
3
+ /* eslint global-require:warn */
4
+ /* eslint import/no-dynamic-require:warn */
5
+ /* eslint prefer-destructuring:warn */
6
+
7
+ const fs = require('fs-extra');
8
+ const path = require('path');
9
+ const rls = require('readline-sync');
10
+
11
+ /**
12
+ * This script will determine the type of integration test to run
13
+ * based on input. If other information is needed, it will solicit
14
+ * that input and then edit the integration test accordingly.
15
+ */
16
+
17
+ /**
18
+ * Updates the action files
19
+ */
20
+ function checkActionFiles(apath) {
21
+ // verify the path
22
+ if (!apath) {
23
+ console.log(' NO PATH PROVIDED!');
24
+ return 'Done';
25
+ }
26
+
27
+ // make sure the entities directory exists
28
+ const entitydir = path.join(__dirname, '../entities');
29
+ if (!fs.statSync(entitydir).isDirectory()) {
30
+ console.log('Could not find the entities directory');
31
+ return 'error';
32
+ }
33
+
34
+ const entities = fs.readdirSync(entitydir);
35
+ let found = false;
36
+
37
+ // need to go through each entity in the entities directory
38
+ for (let e = 0; e < entities.length; e += 1) {
39
+ // make sure the entity is a directory - do not care about extra files
40
+ // only entities (dir)
41
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
42
+ // see if the action file exists in the entity
43
+ if (fs.existsSync(`${entitydir}/${entities[e]}/action.json`)) {
44
+ // Read the entity actions from the file system
45
+ const actions = require(`${entitydir}/${entities[e]}/action.json`);
46
+
47
+ // go through all of the actions set the appropriate info in the newActions
48
+ for (let a = 0; a < actions.actions.length; a += 1) {
49
+ if (actions.actions[a].entitypath.indexOf(apath) >= 0) {
50
+ found = true;
51
+ console.log(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
52
+ console.log(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
53
+ console.log(' ');
54
+ }
55
+ }
56
+ } else {
57
+ console.log(`Could not find entities ${entities[e]} action.json file`);
58
+ return 'error';
59
+ }
60
+ } else {
61
+ console.log(`Could not find entities ${entities[e]} directory`);
62
+ return 'error';
63
+ }
64
+ }
65
+
66
+ if (!found) {
67
+ console.log(' PATH NOT FOUND!');
68
+ }
69
+ return 'Done';
70
+ }
71
+
72
+ const findPath = rls.question('Enter the path/partial path you are looking for: ');
73
+ console.log(`PATH: ${findPath}`);
74
+ checkActionFiles(findPath);