Get the branch info for this revision from the repository. For svn, it is in svn info.

@return
@throws MojoExecutionException
@throws MojoExecutionException
559857
public String getScmBranch()
        throws MojoExecutionException
    {
        try
        {
            ScmRepository repository = getScmRepository();
            ScmProvider provider = scmManager.getProviderByRepository( repository );
            /* git branch can be obtained directly by a command */
            if ( GitScmProviderRepository.PROTOCOL_GIT.equals( provider.getScmType() ) )
            {
                ScmFileSet fileSet = new ScmFileSet( scmDirectory );
                return GitBranchCommand.getCurrentBranch( getLogger(),
                                                          (GitScmProviderRepository) repository.getProviderRepository(),
                                                          fileSet );
            }
            else if ( provider instanceof HgScmProvider )
            {
                /* hg branch can be obtained directly by a command */
                HgOutputConsumer consumer = new HgOutputConsumer( getLogger() );
                ScmResult result = HgUtils.execute( consumer, logger, scmDirectory, new String[] { "id", "-b" } );
                checkResult( result );
                if ( StringUtils.isNotEmpty( consumer.getOutput() ) )
                {
                    return consumer.getOutput();
                }
            }
        }
        catch ( ScmException e )
        {
            getLog().warn( "Cannot get the branch information from the git repository: \n" + e.getLocalizedMessage() );
        }

        return getScmBranchFromUrl();
    }
397519
public static synchronized String getVersion() {
        // Try to get version number from pom.xml (available when running in Eclipse)
        final Class<?> cls = ClassGraph.class;
        try {
            final String className = cls.getName();
            final URL classpathResource = cls.getResource("/" + JarUtils.classNameToClassfilePath(className));
            if (classpathResource != null) {
                final Path absolutePackagePath = Paths.get(classpathResource.toURI()).getParent();
                final int packagePathSegments = className.length() - className.replace(".", "").length();
                // Remove package segments from path
                Path path = absolutePackagePath;
                for (int i = 0; i < packagePathSegments && path != null; i++) {
                    path = path.getParent();
                }
                // Remove up to two more levels for "bin" or "target/classes"
                for (int i = 0; i < 3 && path != null; i++, path = path.getParent()) {
                    final Path pom = path.resolve("pom.xml");
                    try (InputStream is = Files.newInputStream(pom)) {
                        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
                        doc.getDocumentElement().normalize();
                        String version = (String) XPathFactory.newInstance().newXPath().compile("/project/version")
                                .evaluate(doc, XPathConstants.STRING);
                        if (version != null) {
                            version = version.trim();
                            if (!version.isEmpty()) {
                                return version;
                            }
                        }
                    } catch (final IOException e) {
                        // Not found
                    }
                }
            }
        } catch (final Exception e) {
            // Ignore
        }

        // Try to get version number from maven properties in jar's META-INF directory
        try (InputStream is = cls.getResourceAsStream(
                "/META-INF/maven/" + MAVEN_PACKAGE + "/" + MAVEN_ARTIFACT + "/pom.properties")) {
            if (is != null) {
                final Properties p = new Properties();
                p.load(is);
                final String version = p.getProperty("version", "").trim();
                if (!version.isEmpty()) {
                    return version;
                }
            }
        } catch (final IOException e) {
            // Ignore
        }

        // Fallback to using Java API (version number is obtained from MANIFEST.MF)
        final Package pkg = cls.getPackage();
        if (pkg != null) {
            String version = pkg.getImplementationVersion();
            if (version == null) {
                version = "";
            }
            version = version.trim();
            if (version.isEmpty()) {
                version = pkg.getSpecificationVersion();
                if (version == null) {
                    version = "";
                }
                version = version.trim();
            }
            if (!version.isEmpty()) {
                return version;
            }
        }
        return "unknown";
    }
135390
private String getProjectVersion() {
        return Utils.convertToDebianVersion(getProject().getVersion(), this.snapshotExpand, this.snapshotEnv, this.snapshotTemplate, session.getStartTime());
    }
812522
private void generateVersionXml( Set<ResolvedJarResource> jarResources )
            throws MojoExecutionException
    {

        VersionXmlGenerator generator = new VersionXmlGenerator( getEncoding() );
        generator.generate( getLibDirectory(), jarResources );
    }
509817
protected DependencyNode getRootNodeDependecyTree() throws MojoExecutionException{
    try {
      ArtifactFilter artifactFilter = null;

      // works for only maven 3. Use of dependency graph component not handled for maven 2
      // as current version of NAR already requires Maven 3.x
      rootNode = dependencyGraphBuilder.buildDependencyGraph(getMavenProject(), artifactFilter);

    } catch (DependencyGraphBuilderException exception) {
      throw new MojoExecutionException("Cannot build project dependency graph", exception);
    }

    return rootNode;
  }
948856
public String getServerVersion() throws IOException {
        // only do this once -- future invocations will use the known value
        if (m_serverVersion == null) {
            // Make the APIA call for describe repository
            // and make sure that HTTP 302 status is handled.
            String desc = getResponseAsString("/describe?xml=true", true, true);
            logger.debug("describeRepository response:\n" + desc);
            String[] parts = desc.split("<repositoryVersion>");
            if (parts.length < 2) {
                throw new IOException("Could not find repositoryVersion element in content of /describe?xml=true");
            }
            int i = parts[1].indexOf("<");
            if (i == -1) {
                throw new IOException("Could not find end of repositoryVersion element in content of /describe?xml=true");
            }
            m_serverVersion = parts[1].substring(0, i).trim();
            logger.debug("Server version is " + m_serverVersion);
        }
        return m_serverVersion;
    }
58797
public String getVersion() {
        String version = getMavenModel().getVersion();
        if ( version == null && getMavenModel().getParent() != null ) {
            version = getMavenModel().getParent().getVersion();
        }

        return version;
    }
488987
def branch(self):
        
        # return self.sh(['git, 'branch'], shell=False)  # parse for '*'
        cmd = ['git', 'symbolic-ref', '--short', 'HEAD']
        try:
            output = self.sh(cmd, shell=False, ignore_error=True).rstrip()
        except subprocess.CalledProcessError as e:
            log.exception(e)
            return  "#err# %s" % output
            #if e.returncode == 128  # bare repo
        if output.startswith('fatal: ref HEAD is not a symbolic ref'):
            output = '# %s' % output
        return output
1322542
def version(self):
        
        branches = self.branches()
        if self.info['branch'] == branches.sandbox:
            try:
                return self.software_version()
            except Exception as exc:
                raise utils.CommandError(
                    'Could not obtain repo version, do you have a makefile '
                    'with version entry?\n%s' % exc
                )
        else:
            branch = self.info['branch'].lower()
            branch = re.sub('[^a-z0-9_-]+', '-', branch)
            return f"{branch}-{self.info['head']['id'][:8]}"
824788
public UpdateSite.Plugin getInfo() {
        UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
        UpdateSite.Plugin p = uc.getPlugin(getShortName(), getVersionNumber());
        if (p != null) return p;
        return uc.getPlugin(getShortName());
    }
536263
public String getRemoteCommit(String branch) throws Exception {
        fetch();
        ObjectId commit = localRepo.resolve("origin/" + branch);
        if (commit != null)
            return commit.getName();
        else
            return null;
    }
15295
public function getCurrentCommit()
    {
        /** @var $result CallResult */
        $result = $this->getSvn()->{'info'}($this->getRepositoryPath(), array(
            '--xml',
            '--revision' => 'HEAD'
        ));
        $result->assertSuccess(sprintf('Cannot get info for "%s"', $this->getRepositoryPath()));

        $xml    = simplexml_load_string($result->getStdOut());
        if (!$xml) {
            throw new \RuntimeException(sprintf('Cannot read info XML for "%s"', $this->getRepositoryPath()));
        }

        $commit = $xml->xpath('/info/entry/commit[@revision]');
        if (empty($commit)) {
            throw new \RuntimeException(sprintf('Cannot read info XML for "%s"', $this->getRepositoryPath()));
        }

        $commit = reset($commit);
        return (string)($commit['revision']);
    }
985725
@Override
    public List<StepExecution> getStepExecutionsTopLevelFromJobExecutionId(final long jobExecutionId) throws NoSuchJobExecutionException {
        final EntityManager em = getPsu().createEntityManager();
        try {
            List<StepExecution> exec = new TranRequest<List<StepExecution>>(em) {
                @Override
                public List<StepExecution> call() throws Exception {
                    TypedQuery<StepExecution> query = em.createNamedQuery(TopLevelStepExecutionEntity.GET_TOP_LEVEL_STEP_EXECUTIONS_BY_JOB_EXEC_SORT_BY_START_TIME_ASC,
                                                                          StepExecution.class);
                    query.setParameter("jobExecId", jobExecutionId);
                    List<StepExecution> result = query.getResultList();
                    if (result == null) {
                        result = new ArrayList<StepExecution>();
                    }
                    // If empty, try to get job execution to generate NoSuchJobExecutionException if unknown id
                    if (result.isEmpty()) {
                        getJobExecution(jobExecutionId);
                    }
                    return result;
                }
            }.runInNewOrExistingGlobalTran();
            return exec;
        } finally {
            em.close();
        }
    }
955680
public static RevisionInformation getRevisionInformation() {
		String revision = UNKNOWN;
		String commitDate = UNKNOWN;
		try (InputStream propFile = EnvironmentInformation.class.getClassLoader().getResourceAsStream(".version.properties")) {
			if (propFile != null) {
				Properties properties = new Properties();
				properties.load(propFile);
				String propRevision = properties.getProperty("git.commit.id.abbrev");
				String propCommitDate = properties.getProperty("git.commit.time");
				revision = propRevision != null ? propRevision : UNKNOWN;
				commitDate = propCommitDate != null ? propCommitDate : UNKNOWN;
			}
		} catch (Throwable t) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Cannot determine code revision: Unable to read version property file.", t);
			} else {
				LOG.info("Cannot determine code revision: Unable to read version property file.");
			}
		}
		
		return new RevisionInformation(revision, commitDate);
	}
1137246
public static String getExportFormat(RepositoryInfo repoinfo)
            throws Exception {
        String sourceExportFormat = null;
        StringTokenizer stoken =
                new StringTokenizer(repoinfo.getRepositoryVersion(), ".");
        int majorVersion = new Integer(stoken.nextToken()).intValue();
        if (majorVersion < 2) {
            sourceExportFormat = METS_EXT1_0_LEGACY;
        } else {
            sourceExportFormat = repoinfo.getDefaultExportFormat();
        }

        return sourceExportFormat;
    }
288328
@Override
  public File getNoArchDirectory(final File baseDir, final String artifactId, final String version)
      throws MojoExecutionException, MojoFailureException {
    return baseDir;
  }
711712
private Toolchain getToolchain() {
    Toolchain toolChain = null;
    final ToolchainManager toolchainManager = ((NarJavahMojo) this.mojo).getToolchainManager();

    if (toolchainManager != null) {
      toolChain = toolchainManager.getToolchainFromBuildContext("jdk", ((NarJavahMojo) this.mojo).getSession());
    }
    return toolChain;
  }