A feature-rich command-line audio/video downloader
[update] Add option `--update-to`, including to nightly (#6220)
Simon Sawicki77df20f14cc9
diff --git a/Collaborators.md b/Collaborators.mdindex 83dfbe3893..71baf5080b 100644--- a/Collaborators.md+++ b/Collaborators.md@@ -56,6 +56,7 @@ You can also find lists of all [contributors of yt-dlp](CONTRIBUTORS) and [autho## [bashonly](https://github.com/bashonly)+* `--update-to`, automated release, nightly builds* `--cookies-from-browser` support for Firefox containers* Added support for new websites Genius, Kick, NBCStations, Triller, VideoKen etc* Improved/fixed support for Anvato, Brightcove, Instagram, ParamountPlus, Reddit, SlidesLive, TikTok, Twitter, Vimeo etc@@ -65,5 +66,6 @@ You can also find lists of all [contributors of yt-dlp](CONTRIBUTORS) and [autho[](https://ko-fi.com/Grub4K) [](https://github.com/sponsors/Grub4K)+* `--update-to`, automated release, nightly builds* Rework internals like `traverse_obj`, various core refactors and bugs fixes* Helped fix crunchyroll, Twitter, wrestleuniverse, wistia, slideslive etcdiff --git a/README.md b/README.mdindex e6e95b1472..1acd71fd3a 100644--- a/README.md+++ b/README.md@@ -120,7 +120,9 @@ yt-dlp is a [youtube-dl](https://github.com/ytdl-org/youtube-dl) fork based on t* **Plugins**: Extractors and PostProcessors can be loaded from an external file. See [plugins](#plugins) for details-* **Self-updater**: The releases can be updated using `yt-dlp -U`+* **Self updater**: The releases can be updated using `yt-dlp -U`, and downgraded using `--update-to` if required++* **Nightly builds**: [Automated nightly builds](#update-channels) can be used with `--update-to nightly`See [changelog](Changelog.md) or [commits](https://github.com/yt-dlp/yt-dlp/commits) for the full list of changes@@ -187,6 +189,20 @@ If you [installed with PIP](https://github.com/yt-dlp/yt-dlp/wiki/Installation#wFor other third-party package managers, see [the wiki](https://github.com/yt-dlp/yt-dlp/wiki/Installation#third-party-package-managers) or refer their documentation+<a id="update-channels"/>++There are currently two release channels for binaries, `stable` and `nightly`.+`stable` releases are what the program will update to by default, and have had many of their changes tested by users of the master branch.+`nightly` releases are built after each push to the master branch, and will have the most recent fixes and additions, but also have the potential for bugs.+The latest `nightly` is available as a [pre-release from this repository](https://github.com/yt-dlp/yt-dlp/releases/tag/nightly), and all `nightly` releases are [archived in their own repo](https://github.com/yt-dlp/yt-dlp-nightly-builds/releases).++When using `--update`/`-U`, a release binary will only update to its current channel.+This release channel can be changed by using the `--update-to` option. `--update-to` can also be used to upgrade or downgrade to specific tags from a channel.++Example usage:+* `yt-dlp --update-to nightly` change to `nightly` channel and update to its latest release+* `yt-dlp --update-to [email protected]` upgrade/downgrade to release to `stable` channel tag `2023.02.17`+* `yt-dlp --update-to 2023.01.06` upgrade/downgrade to tag `2023.01.06` if it exists on the current channel<!-- MANPAGE: BEGIN EXCLUDED SECTION -->## RELEASE FILES@@ -335,6 +351,11 @@ If you fork the project on GitHub, you can run your fork's [build workflow](.git--version Print program version and exit-U, --update Update this program to the latest version--no-update Do not check for updates (default)+ --update-to [CHANNEL]@[TAG] Upgrade/downgrade to a specific version.+ CHANNEL and TAG defaults to "stable" and+ "latest" respectively if ommited; See+ "UPDATE" for details. Supported channels:+ stable, nightly-i, --ignore-errors Ignore download and postprocessing errors.The download will be considered successfuleven if the postprocessing failsdiff --git a/yt_dlp/__init__.py b/yt_dlp/__init__.pyindex fb44303a26..15c6e997f8 100644--- a/yt_dlp/__init__.py+++ b/yt_dlp/__init__.py@@ -931,7 +931,7 @@ def _real_main(argv=None):if opts.rm_cachedir:ydl.cache.remove()- updater = Updater(ydl)+ updater = Updater(ydl, opts.update_self if isinstance(opts.update_self, str) else None)if opts.update_self and updater.update() and actual_use:if updater.cmd:return updater.restart()diff --git a/yt_dlp/options.py b/yt_dlp/options.pyindex fd60ff55f2..b81e149665 100644--- a/yt_dlp/options.py+++ b/yt_dlp/options.py@@ -20,7 +20,7 @@ from .postprocessor import (SponsorBlockPP,)from .postprocessor.modify_chapters import DEFAULT_SPONSORBLOCK_CHAPTER_TITLE-from .update import detect_variant, is_non_updateable+from .update import UPDATE_SOURCES, detect_variant, is_non_updateablefrom .utils import (OUTTMPL_TYPES,POSTPROCESS_WHEN,@@ -36,7 +36,7 @@ from .utils import (remove_end,write_string,)-from .version import __version__+from .version import CHANNEL, __version__def parseOpts(overrideArguments=None, ignore_config_files='if_override'):@@ -326,11 +326,18 @@ def create_parser():action='store_true', dest='update_self',help=format_field(is_non_updateable(), None, 'Check if updates are available. %s',- default='Update this program to the latest version'))+ default=f'Update this program to the latest {CHANNEL} version'))general.add_option('--no-update',action='store_false', dest='update_self',help='Do not check for updates (default)')+ general.add_option(+ '--update-to',+ action='store', dest='update_self', metavar='[CHANNEL]@[TAG]',+ help=(+ 'Upgrade/downgrade to a specific version. CHANNEL and TAG defaults to '+ f'"{CHANNEL}" and "latest" respectively if ommited; See "UPDATE" for details. '+ f'Supported channels: {", ".join(UPDATE_SOURCES)}'))general.add_option('-i', '--ignore-errors',action='store_true', dest='ignoreerrors',diff --git a/yt_dlp/update.py b/yt_dlp/update.pyindex dad273267f..297539bb68 100644--- a/yt_dlp/update.py+++ b/yt_dlp/update.py@@ -7,6 +7,7 @@ import platformimport reimport subprocessimport sys+import urllib.errorfrom zipimport import zipimporterfrom .compat import functools # isort: split@@ -16,15 +17,26 @@ from .utils import (cached_method,deprecation_warning,remove_end,+ remove_start,+ sanitized_Request,shell_quote,system_identifier,- traverse_obj,version_tuple,)-from .version import UPDATE_HINT, VARIANT, __version__+from .version import CHANNEL, UPDATE_HINT, VARIANT, __version__-REPOSITORY = 'yt-dlp/yt-dlp'-API_URL = f'https://api.github.com/repos/{REPOSITORY}/releases'+UPDATE_SOURCES = {+ 'stable': 'yt-dlp/yt-dlp',+ 'nightly': 'yt-dlp/yt-dlp-nightly-builds',+}++_VERSION_RE = re.compile(r'(\d+\.)*\d+')++API_BASE_URL = 'https://api.github.com/repos'++# Backwards compatibility variables for the current channel+REPOSITORY = UPDATE_SOURCES[CHANNEL]+API_URL = f'{API_BASE_URL}/{REPOSITORY}/releases'@functools.cache@@ -110,49 +122,99 @@ def _sha256_file(path):class Updater:- def __init__(self, ydl):+ _exact = True++ def __init__(self, ydl, target=None):self.ydl = ydl+ self.target_channel, sep, self.target_tag = (target or CHANNEL).rpartition('@')+ if not sep and self.target_tag in UPDATE_SOURCES: # stable => stable@latest+ self.target_channel, self.target_tag = self.target_tag, None+ elif not self.target_channel:+ self.target_channel = CHANNEL++ if not self.target_tag:+ self.target_tag, self._exact = 'latest', False+ elif self.target_tag != 'latest':+ self.target_tag = f'tags/{self.target_tag}'++ @property+ def _target_repo(self):+ try:+ return UPDATE_SOURCES[self.target_channel]+ except KeyError:+ return self._report_error(+ f'Invalid update channel {self.target_channel!r} requested. '+ f'Valid channels are {", ".join(UPDATE_SOURCES)}', True)++ def _version_compare(self, a, b, channel=CHANNEL):+ if channel != self.target_channel:+ return False++ if _VERSION_RE.fullmatch(f'{a}.{b}'):+ a, b = version_tuple(a), version_tuple(b)+ return a == b if self._exact else a >= b+ return a == b+@functools.cached_propertydef _tag(self):- if version_tuple(__version__) >= version_tuple(self.latest_version):- return 'latest'+ if self._version_compare(self.current_version, self.latest_version):+ return self.target_tag- identifier = f'{detect_variant()} {system_identifier()}'+ identifier = f'{detect_variant()} {self.target_channel} {system_identifier()}'for line in self._download('_update_spec', 'latest').decode().splitlines():if not line.startswith('lock '):continue_, tag, pattern = line.split(' ', 2)if re.match(pattern, identifier):- return f'tags/{tag}'- return 'latest'+ if not self._exact:+ return f'tags/{tag}'+ elif self.target_tag == 'latest' or not self._version_compare(+ tag, self.target_tag[5:], channel=self.target_channel):+ self._report_error(+ f'yt-dlp cannot be updated above {tag} since you are on an older Python version', True)+ return f'tags/{self.current_version}'+ return self.target_tag@cached_methoddef _get_version_info(self, tag):- self.ydl.write_debug(f'Fetching release info: {API_URL}/{tag}')- return json.loads(self.ydl.urlopen(f'{API_URL}/{tag}').read().decode())+ url = f'{API_BASE_URL}/{self._target_repo}/releases/{tag}'+ self.ydl.write_debug(f'Fetching release info: {url}')+ return json.loads(self.ydl.urlopen(sanitized_Request(url, headers={+ 'Accept': 'application/vnd.github+json',+ 'User-Agent': 'yt-dlp',+ 'X-GitHub-Api-Version': '2022-11-28',+ })).read().decode())@propertydef current_version(self):"""Current version"""return __version__+ @staticmethod+ def _label(channel, tag):+ """Label for a given channel and tag"""+ return f'{channel}@{remove_start(tag, "tags/")}'++ def _get_actual_tag(self, tag):+ if tag.startswith('tags/'):+ return tag[5:]+ return self._get_version_info(tag)['tag_name']+@propertydef new_version(self):"""Version of the latest release we can update to"""- if self._tag.startswith('tags/'):- return self._tag[5:]- return self._get_version_info(self._tag)['tag_name']+ return self._get_actual_tag(self._tag)@propertydef latest_version(self):- """Version of the latest release"""- return self._get_version_info('latest')['tag_name']+ """Version of the target release"""+ return self._get_actual_tag(self.target_tag)@propertydef has_update(self):"""Whether there is an update available"""- return version_tuple(__version__) < version_tuple(self.new_version)+ return not self._version_compare(self.current_version, self.new_version)@functools.cached_propertydef filename(self):@@ -160,10 +222,8 @@ class Updater:return compat_realpath(_get_variant_and_executable_path()[1])def _download(self, name, tag):- url = traverse_obj(self._get_version_info(tag), (- 'assets', lambda _, v: v['name'] == name, 'browser_download_url'), get_all=False)- if not url:- raise Exception('Unable to find download URL')+ slug = 'latest/download' if tag == 'latest' else f'download/{tag[5:]}'+ url = f'https://github.com/{self._target_repo}/releases/{slug}/{name}'self.ydl.write_debug(f'Downloading {name} from {url}')return self.ydl.urlopen(url).read()@@ -186,24 +246,32 @@ class Updater:self._report_error(f'Unable to write to {file}; Try running as administrator', True)def _report_network_error(self, action, delim=';'):- self._report_error(f'Unable to {action}{delim} Visit https://github.com/{REPOSITORY}/releases/latest', True)+ self._report_error(+ f'Unable to {action}{delim} visit '+ f'https://github.com/{self._target_repo}/releases/{self.target_tag.replace("tags/", "tag/")}', True)def check_update(self):"""Report whether there is an update available"""+ if not self._target_repo:+ return Falsetry:- self.ydl.to_screen(- f'Latest version: {self.latest_version}, Current version: {self.current_version}')- if not self.has_update:- if self._tag == 'latest':- return self.ydl.to_screen(f'yt-dlp is up to date ({__version__})')- return self.ydl.report_warning(- 'yt-dlp cannot be updated any further since you are on an older Python version')+ self.ydl.to_screen((+ f'Available version: {self._label(self.target_channel, self.latest_version)}, ' if self.target_tag == 'latest' else ''+ ) + f'Current version: {self._label(CHANNEL, self.current_version)}')except Exception:return self._report_network_error('obtain version info', delim='; Please try again later or')if not is_non_updateable():- self.ydl.to_screen(f'Current Build Hash {_sha256_file(self.filename)}')- return True+ self.ydl.to_screen(f'Current Build Hash: {_sha256_file(self.filename)}')++ if self.has_update:+ return True++ if self.target_tag == self._tag:+ self.ydl.to_screen(f'yt-dlp is up to date ({self._label(CHANNEL, self.current_version)})')+ elif not self._exact:+ self.ydl.report_warning('yt-dlp cannot be updated any further since you are on an older Python version')+ return Falsedef update(self):"""Update yt-dlp executable to the latest version"""@@ -212,7 +280,10 @@ class Updater:err = is_non_updateable()if err:return self._report_error(err, True)- self.ydl.to_screen(f'Updating to version {self.new_version} ...')+ self.ydl.to_screen(f'Updating to {self._label(self.target_channel, self.new_version)} ...')+ if (_VERSION_RE.fullmatch(self.target_tag[5:])+ and version_tuple(self.target_tag[5:]) < (2023, 3, 2)):+ self.ydl.report_warning('You are downgrading to a version without --update-to')directory = os.path.dirname(self.filename)if not os.access(self.filename, os.W_OK):@@ -232,10 +303,11 @@ class Updater:try:newcontent = self._download(self.release_name, self._tag)- except OSError:- return self._report_network_error('download latest version')- except Exception:- return self._report_network_error('fetch updates')+ except Exception as e:+ if isinstance(e, urllib.error.HTTPError) and e.code == 404:+ return self._report_error(+ f'The requested tag {self._label(self.target_channel, self.target_tag)} does not exist', True)+ return self._report_network_error(f'fetch updates: {e}')try:expected_hash = self.release_hash@@ -280,7 +352,7 @@ class Updater:return self._report_error(f'Unable to set permissions. Run: sudo chmod a+rx {compat_shlex_quote(self.filename)}')- self.ydl.to_screen(f'Updated yt-dlp to version {self.new_version}')+ self.ydl.to_screen(f'Updated yt-dlp to {self._label(self.target_channel, self.new_version)}')return True@functools.cached_property@@ -346,3 +418,6 @@ def update_self(to_screen, verbose, opener):return opener.open(url)return run_update(FakeYDL())+++__all__ = ['Updater']diff --git a/yt_dlp/version.py b/yt_dlp/version.pyindex 3c92a85e10..f477a927ab 100644--- a/yt_dlp/version.py+++ b/yt_dlp/version.py@@ -7,3 +7,5 @@ RELEASE_GIT_HEAD = 'a0a7c0154'VARIANT = NoneUPDATE_HINT = None++CHANNEL = 'stable'