Java Code Examples for org.eclipse.jgit.storage.file.FileRepositoryBuilder

The following examples show how to use org.eclipse.jgit.storage.file.FileRepositoryBuilder. These examples are extracted from open source projects. 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 Project: youran   Source File: GitService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 打开仓库
 *
 * @param repoDir 仓库目录
 * @return
 */
private Repository openRepository(String repoDir) {
    File gitDir = new File(repoDir, ".git");
    // now open the resulting repository with a FileRepositoryBuilder
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository;
    try {
        repository = builder.setGitDir(gitDir)
            .readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();
    } catch (IOException e) {
        LOGGER.error("打开仓库异常", e);
        throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, "打开仓库异常");
    }
    return repository;
}
 
Example 2
Source Project: judgels   Source File: LocalGitProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean fetch(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).fetch().setCheckFetchedObjects(true).call();

        RevWalk walk = new RevWalk(repo);
        RevCommit commit = walk.parseCommit(repo.getRef("master").getObjectId());

        walk.reset();
        RevCommit originCommit = walk.parseCommit(repo.getRef("origin/master").getObjectId());

        repo.close();
        return !commit.getName().equals(originCommit.getName());
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source Project: judgels   Source File: LocalGitProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean rebase(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        RebaseResult result = new Git(repo).rebase().setUpstream("origin/master").call();

        if (result.getStatus() == RebaseResult.Status.STOPPED) {
            new Git(repo).rebase().setOperation(RebaseCommand.Operation.ABORT).call();
            repo.close();
            return false;
        }
        repo.close();
        return true;

    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source Project: judgels   Source File: LocalGitProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<GitCommit> getLog(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));

        Iterable<RevCommit> logs = new Git(repo).log().call();
        ImmutableList.Builder<GitCommit> versions = ImmutableList.builder();
        for (RevCommit rev : logs) {
            versions.add(new GitCommit(rev.getName(), rev.getAuthorIdent().getName(), new Date(rev.getCommitTime() * 1000L), rev.getShortMessage(), rev.getFullMessage()));
        }
        repo.close();
        return versions.build();

    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source Project: vertx-maven-plugin   Source File: GitUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the git {@link Repository} if the the project has one
 *
 * @param project - the {@link MavenProject} whose Git repo needs to be returned in {@link Repository}
 * @return Repository  - the Git Repository of the project
 * @throws IOException - any error that might occur finding the Git folder
 */
public static Repository getGitRepository(MavenProject project) throws IOException {

    MavenProject rootProject = getRootProject(project);

    File baseDir = rootProject.getBasedir();

    if (baseDir == null) {
        baseDir = project.getBasedir();
    }

    File gitFolder = findGitFolder(baseDir);
    if (gitFolder == null) {
        // No git repository found
        return null;
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder
        .readEnvironment()
        .setGitDir(gitFolder)
        .build();
    return repository;
}
 
Example 6
Source Project: centraldogma   Source File: GitMirrorTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void initGitRepo(TestInfo testInfo) throws Exception {
    final String repoName = TestUtil.normalizedDisplayName(testInfo);
    gitWorkTree = new File(gitRepoDir.getRoot().toFile(), repoName).getAbsoluteFile();
    final Repository gitRepo = new FileRepositoryBuilder().setWorkTree(gitWorkTree).build();
    createGitRepo(gitRepo);

    git = Git.wrap(gitRepo);
    gitUri = "git+file://" +
             (gitWorkTree.getPath().startsWith(File.separator) ? "" : "/") +
             gitWorkTree.getPath().replace(File.separatorChar, '/') +
             "/.git";

    // Start the master branch with an empty commit.
    git.commit().setMessage("Initial commit").call();
}
 
Example 7
Source Project: orion.server   Source File: GitRemoteHandlerV1.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String path) throws CoreException, IOException, URISyntaxException,
		JSONException, ServletException {
	Path p = new Path(path);
	if (p.segment(1).equals("file")) { //$NON-NLS-1$
		// expected path: /gitapi/remote/{remote}/file/{path}
		String remoteName = p.segment(0);

		File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
		Repository db = null;
		try {
			db = FileRepositoryBuilder.create(gitDir);
			StoredConfig config = db.getConfig();
			config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName);
			config.save();
			// TODO: handle result
			return true;
		} finally {
			if (db != null) {
				db.close();
			}
		}
	}
	return false;
}
 
Example 8
@Override
protected boolean handleDelete(RequestInfo requestInfo) throws ServletException {
	HttpServletRequest request = requestInfo.request;
	HttpServletResponse response = requestInfo.response;
	Repository db = requestInfo.db;
	Repository parentRepo = null;
	try {
		Map<IPath, File> parents = GitUtils.getGitDirs(requestInfo.filePath.removeLastSegments(1), Traverse.GO_UP);
		if (parents.size() < 1)
			return false;
		parentRepo = FileRepositoryBuilder.create(parents.entrySet().iterator().next().getValue());
		String pathToSubmodule = db.getWorkTree().toString().substring(parentRepo.getWorkTree().toString().length() + 1);
		removeSubmodule(db, parentRepo, pathToSubmodule);
		return true;
	} catch (Exception ex) {
		String msg = "An error occured for delete submodule command.";
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
	}finally{
		if (parentRepo != null) {
			parentRepo.close();
		}
	}
   
}
 
Example 9
Source Project: orion.server   Source File: GitFileDecorator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Repository repositoryForPath(HttpServletRequest request, IPath targetPath) throws CoreException, IOException {
	IPath requestPath = targetPath;

	if (request.getContextPath().length() != 0) {
		IPath contextPath = new Path(request.getContextPath());
		if (contextPath.isPrefixOf(targetPath)) {
			requestPath = targetPath.removeFirstSegments(contextPath.segmentCount());
		}
	}

	File gitDir = GitUtils.getGitDir(requestPath);
	if (gitDir == null)
		return null;

	Repository db = FileRepositoryBuilder.create(gitDir);
	return db;
}
 
Example 10
Source Project: orion.server   Source File: GitConfigTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testKeyToSegmentsMethod() throws Exception {
	Object configOption = ReflectionUtils.callConstructor(ConfigOption.class, new Object[] {new URI(""), FileRepositoryBuilder.create(new File(""))});

	String[] segments = (String[]) ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a.b.c"});
	assertArrayEquals(new String[] {"a", "b", "c"}, segments);

	segments = (String[]) ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a.c"});
	assertArrayEquals(new String[] {"a", null, "c"}, segments);

	segments = (String[]) ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a.b.c.d"});
	assertArrayEquals(new String[] {"a", "b.c", "d"}, segments);

	segments = (String[]) ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a"});
	assertArrayEquals(null, segments);
}
 
Example 11
Source Project: orion.server   Source File: GitConfigTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testSegmentsToKeyMethod() throws Exception {
	Object configOption = ReflectionUtils.callConstructor(ConfigOption.class, new Object[] {new URI(""), FileRepositoryBuilder.create(new File(""))});

	String key = (String) ReflectionUtils.callMethod(configOption, "segmentsToKey", new Object[] {new String[] {"a", "b", "c"}});
	assertEquals("a.b.c", key);

	key = (String) ReflectionUtils.callMethod(configOption, "segmentsToKey", new Object[] {new String[] {"a", null, "c"}});
	assertEquals("a.c", key);

	key = (String) ReflectionUtils.callMethod(configOption, "segmentsToKey", new Object[] {new String[] {"a", "b.c", "d"}});
	assertEquals("a.b.c.d", key);

	key = (String) ReflectionUtils.callMethod(configOption, "segmentsToKey", new Object[] {new String[] {"a", "b"}});
	assertEquals(null, key);

	key = (String) ReflectionUtils.callMethod(configOption, "segmentsToKey", new Object[] {new String[] {"a", "b", "c", "d"}});
	assertEquals(null, key);
}
 
Example 12
Source Project: repositoryminer   Source File: GitSCM.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void open(String path) {
	LOG.info("Repository being opened.");

	FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
	File repoFolder = new File(path, ".git");

	if (!repoFolder.exists()) {
		throw new RepositoryMinerException("Repository not found.");
	}

	try {
		Repository repository = repositoryBuilder.setGitDir(repoFolder).readEnvironment().findGitDir().build();
		git = new Git(repository);
	} catch (IOException e) {
		throw new RepositoryMinerException(e);
	}
}
 
Example 13
protected void commitAllChanges(String site) throws UpgradeException {
    try {
        Path repositoryPath = getRepositoryPath(site);
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repo = builder
            .setGitDir(repositoryPath.toFile())
            .readEnvironment()
            .findGitDir()
            .build();

        try (Git git = new Git(repo)) {
            git.add().addFilepattern(".").call();

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

            if (status.hasUncommittedChanges() || !status.isClean()) {
                git.commit()
                    .setAll(true)
                    .setMessage(getCommitMessage())
                    .call();
            }
        }
    } catch (IOException | GitAPIException e) {
        throw new UpgradeException("Error committing changes for site " + site, e);
    }
}
 
Example 14
Source Project: rug-cli   Source File: GitUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void commitFiles(ProjectOperation operation, ParameterValues arguments, File root,
        RugResolver resolver) {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try (Repository repository = builder.setGitDir(new File(root, ".git")).readEnvironment()
            .findGitDir().build()) {
        try (Git git = new Git(repository)) {
            log.info("Committing to git repository at " + git.getRepository().getDirectory());
            git.add().addFilepattern(".").call();
            RevCommit commit = git.commit().setAll(true)
                    .setMessage(String.format("%s\n\n```\n%s```",
                            StringUtils.capitalize(operation.description()),
                            new ProvenanceInfoWriter().write(operation, arguments,
                                    Constants.cliClient(), resolver)))
                    .setAuthor("Atomist", "cli[email protected]").call();
            log.info("Committed changes to git repository (%s)", commit.abbreviate(7).name());
        }
    }
    catch (IllegalStateException | IOException | GitAPIException e) {
        throw new RunnerException(e);
    }
}
 
Example 15
Source Project: gitflow-incremental-builder   Source File: DifferentFiles.java    License: MIT License 6 votes vote down vote up
private Git setupGit(Configuration configuration) throws IOException {
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File pomDir = mavenSession.getCurrentProject().getBasedir().toPath().toFile();
    builder.findGitDir(pomDir);
    if (builder.getGitDir() == null) {
        String gitDirNotFoundMessage = "Git repository root directory not found ascending from current working directory:'" + pomDir + "'.";
        logger.warn(gitDirNotFoundMessage + " Next step is determined by failOnMissingGitDir property.");
        if (configuration.failOnMissingGitDir) {
            throw new IllegalArgumentException(gitDirNotFoundMessage);
        } else {
            throw new SkipExecutionException(gitDirNotFoundMessage);
        }
    }
    if (isWorktree(builder)) {
        throw new SkipExecutionException(UNSUPPORTED_WORKTREE + builder.getGitDir());
    }
    return Git.wrap(builder.build());
}
 
Example 16
public GitRepository(File location) throws GitRepoException {

        this.location = Objects.requireNonNull(location);

        if ( !isGitRepo(location)) {
            throw new GitRepoException("Git repository not found at " + location);
        }


        File gitDir =
                GIT_FOLDER_NAME.equals(location.getName()) ? location : new File(location, GIT_FOLDER_NAME);

        try {
            repo = new FileRepositoryBuilder()
                    .setGitDir(gitDir)
                    .readEnvironment() // scan environment GIT_* variables
                    .findGitDir()      // scan up the file system tree
                    .build();

            git = new Git(repo);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 17
Source Project: GitFx   Source File: GitFXGsonUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static GitRepoMetaData getGitRepositoryMetaData(String repoPath) {
        try {
            if(!repoPath.endsWith(".git"))
                repoPath = repoPath+File.separator+".git";
            System.out.println("repopath:  "+repoPath);
            GitRepoMetaData gitMetaData = new GitRepoMetaData();
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repository = builder.setGitDir(new File(repoPath))
                    .readEnvironment()
                    .setMustExist(true)
                    .findGitDir()
                    .build();
            RevWalk walk = new RevWalk(repository);
            AnyObjectId id = repository.resolve("HEAD");
            if(id == null)
                return null;//Empty repository
            RevCommit rCommit =walk.parseCommit(id);
            walk.markStart(rCommit);
            gitMetaData.setRepository(repository);
            gitMetaData.setRevWalk(walk);
            return gitMetaData;
        } catch (IOException exception) {
//[LOG]            logger.debug("IOException getGitRepositoryMetaData", exception);
        };
        return null;
    }
 
Example 18
Source Project: celerio   Source File: GITStatusCrawler.java    License: Apache License 2.0 6 votes vote down vote up
public static SCMStatus doStatus(File baseDir) throws RuntimeException {
    try {
        Map<String, Boolean> map = new HashMap<String, Boolean>();

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(new File(baseDir, ".git")).build();
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(getTree(repository));
        treeWalk.setRecursive(true);
        while (treeWalk.next()) {
            map.put(treeWalk.getPathString(), Boolean.TRUE);
        }

        log.info("-----------------------------------------------------------------------------------------------");
        log.info("PROJECT IS UNDER GIT: Files tracked by git ({}) won't be overwritten/deleted by Celerio", map.size());
        log.info("-----------------------------------------------------------------------------------------------");

        return new SCMStatus(map);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example 19
/**
 * Publish release notes.
 *
 * @throws IOException if problem with access to files appears.
 * @throws GitAPIException for problems with jgit.
 */
public void publish() throws IOException, GitAPIException {
    changeLocalRepoXdoc();
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File localRepo = new File(localRepoPath);
    final Repository repo = builder.findGitDir(localRepo).readEnvironment().build();
    final Git git = new Git(repo);
    git.add()
        .addFilepattern(PATH_TO_XDOC_IN_REPO)
        .call();
    git.commit()
        .setMessage(String.format(Locale.ENGLISH, COMMIT_MESSAGE_TEMPLATE, releaseNumber))
        .call();
    if (doPush) {
        final CredentialsProvider credentialsProvider =
            new UsernamePasswordCredentialsProvider(authToken, "");
        git.push()
            .setCredentialsProvider(credentialsProvider)
            .call();
    }
}
 
Example 20
/**
 * Returns a list of commits between two references.
 *
 * @param repoPath path to local git repository.
 * @param startRef start reference.
 * @param endRef end reference.
 * @return a list of commits.
 * @throws IOException if I/O error occurs.
 * @throws GitAPIException if an error occurs when accessing Git API.
 */
private static Set<RevCommit> getCommitsBetweenReferences(String repoPath, String startRef,
        String endRef) throws IOException, GitAPIException {

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final Path path = Paths.get(repoPath);
    final Repository repo = builder.findGitDir(path.toFile()).readEnvironment().build();

    final ObjectId startCommit = getActualRefObjectId(repo, startRef);
    Verify.verifyNotNull(startCommit, "Start reference \"" + startRef + "\" is invalid!");

    final ObjectId endCommit = getActualRefObjectId(repo, endRef);
    final Iterable<RevCommit> commits =
        new Git(repo).log().addRange(startCommit, endCommit).call();

    return Sets.newLinkedHashSet(commits);
}
 
Example 21
Source Project: verigreen   Source File: CommitMessage.java    License: Apache License 2.0 6 votes vote down vote up
@GET
   @Produces(MediaType.APPLICATION_JSON)
public static Response get() {
	Map<String,String> logMessages = new HashMap<>();
	try {
	FileRepositoryBuilder builder = new FileRepositoryBuilder();
     Repository repo = builder.setGitDir(new File(VerigreenNeededLogic.properties.getProperty("git.repositoryLocation"))).setMustExist(true).build();
    Git git = new Git(repo);
    Iterable<RevCommit> log = git.log().call();
    for (Iterator<RevCommit> iterator = log.iterator(); iterator.hasNext();) {
      RevCommit rev = iterator.next();
      logMessages.put(rev.getName(),rev.getFullMessage());
    }
	} catch(Exception e){
		e.printStackTrace();
	}
	return Response.status(Status.OK).entity(logMessages).build();		
}
 
Example 22
Source Project: verigreen   Source File: EmailSender.java    License: Apache License 2.0 6 votes vote down vote up
public String getCommitMessage(String commitId){
  	String commitMessage = null;
try {
	FileRepositoryBuilder builder = new FileRepositoryBuilder();
	String repoPath = VerigreenNeededLogic.properties.getProperty("git.repositoryLocation");
	Repository repo = builder.setGitDir(new File(repoPath)).setMustExist(true).build();
	Git git = new Git(repo);
	Iterable<RevCommit> log = git.log().call();
	Iterator<RevCommit> iterator = log.iterator();
	while(commitMessage == null && iterator.hasNext()){
		RevCommit rev = iterator.next();
		String commit = rev.getName().substring(0,7);
		if(commit.equals(commitId)){
    	  commitMessage = rev.getFullMessage();
		}
	}
} catch(Exception e){
	e.printStackTrace();
}
return commitMessage;
  }
 
Example 23
Source Project: git-changelog-lib   Source File: GitRepo.java    License: Apache License 2.0 6 votes vote down vote up
public GitRepo(final File repo) throws GitChangelogRepositoryException {
  try {
    File repoFile = new File(repo.getAbsolutePath());
    final File gitRepoFile = new File(repo.getAbsolutePath() + "/.git");
    if (gitRepoFile.exists()) {
      repoFile = gitRepoFile;
    }
    final FileRepositoryBuilder builder =
        new FileRepositoryBuilder() //
            .findGitDir(repoFile) //
            .readEnvironment();
    if (builder.getGitDir() == null) {
      throw new GitChangelogRepositoryException(
          "Did not find a GIT repo in " + repo.getAbsolutePath());
    }
    this.repository = builder.build();
    this.revWalk = new RevWalk(this.repository);
    this.git = new Git(this.repository);
  } catch (final IOException e) {
    throw new GitChangelogRepositoryException(
        "Could not use GIT repo in " + repo.getAbsolutePath(), e);
  }
}
 
Example 24
Source Project: aeron   Source File: TutorialPublishTask.java    License: Apache License 2.0 6 votes vote down vote up
public String getWikiUri() throws IOException, URISyntaxException
{
    final File baseGitDir = new File(getProject().getRootDir(), ".git");
    if (!baseGitDir.exists() || !baseGitDir.isDirectory())
    {
        throw new IllegalStateException("unable to find valid git repository at: " + baseGitDir);
    }

    final Repository baseGitRepo = new FileRepositoryBuilder()
        .setGitDir(new File(getProject().getRootDir(), ".git"))
        .build();

    final String origin = baseGitRepo.getConfig().getString(CONFIG_REMOTE_SECTION, "origin", CONFIG_KEY_URL);

    if (null == origin)
    {
        throw new IllegalStateException("unable to find origin URI");
    }

    return GithubUtil.getWikiUriFromOriginUri(origin);
}
 
Example 25
@Before
public void prepareTest() throws Exception {
    remoteRoot = new File("target", "remote").toPath();
    Path repoConfigDir = remoteRoot.resolve("configuration");
    Files.createDirectories(repoConfigDir);
    File baseDir = remoteRoot.toAbsolutePath().toFile();
    PathUtil.copyRecursively(getJbossServerBaseDir().resolve("configuration"), repoConfigDir, true);
    Path properties = repoConfigDir.resolve("logging.properties");
    if(Files.exists(properties)) {
        Files.delete(properties);
    }
    File gitDir = new File(baseDir, Constants.DOT_GIT);
    if (!gitDir.exists()) {
        try (Git git = Git.init().setDirectory(baseDir).call()) {
            git.add().addFilepattern("configuration").call();
            git.commit().setMessage("Repository initialized").call();
        }
    }
    remoteRepository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
}
 
Example 26
Source Project: Flashtool   Source File: DevicesGit.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static boolean openRepository() {
	try {
		logger.info("Opening devices repository.");
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        logger.debug("Local path : "+localPath);
        localRepo = builder.setGitDir(new File(localPath))
                .readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();
        logger.debug("Getting new git object");
        git = new Git(localRepo);
        return true;
	} catch (Exception e) {
		logger.info("Error opening devices repository.");
		closeRepository();
		return false;
	}
}
 
Example 27
protected void updateContent() throws IOException, CryptoException, ServiceLayerException {
    logger.debug("Update global repo");

    Path siteSandboxPath = Paths.get(studioConfiguration.getProperty(StudioConfiguration.REPO_BASE_PATH),
            studioConfiguration.getProperty(StudioConfiguration.GLOBAL_REPO_PATH)).resolve(GIT_ROOT);
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repo = builder
            .setGitDir(siteSandboxPath.toFile())
            .readEnvironment()
            .findGitDir()
            .build();

    try (Git git = new Git(repo)) {
        logger.debug("Update content from each active cluster memeber");
        for (ClusterMember remoteNode : clusterNodes) {
            updateBranch(git, remoteNode);
        }
    } catch (GitAPIException e) {
        logger.error("Error while syncing cluster node global repo content", e);
    }
}
 
Example 28
Source Project: SZZUnleashed   Source File: SimpleCommitSearcher.java    License: MIT License 5 votes vote down vote up
/**
 * Constructor using a path to a local repository.
 */
public SimpleCommitSearcher(String repoPath) throws IOException, GitAPIException {
  Configuration conf = Configuration.getInstance();
  FileRepositoryBuilder builder = new FileRepositoryBuilder();
  builder.setMustExist(true);

  builder.addCeilingDirectory(new File(repoPath));
  builder.findGitDir(new File(repoPath));
  this.repo = builder.build();
  this.git = new Git(repo);

  bugpatterns = Arrays.asList(compile("JENKINS\\-[0-9]"));
}
 
Example 29
Source Project: SZZUnleashed   Source File: GitParser.java    License: MIT License 5 votes vote down vote up
/**
 * The constructor for the GitParser class. It requires the repository to exist and will fail if
 * its not. The resultPath is also created if it's not existing.
 *
 * @param path the path to where the local repository can be found.
 * @param resultPath the path to where the JSON files will be written.
 */
public GitParser(String path, String resultPath, int depth, int customContext)
    throws IOException, GitAPIException {
  FileRepositoryBuilder builder = new FileRepositoryBuilder();
  builder.setMustExist(true);

  builder.addCeilingDirectory(new File(path));
  builder.findGitDir(new File(path));
  this.repo = builder.build();

  this.resultPath = resultPath;

  /*
   * Check if the resultpath exists otherwise create it.
   */

  if (this.resultPath != null) {
    File resDirectory = new File(resultPath);
    if (!resDirectory.exists()) resDirectory.mkdirs();
  } else {
    System.err.println("Resultpath not set! Using deafult directory instead.");
    this.resultPath = this.DEFAULT_RES_PATH;
  }

  this.util = new CommitUtil(this.repo, customContext);

  this.depth = depth;
}
 
Example 30
Source Project: judgels   Source File: LocalGitProvider.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addAll(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));
    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).add().addFilepattern(".").call();
        repo.close();
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}