Run the check on files of the added version.

    They might be different than the one on disk. Equivalent than doing a git
    stash, check, and git stash pop.
971228
def _pre_commit(files, options):
    
    errors = []
    tmpdir = mkdtemp()
    files_to_check = []
    try:
        for (file_, content) in files:
            # write staged version of file to temporary directory
            dirname, filename = os.path.split(os.path.abspath(file_))
            prefix = os.path.commonprefix([dirname, tmpdir])
            dirname = os.path.relpath(dirname, start=prefix)
            dirname = os.path.join(tmpdir, dirname)
            if not os.path.isdir(dirname):
                os.makedirs(dirname)
            filename = os.path.join(dirname, filename)
            with open(filename, "wb") as fh:
                fh.write(content)
            files_to_check.append((file_, filename))

        for (file_, filename) in files_to_check:
            errors += list(map(lambda x: "{0}: {1}".format(file_, x),
                               check_file(filename, **options) or []))
    finally:
        shutil.rmtree(tmpdir, ignore_errors=True)

    return errors
467369
def check_repo_ok(self):
        
        from git import Repo, exc
        # Check that git is at the expected commit and that the repo is not
        # dirty
        if self.runner is not None:
            path = self.runner.path
            try:
                repo = Repo(path)
            except(exc.InvalidGitRepositoryError):
                raise Exception("No git repository detected.\nIn order to "
                                "use SEM and its reproducibility enforcing "
                                "features, please create a git repository at "
                                "the root of your ns-3 project.")
            current_commit = repo.head.commit.hexsha
            campaign_commit = self.db.get_commit()

            if repo.is_dirty(untracked_files=True):
                raise Exception("ns-3 repository is not clean")

            if current_commit != campaign_commit:
                raise Exception("ns-3 repository is on a different commit "
                                "from the one specified in the campaign")
1183876
def ask_run_new_file(new_file_path, source_path, tmp)
      return if tmp && IRT.rails_server
      original_ask_run_new_file(new_file_path, source_path, tmp)
    end
737343
function isExist(filename) {
    try {
        fs.accessSync(filename, fs.R_OK);
        return true;
    } catch (e) {
        return false;
    }
}
185642
def update_version_file(version)
      if File.exists?('VERSION')
        File.open('VERSION', 'w') { |f| f << version.to_s }
        modified_files << 'VERSION'
      end
    end
584457
def get_git_version(path):
    """"""
    branch_name = get_git_cleaned_branch_name(path)
    # Determine whether working copy is dirty (i.e. contains modified files)
    mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
    dirty = '.dirty' if mods else ''
    # Get a list of all commits on branch, with corresponding branch/tag refs
    # Each line looks something like: "d3e4d42 (HEAD, master, tag: v0.1)"
    git_output = run_cmd(path, 'git', 'log', '--pretty="%h%d"')
    commits = git_output.strip().replace('"', '').split('\n')
    num_commits_since_branch = len(commits)
    # Short hash of the latest commit
    short_commit_name = commits[0].partition(' ')[0]
    # A valid version is sequence of dotted numbers optionally prefixed by 'v'
    valid_version = re.compile(r'^v?([\.\d]+)$')

    def tagged_version(commit):
        """First tag on commit that is valid version, as a list of numbers."""
        refs = commit.partition(' ')[2]
        for ref in refs.lstrip('(').rstrip(')').split(', '):
            if ref.startswith('tag: '):
                tag = ref[5:].lower()
                found = valid_version.match(tag)
                if found:
                    return [int(v) for v in found.group(1).split('.') if v]
        return []
    # Walk back along branch and find first valid tagged version (or use 0.0)
    for commit in commits:
        version_numbers = tagged_version(commit)
        if version_numbers:
            break
    else:
        version_numbers = [0, 0]
    # It is a release if current commit has a version tag (and dir is clean)
    release = (commit == commits[0]) and not dirty
    if not release:
        # We are working towards the next (minor) release according to PEP 440
        version_numbers[-1] += 1
    version = '.'.join([str(v) for v in version_numbers])
    if not release:
        # Development version contains extra embellishments
        version = ("%s.dev%d+%s.%s%s" % (version, num_commits_since_branch,
                                         branch_name, short_commit_name, dirty))
    return version
120970
def checkin(url, files, message=None):
    
    from grit import Repo, Item
    r = Repo(url)

    if not files:
        raise GritError('No files')

    def _write(path):
        item = Item.from_path(repo=r, path=path)
        if r.isLocal():
            v.addItem(item=item)
        else:
            r.upload(filename=os.path.basename(path), filedata=open(path, 'r').read())

    if r.isLocal():
        v = r.addVersion()
    count = 1
    total = len(files) 
    while count <= total:
        print '[%s/%s] %0.2f%%' %(count, total, (float(count) / total) * 100), '*'*count, '\r',
        _write(os.path.abspath(files[count-1]))
        count += 1
        sys.stdout.flush()
    if message is None:
        message = 'Publishing %s' % ', '.join(files)
    if r.isLocal():
        v.save(message=message)
    print
58483
def check_version(server, version, filename, timeout=SHORT_TIMEOUT):
    """"""

    address = VERSION_ENDPOINT.format(server=server)

    print('Checking for software updates...')
    log.info('Existing OK version: %s', version)
    log.info('Checking latest version from %s', address)

    try:
        response = requests.get(address, timeout=timeout)
        response.raise_for_status()
    except (requests.exceptions.RequestException, requests.exceptions.BaseHTTPError) as e:
        print('Network error when checking for updates.')
        log.warning('Network error when checking version from %s: %s', address,
                    str(e), stack_info=True)
        return False

    response_json = response.json()
    if not _validate_api_response(response_json):
        print('Error while checking updates: malformed server response')
        log.info('Malformed response from %s: %s', address, response.text)
        return False

    current_version = response_json['data']['results'][0]['current_version']
    if current_version == version:
        print('OK is up to date')
        return True

    download_link = response_json['data']['results'][0]['download_link']

    log.info('Downloading version %s from %s', current_version, download_link)

    try:
        response = requests.get(download_link, timeout=timeout)
        response.raise_for_status()
    except (requests.exceptions.RequestException, requests.exceptions.BaseHTTPError) as e:
        print('Error when downloading new version of OK')
        log.warning('Error when downloading new version of OK: %s', str(e),
                    stack_info=True)
        return False

    log.info('Writing new version to %s', filename)

    zip_binary = response.content
    try:
        _write_zip(filename, zip_binary)
    except IOError as e:
        print('Error when downloading new version of OK')
        log.warning('Error writing to %s: %s', filename, str(e))
        return False
    else:
        print('Updated to version: {}'.format(current_version))
        log.info('Successfully wrote to %s', filename)
        return True
304752
def check_version(self, check, timeout=None, metadata=None,
                      credentials=None):
        """"""
        return self.stub.CheckVersion(check, timeout=timeout,
                                      metadata=metadata,
                                      credentials=credentials)
280342
def do_update
      # note that a recent fetch was performed by remote_differs? and even if
      # remotes have changed again in the brief interim it would invalidate
      # the decisions already made if we refetched now.
      git_repo = git_repo_for(@repo_dir)
      @logger.operation(:cleanup, "ensure no untracked files in #{@repo_dir}") do
        git_repo.hard_reset_to(nil)
        do_clean_all(git_repo)
      end
      do_checkout_revision(git_repo)
      do_clean_all(git_repo)  # clean again once we are on requested revision
      internal_update_tag(git_repo)
      true
    end
1240250
public function checkUpdate()
    {
        $this->log->addNotice('Checking for a new update...');

        // Reset previous updates
        $this->latestVersion = '0.0.0';
        $this->updates = [];

        $versions = $this->cache->get('update-versions');

        // Create absolute url to update file
        $updateFile = $this->updateUrl . '/' . $this->updateFile;
        if (!empty($this->branch)) {
            $updateFile .= '.' . $this->branch;
        }

        // Check if cache is empty
        if ($versions === null || $versions === false) {
            $this->log->addDebug(sprintf('Get new updates from %s', $updateFile));

            // Read update file from update server
            if (function_exists('curl_version') && $this->_isValidUrl($updateFile)) {
                $update = $this->_downloadCurl($updateFile);

                if ($update === false) {
                    $this->log->addError(sprintf('Could not download update file "%s" via curl!', $updateFile));

                    throw new DownloadException($updateFile);
                }
            } else {
                // TODO: Throw exception on error
                $update = @file_get_contents($updateFile, false, $this->_useBasicAuth());

                if ($update === false) {
                    $this->log->addError(sprintf('Could not download update file "%s" via file_get_contents!', $updateFile));

                    throw new DownloadException($updateFile);
                }
            }

            // Parse update file
            $updateFileExtension = substr(strrchr($this->updateFile, '.'), 1);
            switch ($updateFileExtension) {
                case 'ini':
                    $versions = parse_ini_string($update, true);
                    if (!is_array($versions)) {
                        $this->log->addError('Unable to parse ini update file!');

                        throw new ParserException;
                    }

                    $versions = array_map(function ($block) {
                        return isset($block['url']) ? $block['url'] : false;
                    }, $versions);

                    break;
                case 'json':
                    $versions = (array)json_decode($update);
                    if (!is_array($versions)) {
                        $this->log->addError('Unable to parse json update file!');

                        throw new ParserException;
                    }

                    break;
                default:
                    $this->log->addError(sprintf('Unknown file extension "%s"', $updateFileExtension));

                    throw new ParserException;
            }

            $this->cache->set('update-versions', $versions);
        } else {
            $this->log->addDebug('Got updates from cache');
        }

        if (!is_array($versions)) {
            $this->log->addError(sprintf('Could not read versions from server %s', $updateFile));

            return false;
        }

        // Check for latest version
        foreach ($versions as $version => $updateUrl) {
            if (Comparator::greaterThan($version, $this->currentVersion)) {
                if (Comparator::greaterThan($version, $this->latestVersion)) {
                    $this->latestVersion = $version;
                }

                $this->updates[] = [
                    'version' => $version,
                    'url' => $updateUrl,
                ];
            }
        }

        // Sort versions to install
        usort($this->updates, function ($a, $b) {
            if (Comparator::equalTo($a['version'], $b['version'])) {
                return 0;
            }

            return Comparator::lessThan($a['version'], $b['version']) ? -1 : 1;
        });

        if ($this->newVersionAvailable()) {
            $this->log->addDebug(sprintf('New version "%s" available', $this->latestVersion));

            return true;
        } else {
            $this->log->addDebug('No new version available');

            return self::NO_UPDATE_AVAILABLE;
        }
    }
904151
def check_local_install(ctx, version, ext, server="local"):
    
    here = Path(ctx.releaser.here).resolve()
    dist_dir = here / 'dist'

    all_files = list(dist_dir.glob('*.{}'.format(ext)))
    the_file = all_files[0]
    for f in all_files[1:]:
        if f.stat().st_mtime > the_file.stat().st_mtime:
            the_file = f
            # this is the latest generated file of the given version

    environment = 'env-{}-{}-{}'.format(version, ext, server)
    if server == "local":
        pass
    else:
        # upload to server
        print("** Uploading to server **")
        cmd = 'twine upload {}'.format(the_file)
        # for PyPI, let twine pick the server
        if server != "pypi":
            cmd = cmd + ' -r {}'.format(server)
        result = invoke.run(cmd, warn=True)
        if result.failed:
            print(textwrap.fill("[{}ERROR{}] Something broke trying to upload "
                                "your package. This will be the case if you "
                                "have already uploaded it before. To upload "
                                "again, use a different version number "
                                "(or a different build by including a '+' "
                                "suffix to your version number)."
                                .format(ERROR_COLOR, RESET_COLOR),
                                width=text.get_terminal_size().columns - 1,
                                subsequent_indent=' '*8))
            # print(result.stderr)

    # remove directory if it exists
    if (here / 'env' / environment).exists():
        shutil.rmtree('env' + os.sep + environment)
    invoke.run('python -m venv env{}{}'.format(os.sep, environment))
    other_dependencies(ctx, server, environment)
    if server == "local":
        result = invoke.run('env{0}{1}{0}Scripts{0}pip{2} install {3} --no-cache'
                            .format(os.sep, environment, '.exe', the_file),
                            hide=True)
    else:
        #print("  **Install from server**")
        result = invoke.run('env{0}{1}{0}Scripts{0}pip{2} install -i {3} '
                            '{4}=={5} --no-cache'
                            .format(os.sep, environment, '.exe',
                                    server_url(server),
                                    ctx.releaser.module_name, version),
                            hide=True)
        if result.failed:
            print('[{}ERROR{}] Something broke trying to install your package.'
                  .format(ERROR_COLOR, RESET_COLOR))
            print(result.stderr)
            sys.exit(1)
    print("** Test version of installed package **")

    result = invoke.run('env{0}{1}{0}Scripts{0}python{2} -c '
                        'exec("""import {3}\\nprint({3}.__version__)""")'
                        .format(os.sep, environment, '.exe',
                                (ctx.releaser.module_name).strip()))
    test_version = result.stdout.strip()
    # print(test_version, type(test_version), type(expected_version))
    if Version(test_version) == version:
        results = '{}{} install {} works!{}'.format(GOOD_COLOR, server, ext,
                                                    RESET_COLOR)
    else:
        results = '{}{} install {} broken{}'.format(ERROR_COLOR, server, ext,
                                                    RESET_COLOR)
    print(results)
    return results
1067544
function checkRequirements () {
      // Check if git version meets requirements
      var gitVersion = (shelljs.exec('git --version', {silent: true}).output.match(/\d+\.\d+\.\d+/) || []).shift();
      if (!gitVersion || semver.lt(gitVersion, '1.8.0')) {
        throw('Current Git version is ' + gitVersion + '. This plugin requires Git >= 1.8.0.');
      }

      // Check that build directory exists
      if (!fs.existsSync(options.dir)) {
        throw('Build directory "' + options.dir + '" doesn\'t exist. Nothing to version.');
      }

      // Check that build directory conteins files
      if (fs.readdirSync(options.dir).length === 0) {
        throw('Build directory "' + options.dir + '" is empty. Nothing to version.');
      }

      // If connectCommits is true check that the main project's working
      // directory is clean
      if (options.connectCommits) {
        var gitDiffOutput = shelljs.exec('git diff').output;
        if (gitDiffOutput !== '') {
          throw ('There are uncommitted changes in your working directory. \n' +
          'Please commit changes to the main project before you commit to \n' +
          'the built code.\n');
        }
      }

      if (options.shallowFetch && semver.lt(gitVersion, '1.9.0')) {
        throw('Current Git version is ' + gitVersion + '. Option "shallowFetch" is supported on Git >= 1.9.0.');
      }
    }
1302774
def check_update(ctx, forced=False):
    
    try:
        if ctx.update_checked and not forced:
            return
    except AttributeError:
        update_check_file = os.path.join(dir_path, 'update_check.txt')
        today = datetime.date.today().strftime("%m/%d/%Y")
        if os.path.exists(update_check_file):
            date = open(update_check_file, 'r').read()
        else:
            date = []
        if forced or today != date:
            ctx.update_checked = True
            date = today
            with open(update_check_file, 'w') as f:
                f.write(date)
            r = requests.get("https://pypi.org/pypi/keep/json").json()
            version = r['info']['version']
            curr_version = about.__version__
            if version > curr_version:
                click.secho("Keep seems to be outdated. Current version = "
                            "{}, Latest version = {}".format(curr_version, version) +
                            "\n\nPlease update with ", bold=True, fg='red')
                click.secho("\tpip3 --no-cache-dir install -U keep==" + str(version), fg='green')
                click.secho("\n\n")
752964
def run(self):
        
        if (self.repo in self.meta.default_repositories and
                self.repo in self.meta.repositories):
            try:
                self.check = self.all_repos[self.repo]()
            except OSError:
                usage(self.repo)
                raise SystemExit()
        elif self.repo in self.meta.repositories:
            self.check = self._init.custom(self.repo)
        else:
            usage(self.repo)
            raise SystemExit()
        self.status_bar()
        self.status()
        self.print_status(self.repo)
        self.summary()
1347542
def run(self):
        
        args = {"remote": self.remote, "branch": self.branch}
        cmdl = "git pull --ff-only {remote:s} {branch:s}".format(**args)
        try:
            check_call(cmdl.split())
        except CalledProcessError:
            raise SystemExit(1)
        log.info("package version is now {:s}".format(version()))
        return
926808
def check_version(ctx, param, value):
    """"""
    if ctx.resilient_parsing:
        return

    if not value and ctx.invoked_subcommand != 'run':
        ctx.call_on_close(_check_version)