Create a map from component to version number, based on GitHub directory
structure.
484377
async function updateComponentMap() {
  const response = await fetch(GITHUB_AMPHTML_TREE_URL);
  const data = await response.json();
  const pairs = data.tree.map((item) => item.path.match(REGEX_EXTENSION_DIR))
                  .filter((match) => match && !match[1].endsWith('impl'))
                  .map((match) => [match[1], match[2]]);
  const versionMap = {};
  pairs.forEach((pair) => {
    if (!versionMap[pair[0]] || versionMap[pair[0]] < pair[1]) {
      versionMap[pair[0]] = pair[1];
    }
  });
  writeComponentsMap(COMPONENTS_MAP_PATH, versionMap);
}
548538
def versions(self, rev=None, index=None):
        """"""
        raise NotImplementedError
        _revisions = [line.split()[0] for line in self.log.split('\n') if line]
        _versions = [Version(self.obj.repo.commit(r)) for r in _revisions if rev is None or r.startswith(rev)]
        if index is not None and len(_versions) > index:
            _versions = _versions[index]
        return _versions
1046606
def create_version(self, project_id_or_key, version_name, extra_request_params={}):
        
        request_params = extra_request_params
        request_params["name"] = version_name
        return self.do("POST", "projects/{project_id_or_key}/versions",
                       url_params={"project_id_or_key": project_id_or_key},
                       request_params=request_params,
                       )
767729
def bump_version(version, bump='patch'):
    """"""
    try:
        parts = map(int, version.split('.'))
    except ValueError:
        fail('Current version is not numeric')

    if bump == 'patch':
        parts[2] += 1
    elif bump == 'minor':
        parts[1] += 1
        parts[2] = 0
    elif bump == 'major':
        parts[0] +=1
        parts[1] = 0
        parts[2] = 0

    return '.'.join(map(str, parts))
289919
def bump_repos_version(module_name, new_version, local_only):
    
    # Make the cloning directory and change directories into it.
    tmp_dir = tempfile.mkdtemp(dir=os.getcwd())

    # Iterate through each repository.
    for owner, repo_name in REPOS_TO_CHANGE:
        repo_url = REPO_URL_FORMAT.format(owner, repo_name)

        gh = GitHubApiUtils(owner, repo_name)

        os.chdir(tmp_dir)

        # Clone the repo.
        ret_code = subprocess.call(['git', 'clone', '{}.git'.format(repo_url)])
        if ret_code:
            logging.error('Failed to clone repo {}'.format(repo_url))
            continue

        # Change into the cloned repo dir.
        os.chdir(repo_name)

        # Create a branch, using the version number.
        branch_name = '{}/{}'.format(module_name, new_version)
        ret_code = subprocess.call(['git', 'checkout', '-b', branch_name])
        if ret_code:
            logging.error('Failed to create branch in repo {}'.format(repo_url))
            continue

        # Search through all TXT files to find all lines with the module name, changing the pinned version.
        files_changed = False
        for root, _dirs, files in os.walk('.'):
            for file in files:
                if file.endswith('.txt') and (('requirements' in file) or ('requirements' in root)):
                    found = False
                    filepath = os.path.join(root, file)
                    with open(filepath) as f:
                        if '{}=='.format(module_name) in f.read():
                            found = True
                    if found:
                        files_changed = True
                        # Change the file in-place.
                        for line in fileinput.input(filepath, inplace=True):
                            if '{}=='.format(module_name) in line:
                                print '{}=={}'.format(module_name, new_version)
                            else:
                                print line,

        if not files_changed:
            # Module name wasn't found in the requirements files.
            logging.info("Module name '{}' not found in repo {} - skipping.".format(module_name, repo_url))
            continue

        # Add/commit the files.
        ret_code = subprocess.call(['git', 'commit', '-am', 'Updating {} requirement to version {}'.format(module_name, new_version)])
        if ret_code:
            logging.error("Failed to add and commit changed files to repo {}".format(repo_url))
            continue

        if local_only:
            # For local_only, don't push the branch to the remote and create the PR - leave all changes local for review.
            continue

        # Push the branch.
        ret_code = subprocess.call(['git', 'push', '--set-upstream', 'origin', branch_name])
        if ret_code:
            logging.error("Failed to push branch {} upstream for repo {}".format(branch_name, repo_url))
            continue

        # Create a PR with an automated message.
        rollback_branch_push = False
        try:
            # The GitHub "mention" below does not work via the API - unfortunately...
            response = gh.create_pull(
                title='Change {} version.'.format(module_name),
                body='Change the required version of {} to {}.\n\n@edx-ops/pipeline-team Please review and tag appropriate parties.'.format(module_name, new_version),
                head=branch_name,
                base='master'
            )
        except:
            logging.error('Failed to create PR for repo {} - did you set GITHUB_TOKEN?'.format(repo_url))
            rollback_branch_push = True
        else:
            logging.info('Created PR #{} for repo {}: {}'.format(response.number, repo_url, response.html_url))

        if rollback_branch_push:
            # Since the PR creation failed, delete the branch in the remote repo as well.
            ret_code = subprocess.call(['git', 'push', 'origin', '--delete', branch_name])
            if ret_code:
                logging.error("ROLLBACK: Failed to delete upstream branch {} for repo {}".format(branch_name, repo_url))

    if not local_only:
        # Remove the temp directory containing all the cloned repos.
        shutil.rmtree(tmp_dir)
1062677
function generateVersionsTooltip(versions) {
    return versions.map(function(lib) {
      return lib.name + " " + lib.version;
    }).join("\n");
  }
289575
def get_versioned_files(cls):
        """"""
        files = cls._git_ls_files()
        submodules = cls._list_submodules()
        for subdir in submodules:
            subdir = os.path.relpath(subdir).replace(os.path.sep, '/')
            files += add_prefix_to_each(subdir, cls._git_ls_files(subdir))
        return add_directories(files)
941468
def set_version(version, rootdir = Dir.pwd, options = {})
      exit_status = 0
      type    = (options[:type])    ? options[:type]    : FalkorLib.config[:versioning][:type]
      source  = (options[:source])  ? options[:source]  : FalkorLib.config[:versioning][:source][ type ]
      versionfile = File.join( rootdir, source[:filename] ) unless source[:filename].nil?
      major, minor, patch = major(version), minor(version), patch(version)
      #tocommit = ""
      case type
      when 'file'
        info "writing version changes in #{source[:filename]}"
        File.open(versionfile, 'w') { |f| f.puts version } #if File.exist? ( versionfile )
      when 'gem'
        info "=> writing version changes in #{source[:filename]}"
        File.open(versionfile, 'r+') do |f|
          text = f.read
          text.gsub!(/^(\s*)MAJOR\s*,\s*MINOR,\s*PATCH\s*=\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(.*)$/,
                     '\1' + "MAJOR, MINOR, PATCH = #{major}, #{minor}, #{patch}" + '\5')
          f.rewind
          f.write(text)
        end
      when 'puppet_module'
        info "=> writing version changes in #{source[:filename]}"
        metadata = JSON.parse( IO.read( versionfile ) )
        metadata["version"] = version
        File.open(versionfile, "w") do |f|
          f.write JSON.pretty_generate( metadata )
        end
        #exit 1
      end
      if FalkorLib::Git.init?(rootdir)
        filelist = FalkorLib::Git.list_files( rootdir )
        Dir.chdir( rootdir ) do
          next if source[:filename].nil?
          unless filelist.include?( source[:filename] )
            warning "The version file #{source[:filename]} is not part of the Git repository"
            answer = ask("Adding the file to the repository? (Y|n)", 'Yes')
            next if answer =~ /n.*/i
            exit_status = FalkorLib::Git.add(versionfile, "Adding the version file '#{source[:filename]}', inialized to the '#{version}' version" )
            next
          end
          run %( git diff #{source[:filename]} )
          answer = ask(cyan("=> Commit the changes of the version file to the repository? (Y|n)"), 'Yes')
          next if answer =~ /n.*/i
          run %( git commit -s -m "bump to version '#{version}'" #{source[:filename]} )
          exit_status = $?.to_i
          # if (type == 'gem' && File.exists?(File.join(rootdir, 'Gemfile')) )
          #     run %{
          #        sleep 2
          #        bundle update falkorlib
          #        git commit -s -m "Update Gemfile.lock accordingly" Gemfile.lock
          #     } if command?( 'bundle' )
          # end
        end
      end
      exit_status
    end
1274432
def package_version(filename, varname):
    """"""
    _locals = {}
    with open(filename) as fp:
        exec(fp.read(), None, _locals)
    return _locals[varname]
1088388
function generate_module_version_map (modules, host) {
  modules.forEach(function(mod) {
    var name = mod.split('@')[0];
    host[name] = mod;
  });
}
263631
async function updateVersionH (components) {
  const filePath = path.resolve(__dirname, '..', 'atom', 'common', 'atom_version.h')
  const data = await readFile(filePath, 'utf8')
  const arr = data.split('\n')
  const pre = components.pre && components.pre.length >= 2 ? `-${components.pre[0]}.${components.pre[1]}` : null

  arr.forEach((item, idx) => {
    if (item.includes('#define ATOM_MAJOR_VERSION')) {
      arr[idx] = `#define ATOM_MAJOR_VERSION ${components.major}`
      arr[idx + 1] = `#define ATOM_MINOR_VERSION ${components.minor}`
      arr[idx + 2] = `#define ATOM_PATCH_VERSION ${components.patch}`
      arr[idx + 4] = pre ? `#define ATOM_PRE_RELEASE_VERSION ${pre}` : '// #define ATOM_PRE_RELEASE_VERSION'
    }
  })
  await writeFile(filePath, arr.join('\n'))
}
1351493
function bumpVersion() {
  const versionList = gitVersionInfo(packageJson.version);
  const targetBranch = 'master';
  const repoURL = packageJson.repository.url.replace(/(?:git\+|\.git)/g, '');

  gitPorcelainStatus()
    .then(status => {
      if (status.currentBranch !== targetBranch) {
        log.error(
          `${chalk.bold('Working on the wrong branch!')}`,
          `All tags must be created on ${chalk.bold(targetBranch)} branch. Please push your work and`,
          `create a Pull Request to ${chalk.bold(targetBranch)}. Then you can continue this process.`
        );
      }

      if (!status.clean) {
        log.error(`${chalk.bold('Working dirty!')}`, 'Please commit before trying again!');
      }

      log.info(`Current version in package.json is ${chalk.bold(versionList.current)}\n`);

      return inquirer.prompt([
        {
          type: 'list',
          name: 'newVersion',
          message: 'How would you like to bump it?',
          choices: versionList.prompt
        }
      ]);
    })
    .then(answers => {
      packageJson.version = answers.newVersion;
      packageLock.version = answers.newVersion;

      // Update Package files
      return Promise.all([
        promiseWriteFile(path.join(cwd, 'package.json'), packageJson, 2),
        promiseWriteFile(path.join(cwd, 'package-lock.json'), packageLock, 2)
      ]);
    })
    .then(([rewritePKG, rewritePKGLOCK]) => {
      log.success(
        `Version bumped in the following file:`,
        `${figures.arrowRight} ${rewritePKG.fileName}`,
        `${figures.arrowRight} ${rewritePKGLOCK.fileName}`
      );

      return gitTagsInfo(`v${packageJson.version}`);
    })
    .then(([tagsList, firstCommit]) =>
      changelog(
        // Object with all the tags info.
        tagsList,
        // First commit.
        firstCommit.trim(),
        // URL of the repository.
        repoURL,
        // Name of the repository.
        capitalize(packageJson.name.replace(/-/g, ' '))
      )
    )
    .then(result => {
      var filesToAdd = ['changelog/', 'package.json', 'package-lock.json'];
      var resultLog = result.reduce((prev, { fileName }) => prev.concat(`${figures.arrowRight} ${fileName}`), []);

      log.success(`Changelog:`, ...resultLog);

      log.info(`Pushing new tag to ${chalk.bold('origin')}...`);

      return git(`add ${filesToAdd.join(' ')}`);
    })
    .then(() => {
      var commitMessage = `Bump version to ${packageJson.version}`;

      return git(`commit -m "${commitMessage}"`, gitParseOutput);
    })
    .then(status => {
      log(...status);

      return git(`push origin ${targetBranch}`, gitParseOutput);
    })
    .then(status => {
      log(...status);

      return git(`tag -a -m "Tag version ${packageJson.version}." "v${packageJson.version}"`);
    })
    .then(() => git('git push origin --tags', gitParseOutput))
    .then(status => {
      var publicURL = `${repoURL}/releases/tag/v${packageJson.version}`;

      log(...status);

      log.success(`Release v${packageJson.version} was generated!`);

      log(`Please go to: ${chalk.underline(publicURL)}`, 'to describe the new changes/features added in this release.');

      return opn(publicURL, { wait: false });
    })
    .catch(log.error);
}
240311
private void merge(Versioning versioning, ArtifactRepository from, List<VersionInfo> found) {
        if ( StringUtils.isNotEmpty( versioning.getRelease() ) )
            found.add(new VersionInfo(versioning.getRelease(),from));

        if ( StringUtils.isNotEmpty( versioning.getLatest() ) )
            found.add(new VersionInfo(versioning.getLatest(),from));

        for ( String v : versioning.getVersions() )
            found.add(new VersionInfo(v,from));
    }

    VersionInfo findLatest(List<VersionInfo> infos) {
        Collections.sort(infos);
        if (infos.isEmpty())    return null;
        return infos.get(infos.size()-1);
    }

    private static class VersionInfo implements Comparable<VersionInfo> {
        final VersionNumber version;
        final ArtifactRepository repository;

        public VersionInfo(String version, ArtifactRepository repository) {
            this.version = new VersionNumber(version);
            this.repository = repository;
        }

        public int compareTo(VersionInfo that) {
            return this.version.compareTo(that.version);
        }
    }
    
    private Versioning readVersions( RepositorySystemSession session, RequestTrace trace, Metadata metadata,
                                     ArtifactRepository repository, VersionResult result )
    {
        Versioning versioning = null;

        FileInputStream fis = null;
        try
        {
            if ( metadata != null )
            {
                SyncContext syncContext = syncContextFactory.newInstance( session, true );

                try
                {
                    syncContext.acquire( null, Collections.singleton( metadata ) );

                    if ( metadata.getFile() != null && metadata.getFile().exists() )
                    {
                        fis = new FileInputStream( metadata.getFile() );
                        org.apache.maven.artifact.repository.metadata.Metadata m =
                            new MetadataXpp3Reader().read( fis, false );
                        versioning = m.getVersioning();

                        /*
                         * NOTE: Users occasionally misuse the id "local" for remote repos which screws up the metadata
                         * of the local repository. This is especially troublesome during snapshot resolution so we try
                         * to handle that gracefully.
                         */
                        if ( versioning != null && repository instanceof LocalRepository)
                        {
                            if ( versioning.getSnapshot() != null && versioning.getSnapshot().getBuildNumber() > 0 )
                            {
                                Versioning repaired = new Versioning();
                                repaired.setLastUpdated( versioning.getLastUpdated() );
                                Snapshot snapshot = new Snapshot();
                                snapshot.setLocalCopy( true );
                                repaired.setSnapshot( snapshot );
                                versioning = repaired;

                                throw new IOException( "Snapshot information corrupted with remote repository data"
                                    + ", please verify that no remote repository uses the id '" + repository.getId()
                                    + "'" );
                            }
                        }
                    }
                }
                finally
                {
                    syncContext.release();
                }
            }
        }
        catch ( Exception e )
        {
            invalidMetadata( session, trace, metadata, repository, e );
            result.addException( e );
        }
        finally
        {
            IOUtil.close(fis);
        }

        return ( versioning != null ) ? versioning : new Versioning();
    }

    private void invalidMetadata( RepositorySystemSession session, RequestTrace trace, Metadata metadata,
                                  ArtifactRepository repository, Exception exception )
    {
        RepositoryListener listener = session.getRepositoryListener();
        if ( listener != null )
        {
            DefaultRepositoryEvent event = new DefaultRepositoryEvent( EventType.METADATA_INVALID, session, trace );
            event.setMetadata( metadata );
            event.setException( exception );
            event.setRepository( repository );
            listener.metadataInvalid( event );
        }
    }

    private static final String MAVEN_METADATA_XML = "maven-metadata.xml";

    private static final String LATEST = "LATEST";

    private static final String SNAPSHOT = "SNAPSHOT";
}
108320
async function commitVersionBump (version) {
  const gitDir = path.resolve(__dirname, '..')
  const gitArgs = ['commit', '-a', '-m', `Bump v${version}`, '-n']
  await GitProcess.exec(gitArgs, gitDir)
}
1126715
def get_version(version_tuple):
    """"""
    if version_tuple[3] == FINAL and version_tuple[4] != 0:
        raise Exception(
            'Project version number misconfigured:\n'
            '   version may not be final and have segment number.')

    if version_tuple[3] not in (DEV, FINAL) and version_tuple[4] == 0:
        raise Exception(
            'Project version number misconfigured:\n'
            '   version must have segment number.')

    if version_tuple[3] == DEV:
        segment_num = get_git_changeset()
    else:
        segment_num = str(abs(version_tuple[4]))

    # X.X.X
    sem_ver = ".".join([
        str(abs(int(number)))
        for number in version_tuple[:3]
    ])

    if version_tuple[3] != FINAL:
        if version_tuple[3] in (ALPHA, BETA, RC):
            sem_ver = "%s%s%s" % (sem_ver, version_tuple[3], segment_num)
        elif version_tuple[3] in (DEV, POST):
            sem_ver = "%s%s%s%s" % (
                sem_ver, SEPARATOR, version_tuple[3], segment_num)
        else:
            raise Exception(
                'Project version number misconfigured:\n'
                '   Unrecognized release type')

    return sem_ver
165633
def package_version(self, prefix=None, name=None, pkg=None, build=False):
        """"""
        package_versions = {}

        if name and prefix:
            raise TypeError("Exactly one of 'name' or 'prefix' is required.")

        if name:
            prefix = self.get_prefix_envname(name)

        if self.environment_exists(prefix=prefix):

            for package in self.linked(prefix):
                if pkg in package:
                    n, v, b = self.split_canonical_name(package)
                    if build:
                        package_versions[n] = '{0}={1}'.format(v, b)
                    else:
                        package_versions[n] = v

        return package_versions.get(pkg)
273444
def versions(ctx, archive_name):
    '''
    
    '''

    _generate_api(ctx)

    var = ctx.obj.api.get_archive(archive_name)
    click.echo(pprint.pformat(map(str, var.get_versions())))