Blame SOURCES/00356-k_and_a_options_for_pathfix.patch

bca232
From 0cfd9a7f26488567b9a3e5ec192099a8b80ad9df Mon Sep 17 00:00:00 2001
bca232
From: Lumir Balhar <lbalhar@redhat.com>
bca232
Date: Tue, 19 Jan 2021 07:55:37 +0100
bca232
Subject: [PATCH] [PATCH] bpo-37064: Add -k and -a options to pathfix.py tool
bca232
 (GH-16387)
bca232
bca232
* bpo-37064: Add option -k to Tools/scripts/pathfix.py (GH-15548)
bca232
bca232
Add flag -k to pathscript.py script: preserve shebang flags.
bca232
bca232
(cherry picked from commit 50254ac4c179cb412e90682098c97db786143929)
bca232
bca232
* bpo-37064: Add option -a to pathfix.py tool (GH-15717)
bca232
bca232
Add option -a to Tools/Scripts/pathfix.py script: add flags.
bca232
bca232
(cherry picked from commit 1dc1acbd73f05f14c974b7ce1041787d7abef31e)
bca232
---
bca232
 Lib/test/test_tools/test_pathfix.py | 104 ++++++++++++++++++++++++++++
bca232
 Tools/scripts/pathfix.py            |  64 +++++++++++++++--
bca232
 2 files changed, 163 insertions(+), 5 deletions(-)
bca232
 create mode 100644 Lib/test/test_tools/test_pathfix.py
bca232
bca232
diff --git a/Lib/test/test_tools/test_pathfix.py b/Lib/test/test_tools/test_pathfix.py
bca232
new file mode 100644
bca232
index 0000000..1f0585e
bca232
--- /dev/null
bca232
+++ b/Lib/test/test_tools/test_pathfix.py
bca232
@@ -0,0 +1,104 @@
bca232
+import os
bca232
+import subprocess
bca232
+import sys
bca232
+import unittest
bca232
+from test import support
bca232
+from test.test_tools import import_tool, scriptsdir
bca232
+
bca232
+
bca232
+class TestPathfixFunctional(unittest.TestCase):
bca232
+    script = os.path.join(scriptsdir, 'pathfix.py')
bca232
+
bca232
+    def setUp(self):
bca232
+        self.temp_file = support.TESTFN
bca232
+        self.addCleanup(support.unlink, support.TESTFN)
bca232
+
bca232
+    def pathfix(self, shebang, pathfix_flags, exitcode=0, stdout='', stderr=''):
bca232
+        with open(self.temp_file, 'w', encoding='utf8') as f:
bca232
+            f.write(f'{shebang}\n' + 'print("Hello world")\n')
bca232
+
bca232
+        proc = subprocess.run(
bca232
+            [sys.executable, self.script,
bca232
+             *pathfix_flags, '-n', self.temp_file],
bca232
+            universal_newlines=True, stdout=subprocess.PIPE,
bca232
+            stderr=subprocess.PIPE)
bca232
+
bca232
+        if stdout == '' and proc.returncode == 0:
bca232
+            stdout = f'{self.temp_file}: updating\n'
bca232
+        self.assertEqual(proc.returncode, exitcode, proc)
bca232
+        self.assertEqual(proc.stdout, stdout, proc)
bca232
+        self.assertEqual(proc.stderr, stderr, proc)
bca232
+
bca232
+        with open(self.temp_file, 'r', encoding='utf8') as f:
bca232
+            output = f.read()
bca232
+
bca232
+        lines = output.split('\n')
bca232
+        self.assertEqual(lines[1:], ['print("Hello world")', ''])
bca232
+        new_shebang = lines[0]
bca232
+
bca232
+        if proc.returncode != 0:
bca232
+            self.assertEqual(shebang, new_shebang)
bca232
+
bca232
+        return new_shebang
bca232
+
bca232
+    def test_pathfix(self):
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python',
bca232
+                ['-i', '/usr/bin/python3']),
bca232
+            '#! /usr/bin/python3')
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python -R',
bca232
+                ['-i', '/usr/bin/python3']),
bca232
+            '#! /usr/bin/python3')
bca232
+
bca232
+    def test_pathfix_keeping_flags(self):
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python -R',
bca232
+                ['-i', '/usr/bin/python3', '-k']),
bca232
+            '#! /usr/bin/python3 -R')
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python',
bca232
+                ['-i', '/usr/bin/python3', '-k']),
bca232
+            '#! /usr/bin/python3')
bca232
+
bca232
+    def test_pathfix_adding_flag(self):
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python',
bca232
+                ['-i', '/usr/bin/python3', '-a', 's']),
bca232
+            '#! /usr/bin/python3 -s')
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python -S',
bca232
+                ['-i', '/usr/bin/python3', '-a', 's']),
bca232
+            '#! /usr/bin/python3 -s')
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python -V',
bca232
+                ['-i', '/usr/bin/python3', '-a', 'v', '-k']),
bca232
+            '#! /usr/bin/python3 -vV')
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python',
bca232
+                ['-i', '/usr/bin/python3', '-a', 'Rs']),
bca232
+            '#! /usr/bin/python3 -Rs')
bca232
+        self.assertEqual(
bca232
+            self.pathfix(
bca232
+                '#! /usr/bin/env python -W default',
bca232
+                ['-i', '/usr/bin/python3', '-a', 's', '-k']),
bca232
+            '#! /usr/bin/python3 -sW default')
bca232
+
bca232
+    def test_pathfix_adding_errors(self):
bca232
+        self.pathfix(
bca232
+            '#! /usr/bin/env python -E',
bca232
+            ['-i', '/usr/bin/python3', '-a', 'W default', '-k'],
bca232
+            exitcode=2,
bca232
+            stderr="-a option doesn't support whitespaces")
bca232
+
bca232
+
bca232
+if __name__ == '__main__':
bca232
+    unittest.main()
bca232
diff --git a/Tools/scripts/pathfix.py b/Tools/scripts/pathfix.py
bca232
index c5bf984..2dfa6e8 100755
bca232
--- a/Tools/scripts/pathfix.py
bca232
+++ b/Tools/scripts/pathfix.py
bca232
@@ -1,6 +1,6 @@
bca232
 #!/usr/bin/env python3
bca232
 
bca232
-# Change the #! line occurring in Python scripts.  The new interpreter
bca232
+# Change the #! line (shebang) occurring in Python scripts.  The new interpreter
bca232
 # pathname must be given with a -i option.
bca232
 #
bca232
 # Command line arguments are files or directories to be processed.
bca232
@@ -10,7 +10,13 @@
bca232
 # arguments).
bca232
 # The original file is kept as a back-up (with a "~" attached to its name),
bca232
 # -n flag can be used to disable this.
bca232
-#
bca232
+
bca232
+# Sometimes you may find shebangs with flags such as `#! /usr/bin/env python -si`.
bca232
+# Normally, pathfix overwrites the entire line, including the flags.
bca232
+# To change interpreter and keep flags from the original shebang line, use -k.
bca232
+# If you want to keep flags and add to them one single literal flag, use option -a.
bca232
+
bca232
+
bca232
 # Undoubtedly you can do this using find and sed or perl, but this is
bca232
 # a nice example of Python code that recurses down a directory tree
bca232
 # and uses regular expressions.  Also note several subtleties like
bca232
@@ -33,16 +39,21 @@ rep = sys.stdout.write
bca232
 new_interpreter = None
bca232
 preserve_timestamps = False
bca232
 create_backup = True
bca232
+keep_flags = False
bca232
+add_flags = b''
bca232
 
bca232
 
bca232
 def main():
bca232
     global new_interpreter
bca232
     global preserve_timestamps
bca232
     global create_backup
bca232
-    usage = ('usage: %s -i /interpreter -p -n file-or-directory ...\n' %
bca232
+    global keep_flags
bca232
+    global add_flags
bca232
+
bca232
+    usage = ('usage: %s -i /interpreter -p -n -k -a file-or-directory ...\n' %
bca232
              sys.argv[0])
bca232
     try:
bca232
-        opts, args = getopt.getopt(sys.argv[1:], 'i:pn')
bca232
+        opts, args = getopt.getopt(sys.argv[1:], 'i:a:kpn')
bca232
     except getopt.error as msg:
bca232
         err(str(msg) + '\n')
bca232
         err(usage)
bca232
@@ -54,6 +65,13 @@ def main():
bca232
             preserve_timestamps = True
bca232
         if o == '-n':
bca232
             create_backup = False
bca232
+        if o == '-k':
bca232
+            keep_flags = True
bca232
+        if o == '-a':
bca232
+            add_flags = a.encode()
bca232
+            if b' ' in add_flags:
bca232
+                err("-a option doesn't support whitespaces")
bca232
+                sys.exit(2)
bca232
     if not new_interpreter or not new_interpreter.startswith(b'/') or \
bca232
            not args:
bca232
         err('-i option or file-or-directory missing\n')
bca232
@@ -70,10 +88,14 @@ def main():
bca232
             if fix(arg): bad = 1
bca232
     sys.exit(bad)
bca232
 
bca232
+
bca232
 ispythonprog = re.compile(r'^[a-zA-Z0-9_]+\.py$')
bca232
+
bca232
+
bca232
 def ispython(name):
bca232
     return bool(ispythonprog.match(name))
bca232
 
bca232
+
bca232
 def recursedown(dirname):
bca232
     dbg('recursedown(%r)\n' % (dirname,))
bca232
     bad = 0
bca232
@@ -96,6 +118,7 @@ def recursedown(dirname):
bca232
         if recursedown(fullname): bad = 1
bca232
     return bad
bca232
 
bca232
+
bca232
 def fix(filename):
bca232
 ##  dbg('fix(%r)\n' % (filename,))
bca232
     try:
bca232
@@ -166,12 +189,43 @@ def fix(filename):
bca232
     # Return success
bca232
     return 0
bca232
 
bca232
+
bca232
+def parse_shebang(shebangline):
bca232
+    shebangline = shebangline.rstrip(b'\n')
bca232
+    start = shebangline.find(b' -')
bca232
+    if start == -1:
bca232
+        return b''
bca232
+    return shebangline[start:]
bca232
+
bca232
+
bca232
+def populate_flags(shebangline):
bca232
+    old_flags = b''
bca232
+    if keep_flags:
bca232
+        old_flags = parse_shebang(shebangline)
bca232
+        if old_flags:
bca232
+            old_flags = old_flags[2:]
bca232
+    if not (old_flags or add_flags):
bca232
+        return b''
bca232
+    # On Linux, the entire string following the interpreter name
bca232
+    # is passed as a single argument to the interpreter.
bca232
+    # e.g. "#! /usr/bin/python3 -W Error -s" runs "/usr/bin/python3 "-W Error -s"
bca232
+    # so shebang should have single '-' where flags are given and
bca232
+    # flag might need argument for that reasons adding new flags is
bca232
+    # between '-' and original flags
bca232
+    # e.g. #! /usr/bin/python3 -sW Error
bca232
+    return b' -' + add_flags + old_flags
bca232
+
bca232
+
bca232
 def fixline(line):
bca232
     if not line.startswith(b'#!'):
bca232
         return line
bca232
+
bca232
     if b"python" not in line:
bca232
         return line
bca232
-    return b'#! ' + new_interpreter + b'\n'
bca232
+
bca232
+    flags = populate_flags(line)
bca232
+    return b'#! ' + new_interpreter + flags + b'\n'
bca232
+
bca232
 
bca232
 if __name__ == '__main__':
bca232
     main()
bca232
-- 
bca232
2.29.2
bca232