Blame 00335-backport-pathfix-change.patch

433cb8c
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
433cb8c
From: Patrik Kopkan <pkopkan@redhat.com>
433cb8c
Date: Tue, 28 Jul 2020 18:38:07 +0200
433cb8c
Subject: [PATCH] 00335: Backport pathfix change
433cb8c
433cb8c
Tools/scripts/pathfix.py backports
433cb8c
Add -k and -a command line options to preserve and add shebang flags
433cb8c
In upstream since 3.8: https://bugs.python.org/issue37064
433cb8c
Assume all .py files are Python scripts when working recursively:
433cb8c
In upstream since 3.8: https://bugs.python.org/issue38347
433cb8c
433cb8c
Co-authored-by: Victor Stinner <vstinner@redhat.com>
433cb8c
---
433cb8c
 Lib/test/test_tools/test_pathfix.py           | 129 ++++++++++++++++++
433cb8c
 .../2019-05-27-15-26-12.bpo-37064.k_SPW2.rst  |   2 +
433cb8c
 Tools/scripts/pathfix.py                      |  60 +++++++-
433cb8c
 3 files changed, 186 insertions(+), 5 deletions(-)
433cb8c
 create mode 100644 Lib/test/test_tools/test_pathfix.py
433cb8c
 create mode 100644 Misc/NEWS.d/next/Tools-Demos/2019-05-27-15-26-12.bpo-37064.k_SPW2.rst
433cb8c
433cb8c
diff --git a/Lib/test/test_tools/test_pathfix.py b/Lib/test/test_tools/test_pathfix.py
433cb8c
new file mode 100644
433cb8c
index 0000000000..ec361178e6
433cb8c
--- /dev/null
433cb8c
+++ b/Lib/test/test_tools/test_pathfix.py
433cb8c
@@ -0,0 +1,129 @@
433cb8c
+import os
433cb8c
+import subprocess
433cb8c
+import sys
433cb8c
+import unittest
433cb8c
+from test import support
433cb8c
+from test.test_tools import import_tool, scriptsdir, skip_if_missing
433cb8c
+
433cb8c
+
433cb8c
+# need Tools/script/ directory: skip if run on Python installed on the system
433cb8c
+skip_if_missing()
433cb8c
+
433cb8c
+
433cb8c
+class TestPathfixFunctional(unittest.TestCase):
433cb8c
+    script = os.path.join(scriptsdir, 'pathfix.py')
433cb8c
+
433cb8c
+    def setUp(self):
433cb8c
+        self.addCleanup(support.unlink, support.TESTFN)
433cb8c
+
433cb8c
+    def pathfix(self, shebang, pathfix_flags, exitcode=0, stdout='', stderr='',
433cb8c
+                directory=''):
433cb8c
+        if directory:
433cb8c
+            # bpo-38347: Test filename should contain lowercase, uppercase,
433cb8c
+            # "-", "_" and digits.
433cb8c
+            filename = os.path.join(directory, 'script-A_1.py')
433cb8c
+            pathfix_arg = directory
433cb8c
+        else:
433cb8c
+            filename = support.TESTFN
433cb8c
+            pathfix_arg = filename
433cb8c
+
433cb8c
+        with open(filename, 'w', encoding='utf8') as f:
433cb8c
+            f.write(f'{shebang}\n' + 'print("Hello world")\n')
433cb8c
+
433cb8c
+        proc = subprocess.run(
433cb8c
+            [sys.executable, self.script,
433cb8c
+             *pathfix_flags, '-n', pathfix_arg],
433cb8c
+            capture_output=True, text=1)
433cb8c
+
433cb8c
+        if stdout == '' and proc.returncode == 0:
433cb8c
+            stdout = f'{filename}: updating\n'
433cb8c
+        self.assertEqual(proc.returncode, exitcode, proc)
433cb8c
+        self.assertEqual(proc.stdout, stdout, proc)
433cb8c
+        self.assertEqual(proc.stderr, stderr, proc)
433cb8c
+
433cb8c
+        with open(filename, 'r', encoding='utf8') as f:
433cb8c
+            output = f.read()
433cb8c
+
433cb8c
+        lines = output.split('\n')
433cb8c
+        self.assertEqual(lines[1:], ['print("Hello world")', ''])
433cb8c
+        new_shebang = lines[0]
433cb8c
+
433cb8c
+        if proc.returncode != 0:
433cb8c
+            self.assertEqual(shebang, new_shebang)
433cb8c
+
433cb8c
+        return new_shebang
433cb8c
+
433cb8c
+    def test_recursive(self):
433cb8c
+        tmpdir = support.TESTFN + '.d'
433cb8c
+        self.addCleanup(support.rmtree, tmpdir)
433cb8c
+        os.mkdir(tmpdir)
433cb8c
+        expected_stderr = f"recursedown('{os.path.basename(tmpdir)}')\n"
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python',
433cb8c
+                ['-i', '/usr/bin/python3'],
433cb8c
+                directory=tmpdir,
433cb8c
+                stderr=expected_stderr),
433cb8c
+            '#! /usr/bin/python3')
433cb8c
+
433cb8c
+    def test_pathfix(self):
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python',
433cb8c
+                ['-i', '/usr/bin/python3']),
433cb8c
+            '#! /usr/bin/python3')
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python -R',
433cb8c
+                ['-i', '/usr/bin/python3']),
433cb8c
+            '#! /usr/bin/python3')
433cb8c
+
433cb8c
+    def test_pathfix_keeping_flags(self):
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python -R',
433cb8c
+                ['-i', '/usr/bin/python3', '-k']),
433cb8c
+            '#! /usr/bin/python3 -R')
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python',
433cb8c
+                ['-i', '/usr/bin/python3', '-k']),
433cb8c
+            '#! /usr/bin/python3')
433cb8c
+
433cb8c
+    def test_pathfix_adding_flag(self):
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python',
433cb8c
+                ['-i', '/usr/bin/python3', '-a', 's']),
433cb8c
+            '#! /usr/bin/python3 -s')
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python -S',
433cb8c
+                ['-i', '/usr/bin/python3', '-a', 's']),
433cb8c
+            '#! /usr/bin/python3 -s')
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python -V',
433cb8c
+                ['-i', '/usr/bin/python3', '-a', 'v', '-k']),
433cb8c
+            '#! /usr/bin/python3 -vV')
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python',
433cb8c
+                ['-i', '/usr/bin/python3', '-a', 'Rs']),
433cb8c
+            '#! /usr/bin/python3 -Rs')
433cb8c
+        self.assertEqual(
433cb8c
+            self.pathfix(
433cb8c
+                '#! /usr/bin/env python -W default',
433cb8c
+                ['-i', '/usr/bin/python3', '-a', 's', '-k']),
433cb8c
+            '#! /usr/bin/python3 -sW default')
433cb8c
+
433cb8c
+    def test_pathfix_adding_errors(self):
433cb8c
+        self.pathfix(
433cb8c
+            '#! /usr/bin/env python -E',
433cb8c
+            ['-i', '/usr/bin/python3', '-a', 'W default', '-k'],
433cb8c
+            exitcode=2,
433cb8c
+            stderr="-a option doesn't support whitespaces")
433cb8c
+
433cb8c
+
433cb8c
+if __name__ == '__main__':
433cb8c
+    unittest.main()
433cb8c
diff --git a/Misc/NEWS.d/next/Tools-Demos/2019-05-27-15-26-12.bpo-37064.k_SPW2.rst b/Misc/NEWS.d/next/Tools-Demos/2019-05-27-15-26-12.bpo-37064.k_SPW2.rst
433cb8c
new file mode 100644
433cb8c
index 0000000000..d1210e2953
433cb8c
--- /dev/null
433cb8c
+++ b/Misc/NEWS.d/next/Tools-Demos/2019-05-27-15-26-12.bpo-37064.k_SPW2.rst
433cb8c
@@ -0,0 +1,2 @@
433cb8c
+Add option -k to pathscript.py script: preserve shebang flags.
433cb8c
+Add option -a to pathscript.py script: add flags.
433cb8c
diff --git a/Tools/scripts/pathfix.py b/Tools/scripts/pathfix.py
433cb8c
index 28ee428a3a..127c2fe41e 100755
433cb8c
--- a/Tools/scripts/pathfix.py
433cb8c
+++ b/Tools/scripts/pathfix.py
433cb8c
@@ -1,6 +1,6 @@
433cb8c
 #!/usr/bin/env python3
433cb8c
 
433cb8c
-# Change the #! line occurring in Python scripts.  The new interpreter
433cb8c
+# Change the #! line (shebang) occurring in Python scripts.  The new interpreter
433cb8c
 # pathname must be given with a -i option.
433cb8c
 #
433cb8c
 # Command line arguments are files or directories to be processed.
433cb8c
@@ -10,7 +10,13 @@
433cb8c
 # arguments).
433cb8c
 # The original file is kept as a back-up (with a "~" attached to its name),
433cb8c
 # -n flag can be used to disable this.
433cb8c
-#
433cb8c
+
433cb8c
+# Sometimes you may find shebangs with flags such as `#! /usr/bin/env python -si`.
433cb8c
+# Normally, pathfix overwrites the entire line, including the flags.
433cb8c
+# To change interpreter and keep flags from the original shebang line, use -k.
433cb8c
+# If you want to keep flags and add to them one single literal flag, use option -a.
433cb8c
+
433cb8c
+
433cb8c
 # Undoubtedly you can do this using find and sed or perl, but this is
433cb8c
 # a nice example of Python code that recurses down a directory tree
433cb8c
 # and uses regular expressions.  Also note several subtleties like
433cb8c
@@ -33,16 +39,21 @@ rep = sys.stdout.write
433cb8c
 new_interpreter = None
433cb8c
 preserve_timestamps = False
433cb8c
 create_backup = True
433cb8c
+keep_flags = False
433cb8c
+add_flags = b''
433cb8c
 
433cb8c
 
433cb8c
 def main():
433cb8c
     global new_interpreter
433cb8c
     global preserve_timestamps
433cb8c
     global create_backup
433cb8c
-    usage = ('usage: %s -i /interpreter -p -n file-or-directory ...\n' %
433cb8c
+    global keep_flags
433cb8c
+    global add_flags
433cb8c
+
433cb8c
+    usage = ('usage: %s -i /interpreter -p -n -k -a file-or-directory ...\n' %
433cb8c
              sys.argv[0])
433cb8c
     try:
433cb8c
-        opts, args = getopt.getopt(sys.argv[1:], 'i:pn')
433cb8c
+        opts, args = getopt.getopt(sys.argv[1:], 'i:a:kpn')
433cb8c
     except getopt.error as msg:
433cb8c
         err(str(msg) + '\n')
433cb8c
         err(usage)
433cb8c
@@ -54,6 +65,13 @@ def main():
433cb8c
             preserve_timestamps = True
433cb8c
         if o == '-n':
433cb8c
             create_backup = False
433cb8c
+        if o == '-k':
433cb8c
+            keep_flags = True
433cb8c
+        if o == '-a':
433cb8c
+            add_flags = a.encode()
433cb8c
+            if b' ' in add_flags:
433cb8c
+                err("-a option doesn't support whitespaces")
433cb8c
+                sys.exit(2)
433cb8c
     if not new_interpreter or not new_interpreter.startswith(b'/') or \
433cb8c
            not args:
433cb8c
         err('-i option or file-or-directory missing\n')
433cb8c
@@ -96,6 +114,7 @@ def recursedown(dirname):
433cb8c
         if recursedown(fullname): bad = 1
433cb8c
     return bad
433cb8c
 
433cb8c
+
433cb8c
 def fix(filename):
433cb8c
 ##  dbg('fix(%r)\n' % (filename,))
433cb8c
     try:
433cb8c
@@ -166,12 +185,43 @@ def fix(filename):
433cb8c
     # Return success
433cb8c
     return 0
433cb8c
 
433cb8c
+
433cb8c
+def parse_shebang(shebangline):
433cb8c
+    shebangline = shebangline.rstrip(b'\n')
433cb8c
+    start = shebangline.find(b' -')
433cb8c
+    if start == -1:
433cb8c
+        return b''
433cb8c
+    return shebangline[start:]
433cb8c
+
433cb8c
+
433cb8c
+def populate_flags(shebangline):
433cb8c
+    old_flags = b''
433cb8c
+    if keep_flags:
433cb8c
+        old_flags = parse_shebang(shebangline)
433cb8c
+        if old_flags:
433cb8c
+            old_flags = old_flags[2:]
433cb8c
+    if not (old_flags or add_flags):
433cb8c
+        return b''
433cb8c
+    # On Linux, the entire string following the interpreter name
433cb8c
+    # is passed as a single argument to the interpreter.
433cb8c
+    # e.g. "#! /usr/bin/python3 -W Error -s" runs "/usr/bin/python3 "-W Error -s"
433cb8c
+    # so shebang should have single '-' where flags are given and
433cb8c
+    # flag might need argument for that reasons adding new flags is
433cb8c
+    # between '-' and original flags
433cb8c
+    # e.g. #! /usr/bin/python3 -sW Error
433cb8c
+    return b' -' + add_flags + old_flags
433cb8c
+
433cb8c
+
433cb8c
 def fixline(line):
433cb8c
     if not line.startswith(b'#!'):
433cb8c
         return line
433cb8c
+
433cb8c
     if b"python" not in line:
433cb8c
         return line
433cb8c
-    return b'#! ' + new_interpreter + b'\n'
433cb8c
+
433cb8c
+    flags = populate_flags(line)
433cb8c
+    return b'#! ' + new_interpreter + flags + b'\n'
433cb8c
+
433cb8c
 
433cb8c
 if __name__ == '__main__':
433cb8c
     main()