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

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

Introduction

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

Prototype


public File getDirectory() 

Source Link

Document

Get local metadata directory

Usage

From source file:com.github.checkstyle.regression.internal.GitUtils.java

License:Open Source License

public static void clearTempRepositories() throws IOException {
    for (Repository repository : TEMP_REPOSITORIES) {
        FileUtils.deleteDirectory(repository.getDirectory().getParentFile());
    }/*from  w  w w. ja  v a2 s . c  om*/
}

From source file:com.github.pascalgn.maven.properties.GitProperties.java

License:Apache License

private void addProperties(Map<String, String> map) throws IOException {
    Repository repository = new FileRepositoryBuilder().setWorkTree(new File(".")).readEnvironment()
            .findGitDir().setMustExist(true).build();
    logger.debug("Using git repository: " + repository.getDirectory());

    ObjectId head = repository.resolve("HEAD");
    if (head == null) {
        throw new IllegalStateException("No such revision: HEAD");
    }/*  w w w . j  a  v a  2s  .co m*/

    String branch = nullToEmpty(repository.getBranch());
    map.put("git.branch", branch);

    String commitId = head.name();
    map.put("git.commit.id", commitId);

    String commitIdAbbrev = repository.newObjectReader().abbreviate(head).name();
    map.put("git.commit.id.abbrev", commitIdAbbrev);

    RevWalk walk = new RevWalk(repository);
    walk.setRetainBody(false);
    RevCommit headCommit = walk.parseCommit(head);
    int count = RevWalkUtils.count(walk, headCommit, null);
    map.put("git.count", Integer.toString(count));

    String color = commitId.substring(0, 6);
    map.put("git.commit.color.value", color);
    map.put("git.commit.color.name", ColorHelper.getColorName(color));
    map.put("git.commit.color.lightness", Integer.toString(ColorHelper.getLightness(color)));
    map.put("git.commit.color.foreground", ColorHelper.getForeground(color));

    map.put("git.build.datetime.simple", getFormattedDate());
}

From source file:com.google.gerrit.httpd.rpc.changedetail.IncludedInDetailFactory.java

License:Apache License

private List<String> includedIn(final Repository repo, final RevWalk rw, final RevCommit rev,
        final String namespace) throws IOException, MissingObjectException, IncorrectObjectTypeException {
    final List<String> result = new ArrayList<String>();
    for (final Ref ref : repo.getRefDatabase().getRefs(namespace).values()) {
        final RevCommit tip;
        try {/*ww  w. j a  v a 2 s  .com*/
            tip = rw.parseCommit(ref.getObjectId());
        } catch (IncorrectObjectTypeException notCommit) {
            // Its OK for a tag reference to point to a blob or a tree, this
            // is common in the Linux kernel or git.git repository.
            //
            continue;
        } catch (MissingObjectException notHere) {
            // Log the problem with this branch, but keep processing.
            //
            log.warn("Reference " + ref.getName() + " in " + repo.getDirectory() + " points to dangling object "
                    + ref.getObjectId());
            continue;
        }

        if (rw.isMergedInto(rev, tip)) {
            result.add(ref.getName().substring(namespace.length()));
        }
    }
    return result;
}

From source file:com.google.gerrit.httpd.rpc.project.AddBranch.java

License:Apache License

private RevWalk verifyConnected(final Repository repo, final ObjectId revid) throws InvalidRevisionException {
    try {//from w  ww  . j a  v a  2 s  .c om
        final ObjectWalk rw = new ObjectWalk(repo);
        try {
            rw.markStart(rw.parseCommit(revid));
        } catch (IncorrectObjectTypeException err) {
            throw new InvalidRevisionException();
        }
        for (final Ref r : repo.getAllRefs().values()) {
            try {
                rw.markUninteresting(rw.parseAny(r.getObjectId()));
            } catch (MissingObjectException err) {
                continue;
            }
        }
        rw.checkConnectivity();
        return rw;
    } catch (IncorrectObjectTypeException err) {
        throw new InvalidRevisionException();
    } catch (MissingObjectException err) {
        throw new InvalidRevisionException();
    } catch (IOException err) {
        log.error("Repository \"" + repo.getDirectory() + "\" may be corrupt; suggest running git fsck", err);
        throw new InvalidRevisionException();
    }
}

From source file:com.google.gerrit.server.git.LocalDiskRepositoryManager.java

License:Apache License

private Repository createRepository(Path path, Project.NameKey name)
        throws RepositoryNotFoundException, RepositoryCaseMismatchException {
    if (isUnreasonableName(name)) {
        throw new RepositoryNotFoundException("Invalid name: " + name);
    }/* w w w. j av a 2  s.c  om*/

    File dir = FileKey.resolve(path.resolve(name.get()).toFile(), FS.DETECTED);
    FileKey loc;
    if (dir != null) {
        // Already exists on disk, use the repository we found.
        //
        loc = FileKey.exact(dir, FS.DETECTED);

        if (!names.contains(name)) {
            throw new RepositoryCaseMismatchException(name);
        }
    } else {
        // It doesn't exist under any of the standard permutations
        // of the repository name, so prefer the standard bare name.
        //
        String n = name.get() + Constants.DOT_GIT_EXT;
        loc = FileKey.exact(path.resolve(n).toFile(), FS.DETECTED);
    }

    try {
        Repository db = RepositoryCache.open(loc, false);
        db.create(true /* bare */);

        StoredConfig config = db.getConfig();
        config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
                ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true);
        config.save();

        // JGit only writes to the reflog for refs/meta/config if the log file
        // already exists.
        //
        File metaConfigLog = new File(db.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
        if (!metaConfigLog.getParentFile().mkdirs() || !metaConfigLog.createNewFile()) {
            log.error(String.format("Failed to create ref log for %s in repository %s", RefNames.REFS_CONFIG,
                    name));
        }

        onCreateProject(name);

        return db;
    } catch (IOException e1) {
        final RepositoryNotFoundException e2;
        e2 = new RepositoryNotFoundException("Cannot create repository " + name);
        e2.initCause(e1);
        throw e2;
    }
}

From source file:com.google.gerrit.server.git.LocalDiskRepositoryManager.java

License:Apache License

private String getProjectDescription(final Repository e) throws IOException {
    final File d = new File(e.getDirectory(), "description");

    String description;/*from  ww  w . j a  v a 2s . c  o m*/
    try {
        description = RawParseUtils.decode(IO.readFully(d));
    } catch (FileNotFoundException err) {
        return null;
    }

    if (description != null) {
        description = description.trim();
        if (description.isEmpty()) {
            description = null;
        }
        if (UNNAMED.equals(description)) {
            description = null;
        }
    }
    return description;
}

From source file:com.google.gerrit.server.git.MultiBaseLocalDiskRepositoryManagerTest.java

License:Apache License

@Test
public void testDefaultRepositoryLocation()
        throws RepositoryCaseMismatchException, RepositoryNotFoundException {
    Project.NameKey someProjectKey = new Project.NameKey("someProject");
    Repository repo = repoManager.createRepository(someProjectKey);
    assertThat(repo.getDirectory()).isNotNull();
    assertThat(repo.getDirectory().exists()).isTrue();
    assertThat(repo.getDirectory().getParent())
            .isEqualTo(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());

    repo = repoManager.openRepository(someProjectKey);
    assertThat(repo.getDirectory()).isNotNull();
    assertThat(repo.getDirectory().exists()).isTrue();
    assertThat(repo.getDirectory().getParent())
            .isEqualTo(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());

    assertThat(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString())
            .isEqualTo(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());

    SortedSet<Project.NameKey> repoList = repoManager.list();
    assertThat(repoList.size()).isEqualTo(1);
    assertThat(repoList.toArray(new Project.NameKey[repoList.size()]))
            .isEqualTo(new Project.NameKey[] { someProjectKey });
}

From source file:com.google.gerrit.server.git.MultiBaseLocalDiskRepositoryManagerTest.java

License:Apache License

@Test
public void testAlternateRepositoryLocation() throws IOException {
    Path alternateBasePath = TempFileUtil.createTempDirectory().toPath();
    Project.NameKey someProjectKey = new Project.NameKey("someProject");
    reset(configMock);/* w  w  w .j  a v a2 s . c  om*/
    expect(configMock.getBasePath(someProjectKey)).andReturn(alternateBasePath).anyTimes();
    expect(configMock.getAllBasePaths()).andReturn(Arrays.asList(alternateBasePath)).anyTimes();
    replay(configMock);

    Repository repo = repoManager.createRepository(someProjectKey);
    assertThat(repo.getDirectory()).isNotNull();
    assertThat(repo.getDirectory().exists()).isTrue();
    assertThat(repo.getDirectory().getParent()).isEqualTo(alternateBasePath.toString());

    repo = repoManager.openRepository(someProjectKey);
    assertThat(repo.getDirectory()).isNotNull();
    assertThat(repo.getDirectory().exists()).isTrue();
    assertThat(repo.getDirectory().getParent()).isEqualTo(alternateBasePath.toString());

    assertThat(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString())
            .isEqualTo(alternateBasePath.toString());

    SortedSet<Project.NameKey> repoList = repoManager.list();
    assertThat(repoList.size()).isEqualTo(1);
    assertThat(repoList.toArray(new Project.NameKey[repoList.size()]))
            .isEqualTo(new Project.NameKey[] { someProjectKey });
}

From source file:com.google.gerrit.server.git.ReadOnlyRepository.java

License:Apache License

private static BaseRepositoryBuilder<?, ?> builder(Repository r) {
    checkNotNull(r);/*from w  ww.j  a v a2  s. c o  m*/
    BaseRepositoryBuilder<?, ?> builder = new BaseRepositoryBuilder<>().setFS(r.getFS())
            .setGitDir(r.getDirectory());

    if (!r.isBare()) {
        builder.setWorkTree(r.getWorkTree()).setIndexFile(r.getIndexFile());
    }
    return builder;
}

From source file:com.google.gerrit.server.git.VersionedMetaData.java

License:Apache License

/**
 * Open a batch of updates to the same metadata ref.
 * <p>//www .java  2 s  .com
 * This allows making multiple commits to a single metadata ref, at the end of
 * which is a single ref update. For batching together updates to multiple
 * refs (each consisting of one or more commits against their respective
 * refs), create the {@link MetaDataUpdate} with a {@link BatchRefUpdate}.
 * <p>
 * A ref update produced by this {@link BatchMetaDataUpdate} is only committed
 * if there is no associated {@link BatchRefUpdate}. As a result, the
 * configured ref updated event is not fired if there is an associated batch.
 *
 * @param update helper info about the update.
 * @throws IOException if the update failed.
 */
public BatchMetaDataUpdate openUpdate(final MetaDataUpdate update) throws IOException {
    final Repository db = update.getRepository();

    reader = db.newObjectReader();
    inserter = db.newObjectInserter();
    final RevWalk rw = new RevWalk(reader);
    final RevTree tree = revision != null ? rw.parseTree(revision) : null;
    newTree = readTree(tree);
    return new BatchMetaDataUpdate() {
        AnyObjectId src = revision;
        AnyObjectId srcTree = tree;

        @Override
        public void write(CommitBuilder commit) throws IOException {
            write(VersionedMetaData.this, commit);
        }

        private boolean doSave(VersionedMetaData config, CommitBuilder commit) throws IOException {
            DirCache nt = config.newTree;
            ObjectReader r = config.reader;
            ObjectInserter i = config.inserter;
            try {
                config.newTree = newTree;
                config.reader = reader;
                config.inserter = inserter;
                return config.onSave(commit);
            } catch (ConfigInvalidException e) {
                throw new IOException(
                        "Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(),
                        e);
            } finally {
                config.newTree = nt;
                config.reader = r;
                config.inserter = i;
            }
        }

        @Override
        public void write(VersionedMetaData config, CommitBuilder commit) throws IOException {
            if (!doSave(config, commit)) {
                return;
            }

            // Reuse tree from parent commit unless there are contents in newTree or
            // there is no tree for a parent commit.
            ObjectId res = newTree.getEntryCount() != 0 || srcTree == null ? newTree.writeTree(inserter)
                    : srcTree.copy();
            if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) {
                // If there are no changes to the content, don't create the commit.
                return;
            }

            // If changes are made to the DirCache and those changes are written as
            // a commit and then the tree ID is set for the CommitBuilder, then
            // those previous DirCache changes will be ignored and the commit's
            // tree will be replaced with the ID in the CommitBuilder. The same is
            // true if you explicitly set tree ID in a commit and then make changes
            // to the DirCache; that tree ID will be ignored and replaced by that of
            // the tree for the updated DirCache.
            if (commit.getTreeId() == null) {
                commit.setTreeId(res);
            } else {
                // In this case, the caller populated the tree without using DirCache.
                res = commit.getTreeId();
            }

            if (src != null) {
                commit.addParentId(src);
            }

            if (update.insertChangeId()) {
                ObjectId id = ChangeIdUtil.computeChangeId(res, getRevision(), commit.getAuthor(),
                        commit.getCommitter(), commit.getMessage());
                commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id));
            }

            src = inserter.insert(commit);
            srcTree = res;
        }

        @Override
        public RevCommit createRef(String refName) throws IOException {
            if (Objects.equals(src, revision)) {
                return revision;
            }
            return updateRef(ObjectId.zeroId(), src, refName);
        }

        @Override
        public void removeRef(String refName) throws IOException {
            RefUpdate ru = db.updateRef(refName);
            ru.setForceUpdate(true);
            if (revision != null) {
                ru.setExpectedOldObjectId(revision);
            }
            RefUpdate.Result result = ru.delete();
            switch (result) {
            case FORCED:
                update.fireGitRefUpdatedEvent(ru);
                return;
            default:
                throw new IOException(
                        "Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }

        @Override
        public RevCommit commit() throws IOException {
            return commitAt(revision);
        }

        @Override
        public RevCommit commitAt(ObjectId expected) throws IOException {
            if (Objects.equals(src, expected)) {
                return revision;
            }
            return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName());
        }

        @Override
        public void close() {
            newTree = null;

            rw.close();
            if (inserter != null) {
                inserter.close();
                inserter = null;
            }

            if (reader != null) {
                reader.close();
                reader = null;
            }
        }

        private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName) throws IOException {
            BatchRefUpdate bru = update.getBatch();
            if (bru != null) {
                bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName));
                inserter.flush();
                revision = rw.parseCommit(newId);
                return revision;
            }

            RefUpdate ru = db.updateRef(refName);
            ru.setExpectedOldObjectId(oldId);
            ru.setNewObjectId(src);
            ru.setRefLogIdent(update.getCommitBuilder().getAuthor());
            String message = update.getCommitBuilder().getMessage();
            if (message == null) {
                message = "meta data update";
            }
            try (BufferedReader reader = new BufferedReader(new StringReader(message))) {
                // read the subject line and use it as reflog message
                ru.setRefLogMessage("commit: " + reader.readLine(), true);
            }
            inserter.flush();
            RefUpdate.Result result = ru.update();
            switch (result) {
            case NEW:
            case FAST_FORWARD:
                revision = rw.parseCommit(ru.getNewObjectId());
                update.fireGitRefUpdatedEvent(ru);
                return revision;
            default:
                throw new IOException(
                        "Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
            }
        }
    };
}