Skip to content

Instantly share code, notes, and snippets.

@jn0
Created November 8, 2017 08:26
Show Gist options
  • Save jn0/a40c45ede4fc47596a46e4d661fef683 to your computer and use it in GitHub Desktop.
Save jn0/a40c45ede4fc47596a46e4d661fef683 to your computer and use it in GitHub Desktop.
Wanna parse ini-style ./.git/config and failed? Well...
import os
try:
import ConfigParser
except ImportError: # python3?
import configparser as ConfigParser
dot_git_config = os.path.join('.git', 'config')
class GitConfigParser(ConfigParser.RawConfigParser):
def _read(self, fp, filename=None):
filename = filename if filename is not None else (
fp.name if hasattr(fp, 'name') else '<???>')
lineno = 0
section = 'DEFAULT'
name = value = None
while True:
line = fp.readline()
if not line:
break
lineno += 1
if name is not None and value is not None:
## value continuation a la rfc822 is not applicable here
#if line[0].isspace(): # value continuation a la rfc822
# value += line
# continue
self.set(section, name, value)
name = value = None
xline = line.strip()
if not xline or xline.startswith('#') or xline.startswith(';'):
continue # comment
if xline.startswith('['):
if not xline.endswith(']'):
raise ConfigParser.ParsingError('Bad section in %r line %r: %r'
% (filename, lineno, line))
section = xline[1:-1]
if not section in self.sections():
self.add_section(section)
continue
if '=' not in xline:
raise ConfigParser.ParsingError('Bad line in %r line %r: %r'
% (filename, lineno, line))
name, value = [s.strip() for s in xline.split('=', 1)]
if name is not None and value is not None:
self.set(section, name, value) # pending value
fp.close()
#end class GitConfigParser
def my_git_dir():
cwd = os.getcwdu()
while cwd and cwd != '/' and not os.path.exists(os.path.join(cwd, '.git')):
cwd = os.path.dirname(cwd)
if not os.path.exists(os.path.join(cwd, '.git')):
# sys.stderr.write('Not in a git repo!\n')
return None
return cwd
# EOF #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment