+@dataclass
+class UpdateInfo:
+ """
+ Update target information
+
+ Can be created by `query_update()` or manually.
+
+ Attributes:
+ tag The release tag that will be updated to. If from query_update,
+ the value is after API resolution and update spec processing.
+ The only property that is required.
+ version The actual numeric version (if available) of the binary to be updated to,
+ after API resolution and update spec processing. (default: None)
+ requested_version Numeric version of the binary being requested (if available),
+ after API resolution only. (default: None)
+ commit Commit hash (if available) of the binary to be updated to,
+ after API resolution and update spec processing. (default: None)
+ This value will only match the RELEASE_GIT_HEAD of prerelease builds.
+ binary_name Filename of the binary to be updated to. (default: current binary name)
+ checksum Expected checksum (if available) of the binary to be
+ updated to. (default: None)
+ """
+ tag: str
+ version: str | None = None
+ requested_version: str | None = None
+ commit: str | None = None
+
+ binary_name: str | None = _get_binary_name()
+ checksum: str | None = None
+
+ _has_update = True
+
+
+class Updater:
+ # XXX: use class variables to simplify testing
+ _channel = CHANNEL
+ _origin = ORIGIN
+ _update_sources = UPDATE_SOURCES
+
+ def __init__(self, ydl, target: str | None = None):
+ self.ydl = ydl
+ # For backwards compat, target needs to be treated as if it could be None
+ self.requested_channel, sep, self.requested_tag = (target or self._channel).rpartition('@')
+ # Check if requested_tag is actually the requested repo/channel
+ if not sep and ('/' in self.requested_tag or self.requested_tag in self._update_sources):
+ self.requested_channel = self.requested_tag
+ self.requested_tag: str = None # type: ignore (we set it later)
+ elif not self.requested_channel:
+ # User did not specify a channel, so we are requesting the default channel
+ self.requested_channel = self._channel.partition('@')[0]
+
+ # --update should not be treated as an exact tag request even if CHANNEL has a @tag
+ self._exact = bool(target) and target != self._channel
+ if not self.requested_tag:
+ # User did not specify a tag, so we request 'latest' and track that no exact tag was passed
+ self.requested_tag = 'latest'
+ self._exact = False
+
+ if '/' in self.requested_channel:
+ # requested_channel is actually a repository
+ self.requested_repo = self.requested_channel
+ if not self.requested_repo.startswith('yt-dlp/') and self.requested_repo != self._origin:
+ self.ydl.report_warning(
+ f'You are switching to an {self.ydl._format_err("unofficial", "red")} executable '
+ f'from {self.ydl._format_err(self.requested_repo, self.ydl.Styles.EMPHASIS)}. '
+ f'Run {self.ydl._format_err("at your own risk", "light red")}')
+ self._block_restart('Automatically restarting into custom builds is disabled for security reasons')
+ else:
+ # Check if requested_channel resolves to a known repository or else raise
+ self.requested_repo = self._update_sources.get(self.requested_channel)
+ if not self.requested_repo:
+ self._report_error(
+ f'Invalid update channel {self.requested_channel!r} requested. '
+ f'Valid channels are {", ".join(self._update_sources)}', True)
+
+ self._identifier = f'{detect_variant()} {system_identifier()}'
+
+ @property
+ def current_version(self):
+ """Current version"""
+ return __version__
+
+ @property
+ def current_commit(self):
+ """Current commit hash"""
+ return RELEASE_GIT_HEAD
+
+ def _download_asset(self, name, tag=None):
+ if not tag:
+ tag = self.requested_tag
+
+ path = 'latest/download' if tag == 'latest' else f'download/{tag}'
+ url = f'https://github.com/{self.requested_repo}/releases/{path}/{name}'
+ self.ydl.write_debug(f'Downloading {name} from {url}')
+ return self.ydl.urlopen(url).read()
+
+ def _call_api(self, tag):
+ tag = f'tags/{tag}' if tag != 'latest' else tag
+ url = f'{API_BASE_URL}/{self.requested_repo}/releases/{tag}'
+ self.ydl.write_debug(f'Fetching release info: {url}')
+ return json.loads(self.ydl.urlopen(Request(url, headers={
+ 'Accept': 'application/vnd.github+json',
+ 'User-Agent': 'yt-dlp',
+ 'X-GitHub-Api-Version': '2022-11-28',
+ })).read().decode())
+
+ def _get_version_info(self, tag: str) -> tuple[str | None, str | None]:
+ if _VERSION_RE.fullmatch(tag):
+ return tag, None
+
+ api_info = self._call_api(tag)
+
+ if tag == 'latest':
+ requested_version = api_info['tag_name']
+ else:
+ match = re.search(rf'\s+(?P<version>{_VERSION_RE.pattern})$', api_info.get('name', ''))
+ requested_version = match.group('version') if match else None
+
+ if re.fullmatch(_HASH_PATTERN, api_info.get('target_commitish', '')):
+ target_commitish = api_info['target_commitish']
+ else:
+ match = _COMMIT_RE.match(api_info.get('body', ''))
+ target_commitish = match.group('hash') if match else None
+
+ if not (requested_version or target_commitish):
+ self._report_error('One of either version or commit hash must be available on the release', expected=True)
+
+ return requested_version, target_commitish
+
+ def _download_update_spec(self, source_tags):
+ for tag in source_tags:
+ try:
+ return self._download_asset('_update_spec', tag=tag).decode()
+ except network_exceptions as error:
+ if isinstance(error, HTTPError) and error.status == 404:
+ continue
+ self._report_network_error(f'fetch update spec: {error}')
+
+ self._report_error(
+ f'The requested tag {self.requested_tag} does not exist for {self.requested_repo}', True)
+ return None
+
+ def _process_update_spec(self, lockfile: str, resolved_tag: str):
+ lines = lockfile.splitlines()
+ is_version2 = any(line.startswith('lockV2 ') for line in lines)
+
+ for line in lines:
+ if is_version2:
+ if not line.startswith(f'lockV2 {self.requested_repo} '):
+ continue
+ _, _, tag, pattern = line.split(' ', 3)
+ else:
+ if not line.startswith('lock '):
+ continue
+ _, tag, pattern = line.split(' ', 2)
+
+ if re.match(pattern, self._identifier):
+ if _VERSION_RE.fullmatch(tag):
+ if not self._exact:
+ return tag
+ elif self._version_compare(tag, resolved_tag):
+ return resolved_tag
+ elif tag != resolved_tag:
+ continue
+
+ self._report_error(
+ f'yt-dlp cannot be updated to {resolved_tag} since you are on an older Python version', True)
+ return None
+
+ return resolved_tag
+
+ def _version_compare(self, a: str, b: str):
+ """
+ Compare two version strings
+
+ This function SHOULD NOT be called if self._exact == True
+ """
+ if _VERSION_RE.fullmatch(f'{a}.{b}'):
+ return version_tuple(a) >= version_tuple(b)
+ return a == b
+
+ def query_update(self, *, _output=False) -> UpdateInfo | None:
+ """Fetches info about the available update
+ @returns An `UpdateInfo` if there is an update available, else None
+ """
+ if not self.requested_repo:
+ self._report_error('No target repository could be determined from input')
+ return None