Ejemplo n.º 1
0
Archivo: git.py Proyecto: nijel/weblate
 def git_config_update(filename: str, *updates: Tuple[str, str, str]):
     # First, open file read-only to check current settings
     modify = False
     with GitConfigParser(file_or_files=filename, read_only=True) as config:
         for section, key, value in updates:
             try:
                 old = config.get(section, key)
                 if value is None:
                     modify = True
                     break
                 if old == value:
                     continue
             except (NoSectionError, NoOptionError):
                 pass
             if value is not None:
                 modify = True
     if not modify:
         return
     # In case changes are needed, open it for writing as that creates a lock
     # file
     with GitConfigParser(file_or_files=filename, read_only=False) as config:
         for section, key, value in updates:
             try:
                 old = config.get(section, key)
                 if value is None:
                     config.remove_option(section, key)
                     continue
                 if old == value:
                     continue
             except (NoSectionError, NoOptionError):
                 pass
             if value is not None:
                 config.set_value(section, key, value)
Ejemplo n.º 2
0
def parse_submodules(path):
    config = GitConfigParser(path)
    submodules = {}
    for section in config.sections():
        d = dict(config.items(section))
        submodules[d['path']] = d['url']
    return submodules
Ejemplo n.º 3
0
    def __init__(self, config_location=None):

        path = config_location if config_location else DEFAULT_GITCONFIG_PATH
        try:
            config = GitConfigParser(open(path))
            self.base_url = config.get_value('garnet', 'apiurl')

        except:
            raise '[ERROR] error in .gitconfig'
Ejemplo n.º 4
0
def get_username(username):
    """
    If a username is not specified, use the global user.name from ~/.gitconfig
    """
    from git.config import GitConfigParser
    if username is None:
        gitconfig_name = os.path.expanduser('~/.gitconfig')
        if not os.path.isfile(gitconfig_name):
            raise ValueError("You must enter a username if you do not have a ~/.gitconfig file")
        gitconfig = GitConfigParser(gitconfig_name, read_only=True)
        username = gitconfig.get('user','name')
        if username == '':
            raise ValueError("Could not load user.name from ~/.gitconfig")
    return username
Ejemplo n.º 5
0
def ensure_git_user():
    """Prompt for fullname and email if git config is missing it."""
    conf_path = get_config_path('global')
    with GitConfigParser(conf_path, read_only=False) as conf_parser:

        # Make sure a user section exists
        if 'user' not in conf_parser.sections():
            conf_parser.add_section('user')

        # Check for missing options using the ConfigParser and insert them
        # if they're missing.
        name, email = (None, None)
        try:
            name = conf_parser.get(section='user', option='name')
        except NoOptionError:
            pass  # Name doesn't exist deal with it later
        try:
            email = conf_parser.get(section='user', option='email')
        except NoOptionError:
            pass  # E-mail doesn't exist, deal with it later

        if not all((name, email)):
            # Some of the needed config is missing
            print(GIT_IDENTITY_INFO)
            if not name:
                name = input('Please enter Full name: ')
                conf_parser.set('user', 'name', name)
            if not email:
                email = input('Please enter e-mail address: ')
                conf_parser.set('user', 'email', email)

            print(GIT_MANUAL_CHANGE_INFO)
Ejemplo n.º 6
0
 def config_update(self, *updates):
     filename = os.path.join(self.path, '.git', 'config')
     with GitConfigParser(file_or_files=filename,
                          read_only=False) as config:
         for section, key, value in updates:
             if config.get_value(section, key, -1) != value:
                 config.set_value(section, key, value)
Ejemplo n.º 7
0
    def extra_validations(self, **kwargs):
        default_groups = ('Non-Interactive Users', 'Administrators',
                          'Registered Users', 'Anonymous Users')
        logs = []
        acls = kwargs['file']
        groups = kwargs['groups']

        fd, path = tempfile.mkstemp()
        os.close(fd)
        file(path, 'w').write(acls)
        # Validate the file has the right format
        try:
            c = GitConfigParser(path)
            c.read()
        except Exception, e:
            logs.append(str(e))
Ejemplo n.º 8
0
 def __init__(self) -> None:
     self.api_key = "751db5fc75ff34f08a83381f4d54ead6"
     self.user_id = GitConfigParser().get_value("user", "email", "no_user")
     self.device_id = get_mac_address()
     self.os_name = os.name
     self.platform = platform.system()
     self.os_version = platform.version()
Ejemplo n.º 9
0
def get_global_config_parser(read_only=True):
    """Return the global config parser.

    :param bool read_only: Return a read only config parser.
    :return: A `~git.GitConfigParser` object for ~/.gitconfig.
    """
    path = os.path.normpath(os.path.expanduser("~/.gitconfig"))
    return GitConfigParser(path, read_only=read_only)
Ejemplo n.º 10
0
 def config_reader(self, config_level=None):
     files = None
     if config_level is None:
         files = [self._path_at_level(f) for f in self.config_level]
     else:
         files = [self._path_at_level(config_level)]
     # END handle level
     return GitConfigParser(files, read_only=True)
Ejemplo n.º 11
0
    def __init__(self):
        gitconfig = os.path.join(os.getcwd(), self.CONFIG)

        if os.path.isfile(gitconfig):
            self.parser = GitConfigParser(gitconfig, read_only=True)
            self.loadConfig()
        else:
            raise IOError('Stash project configuration file for stashcli not found (' + self.CONFIG + ')')
Ejemplo n.º 12
0
    def extra_validations(self, **kwargs):
        default_groups = ('Non-Interactive Users',
                          'Administrators',
                          'Registered Users',
                          'Anonymous Users')
        logs = []
        acls = kwargs['file']
        groups = kwargs['groups']

        fd, path = tempfile.mkstemp()
        os.close(fd)
        file(path, 'w').write(acls)
        # Validate the file has the right format
        try:
            c = GitConfigParser(path)
            c.read()
        except Exception, e:
            logs.append(str(e))
Ejemplo n.º 13
0
    def config_writer(self, config_level="repository"):
        """
        :return:
            GitConfigParser allowing to write values of the specified configuration file level.
            Config writers should be retrieved, used to change the configuration ,and written
            right away as they will lock the configuration file in question and prevent other's
            to write it.

        :param config_level:
            One of the following values
            system = sytem wide configuration file
            global = user level configuration file
            repository = configuration file for this repostory only"""
        return GitConfigParser(self._get_config_path(config_level), read_only=False)
Ejemplo n.º 14
0
 def config_update(self, *updates):
     filename = os.path.join(self.path, ".git", "config")
     with GitConfigParser(file_or_files=filename, read_only=False) as config:
         for section, key, value in updates:
             try:
                 old = config.get(section, key)
                 if value is None:
                     config.remove_option(section, key)
                     continue
                 if old == value:
                     continue
             except (NoSectionError, NoOptionError):
                 pass
             if value is not None:
                 config.set_value(section, key, value)
Ejemplo n.º 15
0
    def config_reader(self, config_level=None):
        """
        :return:
            GitConfigParser allowing to read the full git configuration, but not to write it

            The configuration will include values from the system, user and repository
            configuration files.

        :param config_level:
            For possible values, see config_writer method
            If None, all applicable levels will be used. Specify a level in case
            you know which file you wish to read to prevent reading multiple files.
        :note: On windows, system configuration cannot currently be read as the path is
            unknown, instead the global path will be used."""
        files = None
        if config_level is None:
            files = [self._get_config_path(f) for f in self.config_level]
        else:
            files = [self._get_config_path(config_level)]
        return GitConfigParser(files, read_only=True)
Ejemplo n.º 16
0
#!/usr/bin/env python
from os.path import expanduser
from git.config import GitConfigParser

# stolen from gitpython/repo/base.py
f=expanduser("~/.gitconfig")
files = [f]
config = GitConfigParser(f, read_only=False)
print config.get("user", "name")
#print config.get("notexisting", "name")
# ConfigParser.NoSectionError: No section: 'notexisting'

config.set("key", "value")
Ejemplo n.º 17
0
 def __init__(self,path,read_only=False):
     self.read_only = read_only
     path = fullpath(path)
     parser = GitConfigParser(path,read_only=self.read_only)
     Conf.__init__(self,path=path,parser=parser)
Ejemplo n.º 18
0
import os
import sys
from git.config import GitConfigParser

# stolen from gitpython/repo/base.py

def _get_config_path(config_level="global"):
    if sys.platform == "win32" and config_level == "system":
        config_level = "global"

    if config_level == "system":
        return "/etc/gitconfig"
    elif config_level == "global":
        return os.path.normpath(os.path.expanduser("~/.gitconfig"))

        raise ValueError("Invalid configuration level: %r" % config_level)

files = _get_config_path()
config = GitConfigParser(files, read_only=True)
print config.get("user", "name")
Ejemplo n.º 19
0
 def config_writer(self, config_level="repository"):
     return GitConfigParser(self._path_at_level(config_level), read_only=False)
Ejemplo n.º 20
0
class GitRepositoryOps(object):
    def __init__(self, conf, new):
        self.conf = conf
        self.new = new
        self.client = None

    def _set_client(self):
        if not self.client:
            gerrit = SoftwareFactoryGerrit(self.conf)
            self.client = gerrit.get_client()

    def get_all(self):
        logs = []
        gitrepos = {}
        acls = {}

        self._set_client()

        try:
            repos = self.client.get_projects()
            if repos is False:
                logs.append("Repo list: err API returned HTTP 404/409")
        except Exception, e:
            logs.append("Repo list: err API returned %s" % e)

        for name in repos:
            gitrepos[name] = {}
            r = utils.GerritRepo(name, self.conf)
            # Remove the project section when it only contains description
            remove_project_section = False
            acl_path = r.get_raw_acls()
            acl_groups = set()
            c = GitConfigParser(acl_path)
            c.read()
            for section_name in c.sections():
                for k, v in c.items(section_name):
                    if section_name == 'project':
                        if k == 'description':
                            if len(c.items(section_name)) == 1:
                                remove_project_section = True
                            gitrepos[name]['description'] = v
                        continue
                    r = re.search('group (.*)', v)
                    if r:
                        acl_groups.add(r.groups()[0].strip())

            _acl = file(acl_path).read()
            acl = ""
            # Clean the ACL file to avoid issue at YAML multiline
            # serialization. Remove the description and as a good
            # practice description should never appears in a ACL rtype
            # TODO(fbo): extra_validation of acl must deny the description
            for l in _acl.splitlines():
                if remove_project_section and l.find('[project]') != -1:
                    continue
                if l.find('description') != -1:
                    continue
                acl += l.replace('\t', '    ').rstrip() + '\n'
            m = hashlib.md5()
            m.update(acl)
            acl_id = m.hexdigest()
            gitrepos[name]['name'] = name
            gitrepos[name]['acl'] = acl_id
            acls[acl_id] = {}
            acls[acl_id]['file'] = acl
            acls[acl_id]['groups'] = acl_groups
            acls[acl_id]['groups'] -= set(DEFAULT_GROUPS)
            acls[acl_id]['groups'] -= set(('Registered Users', ))
            acls[acl_id]['groups'] = list(acls[acl_id]['groups'])
        return logs, {'repos': gitrepos, 'acls': acls}
Ejemplo n.º 21
0
class Config(object):

    CONFIG = '.git/config'
    SECTION = 'stashcli'
    parser = None
    settings = {}

    def __init__(self):
        gitconfig = os.path.join(os.getcwd(), self.CONFIG)

        if os.path.isfile(gitconfig):
            self.parser = GitConfigParser(gitconfig, read_only=True)
            self.loadConfig()
        else:
            raise IOError('Stash project configuration file for stashcli not found (' + self.CONFIG + ')')

    def loadConfig(self):
        '''
        Load configuration from gitconfig, validate at the same time.
        '''
        config_fact = []
        config_fact.append('url')
        config_fact.append('username')
        config_fact.append('password')
        config_fact.append('project')
        config_fact.append('repo')
        config_fact.append('mergedestination')
        config_fact.append('reviewers')
        config_fact.append('template')

        config_opt = []
        config_opt.append('hipchat')
        config_opt.append('hipchattoken')
        config_opt.append('hipchatroom')
        config_opt.append('hipchatagent')

        # Stash config params (mandatory)
        for item in config_fact:
            try:
                self.settings[item] = self.parser.get_value(self.SECTION, item)
            except Exception:
                raise AttributeError('Incorrectly configured stashcli within gitconfig, refer to README.md')

        # Optional config
        for item in config_opt:
            try:
                self.settings[item] = self.parser.get_value(self.SECTION, item)
            except Exception:
                pass

    def getTemplateFilePath(self):
        if os.path.isfile(self.settings['template']):
            return self.settings['template']
        else:
            raise IOError('Pull-request template file for stashcli not found (' + self.settings['template'] + ')')

    def getStashUrl(self):
        return self.settings['url']

    def getMergeDestination(self):
        return self.settings['mergedestination']

    def getUsername(self):
        return self.settings['username']

    def getPassword(self):
        return str(base64.b64decode(self.settings['password'])).strip()

    def getProject(self):
        return self.settings['project']

    def getRepo(self):
        return self.settings['repo']

    def getReviewers(self, delimiter = ','):
        if (delimiter == None):
            return self.settings['reviewers'];
        return map(unicode.strip, self.splitReviewers(self.settings['reviewers'], delimiter))

    def isHipchatEnabled(self):
        return '0' != str(self.settings['hipchat'])

    def getHipchatToken(self):
        return self.settings['hipchattoken']

    def getHipchatRoom(self):
        return self.settings['hipchatroom']

    def getHipchatAgent(self):
        return self.settings['hipchatagent']

    @staticmethod
    def splitReviewers(subject, delimiter = ','):
        if (isinstance(subject, (str, unicode))):
            return subject.split(delimiter)
        else:
            raise ValueError('Need a string to split')
Ejemplo n.º 22
0
def get_config():
    global _config
    if not _config:
        _config = GitConfigParser(GIT_CONFIG)
    return _config