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.

827 lines
27 KiB

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