Tooling for managing asset compression, storage, and retrieval
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

778 lines
26 KiB

  1. #!/usr/bin/env python
  2. import asyncio
  3. import collections.abc
  4. import hashlib
  5. import io
  6. import json
  7. import os
  8. import pathlib
  9. import platform
  10. import sys
  11. import tempfile
  12. from typing import List, Dict, Callable
  13. import click
  14. from minio import Minio, ResponseError
  15. from minio.error import NoSuchKey
  16. # Size of the buffer to read files with
  17. BUF_SIZE = 4096
  18. #Application Version
  19. VERSION = "1.4.0"
  20. ###########
  21. # AsyncIO #
  22. ###########
  23. async def run_command_shell(
  24. command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, on_success: List[Callable] = [()]):
  25. """Run command in subprocess (shell).
  26. Note:
  27. This can be used if you wish to execute e.g. "copy"
  28. on Windows, which can only be executed in the shell.
  29. """
  30. process = await asyncio.create_subprocess_shell(
  31. command, stdout=stdout, stderr=stderr
  32. )
  33. process_stdout, process_stderr = await process.communicate()
  34. if process.returncode == 0:
  35. for callable in on_success:
  36. callable()
  37. if stdout != asyncio.subprocess.DEVNULL:
  38. result = process_stdout.decode().strip()
  39. return result
  40. else:
  41. return None
  42. def make_chunks(tasks, chunk_size):
  43. """Yield successive chunk_size-sized chunks from tasks.
  44. Note:
  45. Taken from https://stackoverflow.com/a/312464
  46. modified for python 3 only
  47. """
  48. for i in range(0, len(tasks), chunk_size):
  49. yield tasks[i: i + chunk_size]
  50. def run_asyncio_commands(tasks, max_concurrent_tasks=0):
  51. """Run tasks asynchronously using asyncio and return results.
  52. If max_concurrent_tasks are set to 0, no limit is applied.
  53. Note:
  54. By default, Windows uses SelectorEventLoop, which does not support
  55. subprocesses. Therefore ProactorEventLoop is used on Windows.
  56. https://docs.python.org/3/library/asyncio-eventloops.html#windows
  57. """
  58. all_results = []
  59. if max_concurrent_tasks == 0:
  60. chunks = [tasks]
  61. num_chunks = len(chunks)
  62. else:
  63. chunks = make_chunks(tasks=tasks, chunk_size=max_concurrent_tasks)
  64. num_chunks = len(list(make_chunks(tasks=tasks, chunk_size=max_concurrent_tasks)))
  65. if asyncio.get_event_loop().is_closed():
  66. asyncio.set_event_loop(asyncio.new_event_loop())
  67. if platform.system() == "Windows":
  68. asyncio.set_event_loop(asyncio.ProactorEventLoop())
  69. loop = asyncio.get_event_loop()
  70. chunk = 1
  71. for tasks_in_chunk in chunks:
  72. commands = asyncio.gather(*tasks_in_chunk)
  73. results = loop.run_until_complete(commands)
  74. all_results += results
  75. chunk += 1
  76. loop.close()
  77. return all_results
  78. ###########
  79. # Helpers #
  80. ###########
  81. def update(d, u):
  82. for k, v in u.items():
  83. if isinstance(v, collections.abc.Mapping):
  84. d[k] = update(d.get(k, {}), v)
  85. else:
  86. d[k] = v
  87. return d
  88. def get_metadata_name(key):
  89. return METADATA_PREFIX + 'SHA256SUM'.capitalize()
  90. def get_clean_stdin_iterator(stdin_stream):
  91. return (line for line in [line.strip() for line in stdin_stream if line.strip() != ''])
  92. def strip_prefix(prefix: str, file: str) -> str:
  93. if file.startswith(prefix):
  94. return file.replace(prefix, '')
  95. return file
  96. def get_file_identity(ctx_obj, file):
  97. if 'REMOVE_PREFIX' in ctx_obj and ctx_obj['REMOVE_PREFIX'] is not None:
  98. path = strip_prefix(ctx_obj['REMOVE_PREFIX'], file)
  99. else:
  100. path = file
  101. if os.pathsep != '/':
  102. path = '/'.join(path.split(os.pathsep))
  103. return path
  104. def list_s3_dir(s3: Minio, bucket: str, prefix: str) -> List[str]:
  105. found_files = []
  106. for obj in s3.list_objects_v2(bucket, prefix=prefix):
  107. if obj.is_dir:
  108. found_files.extend(list_s3_dir(s3, bucket, obj.object_name))
  109. else:
  110. found_files.append(obj.object_name)
  111. return found_files
  112. def get_s3_client(config: any) -> Minio:
  113. host = config['host']
  114. secure = config['secure']
  115. access_key = config['access']
  116. secret_key = config['secret']
  117. return Minio(host, secure=secure, access_key=access_key, secret_key=secret_key)
  118. def prep_s3(ctx):
  119. s3_config = ctx.obj['CONFIG']['s3']
  120. s3_bucket = ctx.obj['CONTEXT']
  121. s3 = get_s3_client(s3_config)
  122. if not s3.bucket_exists(s3_bucket):
  123. s3.make_bucket(s3_bucket)
  124. return s3_bucket, s3
  125. def get_file_sha256sum(stored_data, profile, file):
  126. stored_file_hash = stored_data['sha256sum']
  127. stored_profile_hash = stored_data['profileHash']
  128. sha256sum = hashlib.sha256()
  129. with open(file, 'rb') as f:
  130. for byte_block in iter(lambda: f.read(BUF_SIZE), b""):
  131. sha256sum.update(byte_block)
  132. calculated_file_hash = sha256sum.hexdigest()
  133. return stored_profile_hash, stored_file_hash, calculated_file_hash
  134. def get_string_sha256sum(string: str, encoding='utf-8') -> str:
  135. sha256sum = hashlib.sha256()
  136. with io.BytesIO(json.dumps(string).encode(encoding)) as c:
  137. for byte_block in iter(lambda: c.read(BUF_SIZE), b''):
  138. sha256sum.update(byte_block)
  139. return sha256sum.hexdigest()
  140. def add_nested_key(config: Dict[str, any], path: List[str], value: str) -> bool:
  141. target = path[0].lower()
  142. if len(path) == 1:
  143. config[target] = value
  144. return True
  145. else:
  146. if target not in config:
  147. config[target] = {}
  148. add_nested_key(config[target], path[1:],value)
  149. return False
  150. def read_env_config(prefix, separator='__') -> any:
  151. prefix = prefix+separator
  152. env_config = {}
  153. environment_variables = [env for env in os.environ.keys() if env.startswith(prefix)]
  154. for env in environment_variables:
  155. path = env[len(prefix):].split('__')
  156. add_nested_key(env_config, path, os.environ[env])
  157. return env_config
  158. def load_config(path: str) -> any:
  159. combined_config = {}
  160. with open(
  161. os.path.join(
  162. os.path.dirname(os.path.realpath(__file__)),
  163. 'acm-config-default.json'),
  164. 'r') as combined_config_file:
  165. combined_config = json.load(combined_config_file)
  166. config = {}
  167. with open(path, 'r') as config_file:
  168. config = json.load(config_file)
  169. # Setup concurrency
  170. if 'concurrency' in config:
  171. config['concurrency'] = abs(int(config['concurrency']))
  172. else:
  173. config['concurrency'] = 0
  174. update(combined_config, config)
  175. update(combined_config, read_env_config('ACM'))
  176. # Calculate profiles hash
  177. profile_hashes={}
  178. profile_hashes['all'] = get_string_sha256sum(json.dumps(combined_config['profiles']))
  179. for profile in combined_config['profiles'].keys():
  180. profile_hashes[profile] = get_string_sha256sum(json.dumps(combined_config['profiles'][profile]))
  181. combined_config['profileHashes'] = profile_hashes
  182. return combined_config
  183. @click.group()
  184. @click.option('-d', '--debug/--no-debug', default=False)
  185. @click.option('-c', '--config', default=lambda: os.path.join(os.getcwd(), 'acm-config.json'), show_default=True)
  186. @click.option('-s', '--stdin/--no-stdin', default=False)
  187. @click.option('--remove-prefix', default=None)
  188. @click.option('--add-prefix', default=None)
  189. @click.pass_context
  190. def cli(ctx, debug, config, stdin, remove_prefix, add_prefix):
  191. ctx.ensure_object(dict)
  192. ctx.obj['DEBUG'] = debug
  193. ctx.obj['CONFIG'] = load_config(config)
  194. ctx.obj['READ_STDIN'] = stdin
  195. ctx.obj['REMOVE_PREFIX'] = remove_prefix
  196. ctx.obj['ADD_PREFIX'] = add_prefix
  197. ####################
  198. # Generic Commands #
  199. ####################
  200. @cli.command(name="config")
  201. @click.pass_context
  202. def print_config(ctx):
  203. """
  204. Print the configuration
  205. """
  206. print(json.dumps(ctx.obj['CONFIG'], indent=2, sort_keys=True))
  207. ###############################
  208. # S3 Storage Focused Commands #
  209. ###############################
  210. @cli.command(name="list")
  211. @click.option('--sha256sum/--no-sha256sum', default=False)
  212. @click.option('--suffix', default=None)
  213. @click.option('-x', '--context', required=True)
  214. @click.option('--print-identity/--no-print-identity', default=False)
  215. @click.pass_context
  216. def list_files(ctx, context, sha256sum, suffix, print_identity):
  217. """
  218. List all file object in a bucket
  219. """
  220. ctx.obj['CONTEXT'] = context
  221. s3_config = ctx.obj['CONFIG']['s3']
  222. s3_bucket = ctx.obj['CONTEXT']
  223. s3 = get_s3_client(s3_config)
  224. if not s3.bucket_exists(s3_bucket):
  225. s3.make_bucket(s3_bucket)
  226. found_files: List[str] = []
  227. found_objects: List[str] = []
  228. for obj in s3.list_objects_v2(s3_bucket, recursive=False):
  229. if obj.is_dir:
  230. found_objects.extend(list_s3_dir(s3, s3_bucket, obj.object_name))
  231. else:
  232. found_objects.append(obj.object_name)
  233. for obj in found_objects:
  234. file = obj
  235. if 'REMOVE_PREFIX' in ctx.obj and ctx.obj['REMOVE_PREFIX'] is not None:
  236. file = os.path.join(ctx.obj['REMOVE_PREFIX'], file)
  237. if suffix is not None and suffix in file:
  238. file = file.replace(suffix, '')
  239. file = file.strip()
  240. if sha256sum:
  241. file_object = s3.get_object(s3_bucket, obj)
  242. stored_data = json.load(file_object)
  243. sha256sum_value = stored_data['sha256sum']
  244. file = f'{sha256sum_value} {file}'
  245. elif print_identity:
  246. file_object = s3.get_object(s3_bucket, obj)
  247. stored_data = json.load(file_object)
  248. found_files.append(stored_data['storedAssetIdentity'])
  249. else:
  250. found_files.append(file)
  251. print(os.linesep.join(found_files))
  252. @cli.command(name="match")
  253. @click.option('-x', '--context', required=True)
  254. @click.option('--print-identity/--no-print-identity', default=False)
  255. @click.option('-p', '--profile', default='all')
  256. @click.argument('files', nargs=-1)
  257. @click.pass_context
  258. def check_matched_files_hashes(ctx, context, print_identity, profile, files):
  259. """
  260. List all files that have matching stored sha256sum and profile hash
  261. """
  262. ctx.obj['CONTEXT'] = context
  263. s3_bucket, s3 = prep_s3(ctx)
  264. matching_files: List[str] = []
  265. if ctx.obj['READ_STDIN']:
  266. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  267. for file in files:
  268. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  269. try:
  270. file_object = s3.get_object(s3_bucket, file_identity)
  271. stored_data = json.load(file_object)
  272. stored_profile_hash, stored_file_hash, calculated_file_hash = get_file_sha256sum(stored_data, profile, file)
  273. if calculated_file_hash == stored_file_hash \
  274. and ctx.obj['CONFIG']['profileHashes'][profile] == stored_profile_hash:
  275. if print_identity:
  276. matching_files.append(stored_data['storedAssetIdentity'])
  277. else:
  278. matching_files.append(file)
  279. except NoSuchKey as e:
  280. continue
  281. except ValueError or ResponseError as e:
  282. print(f'ERROR: {file} {e}')
  283. print(os.linesep.join(matching_files))
  284. @cli.command(name="check")
  285. @click.option('-x', '--context', required=True)
  286. @click.option('-p', '--profile', default='all')
  287. @click.argument('files', nargs=-1)
  288. @click.pass_context
  289. def check_changed_files_hashes(ctx, context, profile, files):
  290. """
  291. List all files that do not have a matching sha256sum or profile hash
  292. """
  293. ctx.obj['CONTEXT'] = context
  294. s3_bucket, s3 = prep_s3(ctx)
  295. changed_files: List[str] = []
  296. if ctx.obj['READ_STDIN']:
  297. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  298. for file in files:
  299. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  300. try:
  301. file_object = s3.get_object(s3_bucket, file_identity)
  302. stored_data = json.load(file_object)
  303. stored_profile_hash, stored_file_hash, calculated_file_hash = get_file_sha256sum(stored_data, profile, file)
  304. if calculated_file_hash != stored_file_hash \
  305. or ctx.obj['CONFIG']['profileHashes'][profile] != stored_profile_hash:
  306. changed_files.append(file)
  307. except NoSuchKey as e:
  308. changed_files.append(file)
  309. except ValueError or ResponseError as e:
  310. print(f'ERROR: {file} {e}')
  311. print(os.linesep.join(changed_files))
  312. @cli.command(name="update")
  313. @click.option('-x', '--context', required=True)
  314. @click.option('--input-and-identity/--no-input-and-identity', default=False)
  315. @click.option('-p', '--profile', default='all')
  316. @click.argument('files', nargs=-1)
  317. @click.pass_context
  318. def update_changed_files_hashes(ctx, context, input_and_identity, profile, files):
  319. """
  320. Store new data objects for the provided files
  321. """
  322. ctx.obj['CONTEXT'] = context
  323. s3_bucket, s3 = prep_s3(ctx)
  324. updated_files: List[str] = []
  325. if ctx.obj['READ_STDIN']:
  326. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  327. for file in files:
  328. identity = None
  329. if input_and_identity:
  330. file, identity = file.split('\t')
  331. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  332. try:
  333. sha256sum = hashlib.sha256()
  334. with open(file, 'rb') as f:
  335. for byte_block in iter(lambda: f.read(BUF_SIZE), b''):
  336. sha256sum.update(byte_block)
  337. calculated_file_hash = sha256sum.hexdigest()
  338. object_data = {
  339. "sourcePath": file,
  340. "storedAssetIdentity": identity,
  341. "identity": file_identity,
  342. "sha256sum": calculated_file_hash,
  343. "profileHash": ctx.obj['CONFIG']['profileHashes'][profile]
  344. }
  345. with io.BytesIO(json.dumps(object_data, sort_keys=True, indent=None).encode('utf-8')) as data:
  346. data.seek(0, os.SEEK_END)
  347. data_length = data.tell()
  348. data.seek(0)
  349. s3.put_object(
  350. s3_bucket,
  351. file_identity,
  352. data,
  353. data_length,
  354. content_type="application/json",
  355. metadata={}
  356. )
  357. updated_files.append(file)
  358. except ValueError or ResponseError as e:
  359. print(f'ERROR: {file} {e}')
  360. print(os.linesep.join(updated_files))
  361. @cli.command(name="store")
  362. @click.option('-x', '--context', required=True)
  363. @click.argument('files', nargs=-1)
  364. @click.pass_context
  365. def store_files(ctx, context, files):
  366. """
  367. Store specified files in a <context> bucket for retrieval.
  368. """
  369. ctx.obj['CONTEXT'] = context
  370. s3_bucket, s3 = prep_s3(ctx)
  371. stored_files: List[str] = []
  372. if ctx.obj['READ_STDIN']:
  373. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  374. for file in files:
  375. file_identity = get_file_identity(ctx.obj, file)
  376. try:
  377. s3.fput_object(
  378. s3_bucket,
  379. file_identity,
  380. file,
  381. content_type="application/octet-stream"
  382. )
  383. if 'ADD_PREFIX' in ctx.obj and ctx.obj['ADD_PREFIX'] is not None:
  384. stored_files.append(os.path.join(ctx.obj['ADD_PREFIX'], file_identity))
  385. else:
  386. stored_files.append(file)
  387. except ResponseError as e:
  388. print(f'ERROR: {file} {e}', file=sys.stderr)
  389. print(os.linesep.join(stored_files))
  390. @cli.command(name="retrieve")
  391. @click.option('-x', '--context', required=True)
  392. @click.option('-d', '--destination', default=None)
  393. @click.argument('files', nargs=-1)
  394. @click.pass_context
  395. def retrieve_files(ctx, context, destination, files):
  396. """
  397. Retrieve specified files from a <context> bucket
  398. """
  399. ctx.obj['CONTEXT'] = context
  400. s3_bucket, s3 = prep_s3(ctx)
  401. retrieved_files: List[str] = []
  402. if ctx.obj['READ_STDIN']:
  403. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  404. for file in files:
  405. file_identity = get_file_identity(ctx.obj, file)
  406. file_destination = file
  407. if destination is not None:
  408. file_destination = os.path.join(destination, file_identity)
  409. try:
  410. s3.fget_object(
  411. s3_bucket,
  412. file_identity,
  413. file_destination
  414. )
  415. retrieved_files.append(file_destination)
  416. except NoSuchKey as e:
  417. print(f'ERROR: {file_identity} {file_destination} {e}', file=sys.stderr)
  418. except ResponseError as e:
  419. print(f'ERROR: {file_destination} {e}', file=sys.stderr)
  420. print(os.linesep.join(retrieved_files))
  421. @cli.command(name="clean")
  422. @click.option('-x', '--context', required=True)
  423. @click.option('-d', '--context-data', default=None)
  424. @click.option('-n', '--dry-run/--no-dry-run', default=False)
  425. @click.argument('files', nargs=-1)
  426. @click.pass_context
  427. def clean_files(ctx, context, context_data, dry_run, files):
  428. """
  429. Remove non matching specified files in a <context> bucket for retrieval.
  430. """
  431. ctx.obj['CONTEXT'] = context
  432. s3_bucket, s3 = prep_s3(ctx)
  433. s3_data_bucket = context_data
  434. found_files: List[str] = []
  435. found_data_files: List[str] = []
  436. removed_files: List[str] = []
  437. if ctx.obj['READ_STDIN']:
  438. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  439. # Go through and find all matching files
  440. for file in files:
  441. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  442. try:
  443. if s3_data_bucket is not None:
  444. file_object = s3.get_object(s3_bucket, file_identity)
  445. stored_data = json.load(file_object)
  446. stored_data_file_identity = stored_data['storedAssetIdentity']
  447. found_files.append(file_identity)
  448. found_data_files.append(stored_data_file_identity)
  449. else:
  450. file_object = s3.get_object(s3_bucket, file_identity)
  451. found_files.append(file_identity)
  452. except ResponseError as e:
  453. print(f'ERROR: ResponseError {file_identity} {e}', file=sys.stderr)
  454. except NoSuchKey as e:
  455. print(f'ERROR: NoSuchKey {file_identity}', file=sys.stderr)
  456. # print(os.linesep.join(found_objects))
  457. # print(os.linesep.join(found_objects))
  458. found_files = set(found_files)
  459. found_data_files = set(found_data_files)
  460. # Find all objects in s3 bucket
  461. found_objects: List[str] = []
  462. for obj in s3.list_objects_v2(s3_bucket, recursive=False):
  463. if obj.is_dir:
  464. found_objects.extend(list_s3_dir(s3, s3_bucket, obj.object_name))
  465. else:
  466. found_objects.append(obj.object_name)
  467. # print(os.linesep.join(found_objects))
  468. found_data_objects: List[str] = []
  469. for obj in s3.list_objects_v2(s3_data_bucket, recursive=False):
  470. if obj.is_dir:
  471. found_data_objects.extend(list_s3_dir(s3, s3_data_bucket, obj.object_name))
  472. else:
  473. found_data_objects.append(obj.object_name)
  474. # print(os.linesep.join(found_data_objects))
  475. for file_identity in found_objects:
  476. if not file_identity in found_files:
  477. if dry_run:
  478. removed_files.append(f'{s3_bucket}:{file_identity}')
  479. else:
  480. try:
  481. s3.remove_object(s3_bucket, file_identity)
  482. removed_files.append(f'{s3_bucket}:{file_identity}')
  483. except ResponseError as e:
  484. print(f'ERROR: {s3_bucket}:{file_identity} {e}', file=sys.stderr)
  485. for file_data_identity in found_data_objects:
  486. if not file_data_identity in found_data_files:
  487. if dry_run:
  488. removed_files.append(f'{s3_data_bucket}:{file_data_identity}')
  489. else:
  490. try:
  491. s3.remove_object(s3_data_bucket, file_data_identity)
  492. removed_files.append(f'{s3_data_bucket}:{file_data_identity}')
  493. except ResponseError as e:
  494. print(f'ERROR: {s3_data_bucket}:{file_data_identity} {e}', file=sys.stderr)
  495. print(os.linesep.join(removed_files))
  496. ######################################
  497. # Asset Compression Focused Commands #
  498. ######################################
  499. @cli.command(name="compress")
  500. @click.option('-p', '--profile', default='default')
  501. @click.option('-c', '--content', default='all')
  502. @click.option('-d', '--destination', default=None)
  503. @click.option('--print-input-and-identity/--no-print-input-and-identity', default=False)
  504. @click.argument('files', nargs=-1)
  505. @click.pass_context
  506. def compress_assets(ctx, profile, content, destination, print_input_and_identity, files):
  507. """
  508. Compress the request files and store them in a storage bucket.
  509. """
  510. profiles = ctx.obj['CONFIG']['profiles']
  511. if profile not in profiles:
  512. raise ValueError(f'Unrecognized profile: {profile}')
  513. default_profile: Dict[str, any] = profiles['default']
  514. profile: Dict[str, any] = profiles[profile]
  515. if content != 'all':
  516. if content not in profile and content not in default_profile:
  517. raise ValueError(f'Unrecognized content: {content}')
  518. content_configurations = []
  519. if content == 'all':
  520. content_names: set = set()
  521. for content_name in profile.keys():
  522. content_names.add(content_name)
  523. content_configurations.append(profile[content_name])
  524. for content_name in default_profile.keys():
  525. if content_name not in content_names:
  526. content_names.add(content_name)
  527. content_configurations.append(default_profile[content_name])
  528. else:
  529. if content in profile:
  530. content_configurations.append(profile[content])
  531. else:
  532. content_configurations.append(default_profile[content])
  533. if ctx.obj['READ_STDIN']:
  534. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  535. if destination is None:
  536. destination = tempfile.mkdtemp()
  537. task_output = []
  538. tasks = []
  539. follow_up_tasks = []
  540. def store_filename(storage_list: List[str], filename: str):
  541. """
  542. A simple lambda wrapper to asynchronously add processed files to the list
  543. :param storage_list:
  544. :param filename:
  545. :return:
  546. """
  547. return lambda: storage_list.append(filename)
  548. def queue_follow_up_task_if_keep_smaller_input(follow_up_tasks, input_file: str, output_file: str, keep_smaller_input: bool = True):
  549. """
  550. A lambda wrapper that handles keeping the smallest of the two files.
  551. """
  552. if keep_smaller_input:
  553. command = f"cp {input_file} {output_file}"
  554. return lambda:
  555. input_size = os.path.getsize(input_file)
  556. output_size = os.path.getsize(output_file)
  557. if output_size > input_size:
  558. follow_up_tasks.append(
  559. run_command_shell(
  560. command,
  561. stdout=asyncio.subprocess.DEVNULL,
  562. stderr=asyncio.subprocess.DEVNULL,
  563. on_success=[store_filename(
  564. task_output,
  565. f'Preserved smaller "{input_file}" {output_size} > {input_size}'
  566. )]
  567. )
  568. )
  569. return None
  570. for input_file in files:
  571. for content_configuration in content_configurations:
  572. if any([input_file.endswith(extension) for extension in content_configuration['extensions']]):
  573. file = input_file
  574. file_extension = pathlib.Path(input_file).suffix
  575. if 'REMOVE_PREFIX' in ctx.obj and ctx.obj['REMOVE_PREFIX'] is not None:
  576. file = strip_prefix(ctx.obj['REMOVE_PREFIX'], input_file)
  577. if 'preserveInputExtension' in content_configuration \
  578. and content_configuration['preserveInputExtension']:
  579. output_file = os.path.join(destination, file)
  580. else:
  581. output_file_without_ext = os.path.splitext(os.path.join(destination, file))[0]
  582. output_file = f'{output_file_without_ext}.{content_configuration["outputExtension"]}'
  583. output_file_identity = get_file_identity({'REMOVE_PREFIX': destination}, output_file)
  584. output_file_dir = os.path.dirname(output_file)
  585. os.makedirs(output_file_dir, exist_ok=True)
  586. if 'preserveSmallerInput' in content_configuration:
  587. preserve_smaller_input = bool(content_configuration['preserveSmallerInput'])
  588. else:
  589. preserve_smaller_input = True
  590. if 'forcePreserveSmallerInput' in content_configuration:
  591. force_preserve_smaller_input = bool(content_configuration['forcePreserveSmallerInput'])
  592. else:
  593. force_preserve_smaller_input = False
  594. # Only preserve the input if requested AND the extensions of the input and the output match
  595. preserve_smaller_input = preserve_smaller_input and (force_preserve_smaller_input or file_extension == content_configuration["outputExtension"])
  596. command: str = content_configuration['command'] \
  597. .replace('{input_file}', f'\'{input_file}\'') \
  598. .replace('{output_file}', f'\'{output_file}\'')
  599. tasks.append(
  600. run_command_shell(
  601. command,
  602. stdout=asyncio.subprocess.DEVNULL,
  603. stderr=asyncio.subprocess.DEVNULL,
  604. on_success=[store_filename(
  605. task_output,
  606. f'{input_file}\t{output_file_identity}' if print_input_and_identity else output_file
  607. ),queue_follow_up_task_if_keep_smaller_input(
  608. follow_up_tasks,
  609. input_file,
  610. output_file,
  611. preserve_smaller_input
  612. )]
  613. )
  614. )
  615. results = run_asyncio_commands(
  616. tasks, max_concurrent_tasks=ctx.obj['CONFIG']['concurrency']
  617. )
  618. follow_up_results = run_asyncio_commands(
  619. follow_up_tasks, max_concurrent_tasks=ctx.obj['CONFIG']['concurrency']
  620. )
  621. print(os.linesep.join(task_output))
  622. if __name__ == '__main__':
  623. cli(obj={})