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:com.passgit.app.PassGit.java

License:Open Source License

public boolean openRepository(char[] password, File keyFile) {

    try {/*from ww w  .  jav a2 s  .  c o m*/
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        gitRepository = builder.setMustExist(true).setWorkTree(rootPath.toFile()).build();

        cryptographer = (Cryptography) Class.forName(properties.getProperty("cryptographer")).newInstance();
        fileFormat = (Format) Class.forName(properties.getProperty("format")).newInstance();

        byte[] key = passwordPreparer.getKey(password, keyFile);

        if (key != null) {
            initCryptography(key);

            byte[] propertiesDigest = getCryptographer()
                    .decrypt(Base64.getDecoder().decode(properties.getProperty("mac")));

            if (arraysEqual(digest, propertiesDigest)) {

                preferences.put("root", rootPath.toString());
                if (keyFile != null) {
                    preferences.put("keyfile", keyFile.getAbsolutePath());
                } else {
                    preferences.remove("keyfile");
                }

                repositoryDialog.setVisible(false);

                return true;

            } else {

                JOptionPane.showMessageDialog(repositoryDialog,
                        "Password digest does not match password digest stored in repository properties.");

            }
        }

    } catch (IOException ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;
}

From source file:com.peergreen.configuration.git.GitConfiguration.java

License:Apache License

@Override
public ConfigRepository getRepository(String name) throws RepositoryException {
    check();/*from w w  w.  j  av  a2s . c o m*/

    // Sets the git directory from the given repository name
    File repositoryDir = new File(rootDirectory, name);
    File gitDir = new File(repositoryDir, Constants.DOT_GIT);

    // Find the git directory
    FileRepository fileRepository = null;
    try {
        fileRepository = new FileRepositoryBuilder() //
                .setGitDir(gitDir) // --git-dir if supplied, no-op if null
                .readEnvironment() // scan environment GIT_* variables
                .findGitDir().build();
    } catch (IOException e) {
        throw new RepositoryException("Unable to find a repository for the path '" + name + "'.", e);
    }

    // do not exist yet on the filesystem, create all the directories
    if (!gitDir.exists()) {
        try {
            fileRepository.create();
        } catch (IOException e) {
            throw new RepositoryException("Cannot create repository", e);
        }

        // Create the first commit in order to initiate the repository.
        Git git = new Git(fileRepository);
        CommitCommand commit = git.commit();
        try {
            commit.setMessage("Initial setup for the git configuration of '" + name + "'").call();
        } catch (GitAPIException e) {
            throw new RepositoryException("Cannot init the git repository '" + name + "'", e);
        }

    }

    return new GitRepository(fileRepository);

}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

private void importToGITRepo(RepoDetail repodetail, ApplicationInfo appInfo, File appDir) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.importToGITRepo()");
    }/*from  w  ww.jav a 2s  . c om*/
    boolean gitExists = false;
    if (new File(appDir.getPath() + FORWARD_SLASH + DOT + GIT).exists()) {
        gitExists = true;
    }
    try {
        //For https and ssh
        additionalAuthentication(repodetail.getPassPhrase());

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(repodetail.getUserName(),
                repodetail.getPassword());

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(appDir).readEnvironment().findGitDir().build();
        String dirPath = appDir.getPath();
        File gitignore = new File(dirPath + GITIGNORE_FILE);
        gitignore.createNewFile();
        if (gitignore.exists()) {
            String contents = FileUtils.readFileToString(gitignore);
            if (!contents.isEmpty() && !contents.contains(DO_NOT_CHECKIN_DIR)) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            } else if (contents.isEmpty()) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            }
        }

        Git git = new Git(repository);

        InitCommand initCommand = Git.init();
        initCommand.setDirectory(appDir);
        git = initCommand.call();

        AddCommand add = git.add();
        add.addFilepattern(".");
        add.call();

        CommitCommand commit = git.commit().setAll(true);
        commit.setMessage(repodetail.getCommitMessage()).call();
        StoredConfig config = git.getRepository().getConfig();

        config.setString(REMOTE, ORIGIN, URL, repodetail.getRepoUrl());
        config.setString(REMOTE, ORIGIN, FETCH, REFS_HEADS_REMOTE_ORIGIN);
        config.setString(BRANCH, MASTER, REMOTE, ORIGIN);
        config.setString(BRANCH, MASTER, MERGE, REF_HEAD_MASTER);
        config.save();

        try {
            PushCommand pc = git.push();
            pc.setCredentialsProvider(cp).setForce(true);
            pc.setPushAll().call();
        } catch (Exception e) {
            git.getRepository().close();
            PomProcessor appPomProcessor = new PomProcessor(new File(appDir, appInfo.getPhrescoPomFile()));
            appPomProcessor.removeProperty(Constants.POM_PROP_KEY_SRC_REPO_URL);
            appPomProcessor.save();
            throw e;
        }

        if (appInfo != null) {
            updateSCMConnection(appInfo, repodetail.getRepoUrl());
        }
        git.getRepository().close();
    } catch (Exception e) {
        Exception s = e;
        resetLocalCommit(appDir, gitExists, e);
        throw s;
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

private void resetLocalCommit(File appDir, boolean gitExists, Exception e) throws PhrescoException {
    try {/*  ww  w.  jav a  2  s  .c o m*/
        if (gitExists == true && e.getLocalizedMessage().contains("not authorized")) {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repository = builder.setGitDir(appDir).readEnvironment().findGitDir().build();
            Git git = new Git(repository);

            InitCommand initCommand = Git.init();
            initCommand.setDirectory(appDir);
            git = initCommand.call();

            ResetCommand reset = git.reset();
            ResetType mode = ResetType.SOFT;
            reset.setRef("HEAD~1").setMode(mode);
            reset.call();

            git.getRepository().close();
        }
    } catch (Exception pe) {
        new PhrescoException(pe);
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public List<RepoFileInfo> getGITCommitableFiles(File path) throws IOException, GitAPIException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(path).readEnvironment().findGitDir().build();
    Git git = new Git(repository);
    List<RepoFileInfo> fileslist = new ArrayList<RepoFileInfo>();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(path);//from w  w w. jav  a2 s .  c  om
    git = initCommand.call();
    Status status = git.status().call();

    Set<String> added = status.getAdded();
    Set<String> changed = status.getChanged();
    Set<String> conflicting = status.getConflicting();
    Set<String> missing = status.getMissing();
    Set<String> modified = status.getModified();
    Set<String> removed = status.getRemoved();
    Set<String> untracked = status.getUntracked();

    if (!added.isEmpty()) {
        for (String add : added) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + add;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("A");
            fileslist.add(repoFileInfo);
        }
    }

    if (!changed.isEmpty()) {
        for (String change : changed) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + change;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("M");
            fileslist.add(repoFileInfo);
        }
    }

    if (!conflicting.isEmpty()) {
        for (String conflict : conflicting) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + conflict;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("C");
            fileslist.add(repoFileInfo);
        }
    }

    if (!missing.isEmpty()) {
        for (String miss : missing) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + miss;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("!");
            fileslist.add(repoFileInfo);
        }
    }

    if (!modified.isEmpty()) {
        for (String modify : modified) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + modify;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("M");
            fileslist.add(repoFileInfo);
        }
    }

    if (!removed.isEmpty()) {
        for (String remove : removed) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + remove;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("D");
            fileslist.add(repoFileInfo);
        }
    }

    if (!untracked.isEmpty()) {
        for (String untrack : untracked) {
            RepoFileInfo repoFileInfo = new RepoFileInfo();
            String filePath = path + BACK_SLASH + untrack;
            repoFileInfo.setCommitFilePath(filePath);
            repoFileInfo.setStatus("?");
            fileslist.add(repoFileInfo);
        }
    }
    git.getRepository().close();
    return fileslist;
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public List<String> getSvnLogMessages(String Url, String userName, String Password, String repoType,
        String appDirName) throws PhrescoException {
    List<String> logMessages = new ArrayList<String>();
    if (repoType.equalsIgnoreCase(SVN)) {
        setupLibrary();/* w w w.j av a  2  s.c  o  m*/
        long startRevision = 0;
        long endRevision = -1; //HEAD (the latest) revision
        SVNRepository repository = null;
        try {
            repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(Url));
            ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(userName,
                    Password);
            repository.setAuthenticationManager(authManager);
            Collection logEntries = null;
            logEntries = repository.log(new String[] { "" }, null, startRevision, endRevision, false, true);
            for (Iterator entries = logEntries.iterator(); entries.hasNext();) {
                SVNLogEntry logEntry = (SVNLogEntry) entries.next();
                logMessages.add(logEntry.getMessage());
            }
        } catch (SVNException e) {
            throw new PhrescoException(e);
        } finally {
            if (repository != null) {
                repository.closeSession();
            }
        }
    } else if (repoType.equalsIgnoreCase(GIT)) {
        try {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            String dotGitDir = Utility.getProjectHome() + appDirName + File.separator + DOT_GIT;
            File dotGitDirectory = new File(dotGitDir);
            if (!dotGitDirectory.exists()) {
                dotGitDir = Utility.getProjectHome() + appDirName + File.separator + appDirName + File.separator
                        + DOT_GIT;
                dotGitDirectory = new File(dotGitDir);
            }
            if (!dotGitDir.isEmpty()) {
                Repository repo = builder.setGitDir(dotGitDirectory).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();
                    if (!rev.getFullMessage().isEmpty()) {
                        logMessages.add(rev.getFullMessage());
                    }
                }
                repo.close();
            }
        } catch (GitAPIException ge) {
            throw new PhrescoException(ge);
        } catch (IOException ioe) {
            throw new PhrescoException(ioe);
        }
    }
    return logMessages;
}

From source file:com.pieceof8.gradle.snapshot.GitScmProvider.java

License:Apache License

/** {@inheritDoc} */
@Override/* ww  w  .j  a  v  a  2s  .c  o  m*/
@SneakyThrows(IOException.class)
public Commit getCommit() {
    if (repoDir == null) {
        throw new IllegalArgumentException("'repoDir' must not be null");
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    @Cleanup
    Repository repo = builder.setGitDir(repoDir).readEnvironment().findGitDir().build();
    StoredConfig conf = repo.getConfig();

    int abbrev = Commit.ABBREV_LENGTH;
    if (conf != null) {
        abbrev = conf.getInt("core", "abbrev", abbrev);
    }

    val sdf = new SimpleDateFormat(extension.getDateFormat());

    val HEAD = repo.getRef(Constants.HEAD);
    if (HEAD == null) {
        val msg = "Could not get HEAD Ref, the repository may be corrupt.";
        throw new RuntimeException(msg);
    }

    RevWalk revWalk = new RevWalk(repo);
    if (HEAD.getObjectId() == null) {
        val msg = "Could not find any commits from HEAD ref.";
        throw new RuntimeException(msg);
    }
    RevCommit commit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(commit);

    try {
        // git commit time in sec and java datetime is in ms
        val commitTime = new Date(commit.getCommitTime() * 1000L);
        val ident = commit.getAuthorIdent();

        return new Commit(sdf.format(new Date()), // build time
                conf.getString("user", null, "name"), conf.getString("user", null, "email"), repo.getBranch(),
                commit.getName(), sdf.format(commitTime), ident.getName(), ident.getEmailAddress(),
                commit.getFullMessage().trim());
    } finally {
        revWalk.dispose();
    }
}

From source file:com.puppycrawl.tools.checkstyle.CommitValidationTest.java

License:Open Source License

private static List<RevCommit> getCommitsToCheck() throws Exception {
    Repository repo = new FileRepositoryBuilder().findGitDir().build();

    RevCommitsPair revCommitsPair = resolveRevCommitsPair(repo);
    List<RevCommit> commits;
    if (COMMITS_RESOLUTION_MODE == CommitsResolutionMode.BY_COUNTER) {
        commits = getCommitsByCounter(revCommitsPair.getFirst());
        commits.addAll(getCommitsByCounter(revCommitsPair.getSecond()));
    } else {//from w  w w . ja v a 2s .  co  m
        commits = getCommitsByLastCommitAuthor(revCommitsPair.getFirst());
        commits.addAll(getCommitsByLastCommitAuthor(revCommitsPair.getSecond()));
    }
    return commits;
}

From source file:com.sbt.plugins.MyMojo.java

License:Apache License

private void writeLogsInWriter(Writer writer) throws IOException, GitAPIException {
    Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File("./.git")).build();
    Git git = new Git(existingRepo);
    LogCommand logCommand = git.log();/*ww w.  j  a  v  a 2s  .c  o m*/
    Iterable<RevCommit> logs = logCommand.call();
    for (RevCommit current : logs) {
        writer.write(current.getName() + ": " + current.getFullMessage());
        writer.write(LINE_SEPARATOR);
    }
}

From source file:com.sillelien.dollar.plugins.pipe.GithubModuleResolver.java

License:Apache License

@NotNull
@Override/*w  ww.j  a v a 2 s  .  co m*/
public <T> Pipeable resolve(@NotNull String uriWithoutScheme, @NotNull T scope) throws Exception {
    logger.debug(uriWithoutScheme);
    String[] githubRepo = uriWithoutScheme.split(":");
    GitHub github = GitHub.connect();
    final String githubUser = githubRepo[0];
    GHRepository repository = github.getUser(githubUser).getRepository(githubRepo[1]);
    final String branch = githubRepo[2].length() > 0 ? githubRepo[2] : "master";
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File dir = new File(BASE_PATH + "/" + githubUser + "/" + githubRepo[1] + "/" + branch);
    dir.mkdirs();

    final File gitDir = new File(dir, ".git");
    if (gitDir.exists()) {
        Repository localRepo = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        PullCommand pull = git.pull();
        pull.call();
    } else {
        Repository localRepo = builder.setGitDir(dir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        CloneCommand clone = Git.cloneRepository();
        clone.setBranch(branch);
        clone.setBare(false);
        clone.setCloneAllBranches(false);
        clone.setDirectory(dir).setURI(repository.getGitTransportUrl());
        //        UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(login, password);
        //        clone.setCredentialsProvider(user);
        clone.call();
    }
    final ClassLoader classLoader;
    String content;
    File mainFile;
    if (githubRepo.length == 4) {
        classLoader = getClass().getClassLoader();
        mainFile = new File(dir, githubRepo[3]);
        content = new String(Files.readAllBytes(mainFile.toPath()));
    } else {
        final File moduleFile = new File(dir, "module.json");
        var module = DollarStatic.$(new String(Files.readAllBytes(moduleFile.toPath())));
        mainFile = new File(dir, module.$("main").$S());
        content = new String(Files.readAllBytes(mainFile.toPath()));
        classLoader = DependencyRetriever.retrieve(
                module.$("dependencies").$list().stream().map(var::toString).collect(Collectors.toList()));
    }
    return (params) -> ((Scope) scope).getDollarParser().inScope(false, "github-module", ((Scope) scope),
            newScope -> {

                final ImmutableMap<var, var> paramMap = params[0].$map();
                for (Map.Entry<var, var> entry : paramMap.entrySet()) {
                    newScope.set(entry.getKey().$S(), entry.getValue(), true, null, null, false, false, false);
                }
                return new DollarParserImpl(((Scope) scope).getDollarParser().options(), classLoader, dir)
                        .parse(newScope, content);
            });
}