]> jfr.im git - yt-dlp.git/blobdiff - yt_dlp/update.py
[cleanup] Misc
[yt-dlp.git] / yt_dlp / update.py
index 92c07acc1401738d6f91c327a729874d5a0c399d..ac3e28057de84b7b776d7cdd7eb65b252e5920fa 100644 (file)
@@ -1,4 +1,5 @@
 import atexit
+import contextlib
 import hashlib
 import json
 import os
 from zipimport import zipimporter
 
 from .compat import functools  # isort: split
-from .compat import compat_realpath
+from .compat import compat_realpath, compat_shlex_quote
 from .utils import (
     Popen,
     cached_method,
+    deprecation_warning,
+    remove_end,
     shell_quote,
     system_identifier,
     traverse_obj,
     version_tuple,
 )
-from .version import __version__
+from .version import UPDATE_HINT, VARIANT, __version__
 
 REPOSITORY = 'yt-dlp/yt-dlp'
 API_URL = f'https://api.github.com/repos/{REPOSITORY}/releases'
 @functools.cache
 def _get_variant_and_executable_path():
     """@returns (variant, executable_path)"""
-    if hasattr(sys, 'frozen'):
+    if getattr(sys, 'frozen', False):
         path = sys.executable
         if not hasattr(sys, '_MEIPASS'):
             return 'py2exe', path
-        if sys._MEIPASS == os.path.dirname(path):
+        elif sys._MEIPASS == os.path.dirname(path):
             return f'{sys.platform}_dir', path
-        if sys.platform == 'darwin' and version_tuple(platform.mac_ver()[0]) < (10, 15):
-            return 'darwin_legacy_exe', path
-        return f'{sys.platform}_exe', path
+        elif sys.platform == 'darwin':
+            machine = '_legacy' if version_tuple(platform.mac_ver()[0]) < (10, 15) else ''
+        else:
+            machine = f'_{platform.machine().lower()}'
+            # Ref: https://en.wikipedia.org/wiki/Uname#Examples
+            if machine[1:] in ('x86', 'x86_64', 'amd64', 'i386', 'i686'):
+                machine = '_x86' if platform.architecture()[0][:2] == '32' else ''
+        return f'{remove_end(sys.platform, "32")}{machine}_exe', path
 
     path = os.path.dirname(__file__)
     if isinstance(__loader__, zipimporter):
@@ -47,16 +55,32 @@ def _get_variant_and_executable_path():
 
 
 def detect_variant():
-    return _get_variant_and_executable_path()[0]
+    return VARIANT or _get_variant_and_executable_path()[0]
+
+
+@functools.cache
+def current_git_head():
+    if detect_variant() != 'source':
+        return
+    with contextlib.suppress(Exception):
+        stdout, _, _ = Popen.run(
+            ['git', 'rev-parse', '--short', 'HEAD'],
+            text=True, cwd=os.path.dirname(os.path.abspath(__file__)),
+            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+        if re.fullmatch('[0-9a-f]+', stdout.strip()):
+            return stdout.strip()
 
 
 _FILE_SUFFIXES = {
     'zip': '',
     'py2exe': '_min.exe',
-    'win32_exe': '.exe',
+    'win_exe': '.exe',
+    'win_x86_exe': '_x86.exe',
     'darwin_exe': '_macos',
     'darwin_legacy_exe': '_macos_legacy',
     'linux_exe': '_linux',
+    'linux_aarch64_exe': '_linux_aarch64',
+    'linux_armv7l_exe': '_linux_armv7l',
 }
 
 _NON_UPDATEABLE_REASONS = {
@@ -64,13 +88,16 @@ def detect_variant():
     **{variant: f'Auto-update is not supported for unpackaged {name} executable; Re-download the latest release'
        for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS', 'linux_dir': 'Linux'}.items()},
     'source': 'You cannot update when running from source code; Use git to pull the latest changes',
-    'unknown': 'It looks like you installed yt-dlp with a package manager, pip or setup.py; Use that to update',
-    'other': 'It looks like you are using an unofficial build of yt-dlp; Build the executable again',
+    'unknown': 'You installed yt-dlp with a package manager or setup.py; Use that to update',
+    'other': 'You are using an unofficial build of yt-dlp; Build the executable again',
 }
 
 
 def is_non_updateable():
-    return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['other'])
+    if UPDATE_HINT:
+        return UPDATE_HINT
+    return _NON_UPDATEABLE_REASONS.get(
+        detect_variant(), _NON_UPDATEABLE_REASONS['unknown' if VARIANT else 'other'])
 
 
 def _sha256_file(path):
@@ -143,10 +170,7 @@ def _download(self, name, tag):
     @functools.cached_property
     def release_name(self):
         """The release filename"""
-        label = _FILE_SUFFIXES[detect_variant()]
-        if label and platform.architecture()[0][:2] == '32':
-            label = f'_x86{label}'
-        return f'yt-dlp{label}'
+        return f'yt-dlp{_FILE_SUFFIXES[detect_variant()]}'
 
     @functools.cached_property
     def release_hash(self):
@@ -156,6 +180,7 @@ def release_hash(self):
 
     def _report_error(self, msg, expected=False):
         self.ydl.report_error(msg, tb=False if expected else None)
+        self.ydl._download_retcode = 100
 
     def _report_permission_error(self, file):
         self._report_error(f'Unable to write to {file}; Try running as administrator', True)
@@ -226,24 +251,33 @@ def update(self):
         except OSError:
             return self._report_permission_error(new_filename)
 
-        try:
-            if old_filename:
+        if old_filename:
+            mask = os.stat(self.filename).st_mode
+            try:
                 os.rename(self.filename, old_filename)
-        except OSError:
-            return self._report_error('Unable to move current version')
-        try:
-            if old_filename:
+            except OSError:
+                return self._report_error('Unable to move current version')
+
+            try:
                 os.rename(new_filename, self.filename)
-        except OSError:
-            self._report_error('Unable to overwrite current version')
-            return os.rename(old_filename, self.filename)
+            except OSError:
+                self._report_error('Unable to overwrite current version')
+                return os.rename(old_filename, self.filename)
 
-        if detect_variant() not in ('win32_exe', 'py2exe'):
-            if old_filename:
-                os.remove(old_filename)
-        else:
+        if detect_variant() in ('win32_exe', 'py2exe'):
             atexit.register(Popen, f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
                             shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+        elif old_filename:
+            try:
+                os.remove(old_filename)
+            except OSError:
+                self._report_error('Unable to remove the old version')
+
+            try:
+                os.chmod(self.filename, mask)
+            except OSError:
+                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}')
         return True
@@ -254,7 +288,7 @@ def cmd(self):
         # There is no sys.orig_argv in py < 3.10. Also, it can be [] when frozen
         if getattr(sys, 'orig_argv', None):
             return sys.orig_argv
-        elif hasattr(sys, 'frozen'):
+        elif getattr(sys, 'frozen', False):
             return sys.argv
 
     def restart(self):
@@ -276,11 +310,8 @@ def run_update(ydl):
 def update_self(to_screen, verbose, opener):
     import traceback
 
-    from .utils import write_string
-
-    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')
+    deprecation_warning(f'"{__name__}.update_self" is deprecated and may be removed '
+                        f'in a future version. Use "{__name__}.run_update(ydl)" instead')
 
     printfn = to_screen