{"thread":{"id":"57202","subject":"[PATCH v2 0/3] git-p4: Rationalise command construction","startedAt":"2022-01-06T21:41:01Z","lastAt":"2022-01-06T21:41:10Z","messageCount":4,"participants":["Joel Holdsworth"],"isPatch":true,"patchVersion":2,"patchTotal":3},"messages":[{"id":"445654","messageId":"20220106214035.90725-1-jholdsworth@nvidia.com","threadId":"57202","inReplyTo":null,"subject":"[PATCH v2 0/3] git-p4: Rationalise command construction","fromName":"Joel Holdsworth","fromEmail":"jholdsworth@nvidia.com","sentAt":"2022-01-06T21:40:32Z","receivedAt":"2022-01-06T21:41:01Z","isPatch":true,"sender":{"key":"jholdsworth@nvidia.com","avatar":"https://avatars.githubusercontent.com/u/1449493?v=4"},"body":"This patch-set removes the mixing of commands constructed using strings\nwith commands constructed using python lists. The goal being to simplify\nthe code by standardising on the usage of lists throughout the script.\n\nIt also attempts to make usage of shell execution clearer by changing\nthe code to require the caller to explicitly request execution-in-shell\nif required.\n\nWith the script changed over to using lists every, there is also a patch\nto improve the printing of log messages as command strings rather than\nas stringified python lists\n\nThis version of the patch-set adds a missing signoff, and corrects a\ntypo in a commit message.\n\nJoel Holdsworth (3):\n  git-p4: don't select shell mode using the type of the command argument\n  git-p4: pass command arguments as lists instead of using shell\n  git-p4: don't print shell commands as python lists\n\n git-p4.py | 176 ++++++++++++++++++++++++------------------------------\n 1 file changed, 79 insertions(+), 97 deletions(-)\n\n-- \n2.34.1\n\n"},{"id":"445655","messageId":"20220106214035.90725-2-jholdsworth@nvidia.com","threadId":"57202","inReplyTo":"20220106214035.90725-1-jholdsworth@nvidia.com","subject":"[PATCH v2 1/3] git-p4: don't select shell mode using the type of the command argument","fromName":"Joel Holdsworth","fromEmail":"jholdsworth@nvidia.com","sentAt":"2022-01-06T21:40:33Z","receivedAt":"2022-01-06T21:41:04Z","isPatch":true,"sender":{"key":"jholdsworth@nvidia.com","avatar":"https://avatars.githubusercontent.com/u/1449493?v=4"},"body":"Previously, the script would invoke subprocess functions setting the\nshell argument True if the command argument was a string, setting it\nFalse otherwise.\n\nThis patch replaces this implicit type-driven behaviour with explicit\nshell arguments specified by the caller.\n\nThe apparent motive for the implict behaviour is that the subprocess\nfunctions do not divide command strings into args. Invoking\nsubprocess.call(\"echo hello\") will attempt to execute a program by the\nname \"echo hello\". With subprocess.call(\"echo hello\", shell=True), sh\n-c \"echo hello\" will be executed instead, which will cause the command\nand args to be divided by spaces.\n\nEventually, all usage of shell=True, that is not necessary for some\npurpose beyond parsing command strings, should be removed. For now,\nthis patch makes the usage of shells explicit.\n\nSigned-off-by: Joel Holdsworth <jholdsworth@nvidia.com>\n---\nThis version adds a missing signoff.\n\n git-p4.py | 126 +++++++++++++++++++++++++++---------------------------\n 1 file changed, 63 insertions(+), 63 deletions(-)\n\ndiff --git a/git-p4.py b/git-p4.py\nindex 986595bef0..7ec90388b6 100755\n--- a/git-p4.py\n+++ b/git-p4.py\n@@ -276,12 +276,11 @@ def run_hook_command(cmd, param):\n     return subprocess.call(cli, shell=use_shell)\n \n \n-def write_pipe(c, stdin):\n+def write_pipe(c, stdin, *k, **kw):\n     if verbose:\n         sys.stderr.write('Writing pipe: %s\\n' % str(c))\n \n-    expand = not isinstance(c, list)\n-    p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)\n+    p = subprocess.Popen(c, stdin=subprocess.PIPE, *k, **kw)\n     pipe = p.stdin\n     val = pipe.write(stdin)\n     pipe.close()\n@@ -290,13 +289,13 @@ def write_pipe(c, stdin):\n \n     return val\n \n-def p4_write_pipe(c, stdin):\n+def p4_write_pipe(c, stdin, *k, **kw):\n     real_cmd = p4_build_cmd(c)\n     if bytes is not str and isinstance(stdin, str):\n         stdin = encode_text_stream(stdin)\n-    return write_pipe(real_cmd, stdin)\n+    return write_pipe(real_cmd, stdin, *k, **kw)\n \n-def read_pipe_full(c):\n+def read_pipe_full(c, *k, **kw):\n     \"\"\" Read output from  command. Returns a tuple\n         of the return status, stdout text and stderr\n         text.\n@@ -304,19 +303,19 @@ def read_pipe_full(c):\n     if verbose:\n         sys.stderr.write('Reading pipe: %s\\n' % str(c))\n \n-    expand = not isinstance(c, list)\n-    p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand)\n+    p = subprocess.Popen(\n+        c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, *k, **kw)\n     (out, err) = p.communicate()\n     return (p.returncode, out, decode_text_stream(err))\n \n-def read_pipe(c, ignore_error=False, raw=False):\n+def read_pipe(c, ignore_error=False, raw=False, *k, **kw):\n     \"\"\" Read output from  command. Returns the output text on\n         success. On failure, terminates execution, unless\n         ignore_error is True, when it returns an empty string.\n \n         If raw is True, do not attempt to decode output text.\n     \"\"\"\n-    (retcode, out, err) = read_pipe_full(c)\n+    (retcode, out, err) = read_pipe_full(c, *k, **kw)\n     if retcode != 0:\n         if ignore_error:\n             out = \"\"\n@@ -326,26 +325,25 @@ def read_pipe(c, ignore_error=False, raw=False):\n         out = decode_text_stream(out)\n     return out\n \n-def read_pipe_text(c):\n+def read_pipe_text(c, *k, **kw):\n     \"\"\" Read output from a command with trailing whitespace stripped.\n         On error, returns None.\n     \"\"\"\n-    (retcode, out, err) = read_pipe_full(c)\n+    (retcode, out, err) = read_pipe_full(c, *k, **kw)\n     if retcode != 0:\n         return None\n     else:\n         return decode_text_stream(out).rstrip()\n \n-def p4_read_pipe(c, ignore_error=False, raw=False):\n+def p4_read_pipe(c, ignore_error=False, raw=False, *k, **kw):\n     real_cmd = p4_build_cmd(c)\n-    return read_pipe(real_cmd, ignore_error, raw=raw)\n+    return read_pipe(real_cmd, ignore_error, raw=raw, *k, **kw)\n \n-def read_pipe_lines(c, raw=False):\n+def read_pipe_lines(c, raw=False, *k, **kw):\n     if verbose:\n         sys.stderr.write('Reading pipe: %s\\n' % str(c))\n \n-    expand = not isinstance(c, list)\n-    p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)\n+    p = subprocess.Popen(c, stdout=subprocess.PIPE, *k, **kw)\n     pipe = p.stdout\n     lines = pipe.readlines()\n     if not raw:\n@@ -354,10 +352,10 @@ def read_pipe_lines(c, raw=False):\n         die('Command failed: %s' % str(c))\n     return lines\n \n-def p4_read_pipe_lines(c):\n+def p4_read_pipe_lines(c, *k, **kw):\n     \"\"\"Specifically invoke p4 on the command supplied. \"\"\"\n     real_cmd = p4_build_cmd(c)\n-    return read_pipe_lines(real_cmd)\n+    return read_pipe_lines(real_cmd, *k, **kw)\n \n def p4_has_command(cmd):\n     \"\"\"Ask p4 for help on this command.  If it returns an error, the\n@@ -388,21 +386,19 @@ def p4_has_move_command():\n     # assume it failed because @... was invalid changelist\n     return True\n \n-def system(cmd, ignore_error=False):\n-    expand = not isinstance(cmd, list)\n+def system(cmd, ignore_error=False, *k, **kw):\n     if verbose:\n         sys.stderr.write(\"executing %s\\n\" % str(cmd))\n-    retcode = subprocess.call(cmd, shell=expand)\n+    retcode = subprocess.call(cmd, *k, **kw)\n     if retcode and not ignore_error:\n         raise CalledProcessError(retcode, cmd)\n \n     return retcode\n \n-def p4_system(cmd):\n+def p4_system(cmd, *k, **kw):\n     \"\"\"Specifically invoke p4 as the system command. \"\"\"\n     real_cmd = p4_build_cmd(cmd)\n-    expand = not isinstance(real_cmd, list)\n-    retcode = subprocess.call(real_cmd, shell=expand)\n+    retcode = subprocess.call(real_cmd, *k, **kw)\n     if retcode:\n         raise CalledProcessError(retcode, real_cmd)\n \n@@ -723,14 +719,12 @@ def isModeExecChanged(src_mode, dst_mode):\n     return isModeExec(src_mode) != isModeExec(dst_mode)\n \n def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,\n-        errors_as_exceptions=False):\n+        errors_as_exceptions=False, *k, **kw):\n \n     if not isinstance(cmd, list):\n         cmd = \"-G \" + cmd\n-        expand = True\n     else:\n         cmd = [\"-G\"] + cmd\n-        expand = False\n \n     cmd = p4_build_cmd(cmd)\n     if verbose:\n@@ -751,10 +745,8 @@ def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,\n         stdin_file.flush()\n         stdin_file.seek(0)\n \n-    p4 = subprocess.Popen(cmd,\n-                          shell=expand,\n-                          stdin=stdin_file,\n-                          stdout=subprocess.PIPE)\n+    p4 = subprocess.Popen(\n+        cmd, stdin=stdin_file, stdout=subprocess.PIPE, *k, **kw)\n \n     result = []\n     try:\n@@ -807,8 +799,8 @@ def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,\n \n     return result\n \n-def p4Cmd(cmd):\n-    list = p4CmdList(cmd)\n+def p4Cmd(cmd, *k, **kw):\n+    list = p4CmdList(cmd, *k, **kw)\n     result = {}\n     for entry in list:\n         result.update(entry)\n@@ -857,7 +849,7 @@ def isValidGitDir(path):\n     return git_dir(path) != None\n \n def parseRevision(ref):\n-    return read_pipe(\"git rev-parse %s\" % ref).strip()\n+    return read_pipe(\"git rev-parse %s\" % ref, shell=True).strip()\n \n def branchExists(ref):\n     rev = read_pipe([\"git\", \"rev-parse\", \"-q\", \"--verify\", ref],\n@@ -969,7 +961,7 @@ def p4BranchesInGit(branchesAreInRemotes=True):\n     else:\n         cmdline += \"--branches\"\n \n-    for line in read_pipe_lines(cmdline):\n+    for line in read_pipe_lines(cmdline, shell=True):\n         line = line.strip()\n \n         # only import to p4/\n@@ -1032,7 +1024,7 @@ def createOrUpdateBranchesFromOrigin(localRefPrefix = \"refs/remotes/p4/\", silent\n \n     originPrefix = \"origin/p4/\"\n \n-    for line in read_pipe_lines(\"git rev-parse --symbolic --remotes\"):\n+    for line in read_pipe_lines(\"git rev-parse --symbolic --remotes\", shell=True):\n         line = line.strip()\n         if (not line.startswith(originPrefix)) or line.endswith(\"HEAD\"):\n             continue\n@@ -1070,7 +1062,8 @@ def createOrUpdateBranchesFromOrigin(localRefPrefix = \"refs/remotes/p4/\", silent\n                               remoteHead, ','.join(settings['depot-paths'])))\n \n         if update:\n-            system(\"git update-ref %s %s\" % (remoteHead, originHead))\n+            system(\"git update-ref %s %s\" % (remoteHead, originHead),\n+                shell=True)\n \n def originP4BranchesExist():\n         return gitBranchExists(\"origin\") or gitBranchExists(\"origin/p4\") or gitBranchExists(\"origin/p4/master\")\n@@ -1184,7 +1177,7 @@ def getClientSpec():\n     \"\"\"Look at the p4 client spec, create a View() object that contains\n        all the mappings, and return it.\"\"\"\n \n-    specList = p4CmdList(\"client -o\")\n+    specList = p4CmdList(\"client -o\", shell=True)\n     if len(specList) != 1:\n         die('Output from \"client -o\" is %d lines, expecting 1' %\n             len(specList))\n@@ -1213,7 +1206,7 @@ def getClientSpec():\n def getClientRoot():\n     \"\"\"Grab the client directory.\"\"\"\n \n-    output = p4CmdList(\"client -o\")\n+    output = p4CmdList(\"client -o\", shell=True)\n     if len(output) != 1:\n         die('Output from \"client -o\" is %d lines, expecting 1' % len(output))\n \n@@ -1468,7 +1461,7 @@ def p4UserId(self):\n         if self.myP4UserId:\n             return self.myP4UserId\n \n-        results = p4CmdList(\"user -o\")\n+        results = p4CmdList(\"user -o\", shell=True)\n         for r in results:\n             if 'User' in r:\n                 self.myP4UserId = r['User']\n@@ -1493,7 +1486,7 @@ def getUserMapFromPerforceServer(self):\n         self.users = {}\n         self.emails = {}\n \n-        for output in p4CmdList(\"users\"):\n+        for output in p4CmdList(\"users\", shell=True):\n             if \"User\" not in output:\n                 continue\n             self.users[output[\"User\"]] = output[\"FullName\"] + \" <\" + output[\"Email\"] + \">\"\n@@ -1691,7 +1684,7 @@ def __init__(self):\n             die(\"Large file system not supported for git-p4 submit command. Please remove it from config.\")\n \n     def check(self):\n-        if len(p4CmdList(\"opened ...\")) > 0:\n+        if len(p4CmdList(\"opened ...\", shell=True)) > 0:\n             die(\"You have files opened with perforce! Close them before starting the sync.\")\n \n     def separate_jobs_from_description(self, message):\n@@ -1795,7 +1788,7 @@ def lastP4Changelist(self):\n         # then gets used to patch up the username in the change. If the same\n         # client spec is being used by multiple processes then this might go\n         # wrong.\n-        results = p4CmdList(\"client -o\")        # find the current client\n+        results = p4CmdList(\"client -o\", shell=True)    # find the current client\n         client = None\n         for r in results:\n             if 'Client' in r:\n@@ -1811,7 +1804,7 @@ def lastP4Changelist(self):\n \n     def modifyChangelistUser(self, changelist, newUser):\n         # fixup the user field of a changelist after it has been submitted.\n-        changes = p4CmdList(\"change -o %s\" % changelist)\n+        changes = p4CmdList(\"change -o %s\" % changelist, shell=True)\n         if len(changes) != 1:\n             die(\"Bad output from p4 change modifying %s to user %s\" %\n                 (changelist, newUser))\n@@ -1822,7 +1815,7 @@ def modifyChangelistUser(self, changelist, newUser):\n         # p4 does not understand format version 3 and above\n         input = marshal.dumps(c, 2)\n \n-        result = p4CmdList(\"change -f -i\", stdin=input)\n+        result = p4CmdList(\"change -f -i\", stdin=input, shell=True)\n         for r in result:\n             if 'code' in r:\n                 if r['code'] == 'error':\n@@ -1928,7 +1921,7 @@ def edit_template(self, template_file):\n         if \"P4EDITOR\" in os.environ and (os.environ.get(\"P4EDITOR\") != \"\"):\n             editor = os.environ.get(\"P4EDITOR\")\n         else:\n-            editor = read_pipe(\"git var GIT_EDITOR\").strip()\n+            editor = read_pipe(\"git var GIT_EDITOR\", shell=True).strip()\n         system([\"sh\", \"-c\", ('%s \"$@\"' % editor), editor, template_file])\n \n         # If the file was not saved, prompt to see if this patch should\n@@ -1986,7 +1979,9 @@ def applyCommit(self, id):\n \n         (p4User, gitEmail) = self.p4UserForCommit(id)\n \n-        diff = read_pipe_lines(\"git diff-tree -r %s \\\"%s^\\\" \\\"%s\\\"\" % (self.diffOpts, id, id))\n+        diff = read_pipe_lines(\n+            \"git diff-tree -r %s \\\"%s^\\\" \\\"%s\\\"\" % (self.diffOpts, id, id),\n+            shell=True)\n         filesToAdd = set()\n         filesToChangeType = set()\n         filesToDelete = set()\n@@ -2122,7 +2117,7 @@ def applyCommit(self, id):\n         #\n         # Apply the patch for real, and do add/delete/+x handling.\n         #\n-        system(applyPatchCmd)\n+        system(applyPatchCmd, shell=True)\n \n         for f in filesToChangeType:\n             p4_edit(f, \"-t\", \"auto\")\n@@ -3446,7 +3441,7 @@ def getBranchMapping(self):\n         else:\n             command = \"branches\"\n \n-        for info in p4CmdList(command):\n+        for info in p4CmdList(command, shell=True):\n             details = p4Cmd([\"branch\", \"-o\", info[\"branch\"]])\n             viewIdx = 0\n             while \"View%s\" % viewIdx in details:\n@@ -3537,7 +3532,9 @@ def gitCommitByP4Change(self, ref, change):\n         while True:\n             if self.verbose:\n                 print(\"trying: earliest %s latest %s\" % (earliestCommit, latestCommit))\n-            next = read_pipe(\"git rev-list --bisect %s %s\" % (latestCommit, earliestCommit)).strip()\n+            next = read_pipe(\n+                \"git rev-list --bisect %s %s\" % (latestCommit, earliestCommit),\n+                shell=True).strip()\n             if len(next) == 0:\n                 if self.verbose:\n                     print(\"argh\")\n@@ -3692,7 +3689,7 @@ def sync_origin_only(self):\n             if self.hasOrigin:\n                 if not self.silent:\n                     print('Syncing with origin first, using \"git fetch origin\"')\n-                system(\"git fetch origin\")\n+                system(\"git fetch origin\", shell=True)\n \n     def importHeadRevision(self, revision):\n         print(\"Doing initial import of %s from revision %s into %s\" % (' '.join(self.depotPaths), revision, self.branch))\n@@ -3859,8 +3856,8 @@ def run(self, args):\n         if len(self.branch) == 0:\n             self.branch = self.refPrefix + \"master\"\n             if gitBranchExists(\"refs/heads/p4\") and self.importIntoRemotes:\n-                system(\"git update-ref %s refs/heads/p4\" % self.branch)\n-                system(\"git branch -D p4\")\n+                system(\"git update-ref %s refs/heads/p4\" % self.branch, shell=True)\n+                system(\"git branch -D p4\", shell=True)\n \n         # accept either the command-line option, or the configuration variable\n         if self.useClientSpec:\n@@ -4063,7 +4060,7 @@ def run(self, args):\n         # Cleanup temporary branches created during import\n         if self.tempBranches != []:\n             for branch in self.tempBranches:\n-                read_pipe(\"git update-ref -d %s\" % branch)\n+                read_pipe(\"git update-ref -d %s\" % branch, shell=True)\n             os.rmdir(os.path.join(os.environ.get(\"GIT_DIR\", \".git\"), self.tempBranchLocation))\n \n         # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow\n@@ -4095,7 +4092,7 @@ def run(self, args):\n     def rebase(self):\n         if os.system(\"git update-index --refresh\") != 0:\n             die(\"Some files in your working directory are modified and different than what is in your index. You can use git update-index <filename> to bring the index up to date or stash away all your changes with git stash.\");\n-        if len(read_pipe(\"git diff-index HEAD --\")) > 0:\n+        if len(read_pipe(\"git diff-index HEAD --\", shell=True)) > 0:\n             die(\"You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.\");\n \n         [upstream, settings] = findUpstreamBranchPoint()\n@@ -4106,9 +4103,10 @@ def rebase(self):\n         upstream = re.sub(\"~[0-9]+$\", \"\", upstream)\n \n         print(\"Rebasing the current branch onto %s\" % upstream)\n-        oldHead = read_pipe(\"git rev-parse HEAD\").strip()\n-        system(\"git rebase %s\" % upstream)\n-        system(\"git diff-tree --stat --summary -M %s HEAD --\" % oldHead)\n+        oldHead = read_pipe(\"git rev-parse HEAD\", shell=True).strip()\n+        system(\"git rebase %s\" % upstream, shell=True)\n+        system(\"git diff-tree --stat --summary -M %s HEAD --\" % oldHead,\n+            shell=True)\n         return True\n \n class P4Clone(P4Sync):\n@@ -4185,7 +4183,7 @@ def run(self, args):\n \n         # auto-set this variable if invoked with --use-client-spec\n         if self.useClientSpec_from_options:\n-            system(\"git config --bool git-p4.useclientspec true\")\n+            system(\"git config --bool git-p4.useclientspec true\", shell=True)\n \n         return True\n \n@@ -4319,7 +4317,7 @@ def run(self, args):\n         cmdline = \"git rev-parse --symbolic \"\n         cmdline += \" --remotes\"\n \n-        for line in read_pipe_lines(cmdline):\n+        for line in read_pipe_lines(cmdline, shell=True):\n             line = line.strip()\n \n             if not line.startswith('p4/') or line == \"p4/HEAD\":\n@@ -4404,9 +4402,11 @@ def main():\n             cmd.gitdir = os.path.abspath(\".git\")\n             if not isValidGitDir(cmd.gitdir):\n                 # \"rev-parse --git-dir\" without arguments will try $PWD/.git\n-                cmd.gitdir = read_pipe(\"git rev-parse --git-dir\").strip()\n+                cmd.gitdir = read_pipe(\n+                    \"git rev-parse --git-dir\", shell=True).strip()\n                 if os.path.exists(cmd.gitdir):\n-                    cdup = read_pipe(\"git rev-parse --show-cdup\").strip()\n+                    cdup = read_pipe(\n+                        \"git rev-parse --show-cdup\", shell=True).strip()\n                     if len(cdup) > 0:\n                         chdir(cdup);\n \n-- \n2.34.1\n\n"},{"id":"445656","messageId":"20220106214035.90725-3-jholdsworth@nvidia.com","threadId":"57202","inReplyTo":"20220106214035.90725-1-jholdsworth@nvidia.com","subject":"[PATCH v2 2/3] git-p4: pass command arguments as lists instead of using shell","fromName":"Joel Holdsworth","fromEmail":"jholdsworth@nvidia.com","sentAt":"2022-01-06T21:40:34Z","receivedAt":"2022-01-06T21:41:05Z","isPatch":true,"sender":{"key":"jholdsworth@nvidia.com","avatar":"https://avatars.githubusercontent.com/u/1449493?v=4"},"body":"In the majority of the subprocess calls where shell=True was used, it\nwas only needed to parse command arguments by spaces. In each of these\ncases, the commands are now being passed in as lists instead of strings.\n\nThis change aids the comprehensibility of the code. Constucting commands\nand arguments using strings risks bugs from unsanitized inputs, and the\nattendant complexity of properly quoting and escaping command arguments.\n\nSigned-off-by: Joel Holdsworth <jholdsworth@nvidia.com>\n---\n git-p4.py | 105 ++++++++++++++++++++++--------------------------------\n 1 file changed, 43 insertions(+), 62 deletions(-)\n\ndiff --git a/git-p4.py b/git-p4.py\nindex 7ec90388b6..492eb5aa23 100755\n--- a/git-p4.py\n+++ b/git-p4.py\n@@ -96,10 +96,7 @@ def p4_build_cmd(cmd):\n         # Provide a way to not pass this option by setting git-p4.retries to 0\n         real_cmd += [\"-r\", str(retries)]\n \n-    if not isinstance(cmd, list):\n-        real_cmd = ' '.join(real_cmd) + ' ' + cmd\n-    else:\n-        real_cmd += cmd\n+    real_cmd += cmd\n \n     # now check that we can actually talk to the server\n     global p4_access_checked\n@@ -721,12 +718,7 @@ def isModeExecChanged(src_mode, dst_mode):\n def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,\n         errors_as_exceptions=False, *k, **kw):\n \n-    if not isinstance(cmd, list):\n-        cmd = \"-G \" + cmd\n-    else:\n-        cmd = [\"-G\"] + cmd\n-\n-    cmd = p4_build_cmd(cmd)\n+    cmd = p4_build_cmd([\"-G\"] + cmd)\n     if verbose:\n         sys.stderr.write(\"Opening pipe: %s\\n\" % str(cmd))\n \n@@ -849,7 +841,7 @@ def isValidGitDir(path):\n     return git_dir(path) != None\n \n def parseRevision(ref):\n-    return read_pipe(\"git rev-parse %s\" % ref, shell=True).strip()\n+    return read_pipe([\"git\", \"rev-parse\", ref]).strip()\n \n def branchExists(ref):\n     rev = read_pipe([\"git\", \"rev-parse\", \"-q\", \"--verify\", ref],\n@@ -955,13 +947,13 @@ def p4BranchesInGit(branchesAreInRemotes=True):\n \n     branches = {}\n \n-    cmdline = \"git rev-parse --symbolic \"\n+    cmdline = [\"git\", \"rev-parse\", \"--symbolic\"]\n     if branchesAreInRemotes:\n-        cmdline += \"--remotes\"\n+        cmdline.append(\"--remotes\")\n     else:\n-        cmdline += \"--branches\"\n+        cmdline.append(\"--branches\")\n \n-    for line in read_pipe_lines(cmdline, shell=True):\n+    for line in read_pipe_lines(cmdline):\n         line = line.strip()\n \n         # only import to p4/\n@@ -1024,7 +1016,7 @@ def createOrUpdateBranchesFromOrigin(localRefPrefix = \"refs/remotes/p4/\", silent\n \n     originPrefix = \"origin/p4/\"\n \n-    for line in read_pipe_lines(\"git rev-parse --symbolic --remotes\", shell=True):\n+    for line in read_pipe_lines([\"git\", \"rev-parse\", \"--symbolic\", \"--remotes\"]):\n         line = line.strip()\n         if (not line.startswith(originPrefix)) or line.endswith(\"HEAD\"):\n             continue\n@@ -1062,8 +1054,7 @@ def createOrUpdateBranchesFromOrigin(localRefPrefix = \"refs/remotes/p4/\", silent\n                               remoteHead, ','.join(settings['depot-paths'])))\n \n         if update:\n-            system(\"git update-ref %s %s\" % (remoteHead, originHead),\n-                shell=True)\n+            system([\"git\", \"update-ref\", remoteHead, originHead])\n \n def originP4BranchesExist():\n         return gitBranchExists(\"origin\") or gitBranchExists(\"origin/p4\") or gitBranchExists(\"origin/p4/master\")\n@@ -1177,7 +1168,7 @@ def getClientSpec():\n     \"\"\"Look at the p4 client spec, create a View() object that contains\n        all the mappings, and return it.\"\"\"\n \n-    specList = p4CmdList(\"client -o\", shell=True)\n+    specList = p4CmdList([\"client\", \"-o\"])\n     if len(specList) != 1:\n         die('Output from \"client -o\" is %d lines, expecting 1' %\n             len(specList))\n@@ -1206,7 +1197,7 @@ def getClientSpec():\n def getClientRoot():\n     \"\"\"Grab the client directory.\"\"\"\n \n-    output = p4CmdList(\"client -o\", shell=True)\n+    output = p4CmdList([\"client\", \"-o\"])\n     if len(output) != 1:\n         die('Output from \"client -o\" is %d lines, expecting 1' % len(output))\n \n@@ -1461,7 +1452,7 @@ def p4UserId(self):\n         if self.myP4UserId:\n             return self.myP4UserId\n \n-        results = p4CmdList(\"user -o\", shell=True)\n+        results = p4CmdList([\"user\", \"-o\"])\n         for r in results:\n             if 'User' in r:\n                 self.myP4UserId = r['User']\n@@ -1486,7 +1477,7 @@ def getUserMapFromPerforceServer(self):\n         self.users = {}\n         self.emails = {}\n \n-        for output in p4CmdList(\"users\", shell=True):\n+        for output in p4CmdList([\"users\"]):\n             if \"User\" not in output:\n                 continue\n             self.users[output[\"User\"]] = output[\"FullName\"] + \" <\" + output[\"Email\"] + \">\"\n@@ -1684,7 +1675,7 @@ def __init__(self):\n             die(\"Large file system not supported for git-p4 submit command. Please remove it from config.\")\n \n     def check(self):\n-        if len(p4CmdList(\"opened ...\", shell=True)) > 0:\n+        if len(p4CmdList([\"opened\", \"...\"])) > 0:\n             die(\"You have files opened with perforce! Close them before starting the sync.\")\n \n     def separate_jobs_from_description(self, message):\n@@ -1788,7 +1779,7 @@ def lastP4Changelist(self):\n         # then gets used to patch up the username in the change. If the same\n         # client spec is being used by multiple processes then this might go\n         # wrong.\n-        results = p4CmdList(\"client -o\", shell=True)    # find the current client\n+        results = p4CmdList([\"client\", \"-o\"])        # find the current client\n         client = None\n         for r in results:\n             if 'Client' in r:\n@@ -1804,7 +1795,7 @@ def lastP4Changelist(self):\n \n     def modifyChangelistUser(self, changelist, newUser):\n         # fixup the user field of a changelist after it has been submitted.\n-        changes = p4CmdList(\"change -o %s\" % changelist, shell=True)\n+        changes = p4CmdList([\"change\", \"-o\", changelist])\n         if len(changes) != 1:\n             die(\"Bad output from p4 change modifying %s to user %s\" %\n                 (changelist, newUser))\n@@ -1815,7 +1806,7 @@ def modifyChangelistUser(self, changelist, newUser):\n         # p4 does not understand format version 3 and above\n         input = marshal.dumps(c, 2)\n \n-        result = p4CmdList(\"change -f -i\", stdin=input, shell=True)\n+        result = p4CmdList([\"change\", \"-f\", \"-i\"], stdin=input)\n         for r in result:\n             if 'code' in r:\n                 if r['code'] == 'error':\n@@ -1921,7 +1912,7 @@ def edit_template(self, template_file):\n         if \"P4EDITOR\" in os.environ and (os.environ.get(\"P4EDITOR\") != \"\"):\n             editor = os.environ.get(\"P4EDITOR\")\n         else:\n-            editor = read_pipe(\"git var GIT_EDITOR\", shell=True).strip()\n+            editor = read_pipe([\"git\", \"var\", \"GIT_EDITOR\"]).strip()\n         system([\"sh\", \"-c\", ('%s \"$@\"' % editor), editor, template_file])\n \n         # If the file was not saved, prompt to see if this patch should\n@@ -1980,8 +1971,7 @@ def applyCommit(self, id):\n         (p4User, gitEmail) = self.p4UserForCommit(id)\n \n         diff = read_pipe_lines(\n-            \"git diff-tree -r %s \\\"%s^\\\" \\\"%s\\\"\" % (self.diffOpts, id, id),\n-            shell=True)\n+            [\"git\", \"diff-tree\", \"-r\"] + self.diffOpts + [\"{}^\".format(id), id])\n         filesToAdd = set()\n         filesToChangeType = set()\n         filesToDelete = set()\n@@ -2467,17 +2457,17 @@ def run(self, args):\n         #\n         if self.detectRenames:\n             # command-line -M arg\n-            self.diffOpts = \"-M\"\n+            self.diffOpts = [\"-M\"]\n         else:\n             # If not explicitly set check the config variable\n             detectRenames = gitConfig(\"git-p4.detectRenames\")\n \n             if detectRenames.lower() == \"false\" or detectRenames == \"\":\n-                self.diffOpts = \"\"\n+                self.diffOpts = []\n             elif detectRenames.lower() == \"true\":\n-                self.diffOpts = \"-M\"\n+                self.diffOpts = [\"-M\"]\n             else:\n-                self.diffOpts = \"-M%s\" % detectRenames\n+                self.diffOpts = [\"-M{}\".format(detectRenames)]\n \n         # no command-line arg for -C or --find-copies-harder, just\n         # config variables\n@@ -2485,12 +2475,12 @@ def run(self, args):\n         if detectCopies.lower() == \"false\" or detectCopies == \"\":\n             pass\n         elif detectCopies.lower() == \"true\":\n-            self.diffOpts += \" -C\"\n+            self.diffOpts.append(\"-C\")\n         else:\n-            self.diffOpts += \" -C%s\" % detectCopies\n+            self.diffOpts.append(\"-C{}\".format(detectCopies))\n \n         if gitConfigBool(\"git-p4.detectCopiesHarder\"):\n-            self.diffOpts += \" --find-copies-harder\"\n+            self.diffOpts.append(\"--find-copies-harder\")\n \n         num_shelves = len(self.update_shelve)\n         if num_shelves > 0 and num_shelves != len(commits):\n@@ -3436,12 +3426,9 @@ def getBranchMapping(self):\n         lostAndFoundBranches = set()\n \n         user = gitConfig(\"git-p4.branchUser\")\n-        if len(user) > 0:\n-            command = \"branches -u %s\" % user\n-        else:\n-            command = \"branches\"\n \n-        for info in p4CmdList(command, shell=True):\n+        for info in p4CmdList(\n+            [\"branches\"] + ([\"-u\", user] if len(user) > 0 else [])):\n             details = p4Cmd([\"branch\", \"-o\", info[\"branch\"]])\n             viewIdx = 0\n             while \"View%s\" % viewIdx in details:\n@@ -3532,9 +3519,8 @@ def gitCommitByP4Change(self, ref, change):\n         while True:\n             if self.verbose:\n                 print(\"trying: earliest %s latest %s\" % (earliestCommit, latestCommit))\n-            next = read_pipe(\n-                \"git rev-list --bisect %s %s\" % (latestCommit, earliestCommit),\n-                shell=True).strip()\n+            next = read_pipe([\"git\", \"rev-list\", \"--bisect\",\n+                latestCommit, earliestCommit]).strip()\n             if len(next) == 0:\n                 if self.verbose:\n                     print(\"argh\")\n@@ -3689,7 +3675,7 @@ def sync_origin_only(self):\n             if self.hasOrigin:\n                 if not self.silent:\n                     print('Syncing with origin first, using \"git fetch origin\"')\n-                system(\"git fetch origin\", shell=True)\n+                system([\"git\", \"fetch\", \"origin\"])\n \n     def importHeadRevision(self, revision):\n         print(\"Doing initial import of %s from revision %s into %s\" % (' '.join(self.depotPaths), revision, self.branch))\n@@ -3856,8 +3842,8 @@ def run(self, args):\n         if len(self.branch) == 0:\n             self.branch = self.refPrefix + \"master\"\n             if gitBranchExists(\"refs/heads/p4\") and self.importIntoRemotes:\n-                system(\"git update-ref %s refs/heads/p4\" % self.branch, shell=True)\n-                system(\"git branch -D p4\", shell=True)\n+                system([\"git\", \"update-ref\", self.branch, \"refs/heads/p4\"])\n+                system([\"git\", \"branch\", \"-D\", \"p4\"])\n \n         # accept either the command-line option, or the configuration variable\n         if self.useClientSpec:\n@@ -4060,7 +4046,7 @@ def run(self, args):\n         # Cleanup temporary branches created during import\n         if self.tempBranches != []:\n             for branch in self.tempBranches:\n-                read_pipe(\"git update-ref -d %s\" % branch, shell=True)\n+                read_pipe([\"git\", \"update-ref\", \"-d\", branch])\n             os.rmdir(os.path.join(os.environ.get(\"GIT_DIR\", \".git\"), self.tempBranchLocation))\n \n         # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow\n@@ -4092,7 +4078,7 @@ def run(self, args):\n     def rebase(self):\n         if os.system(\"git update-index --refresh\") != 0:\n             die(\"Some files in your working directory are modified and different than what is in your index. You can use git update-index <filename> to bring the index up to date or stash away all your changes with git stash.\");\n-        if len(read_pipe(\"git diff-index HEAD --\", shell=True)) > 0:\n+        if len(read_pipe([\"git\", \"diff-index\", \"HEAD\", \"--\"])) > 0:\n             die(\"You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.\");\n \n         [upstream, settings] = findUpstreamBranchPoint()\n@@ -4103,10 +4089,10 @@ def rebase(self):\n         upstream = re.sub(\"~[0-9]+$\", \"\", upstream)\n \n         print(\"Rebasing the current branch onto %s\" % upstream)\n-        oldHead = read_pipe(\"git rev-parse HEAD\", shell=True).strip()\n-        system(\"git rebase %s\" % upstream, shell=True)\n-        system(\"git diff-tree --stat --summary -M %s HEAD --\" % oldHead,\n-            shell=True)\n+        oldHead = read_pipe([\"git\", \"rev-parse\", \"HEAD\"]).strip()\n+        system([\"git\", \"rebase\", upstream])\n+        system([\"git\", \"diff-tree\", \"--stat\", \"--summary\", \"-M\", oldHead,\n+            \"HEAD\", \"--\"])\n         return True\n \n class P4Clone(P4Sync):\n@@ -4183,7 +4169,7 @@ def run(self, args):\n \n         # auto-set this variable if invoked with --use-client-spec\n         if self.useClientSpec_from_options:\n-            system(\"git config --bool git-p4.useclientspec true\", shell=True)\n+            system([\"git\", \"config\", \"--bool\", \"git-p4.useclientspec\", \"true\"])\n \n         return True\n \n@@ -4314,10 +4300,7 @@ def run(self, args):\n         if originP4BranchesExist():\n             createOrUpdateBranchesFromOrigin()\n \n-        cmdline = \"git rev-parse --symbolic \"\n-        cmdline += \" --remotes\"\n-\n-        for line in read_pipe_lines(cmdline, shell=True):\n+        for line in read_pipe_lines([\"git\", \"rev-parse\", \"--symbolic\", \"--remotes\"]):\n             line = line.strip()\n \n             if not line.startswith('p4/') or line == \"p4/HEAD\":\n@@ -4402,11 +4385,9 @@ def main():\n             cmd.gitdir = os.path.abspath(\".git\")\n             if not isValidGitDir(cmd.gitdir):\n                 # \"rev-parse --git-dir\" without arguments will try $PWD/.git\n-                cmd.gitdir = read_pipe(\n-                    \"git rev-parse --git-dir\", shell=True).strip()\n+                cmd.gitdir = read_pipe([\"git\", \"rev-parse\", \"--git-dir\"]).strip()\n                 if os.path.exists(cmd.gitdir):\n-                    cdup = read_pipe(\n-                        \"git rev-parse --show-cdup\", shell=True).strip()\n+                    cdup = read_pipe([\"git\", \"rev-parse\", \"--show-cdup\"]).strip()\n                     if len(cdup) > 0:\n                         chdir(cdup);\n \n-- \n2.34.1\n\n"},{"id":"445657","messageId":"20220106214035.90725-4-jholdsworth@nvidia.com","threadId":"57202","inReplyTo":"20220106214035.90725-1-jholdsworth@nvidia.com","subject":"[PATCH v2 3/3] git-p4: don't print shell commands as python lists","fromName":"Joel Holdsworth","fromEmail":"jholdsworth@nvidia.com","sentAt":"2022-01-06T21:40:35Z","receivedAt":"2022-01-06T21:41:10Z","isPatch":true,"sender":{"key":"jholdsworth@nvidia.com","avatar":"https://avatars.githubusercontent.com/u/1449493?v=4"},"body":"Previously the git-p4 script would log commands as stringified\nrepresentations of the command parameter, leading to output such as\nthis:\n\nReading pipe: ['git', 'config', '--bool', 'git-p4.useclientspec']\n\nNow that all commands are list objects, this patch instead joins the\nelements of the list into a single string so the output now looks more\nreadable:\n\nReading pipe: git config --bool git-p4.useclientspec\n\nSigned-off-by: Joel Holdsworth <jholdsworth@nvidia.com>\n---\nThis corrects a typo in the commit message.\n\n git-p4.py | 17 +++++++++--------\n 1 file changed, 9 insertions(+), 8 deletions(-)\n\ndiff --git a/git-p4.py b/git-p4.py\nindex 492eb5aa23..465ed16b25 100755\n--- a/git-p4.py\n+++ b/git-p4.py\n@@ -275,14 +275,14 @@ def run_hook_command(cmd, param):\n \n def write_pipe(c, stdin, *k, **kw):\n     if verbose:\n-        sys.stderr.write('Writing pipe: %s\\n' % str(c))\n+        sys.stderr.write('Writing pipe: {}\\n'.format(' '.join(c)))\n \n     p = subprocess.Popen(c, stdin=subprocess.PIPE, *k, **kw)\n     pipe = p.stdin\n     val = pipe.write(stdin)\n     pipe.close()\n     if p.wait():\n-        die('Command failed: %s' % str(c))\n+        die('Command failed: {}'.format(' '.join(c)))\n \n     return val\n \n@@ -298,7 +298,7 @@ def read_pipe_full(c, *k, **kw):\n         text.\n     \"\"\"\n     if verbose:\n-        sys.stderr.write('Reading pipe: %s\\n' % str(c))\n+        sys.stderr.write('Reading pipe: {}\\n'.format(' '.join(c)))\n \n     p = subprocess.Popen(\n         c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, *k, **kw)\n@@ -317,7 +317,7 @@ def read_pipe(c, ignore_error=False, raw=False, *k, **kw):\n         if ignore_error:\n             out = \"\"\n         else:\n-            die('Command failed: %s\\nError: %s' % (str(c), err))\n+            die('Command failed: {}\\nError: {}'.format(' '.join(c), err))\n     if not raw:\n         out = decode_text_stream(out)\n     return out\n@@ -338,7 +338,7 @@ def p4_read_pipe(c, ignore_error=False, raw=False, *k, **kw):\n \n def read_pipe_lines(c, raw=False, *k, **kw):\n     if verbose:\n-        sys.stderr.write('Reading pipe: %s\\n' % str(c))\n+        sys.stderr.write('Reading pipe: {}\\n'.format(' '.join(c)))\n \n     p = subprocess.Popen(c, stdout=subprocess.PIPE, *k, **kw)\n     pipe = p.stdout\n@@ -346,7 +346,7 @@ def read_pipe_lines(c, raw=False, *k, **kw):\n     if not raw:\n         lines = [decode_text_stream(line) for line in lines]\n     if pipe.close() or p.wait():\n-        die('Command failed: %s' % str(c))\n+        die('Command failed: {}'.format(' '.join(c)))\n     return lines\n \n def p4_read_pipe_lines(c, *k, **kw):\n@@ -385,7 +385,8 @@ def p4_has_move_command():\n \n def system(cmd, ignore_error=False, *k, **kw):\n     if verbose:\n-        sys.stderr.write(\"executing %s\\n\" % str(cmd))\n+        sys.stderr.write(\"executing {}\\n\".format(\n+            ' '.join(cmd) if isinstance(cmd, list) else cmd))\n     retcode = subprocess.call(cmd, *k, **kw)\n     if retcode and not ignore_error:\n         raise CalledProcessError(retcode, cmd)\n@@ -720,7 +721,7 @@ def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,\n \n     cmd = p4_build_cmd([\"-G\"] + cmd)\n     if verbose:\n-        sys.stderr.write(\"Opening pipe: %s\\n\" % str(cmd))\n+        sys.stderr.write(\"Opening pipe: {}\\n\".format(' '.join(cmd)))\n \n     # Use a temporary file to avoid deadlocks without\n     # subprocess.communicate(), which would put another copy\n-- \n2.34.1\n\n"}]}