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

The following examples show how to use org.eclipse.jgit.storage.file.FileRepositoryBuilder. 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: GitRepository.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #2
Source File: RemoteGitRepositoryTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #3
Source File: TutorialPublishTask.java    From aeron with 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 #4
Source File: AbstractUpgradeOperation.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
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 #5
Source File: GitRepo.java    From git-changelog-lib with 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 #6
Source File: GitUtil.java    From vertx-maven-plugin with 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 #7
Source File: GitService.java    From youran with 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 #8
Source File: LocalGitProvider.java    From judgels with 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 #9
Source File: LocalGitProvider.java    From judgels with 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 #10
Source File: DevicesGit.java    From Flashtool with 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 #11
Source File: StudioNodeSyncGlobalRepoTask.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
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 #12
Source File: LocalGitProvider.java    From judgels with 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 #13
Source File: GitSCM.java    From repositoryminer with 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 #14
Source File: EmailSender.java    From verigreen with 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 #15
Source File: CommitMessage.java    From verigreen with 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 #16
Source File: GitRemoteHandlerV1.java    From orion.server with 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 #17
Source File: GitUtils.java    From rug-cli with 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", "[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 #18
Source File: NotesBuilder.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #19
Source File: GitSubmoduleHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@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 #20
Source File: GitFileDecorator.java    From orion.server with 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 #21
Source File: XdocPublisher.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #22
Source File: GITStatusCrawler.java    From celerio with 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 #23
Source File: GitFXGsonUtil.java    From GitFx with 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 #24
Source File: DifferentFiles.java    From gitflow-incremental-builder with 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 #25
Source File: GitConfigTest.java    From orion.server with 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 #26
Source File: GitConfigTest.java    From orion.server with 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 #27
Source File: GitMirrorTest.java    From centraldogma with 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 #28
Source File: LocalFacadeBuilder.java    From sputnik with Apache License 2.0 5 votes vote down vote up
public LocalFacade build() {
    try (Repository repository = new FileRepositoryBuilder().readEnvironment().findGitDir().build()) {
        try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE)) {
            diffFormatter.setRepository(repository);
            return new LocalFacade(repository, diffFormatter, new LocalFacadeOutput());
        }
    } catch (IOException e) {
        throw new RuntimeException("Error getting git repository", e);
    }
}
 
Example #29
Source File: RepositoryHelper.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Repository createRepository(File repo) throws IOException, GitAPIException {
    if (!repo.exists()) {
        Files.createDirectory(repo.toPath());
    }

    Repository repository = FileRepositoryBuilder.create(new File(repo, ".git"));
    repository.create();

    return repository;
}
 
Example #30
Source File: GitManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Repository load(String spaceKey) throws Exception {
    Workspace ws = wsMgr.getWorkspace(spaceKey);
    return new FileRepositoryBuilder()
            .setGitDir(new File(ws.getWorkingDir(), ".git"))
            .setWorkTree(ws.getWorkingDir())
            .setIndexFile(new File(ws.getWorkingDir(), ".git/index"))
            .build();
}