Skip to contentSkip to conversation

Clean up subprocess calling

PATCH In review Karl Hasselström 2 participants 14 messages Jun 15, 2016

lore
Share & tools
lore
#0 lore raw

cover Clean up subprocess calling

We had nearly ten separate functions implementing about five different ways of calling a subprocess. This series cleans it up. The aggregate diffstat looks scary, but that's mostly because these functions were called in a bajillion different places.

If you choose to pull from my repository (which I highly recommend!), note that this series is built on top of the misc fixes, so you get those as well.

The following changes since commit 216a1524c4acbd9952ffaeec054e30cf14dde5fc:
Karl Hasselström (1):
Compile regexp just once

are available in the git repository at:

git://repo.or.cz/stgit/kha.git run

Karl Hasselström (4):
Refactor output handling to break circular dependency Refactor subprocess creation
Assert that the argument to Run is a sequence of strings Add optional logging of subprocess execution

 stgit/basedir.py             |   13 +-
 stgit/commands/applied.py    |    1 +
 stgit/commands/assimilate.py |    1 +
 stgit/commands/branch.py     |    1 +
 stgit/commands/clean.py      |    1 +
 stgit/commands/commit.py     |    1 +
 stgit/commands/common.py     |    1 +
 stgit/commands/delete.py     |    1 +
 stgit/commands/diff.py       |    1 +
 stgit/commands/export.py     |   10 +-
 stgit/commands/files.py      |    1 +
 stgit/commands/fold.py       |    1 +
 stgit/commands/hide.py       |    1 +
 stgit/commands/id.py         |    1 +
 stgit/commands/imprt.py      |    1 +
 stgit/commands/log.py        |    1 +
 stgit/commands/mail.py       |    1 +
 stgit/commands/patches.py    |    1 +
 stgit/commands/pick.py       |    1 +
 stgit/commands/pull.py       |    1 +
 stgit/commands/push.py       |    1 +
 stgit/commands/refresh.py    |    1 +
 stgit/commands/rename.py     |    1 +
 stgit/commands/series.py     |    1 +
 stgit/commands/sync.py       |    1 +
 stgit/commands/top.py        |    1 +
 stgit/commands/unapplied.py  |    1 +
 stgit/commands/uncommit.py   |    1 +
 stgit/commands/unhide.py     |    1 +
 stgit/config.py              |   56 ++-----
 stgit/git.py                 |  331 +++++++++++++++++-------------------------
 stgit/gitmergeonefile.py     |   21 +--
 stgit/main.py                |    2 +-
 stgit/out.py                 |  100 +++++++++++++
 stgit/run.py                 |  141 ++++++++++++++++++
 stgit/stack.py               |    1 +
 stgit/utils.py               |   81 +----------
 37 files changed, 436 insertions(+), 347 deletions(-)
 create mode 100644 stgit/out.py
 create mode 100644 stgit/run.py
Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#1 lore raw

PATCH 1/4 Refactor output handling to break circular dependency

I ran into problems when trying to use the fancy output handling in a new module that was (recursively) imported by stgit.util -- I couldn't use the out object because it wasn't defined yet.

Break out the output handler to its own module to break the circular dependency.

---

 stgit/commands/applied.py    |    1 
 stgit/commands/assimilate.py |    1 
 stgit/commands/branch.py     |    1 
 stgit/commands/clean.py      |    1 
 stgit/commands/commit.py     |    1 
 stgit/commands/common.py     |    1 
 stgit/commands/delete.py     |    1 
 stgit/commands/diff.py       |    1 
 stgit/commands/export.py     |    1 
 stgit/commands/files.py      |    1 
 stgit/commands/fold.py       |    1 
 stgit/commands/hide.py       |    1 
 stgit/commands/id.py         |    1 
 stgit/commands/imprt.py      |    1 
 stgit/commands/log.py        |    1 
 stgit/commands/mail.py       |    1 
 stgit/commands/patches.py    |    1 
 stgit/commands/pick.py       |    1 
 stgit/commands/pull.py       |    1 
 stgit/commands/push.py       |    1 
 stgit/commands/refresh.py    |    1 
 stgit/commands/rename.py     |    1 
 stgit/commands/series.py     |    1 
 stgit/commands/sync.py       |    1 
 stgit/commands/top.py        |    1 
 stgit/commands/unapplied.py  |    1 
 stgit/commands/uncommit.py   |    1 
 stgit/commands/unhide.py     |    1 
 stgit/git.py                 |    1 
 stgit/gitmergeonefile.py     |    3 +
 stgit/main.py                |    2 -
 stgit/out.py                 |  100 ++++++++++++++++++++++++++++++++++++++++++
 stgit/stack.py               |    1 
 stgit/utils.py               |   81 ----------------------------------
 34 files changed, 134 insertions(+), 82 deletions(-)
stgit/commands/applied.py +1 -0
index 0925de0..b9bb716 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/assimilate.py +1 -0
index 5134e34..c5f4340 100644
@@ -22,6 +22,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 help = 'StGIT-ify any GIT commits made on top of your StGIT stack'
stgit/commands/branch.py +1 -0
index 75a9046..2d491d5 100644
@@ -23,6 +23,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git, basedir
 
 
stgit/commands/clean.py +1 -0
index 7b57526..2e3b202 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/commit.py +1 -0
index 2b8d7ce..0b76c56 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 help = 'permanently store the applied patches into stack base'
stgit/commands/common.py +1 -0
index dddee85..f3fa89d 100644
@@ -22,6 +22,7 @@ import sys, os, os.path, re
 from optparse import OptionParser, make_option
 
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git, basedir
 from stgit.config import config, file_extensions
 
stgit/commands/delete.py +1 -0
index a9e2744..2121015 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/diff.py +1 -0
index f8b19f8..aeca4ab 100644
@@ -22,6 +22,7 @@ from pydoc import pager
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/export.py +1 -0
index 8424f9d..5ca07d3 100644
@@ -23,6 +23,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git, templates
 
 
stgit/commands/files.py +1 -0
index 659a82b..1a10023 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/fold.py +1 -0
index 297dfbf..d97185e 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/hide.py +1 -0
index 39cbd67..de19c19 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/id.py +1 -0
index 8c717e8..f72d2f3 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/imprt.py +1 -0
index 98fe708..57bf2c8 100644
@@ -23,6 +23,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/log.py +1 -0
index ebd8cab..4d6b022 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 from pydoc import pager
 from stgit.commands.common import *
 from stgit import stack, git
+from stgit.out import *
 
 help = 'display the patch changelog'
 usage = """%prog [options] [patch]
stgit/commands/mail.py +1 -0
index 71a6e4e..6202fc5 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git, version, templates
 from stgit.config import config
 
stgit/commands/patches.py +1 -0
index 23b3aa7..b3defb6 100644
@@ -21,6 +21,7 @@ from pydoc import pager
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/pick.py +1 -0
index 27fdf9c..1c3ef11 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 from stgit.stack import Series
 
stgit/commands/pull.py +1 -0
index fe3b67d..ad485a5 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit.config import GitConfigException
 from stgit import stack, git
 
stgit/commands/push.py +1 -0
index 17b32f6..53cdb8f 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/refresh.py +1 -0
index 8277388..218075b 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 from stgit.config import config
 
stgit/commands/rename.py +1 -0
index d6c53be..2830e72 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/series.py +1 -0
index 9e0b0ff..00a3372 100644
@@ -22,6 +22,7 @@ from optparse import OptionParser, make_option
 import stgit.commands.common
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/sync.py +1 -0
index 5e33324..580b5bd 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 import stgit.commands.common
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/top.py +1 -0
index 7cc92ca..1a9267a 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/unapplied.py +1 -0
index 0d330a1..c6408a3 100644
@@ -21,6 +21,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/commands/uncommit.py +1 -0
index f611d29..e3bf0d8 100644
@@ -22,6 +22,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 help = 'turn regular GIT commits into StGIT patches'
stgit/commands/unhide.py +1 -0
index b6a2297..0a1dcaf 100644
@@ -20,6 +20,7 @@ from optparse import OptionParser, make_option
 
 from stgit.commands.common import *
 from stgit.utils import *
+from stgit.out import *
 from stgit import stack, git
 
 
stgit/git.py +1 -0
index 14b4c81..827bd61 100644
@@ -23,6 +23,7 @@ from shutil import copyfile
 
 from stgit import basedir
 from stgit.utils import *
+from stgit.out import *
 from stgit.config import config
 from sets import Set
 
stgit/gitmergeonefile.py +2 -1
index 5e51b8a..e76f9b1 100644
@@ -21,7 +21,8 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 import sys, os
 from stgit import basedir
 from stgit.config import config, file_extensions, ConfigOption
-from stgit.utils import append_string, out
+from stgit.utils import append_string
+from stgit.out import *
 
 
 class GitMergeException(Exception):
stgit/main.py +1 -1
index 2390110..5b9d7c4 100644
@@ -22,7 +22,7 @@ import sys, os
 from optparse import OptionParser
 
 import stgit.commands
-from stgit.utils import out
+from stgit.out import *
 
 #
 # The commands map
stgit/out.py new file +100 -0

100 lines not on this page · raw message

stgit/stack.py +1 -0
index 1ab10c5..12c5091 100644
@@ -21,6 +21,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 import sys, os, re
 
 from stgit.utils import *
+from stgit.out import *
 from stgit import git, basedir, templates
 from stgit.config import config
 from shutil import copyfile
stgit/utils.py +1 -80

93 lines not on this page · raw message

#2 lore raw

PATCH 2/4 Refactor subprocess creation

In reply to Karl Hasselström

Instead of having a gazillion different little functions that wrap os.spawnvp and popen2.Popen3, make a single wrapper that's flexible enough to cater to everyone. Apart from making the code cleaner and easier to read, this has the added benefit of making it possible to add little things such as extra safety checks and logging.

Ideally, I'd have liked this wrapper to wrap subprocess.Popen, but that's only available in Python 2.4 and up, so we'll have to make do with os.spawnvp and popen2.Popen3 for now, even though they suck.

---

 stgit/basedir.py         |   13 +-
 stgit/commands/export.py |    9 -
 stgit/config.py          |   56 ++------
 stgit/git.py             |  330 ++++++++++++++++++----------------------------
 stgit/gitmergeonefile.py |   18 +--
 stgit/run.py             |  111 +++++++++++++++
 6 files changed, 272 insertions(+), 265 deletions(-)
stgit/basedir.py +5 -8
index 81f2b40..30f45f9 100644
@@ -19,13 +19,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 """
 
 import os
-
-def __output(cmd):
-    f = os.popen(cmd, 'r')
-    string = f.readline().rstrip()
-    if f.close():
-        return ''
-    return string
+from stgit.run import *
 
 # GIT_DIR value cached
 __base_dir = None
@@ -39,7 +33,10 @@ def get():
         if 'GIT_DIR' in os.environ:
             __base_dir = os.environ['GIT_DIR']
         else:
-            __base_dir = __output('git-rev-parse --git-dir 2> /dev/null')
+            try:
+                __base_dir = Run('git-rev-parse', '--git-dir').output_one_line()
+            except RunException:
+                __base_dir = ''
 
     return __base_dir
 
stgit/commands/export.py +3 -6
index 5ca07d3..62be394 100644
@@ -175,13 +175,10 @@ def func(parser, options, args):
             print patch.get_name()
             print '-'*79
 
-        # write description
         f.write(descr)
-        # write the diff
-        git.diff(rev1 = patch.get_bottom(),
-                 rev2 = patch.get_top(),
-                 out_fd = f,
-                 diff_flags = diff_flags )
+        f.write(git.diff(rev1 = patch.get_bottom(),
+                         rev2 = patch.get_top(),
+                         diff_flags = diff_flags))
         if not options.stdout:
             f.close()
         patch_no += 1
stgit/config.py +15 -41

98 lines not on this page · raw message

stgit/git.py +131 -199

576 lines not on this page · raw message

stgit/gitmergeonefile.py +7 -11
index e76f9b1..2aa5ef8 100644
@@ -23,7 +23,7 @@ from stgit import basedir
 from stgit.config import config, file_extensions, ConfigOption
 from stgit.utils import append_string
 from stgit.out import *
-
+from stgit.run import *
 
 class GitMergeException(Exception):
     pass
@@ -44,12 +44,8 @@ def __str2none(x):
     else:
         return x
 
-def __output(cmd):
-    f = os.popen(cmd, 'r')
-    string = f.readline().rstrip()
-    if f.close():
-        raise GitMergeException, 'Error: failed to execute "%s"' % cmd
-    return string
+class MRun(Run):
+    exc = GitMergeException # use a custom exception class on errors
 
 def __checkout_files(orig_hash, file1_hash, file2_hash,
                      path,
@@ -62,24 +58,24 @@ def __checkout_files(orig_hash, file1_hash, file2_hash,
 
     if orig_hash:
         orig = path + extensions['ancestor']
-        tmp = __output('git-unpack-file %s' % orig_hash)
+        tmp = MRun('git-unpack-file', orig_hash).output_one_line()
         os.chmod(tmp, int(orig_mode, 8))
         os.renames(tmp, orig)
     if file1_hash:
         src1 = path + extensions['current']
-        tmp = __output('git-unpack-file %s' % file1_hash)
+        tmp = MRun('git-unpack-file', file1_hash).output_one_line()
         os.chmod(tmp, int(file1_mode, 8))
         os.renames(tmp, src1)
     if file2_hash:
         src2 = path + extensions['patched']
-        tmp = __output('git-unpack-file %s' % file2_hash)
+        tmp = MRun('git-unpack-file', file2_hash).output_one_line()
         os.chmod(tmp, int(file2_mode, 8))
         os.renames(tmp, src2)
 
     if file1_hash and not os.path.exists(path):
         # the current file might be removed by GIT when it is a new
         # file added in both branches. Just re-generate it
-        tmp = __output('git-unpack-file %s' % file1_hash)
+        tmp = MRun('git-unpack-file', file1_hash).output_one_line()
         os.chmod(tmp, int(file1_mode, 8))
         os.renames(tmp, path)
 
stgit/run.py new file +111 -0

111 lines not on this page · raw message

#3 lore raw

PATCH 3/4 Assert that the argument to Run is a sequence of strings

In reply to Karl Hasselström

This runtime assertion makes bugs easier to find.

In most other languages, we'd have been able to check this at compile time. But this is Python. Yay!

---

 stgit/run.py |    3 +++
 1 files changed, 3 insertions(+), 0 deletions(-)
stgit/run.py +3 -0
index d925cce..1bc4759 100644
@@ -31,6 +31,9 @@ class Run:
     exc = RunException
     def __init__(self, *cmd):
         self.__cmd = list(cmd)
+        for c in cmd:
+            if type(c) != str:
+                raise Exception, 'Bad command: %r' % cmd
         self.__good_retvals = [0]
         self.__env = None
         self.__indata = None
#4 lore raw

PATCH 4/4 Add optional logging of subprocess execution

In reply to Karl Hasselström

Now that the subprocess calling has been refactored and is in a nice shape, it's quite simple to add some logging facilities. This patch adds two separate log modes, switched by the STG_SUBPROCESS_LOG environment variable:

* Setting it to "debug" prints the executable name and all arguments, and the subprocess return value.

* Setting it to "profile" prints just the executable name, and the (wallclock) time elapsed during the call.

* Not setting it will disable logging, of course.

---

 stgit/run.py |   27 +++++++++++++++++++++++++++
 1 files changed, 27 insertions(+), 0 deletions(-)
stgit/run.py +27 -0
index 1bc4759..719ecb7 100644
@@ -22,11 +22,22 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 # to stay Python 2.3 compatible.
 import popen2, os
 
+import datetime
+
+from  stgit.out import *
+
 class RunException(Exception):
     """Thrown when something bad happened when we tried to run the
     subprocess."""
     pass
 
+_all_log_modes = ['debug', 'profile']
+_log_mode = os.environ.get('STG_SUBPROCESS_LOG', '')
+if _log_mode and not _log_mode in _all_log_modes:
+    out.warn(('Unknown log mode "%s" specified in $STG_SUBPROCESS_LOG.'
+              % _log_mode),
+             'Valid values are: %s' % ', '.join(_all_log_modes))
+
 class Run:
     exc = RunException
     def __init__(self, *cmd):
@@ -37,6 +48,18 @@ class Run:
         self.__good_retvals = [0]
         self.__env = None
         self.__indata = None
+    def __log_start(self, cmd):
+        if _log_mode == 'debug':
+            out.start('Running subprocess %s' % cmd)
+        elif _log_mode == 'profile':
+            out.start('Running subprocess %s' % cmd[0])
+            self.__starttime = datetime.datetime.now()
+    def __log_end(self, retcode):
+        if _log_mode == 'debug':
+            out.done('return code: %d' % retcode)
+        elif _log_mode == 'profile':
+            duration = datetime.datetime.now() - self.__starttime
+            out.done('%1.3f s' % (duration.microseconds/1e6 + duration.seconds))
     def __run_io(self, cmd):
         """Run with captured IO. Note: arguments are parsed by the
         shell. We single-quote them, so don't use anything with single
@@ -47,6 +70,7 @@ class Run:
             ecmd = (['env'] + ['%s=%s' % (key, val)
                                for key, val in self.__env.iteritems()]
                     + cmd)
+        self.__log_start(ecmd)
         p = popen2.Popen3(' '.join(["'%s'" % c for c in ecmd]), True)
         if self.__indata != None:
             p.tochild.write(self.__indata)
@@ -54,6 +78,7 @@ class Run:
         outdata = p.fromchild.read()
         errdata = p.childerr.read()
         self.exitcode = p.wait() >> 8
+        self.__log_end(self.exitcode)
         if errdata or self.exitcode not in self.__good_retvals:
             raise self.exc('%s failed with code %d:\n%s'
                            % (cmd[0], self.exitcode, errdata))
@@ -63,7 +88,9 @@ class Run:
         the shell."""
         assert self.__env == None
         assert self.__indata == None
+        self.__log_start(cmd)
         self.exitcode = os.spawnvp(os.P_WAIT, cmd[0], cmd)
+        self.__log_end(self.exitcode)
         if not self.exitcode in self.__good_retvals:
             raise self.exc('%s failed with code %d'
                            % (cmd[0], self.exitcode))
#5 lore raw

Re: [StGIT PATCH 4/4] Add optional logging of subprocess execution

Quoted 4 lines · Karl Hasselström

Now that the subprocess calling has been refactored and is in a nice shape, it's quite simple to add some logging facilities. This patch adds two separate log modes, switched by the STG_SUBPROCESS_LOG environment variable:

Any objection to calling this variable STGIT_SUBPROCESS_LOG? We already have STGIT_DEBUG_LEVEL (used in stgit.main). I can do it in my tree before pushing as I already merged your branches.

BTW, thanks for refactoring the subprocess calling.

Signature · 1 line
Catalin
#6 lore raw

Re: [StGIT PATCH 4/4] Add optional logging of subprocess execution

Quoted 10 lines · Catalin Marinas
Quoted 4 lines · Karl Hasselström

Now that the subprocess calling has been refactored and is in a nice shape, it's quite simple to add some logging facilities. This patch adds two separate log modes, switched by the STG_SUBPROCESS_LOG environment variable:

Any objection to calling this variable STGIT_SUBPROCESS_LOG? We already have STGIT_DEBUG_LEVEL (used in stgit.main). I can do it in my tree before pushing as I already merged your branches.

No, no objection at all. I was simply too lazy to actually check what the existing naming convention was, and misremembered.

Quoted 1 line

BTW, thanks for refactoring the subprocess calling.

It needed doing, and was actually fun.

Any chance we can drop Python 2.3 support any time soon, by the way? I've confined all the ickyness to one place, but it would still be good to get rid of it (not to mention being able to use sets and generator expressions).

Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#7 lore raw

Re: [StGIT PATCH 4/4] Add optional logging of subprocess execution

Quoted 8 lines · Karl Hasselström
Quoted 3 lines · Catalin Marinas

Any objection to calling this variable STGIT_SUBPROCESS_LOG? We already have STGIT_DEBUG_LEVEL (used in stgit.main). I can do it in my tree before pushing as I already merged your branches.

No, no objection at all. I was simply too lazy to actually check what the existing naming convention was, and misremembered.

You changed it in the code, but forgot to change it in the commit message. :-P

Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#8 lore raw

Re: [StGIT PATCH 4/4] Add optional logging of subprocess execution

Quoted 8 lines · Karl Hasselström
Quoted 6 lines · Karl Hasselström
Quoted 3 lines · Catalin Marinas

Any objection to calling this variable STGIT_SUBPROCESS_LOG? We already have STGIT_DEBUG_LEVEL (used in stgit.main). I can do it in my tree before pushing as I already merged your branches.

Quoted 5 lines
Quoted 2 lines

No, no objection at all. I was simply too lazy to actually check what the existing naming convention was, and misremembered.

You changed it in the code, but forgot to change it in the commit message. :-P

I changed it on my office PC and the locale setup breaks your name encoding :-). I tried to avoid it.

Signature · 1 line
Catalin
#9 lore raw

Re: [StGIT PATCH 4/4] Add optional logging of subprocess execution

In reply to Karl Hasselström
Quoted 4 lines · Karl Hasselström

Any chance we can drop Python 2.3 support any time soon, by the way? I've confined all the ickyness to one place, but it would still be good to get rid of it (not to mention being able to use sets and generator expressions).

Unless there is no objection, I'm actually OK with this. Feel free to break the 2.3 support from now on. I'll add a note stating the minimum versions for Python and GIT in the 0.14 release.

Signature · 1 line
Catalin
#10 lore raw

Re: [StGIT PATCH 4/4] Add optional logging of subprocess execution

Quoted 10 lines · Catalin Marinas
Quoted 4 lines · Karl Hasselström

Any chance we can drop Python 2.3 support any time soon, by the way? I've confined all the ickyness to one place, but it would still be good to get rid of it (not to mention being able to use sets and generator expressions).

Unless there is no objection, I'm actually OK with this. Feel free to break the 2.3 support from now on. I'll add a note stating the minimum versions for Python and GIT in the 0.14 release.

Great!

Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#11 lore raw

cover Break Python 2.3 compatibility

In reply to Catalin Marinas
Quoted 10 lines · Catalin Marinas
Quoted 4 lines · Karl Hasselström

Any chance we can drop Python 2.3 support any time soon, by the way? I've confined all the ickyness to one place, but it would still be good to get rid of it (not to mention being able to use sets and generator expressions).

Unless there is no objection, I'm actually OK with this. Feel free to break the 2.3 support from now on. I'll add a note stating the minimum versions for Python and GIT in the 0.14 release.

And here it is. We actually used sets in much fewer places than I thought -- but then again, there are a number of places where we ought to be using them but aren't.

Signature · 2 lines
Karl Hasselström, [email protected]
      www.treskal.com/kalle
#12 lore raw

PATCH 1/2 Use subprocess.Popen to call git executables

Replace popen2.Popen3 and os.spawn* with the superior subprocess.Popen. Now we can pass a modified environment to any subprocess, redirect input and output as we please, and the shell is no longer involved, meaning we don't have to worry about argument quoting. (We could already do all of that, just not at the same time.)

This is a Python 2.4 library, so StGit now officially requires Python 2.4 or later.

---

 stgit/run.py |   89 ++++++++++++++++++++++++++--------------------------------
 1 files changed, 40 insertions(+), 49 deletions(-)
stgit/run.py +40 -49
index 94dd98e..29f8f71 100644
@@ -17,12 +17,7 @@ along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 """
 
-# popen2 and os.spawn* suck. We should really use subprocess instead,
-# but that's only available in Python 2.4 and up, and we try our best
-# to stay Python 2.3 compatible.
-import popen2, os
-
-import datetime
+import datetime, os, subprocess
 
 from  stgit.out import *
 
@@ -48,11 +43,11 @@ class Run:
         self.__good_retvals = [0]
         self.__env = None
         self.__indata = None
-    def __log_start(self, cmd):
+    def __log_start(self):
         if _log_mode == 'debug':
-            out.start('Running subprocess %s' % cmd)
+            out.start('Running subprocess %s' % self.__cmd)
         elif _log_mode == 'profile':
-            out.start('Running subprocess %s' % cmd[0])
+            out.start('Running subprocess %s' % self.__cmd[0])
             self.__starttime = datetime.datetime.now()
     def __log_end(self, retcode):
         if _log_mode == 'debug':
@@ -60,48 +55,41 @@ class Run:
         elif _log_mode == 'profile':
             duration = datetime.datetime.now() - self.__starttime
             out.done('%1.3f s' % (duration.microseconds/1e6 + duration.seconds))
-    def __run_io(self, cmd):
-        """Run with captured IO. Note: arguments are parsed by the
-        shell. We single-quote them, so don't use anything with single
-        quotes in it."""
-        if self.__env == None:
-            ecmd = cmd
-        else:
-            ecmd = (['env'] + ['%s=%s' % (key, val)
-                               for key, val in self.__env.iteritems()]
-                    + cmd)
-        self.__log_start(ecmd)
-        p = popen2.Popen3(' '.join(["'%s'" % c for c in ecmd]), True)
-        if self.__indata != None:
-            p.tochild.write(self.__indata)
-        p.tochild.close()
-        outdata = p.fromchild.read()
-        errdata = p.childerr.read()
-        self.exitcode = p.wait() >> 8
-        self.__log_end(self.exitcode)
+    def __check_exitcode(self):
         if self.exitcode not in self.__good_retvals:
-            raise self.exc('%s failed with code %d:\n%s'
-                           % (cmd[0], self.exitcode, errdata))
-        if errdata:
-            out.warn('call to %s succeeded, but generated a warning:' % cmd[0])
-            out.err_raw(errdata)
+            raise self.exc('%s failed with code %d'
+                           % (self.__cmd[0], self.exitcode))
+    def __run_io(self):
+        """Run with captured IO."""
+        self.__log_start()
+        try:
+            p = subprocess.Popen(self.__cmd, env = self.__env,
+                                 stdin = subprocess.PIPE,
+                                 stdout = subprocess.PIPE)
+            outdata, errdata = p.communicate(self.__indata)
+            self.exitcode = p.returncode
+        except OSError, e:
+            raise self.exc('%s failed: %s' % (self.__cmd[0], e))
+        self.__log_end(self.exitcode)
+        self.__check_exitcode()
         return outdata
-    def __run_noshell(self, cmd):
-        """Run without captured IO. Note: arguments are not parsed by
-        the shell."""
-        assert self.__env == None
+    def __run_noio(self):
+        """Run without captured IO."""
         assert self.__indata == None
-        self.__log_start(cmd)
-        self.exitcode = os.spawnvp(os.P_WAIT, cmd[0], cmd)
+        self.__log_start()
+        try:
+            p = subprocess.Popen(self.__cmd, env = self.__env)
+            self.exitcode = p.wait()
+        except OSError, e:
+            raise self.exc('%s failed: %s' % (self.__cmd[0], e))
         self.__log_end(self.exitcode)
-        if not self.exitcode in self.__good_retvals:
-            raise self.exc('%s failed with code %d'
-                           % (cmd[0], self.exitcode))
+        self.__check_exitcode()
     def returns(self, retvals):
         self.__good_retvals = retvals
         return self
     def env(self, env):
-        self.__env = env
+        self.__env = dict(os.environ)
+        self.__env.update(env)
         return self
     def raw_input(self, indata):
         self.__indata = indata
@@ -110,15 +98,15 @@ class Run:
         self.__indata = ''.join(['%s\n' % line for line in lines])
         return self
     def no_output(self):
-        outdata = self.__run_io(self.__cmd)
+        outdata = self.__run_io()
         if outdata:
             raise self.exc, '%s produced output' % self.__cmd[0]
     def discard_output(self):
-        self.__run_io(self.__cmd)
+        self.__run_io()
     def raw_output(self):
-        return self.__run_io(self.__cmd)
+        return self.__run_io()
     def output_lines(self):
-        outdata = self.__run_io(self.__cmd)
+        outdata = self.__run_io()
         if outdata.endswith('\n'):
             outdata = outdata[:-1]
         if outdata:
@@ -134,11 +122,14 @@ class Run:
                            % (self.__cmd[0], len(outlines)))
     def run(self):
         """Just run, with no IO redirection."""
-        self.__run_noshell(self.__cmd)
+        self.__run_noio()
     def xargs(self, xargs):
         """Just run, with no IO redirection. The extra arguments are
         appended to the command line a few at a time; the command is
         run as many times as needed to consume them all."""
         step = 100
+        basecmd = self.__cmd
         for i in xrange(0, len(xargs), step):
-            self.__run_noshell(self.__cmd + xargs[i:i+step])
+            self.__cmd = basecmd + xargs[i:i+step]
+            self.__run_noio()
+        self.__cmd = basecmd
#13 lore raw

PATCH 2/2 Use the builtin set() instead of sets.Set()

In reply to Karl Hasselström

We can do that now that we're guaranteed to have Python 2.4 or later.

---

 stgit/git.py |    8 +++-----
 1 files changed, 3 insertions(+), 5 deletions(-)
stgit/git.py +3 -5
index 8857209..4b4c626 100644
@@ -26,7 +26,6 @@ from stgit.utils import *
 from stgit.out import *
 from stgit.run import *
 from stgit.config import config
-from sets import Set
 
 # git exception class
 class GitException(Exception):
@@ -959,10 +958,9 @@ def __remotes_from_dir(dir):
 def remotes_list():
     """Return the list of remotes in the repository
     """
-
-    return Set(__remotes_from_config()) | \
-           Set(__remotes_from_dir('remotes')) | \
-           Set(__remotes_from_dir('branches'))
+    return (set(__remotes_from_config())
+            | set(__remotes_from_dir('remotes'))
+            | set(__remotes_from_dir('branches')))
 
 def remotes_local_branches(remote):
     """Returns the list of local branches fetched from given remote