logging_util.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. __package__ = 'archivebox'
  2. import re
  3. import os
  4. import sys
  5. import stat
  6. import time
  7. from math import log
  8. from multiprocessing import Process
  9. from pathlib import Path
  10. from datetime import datetime, timezone
  11. from dataclasses import dataclass
  12. from typing import Any, Optional, List, Dict, Union, IO, TYPE_CHECKING
  13. if TYPE_CHECKING:
  14. from .index.schema import Link, ArchiveResult
  15. from rich import print
  16. from rich.panel import Panel
  17. from rich_argparse import RichHelpFormatter
  18. from django.core.management.base import DjangoHelpFormatter
  19. from archivebox.config import CONSTANTS, DATA_DIR, VERSION, SHELL_CONFIG
  20. from archivebox.misc.system import get_dir_size
  21. from archivebox.misc.util import enforce_types
  22. from archivebox.misc.logging import ANSI, stderr
  23. @dataclass
  24. class RuntimeStats:
  25. """mutable stats counter for logging archiving timing info to CLI output"""
  26. skipped: int = 0
  27. succeeded: int = 0
  28. failed: int = 0
  29. parse_start_ts: Optional[datetime] = None
  30. parse_end_ts: Optional[datetime] = None
  31. index_start_ts: Optional[datetime] = None
  32. index_end_ts: Optional[datetime] = None
  33. archiving_start_ts: Optional[datetime] = None
  34. archiving_end_ts: Optional[datetime] = None
  35. # globals are bad, mmkay
  36. _LAST_RUN_STATS = RuntimeStats()
  37. def debug_dict_summary(obj: Dict[Any, Any]) -> None:
  38. stderr(' '.join(f'{key}={str(val).ljust(6)}' for key, val in obj.items()))
  39. def get_fd_info(fd) -> Dict[str, Any]:
  40. NAME = fd.name[1:-1]
  41. FILENO = fd.fileno()
  42. MODE = os.fstat(FILENO).st_mode
  43. IS_TTY = hasattr(fd, 'isatty') and fd.isatty()
  44. IS_PIPE = stat.S_ISFIFO(MODE)
  45. IS_FILE = stat.S_ISREG(MODE)
  46. IS_TERMINAL = not (IS_PIPE or IS_FILE)
  47. IS_LINE_BUFFERED = fd.line_buffering
  48. IS_READABLE = fd.readable()
  49. return {
  50. 'NAME': NAME, 'FILENO': FILENO, 'MODE': MODE,
  51. 'IS_TTY': IS_TTY, 'IS_PIPE': IS_PIPE, 'IS_FILE': IS_FILE,
  52. 'IS_TERMINAL': IS_TERMINAL, 'IS_LINE_BUFFERED': IS_LINE_BUFFERED,
  53. 'IS_READABLE': IS_READABLE,
  54. }
  55. # # Log debug information about stdin, stdout, and stderr
  56. # sys.stdout.write('[>&1] this is python stdout\n')
  57. # sys.stderr.write('[>&2] this is python stderr\n')
  58. # debug_dict_summary(get_fd_info(sys.stdin))
  59. # debug_dict_summary(get_fd_info(sys.stdout))
  60. # debug_dict_summary(get_fd_info(sys.stderr))
  61. class SmartFormatter(DjangoHelpFormatter, RichHelpFormatter):
  62. """Patched formatter that prints newlines in argparse help strings"""
  63. def _split_lines(self, text, width):
  64. if '\n' in text:
  65. return text.splitlines()
  66. return RichHelpFormatter._split_lines(self, text, width)
  67. def reject_stdin(caller: str, stdin: Optional[IO]=sys.stdin) -> None:
  68. """Tell the user they passed stdin to a command that doesn't accept it"""
  69. if not stdin:
  70. return None
  71. if os.environ.get('IN_DOCKER') in ('1', 'true', 'True', 'TRUE', 'yes'):
  72. # when TTY is disabled in docker we cant tell if stdin is being piped in or not
  73. # if we try to read stdin when its not piped we will hang indefinitely waiting for it
  74. return None
  75. if not stdin.isatty():
  76. # stderr('READING STDIN TO REJECT...')
  77. stdin_raw_text = stdin.read()
  78. if stdin_raw_text.strip():
  79. # stderr('GOT STDIN!', len(stdin_str))
  80. stderr(f'[!] The "{caller}" command does not accept stdin (ignoring).', color='red')
  81. stderr(f' Run archivebox "{caller} --help" to see usage and examples.')
  82. stderr()
  83. # raise SystemExit(1)
  84. return None
  85. def accept_stdin(stdin: Optional[IO]=sys.stdin) -> Optional[str]:
  86. """accept any standard input and return it as a string or None"""
  87. if not stdin:
  88. return None
  89. if not stdin.isatty():
  90. # stderr('READING STDIN TO ACCEPT...')
  91. stdin_str = stdin.read()
  92. if stdin_str:
  93. # stderr('GOT STDIN...', len(stdin_str))
  94. return stdin_str
  95. return None
  96. class TimedProgress:
  97. """Show a progress bar and measure elapsed time until .end() is called"""
  98. def __init__(self, seconds, prefix=''):
  99. self.SHOW_PROGRESS = SHELL_CONFIG.SHOW_PROGRESS
  100. self.ANSI = SHELL_CONFIG.ANSI
  101. if self.SHOW_PROGRESS:
  102. self.p = Process(target=progress_bar, args=(seconds, prefix, self.ANSI))
  103. self.p.start()
  104. self.stats = {'start_ts': datetime.now(timezone.utc), 'end_ts': None}
  105. def end(self):
  106. """immediately end progress, clear the progressbar line, and save end_ts"""
  107. end_ts = datetime.now(timezone.utc)
  108. self.stats['end_ts'] = end_ts
  109. if self.SHOW_PROGRESS:
  110. # terminate if we havent already terminated
  111. try:
  112. # kill the progress bar subprocess
  113. try:
  114. self.p.close() # must be closed *before* its terminnated
  115. except (KeyboardInterrupt, SystemExit):
  116. print()
  117. raise
  118. except BaseException: # lgtm [py/catch-base-exception]
  119. pass
  120. self.p.terminate()
  121. self.p.join()
  122. # clear whole terminal line
  123. try:
  124. sys.stdout.write('\r{}{}\r'.format((' ' * SHELL_CONFIG.TERM_WIDTH), self.ANSI['reset']))
  125. except (IOError, BrokenPipeError):
  126. # ignore when the parent proc has stopped listening to our stdout
  127. pass
  128. except ValueError:
  129. pass
  130. @enforce_types
  131. def progress_bar(seconds: int, prefix: str='', ANSI: Dict[str, str]=ANSI) -> None:
  132. """show timer in the form of progress bar, with percentage and seconds remaining"""
  133. output_buf = (sys.stdout or sys.__stdout__ or sys.stderr or sys.__stderr__)
  134. chunk = '█' if output_buf and output_buf.encoding.upper() == 'UTF-8' else '#'
  135. last_width = SHELL_CONFIG.TERM_WIDTH
  136. chunks = last_width - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
  137. try:
  138. for s in range(seconds * chunks):
  139. max_width = SHELL_CONFIG.TERM_WIDTH
  140. if max_width < last_width:
  141. # when the terminal size is shrunk, we have to write a newline
  142. # otherwise the progress bar will keep wrapping incorrectly
  143. sys.stdout.write('\r\n')
  144. sys.stdout.flush()
  145. chunks = max_width - len(prefix) - 20
  146. pct_complete = s / chunks / seconds * 100
  147. log_pct = (log(pct_complete or 1, 10) / 2) * 100 # everyone likes faster progress bars ;)
  148. bar_width = round(log_pct/(100/chunks))
  149. last_width = max_width
  150. # ████████████████████ 0.9% (1/60sec)
  151. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  152. prefix,
  153. ANSI['green' if pct_complete < 80 else 'lightyellow'],
  154. (chunk * bar_width).ljust(chunks),
  155. ANSI['reset'],
  156. round(pct_complete, 1),
  157. round(s/chunks),
  158. seconds,
  159. ))
  160. sys.stdout.flush()
  161. time.sleep(1 / chunks)
  162. # ██████████████████████████████████ 100.0% (60/60sec)
  163. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  164. prefix,
  165. ANSI['red'],
  166. chunk * chunks,
  167. ANSI['reset'],
  168. 100.0,
  169. seconds,
  170. seconds,
  171. ))
  172. sys.stdout.flush()
  173. # uncomment to have it disappear when it hits 100% instead of staying full red:
  174. # time.sleep(0.5)
  175. # sys.stdout.write('\r{}{}\r'.format((' ' * SHELL_CONFIG.TERM_WIDTH), ANSI['reset']))
  176. # sys.stdout.flush()
  177. except (KeyboardInterrupt, BrokenPipeError):
  178. print()
  179. def log_cli_command(subcommand: str, subcommand_args: List[str], stdin: Optional[str | IO], pwd: str='.'):
  180. args = ' '.join(subcommand_args)
  181. version_msg = '[dark_magenta]\\[{now}][/dark_magenta] [dark_red]ArchiveBox[/dark_red] [dark_goldenrod]v{VERSION}[/dark_goldenrod]: [green4]archivebox [green3]{subcommand}[green2] {args}[/green2]'.format(
  182. now=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S'),
  183. VERSION=VERSION,
  184. subcommand=subcommand,
  185. args=args,
  186. )
  187. # stderr()
  188. # stderr('[bright_black] > {pwd}[/]'.format(pwd=pwd, **ANSI))
  189. # stderr()
  190. print(Panel(version_msg), file=sys.stderr)
  191. ### Parsing Stage
  192. def log_importing_started(urls: Union[str, List[str]], depth: int, index_only: bool):
  193. _LAST_RUN_STATS.parse_start_ts = datetime.now(timezone.utc)
  194. print('[green][+] [{}] Adding {} links to index (crawl depth={}){}...[/]'.format(
  195. _LAST_RUN_STATS.parse_start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  196. len(urls) if isinstance(urls, list) else len(urls.split('\n')),
  197. depth,
  198. ' (index only)' if index_only else '',
  199. ))
  200. def log_source_saved(source_file: str):
  201. print(' > Saved verbatim input to {}/{}'.format(CONSTANTS.SOURCES_DIR_NAME, source_file.rsplit('/', 1)[-1]))
  202. def log_parsing_finished(num_parsed: int, parser_name: str):
  203. _LAST_RUN_STATS.parse_end_ts = datetime.now(timezone.utc)
  204. print(' > Parsed {} URLs from input ({})'.format(num_parsed, parser_name))
  205. def log_deduping_finished(num_new_links: int):
  206. print(' > Found {} new URLs not already in index'.format(num_new_links))
  207. def log_crawl_started(new_links):
  208. print()
  209. print(f'[green][*] Starting crawl of {len(new_links)} sites 1 hop out from starting point[/]')
  210. ### Indexing Stage
  211. def log_indexing_process_started(num_links: int):
  212. start_ts = datetime.now(timezone.utc)
  213. _LAST_RUN_STATS.index_start_ts = start_ts
  214. print()
  215. print('[bright_black][*] [{}] Writing {} links to main index...[/]'.format(
  216. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  217. num_links,
  218. ))
  219. def log_indexing_process_finished():
  220. end_ts = datetime.now(timezone.utc)
  221. _LAST_RUN_STATS.index_end_ts = end_ts
  222. def log_indexing_started(out_path: str):
  223. if SHELL_CONFIG.IS_TTY:
  224. sys.stdout.write(f' > ./{Path(out_path).relative_to(DATA_DIR)}')
  225. def log_indexing_finished(out_path: str):
  226. print(f'\r √ ./{Path(out_path).relative_to(DATA_DIR)}')
  227. ### Archiving Stage
  228. def log_archiving_started(num_links: int, resume: Optional[float]=None):
  229. start_ts = datetime.now(timezone.utc)
  230. _LAST_RUN_STATS.archiving_start_ts = start_ts
  231. print()
  232. if resume:
  233. print('[green][▶] [{}] Resuming archive updating for {} pages starting from {}...[/]'.format(
  234. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  235. num_links,
  236. resume,
  237. ))
  238. else:
  239. print('[green][▶] [{}] Starting archiving of {} snapshots in index...[/]'.format(
  240. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  241. num_links,
  242. ))
  243. def log_archiving_paused(num_links: int, idx: int, timestamp: str):
  244. end_ts = datetime.now(timezone.utc)
  245. _LAST_RUN_STATS.archiving_end_ts = end_ts
  246. print()
  247. print('\n[yellow3][X] [{now}] Downloading paused on link {timestamp} ({idx}/{total})[/]'.format(
  248. now=end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  249. idx=idx+1,
  250. timestamp=timestamp,
  251. total=num_links,
  252. ))
  253. print()
  254. print(' Continue archiving where you left off by running:')
  255. print(' archivebox update --resume={}'.format(timestamp))
  256. def log_archiving_finished(num_links: int):
  257. from core.models import Snapshot
  258. end_ts = datetime.now(timezone.utc)
  259. _LAST_RUN_STATS.archiving_end_ts = end_ts
  260. assert _LAST_RUN_STATS.archiving_start_ts is not None
  261. seconds = end_ts.timestamp() - _LAST_RUN_STATS.archiving_start_ts.timestamp()
  262. if seconds > 60:
  263. duration = '{0:.2f} min'.format(seconds / 60)
  264. else:
  265. duration = '{0:.2f} sec'.format(seconds)
  266. print()
  267. print('[green][√] [{}] Update of {} pages complete ({})[/]'.format(
  268. end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  269. num_links,
  270. duration,
  271. ))
  272. print(' - {} links skipped'.format(_LAST_RUN_STATS.skipped))
  273. print(' - {} links updated'.format(_LAST_RUN_STATS.succeeded + _LAST_RUN_STATS.failed))
  274. print(' - {} links had errors'.format(_LAST_RUN_STATS.failed))
  275. if Snapshot.objects.count() < 50:
  276. print()
  277. print(' [violet]Hint:[/] To manage your archive in a Web UI, run:')
  278. print(' archivebox server 0.0.0.0:8000')
  279. def log_link_archiving_started(link: "Link", link_dir: str, is_new: bool):
  280. # [*] [2019-03-22 13:46:45] "Log Structured Merge Trees - ben stopford"
  281. # http://www.benstopford.com/2015/02/14/log-structured-merge-trees/
  282. # > output/archive/1478739709
  283. print('\n[[{symbol_color}]{symbol}[/]] [[{symbol_color}]{now}[/]] "{title}"'.format(
  284. symbol_color='green' if is_new else 'bright_black',
  285. symbol='+' if is_new else '√',
  286. now=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S'),
  287. title=link.title or link.base_url,
  288. ))
  289. print(f' [sky_blue1]{link.url}[/]')
  290. print(' {} {}'.format(
  291. '>' if is_new else '√',
  292. pretty_path(link_dir),
  293. ))
  294. def log_link_archiving_finished(link: "Link", link_dir: str, is_new: bool, stats: dict, start_ts: datetime):
  295. total = sum(stats.values())
  296. if stats['failed'] > 0 :
  297. _LAST_RUN_STATS.failed += 1
  298. elif stats['skipped'] == total:
  299. _LAST_RUN_STATS.skipped += 1
  300. else:
  301. _LAST_RUN_STATS.succeeded += 1
  302. try:
  303. size = get_dir_size(link_dir)
  304. except FileNotFoundError:
  305. size = (0, None, '0')
  306. end_ts = datetime.now(timezone.utc)
  307. duration = str(end_ts - start_ts).split('.')[0]
  308. print(' [bright_black]{} files ({}) in {}s [/]'.format(size[2], printable_filesize(size[0]), duration))
  309. def log_archive_method_started(method: str):
  310. print(' > {}'.format(method))
  311. def log_archive_method_finished(result: "ArchiveResult"):
  312. """quote the argument with whitespace in a command so the user can
  313. copy-paste the outputted string directly to run the cmd
  314. """
  315. # Prettify CMD string and make it safe to copy-paste by quoting arguments
  316. quoted_cmd = ' '.join(
  317. '"{}"'.format(arg) if (' ' in arg) or (':' in arg) else arg
  318. for arg in result.cmd
  319. )
  320. if result.status == 'failed':
  321. if result.output.__class__.__name__ == 'TimeoutExpired':
  322. duration = (result.end_ts - result.start_ts).seconds
  323. hint_header = [
  324. f'[yellow3]Extractor timed out after {duration}s.[/]',
  325. ]
  326. else:
  327. error_name = result.output.__class__.__name__.replace('ArchiveError', '')
  328. hint_header = [
  329. '[yellow3]Extractor failed:[/]',
  330. f' {error_name} [red1]{result.output}[/]',
  331. ]
  332. # import pudb; pudb.set_trace()
  333. # Prettify error output hints string and limit to five lines
  334. hints = getattr(result.output, 'hints', None) or ()
  335. if hints:
  336. if isinstance(hints, (list, tuple, type(_ for _ in ()))):
  337. hints = [hint.decode() if isinstance(hint, bytes) else str(hint) for hint in hints]
  338. else:
  339. if isinstance(hints, bytes):
  340. hints = hints.decode()
  341. hints = hints.split('\n')
  342. hints = (
  343. f' [yellow1]{line.strip()}[/]'
  344. for line in list(hints)[:5] if line.strip()
  345. )
  346. docker_hints = ()
  347. if os.environ.get('IN_DOCKER') in ('1', 'true', 'True', 'TRUE', 'yes'):
  348. docker_hints = (
  349. ' docker run -it -v $PWD/data:/data archivebox/archivebox /bin/bash',
  350. )
  351. # Collect and prefix output lines with indentation
  352. output_lines = [
  353. *hint_header,
  354. *hints,
  355. '[violet]Run to see full output:[/]',
  356. *docker_hints,
  357. *([' cd {};'.format(result.pwd)] if result.pwd else []),
  358. ' {}'.format(quoted_cmd),
  359. ]
  360. print('\n'.join(
  361. ' {}'.format(line)
  362. for line in output_lines
  363. if line
  364. ))
  365. print()
  366. def log_list_started(filter_patterns: Optional[List[str]], filter_type: str):
  367. print(f'[green][*] Finding links in the archive index matching these {filter_type} patterns:[/]')
  368. print(' {}'.format(' '.join(filter_patterns or ())))
  369. def log_list_finished(links):
  370. from .index.csv import links_to_csv
  371. print()
  372. print('---------------------------------------------------------------------------------------------------')
  373. print(links_to_csv(links, cols=['timestamp', 'is_archived', 'num_outputs', 'url'], header=True, ljust=16, separator=' | '))
  374. print('---------------------------------------------------------------------------------------------------')
  375. print()
  376. def log_removal_started(links: List["Link"], yes: bool, delete: bool):
  377. print(f'[yellow3][i] Found {len(links)} matching URLs to remove.[/]')
  378. if delete:
  379. file_counts = [link.num_outputs for link in links if Path(link.link_dir).exists()]
  380. print(
  381. f' {len(links)} Links will be de-listed from the main index, and their archived content folders will be deleted from disk.\n'
  382. f' ({len(file_counts)} data folders with {sum(file_counts)} archived files will be deleted!)'
  383. )
  384. else:
  385. print(
  386. ' Matching links will be de-listed from the main index, but their archived content folders will remain in place on disk.\n'
  387. ' (Pass --delete if you also want to permanently delete the data folders)'
  388. )
  389. if not yes:
  390. print()
  391. print('[yellow3][?] Do you want to proceed with removing these {len(links)} links?[/]')
  392. try:
  393. assert input(' y/[n]: ').lower() == 'y'
  394. except (KeyboardInterrupt, EOFError, AssertionError):
  395. raise SystemExit(0)
  396. def log_removal_finished(all_links: int, to_remove: int):
  397. if all_links == 0:
  398. print()
  399. print('[red1][X] No matching links found.[/]')
  400. else:
  401. print()
  402. print(f'[red1][√] Removed {to_remove} out of {all_links} links from the archive index.[/]')
  403. print(f' Index now contains {all_links - to_remove} links.')
  404. ### Helpers
  405. @enforce_types
  406. def pretty_path(path: Union[Path, str], pwd: Union[Path, str]=DATA_DIR) -> str:
  407. """convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
  408. pwd = str(Path(pwd)) # .resolve()
  409. path = str(path)
  410. if not path:
  411. return path
  412. # replace long absolute paths with ./ relative ones to save on terminal output width
  413. if path.startswith(pwd) and (pwd != '/') and path != pwd:
  414. path = path.replace(pwd, '[light_slate_blue].[/light_slate_blue]', 1)
  415. # quote paths containing spaces
  416. if ' ' in path:
  417. path = f'"{path}"'
  418. # replace home directory with ~ for shorter output
  419. path = path.replace(str(Path('~').expanduser()), '~')
  420. return path
  421. @enforce_types
  422. def printable_filesize(num_bytes: Union[int, float]) -> str:
  423. for count in ['Bytes','KB','MB','GB']:
  424. if num_bytes > -1024.0 and num_bytes < 1024.0:
  425. return '%3.1f %s' % (num_bytes, count)
  426. num_bytes /= 1024.0
  427. return '%3.1f %s' % (num_bytes, 'TB')
  428. @enforce_types
  429. def printable_folders(folders: Dict[str, Optional["Link"]],
  430. with_headers: bool=False) -> str:
  431. return '\n'.join(
  432. f'{folder} {link and link.url} "{link and link.title}"'
  433. for folder, link in folders.items()
  434. )
  435. @enforce_types
  436. def printable_config(config: dict, prefix: str='') -> str:
  437. return f'\n{prefix}'.join(
  438. f'{key}={val}'
  439. for key, val in config.items()
  440. if not (isinstance(val, dict) or callable(val))
  441. )
  442. @enforce_types
  443. def printable_folder_status(name: str, folder: Dict) -> str:
  444. if folder['enabled']:
  445. if folder['is_valid']:
  446. color, symbol, note, num_files = 'green', '√', 'valid', ''
  447. else:
  448. color, symbol, note, num_files = 'red', 'X', 'invalid', '?'
  449. else:
  450. color, symbol, note, num_files = 'grey53', '-', 'unused', '-'
  451. if folder['path']:
  452. if Path(folder['path']).exists():
  453. num_files = (
  454. f'{len(os.listdir(folder["path"]))} files'
  455. if Path(folder['path']).is_dir() else
  456. printable_filesize(Path(folder['path']).stat().st_size)
  457. )
  458. else:
  459. num_files = 'missing'
  460. if folder.get('is_mount'):
  461. # add symbol @ next to filecount if path is a remote filesystem mount
  462. num_files = f'{num_files} @' if num_files else '@'
  463. path = pretty_path(folder['path'])
  464. return ' '.join((
  465. f'[{color}]',
  466. symbol,
  467. '[/]',
  468. name.ljust(21).replace('DATA_DIR', '[light_slate_blue]DATA_DIR[/light_slate_blue]'),
  469. num_files.ljust(14).replace('missing', '[grey53]missing[/grey53]'),
  470. f'[{color}]',
  471. note.ljust(8),
  472. '[/]',
  473. path.ljust(76),
  474. ))
  475. @enforce_types
  476. def printable_dependency_version(name: str, dependency: Dict) -> str:
  477. color, symbol, note, version = 'red', 'X', 'invalid', '?'
  478. if dependency['enabled']:
  479. if dependency['is_valid']:
  480. color, symbol, note = 'green', '√', 'valid'
  481. parsed_version_num = re.search(r'[\d\.]+', dependency['version'])
  482. if parsed_version_num:
  483. version = f'v{parsed_version_num[0]}'
  484. else:
  485. color, symbol, note, version = 'lightyellow', '-', 'disabled', '-'
  486. path = pretty_path(dependency['path'])
  487. return ' '.join((
  488. ANSI[color],
  489. symbol,
  490. ANSI['reset'],
  491. name.ljust(21),
  492. version.ljust(14),
  493. ANSI[color],
  494. note.ljust(8),
  495. ANSI['reset'],
  496. path.ljust(76),
  497. ))