[utils] Add deprecation_warning

See https://github.com/yt-dlp/yt-dlp/pull/2173#issuecomment-1097021515
This commit is contained in:
pukkandan 2022-08-30 20:58:28 +05:30
parent e1eabd7beb
commit da4db748fa
No known key found for this signature in database
GPG Key ID: 7EEE9E1E817D0A39
12 changed files with 67 additions and 40 deletions

View File

@ -90,6 +90,7 @@
args_to_str, args_to_str,
bug_reports_message, bug_reports_message,
date_from_str, date_from_str,
deprecation_warning,
determine_ext, determine_ext,
determine_protocol, determine_protocol,
encode_compat_str, encode_compat_str,
@ -631,7 +632,7 @@ def check_deprecated(param, option, suggestion):
for msg in self.params.get('_warnings', []): for msg in self.params.get('_warnings', []):
self.report_warning(msg) self.report_warning(msg)
for msg in self.params.get('_deprecation_warnings', []): for msg in self.params.get('_deprecation_warnings', []):
self.deprecation_warning(msg) self.deprecated_feature(msg)
self.params['compat_opts'] = set(self.params.get('compat_opts', ())) self.params['compat_opts'] = set(self.params.get('compat_opts', ()))
if 'list-formats' in self.params['compat_opts']: if 'list-formats' in self.params['compat_opts']:
@ -835,9 +836,11 @@ def _write_string(self, message, out=None, only_once=False):
def to_stdout(self, message, skip_eol=False, quiet=None): def to_stdout(self, message, skip_eol=False, quiet=None):
"""Print message to stdout""" """Print message to stdout"""
if quiet is not None: if quiet is not None:
self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument quiet. Use "YoutubeDL.to_screen" instead') self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument quiet. '
'Use "YoutubeDL.to_screen" instead')
if skip_eol is not False: if skip_eol is not False:
self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. Use "YoutubeDL.to_screen" instead') self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. '
'Use "YoutubeDL.to_screen" instead')
self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.out) self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.out)
def to_screen(self, message, skip_eol=False, quiet=None): def to_screen(self, message, skip_eol=False, quiet=None):
@ -973,11 +976,14 @@ def report_warning(self, message, only_once=False):
return return
self.to_stderr(f'{self._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once) self.to_stderr(f'{self._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once)
def deprecation_warning(self, message): def deprecation_warning(self, message, *, stacklevel=0):
deprecation_warning(
message, stacklevel=stacklevel + 1, printer=self.report_error, is_error=False)
def deprecated_feature(self, message):
if self.params.get('logger') is not None: if self.params.get('logger') is not None:
self.params['logger'].warning(f'DeprecationWarning: {message}') self.params['logger'].warning(f'Deprecated Feature: {message}')
else: self.to_stderr(f'{self._format_err("Deprecated Feature:", self.Styles.ERROR)} {message}', True)
self.to_stderr(f'{self._format_err("DeprecationWarning:", self.Styles.ERROR)} {message}', True)
def report_error(self, message, *args, **kwargs): def report_error(self, message, *args, **kwargs):
''' '''

View File

@ -63,6 +63,8 @@
) )
from .YoutubeDL import YoutubeDL from .YoutubeDL import YoutubeDL
_IN_CLI = False
def _exit(status=0, *args): def _exit(status=0, *args):
for msg in args: for msg in args:

View File

@ -14,4 +14,5 @@
import yt_dlp import yt_dlp
if __name__ == '__main__': if __name__ == '__main__':
yt_dlp._IN_CLI = True
yt_dlp.main() yt_dlp.main()

View File

@ -92,6 +92,7 @@ def _set_ydl(self, ydl):
for func in ( for func in (
'deprecation_warning', 'deprecation_warning',
'deprecated_feature',
'report_error', 'report_error',
'report_file_already_downloaded', 'report_file_already_downloaded',
'report_warning', 'report_warning',

View File

@ -65,8 +65,8 @@ class FragmentFD(FileDownloader):
""" """
def report_retry_fragment(self, err, frag_index, count, retries): def report_retry_fragment(self, err, frag_index, count, retries):
self.deprecation_warning( self.deprecation_warning('yt_dlp.downloader.FragmentFD.report_retry_fragment is deprecated. '
'yt_dlp.downloader.FragmentFD.report_retry_fragment is deprecated. Use yt_dlp.downloader.FileDownloader.report_retry instead') 'Use yt_dlp.downloader.FileDownloader.report_retry instead')
return self.report_retry(err, count, retries, frag_index) return self.report_retry(err, count, retries, frag_index)
def report_skip_fragment(self, frag_index, err=None): def report_skip_fragment(self, frag_index, err=None):

View File

@ -1766,9 +1766,8 @@ def _get_field_setting(self, field, key):
if field not in self.settings: if field not in self.settings:
if key in ('forced', 'priority'): if key in ('forced', 'priority'):
return False return False
self.ydl.deprecation_warning( self.ydl.deprecated_feature(f'Using arbitrary fields ({field}) for format sorting is '
f'Using arbitrary fields ({field}) for format sorting is deprecated ' 'deprecated and may be removed in a future version')
'and may be removed in a future version')
self.settings[field] = {} self.settings[field] = {}
propObj = self.settings[field] propObj = self.settings[field]
if key not in propObj: if key not in propObj:
@ -1853,9 +1852,8 @@ def add_item(field, reverse, closest, limit_text):
if self._get_field_setting(field, 'type') == 'alias': if self._get_field_setting(field, 'type') == 'alias':
alias, field = field, self._get_field_setting(field, 'field') alias, field = field, self._get_field_setting(field, 'field')
if self._get_field_setting(alias, 'deprecated'): if self._get_field_setting(alias, 'deprecated'):
self.ydl.deprecation_warning( self.ydl.deprecated_feature(f'Format sorting alias {alias} is deprecated and may '
f'Format sorting alias {alias} is deprecated ' 'be removed in a future version. Please use {field} instead')
f'and may be removed in a future version. Please use {field} instead')
reverse = match.group('reverse') is not None reverse = match.group('reverse') is not None
closest = match.group('separator') == '~' closest = match.group('separator') == '~'
limit_text = match.group('limit') limit_text = match.group('limit')

View File

@ -2959,8 +2959,8 @@ def extract_thread(contents):
# YouTube comments have a max depth of 2 # YouTube comments have a max depth of 2
max_depth = int_or_none(get_single_config_arg('max_comment_depth')) max_depth = int_or_none(get_single_config_arg('max_comment_depth'))
if max_depth: if max_depth:
self._downloader.deprecation_warning( self._downloader.deprecated_feature('[youtube] max_comment_depth extractor argument is deprecated. '
'[youtube] max_comment_depth extractor argument is deprecated. Set max replies in the max-comments extractor argument instead.') 'Set max replies in the max-comments extractor argument instead')
if max_depth == 1 and parent: if max_depth == 1 and parent:
return return

View File

@ -25,6 +25,7 @@
OUTTMPL_TYPES, OUTTMPL_TYPES,
POSTPROCESS_WHEN, POSTPROCESS_WHEN,
Config, Config,
deprecation_warning,
expand_path, expand_path,
format_field, format_field,
get_executable_path, get_executable_path,
@ -1864,7 +1865,6 @@ def _alias_callback(option, opt_str, value, parser, opts, nargs):
def _hide_login_info(opts): def _hide_login_info(opts):
write_string( deprecation_warning(f'"{__name__}._hide_login_info" is deprecated and may be removed '
'DeprecationWarning: "yt_dlp.options._hide_login_info" is deprecated and may be removed in a future version. ' 'in a future version. Use "yt_dlp.utils.Config.hide_login_info" instead')
'Use "yt_dlp.utils.Config.hide_login_info" instead\n')
return Config.hide_login_info(opts) return Config.hide_login_info(opts)

View File

@ -7,10 +7,10 @@
PostProcessingError, PostProcessingError,
RetryManager, RetryManager,
_configuration_args, _configuration_args,
deprecation_warning,
encodeFilename, encodeFilename,
network_exceptions, network_exceptions,
sanitized_Request, sanitized_Request,
write_string,
) )
@ -73,10 +73,14 @@ def report_warning(self, text, *args, **kwargs):
if self._downloader: if self._downloader:
return self._downloader.report_warning(text, *args, **kwargs) return self._downloader.report_warning(text, *args, **kwargs)
def deprecation_warning(self, text): def deprecation_warning(self, msg):
warn = getattr(self._downloader, 'deprecation_warning', deprecation_warning)
return warn(msg, stacklevel=1)
def deprecated_feature(self, msg):
if self._downloader: if self._downloader:
return self._downloader.deprecation_warning(text) return self._downloader.deprecated_feature(msg)
write_string(f'DeprecationWarning: {text}') return deprecation_warning(msg, stacklevel=1)
def report_error(self, text, *args, **kwargs): def report_error(self, text, *args, **kwargs):
self.deprecation_warning('"yt_dlp.postprocessor.PostProcessor.report_error" is deprecated. ' self.deprecation_warning('"yt_dlp.postprocessor.PostProcessor.report_error" is deprecated. '

View File

@ -15,6 +15,7 @@
Popen, Popen,
PostProcessingError, PostProcessingError,
_get_exe_version_output, _get_exe_version_output,
deprecation_warning,
detect_exe_version, detect_exe_version,
determine_ext, determine_ext,
dfxp2srt, dfxp2srt,
@ -30,7 +31,6 @@
traverse_obj, traverse_obj,
variadic, variadic,
write_json_file, write_json_file,
write_string,
) )
EXT_TO_OUT_FORMATS = { EXT_TO_OUT_FORMATS = {
@ -187,8 +187,8 @@ def _get_version(self, kind):
else: else:
self.probe_basename = basename self.probe_basename = basename
if basename == self._ffmpeg_to_avconv[kind]: if basename == self._ffmpeg_to_avconv[kind]:
self.deprecation_warning( self.deprecated_feature(f'Support for {self._ffmpeg_to_avconv[kind]} is deprecated and '
f'Support for {self._ffmpeg_to_avconv[kind]} is deprecated and may be removed in a future version. Use {kind} instead') f'may be removed in a future version. Use {kind} instead')
return version return version
@functools.cached_property @functools.cached_property
@ -1064,7 +1064,7 @@ def __init__(self, downloader=None, format=None):
@classmethod @classmethod
def is_webp(cls, path): def is_webp(cls, path):
write_string(f'DeprecationWarning: {cls.__module__}.{cls.__name__}.is_webp is deprecated') deprecation_warning(f'{cls.__module__}.{cls.__name__}.is_webp is deprecated')
return imghdr.what(path) == 'webp' return imghdr.what(path) == 'webp'
def fixup_webp(self, info, idx=-1): def fixup_webp(self, info, idx=-1):

View File

@ -14,6 +14,7 @@
from .utils import ( from .utils import (
Popen, Popen,
cached_method, cached_method,
deprecation_warning,
shell_quote, shell_quote,
system_identifier, system_identifier,
traverse_obj, traverse_obj,
@ -302,11 +303,8 @@ def run_update(ydl):
def update_self(to_screen, verbose, opener): def update_self(to_screen, verbose, opener):
import traceback import traceback
from .utils import write_string deprecation_warning(f'"{__name__}.update_self" is deprecated and may be removed '
f'in a future version. Use "{__name__}.run_update(ydl)" instead')
write_string(
'DeprecationWarning: "yt_dlp.update.update_self" is deprecated and may be removed in a future version. '
'Use "yt_dlp.update.run_update(ydl)" instead\n')
printfn = to_screen printfn = to_screen

View File

@ -828,8 +828,8 @@ def escapeHTML(text):
def process_communicate_or_kill(p, *args, **kwargs): def process_communicate_or_kill(p, *args, **kwargs):
write_string('DeprecationWarning: yt_dlp.utils.process_communicate_or_kill is deprecated ' deprecation_warning(f'"{__name__}.process_communicate_or_kill" is deprecated and may be removed '
'and may be removed in a future version. Use yt_dlp.utils.Popen.communicate_or_kill instead') f'in a future version. Use "{__name__}.Popen.communicate_or_kill" instead')
return Popen.communicate_or_kill(p, *args, **kwargs) return Popen.communicate_or_kill(p, *args, **kwargs)
@ -1934,7 +1934,7 @@ def __eq__(self, other):
def platform_name(): def platform_name():
""" Returns the platform name as a str """ """ Returns the platform name as a str """
write_string('DeprecationWarning: yt_dlp.utils.platform_name is deprecated, use platform.platform instead') deprecation_warning(f'"{__name__}.platform_name" is deprecated, use "platform.platform" instead')
return platform.platform() return platform.platform()
@ -1980,6 +1980,23 @@ def write_string(s, out=None, encoding=None):
out.flush() out.flush()
def deprecation_warning(msg, *, printer=None, stacklevel=0, **kwargs):
from . import _IN_CLI
if _IN_CLI:
if msg in deprecation_warning._cache:
return
deprecation_warning._cache.add(msg)
if printer:
return printer(f'{msg}{bug_reports_message()}', **kwargs)
return write_string(f'ERROR: {msg}{bug_reports_message()}\n', **kwargs)
else:
import warnings
warnings.warn(DeprecationWarning(msg), stacklevel=stacklevel + 3)
deprecation_warning._cache = set()
def bytes_to_intlist(bs): def bytes_to_intlist(bs):
if not bs: if not bs:
return [] return []
@ -4862,8 +4879,8 @@ def decode_base_n(string, n=None, table=None):
def decode_base(value, digits): def decode_base(value, digits):
write_string('DeprecationWarning: yt_dlp.utils.decode_base is deprecated ' deprecation_warning(f'{__name__}.decode_base is deprecated and may be removed '
'and may be removed in a future version. Use yt_dlp.decode_base_n instead') f'in a future version. Use {__name__}.decode_base_n instead')
return decode_base_n(value, table=digits) return decode_base_n(value, table=digits)
@ -5332,8 +5349,8 @@ def _traverse_obj(obj, path, _current_depth=0):
def traverse_dict(dictn, keys, casesense=True): def traverse_dict(dictn, keys, casesense=True):
write_string('DeprecationWarning: yt_dlp.utils.traverse_dict is deprecated ' deprecation_warning(f'"{__name__}.traverse_dict" is deprecated and may be removed '
'and may be removed in a future version. Use yt_dlp.utils.traverse_obj instead') f'in a future version. Use "{__name__}.traverse_obj" instead')
return traverse_obj(dictn, keys, casesense=casesense, is_user_input=True, traverse_string=True) return traverse_obj(dictn, keys, casesense=casesense, is_user_input=True, traverse_string=True)