org.eclipse.jgit.lib.RepositoryBuilder Java Examples

The following examples show how to use org.eclipse.jgit.lib.RepositoryBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitServiceImpl.java    From apidiff with MIT License 6 votes vote down vote up
@Override
public Repository openRepositoryAndCloneIfNotExists(String path, String projectName, String cloneUrl) throws Exception {
	File folder = new File(UtilTools.getPathProject(path , projectName));
	Repository repository = null;
	
	if (folder.exists()) {
		this.logger.info(projectName + " exists. Reading properties ... (wait)");
		RepositoryBuilder builder = new RepositoryBuilder();
		repository = builder
				.setGitDir(new File(folder, ".git"))
				.readEnvironment()
				.findGitDir()
				.build();
		
	} else {
		this.logger.info("Cloning " + cloneUrl  + " in " + cloneUrl + " ... (wait)");
		Git git = Git.cloneRepository()
				.setDirectory(folder)
				.setURI(cloneUrl)
				.setCloneAllBranches(true)
				.call();
		repository = git.getRepository();
	}
	this.logger.info("Process " + projectName  + " finish.");
	return repository;
}
 
Example #2
Source File: GitClient.java    From steady with Apache License 2.0 6 votes vote down vote up
private Repository getRepositoryFromPath( String _path ) {

		Repository repository = null;

		try {
			if ( _path == null ) {
				_path = this.workDir.toString() + "/.git";
			}
			else {
				_path += "/.git";
			}

			RepositoryBuilder builder = new RepositoryBuilder();
			repository = builder.setGitDir( new File( _path ) )
					.readEnvironment()
					.findGitDir()
					.build();
		}
		catch ( Exception e ) {
			e.printStackTrace();
		}

		return repository;
	}
 
Example #3
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 6 votes vote down vote up
@Override
public Repository openRepository(String repositoryPath) throws Exception {
    File folder = new File(repositoryPath);
    Repository repository;
    if (folder.exists()) {
        RepositoryBuilder builder = new RepositoryBuilder();
        repository = builder
            .setGitDir(new File(folder, ".git"))
            .readEnvironment()
            .findGitDir()
            .build();
    } else {
        throw new FileNotFoundException(repositoryPath);
    }
    return repository;
}
 
Example #4
Source File: Utils.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * @param gitConfigFolder e.g. /your/project/root/.git
 *
 * @return Returns last commit's UUID, "nocommit" if there are no commits and returns null if an exception occured
 */
public static String getLastCommitUuid( String gitConfigFolder ) throws MojoExecutionException {
    try {
        Repository repo =
                new RepositoryBuilder().setGitDir( new File( gitConfigFolder ) ).readEnvironment().findGitDir()
                                       .build();
        RevWalk walk = new RevWalk( repo );
        ObjectId head = repo.resolve( "HEAD" );
        if ( head != null ) {
            RevCommit lastCommit = walk.parseCommit( head );
            return lastCommit.getId().getName();
        }
        else {
            return "nocommit";
        }
    }
    catch ( Exception e ) {
        throw new MojoExecutionException( "Error trying to get the last git commit uuid", e );
    }
}
 
Example #5
Source File: RepoMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
public RepoMerger(String outputRepositoryPath,
		List<SubtreeConfig> subtreeConfigs) throws IOException {
	this.subtreeConfigs = subtreeConfigs;
	File file = new File(outputRepositoryPath);
	repository = new RepositoryBuilder().setWorkTree(file).build();
	if (!repository.getDirectory().exists()) {
		repository.create();
	}
}
 
Example #6
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * Returns the {@link org.eclipse.jgit.lib.Repository} used by this git instance.
 *
 * @return a {@link org.eclipse.jgit.lib.Repository} object.
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 */
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE",
                    justification = "JGit interaction with spotbugs")
@NonNull
@Override
public Repository getRepository() throws GitException {
    try {
        return new RepositoryBuilder().setWorkTree(workspace).build();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #7
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
@SuppressFBWarnings(value = {"RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
                             "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE"},
                    justification = "Java 11 spotbugs error and JGit interaction with spotbugs")
private StoredConfig getConfig(String GIT_DIR) throws GitException {
    try (Repository repo = isBlank(GIT_DIR) ? getRepository() : new RepositoryBuilder().setWorkTree(new File(GIT_DIR)).build()) {
        return repo.getConfig();
    } catch (IOException ioe) {
        throw new GitException(ioe);
    }
}
 
Example #8
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
@SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
                              "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE" },
                    justification = "Java 11 spotbugs error and JGit interaction with spotbugs")
public void setRemoteUrl(String name, String url, String GIT_DIR) throws GitException, InterruptedException {
    try (Repository repo = new RepositoryBuilder().setGitDir(new File(GIT_DIR)).build()) {
        StoredConfig config = repo.getConfig();
        config.setString("remote", name, "url", url);
        config.save();
    } catch (IOException ioe) {
        throw new GitException(ioe);
    }
}
 
Example #9
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE",
                    justification = "JGit interaction with spotbugs")
@Deprecated
@Override
public boolean isBareRepository(String GIT_DIR) throws GitException, InterruptedException {
    Repository repo = null;
    boolean isBare = false;
    if (GIT_DIR == null) {
        throw new GitException("Not a git repository"); // Compatible with CliGitAPIImpl
    }
    try {
        if (isBlank(GIT_DIR) || !(new File(GIT_DIR)).isAbsolute()) {
            if ((new File(workspace, ".git")).exists()) {
                repo = getRepository();
            } else {
                repo = new RepositoryBuilder().setGitDir(workspace).build();
            }
        } else {
            repo = new RepositoryBuilder().setGitDir(new File(GIT_DIR)).build();
        }
        isBare = repo.isBare();
    } catch (IOException ioe) {
        throw new GitException(ioe);
    } finally {
        if (repo != null) repo.close();
    }
    return isBare;
}
 
Example #10
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * getRepository.
 *
 * @return a {@link org.eclipse.jgit.lib.Repository} object.
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 */
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE",
                    justification = "JGit interaction with spotbugs")
@NonNull
@Override
public Repository getRepository() throws GitException {
    try {
        return new RepositoryBuilder().setWorkTree(workspace).build();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #11
Source File: AbstractGitRepoAwareTask.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
@Override
public final void execute() {
        try {
                try {
                        Repository repository = new RepositoryBuilder().
                                readEnvironment().
                                findGitDir(getDirectory()).
                                build();
                        git = new Git(repository);
                }
                catch (IOException ioe) {
                        String errorMsg = "Specified path (%s) doesn't seem to be a git repository.";

                        throw new BuildException(String.format(errorMsg, getDirectory().getAbsolutePath()), ioe);
                }

                doExecute();

        }
        catch (GitBuildException e) {
                log(e, Project.MSG_ERR);

                if (failOnError) {
                        throw new BuildException(e);
                }
        }
        finally {
                if (git != null) {
                        git.getRepository().close();
                }
        }
}
 
Example #12
Source File: Utils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * @param gitConfigFolder e.g. /your/project/root/.git
 *
 * @return Returns git config remote.origin.url field of the repository located at gitConfigFolder
 */
public static String getGitRemoteUrl( String gitConfigFolder ) throws MojoExecutionException {
    try {
        Repository repo =
                new RepositoryBuilder().setGitDir( new File( gitConfigFolder ) ).readEnvironment().findGitDir()
                                       .build();
        Config config = repo.getConfig();
        return config.getString( "remote", "origin", "url" );
    }
    catch ( Exception e ) {
        throw new MojoExecutionException( "Error trying to get remote origin url of git repository", e );
    }
}
 
Example #13
Source File: GitUtil.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
public GitUtil(File f) {
	try {
		File workspace = findWorkspaceRoot(f);
		if (workspace==null) {
			throw new IllegalStateException("Does not appear to be a Git workspace: "+f.getCanonicalPath());
		}
		Repository r = new RepositoryBuilder().setWorkTree(findWorkspaceRoot(f)).build();
		git = new Git(r);
	}
	catch (IOException e) {
	    throw new AstException(e);
	}
}
 
Example #14
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static boolean exist(File repoDir) {
    try {
        final RepositoryBuilder repositoryBuilder = new RepositoryBuilder().setGitDir(repoDir);
        final org.eclipse.jgit.lib.Repository repository = repositoryBuilder.build();
        if (repository.getConfig() instanceof FileBasedConfig) {
            return ((FileBasedConfig) repository.getConfig()).getFile().exists();
        }
        return repository.getDirectory().exists();
    } catch (IOException e) {
        throw new StorageException("failed to check if repository exists at " + repoDir, e);
    }
}
 
Example #15
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 4 votes vote down vote up
@Override
	public Repository cloneIfNotExists(String projectPath, String cloneUrl/*, String branch*/) throws Exception {
		File folder = new File(projectPath);
		Repository repository;
		if (folder.exists()) {
			RepositoryBuilder builder = new RepositoryBuilder();
			repository = builder
					.setGitDir(new File(folder, ".git"))
					.readEnvironment()
					.findGitDir()
					.build();
			
			//logger.info("Project {} is already cloned, current branch is {}", cloneUrl, repository.getBranch());
			
		} else {
			logger.info("Cloning {} ...", cloneUrl);
			Git git = Git.cloneRepository()
					.setDirectory(folder)
					.setURI(cloneUrl)
					.setCloneAllBranches(true)
					.call();
			repository = git.getRepository();
			//logger.info("Done cloning {}, current branch is {}", cloneUrl, repository.getBranch());
		}

//		if (branch != null && !repository.getBranch().equals(branch)) {
//			Git git = new Git(repository);
//			
//			String localBranch = "refs/heads/" + branch;
//			List<Ref> refs = git.branchList().call();
//			boolean branchExists = false;
//			for (Ref ref : refs) {
//				if (ref.getName().equals(localBranch)) {
//					branchExists = true;
//				}
//			}
//			
//			if (branchExists) {
//				git.checkout()
//					.setName(branch)
//					.call();
//			} else {
//				git.checkout()
//					.setCreateBranch(true)
//					.setName(branch)
//					.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
//					.setStartPoint("origin/" + branch)
//					.call();
//			}
//			
//			logger.info("Project {} switched to {}", cloneUrl, repository.getBranch());
//		}
		return repository;
	}
 
Example #16
Source File: GitClientSampleRepoRule.java    From git-client-plugin with MIT License 4 votes vote down vote up
public String head() throws Exception {
    return new RepositoryBuilder().setWorkTree(sampleRepo).build().resolve(Constants.HEAD).name();
}
 
Example #17
Source File: GitRepository.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new Git-backed repository.
 *
 * @param repoDir the location of this repository
 * @param format the repository format
 * @param repositoryWorker the {@link Executor} which will perform the blocking repository operations
 * @param creationTimeMillis the creation time
 * @param author the user who initiated the creation of this repository
 *
 * @throws StorageException if failed to create a new repository
 */
GitRepository(Project parent, File repoDir, GitRepositoryFormat format, Executor repositoryWorker,
              long creationTimeMillis, Author author, @Nullable RepositoryCache cache) {

    this.parent = requireNonNull(parent, "parent");
    name = requireNonNull(repoDir, "repoDir").getName();
    this.repositoryWorker = requireNonNull(repositoryWorker, "repositoryWorker");
    this.format = requireNonNull(format, "format");
    this.cache = cache;

    requireNonNull(author, "author");

    final RepositoryBuilder repositoryBuilder = new RepositoryBuilder().setGitDir(repoDir).setBare();
    boolean success = false;
    try {
        // Create an empty repository with format version 0 first.
        try (org.eclipse.jgit.lib.Repository initRepo = repositoryBuilder.build()) {
            if (exist(repoDir)) {
                throw new StorageException(
                        "failed to create a repository at: " + repoDir + " (exists already)");
            }

            initRepo.create(true);

            final StoredConfig config = initRepo.getConfig();
            if (format == GitRepositoryFormat.V1) {
                // Update the repository settings to upgrade to format version 1 and reftree.
                config.setInt(CONFIG_CORE_SECTION, null, CONFIG_KEY_REPO_FORMAT_VERSION, 1);
            }

            // Disable hidden files, symlinks and file modes we do not use.
            config.setEnum(CONFIG_CORE_SECTION, null, CONFIG_KEY_HIDEDOTFILES, HideDotFiles.FALSE);
            config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_SYMLINKS, false);
            config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_FILEMODE, false);

            // Disable GPG signing.
            config.setBoolean(CONFIG_COMMIT_SECTION, null, CONFIG_KEY_GPGSIGN, false);

            // Set the diff algorithm.
            config.setString(CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM, "histogram");

            // Disable rename detection which we do not use.
            config.setBoolean(CONFIG_DIFF_SECTION, null, CONFIG_KEY_RENAMES, false);

            config.save();
        }

        // Re-open the repository with the updated settings and format version.
        jGitRepository = new RepositoryBuilder().setGitDir(repoDir).build();

        // Initialize the master branch.
        final RefUpdate head = jGitRepository.updateRef(Constants.HEAD);
        head.disableRefLog();
        head.link(Constants.R_HEADS + Constants.MASTER);

        // Initialize the commit ID database.
        commitIdDatabase = new CommitIdDatabase(jGitRepository);

        // Insert the initial commit into the master branch.
        commit0(null, Revision.INIT, creationTimeMillis, author,
                "Create a new repository", "", Markup.PLAINTEXT,
                Collections.emptyList(), true);

        headRevision = Revision.INIT;
        success = true;
    } catch (IOException e) {
        throw new StorageException("failed to create a repository at: " + repoDir, e);
    } finally {
        if (!success) {
            internalClose();
            // Failed to create a repository. Remove any cruft so that it is not loaded on the next run.
            deleteCruft(repoDir);
        }
    }
}