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