Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def modify_folders_file(root, new_file, **kwargs):
"""
Modify the template test_folders file with the given arguments
:param root: The path to the existing template file
:param new_file: The new file path
:param kwargs: The arguments to modify inside the file
:return: The full path to the new file
"""
try:
import configparser as cfg
except ImportError:
import ConfigParser as cfg
assert os.path.isfile(root)
cfg_parser = cfg.RawConfigParser()
cfg_parser.read(root)
for arg in kwargs:
cfg_parser.set("PATH", arg, kwargs[arg])
with open(new_file, 'w') as f:
cfg_parser.write(f)
return new_file
def read_config_info(ini_file):
"""
Read the INI file
Args:
ini_file - path to the file
Returns:
A dictionary of stuff from the INI file
Exits:
1 - if problems are encountered
"""
try:
config = RawConfigParser()
config.optionxform = lambda option: option
config.read(ini_file)
the_stuff = {}
for section in config.sections():
the_stuff[section] = {}
for option in config.options(section):
the_stuff[section][option] = config.get(section, option)
return the_stuff
except Exception as wtf:
logging.error('Exception caught in read_config_info(): {}'.format(wtf))
traceback.print_exc(file=sys.stdout)
return sys.exit(1)
def get_user_repo_config(repo_dir):
"""Obtain a ConfigParser for a repository.
If the hgrc file doesn't exist, it will be created automatically.
"""
user = os.getenv('USER')
path = '%s/.hg/hgrc' % repo_dir
if not os.path.isfile(path):
run_command('touch %s' % path)
run_command('chown %s:scm_level_1 %s' % (user, path))
config = RawConfigParser()
if not config.read(path):
sys.stderr.write('Could not read the hgrc file for this repo\n')
sys.stderr.write('Please file a Developer Services :: hg.mozilla.org bug\n')
sys.exit(1)
return path, config
def setup_configuration(config_file=None):
global _config
_config = configparser.RawConfigParser()
_config.read(config_file)
globals()['_config'] = _config
return _config
def loadINIPackage(self, inifile):
"""
Load INI file containing macro definitions
Arguments:
inifile -- filename of INI formatted file
"""
ini = configparser.RawConfigParser()
if not isinstance(inifile, (list, tuple)):
inifile = [inifile]
for f in inifile:
ini.read(f)
macros = {}
for section in ini.sections():
try: baseclass = self[section]
except KeyError:
log.warning('Could not find macro %s' % section)
continue
for name in ini.options(section):
value = ini.get(section, name)
m = re.match(r'^str\(\s*(?:(\'|\")(?P.+)(?:\1)|(?P\d+))\s*\)$', value)
if m:
data = m.groupdict()
if data['number'] is not None:
def __init__(self, config_in=None):
self.config_in = config_in
self.config = cp.RawConfigParser()
self.config.read(self.config_in)
self.logger = logging.getLogger('vwConfig')
def _read_config(self, read_config=True):
"""
Read cascading config files
default -> then config
(in all XDG_CONFIG_DIRS)
"""
parser = configparser.RawConfigParser()
def fill_parser(parser, defaults):
for secname, section in defaults.items():
if not parser.has_section(secname):
parser.add_section(secname)
for key, default in section.items():
if isinstance(default, (tuple, list)):
default = self.sep.join(default)
elif isinstance(default, int):
default = str(default)
parser.set(secname, key, default)
# Set up defaults
confmap = copy.deepcopy(self.defaults)
fill_parser(parser, confmap)
def get_immutable_keys(cls):
"""Get set of immutable keys
Immutable keys are calculated from 'ipaca_default' config file
and known keys that are defined in code.
"""
if cls._immutable_keys is None:
immutable = set()
immutable.update(cls._immutable_code_keys)
cfg = RawConfigParser()
with open(cls.ipaca_default) as f:
cfg.read_file(f)
for section in cls.subsystems:
for k, _v in cfg.items(section, raw=True):
if k.startswith('pki_'):
immutable.add(k)
cls._immutable_keys = frozenset(immutable)
return cls._immutable_keys
def make_config(confpath=None):
conf = configparser.RawConfigParser()
if not confpath: confpath = os.path.expanduser('~/.nxt-python')
print("Welcome to the nxt-python config file generator!")
print("This function creates an example file which find_one_brick uses to find a brick.")
try:
if os.path.exists(confpath): input("File already exists at %s. Press Enter to overwrite or Ctrl+C to abort." % confpath)
except KeyboardInterrupt:
print("Not writing file.")
return
conf.add_section('Brick')
conf.set('Brick', 'name', 'MyNXT')
conf.set('Brick', 'host', '54:32:59:92:F9:39')
conf.set('Brick', 'strict', 0)
conf.set('Brick', 'method', 'usb=True, bluetooth=False')
conf.write(open(confpath, 'w'))
print("The file has been written at %s" % confpath)
print("The file contains less-than-sane default values to get you started.")
def rebuildCfg(oldCfg=None):
'''
Rebuilds the configuration file from user inputs.
Optional Parameters:
oldCfg - if defined values will be inserted into this dict instead of returned.
Return:
the new configuration dictionary.
'''
cfgParse = RawConfigParser()
cfgParse['DEFAULT'] = defaults
cfg = {}
#Get user inputs
cfg['username'] = input(I18N['USERNAME_PROMPT_MSG'])
cfg['password'] = input(I18N['PASSWORD_PROMPT_MSG'])
cfg['host'] = input(I18N['HOST_PROMPT_MSG'])
cfg['pause'] = input(I18N['PAUSE_PROMPT_MSG'])
cfg['clear'] = input(I18N['CLEAR_PROMPT_MSG'])
#Set the default if the user chose to input nothing
for k,v in defaults.items():
if cfg[k] == '':
cfg[k] = v