logging_util.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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('{black} > {pwd}{reset}'.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={}){}...{reset}'.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. **ANSI,
  211. ))
  212. def log_source_saved(source_file: str):
  213. print(' > Saved verbatim input to {}/{}'.format(SOURCES_DIR_NAME, source_file.rsplit('/', 1)[-1]))
  214. def log_parsing_finished(num_parsed: int, parser_name: str):
  215. _LAST_RUN_STATS.parse_end_ts = datetime.now(timezone.utc)
  216. print(' > Parsed {} URLs from input ({})'.format(num_parsed, parser_name))
  217. def log_deduping_finished(num_new_links: int):
  218. print(' > Found {} new URLs not already in index'.format(num_new_links))
  219. def log_crawl_started(new_links):
  220. print()
  221. print('{green}[*] Starting crawl of {} sites 1 hop out from starting point{reset}'.format(len(new_links), **ANSI))
  222. ### Indexing Stage
  223. def log_indexing_process_started(num_links: int):
  224. start_ts = datetime.now(timezone.utc)
  225. _LAST_RUN_STATS.index_start_ts = start_ts
  226. print()
  227. print('{black}[*] [{}] Writing {} links to main index...{reset}'.format(
  228. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  229. num_links,
  230. **ANSI,
  231. ))
  232. def log_indexing_process_finished():
  233. end_ts = datetime.now(timezone.utc)
  234. _LAST_RUN_STATS.index_end_ts = end_ts
  235. def log_indexing_started(out_path: str):
  236. if IS_TTY:
  237. sys.stdout.write(f' > ./{Path(out_path).relative_to(OUTPUT_DIR)}')
  238. def log_indexing_finished(out_path: str):
  239. print(f'\r √ ./{Path(out_path).relative_to(OUTPUT_DIR)}')
  240. ### Archiving Stage
  241. def log_archiving_started(num_links: int, resume: Optional[float]=None):
  242. start_ts = datetime.now(timezone.utc)
  243. _LAST_RUN_STATS.archiving_start_ts = start_ts
  244. print()
  245. if resume:
  246. print('{green}[▶] [{}] Resuming archive updating for {} pages starting from {}...{reset}'.format(
  247. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  248. num_links,
  249. resume,
  250. **ANSI,
  251. ))
  252. else:
  253. print('{green}[▶] [{}] Starting archiving of {} snapshots in index...{reset}'.format(
  254. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  255. num_links,
  256. **ANSI,
  257. ))
  258. def log_archiving_paused(num_links: int, idx: int, timestamp: str):
  259. end_ts = datetime.now(timezone.utc)
  260. _LAST_RUN_STATS.archiving_end_ts = end_ts
  261. print()
  262. print('\n{lightyellow}[X] [{now}] Downloading paused on link {timestamp} ({idx}/{total}){reset}'.format(
  263. **ANSI,
  264. now=end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  265. idx=idx+1,
  266. timestamp=timestamp,
  267. total=num_links,
  268. ))
  269. print()
  270. print(' Continue archiving where you left off by running:')
  271. print(' archivebox update --resume={}'.format(timestamp))
  272. def log_archiving_finished(num_links: int):
  273. from core.models import Snapshot
  274. end_ts = datetime.now(timezone.utc)
  275. _LAST_RUN_STATS.archiving_end_ts = end_ts
  276. assert _LAST_RUN_STATS.archiving_start_ts is not None
  277. seconds = end_ts.timestamp() - _LAST_RUN_STATS.archiving_start_ts.timestamp()
  278. if seconds > 60:
  279. duration = '{0:.2f} min'.format(seconds / 60)
  280. else:
  281. duration = '{0:.2f} sec'.format(seconds)
  282. print()
  283. print('{}[√] [{}] Update of {} pages complete ({}){}'.format(
  284. ANSI['green'],
  285. end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  286. num_links,
  287. duration,
  288. ANSI['reset'],
  289. ))
  290. print(' - {} links skipped'.format(_LAST_RUN_STATS.skipped))
  291. print(' - {} links updated'.format(_LAST_RUN_STATS.succeeded + _LAST_RUN_STATS.failed))
  292. print(' - {} links had errors'.format(_LAST_RUN_STATS.failed))
  293. if Snapshot.objects.count() < 50:
  294. print()
  295. print(' {lightred}Hint:{reset} To manage your archive in a Web UI, run:'.format(**ANSI))
  296. print(' archivebox server 0.0.0.0:8000')
  297. def log_link_archiving_started(link: "Link", link_dir: str, is_new: bool):
  298. # [*] [2019-03-22 13:46:45] "Log Structured Merge Trees - ben stopford"
  299. # http://www.benstopford.com/2015/02/14/log-structured-merge-trees/
  300. # > output/archive/1478739709
  301. print('\n[{symbol_color}{symbol}{reset}] [{symbol_color}{now}{reset}] "{title}"'.format(
  302. symbol_color=ANSI['green' if is_new else 'black'],
  303. symbol='+' if is_new else '√',
  304. now=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S'),
  305. title=link.title or link.base_url,
  306. **ANSI,
  307. ))
  308. print(' {blue}{url}{reset}'.format(url=link.url, **ANSI))
  309. print(' {} {}'.format(
  310. '>' if is_new else '√',
  311. pretty_path(link_dir),
  312. ))
  313. def log_link_archiving_finished(link: "Link", link_dir: str, is_new: bool, stats: dict, start_ts: datetime):
  314. total = sum(stats.values())
  315. if stats['failed'] > 0 :
  316. _LAST_RUN_STATS.failed += 1
  317. elif stats['skipped'] == total:
  318. _LAST_RUN_STATS.skipped += 1
  319. else:
  320. _LAST_RUN_STATS.succeeded += 1
  321. try:
  322. size = get_dir_size(link_dir)
  323. except FileNotFoundError:
  324. size = (0, None, '0')
  325. end_ts = datetime.now(timezone.utc)
  326. duration = str(end_ts - start_ts).split('.')[0]
  327. print(' {black}{} files ({}) in {}s {reset}'.format(size[2], printable_filesize(size[0]), duration, **ANSI))
  328. def log_archive_method_started(method: str):
  329. print(' > {}'.format(method))
  330. def log_archive_method_finished(result: "ArchiveResult"):
  331. """quote the argument with whitespace in a command so the user can
  332. copy-paste the outputted string directly to run the cmd
  333. """
  334. # Prettify CMD string and make it safe to copy-paste by quoting arguments
  335. quoted_cmd = ' '.join(
  336. '"{}"'.format(arg) if (' ' in arg) or (':' in arg) else arg
  337. for arg in result.cmd
  338. )
  339. if result.status == 'failed':
  340. if result.output.__class__.__name__ == 'TimeoutExpired':
  341. duration = (result.end_ts - result.start_ts).seconds
  342. hint_header = [
  343. '{lightyellow}Extractor timed out after {}s.{reset}'.format(duration, **ANSI),
  344. ]
  345. else:
  346. hint_header = [
  347. '{lightyellow}Extractor failed:{reset}'.format(**ANSI),
  348. ' {reset}{} {red}{}{reset}'.format(
  349. result.output.__class__.__name__.replace('ArchiveError', ''),
  350. result.output,
  351. **ANSI,
  352. ),
  353. ]
  354. # import pudb; pudb.set_trace()
  355. # Prettify error output hints string and limit to five lines
  356. hints = getattr(result.output, 'hints', None) or ()
  357. if hints:
  358. if isinstance(hints, (list, tuple, type(_ for _ in ()))):
  359. hints = [hint.decode() if isinstance(hint, bytes) else str(hint) for hint in hints]
  360. else:
  361. if isinstance(hints, bytes):
  362. hints = hints.decode()
  363. hints = hints.split('\n')
  364. hints = (
  365. ' {}{}{}'.format(ANSI['lightyellow'], line.strip(), ANSI['reset'])
  366. for line in list(hints)[:5] if line.strip()
  367. )
  368. docker_hints = ()
  369. if IN_DOCKER:
  370. docker_hints = (
  371. ' docker run -it -v $PWD/data:/data archivebox/archivebox /bin/bash',
  372. )
  373. # Collect and prefix output lines with indentation
  374. output_lines = [
  375. *hint_header,
  376. *hints,
  377. '{}Run to see full output:{}'.format(ANSI['lightred'], ANSI['reset']),
  378. *docker_hints,
  379. *([' cd {};'.format(result.pwd)] if result.pwd else []),
  380. ' {}'.format(quoted_cmd),
  381. ]
  382. print('\n'.join(
  383. ' {}'.format(line)
  384. for line in output_lines
  385. if line
  386. ))
  387. print()
  388. def log_list_started(filter_patterns: Optional[List[str]], filter_type: str):
  389. print('{green}[*] Finding links in the archive index matching these {} patterns:{reset}'.format(
  390. filter_type,
  391. **ANSI,
  392. ))
  393. print(' {}'.format(' '.join(filter_patterns or ())))
  394. def log_list_finished(links):
  395. from .index.csv import links_to_csv
  396. print()
  397. print('---------------------------------------------------------------------------------------------------')
  398. print(links_to_csv(links, cols=['timestamp', 'is_archived', 'num_outputs', 'url'], header=True, ljust=16, separator=' | '))
  399. print('---------------------------------------------------------------------------------------------------')
  400. print()
  401. def log_removal_started(links: List["Link"], yes: bool, delete: bool):
  402. print('{lightyellow}[i] Found {} matching URLs to remove.{reset}'.format(len(links), **ANSI))
  403. if delete:
  404. file_counts = [link.num_outputs for link in links if Path(link.link_dir).exists()]
  405. print(
  406. f' {len(links)} Links will be de-listed from the main index, and their archived content folders will be deleted from disk.\n'
  407. f' ({len(file_counts)} data folders with {sum(file_counts)} archived files will be deleted!)'
  408. )
  409. else:
  410. print(
  411. ' Matching links will be de-listed from the main index, but their archived content folders will remain in place on disk.\n'
  412. ' (Pass --delete if you also want to permanently delete the data folders)'
  413. )
  414. if not yes:
  415. print()
  416. print('{lightyellow}[?] Do you want to proceed with removing these {} links?{reset}'.format(len(links), **ANSI))
  417. try:
  418. assert input(' y/[n]: ').lower() == 'y'
  419. except (KeyboardInterrupt, EOFError, AssertionError):
  420. raise SystemExit(0)
  421. def log_removal_finished(all_links: int, to_remove: int):
  422. if all_links == 0:
  423. print()
  424. print('{red}[X] No matching links found.{reset}'.format(**ANSI))
  425. else:
  426. print()
  427. print('{red}[√] Removed {} out of {} links from the archive index.{reset}'.format(
  428. to_remove,
  429. all_links,
  430. **ANSI,
  431. ))
  432. print(' Index now contains {} links.'.format(all_links - to_remove))
  433. def log_shell_welcome_msg():
  434. from .cli import CLI_SUBCOMMANDS
  435. print('{green}# ArchiveBox Imports{reset}'.format(**ANSI))
  436. print('{green}from core.models import Snapshot, ArchiveResult, Tag, User{reset}'.format(**ANSI))
  437. print('{green}from cli import *\n {}{reset}'.format("\n ".join(CLI_SUBCOMMANDS.keys()), **ANSI))
  438. print()
  439. print('[i] Welcome to the ArchiveBox Shell!')
  440. print(' https://github.com/ArchiveBox/ArchiveBox/wiki/Usage#Shell-Usage')
  441. print()
  442. print(' {lightred}Hint:{reset} Example use:'.format(**ANSI))
  443. print(' print(Snapshot.objects.filter(is_archived=True).count())')
  444. print(' Snapshot.objects.get(url="https://example.com").as_json()')
  445. print(' add("https://example.com/some/new/url")')
  446. ### Helpers
  447. @enforce_types
  448. def pretty_path(path: Union[Path, str], pwd: Union[Path, str]=OUTPUT_DIR) -> str:
  449. """convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
  450. pwd = str(Path(pwd)) # .resolve()
  451. path = str(path)
  452. if not path:
  453. return path
  454. # replace long absolute paths with ./ relative ones to save on terminal output width
  455. if path.startswith(pwd) and (pwd != '/'):
  456. path = path.replace(pwd, '.', 1)
  457. # quote paths containing spaces
  458. if ' ' in path:
  459. path = f'"{path}"'
  460. # if path is just a plain dot, replace it back with the absolute path for clarity
  461. if path == '.':
  462. path = pwd
  463. return path
  464. @enforce_types
  465. def printable_filesize(num_bytes: Union[int, float]) -> str:
  466. for count in ['Bytes','KB','MB','GB']:
  467. if num_bytes > -1024.0 and num_bytes < 1024.0:
  468. return '%3.1f %s' % (num_bytes, count)
  469. num_bytes /= 1024.0
  470. return '%3.1f %s' % (num_bytes, 'TB')
  471. @enforce_types
  472. def printable_folders(folders: Dict[str, Optional["Link"]],
  473. with_headers: bool=False) -> str:
  474. return '\n'.join(
  475. f'{folder} {link and link.url} "{link and link.title}"'
  476. for folder, link in folders.items()
  477. )
  478. @enforce_types
  479. def printable_config(config: ConfigDict, prefix: str='') -> str:
  480. return f'\n{prefix}'.join(
  481. f'{key}={val}'
  482. for key, val in config.items()
  483. if not (isinstance(val, dict) or callable(val))
  484. )
  485. @enforce_types
  486. def printable_folder_status(name: str, folder: Dict) -> str:
  487. if folder['enabled']:
  488. if folder['is_valid']:
  489. color, symbol, note, num_files = 'green', '√', 'valid', ''
  490. else:
  491. color, symbol, note, num_files = 'red', 'X', 'invalid', '?'
  492. else:
  493. color, symbol, note, num_files = 'lightyellow', '-', 'disabled', '-'
  494. if folder['path']:
  495. if Path(folder['path']).exists():
  496. num_files = (
  497. f'{len(os.listdir(folder["path"]))} files'
  498. if Path(folder['path']).is_dir() else
  499. printable_filesize(Path(folder['path']).stat().st_size)
  500. )
  501. else:
  502. num_files = 'missing'
  503. if folder.get('is_mount'):
  504. # add symbol @ next to filecount if path is a remote filesystem mount
  505. num_files = f'{num_files} @' if num_files else '@'
  506. path = pretty_path(folder['path'])
  507. return ' '.join((
  508. ANSI[color],
  509. symbol,
  510. ANSI['reset'],
  511. name.ljust(21),
  512. num_files.ljust(14),
  513. ANSI[color],
  514. note.ljust(8),
  515. ANSI['reset'],
  516. path.ljust(76),
  517. ))
  518. @enforce_types
  519. def printable_dependency_version(name: str, dependency: Dict) -> str:
  520. color, symbol, note, version = 'red', 'X', 'invalid', '?'
  521. if dependency['enabled']:
  522. if dependency['is_valid']:
  523. color, symbol, note = 'green', '√', 'valid'
  524. parsed_version_num = re.search(r'[\d\.]+', dependency['version'])
  525. if parsed_version_num:
  526. version = f'v{parsed_version_num[0]}'
  527. else:
  528. color, symbol, note, version = 'lightyellow', '-', 'disabled', '-'
  529. path = pretty_path(dependency['path'])
  530. return ' '.join((
  531. ANSI[color],
  532. symbol,
  533. ANSI['reset'],
  534. name.ljust(21),
  535. version.ljust(14),
  536. ANSI[color],
  537. note.ljust(8),
  538. ANSI['reset'],
  539. path.ljust(76),
  540. ))