Example usage for org.eclipse.jgit.lib Repository getConfig

List of usage examples for org.eclipse.jgit.lib Repository getConfig

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getConfig.

Prototype

@NonNull
public abstract StoredConfig getConfig();

Source Link

Document

Get the configuration of this repository.

Usage

From source file:org.z2env.impl.gitcr.GitComponentRepositoryImpl.java

License:Apache License

private boolean hasUriChanged(Repository clonedRepo) throws Exception {
    String currentRemote = clonedRepo.getConfig().getString("remote", "origin", "url");
    boolean result = currentRemote == null || !this.originUri.equals(new URIish(currentRemote));

    return result;
}

From source file:org.z2env.impl.helper.GitTools.java

License:Apache License

/**
 * Clones the given remote repository into the given destination folder. The method clones all branches but doesn't perform a checkout.
 *   /*from  w  w w  .j a  v a2 s . co m*/
 * @param remoteUri URI of the remote repository
 * @param destFolder local destination folder
 * @param credentials user credentials
 * @return the cloned repository
 * @throws IOException if something went wrong
 */
public static Repository cloneRepository(URIish remoteUri, File destFolder, CredentialsProvider credentials,
        int timeout) throws IOException {

    // workaround for http://redmine.z2-environment.net/issues/902:
    // split clone into its piece in order to get the chance to set "core.autocrlf"
    Git gitResult;
    try {
        gitResult = Git.init().setBare(false).setDirectory(destFolder).call();
    } catch (Exception e) {
        throw new IOException("Failed to initialize a new Git repository at " + destFolder.getAbsolutePath(),
                e);
    }

    Repository repo = gitResult.getRepository();

    // setting "core.autocrlf=false" helps to solve http://redmine.z2-environment.net/issues/902
    StoredConfig config = repo.getConfig();
    config.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF,
            String.valueOf(false));

    // add origin - clone all branches
    RemoteConfig remoteCfg = null;
    try {
        remoteCfg = new RemoteConfig(config, "origin");
    } catch (URISyntaxException e) {
        throw new IOException("Failed to configure origin repository", e);
    }
    remoteCfg.addURI(remoteUri);
    remoteCfg.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
    remoteCfg.update(config);
    config.save();

    // fetch all branches from origin
    try {
        gitResult.fetch().setRemote("origin").setCredentialsProvider(credentials).setTimeout(timeout).call();
    } catch (Exception e) {
        throw new IOException("Failed to fetch from origin!", e);
    }

    return repo;
}

From source file:org.zend.sdkcli.internal.commands.GitAddRemoteCommand.java

License:Open Source License

@Override
protected boolean doExecute() {
    Repository repo = null;
    try {//w ww  .java2s .  c  o m
        File gitDir = getProject();
        if (!gitDir.exists()) {
            getLogger().error("Git repository is not available in provided location");
            return false;
        }
        repo = FileRepositoryBuilder.create(gitDir);
    } catch (IOException e) {
        getLogger().error(e);
        return false;
    }
    if (repo != null) {
        String repoName = getReposiotryName(getRepo(), repo);
        if (repoName == null) {
            getLogger().error("Invalid repository URL :" + getRepo());
            return false;
        }
        try {
            RemoteConfig config = new RemoteConfig(repo.getConfig(), repoName);
            config.addURI(new URIish(getRepo()));
            String dst = Constants.R_REMOTES + config.getName();
            RefSpec refSpec = new RefSpec();
            refSpec = refSpec.setForceUpdate(true);
            refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$
            config.addFetchRefSpec(refSpec);
            config.update(repo.getConfig());
            repo.getConfig().save();
            getLogger().info(
                    MessageFormat.format("New remote called \"{0}\" was added successfully", config.getName()));
        } catch (URISyntaxException e) {
            getLogger().error("Invalid repository URL :" + getRepo());
            return false;
        } catch (IOException e) {
            getLogger().error(e);
            return false;
        }
    }
    return true;
}

From source file:org.zend.sdkcli.internal.commands.GitAddRemoteCommand.java

License:Open Source License

private String getReposiotryName(String url, Repository repo) {
    String customName = getName();
    if (customName != null) {
        return customName;
    }//from w  w w.  j a v  a2s  .  c om
    try {
        URIish repoURL = new URIish(url);
        String host = repoURL.getHost();
        host = host.substring(0, host.lastIndexOf("."));
        String name = host.substring(host.lastIndexOf(".") + 1);
        Set<String> names = repo.getConfig().getSubsections("remote");
        int suffix = 0;
        for (String existingName : names) {
            if (existingName.startsWith(name + "_") || existingName.equals(name)) {
                suffix++;
            }
        }
        if (suffix != 0) {
            name += "_" + suffix;
        }
        return name;
    } catch (URISyntaxException e) {
        getLogger().error(e);
    }
    return null;
}

From source file:org.zend.sdkcli.internal.commands.GitPushApplicationCommand.java

License:Open Source License

private String doGetRemote(Repository repo) {
    String remote = getRemote();/*from  w w w  . j  a  v  a  2s.  co m*/
    if (remote == null) {
        remote = GitHelper.ZEND_CLOUD_REMOTE;
    }
    Set<String> remotes = repo.getConfig().getSubsections("remote");
    if (remotes.contains(remote)) {
        return remote;
    }
    return null;
}

From source file:pl.project13.maven.git.GitCommitIdMojo.java

License:Open Source License

void loadGitData(@NotNull Properties properties) throws IOException, MojoExecutionException {
    Repository git = getGitRepository();
    ObjectReader objectReader = git.newObjectReader();

    // git.user.name
    String userName = git.getConfig().getString("user", null, "name");
    put(properties, BUILD_AUTHOR_NAME, userName);

    // git.user.email
    String userEmail = git.getConfig().getString("user", null, "email");
    put(properties, BUILD_AUTHOR_EMAIL, userEmail);

    // more details parsed out bellow
    Ref HEAD = git.getRef(Constants.HEAD);
    if (HEAD == null) {
        throw new MojoExecutionException(
                "Could not get HEAD Ref, are you sure you've set the dotGitDirectory property of this plugin to a valid path?");
    }/*w ww.j  av  a 2s.  c  o m*/
    RevWalk revWalk = new RevWalk(git);
    RevCommit headCommit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(headCommit);

    try {
        // git.branch
        String branch = determineBranchName(git, System.getenv());
        put(properties, BRANCH, branch);

        // git.commit.id.describe
        maybePutGitDescribe(properties, git);

        // git.commit.id
        put(properties, COMMIT_ID, headCommit.getName());

        // git.commit.id.abbrev
        putAbbrevCommitId(objectReader, properties, headCommit, abbrevLength);

        // git.commit.author.name
        String commitAuthor = headCommit.getAuthorIdent().getName();
        put(properties, COMMIT_AUTHOR_NAME, commitAuthor);

        // git.commit.author.email
        String commitEmail = headCommit.getAuthorIdent().getEmailAddress();
        put(properties, COMMIT_AUTHOR_EMAIL, commitEmail);

        // git commit.message.full
        String fullMessage = headCommit.getFullMessage();
        put(properties, COMMIT_MESSAGE_FULL, fullMessage);

        // git commit.message.short
        String shortMessage = headCommit.getShortMessage();
        put(properties, COMMIT_MESSAGE_SHORT, shortMessage);

        long timeSinceEpoch = headCommit.getCommitTime();
        Date commitDate = new Date(timeSinceEpoch * 1000); // git is "by sec" and java is "by ms"
        SimpleDateFormat smf = new SimpleDateFormat(dateFormat);
        put(properties, COMMIT_TIME, smf.format(commitDate));

        // git remote.origin.url
        String remoteOriginUrl = git.getConfig().getString("remote", "origin", "url");
        put(properties, REMOTE_ORIGIN_URL, remoteOriginUrl);
    } finally {
        revWalk.dispose();
    }
}

From source file:playRepository.GitRepository.java

License:Apache License

private static List<FileDiff> getFileDiffs(final Repository repositoryA, Repository repositoryB,
        ObjectId commitA, ObjectId commitB) throws IOException {
    class MultipleRepositoryObjectReader extends ObjectReader {
        Collection<ObjectReader> readers = new HashSet<>();

        @Override// w  w w  . j  ava  2  s. c o  m
        public ObjectReader newReader() {
            return new MultipleRepositoryObjectReader(readers);
        }

        public MultipleRepositoryObjectReader(Collection<ObjectReader> readers) {
            this.readers = readers;
        }

        public MultipleRepositoryObjectReader() {
            this.readers = new HashSet<>();
        }

        public void addObjectReader(ObjectReader reader) {
            this.readers.add(reader);
        }

        @Override
        public Collection<ObjectId> resolve(AbbreviatedObjectId id) throws IOException {
            Set<ObjectId> result = new HashSet<>();
            for (ObjectReader reader : readers) {
                result.addAll(reader.resolve(id));
            }
            return result;
        }

        @Override
        public ObjectLoader open(AnyObjectId objectId, int typeHint) throws IOException {
            for (ObjectReader reader : readers) {
                if (reader.has(objectId, typeHint)) {
                    return reader.open(objectId, typeHint);
                }
            }
            return null;
        }

        @Override
        public Set<ObjectId> getShallowCommits() throws IOException {
            Set<ObjectId> union = new HashSet<>();
            for (ObjectReader reader : readers) {
                union.addAll(reader.getShallowCommits());
            }
            return union;
        }
    }

    final MultipleRepositoryObjectReader reader = new MultipleRepositoryObjectReader();
    reader.addObjectReader(repositoryA.newObjectReader());
    reader.addObjectReader(repositoryB.newObjectReader());

    @SuppressWarnings("rawtypes")
    Repository fakeRepo = new Repository(new BaseRepositoryBuilder()) {

        @Override
        public void create(boolean bare) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public ObjectDatabase getObjectDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public RefDatabase getRefDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public StoredConfig getConfig() {
            return repositoryA.getConfig();
        }

        @Override
        public void scanForRepoChanges() throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void notifyIndexChanged() {
            throw new UnsupportedOperationException();
        }

        @Override
        public ReflogReader getReflogReader(String refName) throws IOException {
            throw new UnsupportedOperationException();
        }

        public ObjectReader newObjectReader() {
            return reader;
        }
    };

    DiffFormatter formatter = new DiffFormatter(NullOutputStream.INSTANCE);
    formatter.setRepository(fakeRepo);
    formatter.setDetectRenames(true);

    AbstractTreeIterator treeParserA, treeParserB;
    RevTree treeA = null, treeB = null;

    if (commitA != null) {
        treeA = new RevWalk(repositoryA).parseTree(commitA);
        treeParserA = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserA).reset(reader, treeA);
    } else {
        treeParserA = new EmptyTreeIterator();
    }

    if (commitB != null) {
        treeB = new RevWalk(repositoryB).parseTree(commitB);
        treeParserB = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserB).reset(reader, treeB);
    } else {
        treeParserB = new EmptyTreeIterator();
    }

    List<FileDiff> result = new ArrayList<>();
    int size = 0;
    int lines = 0;

    for (DiffEntry diff : formatter.scan(treeParserA, treeParserB)) {
        FileDiff fileDiff = new FileDiff();
        fileDiff.commitA = commitA != null ? commitA.getName() : null;
        fileDiff.commitB = commitB != null ? commitB.getName() : null;

        fileDiff.changeType = diff.getChangeType();

        fileDiff.oldMode = diff.getOldMode();
        fileDiff.newMode = diff.getNewMode();

        String pathA = diff.getPath(DiffEntry.Side.OLD);
        String pathB = diff.getPath(DiffEntry.Side.NEW);

        byte[] rawA = null;
        if (treeA != null && Arrays.asList(DELETE, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t1 = TreeWalk.forPath(repositoryA, pathA, treeA);
            ObjectId blobA = t1.getObjectId(0);
            fileDiff.pathA = pathA;

            try {
                rawA = repositoryA.open(blobA).getBytes();
                fileDiff.isBinaryA = RawText.isBinary(rawA);
                fileDiff.a = fileDiff.isBinaryA ? null : new RawText(rawA);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.A_SIZE_EXCEEDED);
            }
        }

        byte[] rawB = null;
        if (treeB != null && Arrays.asList(ADD, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t2 = TreeWalk.forPath(repositoryB, pathB, treeB);
            ObjectId blobB = t2.getObjectId(0);
            fileDiff.pathB = pathB;

            try {
                rawB = repositoryB.open(blobB).getBytes();
                fileDiff.isBinaryB = RawText.isBinary(rawB);
                fileDiff.b = fileDiff.isBinaryB ? null : new RawText(rawB);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.B_SIZE_EXCEEDED);
            }
        }

        if (size > DIFF_SIZE_LIMIT || lines > DIFF_LINE_LIMIT) {
            fileDiff.addError(FileDiff.Error.OTHERS_SIZE_EXCEEDED);
            result.add(fileDiff);
            continue;
        }

        // Get diff if necessary
        if (fileDiff.a != null && fileDiff.b != null && !(fileDiff.isBinaryA || fileDiff.isBinaryB)
                && Arrays.asList(MODIFY, RENAME).contains(diff.getChangeType())) {
            DiffAlgorithm diffAlgorithm = DiffAlgorithm
                    .getAlgorithm(repositoryB.getConfig().getEnum(ConfigConstants.CONFIG_DIFF_SECTION, null,
                            ConfigConstants.CONFIG_KEY_ALGORITHM, DiffAlgorithm.SupportedAlgorithm.HISTOGRAM));
            fileDiff.editList = diffAlgorithm.diff(RawTextComparator.DEFAULT, fileDiff.a, fileDiff.b);
            size += fileDiff.getHunks().size;
            lines += fileDiff.getHunks().lines;
        }

        // update lines and sizes
        if (fileDiff.b != null && !fileDiff.isBinaryB && diff.getChangeType().equals(ADD)) {
            lines += fileDiff.b.size();
            size += rawB.length;
        }

        // update lines and sizes
        if (fileDiff.a != null && !fileDiff.isBinaryA && diff.getChangeType().equals(DELETE)) {
            lines += fileDiff.a.size();
            size += rawA.length;
        }

        // Stop if exceeds the limit for total number of files
        if (result.size() > DIFF_FILE_LIMIT) {
            break;
        }

        result.add(fileDiff);
    }

    return result;
}