@contrail/cli 1.0.54 → 1.0.56

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.
@@ -1,34 +1,48 @@
1
1
  import { Entities } from '@contrail/sdk';
2
- import { ReducedType, ReducedOptionSet, ReducedTypeProperty } from './interfaces';
2
+ import { ReducedType, ReducedTypeProperty } from './interfaces';
3
3
  import chalk from 'chalk';
4
4
  import fs from 'fs';
5
5
  import { authUser } from '../auth/login';
6
- import { getSeparatorByPlatform } from '../common';
6
+ import * as path from 'path';
7
+ import pLimit from 'p-limit';
8
+ const limit = pLimit(30);
7
9
 
8
10
  const yaml = require('js-yaml');
9
11
 
10
- export async function getTypes(args) {
12
+ export interface DataHolder {
13
+ types: any[],
14
+ optionSets: any[],
15
+ optionSetHierarchies: any[],
16
+ ruleSets: any[],
17
+ ruleSetLinks: any[],
18
+ usageInfo: any[],
19
+ typePropertyPolicies: any[],
20
+ typePropertyPolicyLinks: any[],
21
+ }
22
+
23
+ export async function getAll(args) {
11
24
  try {
12
25
  const userConfig = await authUser();
13
26
  console.log(`%s Getting all types for orgId: ${userConfig.orgId}`, chalk.blue.bold('START'));
14
- console.log('%s Retrieving', chalk.yellow.bold('OPTION SETS'));
15
27
 
16
- const optionSets = await new Entities().get({
17
- entityName: 'type-property-option-set',
18
- });
19
- await getOptionSets(optionSets);
28
+ // make directory to house exports
29
+ const dir = `./contrail-export-${Date.now()}`;
30
+ fs.mkdirSync(dir);
20
31
 
21
- console.log('%s Retrieved', chalk.yellow.bold('OPTION SETS'));
22
- console.log('%s Retrieving', chalk.yellow.bold('TYPES'));
23
-
24
- const reducedTypes = await getReducedTypes(optionSets);
25
- const typesHolder = {
26
- types: reducedTypes,
32
+ const data: DataHolder = {
33
+ types: await getTypes(),
34
+ optionSets: await getOptionSets(),
35
+ optionSetHierarchies: await getOptionSetHierarchies(),
36
+ ruleSets: await getRuleSets(),
37
+ ruleSetLinks: await getRuleSetLinks(),
38
+ usageInfo: await getUsageInfo(),
39
+ typePropertyPolicies: await getTypePropertyPolicies(),
40
+ typePropertyPolicyLinks: await getTypePropertyPolicyLinks(),
27
41
  };
28
- saveData(typesHolder);
42
+ const reducedData = reduceData(data);
43
+ saveData(reducedData, dir);
29
44
 
30
45
  console.log('%s Retrieved', chalk.yellow.bold('TYPES'));
31
-
32
46
  }
33
47
  catch (e) {
34
48
  console.log(`%s Types Retrieval Failed. ${e}`, chalk.red.bold('FAIL'));
@@ -38,53 +52,179 @@ export async function getTypes(args) {
38
52
  console.log('%s Types Retrieval Complete.', chalk.green.bold('COMPLETE'));
39
53
  }
40
54
 
41
- async function getOptionSets(optionSets) {
42
- let reducedOptionSets = [];
43
- for (const optionSet of optionSets) {
44
- const reducedOptionSet: ReducedOptionSet = {
45
- name: optionSet.name,
46
- isArchived: optionSet.isArchived,
47
- optionSet: optionSet.optionSet,
48
- };
55
+ /**
56
+ * stores reduced option sets and returns full option sets */
57
+ export async function getOptionSets() {
58
+ console.log('%s Retrieving', chalk.yellow.bold('OPTION SETS'));
59
+ const optionSets = await new Entities().get({
60
+ entityName: 'type-property-option-set',
61
+ });
62
+ console.log('%s Retrieved', chalk.yellow.bold('OPTION SETS'));
63
+ return optionSets;
64
+ }
49
65
 
50
- reducedOptionSets.push(reducedOptionSet);
66
+ export async function getTypes() {
67
+ console.log('%s Retrieving', chalk.yellow.bold('TYPES'));
68
+ const entitiesClient = new Entities();
69
+ const types = await entitiesClient.get({
70
+ entityName: 'type',
71
+ });
72
+ console.log(`${chalk.yellow.bold('TYPES')} Found ${types.length} types`);
73
+ const typesWithProperties = [];
74
+ const promises = [];
75
+ for (const type of types) {
76
+ const promise = limit(async () => {
77
+ const t = await entitiesClient.get({
78
+ entityName: 'type',
79
+ id: type.id,
80
+ relations: ['typeProperties'],
81
+ });
82
+ typesWithProperties.push(t);
83
+ });
84
+ promises.push(promise);
51
85
  }
86
+ await Promise.all(promises);
87
+ return typesWithProperties;
88
+ }
52
89
 
53
- const optionSetsHolder = {
54
- optionSets: reducedOptionSets,
55
- };
90
+ async function getOptionSetHierarchies() {
91
+ const entitiesClient = new Entities();
92
+ return await entitiesClient.get({
93
+ entityName: 'option-set-hierarchy',
94
+ });
95
+ }
56
96
 
57
- reducedOptionSets = reducedOptionSets.sort((one, two) => (one.name < two.name ? -1 : 1));
97
+ async function getRuleSets() {
98
+ const entitiesClient = new Entities();
99
+ return await entitiesClient.get({
100
+ entityName: 'type-rule-set',
101
+ });
102
+ }
58
103
 
59
- const CURRENT_DIR = process.cwd();
60
- const separator = getSeparatorByPlatform();
104
+ async function getRuleSetLinks() {
105
+ const entitiesClient = new Entities();
106
+ return await entitiesClient.get({
107
+ entityName: 'type-rule-set-link',
108
+ });
109
+ }
61
110
 
62
- const yamlStr = yaml.dump(optionSetsHolder);
63
- fs.writeFileSync(CURRENT_DIR + separator + 'option_sets.yml', yamlStr, 'utf8');
111
+ async function getUsageInfo() {
112
+ const entitiesClient = new Entities();
113
+ return await entitiesClient.get({
114
+ entityName: 'type-property-usage-info',
115
+ });
64
116
  }
65
117
 
66
- export async function getReducedTypes(optionSets) {
67
- const types = await new Entities().get({
68
- entityName: 'type',
118
+ async function getTypePropertyPolicies() {
119
+ const entitiesClient = new Entities();
120
+ return await entitiesClient.get({
121
+ entityName: 'type-property-policy',
122
+ });
123
+ }
124
+ async function getTypePropertyPolicyLinks() {
125
+ const entitiesClient = new Entities();
126
+ return await entitiesClient.get({
127
+ entityName: 'type-property-policy-link',
69
128
  });
129
+ }
70
130
 
71
- console.log('Found types: ', types.length);
131
+ function reduceTypePropertyPolicies(data: DataHolder) {
132
+ return data?.typePropertyPolicies?.map(x => {
133
+ return {
134
+ label: x.label,
135
+ policy: {
136
+ version: x.policy.version,
137
+ statements: x.policy.statements,
138
+ }
139
+ };
140
+ });
141
+ }
72
142
 
73
- let reducedTypes = [];
74
- for (const type of types) {
75
- const typeWithProperties = await new Entities().get({
76
- entityName: 'type',
77
- id: type.id,
78
- relations: ['typeProperties'],
79
- });
143
+ function reduceTypePropertyPolicyLinks(data: DataHolder) {
144
+ const typeProperties = data?.types?.map(x => x.typeProperties).reduce((x, y) => x.concat(y));
145
+ return data?.typePropertyPolicyLinks?.map(x => {
146
+ return {
147
+ typePropertySlug: typeProperties.find(y => y.id === x.typePropertyId)?.slug,
148
+ typePropertyPolicyLabel: data.typePropertyPolicies.find(y => y.id === x.typePropertyPolicyId)?.label,
149
+ };
150
+ });
151
+ }
152
+
153
+ function reduceUsageInfo(data: DataHolder) {
154
+ const typeProperties = data?.types?.map(x => x.typeProperties).reduce((x, y) => x.concat(y));
155
+ return data?.usageInfo?.map(x => {
156
+ return {
157
+ used: x.used,
158
+ editable: x.editable,
159
+ typeSlug: data.types.find(y => y.id === x.typeId)?.slug,
160
+ typePropertySlug: typeProperties.find(y => y.id === x.typePropertyId)?.slug,
161
+ };
162
+ });
163
+ }
80
164
 
81
- const optionSetNameById = {};
82
- for (const optionSet of optionSets) {
83
- optionSetNameById[optionSet.id] = optionSet.name;
165
+ function reduceRuleSetLinks(data: DataHolder) {
166
+ const reducedRuleSetLinks = [];
167
+ if (!data?.ruleSetLinks.length) {
168
+ return [];
169
+ }
170
+ for (const ruleSetLink of data.ruleSetLinks) {
171
+ const ruleSet = data?.ruleSets?.find(x => x.id === ruleSetLink.typeRuleSetId);
172
+ const type = data?.types?.find(x => x.id === ruleSetLink.typeId);
173
+
174
+ if (!ruleSet || !type) {
175
+ console.log('%s Skipping bad rule set link', ruleSetLink.id, chalk.red.bold('TYPES'));
84
176
  }
177
+ reducedRuleSetLinks.push({
178
+ ruleSet: ruleSet.name,
179
+ type: type.slug
180
+ });
181
+ }
182
+ return reducedRuleSetLinks;
183
+ }
184
+
185
+ function reduceRuleSets(data: DataHolder) {
186
+ return data?.ruleSets?.map(x => {
187
+ return {
188
+ ruleSet: x.ruleSet,
189
+ name: x.name,
190
+ };
191
+ });
192
+ }
193
+
194
+ function reduceOptionSets(data: DataHolder) {
195
+ return data.optionSets?.map(optionSet => {
196
+ return {
197
+ name: optionSet.name,
198
+ isArchived: optionSet.isArchived,
199
+ optionSet: optionSet.optionSet,
200
+ };
201
+ });
202
+ }
85
203
 
204
+ function reduceOptionSetHierarchies(data: DataHolder) {
205
+ return data.optionSetHierarchies?.map(x => {
206
+ const hierarchyByName = x.hierarchy.map(
207
+ optionSetId => data.optionSets?.find(x => x.id === optionSetId)?.name
208
+ );
209
+ return {
210
+ hierarchy: hierarchyByName,
211
+ options: x.options,
212
+ name: x.name
213
+ };
214
+ });
215
+ }
216
+
217
+ export function reduceTypes(dataHolder: DataHolder) {
218
+ console.log('Found types: ', dataHolder.types.length);
219
+
220
+ let reducedTypes = [];
221
+ const optionSetNameById = {};
222
+ for (const optionSet of dataHolder.optionSets) {
223
+ optionSetNameById[optionSet.id] = optionSet.name;
224
+ }
225
+ for (const type of dataHolder.types) {
86
226
  const reducedTypeProperties = [];
87
- for (const typeProperty of typeWithProperties.typeProperties) {
227
+ for (const typeProperty of type.typeProperties) {
88
228
  const reducedTypeProperty: ReducedTypeProperty = {
89
229
  slug: typeProperty.slug,
90
230
  id: typeProperty.id,
@@ -108,10 +248,10 @@ export async function getReducedTypes(optionSets) {
108
248
  }
109
249
 
110
250
  const reducedType: ReducedType = {
111
- typePath: typeWithProperties.typePath,
112
- slug: typeWithProperties.slug,
113
- label: typeWithProperties.label,
114
- isArchived: typeWithProperties.isArchived,
251
+ typePath: type.typePath,
252
+ slug: type.slug,
253
+ label: type.label,
254
+ isArchived: type.isArchived,
115
255
  typeProperties: reducedTypeProperties,
116
256
  };
117
257
 
@@ -122,9 +262,50 @@ export async function getReducedTypes(optionSets) {
122
262
  return reducedTypes;
123
263
  }
124
264
 
125
- function saveData(data) {
126
- const yamlStr = yaml.dump(data);
127
- const CURRENT_DIR = process.cwd();
128
- const separator = getSeparatorByPlatform();
129
- fs.writeFileSync(CURRENT_DIR + separator + 'types.yml', yamlStr, 'utf8');
265
+ export function reduceData(data: DataHolder) {
266
+ return {
267
+ reducedTypes: reduceTypes(data),
268
+ reducedOptionSets: reduceOptionSets(data),
269
+ reducedOptionSetHierarchies: reduceOptionSetHierarchies(data),
270
+ reducedRuleSets: reduceRuleSets(data),
271
+ reducedRuleSetLinks: reduceRuleSetLinks(data),
272
+ reducedUsageInfo: reduceUsageInfo(data),
273
+ reducedTypePropertyPolicies: reduceTypePropertyPolicies(data),
274
+ reducedTypePropertyPolicyLinks: reduceTypePropertyPolicyLinks(data),
275
+ };
276
+ }
277
+
278
+ function saveData(reducedData, dir: string) {
279
+
280
+ const propertyToFolderMap = {
281
+ reducedTypes: { filename: 'types', split: true, fileLabel: 'slug' },
282
+ reducedOptionSets: { filename: 'option-sets', split: true, fileLabel: 'name' },
283
+ reducedOptionSetHierarchies: { filename: 'option-set-hierarchies', split: true, fileLabel: 'name' },
284
+ reducedRuleSets: { filename: 'rule-sets', split: true, fileLabel: 'name' },
285
+ reducedRuleSetLinks: { filename: 'rule-set-links', split: false, fileLabel: '' },
286
+ reducedUsageInfo: { filename: 'usage-info', split: false, fileLabel: '' },
287
+ reducedTypePropertyPolicies: { filename: 'type-property-policies', split: true, fileLabel: 'label' },
288
+ reducedTypePropertyPolicyLinks: { filename: 'type-property-policy-links', split: false, fileLabel: '' },
289
+ };
290
+ for(const [key, folder] of Object.entries(propertyToFolderMap)) {
291
+ const CURRENT_DIR = process.cwd();
292
+ if(folder.split) {
293
+ const subDir = path.join(CURRENT_DIR, dir, folder.filename);
294
+ if(!fs.existsSync(subDir)) {
295
+ fs.mkdirSync(subDir);
296
+ }
297
+ for(const item of reducedData[key]) {
298
+ const yamlStr = yaml.dump(item);
299
+ const fileLabel = item[folder.fileLabel];
300
+ if(!fileLabel) {
301
+ console.warn('skipping bad data:', item);
302
+ }
303
+ fs.writeFileSync(path.join(subDir, `${fileLabel}.yml`), yamlStr, 'utf8');
304
+ }
305
+ } else {
306
+ const yamlStr = yaml.dump(reducedData[key]);
307
+ fs.writeFileSync(path.join(CURRENT_DIR, dir, `${folder.filename}.yml`), yamlStr, 'utf8');
308
+ }
309
+
310
+ }
130
311
  }
@@ -1,5 +1,4 @@
1
- import { Entities } from '@contrail/sdk';
2
- import { getReducedTypes } from './types-extractor';
1
+ import { DataHolder, getOptionSets, getTypes, reduceData } from './types-extractor';
3
2
  import { ReducedTypeProperty, ReducedType } from './interfaces';
4
3
  import fs from 'fs';
5
4
  import { getSeparatorByPlatform } from '../common';
@@ -51,21 +50,27 @@ async function mergeTypeProperties(fileLocation, typePaths) {
51
50
 
52
51
  await authUser();
53
52
 
54
- const optionSets = await new Entities().get({
55
- entityName: 'type-property-option-set',
56
- });
57
-
58
- const reducedTypes = await getReducedTypes(optionSets);
53
+ const data: DataHolder = {
54
+ types: await getTypes(),
55
+ optionSets: await getOptionSets(),
56
+ optionSetHierarchies: [],
57
+ ruleSets: [],
58
+ ruleSetLinks: [],
59
+ usageInfo: [],
60
+ typePropertyPolicies: [],
61
+ typePropertyPolicyLinks: [],
62
+ };
63
+ const reducedData = await reduceData(data);
59
64
 
60
65
  for (const typePath of typePaths) {
61
- const foundType = reducedTypes.find(reducedTypes => reducedTypes.typePath === typePath);
66
+ const foundType = reducedData.reducedTypes.find(reducedTypes => reducedTypes.typePath === typePath);
62
67
  if (!foundType){
63
68
  console.log(`%s No Type found for: ${typePath}`, chalk.red.bold('WARNING'));
64
69
  }
65
70
  mergeType(foundType, uploadedTypeProperties);
66
71
  }
67
72
 
68
- saveData({types: reducedTypes});
73
+ saveData({types: reducedData.reducedTypes});
69
74
  }
70
75
 
71
76
  function mergeType(reducedType: ReducedType, typePropertiesToAdd: ReducedTypeProperty[]) {
@@ -3,7 +3,7 @@ import { ReducedType } from './interfaces';
3
3
  import chalk from 'chalk';
4
4
  import fs from 'fs';
5
5
  import { authUser } from '../auth/login';
6
- import { getSeparatorByPlatform } from '../common';
6
+ import * as path from 'path';
7
7
  import * as _ from 'lodash';
8
8
 
9
9
  import yaml from 'js-yaml';
@@ -29,9 +29,12 @@ export async function uploadTypes() {
29
29
  function loadReducedTypes(){
30
30
  const TARGET_DIR = process.cwd();
31
31
  try {
32
- const separator = getSeparatorByPlatform();
33
- const doc = yaml.load(fs.readFileSync(TARGET_DIR + separator + 'types.yml', 'utf8'));
34
- return doc.types;
32
+ const files = fs.readdirSync(path.join(TARGET_DIR, 'types'));
33
+ const types = [];
34
+ for(const file of files) {
35
+ types.push(yaml.load(fs.readFileSync(path.join(TARGET_DIR, 'types', file), 'utf8')));
36
+ }
37
+ return types;
35
38
  } catch (e) {
36
39
  throw new Error(`ERROR PARSING YAML: ${e}`);
37
40
  }
@@ -0,0 +1,134 @@
1
+ import { Entities } from '@contrail/sdk';
2
+ import fs from 'fs';
3
+ import { authUser } from '../auth/login';
4
+ import chalk from 'chalk';
5
+ import { getTypes } from './types-extractor';
6
+ import * as path from 'path';
7
+
8
+ const yaml = require('js-yaml');
9
+
10
+ export async function uploadUsageInfo(args) {
11
+ try {
12
+ await authUser();
13
+
14
+ console.log('%s Uploading', chalk.yellow.bold('USAGE INFO'));
15
+ const reducedUsageInfo = await loadUsageInfo();
16
+ await uploadUsageInfoObjects(reducedUsageInfo);
17
+ console.log('%s Uploaded', chalk.yellow.bold('USAGE INFO'));
18
+
19
+ }
20
+ catch (e) {
21
+ console.log(`%s Usage Info Upload Failed. ${e}`, chalk.red.bold('FAIL'));
22
+ return;
23
+ }
24
+
25
+ console.log('%s Usage Info Upload Complete.', chalk.green.bold('COMPLETE'));
26
+ }
27
+
28
+ function loadUsageInfo() {
29
+ const TARGET_DIR = process.cwd();
30
+ try {
31
+ const doc = yaml.load(fs.readFileSync(path.join(TARGET_DIR, 'usage-info.yml'), 'utf8'));
32
+ return doc;
33
+ } catch (e) {
34
+ throw new Error(`ERROR PARSING YAML: ${e}`);
35
+ }
36
+ }
37
+
38
+ async function uploadUsageInfoObjects(loadedUsageInfo) {
39
+ const typesWithProperties = await getTypes();
40
+ const typeProperties = typesWithProperties
41
+ .filter(t=>!!t.typeProperties)
42
+ .map(t => t.typeProperties)
43
+ .reduce((a, b) => a.concat(b));
44
+
45
+ const currentUsageInfo = await new Entities().get({
46
+ entityName: 'type-property-usage-info',
47
+ });
48
+
49
+ const currentUsageInfosHashes = {};
50
+ for(const currentUI of currentUsageInfo) {
51
+ const foundType = typesWithProperties.find(t => t.id === currentUI.typeId);
52
+ const foundTypeProperty = typeProperties.find(tp => tp.id === currentUI.typePropertyId);
53
+ if(!foundType || !foundTypeProperty) {
54
+ console.log('skipping unhashable, invalid usage info:', currentUI);
55
+ continue;
56
+ }
57
+ const hash = `${foundType.slug}|${foundTypeProperty.slug}`;
58
+ currentUsageInfosHashes[hash] = currentUI;
59
+ }
60
+
61
+ const reducedUsageInfoHashes = {};
62
+ for(const loadedUI of loadedUsageInfo) {
63
+ const hash = `${loadedUI.typeSlug}|${loadedUI.typePropertySlug}`;
64
+ reducedUsageInfoHashes[hash] = loadedUI;
65
+ }
66
+ console.debug('current usage info:', currentUsageInfo);
67
+ console.debug('loaded usage info:', loadedUsageInfo);
68
+
69
+ for (const loadedUI of loadedUsageInfo) {
70
+ try {
71
+ const found = currentUsageInfosHashes[`${loadedUI.typeSlug}|${loadedUI.typePropertySlug}`];
72
+ if (!found) {
73
+ if (!transformReducedUI(loadedUI, typesWithProperties, typeProperties)) { continue; }
74
+ console.debug('Creating: ', loadedUI);
75
+ await new Entities().create({
76
+ entityName: 'type-property-usage-info',
77
+ object: {
78
+ typePropertyId: loadedUI.typePropertyId,
79
+ typeId: loadedUI.typeId,
80
+ editable: loadedUI.editable,
81
+ used: loadedUI.used,
82
+ }
83
+ });
84
+ } else {
85
+ if (!transformReducedUI(loadedUI, typesWithProperties, typeProperties)) { continue; }
86
+ console.log('Updating: ', loadedUI);
87
+ await new Entities().update({
88
+ entityName: 'type-property-usage-info',
89
+ id: found.id,
90
+ object: {
91
+ editable: loadedUI.editable,
92
+ used: loadedUI.used,
93
+ }
94
+ });
95
+ }
96
+ } catch (err) {
97
+ throw new Error(`Error Uploading usage info: ${err}`);
98
+ }
99
+ }
100
+
101
+ for (const [hash, currentUI] of Object.entries(currentUsageInfosHashes)) {
102
+ try {
103
+ const found = reducedUsageInfoHashes[hash];
104
+ if (!found) {
105
+ console.debug('Deleting: ', hash);
106
+ await new Entities().delete({
107
+ entityName: 'type-property-usage-info',
108
+ id: currentUI['id'],
109
+ });
110
+ }
111
+ } catch (err) {
112
+ throw new Error(`Error Deleting usage info: ${err}`);
113
+ }
114
+ }
115
+
116
+ }
117
+
118
+ // transforms the reduced Usage Info from name slugs to ids
119
+ function transformReducedUI(reducedUsageInfo, types, typeProperties) {
120
+ const foundType = types.find(t => t.slug === reducedUsageInfo.typeSlug);
121
+ if (!foundType) {
122
+ console.error('Could not find type with slug', reducedUsageInfo.typeSlug, 'while transforming', reducedUsageInfo);
123
+ return false;
124
+ }
125
+ reducedUsageInfo.typeId = foundType.id;
126
+
127
+ const foundTypeProperty = typeProperties.find(tp => tp.slug === reducedUsageInfo.typePropertySlug);
128
+ if (!foundTypeProperty) {
129
+ console.error('Could not find type property with slug', reducedUsageInfo.typePropertySlug, 'while transforming', reducedUsageInfo);
130
+ return false;
131
+ }
132
+ reducedUsageInfo.typePropertyId = foundTypeProperty.id;
133
+ return true;
134
+ }
File without changes