@contrail/cli 1.0.11 → 1.0.15

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.
package/src/auth/login.ts CHANGED
@@ -1,14 +1,37 @@
1
1
  const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
2
2
  import inquirer from 'inquirer';
3
- import { Request, setConfig } from '@contrail/sdk';
3
+ import { Request, setConfig as setSdkConfig } from '@contrail/sdk';
4
4
  import { Auth, AuthContext } from './auth';
5
+ import { getConfig, storeConfig } from '../config/config';
5
6
 
6
7
  const CONFIGURATION = {
7
8
  userPoolId: 'us-east-1_x8hXZUsL6',
8
9
  clientId: process.env.CONTRAIL_COGNITO_CLIENT_ID || '2oubek96sue5rsncovtqhs3scm',
9
10
  };
10
11
 
11
- export async function authUser(): Promise<AuthContext>{
12
+ export async function authUser(): Promise<AuthContext> {
13
+ console.debug("authorizing user")
14
+ const config = await getConfig();
15
+ if (
16
+ config &&
17
+ config.apiUserToken &&
18
+ config.apiGateway &&
19
+ config.orgSlug
20
+ ) {
21
+ console.debug("populating auth config from fs config")
22
+ Auth.config = {
23
+ apiUserToken: config.apiUserToken,
24
+ apiGateway: config.apiGateway,
25
+ orgSlug: config.orgSlug,
26
+ };
27
+ setSdkConfig(Auth.config);
28
+ try {
29
+ return await refreshCurrentUserOrg();
30
+ } catch (e) {
31
+ console.log("Token expired. Requesting auth credentials...")
32
+ }
33
+
34
+ }
12
35
  const questions = [];
13
36
  if (!process.env.CONTRAIL_CLI_EMAIL) {
14
37
  questions.push({
@@ -41,7 +64,7 @@ export async function authUser(): Promise<AuthContext>{
41
64
  password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
42
65
  orgSlug: process.env.CONTRAIL_CLI_ORGSLUG || answers.orgSlug,
43
66
  };
44
- if (!params.email || !params.password){
67
+ if (!params.email || !params.password) {
45
68
  throw new Error('Email and Password required');
46
69
  }
47
70
 
@@ -64,7 +87,7 @@ export async function authUser(): Promise<AuthContext>{
64
87
 
65
88
  const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
66
89
 
67
- return new Promise( (resolve, reject) => {
90
+ return new Promise((resolve, reject) => {
68
91
  cognitoUser.authenticateUser(authDetails, {
69
92
  onSuccess: async (result) => {
70
93
  const user = result;
@@ -80,21 +103,20 @@ export async function authUser(): Promise<AuthContext>{
80
103
  }
81
104
 
82
105
  async function setAuthContext(user, params): Promise<AuthContext> {
83
-
84
- // TODO Dont allow user to set this - they could set dev
85
- const questions = [];
86
- questions.push({
87
- type: 'list',
88
- name: 'environment',
89
- message: 'Which environment would you like to use?',
90
- choices: ['Dev', 'Prod'],
91
- default: 'Dev',
92
- });
93
-
106
+ const config = await getConfig();
94
107
  let apiGateway;
95
- const answers = await inquirer.prompt(questions);
96
- if (answers.environment === 'Dev') {
97
- apiGateway = 'https://api.vibeiq.com/dev/api';
108
+ console.log(config.environments)
109
+ if(config.environments) {
110
+ const questions = [];
111
+ questions.push({
112
+ type: 'list',
113
+ name: 'environment',
114
+ message: 'Which environment would you like to use?',
115
+ choices: Object.keys(config.environments),
116
+ default: Object.keys(config.environments)[0],
117
+ });
118
+ const answers = await inquirer.prompt(questions);
119
+ apiGateway = config.environments[answers.environment]
98
120
  } else {
99
121
  apiGateway = 'https://api.vibeiq.com/prod/api';
100
122
  }
@@ -106,8 +128,13 @@ async function setAuthContext(user, params): Promise<AuthContext> {
106
128
  orgSlug: params.orgSlug,
107
129
  };
108
130
  // SET SDK CONFIG
109
- setConfig(Auth.config);
131
+ setSdkConfig(Auth.config);
110
132
 
133
+ return refreshCurrentUserOrg();
134
+ }
135
+
136
+ async function refreshCurrentUserOrg() {
137
+ console.debug("refreshing current user org")
111
138
  const currentUser = await Request.request('/users/current', {
112
139
  method: 'GET',
113
140
  headers: {
@@ -122,6 +149,7 @@ async function setAuthContext(user, params): Promise<AuthContext> {
122
149
  if (org) {
123
150
  Auth.config.orgId = org.orgId || org.id;
124
151
  }
125
-
152
+ // cache config in the fs
153
+ storeConfig(Object.assign({}, Auth.config))
126
154
  return Object.assign({}, Auth.config);
127
155
  }
package/src/cli.ts CHANGED
@@ -3,7 +3,11 @@ import { create } from './apps/create-app/create';
3
3
  import { deployApp, removeApp } from './apps/deploy-app/deploy';
4
4
  import { getTypes } from './types/types-extractor';
5
5
  import { uploadTypes } from './types/types-uploader';
6
- import { parseOptionSet } from './types/parse-optionSet';
6
+ import { UploadOptionSets } from './types/option-set-uploader';
7
+ import { MergeOptionSets } from './types/option-set-merger';
8
+ import { MergeTypeProperties } from './types/types-properties-merger';
9
+ import { ParseTypesFromFiles, ParseTypesFromLocalFiles } from './types/parse-types';
10
+
7
11
  const cliUsage = require('command-line-usage');
8
12
 
9
13
  /**
@@ -15,6 +19,10 @@ export async function cli(args) {
15
19
  const fullCommand = args[2];
16
20
  let domain;
17
21
  let command;
22
+ if(!fullCommand) {
23
+ printIllegalCommand();
24
+ return;
25
+ }
18
26
  const commandParts = fullCommand.split('.');
19
27
 
20
28
  if (!commandParts?.length) {
@@ -57,12 +65,28 @@ export async function cli(args) {
57
65
  getTypes(args);
58
66
  break;
59
67
  }
60
- case 'upload': {
68
+ case 'uploadTypes': {
61
69
  uploadTypes(args);
62
70
  break;
63
71
  }
64
- case 'parseOptionSet': {
65
- parseOptionSet(args);
72
+ case 'uploadOptionSets': {
73
+ UploadOptionSets(args);
74
+ break;
75
+ }
76
+ case 'parseTypesFromLocalFiles': {
77
+ ParseTypesFromLocalFiles(args);
78
+ break;
79
+ }
80
+ case 'parseTypesFromFiles': {
81
+ ParseTypesFromFiles(args);
82
+ break;
83
+ }
84
+ case 'mergeOptionSets': {
85
+ MergeOptionSets(args);
86
+ break;
87
+ }
88
+ case 'mergeTypeProperties': {
89
+ MergeTypeProperties(args);
66
90
  break;
67
91
  }
68
92
  default: {
@@ -125,8 +149,22 @@ const helpSections = [
125
149
  header: 'Type Commands - Domain: types',
126
150
  content: [
127
151
  'getAll Get all OptionSets and Types for your Org.',
128
- 'upload Upload OptionSets and Types for your Org.',
129
- 'parseOptionSet <File Path> Parse a CSV file into OptionSets.',
152
+ 'uploadTypes Upload Types for your Org.',
153
+ '. Types are uploaded from types.yml\n',
154
+ 'uploadOptionSets Upload OptionSets for your Org.',
155
+ '. OptionSets are loaded from option_sets.yml\n',
156
+ 'parseTypesFromLocalFiles <File Paths> Parse CSV files into Types and ',
157
+ '. OptionSets from local files.\n',
158
+ 'parseTypesFromFiles <fileIds> Parse CSV files into Types and ',
159
+ '. OptionSets from VibeIQ Files.\n',
160
+ 'mergeOptionSets <File Path> Merge the OptionSets from an existing',
161
+ '. org and the OptionSets passed in.',
162
+ '. File must be .yml\n',
163
+ 'mergeTypeProperties <File Path> <TypePaths> ',
164
+ '. Merge the TypeProperties from an existing',
165
+ '. org and the TypeProperties passed in.',
166
+ '. Add to Types via TypePath',
167
+ '. File must be .yml\n',
130
168
  ],
131
169
  },
132
170
  ];
@@ -0,0 +1,65 @@
1
+ import { readFileSync, access, promises as fsPromises, write } from 'fs';
2
+ import { join } from 'path';
3
+ import {homedir} from 'os';
4
+ const userHomeDir = homedir();
5
+ const configDirectoryLocation = join(userHomeDir, '.vibeiq');
6
+ const configFileLocation = join(configDirectoryLocation, 'config.json');
7
+
8
+ export async function initializeVibeIQConfig() {
9
+ try{
10
+ await fsPromises.mkdir(configDirectoryLocation, {recursive: true})
11
+ } catch (e) {
12
+ console.error("could not initialize vibeiq directory")
13
+ throw e
14
+ }
15
+
16
+ try {
17
+ await fsPromises.writeFile(configFileLocation, '{}');
18
+ } catch (e) {
19
+ console.error(`could not initialize config file (${configFileLocation}).`)
20
+ throw e;
21
+ }
22
+ }
23
+ export async function readVibeIQConfig() {
24
+ let fileContent;
25
+ try {
26
+ fileContent = await fsPromises.readFile(configFileLocation);
27
+ } catch (e) {
28
+ console.debug(`failed to open config file (${configFileLocation}) for reading.`);
29
+ console.debug('trying to initialize config file');
30
+ await initializeVibeIQConfig();
31
+ console.error(`Could not open config file (${configFileLocation}) for reading.`);
32
+ throw e
33
+ }
34
+
35
+ try {
36
+ return JSON.parse(fileContent);
37
+ } catch (e) {
38
+ console.error(`Could not parse local vibeiq config. The file (${configFileLocation}) might be malformed`);
39
+ }
40
+ }
41
+
42
+
43
+ export async function writeVibeIQConfig(config: Object) {
44
+ try {
45
+ await fsPromises.writeFile(configFileLocation, JSON.stringify(config, null, 2));
46
+ } catch (e) {
47
+ console.error(`Could not open config file (${configFileLocation}) for writing.`);
48
+ throw e
49
+ }
50
+ }
51
+
52
+ export async function getConfig() {
53
+ console.debug("getting config from file system")
54
+ return await readVibeIQConfig();
55
+ }
56
+
57
+ export async function storeConfig(incomingConfig: Object) {
58
+ const config = await readVibeIQConfig();
59
+ const newConfig = {
60
+ ...config,
61
+ ...incomingConfig
62
+ };
63
+ await writeVibeIQConfig(newConfig);
64
+ }
65
+
@@ -3,10 +3,10 @@ export interface ReducedType {
3
3
  label: string;
4
4
  typePath: string;
5
5
  isArchived: boolean;
6
- typeProperties: ReducedType[];
6
+ typeProperties: ReducedTypeProperty[];
7
7
  }
8
8
 
9
- export interface ReducedTypeProperties {
9
+ export interface ReducedTypeProperty {
10
10
  id: string;
11
11
  isArchived: boolean;
12
12
  propertyType: PropertyType;
@@ -0,0 +1,123 @@
1
+ import { Entities } from '@contrail/sdk';
2
+ import { ReducedOptionSet } from './interfaces';
3
+ import fs from 'fs';
4
+ import { getSeparatorByPlatform } from '../common';
5
+ import { authUser } from '../auth/login';
6
+ import chalk from 'chalk';
7
+ const yaml = require('js-yaml');
8
+
9
+ export async function MergeOptionSets(args) {
10
+ try {
11
+ if (args?.length < 4) {
12
+ throw new Error('File name must be included.');
13
+ }
14
+ console.log(`%s Importing local file`, chalk.yellow.bold('OPTION SET MERGE'));
15
+ const fileLocation = args[3];
16
+ console.log('Using File: ', fileLocation);
17
+
18
+ await mergeOptionSets(fileLocation);
19
+ console.log(`%s Merged`, chalk.yellow.bold('OPTION SET MERGE'));
20
+
21
+ }
22
+ catch (e) {
23
+ console.log(`%s Merge Failed. ${e}`, chalk.red.bold('FAIL'));
24
+ return;
25
+ }
26
+
27
+ console.log('%s Merge Complete.', chalk.green.bold('COMPLETE'));
28
+ }
29
+ function loadOptionSets(fileLocation) {
30
+ const TARGET_DIR = process.cwd();
31
+ try {
32
+ const separator = getSeparatorByPlatform();
33
+
34
+ const fullPath = TARGET_DIR + separator + fileLocation;
35
+ console.log('Getting file from path: ', fullPath);
36
+
37
+ const doc = yaml.load(fs.readFileSync(TARGET_DIR + separator + fileLocation, 'utf8'));
38
+ return doc.optionSets;
39
+ } catch (e) {
40
+ throw new Error(`ERROR PARSING YAML: ${e}`);
41
+ }
42
+ }
43
+
44
+ async function mergeOptionSets(fileLocation) {
45
+ const uploadedOptionSets: ReducedOptionSet[] = loadOptionSets(fileLocation);
46
+
47
+ await authUser();
48
+
49
+ const currentOptionSetsFull: any[] = await new Entities().get({
50
+ entityName: 'type-property-option-set',
51
+ });
52
+
53
+ const currentOptionSets = currentOptionSetsFull.map(os => Object.assign({}, {
54
+ name: os.name,
55
+ isArchived: os.isArchived,
56
+ optionSet: os.optionSet,
57
+ }));
58
+
59
+ const currentOptionSetsByName = {};
60
+ for (const currentOptionSet of currentOptionSets) {
61
+ currentOptionSetsByName[currentOptionSet.name] = currentOptionSet;
62
+ }
63
+
64
+ const uploadedOptionSetsByName = {};
65
+ for (const optionSet of uploadedOptionSets) {
66
+ uploadedOptionSetsByName[optionSet.name] = optionSet;
67
+ }
68
+
69
+ const mergedOptionSets: any[] = []
70
+ for (const uploadedOptionSet of uploadedOptionSets) {
71
+ const existing = currentOptionSetsByName[uploadedOptionSet.name];
72
+ if (!existing) {
73
+ if (!uploadedOptionSet.optionSet) {
74
+ console.log('No OptionSet for: ', uploadedOptionSet.name);
75
+ continue;
76
+ }
77
+ console.log('Adding New: ', uploadedOptionSet.name);
78
+ mergedOptionSets.push(uploadedOptionSet);
79
+ }
80
+ else {
81
+ console.log('Merging: ', uploadedOptionSet.name);
82
+ mergedOptionSets.push(mergeOptionSet(existing, uploadedOptionSet));
83
+ }
84
+ }
85
+
86
+ for (const currentOptionSet of currentOptionSets) {
87
+ const found = uploadedOptionSetsByName[currentOptionSet.name];
88
+ if (!found) {
89
+ console.log('Adding Existing: ', currentOptionSet.name);
90
+ mergedOptionSets.push(currentOptionSet);
91
+ }
92
+ }
93
+
94
+ saveData({optionSets: mergedOptionSets})
95
+ }
96
+
97
+ function mergeOptionSet(existingOptionSet: ReducedOptionSet, uploadedOptionSet: ReducedOptionSet) {
98
+ const merged = {
99
+ name: uploadedOptionSet.name,
100
+ optionSet: uploadedOptionSet.optionSet,
101
+ isArchived: uploadedOptionSet.isArchived,
102
+ }
103
+
104
+ for (const keyVal of existingOptionSet.optionSet) {
105
+ const value = keyVal.value
106
+ const display = keyVal.display
107
+
108
+ const found = merged.optionSet.find(keyVal => keyVal.value === value)
109
+ if (!found) {
110
+ merged.optionSet.push({value, display})
111
+ }
112
+
113
+ }
114
+
115
+ return merged;
116
+ }
117
+
118
+ function saveData(data) {
119
+ const yamlStr = yaml.dump(data);
120
+ const CURRENT_DIR = process.cwd();
121
+ const separator = getSeparatorByPlatform();
122
+ fs.writeFileSync(CURRENT_DIR + separator + 'merged_optionSets.yml', yamlStr, 'utf8');
123
+ }
@@ -2,9 +2,29 @@ import { Entities } from '@contrail/sdk';
2
2
  import { ReducedOptionSet } from './interfaces';
3
3
  import fs from 'fs';
4
4
  import { getSeparatorByPlatform } from '../common';
5
+ import { authUser } from '../auth/login';
6
+ import chalk from 'chalk';
5
7
 
6
8
  const yaml = require('js-yaml');
7
9
 
10
+ export async function UploadOptionSets(args) {
11
+ try {
12
+ const userConfig = await authUser();
13
+ console.log(`%s Getting all types for orgId: ${userConfig.orgId}`, chalk.blue.bold('START'));
14
+
15
+ console.log(`%s Uploading`, chalk.yellow.bold('OPTION SETS'));
16
+ await uploadOptionSets();
17
+ console.log(`%s Uploaded`, chalk.yellow.bold('OPTION SETS'));
18
+
19
+ }
20
+ catch (e) {
21
+ console.log(`%s Types Upload Failed. ${e}`, chalk.red.bold('FAIL'));
22
+ return;
23
+ }
24
+
25
+ console.log('%s Types Upload Complete.', chalk.green.bold('COMPLETE'));
26
+ }
27
+
8
28
  function loadOptionSets(){
9
29
  const TARGET_DIR = process.cwd();
10
30
  try {
@@ -16,7 +36,7 @@ function loadOptionSets(){
16
36
  }
17
37
  }
18
38
 
19
- export async function uploadOptionSets() {
39
+ async function uploadOptionSets() {
20
40
  const optionSets: ReducedOptionSet[] = loadOptionSets();
21
41
 
22
42
  const currentOptionSets = await new Entities().get({
@@ -0,0 +1,104 @@
1
+ import { TypeProcessor } from '@contrail/sdk';
2
+ import chalk from 'chalk';
3
+ import fs from 'fs';
4
+ import { getSeparatorByPlatform } from '../common';
5
+ import * as csvToJson from 'csvtojson';
6
+ import { authUser } from '../auth/login';
7
+
8
+ const yaml = require('js-yaml');
9
+
10
+ export async function ParseTypesFromLocalFiles(args) {
11
+ try {
12
+ if (args?.length < 4) {
13
+ throw new Error('File names must be included.');
14
+ }
15
+ console.log(`%s Parsing`, chalk.yellow.bold('TYPES AND OPTION SETS'));
16
+ const fileLocations = (args as Array<string>).slice(3);
17
+ console.log('Using File Location(s): ', fileLocations);
18
+
19
+ await parseTypesFromLocalFiles(fileLocations);
20
+ console.log(`%s Parsed`, chalk.yellow.bold('TYPES AND OPTION SETS'));
21
+
22
+ }
23
+ catch (e) {
24
+ console.log(`%s Parsing Failed. ${e}`, chalk.red.bold('FAIL'));
25
+ return;
26
+ }
27
+
28
+ console.log('%s Parsing Complete.', chalk.green.bold('COMPLETE'));
29
+ }
30
+
31
+ export async function ParseTypesFromFiles(args) {
32
+ try {
33
+ if (args?.length < 4) {
34
+ throw new Error('File ids must be included.');
35
+ }
36
+ console.log(`%s Parsing`, chalk.yellow.bold('TYPES AND OPTION SETS'));
37
+ const fileIds = (args as Array<string>).slice(3);
38
+ console.log('Using FileId(s): ', fileIds);
39
+
40
+ await parseTypesFromFiles(fileIds);
41
+ console.log(`%s Parsed`, chalk.yellow.bold('TYPES AND OPTION SETS'));
42
+
43
+ }
44
+ catch (e) {
45
+ console.log(`%s Parsing Failed. ${e}`, chalk.red.bold('FAIL'));
46
+ return;
47
+ }
48
+
49
+ console.log('%s Parsing Complete.', chalk.green.bold('COMPLETE'));
50
+ }
51
+
52
+ async function loadDataFromCSV(fileName) {
53
+ const CURRENT_DIR = process.cwd();
54
+ try {
55
+ const separator = getSeparatorByPlatform();
56
+ const fullPath = CURRENT_DIR + separator + fileName;
57
+
58
+ console.log('Getting file from path: ', fullPath);
59
+ const csvData = await csvToJson.default().fromFile(fullPath);
60
+
61
+ return csvData;
62
+ } catch (e) {
63
+ throw new Error(`ERROR PARSING CSV: ${e}`);
64
+ }
65
+ }
66
+
67
+ async function parseTypesFromLocalFiles(fileLocations: string[]) {
68
+
69
+ const csvJSONData: any[] = [];
70
+ for (const fileLocation of fileLocations) {
71
+ try {
72
+ console.log('Getting data for fileLocation: ', fileLocation);
73
+ const csvData = await loadDataFromCSV(fileLocation);
74
+
75
+ console.log(`CSV import was successful. ${csvData?.length} rows found. Adding to total rows.`);
76
+ csvJSONData.push(...csvData);
77
+ }
78
+ catch (e) {
79
+ console.log('Error importing csv data.', e);
80
+ throw e;
81
+ }
82
+ }
83
+
84
+ console.log(`CSV imports were successful. ${csvJSONData?.length} total rows found.`);
85
+ const suggestions = await new TypeProcessor().GetSuggestedTypes(csvJSONData)
86
+ saveData({optionSets: suggestions.OptionSets}, 'parsed_optionSets.yml');
87
+ saveData({typeProperties: suggestions.TypeProperties}, 'parsed_typeProperties.yml');
88
+ }
89
+
90
+ async function parseTypesFromFiles(fileIds: string[]) {
91
+ await authUser();
92
+
93
+ const suggestions = await new TypeProcessor().GetSuggestedTypesFromFiles({loadFileIds: fileIds})
94
+
95
+ saveData({optionSets: suggestions.OptionSets}, 'parsed_optionSets.yml');
96
+ saveData({typeProperties: suggestions.TypeProperties}, 'parsed_typeProperties.yml');
97
+ }
98
+
99
+ function saveData(data, name) {
100
+ const yamlStr = yaml.dump(data);
101
+ const CURRENT_DIR = process.cwd();
102
+ const separator = getSeparatorByPlatform();
103
+ fs.writeFileSync(CURRENT_DIR + separator + name, yamlStr, 'utf8');
104
+ }
@@ -1,5 +1,5 @@
1
1
  import { Entities } from '@contrail/sdk';
2
- import { ReducedType, ReducedOptionSet, ReducedTypeProperties } from './interfaces';
2
+ import { ReducedType, ReducedOptionSet, ReducedTypeProperty } from './interfaces';
3
3
  import chalk from 'chalk';
4
4
  import fs from 'fs';
5
5
  import { authUser } from '../auth/login';
@@ -21,7 +21,11 @@ export async function getTypes(args) {
21
21
  console.log(`%s Retrieved`, chalk.yellow.bold('OPTION SETS'));
22
22
  console.log(`%s Retrieving`, chalk.yellow.bold('TYPES'));
23
23
 
24
- await getReducedTypes(optionSets);
24
+ const reducedTypes = await getReducedTypes(optionSets);
25
+ const typesHolder = {
26
+ types: reducedTypes,
27
+ };
28
+ saveData(typesHolder)
25
29
 
26
30
  console.log(`%s Retrieved`, chalk.yellow.bold('TYPES'));
27
31
 
@@ -59,7 +63,7 @@ async function getOptionSets(optionSets) {
59
63
  fs.writeFileSync(CURRENT_DIR + separator + 'option_sets.yml', yamlStr, 'utf8');
60
64
  }
61
65
 
62
- async function getReducedTypes(optionSets) {
66
+ export async function getReducedTypes(optionSets) {
63
67
  const types = await new Entities().get({
64
68
  entityName: 'type',
65
69
  });
@@ -81,7 +85,7 @@ async function getReducedTypes(optionSets) {
81
85
 
82
86
  const reducedTypeProperties = [];
83
87
  for (const typeProperty of typeWithProperties.typeProperties) {
84
- const reducedTypeProperty: ReducedTypeProperties = {
88
+ const reducedTypeProperty: ReducedTypeProperty = {
85
89
  slug: typeProperty.slug,
86
90
  id: typeProperty.id,
87
91
  isArchived: typeProperty.isArchived,
@@ -114,14 +118,12 @@ async function getReducedTypes(optionSets) {
114
118
  }
115
119
 
116
120
  reducedTypes = reducedTypes.sort((one, two) => (one.typePath < two.typePath ? -1 : 1));
121
+ return reducedTypes;
122
+ }
117
123
 
118
- const typesHolder = {
119
- types: reducedTypes,
120
- };
121
-
124
+ function saveData(data) {
125
+ const yamlStr = yaml.dump(data);
122
126
  const CURRENT_DIR = process.cwd();
123
127
  const separator = getSeparatorByPlatform();
124
-
125
- const yamlStr = yaml.dump(typesHolder);
126
128
  fs.writeFileSync(CURRENT_DIR + separator + 'types.yml', yamlStr, 'utf8');
127
129
  }
@@ -0,0 +1,85 @@
1
+ import { Entities } from '@contrail/sdk';
2
+ import { getReducedTypes } from './types-extractor';
3
+ import { ReducedTypeProperty, ReducedType } from './interfaces';
4
+ import fs from 'fs';
5
+ import { getSeparatorByPlatform } from '../common';
6
+ import { authUser } from '../auth/login';
7
+ import chalk from 'chalk';
8
+ const yaml = require('js-yaml');
9
+
10
+ export async function MergeTypeProperties(args) {
11
+ try {
12
+ if (args?.length < 5) {
13
+ throw new Error('File name must be included along with a type path.');
14
+ }
15
+ console.log(`%s Importing local file`, chalk.yellow.bold('TYPE PROPERTIES MERGE'));
16
+ const fileLocation = args[3];
17
+ console.log('Using File: ', fileLocation);
18
+
19
+ const typePaths = (args as Array<string>).slice(4);
20
+ console.log('Using TypePaths: ', typePaths);
21
+
22
+ await mergeTypeProperties(fileLocation, typePaths);
23
+ console.log(`%s Merged`, chalk.yellow.bold('TYPE PROPERTIES MERGE'));
24
+
25
+ }
26
+ catch (e) {
27
+ console.log(`%s Merge Failed. ${e}`, chalk.red.bold('FAIL'));
28
+ return;
29
+ }
30
+
31
+ console.log('%s Merge Complete.', chalk.green.bold('COMPLETE'));
32
+ }
33
+
34
+ function loadTypeProperties(fileLocation) {
35
+ const TARGET_DIR = process.cwd();
36
+ try {
37
+ const separator = getSeparatorByPlatform();
38
+
39
+ const fullPath = TARGET_DIR + separator + fileLocation;
40
+ console.log('Getting file from path: ', fullPath);
41
+
42
+ const doc = yaml.load(fs.readFileSync(TARGET_DIR + separator + fileLocation, 'utf8'));
43
+ return doc.typeProperties;
44
+ } catch (e) {
45
+ throw new Error(`ERROR PARSING YAML: ${e}`);
46
+ }
47
+ }
48
+
49
+ async function mergeTypeProperties(fileLocation, typePaths) {
50
+ const uploadedTypeProperties: ReducedTypeProperty[] = loadTypeProperties(fileLocation);
51
+
52
+ await authUser();
53
+
54
+ const optionSets = await new Entities().get({
55
+ entityName: 'type-property-option-set',
56
+ });
57
+
58
+ const reducedTypes = await getReducedTypes(optionSets);
59
+
60
+ for (const typePath of typePaths) {
61
+ const foundType = reducedTypes.find(reducedTypes => reducedTypes.typePath === typePath);
62
+ if (!foundType){
63
+ console.log(`%s No Type found for: ${typePath}`, chalk.red.bold('WARNING'));
64
+ }
65
+ mergeType(foundType, uploadedTypeProperties)
66
+ }
67
+
68
+ saveData({types: reducedTypes})
69
+ }
70
+
71
+ function mergeType(reducedType: ReducedType, typePropertiesToAdd: ReducedTypeProperty[]) {
72
+ for (const typeProperty of typePropertiesToAdd) {
73
+ const found = reducedType.typeProperties.find(tp => tp.slug === typeProperty.slug)
74
+ if (!found) {
75
+ reducedType.typeProperties.push(typeProperty)
76
+ }
77
+ }
78
+ }
79
+
80
+ function saveData(data) {
81
+ const yamlStr = yaml.dump(data);
82
+ const CURRENT_DIR = process.cwd();
83
+ const separator = getSeparatorByPlatform();
84
+ fs.writeFileSync(CURRENT_DIR + separator + 'merged_types.yml', yamlStr, 'utf8');
85
+ }