summaryrefslogtreecommitdiff
path: root/tortoisehg/hgqt/hgrcutil.py
blob: e70ab0f3a93273e67535007b76a076c54d3c6aef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# hgrcutils.py - Functions to manipulate hgrc (or similar) files
#
# Copyright 2011 Angel Ezquerra <angel.ezquerra@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

import os

from tortoisehg.hgqt import qtlib
from tortoisehg.util import wconfig
from tortoisehg.util.i18n import _

def loadIniFile(rcpath, parent=None):
    for fn in rcpath:
        if os.path.exists(fn):
            break
    else:
        for fn in rcpath:
            # Try to create a file from rcpath
            try:
                f = open(fn, 'w')
                f.write('# Generated by TortoiseHg\n')
                f.close()
                break
            except EnvironmentError:
                pass
        else:
            qtlib.WarningMsgBox(_('Unable to create a config file'),
                   _('Insufficient access rights.'), parent=parent)
            return None, {}

    return fn, wconfig.readfile(fn)

def setConfigValue(rcfilepath, cfgpath, value):
    '''
    Set a value on a config file, such as an hgrc or a .ini file

    rcpfilepath: Absolute path to a configuration file
    cfgpath: Full "path" of a configurable key
             Format is section.keyNamee.g. 'web.name')
    value: String value for the selected config key
    '''
    fn, cfg = loadIniFile([rcfilepath])
    if not hasattr(cfg, 'write'):
        return False
    if fn is None:
        return False
    cfgFullKey = cfgpath.split('.')
    if len(cfgFullKey) < 2:
        return False
    cfg.set(cfgFullKey[0], cfgFullKey[1], value)
    try:
        wconfig.writefile(cfg, fn)
    except EnvironmentError, e:
        return False
    return True