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.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Updates the last changed fields and optionally calculates the size of the
 * repository.  Gitblit caches the repository sizes to reduce the performance
 * penalty of recursive calculation. The cache is updated if the repository
 * has been changed since the last calculation.
 *
 * @param model/*from   ww w .ja  v  a  2s  .c o  m*/
 * @return size in bytes of the repository
 */
@Override
public long updateLastChangeFields(Repository r, RepositoryModel model) {
    LastChange lc = JGitUtils.getLastChange(r);
    model.lastChange = lc.when;
    model.lastChangeAuthor = lc.who;

    if (!settings.getBoolean(Keys.web.showRepositorySizes, true) || model.skipSizeCalculation) {
        model.size = null;
        return 0L;
    }
    if (!repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
        File gitDir = r.getDirectory();
        long sz = com.gitblit.utils.FileUtils.folderSize(gitDir);
        repositorySizeCache.updateObject(model.name, model.lastChange, sz);
    }
    long size = repositorySizeCache.getObject(model.name);
    ByteFormat byteFormat = new ByteFormat();
    model.size = byteFormat.format(size);
    return size;
}

From source file:com.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Returns true if the repository is idle (not being accessed).
 *
 * @param repository//w w w  .  j  a  v a  2 s .  c o  m
 * @return true if the repository is idle
 */
@Override
public boolean isIdle(Repository repository) {
    try {
        // Read the use count.
        // An idle use count is 2:
        // +1 for being in the cache
        // +1 for the repository parameter in this method
        Field useCnt = Repository.class.getDeclaredField("useCnt");
        useCnt.setAccessible(true);
        int useCount = ((AtomicInteger) useCnt.get(repository)).get();
        return useCount == 2;
    } catch (Exception e) {
        logger.warn(MessageFormat.format("Failed to reflectively determine use count for repository {0}",
                repository.getDirectory().getPath()), e);
    }
    return false;
}

From source file:com.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Creates/updates the repository model keyed by repositoryName. Saves all
 * repository settings in .git/config. This method allows for renaming
 * repositories and will update user access permissions accordingly.
 *
 * All repositories created by this method are bare and automatically have
 * .git appended to their names, which is the standard convention for bare
 * repositories./*from   w w w  .j  a v  a 2  s.c  o  m*/
 *
 * @param repositoryName
 * @param repository
 * @param isCreate
 * @throws GitBlitException
 */
@Override
public void updateRepositoryModel(String repositoryName, RepositoryModel repository, boolean isCreate)
        throws GitBlitException {
    if (isCollectingGarbage(repositoryName)) {
        throw new GitBlitException(
                MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}", repositoryName));
    }
    Repository r = null;
    String projectPath = StringUtils.getFirstPathElement(repository.name);
    if (!StringUtils.isEmpty(projectPath)) {
        if (projectPath.equalsIgnoreCase(settings.getString(Keys.web.repositoryRootGroupName, "main"))) {
            // strip leading group name
            repository.name = repository.name.substring(projectPath.length() + 1);
        }
    }
    boolean isRename = false;
    if (isCreate) {
        // ensure created repository name ends with .git
        if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
            repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
        }
        if (hasRepository(repository.name)) {
            throw new GitBlitException(MessageFormat
                    .format("Can not create repository ''{0}'' because it already exists.", repository.name));
        }
        // create repository
        logger.info("create repository " + repository.name);
        String shared = settings.getString(Keys.git.createRepositoriesShared, "FALSE");
        r = JGitUtils.createRepository(repositoriesFolder, repository.name, shared);
    } else {
        // rename repository
        isRename = !repositoryName.equalsIgnoreCase(repository.name);
        if (isRename) {
            if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
                repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
            }
            if (new File(repositoriesFolder, repository.name).exists()) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to rename ''{0}'' because ''{1}'' already exists.",
                                repositoryName, repository.name));
            }
            close(repositoryName);
            File folder = new File(repositoriesFolder, repositoryName);
            File destFolder = new File(repositoriesFolder, repository.name);
            if (destFolder.exists()) {
                throw new GitBlitException(MessageFormat.format(
                        "Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
                        repositoryName, repository.name));
            }
            File parentFile = destFolder.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
            }
            if (!folder.renameTo(destFolder)) {
                throw new GitBlitException(MessageFormat.format(
                        "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName, repository.name));
            }
            // rename the roles
            if (!userManager.renameRepositoryRole(repositoryName, repository.name)) {
                throw new GitBlitException(
                        MessageFormat.format("Failed to rename repository permissions ''{0}'' to ''{1}''.",
                                repositoryName, repository.name));
            }

            // rename fork origins in their configs
            if (!ArrayUtils.isEmpty(repository.forks)) {
                for (String fork : repository.forks) {
                    Repository rf = getRepository(fork);
                    try {
                        StoredConfig config = rf.getConfig();
                        String origin = config.getString("remote", "origin", "url");
                        origin = origin.replace(repositoryName, repository.name);
                        config.setString("remote", "origin", "url", origin);
                        config.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.name);
                        config.save();
                    } catch (Exception e) {
                        logger.error("Failed to update repository fork config for " + fork, e);
                    }
                    rf.close();
                }
            }

            // update this repository's origin's fork list
            if (!StringUtils.isEmpty(repository.originRepository)) {
                String originKey = getRepositoryKey(repository.originRepository);
                RepositoryModel origin = repositoryListCache.get(originKey);
                if (origin != null && !ArrayUtils.isEmpty(origin.forks)) {
                    origin.forks.remove(repositoryName);
                    origin.forks.add(repository.name);
                }
            }

            // clear the cache
            clearRepositoryMetadataCache(repositoryName);
            repository.resetDisplayName();
        }

        // load repository
        logger.info("edit repository " + repository.name);
        r = getRepository(repository.name);
    }

    // update settings
    if (r != null) {
        updateConfiguration(r, repository);
        // Update the description file
        File descFile = new File(r.getDirectory(), "description");
        if (repository.description != null) {
            com.gitblit.utils.FileUtils.writeContent(descFile, repository.description);
        } else if (descFile.exists() && !descFile.isDirectory()) {
            descFile.delete();
        }
        // only update symbolic head if it changes
        String currentRef = JGitUtils.getHEADRef(r);
        if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
            logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}", repository.name, currentRef,
                    repository.HEAD));
            if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
                // clear the cache
                clearRepositoryMetadataCache(repository.name);
            }
        }

        // Adjust permissions in case we updated the config files
        JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "config"),
                settings.getString(Keys.git.createRepositoriesShared, "FALSE"));
        JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "HEAD"),
                settings.getString(Keys.git.createRepositoriesShared, "FALSE"));

        // close the repository object
        r.close();
    }

    // update repository cache
    removeFromCachedRepositoryList(repositoryName);
    // model will actually be replaced on next load because config is stale
    addToCachedRepositoryList(repository);

    if (isCreate && pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager
                .getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onCreation(repository);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onCreation %s", repositoryName), t);
            }
        }
    } else if (isRename && pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager
                .getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onRename(repositoryName, repository);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onRename %s", repositoryName), t);
            }
        }
    }
}

From source file:com.gitblit.service.LuceneService.java

License:Apache License

/**
 * Returns the Lucene configuration for the specified repository.
 *
 * @param repository/*  w w  w . j a va  2s  .  c om*/
 * @return a config object
 */
private FileBasedConfig getConfig(Repository repository) {
    LuceneRepoIndexStore luceneIndex = new LuceneRepoIndexStore(repository.getDirectory(), INDEX_VERSION);
    FileBasedConfig config = new FileBasedConfig(luceneIndex.getConfigFile(), FS.detect());
    return config;
}

From source file:com.gitblit.service.LuceneService.java

License:Apache License

/**
 * Checks if an index exists for the repository, that is compatible with
 * INDEX_VERSION and the Lucene version.
 *
 * @param repository//from  w  w  w  .  ja v  a 2  s  . c o m
 * @return true if no index is found for the repository, false otherwise.
 */
private boolean shouldReindex(Repository repository) {
    return !(new LuceneRepoIndexStore(repository.getDirectory(), INDEX_VERSION).hasIndex());
}

From source file:com.gitblit.tests.GitBlitTest.java

License:Apache License

@Test
public void testRepositoryModel() throws Exception {
    List<String> repositories = repositories().getRepositoryList();
    assertTrue("Repository list is empty!", repositories.size() > 0);
    assertTrue("Missing Helloworld repository!",
            repositories.contains(GitBlitSuite.getHelloworldRepository().getDirectory().getName()));
    Repository r = GitBlitSuite.getHelloworldRepository();
    RepositoryModel model = repositories().getRepositoryModel(r.getDirectory().getName());
    assertTrue("Helloworld model is null!", model != null);
    assertEquals(GitBlitSuite.getHelloworldRepository().getDirectory().getName(), model.name);
    assertTrue(repositories().updateLastChangeFields(r, model) > 22000L);
    r.close();//from ww  w .j a  v  a  2s .c o  m
}

From source file:com.gitblit.tests.IssuesTest.java

License:Apache License

@Test
public void testLifecycle() throws Exception {
    Repository repository = GitBlitSuite.getIssuesTestRepository();
    String name = FileUtils.getRelativePath(GitBlitSuite.REPOSITORIES, repository.getDirectory());

    // create and insert an issue
    Change c1 = newChange("testCreation() " + Long.toHexString(System.currentTimeMillis()));
    IssueModel issue = IssueUtils.createIssue(repository, c1);
    assertNotNull(issue.id);//from w ww .  ja  v a2  s .  c  o m

    // retrieve issue and compare
    IssueModel constructed = IssueUtils.getIssue(repository, issue.id);
    compare(issue, constructed);

    assertEquals(1, constructed.changes.size());

    // C1: create the issue
    c1 = newChange("testUpdates() " + Long.toHexString(System.currentTimeMillis()));
    issue = IssueUtils.createIssue(repository, c1);
    assertNotNull(issue.id);

    constructed = IssueUtils.getIssue(repository, issue.id);
    compare(issue, constructed);
    assertEquals(1, constructed.changes.size());

    // C2: set owner
    Change c2 = new Change("C2");
    c2.comment("I'll fix this");
    c2.setField(Field.Owner, c2.author);
    assertTrue(IssueUtils.updateIssue(repository, issue.id, c2));
    constructed = IssueUtils.getIssue(repository, issue.id);
    assertEquals(2, constructed.changes.size());
    assertEquals(c2.author, constructed.owner);

    // C3: add a note
    Change c3 = new Change("C3");
    c3.comment("yeah, this is working");
    assertTrue(IssueUtils.updateIssue(repository, issue.id, c3));
    constructed = IssueUtils.getIssue(repository, issue.id);
    assertEquals(3, constructed.changes.size());

    // C4: add attachment
    Change c4 = new Change("C4");
    Attachment a = newAttachment();
    c4.addAttachment(a);
    assertTrue(IssueUtils.updateIssue(repository, issue.id, c4));

    Attachment a1 = IssueUtils.getIssueAttachment(repository, issue.id, a.name);
    assertEquals(a.content.length, a1.content.length);
    assertTrue(Arrays.areEqual(a.content, a1.content));

    // C5: close the issue
    Change c5 = new Change("C5");
    c5.comment("closing issue");
    c5.setField(Field.Status, Status.Fixed);
    assertTrue(IssueUtils.updateIssue(repository, issue.id, c5));

    // retrieve issue again
    constructed = IssueUtils.getIssue(repository, issue.id);

    assertEquals(5, constructed.changes.size());
    assertTrue(constructed.status.isClosed());

    List<IssueModel> allIssues = IssueUtils.getIssues(repository, null);
    List<IssueModel> openIssues = IssueUtils.getIssues(repository, new IssueFilter() {
        @Override
        public boolean accept(IssueModel issue) {
            return !issue.status.isClosed();
        }
    });
    List<IssueModel> closedIssues = IssueUtils.getIssues(repository, new IssueFilter() {
        @Override
        public boolean accept(IssueModel issue) {
            return issue.status.isClosed();
        }
    });

    assertTrue(allIssues.size() > 0);
    assertEquals(1, openIssues.size());
    assertEquals(1, closedIssues.size());

    // build a new Lucene index
    LuceneExecutor lucene = new LuceneExecutor(null, GitBlitSuite.REPOSITORIES);
    lucene.deleteIndex(name);
    for (IssueModel anIssue : allIssues) {
        lucene.index(name, anIssue);
    }
    List<SearchResult> hits = lucene.search("working", 1, 10, name);
    assertTrue(hits.size() == 1);

    // reindex an issue
    issue = allIssues.get(0);
    Change change = new Change("reindex");
    change.comment("this is a test of reindexing an issue");
    IssueUtils.updateIssue(repository, issue.id, change);
    issue = IssueUtils.getIssue(repository, issue.id);
    lucene.index(name, issue);

    hits = lucene.search("working", 1, 10, name);
    assertTrue(hits.size() == 1);

    // delete all issues
    for (IssueModel anIssue : allIssues) {
        assertTrue(IssueUtils.deleteIssue(repository, anIssue.id, "D"));
    }

    lucene.close();
    repository.close();
}

From source file:com.gitblit.tests.JGitUtilsTest.java

License:Apache License

@Test
public void testCreateRepository() throws Exception {
    String[] repositories = { "NewTestRepository.git", "NewTestRepository" };
    for (String repositoryName : repositories) {
        Repository repository = JGitUtils.createRepository(GitBlitSuite.REPOSITORIES, repositoryName);
        File folder = FileKey.resolve(new File(GitBlitSuite.REPOSITORIES, repositoryName), FS.DETECTED);
        assertNotNull(repository);/* w  ww.j  av  a  2  s. co m*/
        assertFalse(JGitUtils.hasCommits(repository));
        assertNull(JGitUtils.getFirstCommit(repository, null));
        assertEquals(folder.lastModified(), JGitUtils.getFirstChange(repository, null).getTime());
        assertEquals(folder.lastModified(), JGitUtils.getLastChange(repository).when.getTime());
        assertNull(JGitUtils.getCommit(repository, null));
        repository.close();
        RepositoryCache.close(repository);
        FileUtils.delete(repository.getDirectory(), FileUtils.RECURSIVE);
    }
}

From source file:com.gitblit.tests.JGitUtilsTest.java

License:Apache License

@Test
public void testCreateRepositoryShared() throws Exception {
    String[] repositories = { "NewSharedTestRepository.git" };
    for (String repositoryName : repositories) {
        Repository repository = JGitUtils.createRepository(GitBlitSuite.REPOSITORIES, repositoryName, "group");
        File folder = FileKey.resolve(new File(GitBlitSuite.REPOSITORIES, repositoryName), FS.DETECTED);
        assertNotNull(repository);//from   w  w  w  .ja  v  a2  s.  c  o m
        assertFalse(JGitUtils.hasCommits(repository));
        assertNull(JGitUtils.getFirstCommit(repository, null));

        assertEquals("1", repository.getConfig().getString("core", null, "sharedRepository"));

        assertTrue(folder.exists());
        if (!JnaUtils.isWindows()) {
            int mode = JnaUtils.getFilemode(folder);
            assertEquals(JnaUtils.S_ISGID, mode & JnaUtils.S_ISGID);
            assertEquals(JnaUtils.S_IRWXG, mode & JnaUtils.S_IRWXG);

            mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/HEAD");
            assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG);

            mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/config");
            assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG);
        }

        repository.close();
        RepositoryCache.close(repository);
        FileUtils.delete(repository.getDirectory(), FileUtils.RECURSIVE);
    }
}

From source file:com.gitblit.tests.JGitUtilsTest.java

License:Apache License

@Test
public void testCreateRepositorySharedCustom() throws Exception {
    String[] repositories = { "NewSharedTestRepository.git" };
    for (String repositoryName : repositories) {
        Repository repository = JGitUtils.createRepository(GitBlitSuite.REPOSITORIES, repositoryName, "660");
        File folder = FileKey.resolve(new File(GitBlitSuite.REPOSITORIES, repositoryName), FS.DETECTED);
        assertNotNull(repository);//from  ww  w .ja  va 2 s  .c o  m
        assertFalse(JGitUtils.hasCommits(repository));
        assertNull(JGitUtils.getFirstCommit(repository, null));

        assertEquals("0660", repository.getConfig().getString("core", null, "sharedRepository"));

        assertTrue(folder.exists());
        if (!JnaUtils.isWindows()) {
            int mode = JnaUtils.getFilemode(folder);
            assertEquals(JnaUtils.S_ISGID, mode & JnaUtils.S_ISGID);
            assertEquals(JnaUtils.S_IRWXG, mode & JnaUtils.S_IRWXG);
            assertEquals(0, mode & JnaUtils.S_IRWXO);

            mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/HEAD");
            assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG);
            assertEquals(0, mode & JnaUtils.S_IRWXO);

            mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/config");
            assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG);
            assertEquals(0, mode & JnaUtils.S_IRWXO);
        }

        repository.close();
        RepositoryCache.close(repository);
        FileUtils.delete(repository.getDirectory(), FileUtils.RECURSIVE);
    }
}