Skip to content

Commit 0a44916

Browse files
A script for renaming a scan file to a different project version within the same project.
Take a directory of bdio files, copy and unzip each file, update the project and project version name to the name specified by the user, zip each jsonld file into a bdio of the same name as the source bdio.
1 parent ff537c2 commit 0a44916

File tree

1 file changed

+155
-0
lines changed

1 file changed

+155
-0
lines changed
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import argparse
2+
import json
3+
import os
4+
import shutil
5+
import sys
6+
import logging
7+
import zipfile
8+
from zipfile import ZIP_DEFLATED
9+
10+
parser = argparse.ArgumentParser("Take a directory of bdio files, copy and unzip each file,"
11+
"update the project and project version name to the name specified by the user,"
12+
"zip each jsonld file into a bdio of the same name as the source bdio. ")
13+
parser.add_argument('-d', '--bdio-directory', required=True, help="Directory path containing source bdio files")
14+
parser.add_argument('-n', '--project-name', required=True, default=None, help="Project name")
15+
parser.add_argument('-p', '--project-version', required=True, default=None, help="Target project version name")
16+
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='turn on DEBUG logging')
17+
18+
args = parser.parse_args()
19+
20+
21+
def set_logging_level(log_level):
22+
logging.basicConfig(stream=sys.stderr, level=log_level)
23+
24+
25+
if args.verbose:
26+
set_logging_level(logging.DEBUG)
27+
else:
28+
set_logging_level(logging.INFO)
29+
30+
# examples
31+
working_dir = os.getcwd()
32+
bdio_dir = os.path.join(working_dir, args.bdio_directory)
33+
project_name = args.project_name
34+
target_version = args.project_version
35+
temp_dir = os.path.join(working_dir, 'temp')
36+
renamed_directory = os.path.join(bdio_dir, "renamed_bdio")
37+
38+
39+
def do_refresh(dir_name):
40+
dir = os.path.join(working_dir, dir_name)
41+
for fileName in os.listdir(dir):
42+
print("Removing stale files {}".format(os.path.join(dir, fileName)))
43+
os.remove(os.path.join(dir, fileName))
44+
45+
46+
def check_dirs():
47+
os.chdir(working_dir)
48+
if not os.path.isdir('{}'.format(bdio_dir)) or len(os.listdir('{}'.format(bdio_dir))) <= 0:
49+
parser.print_help(sys.stdout)
50+
sys.exit(1)
51+
52+
if not os.path.isdir(temp_dir):
53+
os.makedirs(temp_dir)
54+
print('Made temp directory')
55+
elif len(os.listdir(temp_dir)) != 0:
56+
do_refresh(temp_dir)
57+
pass
58+
else:
59+
print('Temp directory already exists')
60+
61+
if not os.path.isdir(renamed_directory):
62+
os.makedirs(renamed_directory)
63+
print('Made renamed bdio directory')
64+
elif len(os.listdir(renamed_directory)) != 0:
65+
do_refresh(renamed_directory)
66+
else:
67+
print('Renamed bdio directory already exists')
68+
69+
70+
def zip_extract_files(zip_file, dir_name):
71+
print("Extracting content of {} into {}".format(zip_file, dir_name))
72+
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
73+
zip_ref.extractall(dir_name)
74+
75+
76+
def zip_create_archive(zip_file, dir_name):
77+
print("Writing content of {} into {} file".format(dir_name, zip_file))
78+
with zipfile.ZipFile(zip_file, mode='a', compression=ZIP_DEFLATED) as zipObj:
79+
for folderName, subfolders, filenames in os.walk(dir_name):
80+
jsonld_list = [x for x in filenames if x.endswith('.jsonld')]
81+
for filename in jsonld_list:
82+
filePath = os.path.join(folderName, filename)
83+
zipObj.write(filePath, os.path.basename(filePath))
84+
85+
86+
def jsonld_update_project_name(data, name):
87+
content_array = data['@graph']
88+
89+
for counter, array_entry in enumerate(content_array):
90+
if array_entry['@type'][0] == 'https://blackducksoftware.github.io/bdio#Project':
91+
logging.debug(counter)
92+
logging.debug(content_array[counter].keys())
93+
if "https://blackducksoftware.github.io/bdio#hasName" in content_array[counter]:
94+
content_array[counter]["https://blackducksoftware.github.io/bdio#hasName"][0]['@value'] = name
95+
logging.debug(content_array[counter])
96+
97+
98+
def jsonld_update_project_version(data, version):
99+
content_array = data['@graph']
100+
101+
for counter, array_entry in enumerate(content_array):
102+
if array_entry['@type'][0] == 'https://blackducksoftware.github.io/bdio#Project':
103+
logging.debug(counter)
104+
logging.debug(content_array[counter].keys())
105+
if "https://blackducksoftware.github.io/bdio#hasVersion" in content_array[counter]:
106+
content_array[counter]["https://blackducksoftware.github.io/bdio#hasVersion"][0]['@value'] = version
107+
logging.debug(content_array[counter])
108+
109+
110+
def read_json_object(filepath):
111+
with open(os.path.join(temp_dir, filepath)) as jsonfile:
112+
data = json.load(jsonfile)
113+
return data
114+
115+
116+
def write_json_file(filepath, data):
117+
with open(filepath, "w") as outfile:
118+
json.dump(data, outfile)
119+
120+
121+
# copy .bdio file to temp directory
122+
# unzip it
123+
# change the project version in jsonld file
124+
# zip files back in to a bdio file of the same name
125+
# copy from temp in to a directory named "renamed-bdios"
126+
# do the next bdio file
127+
# delete the contents of the temp directory
128+
def bdio_update_project_version():
129+
file_list = [x for x in os.listdir(bdio_dir) if x.endswith('.bdio')]
130+
for file in file_list:
131+
zip_extract_files(os.path.join(bdio_dir, file), temp_dir)
132+
os.chdir(temp_dir)
133+
output_bdio = os.path.join(temp_dir, file)
134+
jsonld_files = [y for y in os.listdir(temp_dir) if y.split('-').pop(1) == 'entry']
135+
for jsonld_file in jsonld_files:
136+
jsonld_path = os.path.join(temp_dir, jsonld_file)
137+
data = read_json_object(jsonld_path)
138+
jsonld_update_project_name(data, project_name)
139+
jsonld_update_project_version(data, target_version)
140+
write_json_file(jsonld_path, data)
141+
zip_create_archive(output_bdio, temp_dir)
142+
shutil.copy(output_bdio, renamed_directory)
143+
print('Cleaning up temp directory ')
144+
do_refresh('temp')
145+
os.chdir(working_dir)
146+
shutil.rmtree('temp')
147+
148+
149+
150+
def main():
151+
check_dirs()
152+
bdio_update_project_version()
153+
154+
155+
main()

0 commit comments

Comments
 (0)