util.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import os
  2. import re
  3. import sys
  4. import time
  5. import json
  6. import signal
  7. import urllib.request
  8. from decimal import Decimal
  9. from urllib.parse import quote
  10. from datetime import datetime
  11. from subprocess import TimeoutExpired, Popen, PIPE, DEVNULL, CompletedProcess, CalledProcessError
  12. from multiprocessing import Process
  13. from config import (
  14. IS_TTY,
  15. OUTPUT_PERMISSIONS,
  16. REPO_DIR,
  17. SOURCES_DIR,
  18. OUTPUT_DIR,
  19. ARCHIVE_DIR,
  20. TIMEOUT,
  21. TERM_WIDTH,
  22. SHOW_PROGRESS,
  23. ANSI,
  24. CHROME_BINARY,
  25. FETCH_WGET,
  26. FETCH_PDF,
  27. FETCH_SCREENSHOT,
  28. FETCH_DOM,
  29. FETCH_FAVICON,
  30. FETCH_MEDIA,
  31. SUBMIT_ARCHIVE_DOT_ORG,
  32. )
  33. # URL helpers
  34. without_scheme = lambda url: url.replace('http://', '').replace('https://', '').replace('ftp://', '')
  35. without_query = lambda url: url.split('?', 1)[0]
  36. without_hash = lambda url: url.split('#', 1)[0]
  37. without_path = lambda url: url.split('/', 1)[0]
  38. domain = lambda url: without_hash(without_query(without_path(without_scheme(url))))
  39. base_url = lambda url: without_scheme(url) # uniq base url used to dedupe links
  40. short_ts = lambda ts: ts.split('.')[0]
  41. URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))[^<\""]+'
  42. def check_dependencies():
  43. """Check that all necessary dependencies are installed, and have valid versions"""
  44. python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
  45. if python_vers < 3.5:
  46. print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
  47. print(' See https://github.com/pirate/ArchiveBox#troubleshooting for help upgrading your Python installation.')
  48. raise SystemExit(1)
  49. if FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM:
  50. if run(['which', CHROME_BINARY], stdout=DEVNULL).returncode:
  51. print('{}[X] Missing dependency: {}{}'.format(ANSI['red'], CHROME_BINARY, ANSI['reset']))
  52. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
  53. print(' See https://github.com/pirate/ArchiveBox for help.')
  54. raise SystemExit(1)
  55. # parse chrome --version e.g. Google Chrome 61.0.3114.0 canary / Chromium 59.0.3029.110 built on Ubuntu, running on Ubuntu 16.04
  56. try:
  57. result = run([CHROME_BINARY, '--version'], stdout=PIPE)
  58. version_str = result.stdout.decode('utf-8')
  59. version_lines = re.sub("(Google Chrome|Chromium) (\\d+?)\\.(\\d+?)\\.(\\d+?).*?$", "\\2", version_str).split('\n')
  60. version = [l for l in version_lines if l.isdigit()][-1]
  61. if int(version) < 59:
  62. print(version_lines)
  63. print('{red}[X] Chrome version must be 59 or greater for headless PDF, screenshot, and DOM saving{reset}'.format(**ANSI))
  64. print(' See https://github.com/pirate/ArchiveBox for help.')
  65. raise SystemExit(1)
  66. except (IndexError, TypeError, OSError):
  67. print('{red}[X] Failed to parse Chrome version, is it installed properly?{reset}'.format(**ANSI))
  68. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
  69. print(' See https://github.com/pirate/ArchiveBox for help.')
  70. raise SystemExit(1)
  71. if FETCH_WGET:
  72. if run(['which', 'wget'], stdout=DEVNULL).returncode or run(['wget', '--version'], stdout=DEVNULL).returncode:
  73. print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
  74. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('wget'))
  75. print(' See https://github.com/pirate/ArchiveBox for help.')
  76. raise SystemExit(1)
  77. if FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG:
  78. if run(['which', 'curl'], stdout=DEVNULL).returncode or run(['curl', '--version'], stdout=DEVNULL).returncode:
  79. print('{red}[X] Missing dependency: curl{reset}'.format(**ANSI))
  80. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('curl'))
  81. print(' See https://github.com/pirate/ArchiveBox for help.')
  82. raise SystemExit(1)
  83. if FETCH_MEDIA:
  84. if run(['which', 'youtube-dl'], stdout=DEVNULL).returncode or run(['youtube-dl', '--version'], stdout=DEVNULL).returncode:
  85. print('{red}[X] Missing dependency: youtube-dl{reset}'.format(**ANSI))
  86. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('youtube-dl'))
  87. print(' See https://github.com/pirate/ArchiveBox for help.')
  88. raise SystemExit(1)
  89. def chmod_file(path, cwd='.', permissions=OUTPUT_PERMISSIONS, timeout=30):
  90. """chmod -R <permissions> <cwd>/<path>"""
  91. if not os.path.exists(os.path.join(cwd, path)):
  92. raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
  93. chmod_result = run(['chmod', '-R', permissions, path], cwd=cwd, stdout=DEVNULL, stderr=PIPE, timeout=timeout)
  94. if chmod_result.returncode == 1:
  95. print(' ', chmod_result.stderr.decode())
  96. raise Exception('Failed to chmod {}/{}'.format(cwd, path))
  97. def progress(seconds=TIMEOUT, prefix=''):
  98. """Show a (subprocess-controlled) progress bar with a <seconds> timeout,
  99. returns end() function to instantly finish the progress
  100. """
  101. if not SHOW_PROGRESS:
  102. return lambda: None
  103. def progress_bar(seconds, prefix):
  104. """show timer in the form of progress bar, with percentage and seconds remaining"""
  105. chunk = '█' if sys.stdout.encoding == 'UTF-8' else '#'
  106. chunks = TERM_WIDTH - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
  107. try:
  108. for s in range(seconds * chunks):
  109. progress = s / chunks / seconds * 100
  110. bar_width = round(progress/(100/chunks))
  111. # ████████████████████ 0.9% (1/60sec)
  112. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  113. prefix,
  114. ANSI['green'],
  115. (chunk * bar_width).ljust(chunks),
  116. ANSI['reset'],
  117. round(progress, 1),
  118. round(s/chunks),
  119. seconds,
  120. ))
  121. sys.stdout.flush()
  122. time.sleep(1 / chunks)
  123. # ██████████████████████████████████ 100.0% (60/60sec)
  124. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)\n'.format(
  125. prefix,
  126. ANSI['red'],
  127. chunk * chunks,
  128. ANSI['reset'],
  129. 100.0,
  130. seconds,
  131. seconds,
  132. ))
  133. sys.stdout.flush()
  134. except KeyboardInterrupt:
  135. print()
  136. pass
  137. p = Process(target=progress_bar, args=(seconds, prefix))
  138. p.start()
  139. def end():
  140. """immediately finish progress and clear the progressbar line"""
  141. # protect from double termination
  142. #if p is None or not hasattr(p, 'kill'):
  143. # return
  144. nonlocal p
  145. if p is not None:
  146. p.terminate()
  147. p = None
  148. sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH), ANSI['reset'])) # clear whole terminal line
  149. sys.stdout.flush()
  150. return end
  151. def pretty_path(path):
  152. """convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
  153. return path.replace(REPO_DIR + '/', '')
  154. def save_source(raw_text):
  155. if not os.path.exists(SOURCES_DIR):
  156. os.makedirs(SOURCES_DIR)
  157. ts = str(datetime.now().timestamp()).split('.', 1)[0]
  158. source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format('stdin', ts))
  159. with open(source_path, 'w', encoding='utf-8') as f:
  160. f.write(raw_text)
  161. return source_path
  162. def download_url(url):
  163. """download a given url's content into downloads/domain.txt"""
  164. if not os.path.exists(SOURCES_DIR):
  165. os.makedirs(SOURCES_DIR)
  166. ts = str(datetime.now().timestamp()).split('.', 1)[0]
  167. source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format(domain(url), ts))
  168. print('[*] [{}] Downloading {} > {}'.format(
  169. datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  170. url,
  171. pretty_path(source_path),
  172. ))
  173. end = progress(TIMEOUT, prefix=' ')
  174. try:
  175. downloaded_xml = urllib.request.urlopen(url).read().decode('utf-8')
  176. end()
  177. except Exception as e:
  178. end()
  179. print('[!] Failed to download {}\n'.format(url))
  180. print(' ', e)
  181. raise SystemExit(1)
  182. with open(source_path, 'w', encoding='utf-8') as f:
  183. f.write(downloaded_xml)
  184. return source_path
  185. def fetch_page_title(url, default=True):
  186. """Attempt to guess a page's title by downloading the html"""
  187. if default is True:
  188. default = url
  189. try:
  190. sys.stdout.write('.')
  191. html_content = urllib.request.urlopen(url, timeout=10).read().decode('utf-8')
  192. match = re.search('<title>(.*?)</title>', html_content)
  193. return match.group(1) if match else default or None
  194. except Exception:
  195. if default is False:
  196. raise
  197. return default
  198. def str_between(string, start, end=None):
  199. """(<abc>12345</def>, <abc>, </def>) -> 12345"""
  200. content = string.split(start, 1)[-1]
  201. if end is not None:
  202. content = content.rsplit(end, 1)[0]
  203. return content
  204. def get_link_type(link):
  205. """Certain types of links need to be handled specially, this figures out when that's the case"""
  206. if link['base_url'].endswith('.pdf'):
  207. return 'PDF'
  208. elif link['base_url'].rsplit('.', 1) in ('pdf', 'png', 'jpg', 'jpeg', 'svg', 'bmp', 'gif', 'tiff', 'webp'):
  209. return 'image'
  210. elif 'wikipedia.org' in link['domain']:
  211. return 'wiki'
  212. elif 'youtube.com' in link['domain']:
  213. return 'youtube'
  214. elif 'soundcloud.com' in link['domain']:
  215. return 'soundcloud'
  216. elif 'youku.com' in link['domain']:
  217. return 'youku'
  218. elif 'vimeo.com' in link['domain']:
  219. return 'vimeo'
  220. return None
  221. def merge_links(a, b):
  222. """deterministially merge two links, favoring longer field values over shorter,
  223. and "cleaner" values over worse ones.
  224. """
  225. longer = lambda key: a[key] if len(a[key]) > len(b[key]) else b[key]
  226. earlier = lambda key: a[key] if a[key] < b[key] else b[key]
  227. url = longer('url')
  228. longest_title = longer('title')
  229. cleanest_title = a['title'] if '://' not in a['title'] else b['title']
  230. link = {
  231. 'timestamp': earlier('timestamp'),
  232. 'url': url,
  233. 'domain': domain(url),
  234. 'base_url': base_url(url),
  235. 'tags': longer('tags'),
  236. 'title': longest_title if '://' not in longest_title else cleanest_title,
  237. 'sources': list(set(a.get('sources', []) + b.get('sources', []))),
  238. }
  239. link['type'] = get_link_type(link)
  240. return link
  241. def find_link(folder, links):
  242. """for a given archive folder, find the corresponding link object in links"""
  243. url = parse_url(folder)
  244. if url:
  245. for link in links:
  246. if (link['base_url'] in url) or (url in link['url']):
  247. return link
  248. timestamp = folder.split('.')[0]
  249. for link in links:
  250. if link['timestamp'].startswith(timestamp):
  251. if link['domain'] in os.listdir(os.path.join(ARCHIVE_DIR, folder)):
  252. return link # careful now, this isn't safe for most ppl
  253. if link['domain'] in parse_url(folder):
  254. return link
  255. return None
  256. def parse_url(folder):
  257. """for a given archive folder, figure out what url it's for"""
  258. link_json = os.path.join(ARCHIVE_DIR, folder, 'index.json')
  259. if os.path.exists(link_json):
  260. with open(link_json, 'r') as f:
  261. try:
  262. link_json = f.read().strip()
  263. if link_json:
  264. link = json.loads(link_json)
  265. return link['base_url']
  266. except ValueError:
  267. print('File contains invalid JSON: {}!'.format(link_json))
  268. archive_org_txt = os.path.join(ARCHIVE_DIR, folder, 'archive.org.txt')
  269. if os.path.exists(archive_org_txt):
  270. with open(archive_org_txt, 'r') as f:
  271. original_link = f.read().strip().split('/http', 1)[-1]
  272. with_scheme = 'http{}'.format(original_link)
  273. return with_scheme
  274. return ''
  275. def manually_merge_folders(source, target):
  276. """prompt for user input to resolve a conflict between two archive folders"""
  277. if not IS_TTY:
  278. return
  279. fname = lambda path: path.split('/')[-1]
  280. print(' {} and {} have conflicting files, which do you want to keep?'.format(fname(source), fname(target)))
  281. print(' - [enter]: do nothing (keep both)')
  282. print(' - a: prefer files from {}'.format(source))
  283. print(' - b: prefer files from {}'.format(target))
  284. print(' - q: quit and resolve the conflict manually')
  285. try:
  286. answer = input('> ').strip().lower()
  287. except KeyboardInterrupt:
  288. answer = 'q'
  289. assert answer in ('', 'a', 'b', 'q'), 'Invalid choice.'
  290. if answer == 'q':
  291. print('\nJust run ArchiveBox again to pick up where you left off.')
  292. raise SystemExit(0)
  293. elif answer == '':
  294. return
  295. files_in_source = set(os.listdir(source))
  296. files_in_target = set(os.listdir(target))
  297. for file in files_in_source:
  298. if file in files_in_target:
  299. to_delete = target if answer == 'a' else source
  300. run(['rm', '-Rf', os.path.join(to_delete, file)])
  301. run(['mv', os.path.join(source, file), os.path.join(target, file)])
  302. if not set(os.listdir(source)):
  303. run(['rm', '-Rf', source])
  304. def fix_folder_path(archive_path, link_folder, link):
  305. """given a folder, merge it to the canonical 'correct' path for the given link object"""
  306. source = os.path.join(archive_path, link_folder)
  307. target = os.path.join(archive_path, link['timestamp'])
  308. url_in_folder = parse_url(source)
  309. if not (url_in_folder in link['base_url']
  310. or link['base_url'] in url_in_folder):
  311. raise ValueError('The link does not match the url for this folder.')
  312. if not os.path.exists(target):
  313. # target doesn't exist so nothing needs merging, simply move A to B
  314. run(['mv', source, target])
  315. else:
  316. # target folder exists, check for conflicting files and attempt manual merge
  317. files_in_source = set(os.listdir(source))
  318. files_in_target = set(os.listdir(target))
  319. conflicting_files = files_in_source & files_in_target
  320. if not conflicting_files:
  321. for file in files_in_source:
  322. run(['mv', os.path.join(source, file), os.path.join(target, file)])
  323. if os.path.exists(source):
  324. files_in_source = set(os.listdir(source))
  325. if files_in_source:
  326. manually_merge_folders(source, target)
  327. else:
  328. run(['rm', '-R', source])
  329. def migrate_data():
  330. # migrate old folder to new OUTPUT folder
  331. old_dir = os.path.join(REPO_DIR, 'html')
  332. if os.path.exists(old_dir):
  333. print('[!] WARNING: Moved old output folder "html" to new location: {}'.format(OUTPUT_DIR))
  334. run(['mv', old_dir, OUTPUT_DIR], timeout=10)
  335. def cleanup_archive(archive_path, links):
  336. """move any incorrectly named folders to their canonical locations"""
  337. # for each folder that exists, see if we can match it up with a known good link
  338. # if we can, then merge the two folders (TODO: if not, move it to lost & found)
  339. unmatched = []
  340. bad_folders = []
  341. if not os.path.exists(archive_path):
  342. return
  343. for folder in os.listdir(archive_path):
  344. try:
  345. files = os.listdir(os.path.join(archive_path, folder))
  346. except NotADirectoryError:
  347. continue
  348. if files:
  349. link = find_link(folder, links)
  350. if link is None:
  351. unmatched.append(folder)
  352. continue
  353. if folder != link['timestamp']:
  354. bad_folders.append((folder, link))
  355. else:
  356. # delete empty folders
  357. run(['rm', '-R', os.path.join(archive_path, folder)])
  358. if bad_folders and IS_TTY and input('[!] Cleanup archive? y/[n]: ') == 'y':
  359. print('[!] Fixing {} improperly named folders in archive...'.format(len(bad_folders)))
  360. for folder, link in bad_folders:
  361. fix_folder_path(archive_path, folder, link)
  362. elif bad_folders:
  363. print('[!] Warning! {} folders need to be merged, fix by running ArchiveBox.'.format(len(bad_folders)))
  364. if unmatched:
  365. print('[!] Warning! {} unrecognized folders in html/archive/'.format(len(unmatched)))
  366. print(' '+ '\n '.join(unmatched))
  367. def wget_output_path(link, look_in=None):
  368. """calculate the path to the wgetted .html file, since wget may
  369. adjust some paths to be different than the base_url path.
  370. See docs on wget --adjust-extension (-E)
  371. """
  372. # if we have it stored, always prefer the actual output path to computed one
  373. if link.get('latest', {}).get('wget'):
  374. return link['latest']['wget']
  375. urlencode = lambda s: quote(s, encoding='utf-8', errors='replace')
  376. if link['type'] in ('PDF', 'image'):
  377. return urlencode(link['base_url'])
  378. # Since the wget algorithm to for -E (appending .html) is incredibly complex
  379. # instead of trying to emulate it here, we just look in the output folder
  380. # to see what html file wget actually created as the output
  381. wget_folder = link['base_url'].rsplit('/', 1)[0].split('/')
  382. look_in = os.path.join(ARCHIVE_DIR, link['timestamp'], *wget_folder)
  383. if look_in and os.path.exists(look_in):
  384. html_files = [
  385. f for f in os.listdir(look_in)
  386. if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", f, re.I | re.M)
  387. ]
  388. if html_files:
  389. return urlencode(os.path.join(*wget_folder, html_files[0]))
  390. return None
  391. # If finding the actual output file didn't work, fall back to the buggy
  392. # implementation of the wget .html appending algorithm
  393. # split_url = link['url'].split('#', 1)
  394. # query = ('%3F' + link['url'].split('?', 1)[-1]) if '?' in link['url'] else ''
  395. # if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", split_url[0], re.I | re.M):
  396. # # already ends in .html
  397. # return urlencode(link['base_url'])
  398. # else:
  399. # # .html needs to be appended
  400. # without_scheme = split_url[0].split('://', 1)[-1].split('?', 1)[0]
  401. # if without_scheme.endswith('/'):
  402. # if query:
  403. # return urlencode('#'.join([without_scheme + 'index.html' + query + '.html', *split_url[1:]]))
  404. # return urlencode('#'.join([without_scheme + 'index.html', *split_url[1:]]))
  405. # else:
  406. # if query:
  407. # return urlencode('#'.join([without_scheme + '/index.html' + query + '.html', *split_url[1:]]))
  408. # elif '/' in without_scheme:
  409. # return urlencode('#'.join([without_scheme + '.html', *split_url[1:]]))
  410. # return urlencode(link['base_url'] + '/index.html')
  411. def derived_link_info(link):
  412. """extend link info with the archive urls and other derived data"""
  413. link_info = {
  414. **link,
  415. 'date': datetime.fromtimestamp(Decimal(link['timestamp'])).strftime('%Y-%m-%d %H:%M'),
  416. 'google_favicon_url': 'https://www.google.com/s2/favicons?domain={domain}'.format(**link),
  417. 'favicon_url': 'archive/{timestamp}/favicon.ico'.format(**link),
  418. 'files_url': 'archive/{timestamp}/index.html'.format(**link),
  419. 'archive_url': 'archive/{}/{}'.format(link['timestamp'], wget_output_path(link) or 'index.html'),
  420. 'pdf_link': 'archive/{timestamp}/output.pdf'.format(**link),
  421. 'screenshot_link': 'archive/{timestamp}/screenshot.png'.format(**link),
  422. 'dom_link': 'archive/{timestamp}/output.html'.format(**link),
  423. 'archive_org_url': 'https://web.archive.org/web/{base_url}'.format(**link),
  424. }
  425. # PDF and images are handled slightly differently
  426. # wget, screenshot, & pdf urls all point to the same file
  427. if link['type'] in ('PDF', 'image'):
  428. link_info.update({
  429. 'archive_url': 'archive/{timestamp}/{base_url}'.format(**link),
  430. 'pdf_link': 'archive/{timestamp}/{base_url}'.format(**link),
  431. 'screenshot_link': 'archive/{timestamp}/{base_url}'.format(**link),
  432. 'dom_link': 'archive/{timestamp}/{base_url}'.format(**link),
  433. 'title': '{title} ({type})'.format(**link),
  434. })
  435. return link_info
  436. def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
  437. """Patched of subprocess.run to fix blocking io making timeout=innefective"""
  438. if input is not None:
  439. if 'stdin' in kwargs:
  440. raise ValueError('stdin and input arguments may not both be used.')
  441. kwargs['stdin'] = PIPE
  442. if capture_output:
  443. if ('stdout' in kwargs) or ('stderr' in kwargs):
  444. raise ValueError('stdout and stderr arguments may not be used '
  445. 'with capture_output.')
  446. kwargs['stdout'] = PIPE
  447. kwargs['stderr'] = PIPE
  448. with Popen(*popenargs, **kwargs) as process:
  449. try:
  450. stdout, stderr = process.communicate(input, timeout=timeout)
  451. except TimeoutExpired:
  452. process.kill()
  453. try:
  454. stdout, stderr = process.communicate(input, timeout=2)
  455. except:
  456. pass
  457. raise TimeoutExpired(popenargs[0][0], timeout)
  458. except BaseException as err:
  459. process.kill()
  460. # We don't call process.wait() as .__exit__ does that for us.
  461. raise
  462. retcode = process.poll()
  463. if check and retcode:
  464. raise CalledProcessError(retcode, process.args,
  465. output=stdout, stderr=stderr)
  466. return CompletedProcess(process.args, retcode, stdout, stderr)