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 void create() throws IOException 

Source Link

Document

Create a new Git repository.

Usage

From source file:getgitdata.TestJGit.java

public void testCreate() throws IOException {
    Repository newRepo = new FileRepository(localPath + ".git");
    newRepo.create();
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws AuthenticationException /*from  ww w. jav a2 s.  co m*/
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, String password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    log.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", localFolder,
            remoteAddress, username);
    try {
        File gitFolder = new File(localFolder, ".git");
        Repository r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            log.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);

        Git git = new Git(r);

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));

        log.debug("Fetching");
        FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();
        log.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();
        for (Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                log.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            //we need to fetch and (maybe) merge - get onto origin/master.

            log.debug("Fetching from remote");
            String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();
            log.debug("Fetch Result: {}", fetchResult);

            log.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            //Get the files from master that we didn't have in our working folder
            log.debug("Checking out missing files from origin/master");
            for (String missing : git.status().call().getMissing()) {
                log.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    log.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            //just push
            //make sure we have something to push
            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding readme file").setAuthor(username, "42").call();
            }

            log.debug("Pushing repository");
            for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                log.debug("Push Result: {}", pr.getMessages());
            }
        }

        log.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:me.seeber.gradle.repository.git.ConfigureLocalGitRepository.java

License:Open Source License

/**
 * Run task//from   w w  w.java 2  s. c  o  m
 *
 * @throws IOException if something really bad happens
 */
@TaskAction
public void configure() throws IOException {
    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    repositoryBuilder.addCeilingDirectory(getProject().getProjectDir());
    repositoryBuilder.findGitDir(getProject().getProjectDir());

    boolean create = (repositoryBuilder.getGitDir() == null);

    repositoryBuilder.setWorkTree(getProject().getProjectDir());

    Repository repository = repositoryBuilder.build();

    if (create) {
        repository.create();
    }

    try (Git git = new Git(repository)) {
        StoredConfig config = git.getRepository().getConfig();

        getRemoteRepositories().forEach((name, url) -> {
            config.setString("remote", name, "url", url);
        });

        config.save();
    }

    File ignoreFile = getProject().file(".gitignore");
    SortedSet<@NonNull String> remainingIgnores = new TreeSet<>(getIgnores());
    List<String> lines = new ArrayList<>();

    if (ignoreFile.exists()) {
        Files.lines(ignoreFile.toPath()).forEach(l -> {
            lines.add(l);

            if (!l.trim().startsWith("#")) {
                remainingIgnores.remove(unescapePattern(l));
            }
        });
    }

    if (!remainingIgnores.isEmpty()) {
        List<@NonNull String> escapedIgnores = remainingIgnores.stream().map(l -> escapePattern(l))
                .collect(Collectors.toList());
        lines.addAll(escapedIgnores);
        Files.write(ignoreFile.toPath(), lines, StandardOpenOption.CREATE);
    }
}

From source file:org.apache.zeppelin.notebook.repo.GitHubNotebookRepoTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    conf = ZeppelinConfiguration.create();

    String remoteRepositoryPath = System.getProperty("java.io.tmpdir") + "/ZeppelinTestRemote_"
            + System.currentTimeMillis();
    String localRepositoryPath = System.getProperty("java.io.tmpdir") + "/ZeppelinTest_"
            + System.currentTimeMillis();

    // Create a fake remote notebook Git repository locally in another directory
    remoteZeppelinDir = new File(remoteRepositoryPath);
    remoteZeppelinDir.mkdirs();/*from   w  w  w.j  a va  2  s.  c  o  m*/

    // Create a local repository for notebooks
    localZeppelinDir = new File(localRepositoryPath);
    localZeppelinDir.mkdirs();

    // Notebooks directory (for both the remote and local directories)
    localNotebooksDir = Joiner.on(File.separator).join(localRepositoryPath, "notebook");
    remoteNotebooksDir = Joiner.on(File.separator).join(remoteRepositoryPath, "notebook");

    File notebookDir = new File(localNotebooksDir);
    notebookDir.mkdirs();

    FileUtils.copyDirectory(new File(GitHubNotebookRepoTest.class.getResource("/notebook").getFile()),
            new File(remoteNotebooksDir));

    // Create the fake remote Git repository
    Repository remoteRepository = new FileRepository(
            Joiner.on(File.separator).join(remoteNotebooksDir, ".git"));
    remoteRepository.create();

    remoteGit = new Git(remoteRepository);
    remoteGit.add().addFilepattern(".").call();
    firstCommitRevision = remoteGit.commit().setMessage("First commit from remote repository").call();

    // Set the Git and Git configurations
    System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_HOME.getVarName(),
            remoteZeppelinDir.getAbsolutePath());
    System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_DIR.getVarName(),
            notebookDir.getAbsolutePath());

    // Set the GitHub configurations
    System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_STORAGE.getVarName(),
            "org.apache.zeppelin.notebook.repo.GitHubNotebookRepo");
    System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_GIT_REMOTE_URL.getVarName(),
            remoteNotebooksDir + File.separator + ".git");
    System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_GIT_REMOTE_USERNAME.getVarName(),
            "token");
    System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_GIT_REMOTE_ACCESS_TOKEN.getVarName(),
            "access-token");

    // Create the Notebook repository (configured for the local repository)
    gitHubNotebookRepo = new GitHubNotebookRepo();
    gitHubNotebookRepo.init(conf);
}

From source file:org.apache.zeppelin.notebook.repo.GitNotebookRepo.java

License:Apache License

@Override
public void init(ZeppelinConfiguration conf) throws IOException {
    //TODO(zjffdu), it is weird that I can not call super.init directly here, as it would cause
    //AbstractMethodError
    this.conf = conf;
    setNotebookDirectory(conf.getNotebookDir());

    LOGGER.info("Opening a git repo at '{}'", this.rootNotebookFolder);
    Repository localRepo = new FileRepository(Joiner.on(File.separator).join(this.rootNotebookFolder, ".git"));
    if (!localRepo.getDirectory().exists()) {
        LOGGER.info("Git repo {} does not exist, creating a new one", localRepo.getDirectory());
        localRepo.create();
    }//from  w  w  w .j ava  2 s . co m
    git = new Git(localRepo);
}

From source file:org.apache.zeppelin.notebook.repo.OldGitNotebookRepo.java

License:Apache License

@Override
public void init(ZeppelinConfiguration conf) throws IOException {
    //TODO(zjffdu), it is weird that I can not call super.init directly here, as it would cause
    //AbstractMethodError
    this.conf = conf;
    setNotebookDirectory(conf.getNotebookDir());

    localPath = getRootDir().getName().getPath();
    LOG.info("Opening a git repo at '{}'", localPath);
    Repository localRepo = new FileRepository(Joiner.on(File.separator).join(localPath, ".git"));
    if (!localRepo.getDirectory().exists()) {
        LOG.info("Git repo {} does not exist, creating a new one", localRepo.getDirectory());
        localRepo.create();
    }/*from www .jav a  2 s. c o m*/
    git = new Git(localRepo);
}

From source file:org.archicontribs.modelrepository.GitHelper.java

License:Open Source License

public static Repository createNewRepository(File localPath) throws IOException {
    Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create();
    return repository;
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private boolean createEnvironmentStoreRepository(String site) {
    boolean success = true;
    Path siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment);
    try {/*w w w  .  ja va2  s  .  c o  m*/
        Files.deleteIfExists(siteEnvironmentStoreRepoPath);
        siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment, ".git");
        Repository repository = FileRepositoryBuilder.create(siteEnvironmentStoreRepoPath.toFile());
        repository.create();

        Git git = new Git(repository);
        git.add().addFilepattern(".").call();
        RevCommit commit = git.commit().setMessage("initial content").setAllowEmpty(true).call();
    } catch (IOException | GitAPIException e) {
        logger.error("Error while creating repository for site " + site, e);
        success = false;
    }
    return success;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java

License:Open Source License

public Repository createGitRepository(Path path) {
    Repository toReturn;
    path = Paths.get(path.toAbsolutePath().toString(), GIT_ROOT);
    try {/*from  w  w  w  .ja va2 s. co  m*/
        toReturn = FileRepositoryBuilder.create(path.toFile());
        toReturn.create();

        // Get git configuration
        StoredConfig config = toReturn.getConfig();
        // Set compression level (core.compression)
        config.setInt(CONFIG_SECTION_CORE, null, CONFIG_PARAMETER_COMPRESSION,
                CONFIG_PARAMETER_COMPRESSION_DEFAULT);
        // Set big file threshold (core.bigFileThreshold)
        config.setString(CONFIG_SECTION_CORE, null, CONFIG_PARAMETER_BIG_FILE_THRESHOLD,
                CONFIG_PARAMETER_BIG_FILE_THRESHOLD_DEFAULT);
        // Save configuration changes
        config.save();
    } catch (IOException e) {
        logger.error("Error while creating repository for site with path" + path.toString(), e);
        toReturn = null;
    }

    return toReturn;
}

From source file:org.dstadler.jgit.helper.CookbookHelper.java

License:Apache License

public static Repository createNewRepository() throws IOException {
    // prepare a new folder
    File localPath = File.createTempFile("TestGitRepository", "");
    if (!localPath.delete()) {
        throw new IOException("Could not delete temporary file " + localPath);
    }/*from  w  w  w.j  ava  2 s. c o  m*/

    // create the directory
    Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create();

    return repository;
}