From a5130a6dfff8c89c2a17c1b6196048d2f9a16a88 Mon Sep 17 00:00:00 2001 From: mk-pmb Date: Wed, 15 May 2024 06:16:56 +0200 Subject: [PATCH] [core] Simplify code for report_warning(). --- youtube_dl/YoutubeDL.py | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/youtube_dl/YoutubeDL.py b/youtube_dl/YoutubeDL.py index 6f2aba5ac8e..5b55119de6c 100755 --- a/youtube_dl/YoutubeDL.py +++ b/youtube_dl/YoutubeDL.py @@ -625,6 +625,18 @@ def trouble(self, *args, **kwargs): raise DownloadError(message, exc_info) self._download_retcode = 1 + def can_use_color_codes(self, output_file=None): + """Decide if we should use color codes for the given output channel.""" + # Try to keep criteria ordered by computational effort, easiest first. + if compat_os_name == 'nt': + return False + if self.params.get('no_color'): + return False + if output_file is not None: + if not output_file.isatty(): + return False + return True + def report_warning(self, message, only_once=False, _cache={}): ''' Print the message to stderr, it will be prefixed with 'WARNING:' @@ -637,17 +649,19 @@ def report_warning(self, message, only_once=False, _cache={}): if m_cnt > 0: return - if self.params.get('logger') is not None: - self.params['logger'].warning(message) - else: - if self.params.get('no_warnings'): - return - if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt': - _msg_header = '\033[0;33mWARNING:\033[0m' - else: - _msg_header = 'WARNING:' - warning_message = '%s %s' % (_msg_header, message) - self.to_stderr(warning_message) + custom_logger = self.params.get('logger') + if custom_logger is not None: + custom_logger.warning(message) + return + + if self.params.get('no_warnings'): + return + + msg = 'WARNING:' + if self.can_use_color_codes(output_file=self._err_file): + msg = '\033[0;33m' + msg + '\033[0m' + msg += ' ' + message + self.to_stderr(msg) def report_error(self, message, *args, **kwargs): '''