update.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. from __future__ import annotations
  2. import atexit
  3. import contextlib
  4. import hashlib
  5. import json
  6. import os
  7. import platform
  8. import re
  9. import subprocess
  10. import sys
  11. from dataclasses import dataclass
  12. from zipimport import zipimporter
  13. from .compat import functools # isort: split
  14. from .compat import compat_realpath
  15. from .networking import Request
  16. from .networking.exceptions import HTTPError, network_exceptions
  17. from .utils import (
  18. NO_DEFAULT,
  19. Popen,
  20. deprecation_warning,
  21. format_field,
  22. remove_end,
  23. shell_quote,
  24. system_identifier,
  25. version_tuple,
  26. )
  27. from .version import (
  28. CHANNEL,
  29. ORIGIN,
  30. RELEASE_GIT_HEAD,
  31. UPDATE_HINT,
  32. VARIANT,
  33. __version__,
  34. )
  35. UPDATE_SOURCES = {
  36. 'stable': 'yt-dlp/yt-dlp',
  37. 'nightly': 'yt-dlp/yt-dlp-nightly-builds',
  38. 'master': 'yt-dlp/yt-dlp-master-builds',
  39. }
  40. REPOSITORY = UPDATE_SOURCES['stable']
  41. _INVERSE_UPDATE_SOURCES = {value: key for key, value in UPDATE_SOURCES.items()}
  42. _VERSION_RE = re.compile(r'(\d+\.)*\d+')
  43. _HASH_PATTERN = r'[\da-f]{40}'
  44. _COMMIT_RE = re.compile(rf'Generated from: https://(?:[^/?#]+/){{3}}commit/(?P<hash>{_HASH_PATTERN})')
  45. API_BASE_URL = 'https://api.github.com/repos'
  46. # Backwards compatibility variables for the current channel
  47. API_URL = f'{API_BASE_URL}/{REPOSITORY}/releases'
  48. @functools.cache
  49. def _get_variant_and_executable_path():
  50. """@returns (variant, executable_path)"""
  51. if getattr(sys, 'frozen', False):
  52. path = sys.executable
  53. if not hasattr(sys, '_MEIPASS'):
  54. return 'py2exe', path
  55. elif sys._MEIPASS == os.path.dirname(path):
  56. return f'{sys.platform}_dir', path
  57. elif sys.platform == 'darwin':
  58. machine = '_legacy' if version_tuple(platform.mac_ver()[0]) < (10, 15) else ''
  59. else:
  60. machine = f'_{platform.machine().lower()}'
  61. # Ref: https://en.wikipedia.org/wiki/Uname#Examples
  62. if machine[1:] in ('x86', 'x86_64', 'amd64', 'i386', 'i686'):
  63. machine = '_x86' if platform.architecture()[0][:2] == '32' else ''
  64. # sys.executable returns a /tmp/ path for staticx builds (linux_static)
  65. # Ref: https://staticx.readthedocs.io/en/latest/usage.html#run-time-information
  66. if static_exe_path := os.getenv('STATICX_PROG_PATH'):
  67. path = static_exe_path
  68. return f'{remove_end(sys.platform, "32")}{machine}_exe', path
  69. path = os.path.dirname(__file__)
  70. if isinstance(__loader__, zipimporter):
  71. return 'zip', os.path.join(path, '..')
  72. elif (os.path.basename(sys.argv[0]) in ('__main__.py', '-m')
  73. and os.path.exists(os.path.join(path, '../.git/HEAD'))):
  74. return 'source', path
  75. return 'unknown', path
  76. def detect_variant():
  77. return VARIANT or _get_variant_and_executable_path()[0]
  78. @functools.cache
  79. def current_git_head():
  80. if detect_variant() != 'source':
  81. return
  82. with contextlib.suppress(Exception):
  83. stdout, _, _ = Popen.run(
  84. ['git', 'rev-parse', '--short', 'HEAD'],
  85. text=True, cwd=os.path.dirname(os.path.abspath(__file__)),
  86. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  87. if re.fullmatch('[0-9a-f]+', stdout.strip()):
  88. return stdout.strip()
  89. _FILE_SUFFIXES = {
  90. 'zip': '',
  91. 'py2exe': '_min.exe',
  92. 'win_exe': '.exe',
  93. 'win_x86_exe': '_x86.exe',
  94. 'darwin_exe': '_macos',
  95. 'darwin_legacy_exe': '_macos_legacy',
  96. 'linux_exe': '_linux',
  97. 'linux_aarch64_exe': '_linux_aarch64',
  98. 'linux_armv7l_exe': '_linux_armv7l',
  99. }
  100. _NON_UPDATEABLE_REASONS = {
  101. **{variant: None for variant in _FILE_SUFFIXES}, # Updatable
  102. **{variant: f'Auto-update is not supported for unpackaged {name} executable; Re-download the latest release'
  103. for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS', 'linux_dir': 'Linux'}.items()},
  104. 'source': 'You cannot update when running from source code; Use git to pull the latest changes',
  105. 'unknown': 'You installed yt-dlp from a manual build or with a package manager; Use that to update',
  106. 'other': 'You are using an unofficial build of yt-dlp; Build the executable again',
  107. }
  108. def is_non_updateable():
  109. if UPDATE_HINT:
  110. return UPDATE_HINT
  111. return _NON_UPDATEABLE_REASONS.get(
  112. detect_variant(), _NON_UPDATEABLE_REASONS['unknown' if VARIANT else 'other'])
  113. def _get_binary_name():
  114. return format_field(_FILE_SUFFIXES, detect_variant(), template='yt-dlp%s', ignore=None, default=None)
  115. def _get_system_deprecation():
  116. MIN_SUPPORTED, MIN_RECOMMENDED = (3, 8), (3, 8)
  117. if sys.version_info > MIN_RECOMMENDED:
  118. return None
  119. major, minor = sys.version_info[:2]
  120. if sys.version_info < MIN_SUPPORTED:
  121. msg = f'Python version {major}.{minor} is no longer supported'
  122. else:
  123. msg = (f'Support for Python version {major}.{minor} has been deprecated. '
  124. '\nYou may stop receiving updates on this version at any time')
  125. major, minor = MIN_RECOMMENDED
  126. return f'{msg}! Please update to Python {major}.{minor} or above'
  127. def _sha256_file(path):
  128. h = hashlib.sha256()
  129. mv = memoryview(bytearray(128 * 1024))
  130. with open(os.path.realpath(path), 'rb', buffering=0) as f:
  131. for n in iter(lambda: f.readinto(mv), 0):
  132. h.update(mv[:n])
  133. return h.hexdigest()
  134. def _make_label(origin, tag, version=None):
  135. if '/' in origin:
  136. channel = _INVERSE_UPDATE_SOURCES.get(origin, origin)
  137. else:
  138. channel = origin
  139. label = f'{channel}@{tag}'
  140. if version and version != tag:
  141. label += f' build {version}'
  142. if channel != origin:
  143. label += f' from {origin}'
  144. return label
  145. @dataclass
  146. class UpdateInfo:
  147. """
  148. Update target information
  149. Can be created by `query_update()` or manually.
  150. Attributes:
  151. tag The release tag that will be updated to. If from query_update,
  152. the value is after API resolution and update spec processing.
  153. The only property that is required.
  154. version The actual numeric version (if available) of the binary to be updated to,
  155. after API resolution and update spec processing. (default: None)
  156. requested_version Numeric version of the binary being requested (if available),
  157. after API resolution only. (default: None)
  158. commit Commit hash (if available) of the binary to be updated to,
  159. after API resolution and update spec processing. (default: None)
  160. This value will only match the RELEASE_GIT_HEAD of prerelease builds.
  161. binary_name Filename of the binary to be updated to. (default: current binary name)
  162. checksum Expected checksum (if available) of the binary to be
  163. updated to. (default: None)
  164. """
  165. tag: str
  166. version: str | None = None
  167. requested_version: str | None = None
  168. commit: str | None = None
  169. binary_name: str | None = _get_binary_name() # noqa: RUF009: Always returns the same value
  170. checksum: str | None = None
  171. _has_update = True
  172. class Updater:
  173. # XXX: use class variables to simplify testing
  174. _channel = CHANNEL
  175. _origin = ORIGIN
  176. _update_sources = UPDATE_SOURCES
  177. def __init__(self, ydl, target: str | None = None):
  178. self.ydl = ydl
  179. # For backwards compat, target needs to be treated as if it could be None
  180. self.requested_channel, sep, self.requested_tag = (target or self._channel).rpartition('@')
  181. # Check if requested_tag is actually the requested repo/channel
  182. if not sep and ('/' in self.requested_tag or self.requested_tag in self._update_sources):
  183. self.requested_channel = self.requested_tag
  184. self.requested_tag: str = None # type: ignore (we set it later)
  185. elif not self.requested_channel:
  186. # User did not specify a channel, so we are requesting the default channel
  187. self.requested_channel = self._channel.partition('@')[0]
  188. # --update should not be treated as an exact tag request even if CHANNEL has a @tag
  189. self._exact = bool(target) and target != self._channel
  190. if not self.requested_tag:
  191. # User did not specify a tag, so we request 'latest' and track that no exact tag was passed
  192. self.requested_tag = 'latest'
  193. self._exact = False
  194. if '/' in self.requested_channel:
  195. # requested_channel is actually a repository
  196. self.requested_repo = self.requested_channel
  197. if not self.requested_repo.startswith('yt-dlp/') and self.requested_repo != self._origin:
  198. self.ydl.report_warning(
  199. f'You are switching to an {self.ydl._format_err("unofficial", "red")} executable '
  200. f'from {self.ydl._format_err(self.requested_repo, self.ydl.Styles.EMPHASIS)}. '
  201. f'Run {self.ydl._format_err("at your own risk", "light red")}')
  202. self._block_restart('Automatically restarting into custom builds is disabled for security reasons')
  203. else:
  204. # Check if requested_channel resolves to a known repository or else raise
  205. self.requested_repo = self._update_sources.get(self.requested_channel)
  206. if not self.requested_repo:
  207. self._report_error(
  208. f'Invalid update channel {self.requested_channel!r} requested. '
  209. f'Valid channels are {", ".join(self._update_sources)}', True)
  210. self._identifier = f'{detect_variant()} {system_identifier()}'
  211. @property
  212. def current_version(self):
  213. """Current version"""
  214. return __version__
  215. @property
  216. def current_commit(self):
  217. """Current commit hash"""
  218. return RELEASE_GIT_HEAD
  219. def _download_asset(self, name, tag=None):
  220. if not tag:
  221. tag = self.requested_tag
  222. path = 'latest/download' if tag == 'latest' else f'download/{tag}'
  223. url = f'https://github.com/{self.requested_repo}/releases/{path}/{name}'
  224. self.ydl.write_debug(f'Downloading {name} from {url}')
  225. return self.ydl.urlopen(url).read()
  226. def _call_api(self, tag):
  227. tag = f'tags/{tag}' if tag != 'latest' else tag
  228. url = f'{API_BASE_URL}/{self.requested_repo}/releases/{tag}'
  229. self.ydl.write_debug(f'Fetching release info: {url}')
  230. return json.loads(self.ydl.urlopen(Request(url, headers={
  231. 'Accept': 'application/vnd.github+json',
  232. 'User-Agent': 'yt-dlp',
  233. 'X-GitHub-Api-Version': '2022-11-28',
  234. })).read().decode())
  235. def _get_version_info(self, tag: str) -> tuple[str | None, str | None]:
  236. if _VERSION_RE.fullmatch(tag):
  237. return tag, None
  238. api_info = self._call_api(tag)
  239. if tag == 'latest':
  240. requested_version = api_info['tag_name']
  241. else:
  242. match = re.search(rf'\s+(?P<version>{_VERSION_RE.pattern})$', api_info.get('name', ''))
  243. requested_version = match.group('version') if match else None
  244. if re.fullmatch(_HASH_PATTERN, api_info.get('target_commitish', '')):
  245. target_commitish = api_info['target_commitish']
  246. else:
  247. match = _COMMIT_RE.match(api_info.get('body', ''))
  248. target_commitish = match.group('hash') if match else None
  249. if not (requested_version or target_commitish):
  250. self._report_error('One of either version or commit hash must be available on the release', expected=True)
  251. return requested_version, target_commitish
  252. def _download_update_spec(self, source_tags):
  253. for tag in source_tags:
  254. try:
  255. return self._download_asset('_update_spec', tag=tag).decode()
  256. except network_exceptions as error:
  257. if isinstance(error, HTTPError) and error.status == 404:
  258. continue
  259. self._report_network_error(f'fetch update spec: {error}')
  260. self._report_error(
  261. f'The requested tag {self.requested_tag} does not exist for {self.requested_repo}', True)
  262. return None
  263. def _process_update_spec(self, lockfile: str, resolved_tag: str):
  264. lines = lockfile.splitlines()
  265. is_version2 = any(line.startswith('lockV2 ') for line in lines)
  266. for line in lines:
  267. if is_version2:
  268. if not line.startswith(f'lockV2 {self.requested_repo} '):
  269. continue
  270. _, _, tag, pattern = line.split(' ', 3)
  271. else:
  272. if not line.startswith('lock '):
  273. continue
  274. _, tag, pattern = line.split(' ', 2)
  275. if re.match(pattern, self._identifier):
  276. if _VERSION_RE.fullmatch(tag):
  277. if not self._exact:
  278. return tag
  279. elif self._version_compare(tag, resolved_tag):
  280. return resolved_tag
  281. elif tag != resolved_tag:
  282. continue
  283. self._report_error(
  284. f'yt-dlp cannot be updated to {resolved_tag} since you are on an older Python version', True)
  285. return None
  286. return resolved_tag
  287. def _version_compare(self, a: str, b: str):
  288. """
  289. Compare two version strings
  290. This function SHOULD NOT be called if self._exact == True
  291. """
  292. if _VERSION_RE.fullmatch(f'{a}.{b}'):
  293. return version_tuple(a) >= version_tuple(b)
  294. return a == b
  295. def query_update(self, *, _output=False) -> UpdateInfo | None:
  296. """Fetches info about the available update
  297. @returns An `UpdateInfo` if there is an update available, else None
  298. """
  299. if not self.requested_repo:
  300. self._report_error('No target repository could be determined from input')
  301. return None
  302. try:
  303. requested_version, target_commitish = self._get_version_info(self.requested_tag)
  304. except network_exceptions as e:
  305. self._report_network_error(f'obtain version info ({e})', delim='; Please try again later or')
  306. return None
  307. if self._exact and self._origin != self.requested_repo:
  308. has_update = True
  309. elif requested_version:
  310. if self._exact:
  311. has_update = self.current_version != requested_version
  312. else:
  313. has_update = not self._version_compare(self.current_version, requested_version)
  314. elif target_commitish:
  315. has_update = target_commitish != self.current_commit
  316. else:
  317. has_update = False
  318. resolved_tag = requested_version if self.requested_tag == 'latest' else self.requested_tag
  319. current_label = _make_label(self._origin, self._channel.partition('@')[2] or self.current_version, self.current_version)
  320. requested_label = _make_label(self.requested_repo, resolved_tag, requested_version)
  321. latest_or_requested = f'{"Latest" if self.requested_tag == "latest" else "Requested"} version: {requested_label}'
  322. if not has_update:
  323. if _output:
  324. self.ydl.to_screen(f'{latest_or_requested}\nyt-dlp is up to date ({current_label})')
  325. return None
  326. update_spec = self._download_update_spec(('latest', None) if requested_version else (None,))
  327. if not update_spec:
  328. return None
  329. # `result_` prefixed vars == post-_process_update_spec() values
  330. result_tag = self._process_update_spec(update_spec, resolved_tag)
  331. if not result_tag or result_tag == self.current_version:
  332. return None
  333. elif result_tag == resolved_tag:
  334. result_version = requested_version
  335. elif _VERSION_RE.fullmatch(result_tag):
  336. result_version = result_tag
  337. else: # actual version being updated to is unknown
  338. result_version = None
  339. checksum = None
  340. # Non-updateable variants can get update_info but need to skip checksum
  341. if not is_non_updateable():
  342. try:
  343. hashes = self._download_asset('SHA2-256SUMS', result_tag)
  344. except network_exceptions as error:
  345. if not isinstance(error, HTTPError) or error.status != 404:
  346. self._report_network_error(f'fetch checksums: {error}')
  347. return None
  348. self.ydl.report_warning('No hash information found for the release, skipping verification')
  349. else:
  350. for ln in hashes.decode().splitlines():
  351. if ln.endswith(_get_binary_name()):
  352. checksum = ln.split()[0]
  353. break
  354. if not checksum:
  355. self.ydl.report_warning('The hash could not be found in the checksum file, skipping verification')
  356. if _output:
  357. update_label = _make_label(self.requested_repo, result_tag, result_version)
  358. self.ydl.to_screen(
  359. f'Current version: {current_label}\n{latest_or_requested}'
  360. + (f'\nUpgradable to: {update_label}' if update_label != requested_label else ''))
  361. return UpdateInfo(
  362. tag=result_tag,
  363. version=result_version,
  364. requested_version=requested_version,
  365. commit=target_commitish if result_tag == resolved_tag else None,
  366. checksum=checksum)
  367. def update(self, update_info=NO_DEFAULT):
  368. """Update yt-dlp executable to the latest version
  369. @param update_info `UpdateInfo | None` as returned by query_update()
  370. """
  371. if update_info is NO_DEFAULT:
  372. update_info = self.query_update(_output=True)
  373. if not update_info:
  374. return False
  375. err = is_non_updateable()
  376. if err:
  377. self._report_error(err, True)
  378. return False
  379. self.ydl.to_screen(f'Current Build Hash: {_sha256_file(self.filename)}')
  380. update_label = _make_label(self.requested_repo, update_info.tag, update_info.version)
  381. self.ydl.to_screen(f'Updating to {update_label} ...')
  382. directory = os.path.dirname(self.filename)
  383. if not os.access(self.filename, os.W_OK):
  384. return self._report_permission_error(self.filename)
  385. elif not os.access(directory, os.W_OK):
  386. return self._report_permission_error(directory)
  387. new_filename, old_filename = f'{self.filename}.new', f'{self.filename}.old'
  388. if detect_variant() == 'zip': # Can be replaced in-place
  389. new_filename, old_filename = self.filename, None
  390. try:
  391. if os.path.exists(old_filename or ''):
  392. os.remove(old_filename)
  393. except OSError:
  394. return self._report_error('Unable to remove the old version')
  395. try:
  396. newcontent = self._download_asset(update_info.binary_name, update_info.tag)
  397. except network_exceptions as e:
  398. if isinstance(e, HTTPError) and e.status == 404:
  399. return self._report_error(
  400. f'The requested tag {self.requested_repo}@{update_info.tag} does not exist', True)
  401. return self._report_network_error(f'fetch updates: {e}', tag=update_info.tag)
  402. if not update_info.checksum:
  403. self._block_restart('Automatically restarting into unverified builds is disabled for security reasons')
  404. elif hashlib.sha256(newcontent).hexdigest() != update_info.checksum:
  405. return self._report_network_error('verify the new executable', tag=update_info.tag)
  406. try:
  407. with open(new_filename, 'wb') as outf:
  408. outf.write(newcontent)
  409. except OSError:
  410. return self._report_permission_error(new_filename)
  411. if old_filename:
  412. mask = os.stat(self.filename).st_mode
  413. try:
  414. os.rename(self.filename, old_filename)
  415. except OSError:
  416. return self._report_error('Unable to move current version')
  417. try:
  418. os.rename(new_filename, self.filename)
  419. except OSError:
  420. self._report_error('Unable to overwrite current version')
  421. return os.rename(old_filename, self.filename)
  422. variant = detect_variant()
  423. if variant.startswith('win') or variant == 'py2exe':
  424. atexit.register(Popen, f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
  425. shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  426. elif old_filename:
  427. try:
  428. os.remove(old_filename)
  429. except OSError:
  430. self._report_error('Unable to remove the old version')
  431. try:
  432. os.chmod(self.filename, mask)
  433. except OSError:
  434. return self._report_error(
  435. f'Unable to set permissions. Run: sudo chmod a+rx {shell_quote(self.filename)}')
  436. self.ydl.to_screen(f'Updated yt-dlp to {update_label}')
  437. return True
  438. @functools.cached_property
  439. def filename(self):
  440. """Filename of the executable"""
  441. return compat_realpath(_get_variant_and_executable_path()[1])
  442. @functools.cached_property
  443. def cmd(self):
  444. """The command-line to run the executable, if known"""
  445. # There is no sys.orig_argv in py < 3.10. Also, it can be [] when frozen
  446. if getattr(sys, 'orig_argv', None):
  447. return sys.orig_argv
  448. elif getattr(sys, 'frozen', False):
  449. return sys.argv
  450. def restart(self):
  451. """Restart the executable"""
  452. assert self.cmd, 'Must be frozen or Py >= 3.10'
  453. self.ydl.write_debug(f'Restarting: {shell_quote(self.cmd)}')
  454. _, _, returncode = Popen.run(self.cmd)
  455. return returncode
  456. def _block_restart(self, msg):
  457. def wrapper():
  458. self._report_error(f'{msg}. Restart yt-dlp to use the updated version', expected=True)
  459. return self.ydl._download_retcode
  460. self.restart = wrapper
  461. def _report_error(self, msg, expected=False):
  462. self.ydl.report_error(msg, tb=False if expected else None)
  463. self.ydl._download_retcode = 100
  464. def _report_permission_error(self, file):
  465. self._report_error(f'Unable to write to {file}; try running as administrator', True)
  466. def _report_network_error(self, action, delim=';', tag=None):
  467. if not tag:
  468. tag = self.requested_tag
  469. self._report_error(
  470. f'Unable to {action}{delim} visit https://github.com/{self.requested_repo}/releases/'
  471. + tag if tag == 'latest' else f'tag/{tag}', True)
  472. # XXX: Everything below this line in this class is deprecated / for compat only
  473. @property
  474. def _target_tag(self):
  475. """Deprecated; requested tag with 'tags/' prepended when necessary for API calls"""
  476. return f'tags/{self.requested_tag}' if self.requested_tag != 'latest' else self.requested_tag
  477. def _check_update(self):
  478. """Deprecated; report whether there is an update available"""
  479. return bool(self.query_update(_output=True))
  480. def __getattr__(self, attribute: str):
  481. """Compat getter function for deprecated attributes"""
  482. deprecated_props_map = {
  483. 'check_update': '_check_update',
  484. 'target_tag': '_target_tag',
  485. 'target_channel': 'requested_channel',
  486. }
  487. update_info_props_map = {
  488. 'has_update': '_has_update',
  489. 'new_version': 'version',
  490. 'latest_version': 'requested_version',
  491. 'release_name': 'binary_name',
  492. 'release_hash': 'checksum',
  493. }
  494. if attribute not in deprecated_props_map and attribute not in update_info_props_map:
  495. raise AttributeError(f'{type(self).__name__!r} object has no attribute {attribute!r}')
  496. msg = f'{type(self).__name__}.{attribute} is deprecated and will be removed in a future version'
  497. if attribute in deprecated_props_map:
  498. source_name = deprecated_props_map[attribute]
  499. if not source_name.startswith('_'):
  500. msg += f'. Please use {source_name!r} instead'
  501. source = self
  502. mapping = deprecated_props_map
  503. else: # attribute in update_info_props_map
  504. msg += '. Please call query_update() instead'
  505. source = self.query_update()
  506. if source is None:
  507. source = UpdateInfo('', None, None, None)
  508. source._has_update = False
  509. mapping = update_info_props_map
  510. deprecation_warning(msg)
  511. for target_name, source_name in mapping.items():
  512. value = getattr(source, source_name)
  513. setattr(self, target_name, value)
  514. return getattr(self, attribute)
  515. def run_update(ydl):
  516. """Update the program file with the latest version from the repository
  517. @returns Whether there was a successful update (No update = False)
  518. """
  519. return Updater(ydl).update()
  520. __all__ = ['Updater']