Example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder

List of usage examples for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder

Introduction

In this page you can find the example usage for org.eclipse.jgit.storage.file FileRepositoryBuilder FileRepositoryBuilder.

Prototype

FileRepositoryBuilder

Source Link

Usage

From source file:org.xwiki.git.GitHelper.java

License:Open Source License

public Repository createGitTestRepository(String repoName) throws Exception {
    File localDirectory = getRepositoryFile(repoName);
    File gitDirectory = new File(localDirectory, ".git");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(gitDirectory).readEnvironment().findGitDir().build();
    if (!gitDirectory.exists()) {
        repository.create();//from  w w w  . ja v  a  2 s  . co m
    }
    return repository;
}

From source file:org.xwiki.git.internal.DefaultGitManager.java

License:Open Source License

@Override
public Repository getRepository(String repositoryURI, String localDirectoryName) {
    Repository repository;/*from   w  w w . j a v  a  2 s  . co  m*/

    File localGitDirectory = new File(this.environment.getPermanentDirectory(), "git");
    File localDirectory = new File(localGitDirectory, localDirectoryName);
    File gitDirectory = new File(localDirectory, ".git");
    this.logger.debug("Local Git repository is at [{}]", gitDirectory);
    FileRepositoryBuilder builder = new FileRepositoryBuilder();

    try {
        // Step 1: Initialize Git environment
        repository = builder.setGitDir(gitDirectory).readEnvironment().findGitDir().build();
        Git git = new Git(repository);

        // Step 2: Verify if the directory exists and isn't empty.
        if (!gitDirectory.exists()) {
            // Step 2.1: Need to clone the remote repository since it doesn't exist
            git.cloneRepository().setDirectory(localDirectory).setURI(repositoryURI).call();
        }
    } catch (Exception e) {
        throw new RuntimeException(String.format("Failed to execute Git command in [%s]", gitDirectory), e);
    }

    return repository;
}

From source file:org.xwiki.git.internal.GitScriptService.java

License:Open Source License

/**
 * Clone a Git repository by storing it locally in the XWiki Permanent directory. If the repository is already
 * cloned, no action is done./*w ww. j a  va  2  s  .c o m*/
 *
 * @param repositoryURI the URI to the Git repository to clone (eg "git://github.com/xwiki/xwiki-commons.git")
 * @param localDirectoryName the name of the directory where the Git repository will be cloned (this directory is
 *        relative to the permanent directory
 * @return the cloned Repository instance
 */
public Repository getRepository(String repositoryURI, String localDirectoryName) {
    Repository repository;

    File localDirectory = new File(this.environment.getPermanentDirectory(), "git/" + localDirectoryName);
    File gitDirectory = new File(localDirectory, ".git");
    this.logger.debug("Local Git repository is at [{}]", gitDirectory);
    FileRepositoryBuilder builder = new FileRepositoryBuilder();

    try {
        // Step 1: Initialize Git environment
        repository = builder.setGitDir(gitDirectory).readEnvironment().findGitDir().build();
        Git git = new Git(repository);

        // Step 2: Verify if the directory exists and isn't empty.
        if (!gitDirectory.exists()) {
            // Step 2.1: Need to clone the remote repository since it doesn't exist
            git.cloneRepository().setDirectory(localDirectory).setURI(repositoryURI).call();
        }
    } catch (Exception e) {
        throw new RuntimeException(String.format("Failed to execute Git command in [%s]", gitDirectory), e);
    }

    return repository;
}

From source file:org.xwiki.git.internal.GitScriptServiceTest.java

License:Open Source License

private File createGitTestRepository(String repoName) throws Exception {
    File localDirectory = getRepositoryFile(repoName);
    File gitDirectory = new File(localDirectory, ".git");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(gitDirectory).readEnvironment().findGitDir().build();
    repository.create();/*  w  w  w  . j a  v a  2s . c o  m*/
    return repository.getDirectory();
}

From source file:pl.nask.hsn2.framework.workflow.repository.GitWorkflowRepository.java

License:Open Source License

public GitWorkflowRepository(String repositoryPath, boolean forceCreate) throws WorkflowRepoException {

    repoDir = new File(repositoryPath);
    ensureDirExists(repoDir, forceCreate);
    ensureDirIsWritable(repoDir);/* w ww . jav a2s  .c o m*/

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {
        // expecting repositoryPath to be exact, so 'findGitDir()' is not required here
        repo = builder.setWorkTree(repoDir).findGitDir(repoDir).build();

        if (forceCreate && !repo.getConfig().getFile().exists() && checkRepoMightBeCreated(repoDir)) {
            LOGGER.debug("Workflow repository structure does't exist, trying to create one...");
            repo.create();
        }
        if (!repo.getConfig().getFile().exists()) {
            throw new WorkflowRepoException(
                    "Workflow repository structure doesn't exist and cannot be created or is not forced.");
        }
        validateGitRepo();
    } catch (IOException e) {
        throw new WorkflowRepoException("Couldn't create repository for path: " + repoDir.getAbsolutePath(), e);
    }
}

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

License:Open Source License

@NotNull
private Repository getGitRepository() throws MojoExecutionException {
    Repository repository;/* www  .j  av a2s .  c o m*/

    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    try {
        repository = repositoryBuilder.setGitDir(dotGitDirectory).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not initialize repository...", e);
    }

    if (repository == null) {
        throw new MojoExecutionException("Could not create git repository. Are you sure '" + dotGitDirectory
                + "' is the valid Git root for your project?");
    }

    return repository;
}

From source file:plumber.core.git.GitWorker.java

License:Apache License

public void init() throws IOException, GitAPIException {
    File gitFolder = new File(gitPath);
    File gitDB = new File(gitFolder, ".git");
    if (gitDB.exists() && gitDB.isDirectory()) {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitDB).readEnvironment().findGitDir().build();
        git = new Git(repository);
    } else {//  w w  w.j  av  a2  s.c  o m
        CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI(gitUrl);
        cloneCommand.setDirectory(gitFolder);
        cloneCommand.setTransportConfigCallback(sshTransportConfigCallback);
        git = cloneCommand.call();
    }
}

From source file:pt.up.fe.specs.psfbuilder.GitBranch.java

License:Apache License

public static GitBranch newInstance(File location) {
    FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder().findGitDir(location.getAbsoluteFile());

    if (repoBuilder.getGitDir() == null) {
        throw new RuntimeException("Could not find a git repository for folder '"
                + SpecsIo.getWorkingDir().getAbsolutePath() + "'");
    }/*w  ww. j a  va2 s . c o  m*/

    // Open an existing repository
    try (Repository repo = repoBuilder.build()) {
        StoredConfig config = repo.getConfig();
        Set<String> remotes = config.getSubsections("remote");

        if (remotes.isEmpty()) {
            throw new RuntimeException("Could not find a remote in '" + repo.getWorkTree() + "'");
        }

        // Get a remote. Try origin first, if not found, get the first on the list
        String remoteName = getRemoteName(remotes);
        String remote = config.getString("remote", remoteName, "url");

        Set<String> branches = config.getSubsections("branch");
        if (branches.isEmpty()) {
            throw new RuntimeException("Could not find a branch in '" + repo.getWorkTree() + "'");
        }

        String branch = getBranchName(branches);

        return new GitBranch(repo.getWorkTree(), remote, branch);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

}

From source file:replicatorg.app.ui.panels.UpdateChecker.java

License:Open Source License

private void updateFilaments() {
    final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
    final Git git;
    final Status repoStatus;
    final RemoteAddCommand remoteAddCmd;
    ResetCommand resetCmd;//from w  w  w . j av a  2 s .  c o  m
    CheckoutCommand checkoutCmd;
    final String currentBranch, newBranch;
    final List<Ref> branchList;
    Repository filamentsRepo;
    boolean branchFoundLocally = false;
    RevCommit stash = null;

    repoBuilder.setMustExist(true);
    repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git"));

    try {
        try {
            Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass());
            filamentsRepo = repoBuilder.build();
        } catch (RepositoryNotFoundException ex) {
            try {
                Base.writeLog("Repository wasn't initialized, initializing it to the given URL: "
                        + FILAMENTS_REPO_URL, this.getClass());
                repoBuilder.setMustExist(false);
                filamentsRepo = repoBuilder.build();
                filamentsRepo.create();
            } catch (IOException ex1) {
                Base.writeLog("IOException while attempting to initialize repository, not updating filaments",
                        this.getClass());
                return;
            }
        }

        currentBranch = filamentsRepo.getBranch();

    } catch (IOException ex) {
        Base.writeLog("IOException while attempting to open repository, not updating filaments",
                this.getClass());
        return;
    }

    git = new Git(filamentsRepo);

    try {
        // it should be only 1, but it shortens the code needed, as the call()
        // method returns an iterable
        for (RevCommit commit : git.log().setMaxCount(1).call()) {
            Base.writeLog("Current commit hash: " + commit, this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog(
                "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update",
                this.getClass());
    }

    try {
        remoteAddCmd = git.remoteAdd();
        remoteAddCmd.setName("origin");
        remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL));
        remoteAddCmd.call();
    } catch (URISyntaxException ex) {
        Base.writeLog("Invalid git filament repo remote URL!", this.getClass());
        return;
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass());
        return;
    }

    try {

        if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) {
            Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH
                    + ", searching for it", this.getClass());
            checkoutCmd = git.checkout();
            checkoutCmd.setName(FILAMENTS_REPO_BRANCH);

            branchList = git.branchList().call();

            for (Ref ref : branchList) {
                if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) {
                    Base.writeLog("Correct branch was found locally", this.getClass());
                    branchFoundLocally = true;
                    break;
                }
            }

            if (branchFoundLocally == false) {
                Base.writeLog(
                        "No correct branch was found locally, attempting to checkout a new branch tracking the remote",
                        this.getClass());
                checkoutCmd.setCreateBranch(true);
                checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
                checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH);
                git.fetch().call();
            }

            RevCommit backup = null;
            if (git.status().call().isClean() == false) {
                git.add().addFilepattern(".").call();
                backup = git.commit().setMessage("local backup of user modifications").call();
            }

            newBranch = checkoutCmd.call().getName();

            if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) {
                Base.writeLog("Unable to change to correct branch, aborting update", this.getClass());
                return;
            } else {
                Base.writeLog("Changed to correct branch, " + newBranch, this.getClass());
            }

            try {
                for (RevCommit commit : git.log().setMaxCount(1).call()) {
                    Base.writeLog("Commit hash after branch change: " + commit, this.getClass());

                }
            } catch (GitAPIException ex) {
                // we don't want all the process to stop just because we couldn't acquire the hash here,
                // hence this catch
                Base.writeLog(
                        "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update",
                        this.getClass());
            }

            if (backup != null) {
                // TODO: restore backup of user modifications
                //git.cherryPick().setNoCommit(true).include(backup).call();
            }
        }

        repoStatus = git.status().call();

        checkoutCmd = git.checkout();
        checkoutCmd.setName(FILAMENTS_REPO_BRANCH);
        checkoutCmd.call();

        git.fetch();
        resetCmd = git.reset();
        resetCmd.setMode(ResetType.HARD);
        resetCmd.call();

        git.pull().call();

        /*
        repoStatus = git.status().call();
        if (repoStatus.hasUncommittedChanges()) {
        Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass());
        stash = git.stashCreate().call();
        git.pull().call();
        git.stashApply().call();        // will apply the last stash made
        git.stashDrop().call();         // remove the last stash made
        } else {
        Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass());
        git.pull().call();
        }
        */

        Base.writeLog("Filament update concluded successfully!", this.getClass());

        try {
            for (RevCommit commit : git.log().setMaxCount(1).call()) {
                Base.writeLog("Commit hash after update process finished: " + commit, this.getClass());

            }
        } catch (GitAPIException ex) {
            // we don't want all the process to stop just because we couldn't acquire the hash here,
            // hence this catch
            Base.writeLog(
                    "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update",
                    this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass());
        try {
            resetCmd = git.reset();
            resetCmd.setMode(ResetType.HARD);
            resetCmd.call();

            if (stash != null) {
                git.stashApply().call();
                git.stashDrop().call();
            }

        } catch (GitAPIException ex1) {
            Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...",
                    this.getClass());
        }
    }

}

From source file:util.Util.java

public static Git buildGit(File repositorieFile) throws IOException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(repositorieFile.getAbsolutePath() + "/.git"))
            .setMustExist(true).build();

    return new Git(repository);
}