Beispiel #1
0
    def _ui(self):
        """
        Creates an db based ui object for this repository
        """
        from mercurial import ui
        from mercurial import config
        baseui = ui.ui()

        #clean the baseui object
        baseui._ocfg = config.config()
        baseui._ucfg = config.config()
        baseui._tcfg = config.config()


        ret = RhodeCodeUi.query()\
            .options(FromCache("sql_cache_short", "repository_repo_ui")).all()

        hg_ui = ret
        for ui_ in hg_ui:
            if ui_.ui_active:
                log.debug('settings ui from db[%s]%s:%s', ui_.ui_section,
                          ui_.ui_key, ui_.ui_value)
                baseui.setconfig(ui_.ui_section, ui_.ui_key, ui_.ui_value)

        return baseui
Beispiel #2
0
def make_ui(read_from='file', path=None, checkpaths=True, clear_session=True):
    """
    A function that will read python rc files or database
    and make an mercurial ui object from read options

    :param path: path to mercurial config file
    :param checkpaths: check the path
    :param read_from: read from 'file' or 'db'
    """

    baseui = ui.ui()

    # clean the baseui object
    baseui._ocfg = config.config()
    baseui._ucfg = config.config()
    baseui._tcfg = config.config()

    if read_from == 'file':
        if not os.path.isfile(path):
            log.debug('hgrc file is not present at %s, skipping...' % path)
            return False
        log.debug('reading hgrc from %s' % path)
        cfg = config.config()
        cfg.read(path)
        for section in ui_sections:
            for k, v in cfg.items(section):
                log.debug('settings ui from file: [%s] %s=%s' %
                          (section, k, v))
                baseui.setconfig(safe_str(section), safe_str(k), safe_str(v))

    elif read_from == 'db':
        sa = meta.Session()
        ret = sa.query(RhodeCodeUi)\
            .options(FromCache("sql_cache_short", "get_hg_ui_settings"))\
            .all()

        hg_ui = ret
        for ui_ in hg_ui:
            if ui_.ui_active:
                log.debug('settings ui from db: [%s] %s=%s', ui_.ui_section,
                          ui_.ui_key, ui_.ui_value)
                baseui.setconfig(safe_str(ui_.ui_section),
                                 safe_str(ui_.ui_key), safe_str(ui_.ui_value))
            if ui_.ui_key == 'push_ssl':
                # force set push_ssl requirement to False, rhodecode
                # handles that
                baseui.setconfig(safe_str(ui_.ui_section),
                                 safe_str(ui_.ui_key), False)
        if clear_session:
            meta.Session.remove()
    return baseui
Beispiel #3
0
def make_ui(read_from='file', path=None, checkpaths=True, clear_session=True):
    """
    A function that will read python rc files or database
    and make an mercurial ui object from read options

    :param path: path to mercurial config file
    :param checkpaths: check the path
    :param read_from: read from 'file' or 'db'
    """

    baseui = ui.ui()

    # clean the baseui object
    baseui._ocfg = config.config()
    baseui._ucfg = config.config()
    baseui._tcfg = config.config()

    if read_from == 'file':
        if not os.path.isfile(path):
            log.debug('hgrc file is not present at %s, skipping...' % path)
            return False
        log.debug('reading hgrc from %s' % path)
        cfg = config.config()
        cfg.read(path)
        for section in ui_sections:
            for k, v in cfg.items(section):
                log.debug('settings ui from file[%s]%s:%s' % (section, k, v))
                baseui.setconfig(safe_str(section), safe_str(k), safe_str(v))

    elif read_from == 'db':
        sa = meta.Session()
        ret = sa.query(RhodeCodeUi)\
            .options(FromCache("sql_cache_short", "get_hg_ui_settings"))\
            .all()

        hg_ui = ret
        for ui_ in hg_ui:
            if ui_.ui_active:
                log.debug('settings ui from db[%s]%s:%s', ui_.ui_section,
                          ui_.ui_key, ui_.ui_value)
                baseui.setconfig(safe_str(ui_.ui_section), safe_str(ui_.ui_key),
                                 safe_str(ui_.ui_value))
            if ui_.ui_key == 'push_ssl':
                # force set push_ssl requirement to False, rhodecode
                # handles that
                baseui.setconfig(safe_str(ui_.ui_section), safe_str(ui_.ui_key),
                                 False)
        if clear_session:
            meta.Session.remove()
    return baseui
Beispiel #4
0
    def __init__(self, ui, root, data):
        self._decode = {"LF": "to-lf", "CRLF": "to-crlf", "BIN": "is-binary"}
        self._encode = {"LF": "to-lf", "CRLF": "to-crlf", "BIN": "is-binary"}

        self.cfg = config.config()
        # Our files should not be touched. The pattern must be
        # inserted first override a '** = native' pattern.
        self.cfg.set("patterns", ".hg*", "BIN", "eol")
        # We can then parse the user's patterns.
        self.cfg.parse(".hgeol", data)

        isrepolf = self.cfg.get("repository", "native") != "CRLF"
        self._encode["NATIVE"] = isrepolf and "to-lf" or "to-crlf"
        iswdlf = ui.config("eol", "native", os.linesep) in ("LF", "\n")
        self._decode["NATIVE"] = iswdlf and "to-lf" or "to-crlf"

        include = []
        exclude = []
        for pattern, style in self.cfg.items("patterns"):
            key = style.upper()
            if key == "BIN":
                exclude.append(pattern)
            else:
                include.append(pattern)
        # This will match the files for which we need to care
        # about inconsistent newlines.
        self.match = match.match(root, "", [], include, exclude)
    def __init__(self, ui, root, data):
        self._decode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}
        self._encode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}

        self.cfg = config.config()
        # Our files should not be touched. The pattern must be
        # inserted first override a '** = native' pattern.
        self.cfg.set('patterns', '.hg*', 'BIN', 'eol')
        # We can then parse the user's patterns.
        self.cfg.parse('.hgeol', data)

        isrepolf = self.cfg.get('repository', 'native') != 'CRLF'
        self._encode['NATIVE'] = isrepolf and 'to-lf' or 'to-crlf'
        iswdlf = ui.config('eol', 'native', pycompat.oslinesep) in ('LF', '\n')
        self._decode['NATIVE'] = iswdlf and 'to-lf' or 'to-crlf'

        include = []
        exclude = []
        self.patterns = []
        for pattern, style in self.cfg.items('patterns'):
            key = style.upper()
            if key == 'BIN':
                exclude.append(pattern)
            else:
                include.append(pattern)
            m = match.match(root, '', [pattern])
            self.patterns.append((pattern, key, m))
        # This will match the files for which we need to care
        # about inconsistent newlines.
        self.match = match.match(root, '', [], include, exclude)
Beispiel #6
0
    def __init__(self, ui, root, data):
        self._decode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}
        self._encode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}

        self.cfg = config.config()
        # Our files should not be touched. The pattern must be
        # inserted first override a '** = native' pattern.
        self.cfg.set('patterns', '.hg*', 'BIN')
        # We can then parse the user's patterns.
        self.cfg.parse('.hgeol', data)

        isrepolf = self.cfg.get('repository', 'native') != 'CRLF'
        self._encode['NATIVE'] = isrepolf and 'to-lf' or 'to-crlf'
        iswdlf = ui.config('eol', 'native', os.linesep) in ('LF', '\n')
        self._decode['NATIVE'] = iswdlf and 'to-lf' or 'to-crlf'

        include = []
        exclude = []
        for pattern, style in self.cfg.items('patterns'):
            key = style.upper()
            if key == 'BIN':
                exclude.append(pattern)
            else:
                include.append(pattern)
        # This will match the files for which we need to care
        # about inconsistent newlines.
        self.match = match.match(root, '', [], include, exclude)
 def _activepath(self, remote):
     conf = config.config()
     try:
         rc = self.vfs.join('hgrc')
     except AttributeError:
         # old hg
         rc = self.join('hgrc')
     if os.path.exists(rc):
         with open(rc) as fp:
             conf.parse('.hgrc', fp.read(), include=conf.read)
     realpath = ''
     if 'paths' in conf:
         for path, uri in conf['paths'].items():
             for s in schemes.schemes.iterkeys():
                 if uri.startswith('%s://' % s):
                     # TODO: refactor schemes so we don't
                     # duplicate this logic
                     ui.note('performing schemes expansion with '
                             'scheme %s\n' % s)
                     scheme = hg.schemes[s]
                     parts = uri.split('://', 1)[1].split('/',
                                                          scheme.parts)
                     if len(parts) > scheme.parts:
                         tail = parts[-1]
                         parts = parts[:-1]
                     else:
                         tail = ''
                     context = dict((str(i+1), v) for i, v in
                                    enumerate(parts))
                     uri = ''.join(scheme.templater.process(
                         scheme.url, context)) + tail
             uri = self.ui.expandpath(uri)
             if remote.local():
                 uri = os.path.realpath(uri)
                 rpath = getattr(remote, 'root', None)
                 if rpath is None:
                     # Maybe a localpeer? (hg@1ac628cd7113, 2.3)
                     rpath = getattr(getattr(remote, '_repo', None),
                                     'root', None)
             else:
                 rpath = getattr(remote, 'url', lambda : remote._url)()
                 if uri.startswith('http'):
                     try:
                         uri = url.url(uri).authinfo()[0]
                     except AttributeError:
                         try:
                             uri = util.url(uri).authinfo()[0]
                         except AttributeError:
                             uri = url.getauthinfo(uri)[0]
             uri = uri.rstrip('/')
             rpath = rpath.rstrip('/')
             if uri == rpath:
                 realpath = path
                 # prefer a non-default name to default
                 if path != 'default':
                     break
     return realpath
Beispiel #8
0
 def _activepath(self, remote):
     conf = config.config()
     try:
         rc = self.vfs.join('hgrc')
     except AttributeError:
         # old hg
         rc = self.join('hgrc')
     if os.path.exists(rc):
         with open(rc) as fp:
             conf.parse('.hgrc', fp.read(), include=conf.read)
     realpath = ''
     if 'paths' in conf:
         for path, uri in conf['paths'].items():
             for s in schemes.schemes.iterkeys():
                 if uri.startswith('%s://' % s):
                     # TODO: refactor schemes so we don't
                     # duplicate this logic
                     ui.note('performing schemes expansion with '
                             'scheme %s\n' % s)
                     scheme = hg.schemes[s]
                     parts = uri.split('://', 1)[1].split('/',
                                                          scheme.parts)
                     if len(parts) > scheme.parts:
                         tail = parts[-1]
                         parts = parts[:-1]
                     else:
                         tail = ''
                     context = dict((str(i+1), v) for i, v in
                                    enumerate(parts))
                     uri = ''.join(scheme.templater.process(
                         scheme.url, context)) + tail
             uri = self.ui.expandpath(uri)
             if remote.local():
                 uri = os.path.realpath(uri)
                 rpath = getattr(remote, 'root', None)
                 if rpath is None:
                     # Maybe a localpeer? (hg@1ac628cd7113, 2.3)
                     rpath = getattr(getattr(remote, '_repo', None),
                                     'root', None)
             else:
                 rpath = getattr(remote, 'url', lambda : remote._url)()
                 if uri.startswith('http'):
                     try:
                         uri = url.url(uri).authinfo()[0]
                     except AttributeError:
                         try:
                             uri = util.url(uri).authinfo()[0]
                         except AttributeError:
                             uri = url.getauthinfo(uri)[0]
             uri = uri.rstrip('/')
             rpath = rpath.rstrip('/')
             if uri == rpath:
                 realpath = path
                 # prefer a non-default name to default
                 if path != 'default':
                     break
     return realpath
Beispiel #9
0
def config(data=None):
    """Create writable config if iniparse available; otherwise readonly obj

    You can test whether the returned obj is writable or not by
    `hasattr(obj, 'write')`.
    """
    if _hasiniparse:
        return _wconfig(data)
    else:
        return config_mod.config(data)
Beispiel #10
0
    def __init__(self, data=None):
        self._config = config_mod.config(data)
        self._readfiles = []  # list of read (path, fp, sections, remap)
        self._sections = {}

        if isinstance(data, self.__class__):  # keep log
            self._readfiles.extend(data._readfiles)
            self._sections.update(data._sections)
        elif data:  # record as changes
            self._logupdates(data)
def load_user_cache(ui, api_server, filename):
    user_cache = get_global_path(filename)

    # Ensure that the cache exists before attempting to use it
    fp = open(user_cache, "a")
    fp.close()

    c = config.config()
    c.read(user_cache)
    return c
Beispiel #12
0
def load_user_cache(ui, api_server, filename):
    user_cache = get_global_path(filename)

    # Ensure that the cache exists before attempting to use it
    fp = open(user_cache, "a");
    fp.close()

    c = config.config()
    c.read(user_cache)
    return c
Beispiel #13
0
    def __init__(self, data=None):
        self._config = config_mod.config(data)
        self._readfiles = []  # list of read (path, fp, sections, remap)
        self._sections = {}

        if isinstance(data, self.__class__):  # keep log
            self._readfiles.extend(data._readfiles)
            self._sections.update(data._sections)
        elif data:  # record as changes
            self._logupdates(data)
Beispiel #14
0
def config(data=None):
    """Create writable config if iniparse available; otherwise readonly obj

    You can test whether the returned obj is writable or not by
    `hasattr(obj, 'write')`.
    """
    if _hasiniparse:
        return _wconfig(data)
    else:
        return config_mod.config(data)
Beispiel #15
0
def make_ui(read_from='file', path=None, checkpaths=True):
    """A function that will read python rc files or database
    and make an mercurial ui object from read options

    :param path: path to mercurial config file
    :param checkpaths: check the path
    :param read_from: read from 'file' or 'db'
    """

    baseui = ui.ui()

    #clean the baseui object
    baseui._ocfg = config.config()
    baseui._ucfg = config.config()
    baseui._tcfg = config.config()

    if read_from == 'file':
        if not os.path.isfile(path):
            log.warning('Unable to read config file %s' % path)
            return False
        log.debug('reading hgrc from %s', path)
        cfg = config.config()
        cfg.read(path)
        for section in ui_sections:
            for k, v in cfg.items(section):
                log.debug('settings ui from file[%s]%s:%s', section, k, v)
                baseui.setconfig(section, k, v)

    elif read_from == 'db':
        sa = meta.Session()
        ret = sa.query(RhodeCodeUi)\
            .options(FromCache("sql_cache_short",
                               "get_hg_ui_settings")).all()

        hg_ui = ret
        for ui_ in hg_ui:
            if ui_.ui_active:
                log.debug('settings ui from db[%s]%s:%s', ui_.ui_section,
                          ui_.ui_key, ui_.ui_value)
                baseui.setconfig(ui_.ui_section, ui_.ui_key, ui_.ui_value)

        meta.Session.remove()
    return baseui
Beispiel #16
0
def listprojrc(repo):
    if os.path.exists(repo_join(repo, 'projrc')):
        try:
            conf = config.config()
            conf.read(repo_join(repo, 'projrc'))
            data = ENCODING_CHECK + serializeconfig(conf)
        except error.ParseError, e:
            # Send broken file to client so that it can detect and
            # report the error there.
            print "error"
            data = repo_read(repo, 'projrc')
        return {'data': data.encode('string-escape')}
Beispiel #17
0
 def parsegitmodules(self, content):
     """Parse the formatted .gitmodules file, example file format:
     [submodule "sub"]\n
     \tpath = sub\n
     \turl = git://giturl\n
     """
     self.submodules = []
     c = config.config()
     # Each item in .gitmodules starts with \t that cant be parsed
     c.parse('.gitmodules', content.replace('\t',''))
     for sec in c.sections():
         s = c[sec]
         if 'url' in s and 'path' in s:
             self.submodules.append(submodule(s['path'], '', s['url']))
Beispiel #18
0
 def parsegitmodules(self, content):
     """Parse the formatted .gitmodules file, example file format:
     [submodule "sub"]\n
     \tpath = sub\n
     \turl = git://giturl\n
     """
     self.submodules = []
     c = config.config()
     # Each item in .gitmodules starts with \t that cant be parsed
     c.parse('.gitmodules', content.replace('\t',''))
     for sec in c.sections():
         s = c[sec]
         if 'url' in s and 'path' in s:
             self.submodules.append(submodule(s['path'], '', s['url']))
Beispiel #19
0
def user_config():
    """Read the Mercurial user configuration

    This is typically ~/.hgrc on POSIX.  This is returned
    as a Mercurial.config.config object.
    """
    hgrc = config()
    for cfg in userrcpath():
        if not os.path.exists(cfg):
            log("NOT reading missing cfg: " + cfg)
            continue
        log("Reading config: " + cfg)
        hgrc.read(cfg)
    return hgrc
Beispiel #20
0
def user_config():
    """Read the Mercurial user configuration

    This is typically ~/.hgrc on POSIX.  This is returned
    as a Mercurial.config.config object.
    """
    hgrc = config()
    for cfg in userrcpath():
        if not os.path.exists(cfg):
            log("NOT reading missing cfg: " + cfg)
            continue
        log("Reading config: " + cfg)
        hgrc.read(cfg)
    return hgrc
Beispiel #21
0
        def readhgeol(self, node=None, data=None):
            if data is None:
                try:
                    if node is None:
                        data = self.wfile('.hgeol').read()
                    else:
                        data = self[node]['.hgeol'].data()
                except (IOError, LookupError):
                    return None

            if self.ui.config('eol', 'native', os.linesep) in ('LF', '\n'):
                self._decode['NATIVE'] = 'to-lf'
            else:
                self._decode['NATIVE'] = 'to-crlf'

            eol = config.config()
            # Our files should not be touched. The pattern must be
            # inserted first override a '** = native' pattern.
            eol.set('patterns', '.hg*', 'BIN')
            # We can then parse the user's patterns.
            eol.parse('.hgeol', data)

            if eol.get('repository', 'native') == 'CRLF':
                self._encode['NATIVE'] = 'to-crlf'
            else:
                self._encode['NATIVE'] = 'to-lf'

            for pattern, style in eol.items('patterns'):
                key = style.upper()
                try:
                    self.ui.setconfig('decode', pattern, self._decode[key])
                    self.ui.setconfig('encode', pattern, self._encode[key])
                except KeyError:
                    self.ui.warn(
                        _("ignoring unknown EOL style '%s' from %s\n") %
                        (style, eol.source('patterns', pattern)))

            include = []
            exclude = []
            for pattern, style in eol.items('patterns'):
                key = style.upper()
                if key == 'BIN':
                    exclude.append(pattern)
                else:
                    include.append(pattern)

            # This will match the files for which we need to care
            # about inconsistent newlines.
            return match.match(self.root, '', [], include, exclude)
 def _activepath(self, remote):
     conf = config.config()
     rc = self.join("hgrc")
     if os.path.exists(rc):
         fp = open(rc)
         conf.parse(".hgrc", fp.read())
         fp.close()
     realpath = ""
     if "paths" in conf:
         for path, uri in conf["paths"].items():
             for s in schemes.schemes.iterkeys():
                 if uri.startswith("%s://" % s):
                     # TODO: refactor schemes so we don't
                     # duplicate this logic
                     ui.note("performing schemes expansion with " "scheme %s\n" % s)
                     scheme = hg.schemes[s]
                     parts = uri.split("://", 1)[1].split("/", scheme.parts)
                     if len(parts) > scheme.parts:
                         tail = parts[-1]
                         parts = parts[:-1]
                     else:
                         tail = ""
                     context = dict((str(i + 1), v) for i, v in enumerate(parts))
                     uri = "".join(scheme.templater.process(scheme.url, context)) + tail
             uri = self.ui.expandpath(uri)
             if remote.local():
                 uri = os.path.realpath(uri)
                 rpath = getattr(remote, "root", None)
                 if rpath is None:
                     # Maybe a localpeer? (hg@1ac628cd7113, 2.3)
                     rpath = getattr(getattr(remote, "_repo", None), "root", None)
             else:
                 rpath = remote._url
                 if uri.startswith("http"):
                     try:
                         uri = url.url(uri).authinfo()[0]
                     except AttributeError:
                         try:
                             uri = util.url(uri).authinfo()[0]
                         except AttributeError:
                             uri = url.getauthinfo(uri)[0]
             uri = uri.rstrip("/")
             rpath = rpath.rstrip("/")
             if uri == rpath:
                 realpath = path
                 # prefer a non-default name to default
                 if path != "default":
                     break
     return realpath
Beispiel #23
0
def getcustomadmonitions(repo):
    ctx = repo['.']
    p = config.config()

    def read(f, sections=None, remap=None):
        if f in ctx:
            data = ctx[f].data()
            p.parse(f, data, sections, remap, read)
        else:
            raise error.Abort(_(".hgreleasenotes file \'%s\' not found") %
                              repo.pathto(f))

    if '.hgreleasenotes' in ctx:
        read('.hgreleasenotes')
    return p['sections']
    def __init__(self, path):
        self._c = config.config()
        with open(path, 'rb') as fh:
            self._c.read(path, fh)

        if 'GLOBAL' not in self._c:
            raise error.Abort('config file missing GLOBAL section')

        self.stagepath = self._c.get('GLOBAL', 'stagepath')
        if not self.stagepath:
            raise error.Abort('GLOBAL.stagepath not defined in config')

        self.destpath = self._c.get('GLOBAL', 'destpath')
        if not self.destpath:
            raise error.Abort('GLOBAL.destpath not defined in config')
Beispiel #25
0
    def __init__(self, path):
        self._c = config.config()
        with open(path, 'rb') as fh:
            self._c.read(path, fh)

        if 'GLOBAL' not in self._c:
            raise error.Abort('config file missing GLOBAL section')

        self.stagepath = self._c.get('GLOBAL', 'stagepath')
        if not self.stagepath:
            raise error.Abort('GLOBAL.stagepath not defined in config')

        self.destpath = self._c.get('GLOBAL', 'destpath')
        if not self.destpath:
            raise error.Abort('GLOBAL.destpath not defined in config')
def find_profile(ui, profileName):
    """
    Find the default Firefox profile location. Returns None
    if no profile could be located.

    """
    path = None
    if platform.system() == "Darwin":
        # Use FSFindFolder
        from Carbon import Folder, Folders
        pathref = Folder.FSFindFolder(Folders.kUserDomain,
                                      Folders.kApplicationSupportFolderType,
                                      Folders.kDontCreateFolder)
        basepath = pathref.FSRefMakePath()
        path = os.path.join(basepath, "Firefox")
    elif platform.system() == "Windows":
        # From http://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx
        CSIDL_APPDATA = 26
        path = win_get_folder_path(CSIDL_APPDATA)
        if path:
            path = os.path.join(path, "Mozilla", "Firefox")
    else:
        # Assume POSIX
        # Pretty simple in comparison, eh?
        path = os.path.expanduser("~/.mozilla/firefox")
    if path is None:
        raise util.Abort(_("Could not find a Firefox profile"))

    profileini = os.path.join(path, "profiles.ini")
    c = config.config()
    c.read(profileini)

    if profileName:
        sections = [s for s in c.sections() if profileName in [s, c.get(s, "Name", None)]]
    else:
        sections = [s for s in c.sections() if c.get(s, "Default", None)]
        if len(sections) == 0:
            sections = c.sections()

    sections = [s for s in sections if c.get(s, "Path", None) is not None]
    if len(sections) == 0:
        raise util.Abort(_("Could not find a Firefox profile"))

    section = sections.pop(0)
    profile = c[section].get("Path")
    if c.get(section, "IsRelative", "0") == "1":
        profile = os.path.join(path, profile)
    return profile
Beispiel #27
0
        def readhgeol(self, node=None, data=None):
            if data is None:
                try:
                    if node is None:
                        data = self.wfile('.hgeol').read()
                    else:
                        data = self[node]['.hgeol'].data()
                except (IOError, LookupError):
                    return None

            if self.ui.config('eol', 'native', os.linesep) in ('LF', '\n'):
                self._decode['NATIVE'] = 'to-lf'
            else:
                self._decode['NATIVE'] = 'to-crlf'

            eol = config.config()
            # Our files should not be touched. The pattern must be
            # inserted first override a '** = native' pattern.
            eol.set('patterns', '.hg*', 'BIN')
            # We can then parse the user's patterns.
            eol.parse('.hgeol', data)

            if eol.get('repository', 'native') == 'CRLF':
                self._encode['NATIVE'] = 'to-crlf'
            else:
                self._encode['NATIVE'] = 'to-lf'

            for pattern, style in eol.items('patterns'):
                key = style.upper()
                try:
                    self.ui.setconfig('decode', pattern, self._decode[key])
                    self.ui.setconfig('encode', pattern, self._encode[key])
                except KeyError:
                    self.ui.warn(_("ignoring unknown EOL style '%s' from %s\n")
                                 % (style, eol.source('patterns', pattern)))

            include = []
            exclude = []
            for pattern, style in eol.items('patterns'):
                key = style.upper()
                if key == 'BIN':
                    exclude.append(pattern)
                else:
                    include.append(pattern)

            # This will match the files for which we need to care
            # about inconsistent newlines.
            return match.match(self.root, '', [], include, exclude)
Beispiel #28
0
 def parsegitmodules(self, content):
     """Parse the formatted .gitmodules file, example file format:
     [submodule "sub"]\n
     \tpath = sub\n
     \turl = git://giturl\n
     """
     self.submodules = []
     c = config.config()
     # Each item in .gitmodules starts with whitespace that cant be parsed
     c.parse(
         b'.gitmodules',
         b'\n'.join(line.strip() for line in content.split(b'\n')),
     )
     for sec in c.sections():
         s = c[sec]
         if b'url' in s and b'path' in s:
             self.submodules.append(submodule(s[b'path'], b'', s[b'url']))
Beispiel #29
0
def make_ui(self, path='hgwebdir.config'):
    """
    A funcion that will read python rc files and make an ui from read options

    :param path: path to mercurial config file
    """
    #propagated from mercurial documentation
    sections = [
                'alias',
                'auth',
                'decode/encode',
                'defaults',
                'diff',
                'email',
                'extensions',
                'format',
                'merge-patterns',
                'merge-tools',
                'hooks',
                'http_proxy',
                'smtp',
                'patch',
                'paths',
                'profiling',
                'server',
                'trusted',
                'ui',
                'web',
                ]

    repos = path
    baseui = ui.ui()
    cfg = config.config()
    cfg.read(repos)
    self.paths = cfg.items('paths')
    self.base_path = self.paths[0][1].replace('*', '')
    self.check_repo_dir(self.paths)
    self.set_statics(cfg)

    for section in sections:
        for k, v in cfg.items(section):
            baseui.setconfig(section, k, v)

    return baseui
Beispiel #30
0
def make_ui(self, path='hgwebdir.config'):
    """
    A funcion that will read python rc files and make an ui from read options

    :param path: path to mercurial config file
    """
    #propagated from mercurial documentation
    sections = [
        'alias',
        'auth',
        'decode/encode',
        'defaults',
        'diff',
        'email',
        'extensions',
        'format',
        'merge-patterns',
        'merge-tools',
        'hooks',
        'http_proxy',
        'smtp',
        'patch',
        'paths',
        'profiling',
        'server',
        'trusted',
        'ui',
        'web',
    ]

    repos = path
    baseui = ui.ui()
    cfg = config.config()
    cfg.read(repos)
    self.paths = cfg.items('paths')
    self.base_path = self.paths[0][1].replace('*', '')
    self.check_repo_dir(self.paths)
    self.set_statics(cfg)

    for section in sections:
        for k, v in cfg.items(section):
            baseui.setconfig(section, k, v)

    return baseui
Beispiel #31
0
def _trackedmatcher(repo):
    """Return a function (path, size) -> bool indicating whether or not to
    track a given file with lfs."""
    if not repo.wvfs.exists(b'.hglfs'):
        # No '.hglfs' in wdir.  Fallback to config for now.
        trackspec = repo.ui.config(b'lfs', b'track')

        # deprecated config: lfs.threshold
        threshold = repo.ui.configbytes(b'lfs', b'threshold')
        if threshold:
            filesetlang.parse(
                trackspec)  # make sure syntax errors are confined
            trackspec = b"(%s) | size('>%d')" % (trackspec, threshold)

        return minifileset.compile(trackspec)

    data = repo.wvfs.tryread(b'.hglfs')
    if not data:
        return lambda p, s: False

    # Parse errors here will abort with a message that points to the .hglfs file
    # and line number.
    cfg = config.config()
    cfg.parse(b'.hglfs', data)

    try:
        rules = [(minifileset.compile(pattern), minifileset.compile(rule))
                 for pattern, rule in cfg.items(b'track')]
    except error.ParseError as e:
        # The original exception gives no indicator that the error is in the
        # .hglfs file, so add that.

        # TODO: See if the line number of the file can be made available.
        raise error.Abort(_(b'parse error in .hglfs: %s') % e)

    def _match(path, size):
        for pat, rule in rules:
            if pat(path, size):
                return rule(path, size)

        return False

    return _match
Beispiel #32
0
def newrconfig(vals={}):
    c = config.config()
    for k, v in isinstance(vals, dict) and vals.iteritems() or vals:
        sec, it = k.split('.', 1)
        c.set(sec, it, v)
    return c
def get_profiles(profilesdir):
    """Obtain information about available Firefox profiles.

    The Firefox profiles from the specified path will be loaded. A list of
    dicts describing each profile will be returned. The list is sorted
    according to profile preference. The default profile is always first.
    """
    profileini = os.path.join(profilesdir, b'profiles.ini')
    if not os.path.exists(profileini):
        return []

    c = config.config()
    c.read(pycompat.bytestr(profileini))

    profiles = []
    for s in c.sections():
        if not c.get(s, b'Path') or not c.get(s, b'Name'):
            continue

        name = c.get(s, b'Name')
        path = c.get(s, b'Path')

        if c.get(s, b'IsRelative') == b'1':
            path = os.path.join(profilesdir, path)

        newest = -1
        if os.path.exists(path):
            mtimes = []
            for p in os.listdir(path):
                p = os.path.join(path, p)
                if os.path.isfile(p):
                    mtimes.append(os.path.getmtime(p))

            # If there are no files, ignore the profile completely.
            if not mtimes:
                continue

            newest = max(mtimes)

        p = {
            b'name': name,
            b'path': path,
            b'default': c.get(s, b'Default', False) and True,
            b'mtime': newest,
        }

        profiles.append(p)

    def compare(a, b):
        """Sort profile by default first, file mtime second."""
        if a[b'default']:
            return -1

        if a[b'mtime'] > b[b'mtime']:
            return -1
        elif a[b'mtime'] < b[b'mtime']:
            return 1

        return 0

    # TRACKING py3 - sorted takes a `key`
    if pycompat.ispy3:
        import functools
        sorted_kwargs = {
            'key': functools.cmp_to_key(compare),
        }
    else:
        sorted_kwargs = {
            'cmp': compare,
        }

    return sorted(profiles, **sorted_kwargs)
Beispiel #34
0
def getremoteprojrc(ui, repo, other):
    """
    Get the contents of a remote projrc and check that they are valid
    
    This function returns a 2-element tuple:
    - The projrc contents as a string (or None if no projrc was found)
    - A boolean indicating whether the data is valid.
    
    Note that it is possible to return (None, True), which simply means
    that no data matching the projrc filter settings was found.
    """
    if not repo.local():
        return None, True

    # Get the list of repos that we are supposed to get a projrc file from
    # (i.e. the projrc "servers")
    projrcserverset = getprojrcserverset(ui)

    try:
        remotepath = other.root
        remotepath = os.path.normcase(util.normpath(remotepath))
    except:
        # Non local repos have no root property
        remotepath = other.url()
        if remotepath.startswith('file:'):
            remotepath = remotepath[5:]

    if '*' not in projrcserverset and \
            not findpatternmatch(remotepath, projrcserverset)[0] and \
            not ("localhost" in projrcserverset and islocalpath(remotepath)):
        # The pull source is not on the projrc server list
        # Note that we keep any existing local projrc file, which may have been
        # transferred from another valid server
        return None, True

    # Get the list of remote keys that we must load from the remote projrc file
    includedkeys, excludedkeys = getallowedkeys(ui)
    if includedkeys or excludedkeys:
        projrc = other.listkeys('projrc')
    else:
        # There are no remote keys to load
        projrc = {} # This ensures that any existing projrc file will be deleted

    data = None
    valid = True
    if 'data' in projrc:
        data = projrc['data'].decode('string-escape')
        if data.startswith("#\\\\ "):
            data = data.decode('string-escape')
        # verify that we can parse the file we got, and filter it according
        # to the local projrc extension settings
        try:
            c = config.config()
            c.parse('projrc', data)
            # Filter the received config, only allowing the sections that
            # the user has specified in any of its hgrc files
            data = ENCODING_CHECK + \
                serializeconfig(c, includedkeys, excludedkeys)
        except error.ParseError, e:
                ui.warn(_("not saving retrieved projrc file: "
                          "parse error at '%s' on %s\n") % e.args)
                valid = False
Beispiel #35
0
def get_profiles(profilesdir):
    """Obtain information about available Firefox profiles.

    The Firefox profiles from the specified path will be loaded. A list of
    dicts describing each profile will be returned. The list is sorted
    according to profile preference. The default profile is always first.
    """
    profileini = os.path.join(profilesdir, 'profiles.ini')
    if not os.path.exists(profileini):
        return []

    c = config.config()
    c.read(profileini)

    profiles = []
    for s in c.sections():
        if not c.get(s, 'Path') or not c.get(s, 'Name'):
            continue

        name = c.get(s, 'Name')
        path = c.get(s, 'Path')

        if c.get(s, 'IsRelative') == '1':
            path = os.path.join(profilesdir, path)

        newest = -1
        if os.path.exists(path):
            mtimes = []
            for p in os.listdir(path):
                p = os.path.join(path, p)
                if os.path.isfile(p):
                    mtimes.append(os.path.getmtime(p))

            # If there are no files, ignore the profile completely.
            if not mtimes:
                continue

            newest = max(mtimes)

        p = {
            'name': name,
            'path': path,
            'default': c.get(s, 'Default', False) and True,
            'mtime': newest,
        }

        profiles.append(p)

    def compare(a, b):
        """Sort profile by default first, file mtime second."""
        if a['default']:
            return -1

        if a['mtime'] > b['mtime']:
            return -1
        elif a['mtime'] < b['mtime']:
            return 1

        return 0

    return sorted(profiles, cmp=compare)
Beispiel #36
0
def cdm_reparent(ui, repo, parent):
    '''reparent your workspace

    Update the 'default' path alias that is used as the default source
    for 'hg pull' and the default destination for 'hg push' (unless
    there is a 'default-push' alias).  This is also the path all
    Cadmium commands treat as your parent workspace.
    '''

    def append_new_parent(parent):
        fp = None
        try:
            fp = repo.opener('hgrc', 'a', atomictemp=True)
            if fp.tell() != 0:
                fp.write('\n')
            fp.write('[paths]\n'
                     'default = %s\n\n' % parent)
            fp.rename()
        finally:
            if fp and not fp.closed:
                fp.close()

    def update_parent(path, line, parent):
        line = line - 1 # The line number we're passed will be 1-based
        fp = None

        try:
            fp = open(path)
            data = fp.readlines()
        finally:
            if fp and not fp.closed:
                fp.close()

        #
        # line will be the last line of any continued block, go back
        # to the first removing the continuation as we go.
        #
        while data[line][0].isspace():
            data.pop(line)
            line -= 1

        assert data[line].startswith('default')

        data[line] = "default = %s\n" % parent
        if data[-1] != '\n':
            data.append('\n')

        try:
            fp = util.atomictempfile(path, 'w', 0644)
            fp.writelines(data)
            fp.rename()
        finally:
            if fp and not fp.closed:
                fp.close()

    from mercurial import config
    parent = ui.expandpath(parent)

    if not os.path.exists(repo.join('hgrc')):
        append_new_parent(parent)
        return

    cfg = config.config()
    cfg.read(repo.join('hgrc'))
    source = cfg.source('paths', 'default')

    if not source:
        append_new_parent(parent)
        return
    else:
        path, target = source.rsplit(':', 1)

        if path != repo.join('hgrc'):
            raise util.Abort("Cannot edit path specification not in repo hgrc\n"
                             "default path is from: %s" % source)

        update_parent(path, int(target), parent)
def get_profiles(profilesdir):
    """Obtain information about available Firefox profiles.

    The Firefox profiles from the specified path will be loaded. A list of
    dicts describing each profile will be returned. The list is sorted
    according to profile preference. The default profile is always first.
    """
    profileini = os.path.join(profilesdir, 'profiles.ini')
    if not os.path.exists(profileini):
        return []

    c = config.config()
    c.read(profileini)

    profiles = []
    for s in c.sections():
        if not c.get(s, 'Path') or not c.get(s, 'Name'):
            continue

        name = c.get(s, 'Name')
        path = c.get(s, 'Path')

        if c.get(s, 'IsRelative') == '1':
            path = os.path.join(profilesdir, path)

        newest = -1
        if os.path.exists(path):
            mtimes = []
            for p in os.listdir(path):
                p = os.path.join(path, p)
                if os.path.isfile(p):
                    mtimes.append(os.path.getmtime(p))

            # If there are no files, ignore the profile completely.
            if not mtimes:
                continue

            newest = max(mtimes)

        p = {
            'name': name,
            'path': path,
            'default': c.get(s, 'Default', False) and True,
            'mtime': newest,
        }

        profiles.append(p)

    def compare(a, b):
        """Sort profile by default first, file mtime second."""
        if a['default']:
            return -1

        if a['mtime'] > b['mtime']:
            return -1
        elif a['mtime'] < b['mtime']:
            return 1

        return 0

    return sorted(profiles, cmp=compare)
Beispiel #38
0
def newrconfig(vals={}):
    c = config.config()
    for k, v in isinstance(vals, dict) and vals.iteritems() or vals:
        sec, it = k.split('.', 1)
        c.set(sec, it, v)
    return c