Example #1
0
    def edit_account_config(self, config, **kwargs):
        """ Launches an editor to edit a user or group configuration """
        account_type = self._config_account_type(config)

        if not kwargs:  # interactive mode
            # save config to file
            temp_fd, temp_filename = mkstemp(suffix=".ini", text=True)
            try:
                temp_file = os.fdopen(temp_fd, "w")
                config.write(temp_file)
                temp_file.close()

                # open config in editor
                editor = os.environ.get('EDITOR', 'vi')
                subprocess.call([editor, temp_filename])

                # fetch config from file
                new_config = ConfigParser()
                new_config.read(temp_filename)
            finally:
                os.remove(temp_filename)
        else:
            new_config = config
            for key in kwargs:
                new_config.set(account_type, key, kwargs[key])

        # Sanity check resulting config
        if account_type == "user":
            User("foo", new_config)
        elif account_type == "group":
            Group("foo", new_config)

        return new_config
Example #2
0
def auth_springpad_client(config_file=None):
    """
    Auth the application to make to be allowed to access to user's springpad
    account. If not a valid config file is provided it will prompt the user to
    visit an url in order to allow the application to access to its account
    and it will store authentication details in `config_file`.
    args:
        config_file: the configuration file path to be used. If it is not
            provided, '~/.springpad' will be used instead.
    returns: SpringpadClient instance to interact with the authenticated
        account.
    """
    config_file = config_file or os.path.expanduser("~/.springpad")
    config = ConfigParser()
    config.read([config_file])
    token = config.get("access", "token") if config.has_option("access", "token") else None
    if token:
        token = oauth.OAuthToken.from_string(token)

    client = SpringpadClient(SPRINGPAD_CONSUMER_KEY, SPRINGPAD_CONSUMER_PRIVATE, token)

    if not client.access_token:
        req_token = client.get_request_token()
        print "Please grant access to your springpad account in the following url:\n"
        print "http://springpad.com/api/oauth-authorize?{0}\n".format(req_token)
        print "Once authorized, press intro to continue:",
        raw_input()
        client.access_token = client.get_access_token(req_token)
        config.add_section("access")
        config.set("access", "token", str(client.access_token))
        with open(os.path.expanduser(config_file), "w") as cf:
            config.write(cf)
    return client
Example #3
0
class UserConfig:

    def __init__(self, filename=default_user_config_file):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        if not isfile(self.filename):
            self.parser.add_section('diaspora')
            self.set_activated(False)
            self.__save()
        else:
            self.parser.read(self.filename)

        if not self.parser.has_section('diaspora'):
            self.parser.add_section('diaspora')

    def is_installed(self):
        return self.parser.getboolean('diaspora', 'activated')

    def set_activated(self, value):
        self.parser.set('diaspora', 'activated', str(value))
        self.__save()

    def __save(self):
        with open(self.filename, 'wb') as f:
            self.parser.write(f)
Example #4
0
    def _hg_hook(self):
        # In hg, hooks can be set in config
        hgrc = "%s/.hg/hgrc" % self.vcs_path
        parser = ConfigParser()
        files = parser.read(hgrc)

        if not files:
            conf.log.warning("Failed to find mercurial config: {0}".format(hgrc))
            return False

        try:
            # Set hook
            path = os.path.join(conf.version_control_hooks_dir, "hg-incoming")
            if 'hooks' not in parser.sections():
                parser.add_section('hooks')
            parser.set('hooks', 'incoming', path)

            # Write hook in config
            with open(hgrc, "w") as hgrc_file:
                parser.write(hgrc_file)

        except Exception:
            conf.log.exception("Failed to hook with mercurial repository")
            return False

        return True
Example #5
0
def install_mercurial_hook():
    """
    Installs the mercurial precommit hook by adding a hook to the hgrc
    file in the .hg directory of the repository.
    """

    repo_dir = get_repo_dir()

    config_file = os.path.join(repo_dir, '.hg', 'hgrc')
    config_parser = ConfigParser()
    config_parser.read(config_file)

    precommit_abs_file = os.path.join(repo_dir, 'scripts',
            'codestyleprecommit.py')

    section = 'hooks'
    key = 'pretxncommit.precommit'
    value = 'python:%s:mercurial_hook' % precommit_abs_file

    if not config_parser.has_section(section):
        config_parser.add_section(section)

    config_parser.set(section, key, value)

    with open(config_file, 'w') as config:
        config_parser.write(config)
Example #6
0
 def save_action_to_file(action, f):
     parser = ConfigParser()
     parser.add_section('action')
     for action_k, action_v in action.items():
         parser.set('action', action_k, action_v)
     parser.write(f)
     f.seek(0)
Example #7
0
 def set(self, section, option, value):
     """Set an option value. Knows how to set options properly marked
     as secure."""
     if self.is_secure_option(section, option):
         self.set_secure(section, option, value)
     else:
         ConfigParser.set(self, section, option, value)
 def hour_set(arg, hour):
     cp = ConfigParser()
     cp.read("conf.txt")
     cp.set("pills_must_be_taken", "hour", hour)
     hd = open("conf.txt", "w")
     cp.write(hd)
     hd.close()
 def minutes_set(arg, mins):
     cp = ConfigParser()
     cp.read("conf.txt")
     cp.set("pills_must_be_taken", "minutes", mins)
     hd = open("conf.txt", "w")
     cp.write(hd)
     hd.close()
	def addRegra(self, ipORrede, nome, banda_liberada, banda_down, prio, delimitado, isolado):
		#system("tc qdisc del dev %s root"%self.device)
		arquivo = ConfigParser()
		arquivo.read( '/var/lib/netcontrol/plugins/limite_banda/etc/config_server' )
		
		if not arquivo.has_section("contador_regras"):
			arquivo.add_section("contador_regras")
			arquivo.set("contador_regras","contador",1)
			arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') )
			cont = "1"
		else:
			cont = int(arquivo.get("contador_regras", "contador")) + 1
			arquivo.set("contador_regras","contador", cont)
			arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') )
			cont = str(cont)
		cont = "000%s"%(cont)
		ip   = ipORrede.replace('.','_').replace('/','_')
		user = nome.replace(' ','_')
		nome = "cbq-%s.%s%s-in"%(cont[-4:],ip,user)
		regra = "DEVICE=%s,%s,%s\n" \
				"RATE=%sKbit\n"   \
				"WEIGHT=%sKbit\n" \
				"PRIO=%s\n"       \
				"RULE=%s\n"       \
				"BOUNDED=%s\n"    \
				"ISOLATED=%s"%(self.device, self.banda_total, self.banda_total_down, banda_liberada, banda_down, prio, ipORrede, delimitado, isolado)
		open('%s%s'%(self.etc,nome),'w').write(regra)
 def mail_set(arg, email):
     cp = ConfigParser()
     cp.read("conf.txt")
     cp.set("parents", "mail", email)
     hd = open("conf.txt", "w")
     cp.write(hd)
     hd.close()
Example #12
0
def start_config(config_file_name):
    config = ConfigParser()
    config.add_section("global")

    value = raw_input("Enter the JSON root folder to write the json files too : ")
    if len(value) == 0:
        value = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/www/JSON'
    elif value[-1] != "/":
        value += "/"
    config.set("global", "json_root", value)

    modules_config = []

    module_list = os.listdir(os.path.dirname(os.path.abspath(__file__)))
    for module in module_list:
        if module == "__init__.py" or module[-3:] != ".py" or module[:4] == 'main':
            continue
        loaded_module = __import__("pygamescanner." + module[:-3], fromlist=["*"])
        module_config = loaded_module.start_config(config)
        modules_config.append(module_config)

    modules_config_dict = dict()
    modules_config_dict["module_list"] = modules_config
    config_string = json.dumps(modules_config_dict)
    modules_file = open(config.get("global", "json_root") + "modules.json", "w")
    modules_file.write(config_string)
    modules_file.close()

    config_file = open(config_file_name, "w")
    config.write(config_file)
    config_file.close()
Example #13
0
def set_config_to_path(configPath, section, option, value):

    read = False

    #check if config file exists
    if ( os.path.isfile(configPath)):
        configPath = os.path.realpath(configPath);
        config = ConfigParser();
        #try to read the value from ini file
        try:
            config.read(configPath)
            if config.has_section(section) :
                    #Update the new values
                config.set(section, option, value)
                read = True
        except: #read failed due currupted ini file that can happen due to suddent power of during update
            print "except"
    if( read == False): #file not exist and needs to be creatred
        config = ConfigParser();
        config.add_section(section)
        config.set(section, option, value)
        read = True

    fo=open(configPath, "w+")
    config.write(fo) # Write update config

    return read
def update_configuration(section, parameter, new_value):
    config = ConfigParser()
    config.read(configuration_file)
    config.set(section, parameter, new_value)
    log("[%s] The %s variable of %s has been changed to %s" %(datetime.datetime.now(), parameter, section, new_value))
    with open(configuration_file, 'w') as configfile:
        config.write(configfile)
Example #15
0
    def create_project(harvest_version, project_name):
        package_name = project_dir = project_name

        if os.path.exists(project_dir):
            print(red('Error: project directory already exists'))
            sys.exit(1)

        if template:
            archive_url = '{0}/archive/HEAD.zip'.format(template)
            archive = 'custom-template.zip'
        else:
            archive_url = config.TEMPLATE_ARCHIVE_URL.format(harvest_version)
            archive = config.TEMPLATE_ARCHIVE.format(harvest_version)

        download = True
        if os.path.exists(archive):
            download = prompt('{0} archive already exists. Redownload? '.format(archive),
                    default='n', validate=r'^[YyNn]$').lower()
            if download == 'n':
                download = False
            else:
                os.remove(archive)

        if download:
            print(green('- Downloading Harvest @ {0}'.format(harvest_version)))
            local('wget -O "{0}" "{1}"'.format(archive, archive_url), shell='/bin/bash')

        # Expected directory name of template
        template_dir = zipfile.ZipFile(archive).namelist()[0].rstrip('/')

        # Remove existing unarchived directory
        if os.path.exists(template_dir):
            local('rm -rf {0}'.format(template_dir), shell='/bin/bash')

        with hide(*hidden_output):
            local('unzip {0}'.format(archive), shell='/bin/bash')
            local('rm -rf {0}'.format(archive), shell='/bin/bash')

        # Rename template to project name
        local('mv {0} {1}'.format(template_dir, project_dir), shell='/bin/bash')

        # Get the template's main package name
        cparser = ConfigParser()
        cparser.read(os.path.join(project_dir, config.HARVESTRC_PATH))
        old_package_name = cparser.get('harvest', 'package')

        # Replace old package name with new one
        find_replace(project_dir, old_package_name, package_name)

        # Rename package to new name
        with lcd(project_dir):
            local('mv {0} {1}'.format(old_package_name, package_name), shell='/bin/bash')

        # Set the new package name and version
        cparser.set('harvest', 'package', package_name)
        cparser.set('harvest', 'version', template_dir.split('-')[-1])

        with lcd(project_dir):
            with open(config.HARVESTRC_PATH, 'w') as rc:
                cparser.write(rc)
Example #16
0
def run_gui(input_start_page, end_page, strict):
    """ Batch cleans the pages in text/clean."""
    config = ConfigParser()
    config.read('book.cnf')
    if strict and \
        config.has_option('process', 'last_strict_page'):
        hold_page = config.getint('process', 'last_strict_page')
    elif not strict and \
        config.has_option('process', 'last_checked_page'):
        hold_page = config.getint('process', 'last_checked_page')
    else:
        hold_page = input_start_page
    print hold_page
    if input_start_page == 0:
        start_page = hold_page
    else:
        start_page = input_start_page
    lang = get_lang()
    lm = line_manager.LineManager(
        spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
        start_page,
        end_page
        )
    lm.load('text/clean')
    app = gui.main(lm, strict)
    lm.write_pages('text/clean', False)

    if strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_strict_page', app.last_page)
    elif not strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_checked_page', app.last_page)
    with open('book.cnf', 'wb') as f:
        config.write(f)
Example #17
0
def update_config(repo_file, enabled=True):
    """Enables or disables all sections in Yum config files

    :param repo_file: Config file, which should be processed
    :type repo_file: str
    :param enabled: Whether to enable or disable
    :type enabled: bool

    """
    if os.path.isfile(repo_file):
        cfg = ConfigParser()
        cfg.read([repo_file])
        save_changes = False
        for section in cfg.sections():
            if cfg.has_option(section, 'enabled'):
                save_changes = True
                if enabled:
                    cfg.set(section, 'enabled', 1)
                else:
                    cfg.set(section, 'enabled', 0)
        if save_changes:
            fd = open(repo_file, 'rwa+')
            cfg.write(fd)
            fd.close()
    else:
        pytest.fail(msg="%s was not found!" % repo_file)
Example #18
0
class SetupConfig(object):
    """Wrapper around the setup.cfg file if available.

    Mostly, this is here to cleanup setup.cfg from these settings:

    [egg_info]
    tag_build = dev
    tag_svn_revision = true
    """

    config_filename = SETUP_CONFIG_FILE

    def __init__(self):
        """Grab the configuration (overridable for test purposes)"""
        # If there is a setup.cfg in the package, parse it
        if not os.path.exists(self.config_filename):
            self.config = None
            return
        self.config = ConfigParser()
        self.config.read(self.config_filename)

    def has_bad_commands(self):
        if self.config is None:
            return False
        if not self.config.has_section('egg_info'):
            # bail out early as the main section is not there
            return False
        bad = False
        # Check 1.
        if self.config.has_option('egg_info', 'tag_build'):
            # Might still be empty.
            value = self.config.get('egg_info', 'tag_build')
            if value:
                logger.warn("%s has [egg_info] tag_build set to %r",
                            self.config_filename, value)
                bad = True
        # Check 2.
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            if self.config.getboolean('egg_info', 'tag_svn_revision'):
                value = self.config.get('egg_info', 'tag_svn_revision')
                logger.warn("%s has [egg_info] tag_svn_revision set to %r",
                            self.config_filename, value)
                bad = True
        return bad

    def fix_config(self):
        if not self.has_bad_commands():
            logger.warn("Cannot fix already fine %s.", self.config_filename)
            return
        if self.config.has_option('egg_info', 'tag_build'):
            self.config.set('egg_info', 'tag_build', '')
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            self.config.set('egg_info', 'tag_svn_revision', 'false')
        new_setup = open(self.config_filename, 'wb')
        try:
            self.config.write(new_setup)
        finally:
            new_setup.close()
        logger.info("New setup.cfg contents:")
        print ''.join(open(self.config_filename).readlines())
 def set_config(self, config):
     cp = ConfigParser()
     cp.add_section(self.DEFAULT_INI_SECTION)
     for k, v in config.items():
         cp.set(self.DEFAULT_INI_SECTION, k, v)
     with open(self.ini_file_name, "w") as f:
         cp.write(f)
Example #20
0
def load_configparser(config_file=None):
    cp = CP()
    if config_file is not None:
        config_file = resolve_file(config_file)
        if not os.path.isfile(config_file):
            es = "Could not find configuration file [%s]"
            raise ValueError(es % (config_file))
    else:
        possible_config_files = ['zdstackrc', 'zdstack.ini',
                                 '~/.zdstackrc', '~/.zdstack.ini',
                                 '~/.zdstack/zdstackrc',
                                 '~/.zdstack/zdstack.ini',
                                 '/etc/zdstackrc', '/etc/zdstack.ini',
                                 '/etc/zdstack/zdstackrc'
                                 '/etc/zdstack/zdstack.ini']
        possible_config_files = \
                        [resolve_file(x) for x in possible_config_files]
        if not [y for y in possible_config_files if os.path.isfile(y)]:
            raise ValueError("Could not find a valid configuration file")
        config_file = possible_config_files[0]
    config_fobj = StringIO(read_file(config_file))
    regexp = r'^\[(.*)\]%'
    sections = []
    for line in config_fobj.getvalue().splitlines():
        if re.match(regexp, line) and line in sections:
            es = "Duplicate section found in config: [%s]"
            raise ValueError(es % (line))
    config_fobj.seek(0)
    cp.readfp(config_fobj)
    cp.filename = config_file
    for section in cp.sections():
        cp.set(section, 'name', section)
    return cp
class NightscoutConfig(object):
    FILENAME = 'config'
    SECTION = 'NightscoutMenubar'
    HOST = 'nightscout_host'
    USE_MMOL = 'use_mmol'

    def __init__(self, app_name):
        self.config_path = os.path.join(rumps.application_support(app_name), self.FILENAME)
        self.config = ConfigParser()
        self.config.read([self.config_path])
        if not self.config.has_section(self.SECTION):
            self.config.add_section(self.SECTION)
        if not self.config.has_option(self.SECTION, self.HOST):
            self.set_host('')
        if not self.config.has_option(self.SECTION, self.USE_MMOL):
            self.set_use_mmol(False)

    def get_host(self):
        return self.config.get(self.SECTION, self.HOST)

    def set_host(self, host):
        self.config.set(self.SECTION, self.HOST, host)
        with open(self.config_path, 'w') as f:
            self.config.write(f)

    def get_use_mmol(self):
        return bool(self.config.get(self.SECTION, self.USE_MMOL))

    def set_use_mmol(self, mmol):
        self.config.set(self.SECTION, self.USE_MMOL, 'true' if mmol else '')
        with open(self.config_path, 'w') as f:
            self.config.write(f)
def configure_manager(manager_config_path,
                      manager_config):
    '''Sets config defaults and creates the config file'''
    _, temp_config = tempfile.mkstemp()
    config = ConfigParser()

    config.add_section('Credentials')
    config.set('Credentials', 'subscription_id',
               manager_config['subscription_id'])
    config.set('Credentials', 'tenant_id',
               manager_config['tenant_id'])
    config.set('Credentials', 'client_id',
               manager_config['client_id'])
    config.set('Credentials', 'client_secret',
               manager_config['client_secret'])

    config.add_section('Azure')
    config.set('Azure', 'location',
               manager_config['location'])

    with open(temp_config, 'w') as temp_config_file:
        config.write(temp_config_file)

    fabric.api.sudo('mkdir -p {0}'.
                    format(os.path.dirname(manager_config_path)))
    fabric.api.put(temp_config,
                   manager_config_path,
                   use_sudo=True)
    def write_ini_config_file(self, command, data, client):
        """\
        Write the new command configuration in the plugin configuration file
        """
        try:

            # read the config file
            config = ConfigParser()
            config.read(command.plugin.config.fileName)

            # if there is no commands section
            if not config.has_section('commands'):
                raise NoSectionError('could not find <commands> section in '
                                     'plugin <%s> config file' % data['plugin_name'])

            # remove the old entry
            found = False
            for temp in config.options('commands'):
                search = temp.split('-')[0]
                if search == command.command:
                    config.remove_option('commands', temp)
                    found = True

            # set the new command option value
            config.set('commands', data['command_name'], data['command_level'])
            self.debug('%s command <%s> in plugin <%s> config file' % ('updated' if found else 'created new entry for',
                                                                       command.command, data['plugin_name']))

            # write the updated configuration file
            with open(command.plugin.config.fileName, 'wb') as configfile:
                config.write(configfile)

        except (IOError, NoSectionError), e:
            self.warning('could not change plugin <%s> config file: %s' % (data['plugin_name'], e))
            client.message('^7could not change plugin ^1%s ^7config file' % data['plugin_name'])
Example #24
0
class RedirectConfig:
    def __init__(self, filename):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        self.logger = logger.get_logger('insider.RedirectConfig')

    def update(self, domain, api_url):
        self.logger.info('settig domain={0}, api_url={1}'.format(domain, api_url))
        if not self.parser.has_section('redirect'):
            self.parser.add_section('redirect')

        self.parser.set('redirect', 'domain', domain)
        self.parser.set('redirect', 'api_url', api_url)
        self._save()

    def get_domain(self):
        return self.parser.get('redirect', 'domain')

    def get_api_url(self):
        return self.parser.get('redirect', 'api_url')

    def _save(self):
        self.logger.info('saving config={0}'.format(self.filename))
        with open(self.filename, 'wb') as file:
            self.parser.write(file)
    def initConfig(self):
        kate.debug("initConfig()")
        config_path = kate.pate.pluginDirectories[1] + "/%s/%s.conf" % (__name__, __name__)
        config_file = QFileInfo(config_path)

        if not config_file.exists():
            open(config_path, "w").close()

        config = ConfigParser()
        config.read(config_path)

        # init the DEFAULT options if they don't exist
        # the DEFAULT section is special and doesn't need to be created: if not config.has_section('DEFAULT'): config.add_section('DEFAULT')
        if not config.has_option("DEFAULT", "ignore"):
            config.set("DEFAULT", "ignore", "")
        if not config.has_option("DEFAULT", "filter"):
            config.set("DEFAULT", "filter", "*")
        if not config.has_option("DEFAULT", "finder_size"):
            config.set("DEFAULT", "finder_size", "400x450")
        if not config.has_option("DEFAULT", "config_size"):
            config.set("DEFAULT", "config_size", "300x350")
        if not config.has_option("DEFAULT", "search_type"):
            config.set("DEFAULT", "search_type", "word")

        # create the general section if it doesn't exist
        if not config.has_section("general"):
            config.add_section("general")

        # flush the config file
        config.write(open(config_path, "w"))

        # save the config object and config path as instance vars for use later
        self.config = config
        self.config_path = config_path
Example #26
0
class InsiderConfig:

    def __init__(self, filename):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        self.redirect_config = RedirectConfig(join(dirname(filename), 'redirect.cfg'))
        self.logger = logger.get_logger('insider.InsiderConfig')

    def _save(self):
        self.logger.info('saving config={0}'.format(self.filename))
        with open(self.filename, 'wb') as file:
            self.parser.write(file)

    def update(self, domain, api_url):
        self.redirect_config.update(domain, api_url)

    def get_redirect_api_url(self):
        return self.redirect_config.get_api_url()

    def get_redirect_main_domain(self):
        return self.redirect_config.get_domain()

    def get_cron_period_mins(self):
        return self.parser.getint('cron', 'period_mins')

    def is_upnpc_mock(self):
        return self.parser.getboolean('upnpc', 'mock')

    def set_upnpc_mock(self, enable):
        if not self.parser.has_section('upnpc'):
            self.parser.add_section('upnpc')
        self.parser.set('upnpc', 'mock', enable)
        self._save()
Example #27
0
def startSetup():
    config = ConfigParser()
    moduleList = listdir("modules")

    config.add_section("global")
    value = raw_input("Enter the JSON root folder to write the json files too : ")
    if value[-1] != "/":
        value += "/"
    config.set("global", "jsonRoot", value)

    modulesConfig = []

    for module in moduleList:
        if module == "__init__.py" or module[-3:] != ".py":
            continue
        loadedModule = __import__("modules." + module[:-3], fromlist=["*"])
        moduleConfig = loadedModule.startConfig(config)
        modulesConfig.append(moduleConfig)

    modulesConfigDict = {}
    modulesConfigDict["moduleList"] = modulesConfig
    configString = json.dumps(modulesConfigDict)
    modulesFile = open(config.get("global", "jsonRoot") + "modules.json", "w")
    modulesFile.write(configString)
    modulesFile.close()

    configFile = open("server.cfg", "w")
    config.write(configFile)
    configFile.close()
Example #28
0
class RepoConfig(object):
    '''
    This class provides an abstraction around repository configuration files
    '''

    def __init__(self, path):
        '''
        :param path:    Plumbum path to the repository
        '''
        self._config = ConfigParser()
        self._path = path / '.hg' / 'hgrc'
        if self._path.exists():
            self._config.readfp(self._path.open())
        else:
            self._config.add_section('paths')

    def AddRemote(self, name, destination):
        '''
        Adds a remote to the config, or overwrites if it already exists

        :param name:        The name of the remote
        :param destination: The destination path of the remote
        '''
        self._config.set('paths', name, destination)
        self._config.write(self._path.open('w'))

    @property
    def remotes(self):
        '''
        Property to get a dictionary of remotes
        '''
        return dict(self._config.items('paths'))
Example #29
0
    def write_last_synced(self, _value, _job, _new, _smb_connection=None):
        """
        Write _value to the last_synced property of the destination status file
        :param _value: The value to write
        :param _job: A SyncJob instance
        :param _new: If there isn't already a history-section
        :param _smb_connection: An SMB connection.
        :return:
        """
        if _new is None:
            if _smb_connection is not None:
                _file_obj = read_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'))
            else:
                try:
                    _file_obj = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r")
                except IOError:
                    pass
        else:
            _file_obj = StringIO.StringIO()

        _cfg = ConfigParser()
        _cfg.readfp(_file_obj)
        if _new is not None:
            _cfg.add_section("history")

        _cfg.set("history", "last_synced", _value)
        _cfg.write(_file_obj)

        if _smb_connection is not None:
            write_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'), _file_obj)
        else:
            try:
                _file = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r")
            except IOError:
                pass
Example #30
0
class Playlist(object):
  def __init__(self, location):
    dir = os.path.expanduser(os.path.dirname(location))
    if not os.path.exists(dir):
      os.makedirs(dir)

    self._config = ConfigParser()
    self._config.optionxform = str

    self._file = os.path.expanduser(location)
    if os.path.exists(self._file):
      self._config.read(self._file)
    else:
      self._config.add_section('Playlist')
      self.save()

  def save(self):
    self._config.write(open(self._file, 'wb'))

  def append(self, item):
    self._config.set('Playlist', *item)
    self.save()

  def remove(self, option):
    self._config.remove_option('Playlist', option)
    self.save()

  def __getitem__(self, item):
    return self._config.items('Playlist')[item]

  def __iter__(self):
    return iter(self._config.items('Playlist'))