Skip to content

Commit

Permalink
Extract subprocess-related code to separate class
Browse files Browse the repository at this point in the history
  • Loading branch information
Roman Kharitonov committed Jun 17, 2012
1 parent c593479 commit 402c8eb
Showing 1 changed file with 38 additions and 17 deletions.
55 changes: 38 additions & 17 deletions gtags.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,34 @@ def find_tags_root(current, previous=None):
return find_tags_root(parent, current)


class TagSubprocess(object):
def __init__(self, **kwargs):
self.default_kwargs = kwargs
if IS_WINDOWS:
self.default_kwargs['shell'] = True

def create(self, command, **kwargs):
final_kwargs = self.default_kwargs
final_kwargs.update(kwargs)

if isinstance(command, basestring):
if IS_WINDOWS:
command = command.encode('utf-8')
command = shlex.split(command)

return subprocess.Popen(command, **final_kwargs)

def stdout(self, command, **kwargs):
process = self.create(command, stdout=subprocess.PIPE, **kwargs)
return process.communicate()[0]

def call(self, command, **kwargs):
process = self.create(command, stderr=subprocess.PIPE, **kwargs)
retcode = process.wait()
_, stderr = process.communicate()
return retcode, stderr


class TagFile(object):
def _expand_path(self, path):
path = os.path.expandvars(os.path.expanduser(path))
Expand All @@ -55,25 +83,14 @@ def __init__(self, root_dir=None, extra_paths=[]):
self.__env['GTAGSLIBPATH'] = os.pathsep.join(
map(self._expand_path, extra_paths))

def start_with(self, prefix):
return self._shell('global -c %s' % prefix, stdout=subprocess.PIPE)

def _shell(self, command, **kwargs):
if isinstance(command, basestring):
if IS_WINDOWS:
command = command.encode('utf-8')
command = shlex.split(command)

if IS_WINDOWS:
kwargs['shell'] = True
self.subprocess = TagSubprocess(env=self.__env)

process = subprocess.Popen(command, env=self.__env, **kwargs)
stdout, _ = process.communicate()
return stdout.rstrip().splitlines()
def start_with(self, prefix):
return self.subprocess.stdout('global -c %s' % prefix).splitlines()

def _match(self, pattern, options):
lines = self._shell('global %s %s' % (options, pattern),
stdout=subprocess.PIPE)
lines = self.subprocess.stdout(
'global %s %s' % (options, pattern)).splitlines()
matches = []
for search_obj in (t for t in (TAGS_RE.search(l) for l in lines) if t):
matches.append(search_obj.groupdict())
Expand All @@ -83,7 +100,11 @@ def match(self, pattern, reference=False):
return self._match(pattern, '-ax' + ('r' if reference else ''))

def rebuild(self):
self._shell('gtags -vv', cwd=self.__root)
retcode, stderr = self.subprocess.call('gtags -v', cwd=self.__root)
success = retcode == 0
if not success:
print stderr
return success


class GTagsTest(unittest.TestCase):
Expand Down

0 comments on commit 402c8eb

Please sign in to comment.