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

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

Introduction

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

Prototype

@Override
public Repository build() throws IOException 

Source Link

Document

Create a repository matching the configuration in this builder.

Usage

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

License:Open Source License

/**
 * Run task//from w  ww.ja v  a 2  s.  c  om
 *
 * @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:net.polydawn.mdm.Mdm.java

License:Open Source License

/**
 * Like the main method (does full args parsing, takes your cwd as serious
 * business, etc) except passes out exceptions instead of logging or halting the
 * jvm, so it can be used in tests./*from w  w  w  .j a  v a 2 s  .c  o  m*/
 * @throws Exception
 */
public static MdmExitMessage run(String... args) throws Exception {
    // find the repo to operate on
    Repository repo = null;
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        builder.findGitDir();
        if (builder.getGitDir() != null)
            repo = builder.build();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // parse args
    ArgumentParser parser = new MdmArgumentParser().parser;
    Namespace parsedArgs = null;
    try {
        parsedArgs = parser.parseArgs(args);
    } catch (HelpScreenException e) {
        if (real)
            System.exit(0);
        return null;
    } catch (MdmArgumentParser.VersionExit e) {
        if (real)
            System.exit(0);
        return null;
    } catch (ArgumentParserException e) {
        parser.handleError(e);
        if (real)
            System.exit(1);
        return null;
    }

    // fire command
    MdmCommand cmd = getCommand(parsedArgs.getString("subcommand"), repo, parsedArgs);
    cmd.parse(parsedArgs);
    cmd.validate();
    return cmd.call();
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

/**
 * Open a Git repository using the specified directory.
 * @param gitProjectRootDir a root directory of a Git project
 * @return created Repository/*  w  w  w.  ja v a 2 s. co m*/
 * @throws IOException thrown when the specified directory does not exist,
 * does not have read/write privilege or not containing .git directory
 */
private Repository openRepository(final File gitProjectRootDir) throws IOException {

    // Instead of using FileUtils.ensureDirectoryExistAndCanReadAndWrite, check availability manually here.
    // Because the util will try to create a dir if not exist.
    // The git dir should be initialized and configured by users.
    if (!gitProjectRootDir.isDirectory()) {
        throw new IOException(format("'%s' is not a directory or does not exist.", gitProjectRootDir));
    }

    if (!(gitProjectRootDir.canRead() && gitProjectRootDir.canWrite())) {
        throw new IOException(format("Directory '%s' does not have read/write privilege.", gitProjectRootDir));
    }

    // Search .git dir but avoid searching parent directories.
    final FileRepositoryBuilder builder = new FileRepositoryBuilder().readEnvironment().setMustExist(true)
            .addCeilingDirectory(gitProjectRootDir).findGitDir(gitProjectRootDir);

    if (builder.getGitDir() == null) {
        throw new IOException(format("Directory '%s' does not contain a .git directory."
                + " Please init and configure the directory with 'git init' command before using it from NiFi Registry.",
                gitProjectRootDir));
    }

    return builder.build();
}

From source file:org.eclipse.tycho.extras.buildtimestamp.jgit.JGitBuildTimestampProvider.java

License:Open Source License

public Date getTimestamp(MavenSession session, MavenProject project, MojoExecution execution)
        throws MojoExecutionException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder() //
            .readEnvironment() //
            .findGitDir(project.getBasedir()) //
            .setMustExist(true);//from  ww  w  .java 2  s  .  c  o m
    try {
        Repository repository = builder.build();
        try {
            RevWalk walk = new RevWalk(repository);
            try {
                String relPath = getRelPath(repository, project);
                if (relPath != null && relPath.length() > 0) {
                    walk.setTreeFilter(AndTreeFilter.create(new PathFilter(relPath, getIgnoreFilter(execution)),
                            TreeFilter.ANY_DIFF));
                }

                // TODO make sure working tree is clean

                ObjectId headId = repository.resolve(Constants.HEAD);
                walk.markStart(walk.parseCommit(headId));
                RevCommit commit = walk.next();
                return new Date(commit.getCommitTime() * 1000L);
            } finally {
                walk.release();
            }
        } finally {
            repository.close();
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Could not determine git commit timestamp", e);
    }
}

From source file:org.eclipse.tycho.extras.sourceref.jgit.JGitSourceReferencesProvider.java

License:Open Source License

public String getSourceReferencesHeader(MavenProject project, ScmUrl scmUrl) throws MojoExecutionException {
    File basedir = project.getBasedir().getAbsoluteFile();
    FileRepositoryBuilder builder = new FileRepositoryBuilder().readEnvironment().findGitDir(basedir)
            .setMustExist(true);/*  w  w w .  j  av  a  2  s .  c o  m*/
    Repository repo;
    Git git;
    try {
        repo = builder.build();
        git = Git.wrap(repo);
    } catch (IOException e) {
        throw new MojoExecutionException("IO exception trying to create git repo ", e);
    }
    ObjectId head = resolveHead(repo);

    StringBuilder result = new StringBuilder(scmUrl.getUrl());
    result.append(";path=\"");
    result.append(getRelativePath(basedir, repo.getWorkTree()));
    result.append("\"");

    String tag = findTagForHead(git, head);
    if (tag != null) {
        // may contain e.g. spaces, so we quote it
        result.append(";tag=\"");
        result.append(tag);
        result.append("\"");
    }
    result.append(";commitId=");
    result.append(head.getName());
    return result.toString();
}

From source file:org.jenkinsci.git.FileRepositoryOperation.java

License:Open Source License

public Repository invoke(File file, VirtualChannel channel) throws IOException {
    String directory = repo.getDirectory();
    File gitDir;/* w w w  .java2 s  .c  o m*/
    if (directory == null || directory.length() == 0 || ".".equals(directory))
        gitDir = file;
    else
        gitDir = new File(file, directory);
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.setFS(FS.DETECTED);
    if (Constants.DOT_GIT.equals(gitDir.getName()))
        builder.setGitDir(gitDir);
    else
        builder.setWorkTree(gitDir);
    builder.setMustExist(true);
    try {
        return builder.build();
    } catch (RepositoryNotFoundException rnfe) {
        return null;
    }
}

From source file:org.kuali.student.git.model.GitRepositoryUtils.java

License:Educational Community License

public static Repository buildFileRepository(File repositoryPath, boolean create, boolean bare)
        throws IOException {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();

    if (bare) {/*  w  w w . j  av a  2s.  c  o  m*/
        builder = builder.setGitDir(repositoryPath);
    } else {
        builder.setWorkTree(repositoryPath);
    }

    builder = builder.readEnvironment();

    Repository repo = builder.build();

    if (create)
        repo.create(bare);

    return repo;
}

From source file:org.kuali.student.git.tools.GitExtractor.java

License:Educational Community License

public void buildRepository(File repositoryPath) throws IOException {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();

    builder = builder.setGitDir(repositoryPath);

    builder = builder.readEnvironment();

    builder = builder.findGitDir();/*from   w  w w  .  j a  v  a  2 s.co m*/

    repository = builder.build();

}

From source file:org.mule.module.git.GitConnector.java

License:Open Source License

private Repository getGitRepo(String overrideDirectory) throws IOException {
    File dir = resolveDirectory(overrideDirectory);
    if (!dir.exists()) {
        throw new RuntimeException("Directory " + dir.getAbsolutePath() + " does not exists");
    }//from   w ww  .  j  a  va 2 s .  c  o m

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.setWorkTree(dir);
    //        builder.setGitDir(dir);
    //        builder.readEnvironment();
    //        builder.findGitDir();
    return builder.build();
}

From source file:org.openengsb.connector.git.internal.GitServiceImpl.java

License:Apache License

/**
 * Initializes the {@link FileRepository} or creates a new own if it does
 * not exist.// w  w w  .  j  av a  2  s  .  c  o m
 */
private void initRepository() throws IOException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.setWorkTree(localWorkspace);
    repository = builder.build();
    if (!new File(localWorkspace, ".git").isDirectory()) {
        repository.create();
        repository.getConfig().setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
        repository.getConfig().setString("remote", "origin", "url", remoteLocation);
        repository.getConfig().setString("branch", watchBranch, "remote", "origin");
        repository.getConfig().setString("branch", watchBranch, "merge", "refs/heads/" + watchBranch);
        repository.getConfig().save();
    }
}