logging_util.py 22 KB

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