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

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

Introduction

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

Prototype

public abstract void create(boolean bare) throws IOException;

Source Link

Document

Create a new Git repository initializing the necessary files and directories.

Usage

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);
    }/*from   w  w  w.j a  va 2  s .c o m*/

    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.osbitools.ws.shared.prj.web.AbstractWsPrjInit.java

License:LGPL

public static Git createGitRepo(File dir) throws Exception {
    Repository repo = FileRepositoryBuilder.create(dir);
    repo.create(false);

    Git git = new Git(repo);

    // Commit first revision
    git.commit().setMessage("Repository created").call();

    return git;//from   w  ww .  j a  va 2 s  .  c  o m
}

From source file:git_manager.tool.GitOperations.java

License:Open Source License

public void initBareRepo() {
    Repository repo;
    try {/*from  w  ww . j a v a 2s.  c o  m*/
        repo = new FileRepository(thisDir);
        repo.create(true);
        System.out.println("Bare repo created.");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java

License:Apache License

/**
 * Ensures that a bare repository exists at the specified path.
 * If it does not, the directory is attempted to be created.
 *
 * @param dir    the path to the directory to init
 * @param remote the remote URL//  w w  w . j  a  v a2  s  .  c  o  m
 * @return a connection to repository
 * @throws VcsException if the there is a problem with accessing VCS
 */
public static Repository getRepository(@NotNull final File dir, @NotNull final URIish remote)
        throws VcsException {
    if (dir.exists() && !dir.isDirectory()) {
        throw new VcsException("The specified path is not a directory: " + dir);
    }
    try {
        ensureRepositoryIsValid(dir);
        Repository r = new RepositoryBuilder().setBare().setGitDir(dir).build();
        if (!new File(dir, "config").exists()) {
            r.create(true);
            final StoredConfig config = r.getConfig();
            config.setString("teamcity", null, "remote", remote.toString());
            config.save();
        } else {
            final StoredConfig config = r.getConfig();
            final String existingRemote = config.getString("teamcity", null, "remote");
            if (existingRemote != null && !remote.toString().equals(existingRemote)) {
                throw getWrongUrlError(dir, existingRemote, remote);
            } else if (existingRemote == null) {
                config.setString("teamcity", null, "remote", remote.toString());
                config.save();
            }
        }
        return r;
    } catch (Exception ex) {
        if (ex instanceof NullPointerException)
            LOG.warn("The repository at directory '" + dir + "' cannot be opened or created", ex);
        throw new VcsException("The repository at directory '" + dir + "' cannot be opened or created, reason: "
                + ex.toString(), ex);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.GitCommitSupportTest.java

License:Apache License

@TestFor(issues = "TW-39051")
public void should_create_branch_if_repository_has_no_branches() throws Exception {
    String nonExistingBranch = "refs/heads/nonExisting";

    File remoteRepo = myTempFiles.createTempDir();
    Repository r = new RepositoryBuilder().setBare().setGitDir(remoteRepo).build();
    r.create(true);
    VcsRoot root = vcsRoot().withFetchUrl(remoteRepo).withBranch(nonExistingBranch).build();

    CommitPatchBuilder patchBuilder = myCommitSupport.getCommitPatchBuilder(root);
    byte[] bytes = "test-content".getBytes();
    patchBuilder.createFile("file-to-commit", new ByteArrayInputStream(bytes));
    patchBuilder.commit(new CommitSettingsImpl("user", "Commit description"));
    patchBuilder.dispose();// w  ww  .ja v  a  2  s.c o  m

    RepositoryStateData state2 = myGit.getCurrentState(root);
    assertNotNull(state2.getBranchRevisions().get(nonExistingBranch));
}

From source file:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java

License:Apache License

@Test
public void testOpenExistingRepository() throws Exception {
    final String REPO_NAME = "testOpenExistingRepository";
    File expected = new File(reposDir, REPO_NAME + Constants.DOT_GIT_EXT);
    if (!expected.exists()) {
        Repository repo = new FileRepository(expected);
        try {/*w  w w. j a va2 s .  c o  m*/
            repo.create(true);
        } finally {
            repo.close();
        }
    } else {
        assertTrue("Test repo not a folder: " + expected, expected.isDirectory());
    }

    for (String ext : TEST_EXTS) {
        Repository repo = resolver.open(null, REPO_NAME + ext);
        assertNotNull("No resolution result for ext=" + ext, repo);

        try {
            File actual = repo.getDirectory();
            assertEquals("Mismatched resolved location for ext=" + ext, expected, actual);
        } finally {
            repo.close();
        }
    }
}

From source file:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java

License:Apache License

@Test
public void testDeepDownRepositoryResolution() throws Exception {
    final String REPO_NAME = "testDeepDownRepositoryResolution", GIT_NAME = REPO_NAME + Constants.DOT_GIT_EXT;
    final int MAX_DEPTH = Byte.SIZE;
    StringBuilder sb = new StringBuilder(MAX_DEPTH + Long.SIZE);
    File parentDir = reposDir;//ww  w  . ja  v a2 s  . c  om
    for (int depth = 0; depth < MAX_DEPTH; depth++) {
        String subName = String.valueOf(depth);
        parentDir = new File(parentDir, subName);
        sb.append(subName).append('/');

        File gitDir = new File(parentDir, GIT_NAME);
        if (!gitDir.exists()) {
            Repository repo = new FileRepository(gitDir);
            try {
                repo.create(true);
            } finally {
                repo.close();
            }
        } else {
            assertTrue("Child repo not a folder: " + gitDir, gitDir.isDirectory());
        }

        int curLen = sb.length();
        try {
            sb.append(REPO_NAME);

            int baseLen = sb.length();
            for (String ext : TEST_EXTS) {
                try {
                    Repository repo = resolver.open(null, sb.append(ext).toString());
                    assertNotNull("No resolution result for ext=" + ext, repo);

                    try {
                        File actual = repo.getDirectory();
                        assertEquals("Mismatched resolved location for ext=" + ext, gitDir, actual);
                    } finally {
                        repo.close();
                    }
                } finally {
                    sb.setLength(baseLen);
                }
            }
        } finally {
            sb.setLength(curLen);
        }
    }
}

From source file:net.polydawn.mdm.commands.MdmReleaseInitCommand.java

License:Open Source License

/**
 * Initialize a new non-bare repository at {@link #path}.
 *
 * @return handle to the repository created.
 *
 * @throws MdmRepositoryIOException//from  www  .  ja  v a  2 s.  c  o m
 */
Repository makeReleaseRepo() {
    try {
        Repository releaserepo = new RepositoryBuilder().setWorkTree(new File(path).getCanonicalFile()).build();
        releaserepo.create(false);
        return releaserepo;
    } catch (IOException e) {
        throw new MdmRepositoryIOException("create a release repo", true, path, e);
    }
}

From source file:org.apache.gobblin.service.modules.flow.MultiHopFlowCompilerTest.java

License:Apache License

@Test(dependsOnMethods = "testMulticastPath")
public void testGitFlowGraphMonitorService()
        throws IOException, GitAPIException, URISyntaxException, InterruptedException {
    File remoteDir = new File(TESTDIR + "/remote");
    File cloneDir = new File(TESTDIR + "/clone");
    File flowGraphDir = new File(cloneDir, "/gobblin-flowgraph");

    //Clean up/*from   w  w w.ja v a 2 s  .  c  om*/
    cleanUpDir(TESTDIR);

    // Create a bare repository
    RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED);
    Repository remoteRepo = fileKey.open(false);
    remoteRepo.create(true);

    Git gitForPush = Git.cloneRepository().setURI(remoteRepo.getDirectory().getAbsolutePath())
            .setDirectory(cloneDir).call();

    // push an empty commit as a base for detecting changes
    gitForPush.commit().setMessage("First commit").call();
    RefSpec masterRefSpec = new RefSpec("master");
    gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();

    URI flowTemplateCatalogUri = this.getClass().getClassLoader().getResource("template_catalog").toURI();

    Config config = ConfigBuilder.create()
            .addPrimitive(
                    GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                            + ConfigurationKeys.GIT_MONITOR_REPO_URI,
                    remoteRepo.getDirectory().getAbsolutePath())
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TESTDIR + "/git-flowgraph")
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5)
            .addPrimitive(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY,
                    flowTemplateCatalogUri.toString())
            .build();

    //Create a MultiHopFlowCompiler instance
    specCompiler = new MultiHopFlowCompiler(config, Optional.absent(), false);

    specCompiler.setActive(true);

    //Ensure node1 is not present in the graph
    Assert.assertNull(specCompiler.getFlowGraph().getNode("node1"));

    // push a new node file
    File nodeDir = new File(flowGraphDir, "node1");
    File nodeFile = new File(nodeDir, "node1.properties");
    nodeDir.mkdirs();
    nodeFile.createNewFile();
    Files.write(FlowGraphConfigurationKeys.DATA_NODE_IS_ACTIVE_KEY + "=true\nparam1=val1" + "\n", nodeFile,
            Charsets.UTF_8);

    // add, commit, push node
    gitForPush.add().addFilepattern(formNodeFilePath(flowGraphDir, nodeDir.getName(), nodeFile.getName()))
            .call();
    gitForPush.commit().setMessage("Node commit").call();
    gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();

    // polling is every 5 seconds, so wait twice as long and check
    TimeUnit.SECONDS.sleep(10);

    //Test that a DataNode is added to FlowGraph
    DataNode dataNode = specCompiler.getFlowGraph().getNode("node1");
    Assert.assertEquals(dataNode.getId(), "node1");
    Assert.assertEquals(dataNode.getRawConfig().getString("param1"), "val1");
}

From source file:org.eclipse.egit.ui.internal.push.PushBranchWizardTest.java

License:Open Source License

private Repository createRemoteRepository() throws IOException {
    File gitDir = new File(getTestDirectory(), "pushbranchremote");
    Repository repo = FileRepositoryBuilder.create(gitDir);
    repo.create(true);
    assertTrue(repo.isBare());// ww w . j ava2s. co m
    return repo;
}