Repository navigation
Expand file tree
/
Copy pathchangeimportloc.py
More file actions
executable file
·437 lines (373 loc) · 16 KB
/
Copy pathchangeimportloc.py
File metadata and controls
executable file
·437 lines (373 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# changeimportloc.py
# December 2024
#
# Transforms relevant objects and values of an exported json file to
# to enable the exported content to be imported (or promoted) into
# an specific Viya folder, (initially only /Public is an option).
#
# Change History
# 29NOV2024 Initial release
# 02DEC2024 Restructure of Stage 2 and 3 to plug scenario gaps
# 03DEC2024 > Noted that the 'case_sensitive' argument from the 'Path' package was only released in Python 3.12+.
# Have added in a version check if statement/toggle to ensure this script's backwards capability.
# > Added 'Colour set and SAS check' section
# > Made the use of input arguments be overridden by SAS macros automatically when run from SAS Studio
# > Tidied up console messaging output
#
#
# Copyright © 2024, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
## Import Python modules
import argparse, sys, json, os
import pip
from pathlib import Path
### Pre-req checks
## Numpy
try:
import numpy as np
except ModuleNotFoundError:
print(red,"ERROR: The 'numpy' module is not installed, please install this to your local system and try again.",white)
exit()
## Python 3.4+
versionmajor=int(str(sys.version_info[0]))
versionminor=int(str(sys.version_info[1]))
sysvers=(sys.version)
if versionmajor < 3 or versionminor < 4:
print(red,"\nERROR: Python version 3.4, or above, is required for this script to run.\n\nThe Python currently in use is:\n\n"
+ cyan + sysvers + white)
exit()
## Defines variables
cwd = Path.cwd() # Sets current working dir.
objArr=np.array([], dtype='int16') #used in Stage 1
objCount=0 #used in Stage 1
hrefobj=0 #used in Stage 3
uriobj=0 #used in Stage 3
## Colour set and SAS check:
## If script is being run in SAS Studio, blank colour vars are set,
## else colour vars are defined for aesthetic purposes.
try:
SAS.submit("proc print data=_null_; run;")
print("Running script in SAS Studio...\n"+
"Ensure that the SAS macro variables \"source\" and \"outdir\" are set and are unquoted.\n")
## Defines empty colour vars
green=''
white=''
red=''
cyan=''
yellow=''
## Retrieves input from SAS macros
source=SAS.symget('source')
outdir=SAS.symget('outdir')
print("SAS macro "+source+" read in.\n"+
"SAS macro "+outdir+" read in.")
## DEBUG (SAS --> python var check)
#print("SAS macro 'source' as received by python = "+(SAS.symget('source')))
#print("SAS macro 'outdir' as received by python = "+(SAS.symget('outdir')))
except NameError:
## Defines colours as vars
green="\033[1;32;40m"
white="\033[1;37;40m"
red="\033[1;31;40m"
cyan="\033[1;36;40m"
yellow="\033[1;33;40m"
## Presents input options/arguments
parser = argparse.ArgumentParser(description="Modifies exported VA report json file to having /Public as it's source location")
parser.add_argument("-f","--file", help="Enter the path to the source file.",required='True')
parser.add_argument("-o","--outputdir", help="Enter the destination path for file/s output.",default=cwd)
args = parser.parse_args()
# Input via argument
source=args.file
outdir=args.outputdir
## Input via static assignment
#source='<filename>.json'
#outdir='<directory>'
## Defines Viya output location for report being transformed
## (could be made dynamic in the future, currently hardcoded for the values of /Public set on all Viya 4 environments)
ftarget=('/Public')
ftargeturi=('/folders/folders/751063da-3eea-4b1c-be09-dd55fd3c15c9')
ftargetid=('751063da-3eea-4b1c-be09-dd55fd3c15c9')
ftargetname=('Public')
## Formats the input json's file and resolves collapsed dirs
source=Path(source)
source=source.resolve()
## Validates that the input file has a .json file extension
if versionminor > 11 and Path(source).match('*.json', case_sensitive=None) == False:
print(red,"ERROR: A valid json file is required for this script to function. Please check your input file and try again.",white)
exit()
elif Path(source).match('*.json') == False:
print(red,"ERROR: A valid json file is required for this script to function. Please check your input file and try again.",white)
exit()
## Read in JSON file
with open(source, 'r') as f:
data = json.load(f)
## DEBUG: For reviewing json file content that's been parsed in
#print(json.dumps(data, indent = 4, sort_keys=False))
##########################
###### FUNCTIONS ######
##########################
## +++ objectcount()
## Counts objects directly underneath 'transferDetails' of a json
## file read in to the variable "data". It should be run at the
## start of every Stage, and after a 'del(data[...' command is run.
def objectcount():
global count
count=0
for obj in data['transferDetails']:
count += 1
## +++ setitr()
## Sets the 'itr' variable to '0'.
def setitr():
global itr
itr=0
##########################
###### Begin STAGE 1 ####
##########################
## Loops and scans through all 'transferObject' objects and removes all objects of
## "type": "folder", EXCEPT for one.
####
objectcount()
setitr()
for count in data['transferDetails']:
try:
if data['transferDetails'][itr]['transferObject']['summary']['type'] == "folder" and data['transferDetails'][itr]['connectors'][0]['type'] == "parentFolder":
## DEBUG
#print('\niteration= ',s1itr)
#print(data['transferDetails'][s1itr]['transferObject']['summary']['type'])
#print(data['transferDetails'][s1itr]['connectors'][0]['type'])
objArr=np.append(objArr,itr,axis=None)
itr += 1
else:
itr += 1
except IndexError:
itr = itr+1
pass
for obj in objArr:
objCount += 1
for obj in objArr:
try:
objCount -= 1
## DEBUG
#print('deleting iteration = ',objArr[objCount])
del(data['transferDetails'][objArr[objCount]])
except IndexError:
pass
#print(cyan)
print(cyan + "\nDELETED object(s):\n"+ white + str(objArr.size) + " x \'transferObject(s)\' and \'connector(s)\'\n")
##########################
###### End STAGE 1 ######
##########################
##########################
###### Begin STAGE 2 ####
##########################
## Loops and scan the remaining 'transferObject' object that has a 'folder' value and makes updates.
##
## Updates 'name' to variable 'ftargetname'
## Updates 'id' to variable 'ftargetid'
####
objectcount()
setitr()
for count in data['transferDetails']:
try:
if data['transferDetails'][itr]['transferObject']['summary']['type'] == "folder":
origname = data['transferDetails'][itr]['transferObject']['summary']['name']
origid1 = data['transferDetails'][itr]['transferObject']['summary']['id']
changedname=(cyan + "CHANGED 'transferObject' --> 'summary' --> 'name' object: \n"+white+origname+ " --> "+ftargetname+"\n")
changedid=(cyan + "\nCHANGED 'transferObject' --> 'summary' --> 'id' object: \n"+white+origid1+ " --> "+ftargetid+"\n")
nochangedname=(yellow+"NO CHANGE required to 'transferObject' --> 'summary' --> 'name' ("+origname+")")
nochangedid=(yellow+"\nNO CHANGE required to 'transferObject' --> 'summary' --> 'id' ("+origid1+")\n")
if origname != ftargetname or origid1 != ftargetid:
if origname != ftargetname and origid1 != ftargetid:
origid2 = origid1
data['transferDetails'][itr]['transferObject']['summary']['name'] = ftargetname
data['transferDetails'][itr]['transferObject']['summary']['id'] = ftargetid
print(changedname, changedid)
itr += 1
elif origname != ftargetname and origid1 == ftargetid:
origid2 = origid1
data['transferDetails'][itr]['transferObject']['summary']['name'] = ftargetname
print(changedname, nochangedid)
itr += 1
elif origname == ftargetname and origid1 != ftargetid:
origid2 = origid1
data['transferDetails'][itr]['transferObject']['summary']['id'] = ftargetid
print(nochangedname, changedid)
itr += 1
else:
origid2 = origid1
print(nochangedname, nochangedid)
itr += 1
else:
origid2 = origid1
print(nochangedname,'\n', nochangedid)
itr += 1
else:
itr += 1
except IndexError:
itr += 1
pass
##########################
###### End STAGE 2 ######
##########################
##########################
###### Begin STAGE 3 ####
##########################
## Searches for the sole 'transferObject' of type 'folder' (as per outcome of STAGE 1), and
## makes updates to nested objects within this object.
####
## Finds and replaces of the object's references to 'origid2', within the nested 'href' object, to 'ftargetid'
objectcount()
setitr()
if origid2 == ftargetid:
print(yellow+"NO CHANGE required to 'connectors' --> 'links' --> 'href' objects"+white+"\n")
print(yellow+"NO CHANGE required to 'connectors' --> 'links' --> 'uri' objects"+white+"\n")
else:
print(cyan+"CHANGED \"href\" value(s):"+white)
for count in data['transferDetails']:
try:
doesexist=data['transferDetails'][itr]['transferObject']['summary']['links'][hrefobj]
except IndexError:
pass
if data['transferDetails'][itr]['transferObject']['summary']['type'] == "folder" and origid2 != ftargetid:
try:
if origid2 in data['transferDetails'][itr]['transferObject']['summary']['links'][hrefobj]['href']:
orighref=data['transferDetails'][itr]['transferObject']['summary']['links'][hrefobj]['href']
data['transferDetails'][itr]['transferObject']['summary']['links'][hrefobj]['href']=data['transferDetails'][itr]['transferObject']['summary']['links'][hrefobj]['href'].replace(origid2,ftargetid)
print(orighref,"-->",data['transferDetails'][itr]['transferObject']['summary']['links'][hrefobj]['href'])
hrefobj += 1
else:
hrefobj = 0
itr += 1
except IndexError:
print("\n")
pass
else:
itr += 1
## Finds and replaces of the object's references to 'origid2', within the nested 'uri' object, to 'ftargetid'
setitr()
print(cyan,"\nCHANGED \"uri\" value(s):",white)
for count in data['transferDetails']:
try:
doesexist=data['transferDetails'][itr]['transferObject']['summary']['links'][uriobj]
except IndexError:
pass
if data['transferDetails'][itr]['transferObject']['summary']['type'] == "folder":
try:
if origid2 in data['transferDetails'][itr]['transferObject']['summary']['links'][uriobj]['uri']:
origuri=data['transferDetails'][itr]['transferObject']['summary']['links'][uriobj]['uri']
data['transferDetails'][itr]['transferObject']['summary']['links'][uriobj]['uri']=data['transferDetails'][itr]['transferObject']['summary']['links'][uriobj]['uri'].replace(origid2,ftargetid)
print(origuri,"-->",data['transferDetails'][itr]['transferObject']['summary']['links'][uriobj]['uri'])
uriobj += 1
else:
uriobj = 0
itr += 1
except IndexError:
print("\n")
pass
else:
itr += 1
##########################
###### End STAGE 3 ######
##########################
##########################
###### Begin STAGE 4 ####
##########################
## Loops and scans through all remaining (non 'folder') 'transferObject' objects making updates
####
##########################
#### Begin Part A ####
##########################
## Updates 'contentSourceLocation' to variable 'ftarget'
####
objectcount()
setitr()
print(cyan,"\nCHANGED \"contentSourceLocation\" value(s):",white)
for count in data['transferDetails']:
try:
if 'contentSourceLocation' in data['transferDetails'][itr]['transferObject']:
if data['transferDetails'][itr]['transferObject']['contentSourceLocation'] != ftarget:
origcsl = data['transferDetails'][itr]['transferObject']['contentSourceLocation']
data['transferDetails'][itr]['transferObject']['contentSourceLocation'] = ftarget
print(origcsl+ " --> " + ftarget)
itr += 1
else:
print("\nNo change to 'contentSourceLocation' required.")
itr += 1
else:
itr += 1
except IndexError:
pass
##########################
#### End Part A ####
##########################
##########################
#### Begin Part B ####
##########################
## Updates 'uri' to variable 'ftargeturi'
## Updates 'name' to variable 'ftargetname'
####
objectcount()
setitr()
print(cyan,"\nCHANGED \"connectors\" > \"uri\" & \"name\" value(s) of non-folder objects:",white)
for count in data['transferDetails']:
try:
doesexist=data['transferDetails'][itr]['connectors'][0]['uri']
except IndexError:
itr += 1
try:
if data['transferDetails'][itr]['transferObject']['summary']['type'] != "folder":
if data['transferDetails'][itr]['connectors'][0]['uri'] != ftargeturi:
origuri = data['transferDetails'][itr]['connectors'][0]['uri']
data['transferDetails'][itr]['connectors'][0]['uri'] = ftargeturi
print(origuri+ " --> " + ftargeturi)
else:
print("No change to \"connectors\" -> \"uri\" required.")
if data['transferDetails'][itr]['connectors'][0]['name'] != ftargetname:
origname = data['transferDetails'][itr]['connectors'][0]['name']
data['transferDetails'][itr]['connectors'][0]['name'] = ftargetname
print(origname+ " --> " + ftargetname)
else:
print("No change to \"connectors\" -> \"name\" required.")
itr += 1
else:
itr +=1
except IndexError:
pass
##########################
#### End Part B ####
##########################
##########################
###### End STAGE 4 ######
##########################
##########################
###### Begin STAGE 5 ####
##########################
## Writes out transformed json content to a new json file
####
# Remove absolute location and file extension
source=source.stem
# Append filename to outdir location
jsonout=Path(outdir, source)
# Add custom suffix
jsonout=jsonout.with_suffix('.modified.json')
# Write out JSON file
with open(jsonout, 'w') as f:
json.dump(data, f, indent = 2, sort_keys=False)
print(cyan,"\n\nJOB COMPLETE - new json file written to:\n\n",green,jsonout,white)
##########################
###### End STAGE 5 ######
##########################