show archive config differences <base_file> <new_file>.

        Default operation is to compare system:running-config to self.candidate_cfg
172604
def compare_config(self):
        
        # Set defaults
        base_file = "running-config"
        base_file_system = "system:"
        if self.config_replace:
            new_file = self.candidate_cfg
        else:
            new_file = self.merge_cfg
        new_file_system = self.dest_file_system

        base_file_full = self._gen_full_path(
            filename=base_file, file_system=base_file_system
        )
        new_file_full = self._gen_full_path(
            filename=new_file, file_system=new_file_system
        )

        if self.config_replace:
            cmd = "show archive config differences {} {}".format(
                base_file_full, new_file_full
            )
            diff = self.device.send_command_expect(cmd)
            diff = self._normalize_compare_config(diff)
        else:
            # merge
            cmd = "show archive config incremental-diffs {} ignorecase".format(
                new_file_full
            )
            diff = self.device.send_command_expect(cmd)
            if "error code 5" in diff or "returned error 5" in diff:
                diff = (
                    "You have encountered the obscure 'error 5' message. This generally "
                    "means you need to add an 'end' statement to the end of your merge changes."
                )
            elif "% Invalid" not in diff:
                diff = self._normalize_merge_diff_incr(diff)
            else:
                cmd = "more {}".format(new_file_full)
                diff = self.device.send_command_expect(cmd)
                diff = self._normalize_merge_diff(diff)

        return diff.strip()
659194
def load_merge_candidate(self, filename=None, config=None):
        """"""
        self.config_replace = False
        self._load_candidate(filename, config, False)
437276
def jiggle_config_file(self):  # type: () ->int
        
        changed = 0
        # setup.py related. setup.py itself should read __init__.py or __version__.py

        other_files = ["setup.cfg"]

        for file_name in other_files:
            filepath = os.path.join(self.SRC, file_name)

            # only create setup.cfg if we have setup.py
            if (
                self.create_configs
                and not os.path.isfile(filepath)
                and os.path.isfile("setup.py")
            ):
                logger.info("Creating " + unicode(filepath))
                self.file_maker.create_setup_cfg(filepath)

            if os.path.isfile(filepath):
                config = configparser.ConfigParser()
                config.read(filepath)
                try:
                    version = config["metadata"]["version"]
                except KeyError:
                    version = ""
                if version:
                    with io.open(filepath, "w") as configfile:  # save
                        config["metadata"]["version"] = unicode(self.version_to_write())
                        config.write(configfile)
                        changed += 1
        return changed
448372
def command_new_config(self):
        
        if len(self.args) == 1 and self.args[0] == "new-config":
            NewConfig().run()
        else:
            usage("")
823470
def register_config_changes(self, configs, meta_changes):
        
        for config_file in meta_changes['remove_configs'].keys():
            self._purge_config_file(config_file)
        for config_file, config in configs.items():
            if 'update_attribs' in config:
                config['attribs'] = config.pop('update_attribs')
            if 'update_instance_name' in config:
                config['instance_name'] = config.pop('update_instance_name')
            if 'update_services' in config or 'remove_services' in config:
                remove = config.pop('remove_services', [])
                services = config.pop('update_services', [])
                # need to prevent old service defs from overwriting new ones
                for service in config['services']:
                    if service not in remove and service not in services:
                        services.append(service)
                config['services'] = services
            self._register_config_file(config_file, config)
810628
def edit(self):
        
        if platform.system().lower() == 'windows':
            os.startfile(str(self.config_file))
        else:
            if platform.system().lower() == 'darwin':
                call = 'open'
            else:
                call = 'xdg-open'
            subprocess.call([call, self.config_file])
1193913
private function compareConfigFile()
    {
        $cachePath = INITIALLY_RPC_ROOT_PATH . "/src";
        $cacheFile = $cachePath . "/info.cache";
        Util::createDirIfNotExists($cachePath);
        $configSha1 = sha1_file($this->configFile);
        if (!is_file($cacheFile)) {
            if (!@file_put_contents($cacheFile, $configSha1)) {
                throw new InitiallyRpcException("write config file md5 failed");
            }

            $oldConfigSha1 = $configSha1;
        } else {
            $oldConfigSha1 = file_get_contents($cacheFile);
            if ($configSha1 != $oldConfigSha1 && !@file_put_contents($cacheFile, $configSha1)) {
                throw new InitiallyRpcException("write config file md5 failed");
            }
        }

        return $configSha1 == $oldConfigSha1;
    }
1170859
def run_configurations(callback, sections_reader):
    """"""
    base = dict(OPTIONS)
    sections = sections_reader()
    if sections is None:
        logger.info("Configuration not found in .ini files. "
                    "Running with default settings")
        recompile()
    elif sections == []:
        logger.info("Configuration does not match current runtime. "
                    "Exiting")
    results = []
    for section, options in sections:
        OPTIONS.clear()
        OPTIONS.update(base)
        OPTIONS.update(options)
        logger.debug("Running configuration from section \"%s\". OPTIONS: %r",
                     section, OPTIONS)
        results.append(callback())
    return results
156920
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None):
    
    with open(from_file) as from_stream:
        with open(to_file) as to_stream:
            from_records = records.load(from_stream, sep=sep)
            to_records = records.load(to_stream, sep=sep)
            return patch.create(from_records, to_records, index_columns,
                                ignore_columns=ignored_columns)
425298
def sym_reads_new_config(self, newDir, sym=False, mv=False):
        """"""
        newParams = copy.copy(self)
        for i in range(0,len(self.params["lib_seq"])):
            lib_seq = self.params["lib_seq"][i]
            #update the glob
            newParams.params["lib_seq"][i]["globs"] = [os.path.join(
                newDir,os.path.basename(x)) for x in lib_seq["globs"]]
            #now update the file paths and move/symlink if necessary
            for j in range(0, len(lib_seq["pairs"])):
                forward, reverse = lib_seq["pairs"][j]
                new_forward = os.path.join(newDir, os.path.basename(forward))
                new_reverse = os.path.join(newDir, os.path.basename(reverse))
                #move or symlink the files
                if sym:
                    for each in [new_forward, new_reverse]:
                        if os.path.exists(each):
                            raise ValueError("""Attempted to make a symlink for
                            a reads file, but it already exists. Chances are
                            that you used the same reads for two lines in the
                            Meraculous config file""")
                    os.symlink(forward, new_forward)
                    os.symlink(reverse, new_reverse)
                #update the reads in the new config
                newParams.params["lib_seq"][i]["pairs"][j] = [new_forward, new_reverse]
        return newParams
689799
def find_new(self):
        
        print("\nSearch for .new configuration files:\n")
        for path, dirs, files in os.walk(self.etc):
            del dirs    # delete unsed
            for f in files:
                if f.endswith(".new"):
                    self.news.append(os.path.join(path, f))
        if not self.news:
            print("  No new configuration files\n")
            raise SystemExit()
182729
def main(config_file):
    """"""

    if not (os.path.exists(config_file) and os.path.isfile(config_file)):
        msg = "Missing or invalid config file {0}".format(config_file)
        raise ValueError(msg)

    print("Loading config file {0}.".format(config_file))

    # Use the appropriate network driver to connect to the device:
    driver = napalm.get_network_driver("eos")

    # Connect:
    device = driver(
        hostname="127.0.0.1",
        username="vagrant",
        password="vagrant",
        optional_args={"port": 12443},
    )

    print("Opening ...")
    device.open()

    print("Loading replacement candidate ...")
    device.load_replace_candidate(filename=config_file)

    # Note that the changes have not been applied yet. Before applying
    # the configuration you can check the changes:
    print("\nDiff:")
    print(device.compare_config())

    # You can commit or discard the candidate changes.
    try:
        choice = raw_input("\nWould you like to commit these changes? [yN]: ")
    except NameError:
        choice = input("\nWould you like to commit these changes? [yN]: ")
    if choice == "y":
        print("Committing ...")
        device.commit_config()
    else:
        print("Discarding ...")
        device.discard_config()

    # close the session with the device.
    device.close()
    print("Done.")
561069
def load_cfg(self, src_dir):
        

        # last files override previous ones
        cfg_files = [os.path.expanduser(USER_CFG_FILE),
                     os.path.abspath(os.path.join(src_dir, '.dirsync'))]

        cfg = ConfigParser()
        cfg.read(cfg_files)

        if not cfg.has_section('defaults'):
            return

        defaults = {}
        for name, val in cfg.items('defaults'):
            try:
                opt = OPTIONS[name][1]
            except KeyError:
                if name == 'action':
                    if val in OPTIONS:
                        defaults['action'] = val
                    else:
                        raise ValueError('Invalid value for "action" option '
                                         'in configuration file: %s' % val)
                continue

            curdef = opt.get('default', '')
            if isinstance(curdef, bool):
                newdef = val not in ('0', 'False', 'false')
            elif isinstance(curdef, string_types):
                newdef = val
            else:
                newdef = val.strip('\n').split('\n')

            defaults[name] = newdef

        self.set_defaults(**defaults)
786930
def get_config(basedir, files):
    
    config_details = config.find(
        basedir, files,
        environment.Environment.from_env_file(basedir))

    return config.load(config_details)
1310558
def build_config(config_file=get_system_config_directory()):
    
    config = Config(config_file, allow_no_value=True)
    application_versions = find_applications_on_system()

    # Add found versions to config if they don't exist. Versions found
    # in the config file takes precedence over versions found in PATH.
    for item in application_versions.iteritems():
        if not config.has_option(Config.EXECUTABLES, item[0]):
            config.set(Config.EXECUTABLES, item[0], item[1])
    return config
1251107
def record_diff(old, new):
    
    return '\n'.join(difflib.ndiff(
        ['%s: %s' % (k, v) for op in old for k, v in op.items()],
        ['%s: %s' % (k, v) for op in new for k, v in op.items()],
    ))
453443
def _get_diff(self, cp_file):
        """"""
        diff = []
        self._create_sot_file()
        diff_out = self.device.show(
            'show diff rollback-patch file {0} file {1}'.format(
                'sot_file', self.replace_file.split('/')[-1]), raw_text=True)
        try:
            diff_out = diff_out.split(
                '#Generating Rollback Patch')[1].replace(
                    'Rollback Patch is Empty', '').strip()
            for line in diff_out.splitlines():
                if line:
                    if line[0].strip() != '!':
                        diff.append(line.rstrip(' '))
        except (AttributeError, KeyError):
            raise ReplaceConfigException(
                'Could not calculate diff. It\'s possible the given file doesn\'t exist.')
        return '\n'.join(diff)