logging_util.py 22 KB

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