logging_util.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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
  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:
  87. # stderr('GOT STDIN!', len(stdin_str))
  88. stderr(f'[X] The "{caller}" command does not accept stdin.', 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(), 'end_ts': None}
  112. def end(self):
  113. """immediately end progress, clear the progressbar line, and save end_ts"""
  114. end_ts = datetime.now()
  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:
  123. pass
  124. self.p.terminate()
  125. self.p.join()
  126. # clear whole terminal line
  127. try:
  128. sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH()), ANSI['reset']))
  129. except (IOError, BrokenPipeError):
  130. # ignore when the parent proc has stopped listening to our stdout
  131. pass
  132. except ValueError:
  133. pass
  134. @enforce_types
  135. def progress_bar(seconds: int, prefix: str='') -> None:
  136. """show timer in the form of progress bar, with percentage and seconds remaining"""
  137. chunk = '█' if PYTHON_ENCODING == 'UTF-8' else '#'
  138. last_width = TERM_WIDTH()
  139. chunks = last_width - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
  140. try:
  141. for s in range(seconds * chunks):
  142. max_width = TERM_WIDTH()
  143. if max_width < last_width:
  144. # when the terminal size is shrunk, we have to write a newline
  145. # otherwise the progress bar will keep wrapping incorrectly
  146. sys.stdout.write('\r\n')
  147. sys.stdout.flush()
  148. chunks = max_width - len(prefix) - 20
  149. pct_complete = s / chunks / seconds * 100
  150. log_pct = (log(pct_complete or 1, 10) / 2) * 100 # everyone likes faster progress bars ;)
  151. bar_width = round(log_pct/(100/chunks))
  152. last_width = max_width
  153. # ████████████████████ 0.9% (1/60sec)
  154. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  155. prefix,
  156. ANSI['green' if pct_complete < 80 else 'lightyellow'],
  157. (chunk * bar_width).ljust(chunks),
  158. ANSI['reset'],
  159. round(pct_complete, 1),
  160. round(s/chunks),
  161. seconds,
  162. ))
  163. sys.stdout.flush()
  164. time.sleep(1 / chunks)
  165. # ██████████████████████████████████ 100.0% (60/60sec)
  166. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  167. prefix,
  168. ANSI['red'],
  169. chunk * chunks,
  170. ANSI['reset'],
  171. 100.0,
  172. seconds,
  173. seconds,
  174. ))
  175. sys.stdout.flush()
  176. # uncomment to have it disappear when it hits 100% instead of staying full red:
  177. # time.sleep(0.5)
  178. # sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH()), ANSI['reset']))
  179. # sys.stdout.flush()
  180. except (KeyboardInterrupt, BrokenPipeError):
  181. print()
  182. pass
  183. def log_cli_command(subcommand: str, subcommand_args: List[str], stdin: Optional[str], pwd: str):
  184. cmd = ' '.join(('archivebox', subcommand, *subcommand_args))
  185. stderr('{black}[i] [{now}] ArchiveBox v{VERSION}: {cmd}{reset}'.format(
  186. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  187. VERSION=VERSION,
  188. cmd=cmd,
  189. **ANSI,
  190. ))
  191. stderr('{black} > {pwd}{reset}'.format(pwd=pwd, **ANSI))
  192. stderr()
  193. ### Parsing Stage
  194. def log_importing_started(urls: Union[str, List[str]], depth: int, index_only: bool):
  195. _LAST_RUN_STATS.parse_start_ts = datetime.now()
  196. print('{green}[+] [{}] Adding {} links to index (crawl depth={}){}...{reset}'.format(
  197. _LAST_RUN_STATS.parse_start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  198. len(urls) if isinstance(urls, list) else len(urls.split('\n')),
  199. depth,
  200. ' (index only)' if index_only else '',
  201. **ANSI,
  202. ))
  203. def log_source_saved(source_file: str):
  204. print(' > Saved verbatim input to {}/{}'.format(SOURCES_DIR_NAME, source_file.rsplit('/', 1)[-1]))
  205. def log_parsing_finished(num_parsed: int, parser_name: str):
  206. _LAST_RUN_STATS.parse_end_ts = datetime.now()
  207. print(' > Parsed {} URLs from input ({})'.format(num_parsed, parser_name))
  208. def log_deduping_finished(num_new_links: int):
  209. print(' > Found {} new URLs not already in index'.format(num_new_links))
  210. def log_crawl_started(new_links):
  211. print()
  212. print('{green}[*] Starting crawl of {} sites 1 hop out from starting point{reset}'.format(len(new_links), **ANSI))
  213. ### Indexing Stage
  214. def log_indexing_process_started(num_links: int):
  215. start_ts = datetime.now()
  216. _LAST_RUN_STATS.index_start_ts = start_ts
  217. print()
  218. print('{black}[*] [{}] Writing {} links to main index...{reset}'.format(
  219. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  220. num_links,
  221. **ANSI,
  222. ))
  223. def log_indexing_process_finished():
  224. end_ts = datetime.now()
  225. _LAST_RUN_STATS.index_end_ts = end_ts
  226. def log_indexing_started(out_path: str):
  227. if IS_TTY:
  228. sys.stdout.write(f' > {out_path}')
  229. def log_indexing_finished(out_path: str):
  230. print(f'\r √ {out_path}')
  231. ### Archiving Stage
  232. def log_archiving_started(num_links: int, resume: Optional[float]=None):
  233. start_ts = datetime.now()
  234. _LAST_RUN_STATS.archiving_start_ts = start_ts
  235. print()
  236. if resume:
  237. print('{green}[▶] [{}] Resuming archive updating for {} pages starting from {}...{reset}'.format(
  238. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  239. num_links,
  240. resume,
  241. **ANSI,
  242. ))
  243. else:
  244. print('{green}[▶] [{}] Starting archiving of {} snapshots in index...{reset}'.format(
  245. start_ts.strftime('%Y-%m-%d %H:%M:%S'),
  246. num_links,
  247. **ANSI,
  248. ))
  249. def log_archiving_paused(num_links: int, idx: int, timestamp: str):
  250. end_ts = datetime.now()
  251. _LAST_RUN_STATS.archiving_end_ts = end_ts
  252. print()
  253. print('\n{lightyellow}[X] [{now}] Downloading paused on link {timestamp} ({idx}/{total}){reset}'.format(
  254. **ANSI,
  255. now=end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  256. idx=idx+1,
  257. timestamp=timestamp,
  258. total=num_links,
  259. ))
  260. print()
  261. print(' Continue archiving where you left off by running:')
  262. print(' archivebox update --resume={}'.format(timestamp))
  263. def log_archiving_finished(num_links: int):
  264. end_ts = datetime.now()
  265. _LAST_RUN_STATS.archiving_end_ts = end_ts
  266. assert _LAST_RUN_STATS.archiving_start_ts is not None
  267. seconds = end_ts.timestamp() - _LAST_RUN_STATS.archiving_start_ts.timestamp()
  268. if seconds > 60:
  269. duration = '{0:.2f} min'.format(seconds / 60)
  270. else:
  271. duration = '{0:.2f} sec'.format(seconds)
  272. print()
  273. print('{}[√] [{}] Update of {} pages complete ({}){}'.format(
  274. ANSI['green'],
  275. end_ts.strftime('%Y-%m-%d %H:%M:%S'),
  276. num_links,
  277. duration,
  278. ANSI['reset'],
  279. ))
  280. print(' - {} links skipped'.format(_LAST_RUN_STATS.skipped))
  281. print(' - {} links updated'.format(_LAST_RUN_STATS.succeeded + _LAST_RUN_STATS.failed))
  282. print(' - {} links had errors'.format(_LAST_RUN_STATS.failed))
  283. print()
  284. print(' {lightred}Hint:{reset} To manage your archive in a Web UI, run:'.format(**ANSI))
  285. print(' archivebox server 0.0.0.0:8000')
  286. def log_link_archiving_started(link: "Link", link_dir: str, is_new: bool):
  287. # [*] [2019-03-22 13:46:45] "Log Structured Merge Trees - ben stopford"
  288. # http://www.benstopford.com/2015/02/14/log-structured-merge-trees/
  289. # > output/archive/1478739709
  290. print('\n[{symbol_color}{symbol}{reset}] [{symbol_color}{now}{reset}] "{title}"'.format(
  291. symbol_color=ANSI['green' if is_new else 'black'],
  292. symbol='+' if is_new else '√',
  293. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  294. title=link.title or link.base_url,
  295. **ANSI,
  296. ))
  297. print(' {blue}{url}{reset}'.format(url=link.url, **ANSI))
  298. print(' {} {}'.format(
  299. '>' if is_new else '√',
  300. pretty_path(link_dir),
  301. ))
  302. def log_link_archiving_finished(link: "Link", link_dir: str, is_new: bool, stats: dict):
  303. total = sum(stats.values())
  304. if stats['failed'] > 0 :
  305. _LAST_RUN_STATS.failed += 1
  306. elif stats['skipped'] == total:
  307. _LAST_RUN_STATS.skipped += 1
  308. else:
  309. _LAST_RUN_STATS.succeeded += 1
  310. size = get_dir_size(link_dir)
  311. print(' {black}{} files ({}){reset}'.format(size[2], printable_filesize(size[0]), **ANSI))
  312. def log_archive_method_started(method: str):
  313. print(' > {}'.format(method))
  314. def log_archive_method_finished(result: "ArchiveResult"):
  315. """quote the argument with whitespace in a command so the user can
  316. copy-paste the outputted string directly to run the cmd
  317. """
  318. # Prettify CMD string and make it safe to copy-paste by quoting arguments
  319. quoted_cmd = ' '.join(
  320. '"{}"'.format(arg) if ' ' in arg else arg
  321. for arg in result.cmd
  322. )
  323. if result.status == 'failed':
  324. if result.output.__class__.__name__ == 'TimeoutExpired':
  325. duration = (result.end_ts - result.start_ts).seconds
  326. hint_header = [
  327. '{lightyellow}Extractor timed out after {}s.{reset}'.format(duration, **ANSI),
  328. ]
  329. else:
  330. hint_header = [
  331. '{lightyellow}Extractor failed:{reset}'.format(**ANSI),
  332. ' {reset}{} {red}{}{reset}'.format(
  333. result.output.__class__.__name__.replace('ArchiveError', ''),
  334. result.output,
  335. **ANSI,
  336. ),
  337. ]
  338. # Prettify error output hints string and limit to five lines
  339. hints = getattr(result.output, 'hints', None) or ()
  340. if hints:
  341. hints = hints if isinstance(hints, (list, tuple)) else hints.split('\n')
  342. hints = (
  343. ' {}{}{}'.format(ANSI['lightyellow'], line.strip(), ANSI['reset'])
  344. for line in hints[:5] if line.strip()
  345. )
  346. # Collect and prefix output lines with indentation
  347. output_lines = [
  348. *hint_header,
  349. *hints,
  350. '{}Run to see full output:{}'.format(ANSI['lightred'], ANSI['reset']),
  351. *([' cd {};'.format(result.pwd)] if result.pwd else []),
  352. ' {}'.format(quoted_cmd),
  353. ]
  354. print('\n'.join(
  355. ' {}'.format(line)
  356. for line in output_lines
  357. if line
  358. ))
  359. print()
  360. def log_list_started(filter_patterns: Optional[List[str]], filter_type: str):
  361. print('{green}[*] Finding links in the archive index matching these {} patterns:{reset}'.format(
  362. filter_type,
  363. **ANSI,
  364. ))
  365. print(' {}'.format(' '.join(filter_patterns or ())))
  366. def log_list_finished(links):
  367. from .index.csv import links_to_csv
  368. print()
  369. print('---------------------------------------------------------------------------------------------------')
  370. print(links_to_csv(links, cols=['timestamp', 'is_archived', 'num_outputs', 'url'], header=True, ljust=16, separator=' | '))
  371. print('---------------------------------------------------------------------------------------------------')
  372. print()
  373. def log_removal_started(links: List["Link"], yes: bool, delete: bool):
  374. print('{lightyellow}[i] Found {} matching URLs to remove.{reset}'.format(len(links), **ANSI))
  375. if delete:
  376. file_counts = [link.num_outputs for link in links if Path(link.link_dir).exists()]
  377. print(
  378. f' {len(links)} Links will be de-listed from the main index, and their archived content folders will be deleted from disk.\n'
  379. f' ({len(file_counts)} data folders with {sum(file_counts)} archived files will be deleted!)'
  380. )
  381. else:
  382. print(
  383. ' Matching links will be de-listed from the main index, but their archived content folders will remain in place on disk.\n'
  384. ' (Pass --delete if you also want to permanently delete the data folders)'
  385. )
  386. if not yes:
  387. print()
  388. print('{lightyellow}[?] Do you want to proceed with removing these {} links?{reset}'.format(len(links), **ANSI))
  389. try:
  390. assert input(' y/[n]: ').lower() == 'y'
  391. except (KeyboardInterrupt, EOFError, AssertionError):
  392. raise SystemExit(0)
  393. def log_removal_finished(all_links: int, to_remove: int):
  394. if all_links == 0:
  395. print()
  396. print('{red}[X] No matching links found.{reset}'.format(**ANSI))
  397. else:
  398. print()
  399. print('{red}[√] Removed {} out of {} links from the archive index.{reset}'.format(
  400. to_remove,
  401. all_links,
  402. **ANSI,
  403. ))
  404. print(' Index now contains {} links.'.format(all_links - to_remove))
  405. def log_shell_welcome_msg():
  406. from .cli import list_subcommands
  407. print('{green}# ArchiveBox Imports{reset}'.format(**ANSI))
  408. print('{green}from core.models import Snapshot, User{reset}'.format(**ANSI))
  409. print('{green}from archivebox import *\n {}{reset}'.format("\n ".join(list_subcommands().keys()), **ANSI))
  410. print()
  411. print('[i] Welcome to the ArchiveBox Shell!')
  412. print(' https://github.com/ArchiveBox/ArchiveBox/wiki/Usage#Shell-Usage')
  413. print()
  414. print(' {lightred}Hint:{reset} Example use:'.format(**ANSI))
  415. print(' print(Snapshot.objects.filter(is_archived=True).count())')
  416. print(' Snapshot.objects.get(url="https://example.com").as_json()')
  417. print(' add("https://example.com/some/new/url")')
  418. ### Helpers
  419. @enforce_types
  420. def pretty_path(path: Union[Path, str]) -> str:
  421. """convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
  422. pwd = Path('.').resolve()
  423. # parent = os.path.abspath(os.path.join(pwd, os.path.pardir))
  424. return str(path).replace(str(pwd) + '/', './')
  425. @enforce_types
  426. def printable_filesize(num_bytes: Union[int, float]) -> str:
  427. for count in ['Bytes','KB','MB','GB']:
  428. if num_bytes > -1024.0 and num_bytes < 1024.0:
  429. return '%3.1f %s' % (num_bytes, count)
  430. num_bytes /= 1024.0
  431. return '%3.1f %s' % (num_bytes, 'TB')
  432. @enforce_types
  433. def printable_folders(folders: Dict[str, Optional["Link"]],
  434. with_headers: bool=False) -> str:
  435. return '\n'.join(
  436. f'{folder} {link and link.url} "{link and link.title}"'
  437. for folder, link in folders.items()
  438. )
  439. @enforce_types
  440. def printable_config(config: ConfigDict, prefix: str='') -> str:
  441. return f'\n{prefix}'.join(
  442. f'{key}={val}'
  443. for key, val in config.items()
  444. if not (isinstance(val, dict) or callable(val))
  445. )
  446. @enforce_types
  447. def printable_folder_status(name: str, folder: Dict) -> str:
  448. if folder['enabled']:
  449. if folder['is_valid']:
  450. color, symbol, note = 'green', '√', 'valid'
  451. else:
  452. color, symbol, note, num_files = 'red', 'X', 'invalid', '?'
  453. else:
  454. color, symbol, note, num_files = 'lightyellow', '-', 'disabled', '-'
  455. if folder['path']:
  456. if Path(folder['path']).exists():
  457. num_files = (
  458. f'{len(os.listdir(folder["path"]))} files'
  459. if Path(folder['path']).is_dir() else
  460. printable_filesize(Path(folder['path']).stat().st_size)
  461. )
  462. else:
  463. num_files = 'missing'
  464. path = str(folder['path']).replace(str(OUTPUT_DIR), '.') if folder['path'] else ''
  465. if path and ' ' in path:
  466. path = f'"{path}"'
  467. # if path is just a plain dot, replace it back with the full path for clarity
  468. if path == '.':
  469. path = str(OUTPUT_DIR)
  470. return ' '.join((
  471. ANSI[color],
  472. symbol,
  473. ANSI['reset'],
  474. name.ljust(21),
  475. num_files.ljust(14),
  476. ANSI[color],
  477. note.ljust(8),
  478. ANSI['reset'],
  479. path.ljust(76),
  480. ))
  481. @enforce_types
  482. def printable_dependency_version(name: str, dependency: Dict) -> str:
  483. version = None
  484. if dependency['enabled']:
  485. if dependency['is_valid']:
  486. color, symbol, note, version = 'green', '√', 'valid', ''
  487. parsed_version_num = re.search(r'[\d\.]+', dependency['version'])
  488. if parsed_version_num:
  489. version = f'v{parsed_version_num[0]}'
  490. if not version:
  491. color, symbol, note, version = 'red', 'X', 'invalid', '?'
  492. else:
  493. color, symbol, note, version = 'lightyellow', '-', 'disabled', '-'
  494. path = str(dependency["path"]).replace(str(OUTPUT_DIR), '.') if dependency["path"] else ''
  495. if path and ' ' in path:
  496. path = f'"{path}"'
  497. return ' '.join((
  498. ANSI[color],
  499. symbol,
  500. ANSI['reset'],
  501. name.ljust(21),
  502. version.ljust(14),
  503. ANSI[color],
  504. note.ljust(8),
  505. ANSI['reset'],
  506. path.ljust(76),
  507. ))