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.

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