logging_util.py 22 KB

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