Example usage for org.eclipse.jgit.api Git open

List of usage examples for org.eclipse.jgit.api Git open

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git open.

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

From source file:org.omegat.convert.ConvertProject26to37team.java

License:Open Source License

/**
 * Get repository URL for SVN./*from  w  w  w.  ja  v  a2 s.c  o  m*/
 */
private static String getGITUrl(File wc) throws Exception {
    Repository repository = Git.open(wc).getRepository();
    StoredConfig config = repository.getConfig();
    return config.getString("remote", "origin", "url");
}

From source file:org.omegat.convert.ConvertProject26to37team.java

License:Open Source License

/**
 * Get version of "omegat/project_save.tmx" in GIT.
 *///  ww  w .  java 2s. c  o m
private static String getGITTmxVersion(File wc) throws Exception {
    Repository repository = Git.open(wc).getRepository();
    try (RevWalk walk = new RevWalk(repository)) {
        Ref localBranch = repository.findRef("HEAD");
        RevCommit headCommit = walk.lookupCommit(localBranch.getObjectId());
        return headCommit.getName();
    }
}

From source file:org.omegat.core.team.GITRemoteRepository.java

License:Open Source License

public GITRemoteRepository(File localDirectory) throws Exception {

    try {// w  ww .  j a v  a 2s.c  om
        //workaround for: file c:\project\omegat\project_save.tmx is not contained in C:\project\.
        //The git repo uses the canonical path for some actions, and if c: != C: then an error is raised.
        //if we make it canonical already here, then we don't have that problem.
        localDirectory = localDirectory.getCanonicalFile();
    } catch (Exception e) {
    }

    this.localDirectory = localDirectory;
    CredentialsProvider prevProvider = CredentialsProvider.getDefault();
    myCredentialsProvider = new MyCredentialsProvider(this);
    if (prevProvider instanceof MyCredentialsProvider) {
        myCredentialsProvider.setCredentials(((MyCredentialsProvider) prevProvider).credentials);
    }
    CredentialsProvider.setDefault(myCredentialsProvider);
    File localRepositoryDirectory = getLocalRepositoryRoot(localDirectory);
    if (localRepositoryDirectory != null) {
        repository = Git.open(localRepositoryDirectory).getRepository();
    }
}

From source file:org.omegat.core.team.GITRemoteRepository.java

License:Open Source License

public void checkoutFullProject(String repositoryURL) throws Exception {
    Log.logInfoRB("GIT_START", "clone");
    CloneCommand c = Git.cloneRepository();
    c.setURI(repositoryURL);/*  w  w  w .j  av  a2s  .  c  o  m*/
    c.setDirectory(localDirectory);
    try {
        c.call();
    } catch (InvalidRemoteException e) {
        FileUtil.deleteTree(localDirectory);
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) {
            BadRepositoryException bre = new BadRepositoryException(
                    ((org.eclipse.jgit.errors.NoRemoteRepositoryException) cause).getLocalizedMessage());
            bre.initCause(e);
            throw bre;
        }
        throw e;
    }
    repository = Git.open(localDirectory).getRepository();
    new Git(repository).submoduleInit().call();
    new Git(repository).submoduleUpdate().call();

    //Deal with line endings. A normalized repo has LF line endings. 
    //OmegaT uses line endings of OS for storing tmx files.
    //To do auto converting, we need to change a setting:
    StoredConfig config = repository.getConfig();
    if ("\r\n".equals(FileUtil.LINE_SEPARATOR)) {
        //on windows machines, convert text files to CRLF
        config.setBoolean("core", null, "autocrlf", true);
    } else {
        //on Linux/Mac machines (using LF), don't convert text files
        //but use input format, unchanged.
        //NB: I don't know correct setting for OS'es like MacOS <= 9, 
        // which uses CR. Git manual only speaks about converting from/to
        //CRLF, so for CR, you probably don't want conversion either.
        config.setString("core", null, "autocrlf", "input");
    }
    config.save();
    myCredentialsProvider.saveCredentials();
    Log.logInfoRB("GIT_FINISH", "clone");
}

From source file:org.omegat.core.team2.impl.GITRemoteRepository2.java

License:Open Source License

@Override
public void init(RepositoryDefinition repo, File dir, ProjectTeamSettings teamSettings) throws Exception {
    repositoryURL = repo.getUrl();//w  w w . j av a2  s  . c o  m
    localDirectory = dir;

    String predefinedUser = repo.getOtherAttributes().get(new QName("gitUsername"));
    String predefinedPass = repo.getOtherAttributes().get(new QName("gitPassword"));
    String predefinedFingerprint = repo.getOtherAttributes().get(new QName("gitFingerprint"));
    ((GITCredentialsProvider) CredentialsProvider.getDefault()).setPredefinedCredentials(repositoryURL,
            predefinedUser, predefinedPass, predefinedFingerprint);
    ((GITCredentialsProvider) CredentialsProvider.getDefault()).setTeamSettings(teamSettings);

    File gitDir = new File(localDirectory, ".git");
    if (gitDir.exists() && gitDir.isDirectory()) {
        // already cloned
        repository = Git.open(localDirectory).getRepository();
    } else {
        Log.logInfoRB("GIT_START", "clone");
        CloneCommand c = Git.cloneRepository();
        c.setURI(repositoryURL);
        c.setDirectory(localDirectory);
        try {
            c.call();
        } catch (InvalidRemoteException e) {
            if (localDirectory.exists()) {
                deleteDirectory(localDirectory);
            }
            Throwable cause = e.getCause();
            if (cause != null && cause instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) {
                BadRepositoryException bre = new BadRepositoryException(
                        ((org.eclipse.jgit.errors.NoRemoteRepositoryException) cause).getLocalizedMessage());
                bre.initCause(e);
                throw bre;
            }
            throw e;
        }
        repository = Git.open(localDirectory).getRepository();
        try (Git git = new Git(repository)) {
            git.submoduleInit().call();
            git.submoduleUpdate().call();
        }

        // Deal with line endings. A normalized repo has LF line endings.
        // OmegaT uses line endings of OS for storing tmx files.
        // To do auto converting, we need to change a setting:
        StoredConfig config = repository.getConfig();
        if ("\r\n".equals(System.lineSeparator())) {
            // on windows machines, convert text files to CRLF
            config.setBoolean("core", null, "autocrlf", true);
        } else {
            // on Linux/Mac machines (using LF), don't convert text files
            // but use input format, unchanged.
            // NB: I don't know correct setting for OS'es like MacOS <= 9,
            // which uses CR. Git manual only speaks about converting from/to
            // CRLF, so for CR, you probably don't want conversion either.
            config.setString("core", null, "autocrlf", "input");
        }
        config.save();
        Log.logInfoRB("GIT_FINISH", "clone");
    }

    // cleanup repository
    try (Git git = new Git(repository)) {
        git.reset().setMode(ResetType.HARD).call();
    }
}

From source file:org.omegat.core.team2.TeamTool.java

License:Open Source License

/**
 * Utility function to create a minimal project to serve as a base for a
 * team project. Will add/stage everything if invoked on a path already
 * containing a git working tree or svn checkout.
 * /*from w  w w.j ava  2s . c  o m*/
 * @param dir
 *            Directory in which to create team project
 * @param srcLang
 *            Source language
 * @param trgLang
 *            Target language
 * @param showGui
 *            If true, show the Project Properties dialog
 * @throws Exception
 *             If specified dir is not a directory, is not writeable, etc.
 */
public static void initTeamProject(File dir, String srcLang, String trgLang) throws Exception {
    if (!dir.isDirectory()) {
        throw new IllegalArgumentException("Specified dir is not a directory: " + dir.getPath());
    }
    if (!dir.canWrite()) {
        throw new IOException("Specified dir is not writeable: " + dir.getPath());
    }

    // Create project properties
    ProjectProperties props = new ProjectProperties(dir);
    props.setSourceLanguage(srcLang);
    props.setTargetLanguage(trgLang);
    // Create project internal directories
    props.autocreateDirectories();
    // Create version-controlled glossary file
    props.getWritableGlossaryFile().getAsFile().createNewFile();
    ProjectFileStorage.writeProjectFile(props);

    // Create empty project TM
    new ProjectTMX(props.getSourceLanguage(), props.getTargetLanguage(), props.isSentenceSegmentingEnabled(),
            null, null).save(props, new File(props.getProjectInternal(), OConsts.STATUS_EXTENSION).getPath(),
                    false);

    // If the supplied dir is under version control, add everything we made
    // and set EOL handling correctly for cross-platform work
    if (new File(dir, ".svn").isDirectory()) {
        SVNClientManager mgr = SVNClientManager.newInstance();
        mgr.getWCClient().doSetProperty(dir, "svn:auto-props",
                SVNPropertyValue.create("*.txt = svn:eol-style=native\n*.tmx = svn:eol-style=native\n"), false,
                SVNDepth.EMPTY, null, null);
        mgr.getWCClient().doAdd(dir.listFiles(f -> !f.getName().startsWith(".")), false, false, true,
                SVNDepth.fromRecurse(true), false, false, false, true);
    } else if (new File(dir, ".git").isDirectory()) {
        try (BufferedWriter writer = Files.newBufferedWriter(new File(dir, ".gitattributes").toPath())) {
            writer.write("* text=auto\n");
            writer.write("*.tmx text\n");
            writer.write("*.txt text\n");
        }
        Git.open(dir).add().addFilepattern(".").call();
    }

    System.out.println(StringUtil.format(OStrings.getString("TEAM_TOOL_INIT_COMPLETE"), srcLang, trgLang));
}

From source file:org.openflexo.hannah.IterativeFileGenerator.java

License:Open Source License

/**
 * <p>Prepares the next generation. It collects the modifications made 
 * since last generation. By default all modifications are kept and merged
 * with the next generation, but the callback allows to cancel 
 * modifications (for example if's pushed back to the model)..</p>
 * /*  ww  w  . j  ava  2 s.c o m*/
 * @param callback called for each user modification.
 * 
 * @throws IOException for any file manipulation gone wrong.
 * @throws GitAPIException  if Git can't manipulate the repository.
 */
public void start(ModificationHandler callback) throws IOException, GitAPIException {
    // creates output folder if needed.
    if (outputFolder.exists() == false) {
        outputFolder.mkdirs();
    }

    // checks that output folder is a folder and accessible.
    if (outputFolder.isDirectory() == false || outputFolder.canRead() == false
            || outputFolder.canWrite() == false) {
        throw new IOException("Folder '" + outputFolder + "' isn't accessible.");
    }

    if (gitFolder.exists()) {
        throw new IOException("Output folder is already a Git working copy.");
    }

    // is the folder already a generation folder, checks the git file.
    if (hannahFolder.exists() == false) {
        // no repository, creates the repository.
        git = Git.init().setDirectory(outputFolder).setBare(false).call();

        final String[] children = outputFolder.list();
        if (children == null || children.length <= 1) {
            // if folder only contains '.git' creates a dummy file.
            FileUtil.writeFile(new File(outputFolder, DUMMY_FILENAME), "For master branch creation\n", "UTF-8");
        }

        // creates the master branch
        git.add().addFilepattern(".").call();
        git.commit().setMessage("Creates master branch.").call();

        // create the generation branch
        git.branchCreate().setName(GENERATION).call();

    } else {
        // repository exists, renames it and opens it.
        hannahFolder.renameTo(gitFolder);
        git = Git.open(outputFolder);
    }

    // retrieves diffs
    final List<DiffEntry> diffEntries = git.diff().call();
    if (diffEntries.size() > 0) {
        // creates modifications and calls the handler.
        final List<Modification> modifications = createModificationList(diffEntries);
        if (callback != null) {
            callback.modifications(modifications);
        }

        // checks which modifications should be committed
        boolean somethingAccepted = false;
        final AddCommand add = git.add();
        for (Modification modification : modifications) {
            if (modification.isAccept()) {
                somethingAccepted = true;
                add.addFilepattern(modification.getDiff().getNewPath());
            }
        }

        // calls add on accepted modifications
        if (somethingAccepted) {
            add.call();
            git.commit().setMessage("User modifications").call();
        }

        // reverts un-commited diffs
        git.revert().call();

    }

    // checkouts generation branch
    git.checkout().setName(GENERATION).call();

    // clear files before new generation
    final File[] children = outputFolder.listFiles();
    if (children != null) {
        for (File child : children) {
            if (NOT_DELETED_FILES.contains(child.getName()) == false) {
                FileUtil.delete(child);
            }
        }
    }
}

From source file:org.phoenicis.repository.types.GitRepository.java

License:Open Source License

private void cloneOrUpdate() throws RepositoryException {
    final boolean folderExists = this.localFolder.exists();

    // check that the repository folder exists
    if (!folderExists) {
        LOGGER.info("Creating local folder for " + this);

        if (!this.localFolder.mkdirs()) {
            throw new RepositoryException("Couldn't create local folder for " + this);
        }/* ww  w . j ava  2 s. c  o m*/
    }
    Git gitRepository = null;

    /*
     * if the repository folder previously didn't exist, clone the
     * repository now and checkout the correct branch
     */
    if (!folderExists) {
        LOGGER.info("Cloning " + this);

        try {
            gitRepository = Git.cloneRepository().setURI(this.repositoryUri.toString())
                    .setDirectory(this.localFolder).setBranch(this.branch).call();
        } catch (GitAPIException e) {
            throw new RepositoryException(
                    String.format("Folder '%s' is no git-repository", this.localFolder.getAbsolutePath()), e);
        } finally {
            // close repository to free resources
            if (gitRepository != null) {
                gitRepository.close();
            }
        }
    }
    /*
     * otherwise open the folder and pull the newest updates from the
     * repository
     */
    else {
        // if anything doesn't work here, we still have our local checkout
        // e.g. could be that the git repository cannot be accessed, there is not Internet connection etc.
        // TODO: it might make sense to ensure that our local checkout is not empty / a valid git repository
        try {
            LOGGER.info("Opening " + this);

            gitRepository = Git.open(localFolder);

            LOGGER.info("Pulling new commits from " + this);

            gitRepository.pull().call();
        } catch (Exception e) {
            LOGGER.warn("Could not update {0}. Local checkout will be used.", e);
        } finally {
            // close repository to free resources
            if (gitRepository != null) {
                gitRepository.close();
            }
        }
    }
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

protected Git openRepository() throws IOException, GitAPIException {
    Git git = Git.open(new File(path));
    if (this.mainBranchName == null) {
        this.mainBranchName = discoverMainBranchName(git);
    }/*from   ww w  . j  av  a2 s  . c o  m*/
    return git;
}

From source file:org.springframework.cloud.config.server.environment.JGitConfigServerTestData.java

License:Apache License

public static JGitConfigServerTestData prepareClonedGitRepository(Object... sources) throws Exception {
    //setup remote repository
    String remoteUri = ConfigServerTestUtils.prepareLocalRepo();
    File remoteRepoDir = ResourceUtils.getFile(remoteUri);
    Git remoteGit = Git.open(remoteRepoDir.getAbsoluteFile());
    remoteGit.checkout().setName("master").call();

    //setup local repository
    File clonedRepoDir = new File("target/repos/cloned");
    if (clonedRepoDir.exists()) {
        FileSystemUtils.deleteRecursively(clonedRepoDir);
    } else {//from   w w w  .  j av a 2s .com
        clonedRepoDir.mkdirs();
    }
    Git clonedGit = Git.cloneRepository().setURI("file://" + remoteRepoDir.getAbsolutePath())
            .setDirectory(clonedRepoDir).setBranch("master").setCloneAllBranches(true).call();

    //setup our test spring application pointing to the local repo
    ConfigurableApplicationContext context = new SpringApplicationBuilder(sources).web(false)
            .properties("spring.cloud.config.server.git.uri:" + "file://" + clonedRepoDir.getAbsolutePath())
            .run();
    JGitEnvironmentRepository repository = context.getBean(JGitEnvironmentRepository.class);

    return new JGitConfigServerTestData(new JGitConfigServerTestData.LocalGit(remoteGit, remoteRepoDir),
            new JGitConfigServerTestData.LocalGit(clonedGit, clonedRepoDir), repository, context);
}