Example usage for org.eclipse.jgit.submodule SubmoduleWalk getSubmoduleRepository

List of usage examples for org.eclipse.jgit.submodule SubmoduleWalk getSubmoduleRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.submodule SubmoduleWalk getSubmoduleRepository.

Prototype

public static Repository getSubmoduleRepository(final File parent, final String path) throws IOException 

Source Link

Document

Get submodule repository at path

Usage

From source file:com.github.rwhogg.git_vcr.App.java

License:Open Source License

/**
 * main is the entry point for Git-VCR// w w w .  j a  v  a  2  s  .c o m
 * @param args Command-line arguments
 */
public static void main(String[] args) {
    Options options = parseCommandLine(args);

    HierarchicalINIConfiguration configuration = null;
    try {
        configuration = getConfiguration();
    } catch (ConfigurationException e) {
        Util.error("could not parse configuration file!");
    }

    // verify we are in a git folder and then construct the repo
    final File currentFolder = new File(".");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository localRepo = null;
    try {
        localRepo = builder.findGitDir().build();
    } catch (IOException e) {
        Util.error("not in a Git folder!");
    }

    // deal with submodules
    assert localRepo != null;
    if (localRepo.isBare()) {
        FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder();
        Repository parentRepo;
        try {
            parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build();
            localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName());
        } catch (IOException e) {
            Util.error("could not find parent of submodule!");
        }
    }

    // if we need to retrieve the patch file, get it now
    URL patchUrl = options.getPatchUrl();
    String patchPath = patchUrl.getFile();
    File patchFile = null;
    HttpUrl httpUrl = HttpUrl.get(patchUrl);
    if (httpUrl != null) {
        try {
            patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff");
            Request request = new Request.Builder().url(httpUrl).build();
            OkHttpClient client = new OkHttpClient();
            Call call = client.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (!response.isSuccessful()) {
                Util.error("could not retrieve diff file from URL " + patchUrl);
            }
            String content = body.string();
            org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null);
        } catch (IOException ie) {
            Util.error("could not retrieve diff file from URL " + patchUrl);
        }
    } else {
        patchFile = new File(patchPath);
    }

    // find the patch
    //noinspection ConstantConditions
    if (!patchFile.canRead()) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!");
    }

    final Git git = new Git(localRepo);

    // handle the branch
    String branchName = options.getBranchName();
    String theOldCommit = null;
    try {
        theOldCommit = localRepo.getBranch();
    } catch (IOException e2) {
        Util.error("could not get reference to current branch!");
    }
    final String oldCommit = theOldCommit; // needed to reference from shutdown hook

    if (branchName != null) {
        // switch to the branch
        try {
            git.checkout().setName(branchName).call();
        } catch (RefAlreadyExistsException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        } catch (RefNotFoundException e) {
            Util.error("the branch " + branchName + " was not found!");
        } catch (InvalidRefNameException e) {
            Util.error("the branch name " + branchName + " is invalid!");
        } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
            Util.error("there was a checkout conflict!");
        } catch (GitAPIException e) {
            Util.error("there was an unspecified Git API failure!");
        }
    }

    // ensure there are no changes before we apply the patch
    try {
        if (!git.status().call().isClean()) {
            Util.error("cannot run git-vcr while there are uncommitted changes!");
        }
    } catch (NoWorkTreeException e1) {
        // won't happen
        assert false;
    } catch (GitAPIException e1) {
        Util.error("call to git status failed!");
    }

    // list all the files changed
    String patchName = patchFile.getName();
    Patch patch = new Patch();
    try {
        patch.parse(new FileInputStream(patchFile));
    } catch (FileNotFoundException e) {
        assert false;
    } catch (IOException e) {
        Util.error("could not parse the patch file!");
    }

    ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false);
    try {
        oldResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // we're about to change the repo, so register a shutdown hook to clean it up
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            cleanupGit(git, oldCommit);
        }
    });

    // apply the patch
    try {
        git.apply().setPatch(new FileInputStream(patchFile)).call();
    } catch (PatchFormatException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!");
    } catch (PatchApplyException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!");
    } catch (FileNotFoundException e) {
        assert false;
    } catch (GitAPIException e) {
        Util.error(e.getLocalizedMessage());
    }

    ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true);
    try {
        newResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // generate and show the report
    VelocityReport report = new VelocityReport(patch, oldResults, newResults);
    File reportFile = null;
    try {
        reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html");
        org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null);
    } catch (IOException e) {
        Util.error("could not generate the results page!");
    }

    try {
        assert reportFile != null;
        Desktop.getDesktop().open(reportFile);
    } catch (IOException e) {
        Util.error("could not open the results page!");
    }
}

From source file:net.polydawn.mdm.MdmModuleRelease.java

License:Open Source License

public static MdmModuleRelease load(Repository parent, String path, Config gitmodulesCfg)
        throws MdmRepositoryNonexistant, MdmRepositoryIOException, MdmModuleTypeException {
    try {//from   w  w  w . ja  v a  2s  . c om
        Repository repo = SubmoduleWalk.getSubmoduleRepository(parent, path);
        return new MdmModuleRelease(repo, path, parent, gitmodulesCfg, null);
    } catch (IOException e) {
        throw new MdmRepositoryIOException(false, path, e);
    }
}

From source file:org.eclipse.egit.core.op.SubmoduleUpdateOperation.java

License:Open Source License

public void execute(final IProgressMonitor monitor) throws CoreException {
    IWorkspaceRunnable action = new IWorkspaceRunnable() {

        public void run(IProgressMonitor pm) throws CoreException {
            pm.beginTask("", 3); //$NON-NLS-1$
            Git git = Git.wrap(repository);

            Collection<String> updated = null;
            try {
                SubmoduleInitCommand init = git.submoduleInit();
                for (String path : paths)
                    init.addPath(path);//  ww w  .j a va 2  s  .c o  m
                init.call();
                pm.worked(1);

                SubmoduleUpdateCommand update = git.submoduleUpdate();
                for (String path : paths)
                    update.addPath(path);
                update.setProgressMonitor(new EclipseGitProgressTransformer(new SubProgressMonitor(pm, 2)));
                updated = update.call();
                pm.worked(1);
                SubProgressMonitor refreshMonitor = new SubProgressMonitor(pm, 1);
                refreshMonitor.beginTask("", updated.size()); //$NON-NLS-1$
                for (String path : updated) {
                    Repository subRepo = SubmoduleWalk.getSubmoduleRepository(repository, path);
                    if (subRepo != null)
                        ProjectUtil.refreshValidProjects(ProjectUtil.getValidOpenProjects(subRepo),
                                new SubProgressMonitor(refreshMonitor, 1));
                    else
                        refreshMonitor.worked(1);
                }
                refreshMonitor.done();
            } catch (GitAPIException e) {
                throw new TeamException(e.getLocalizedMessage(), e.getCause());
            } catch (IOException e) {
                throw new TeamException(e.getLocalizedMessage(), e.getCause());
            } finally {
                if (updated != null && !updated.isEmpty())
                    repository.notifyIndexChanged();
                pm.done();
            }
        }
    };
    ResourcesPlugin.getWorkspace().run(action, monitor != null ? monitor : new NullProgressMonitor());
}

From source file:org.eclipse.egit.ui.internal.submodules.SubmoduleFolderTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    parentRepositoryGitDir = createProjectAndCommitToRepository();
    childRepositoryGitDir = createProjectAndCommitToRepository(CHILDREPO, CHILDPROJECT);
    Activator.getDefault().getRepositoryUtil().addConfiguredRepository(parentRepositoryGitDir);
    parentRepository = lookupRepository(parentRepositoryGitDir);
    childRepository = lookupRepository(childRepositoryGitDir);
    parentProject = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1);
    IFolder folder = parentProject.getFolder(FOLDER);
    IFolder subfolder = folder.getFolder(SUBFOLDER);
    subfolder.create(false, true, null);
    assertTrue(subfolder.exists());/*  w  w  w.ja  va 2 s  . c o m*/
    IFile someFile = subfolder.getFile("dummy.txt");
    touch(PROJ1, someFile.getProjectRelativePath().toOSString(), "Dummy content");
    addAndCommit(someFile, "Commit sub/dummy.txt");
    childFolder = subfolder.getFolder(CHILD);
    Git.wrap(parentRepository).submoduleAdd().setPath(childFolder.getFullPath().toPortableString())
            .setURI(childRepository.getDirectory().toURI().toString()).call();
    TestRepository parentRepo = new TestRepository(parentRepository);
    parentRepo.trackAllFiles(parentProject);
    parentRepo.commit("Commit submodule");
    assertTrue(SubmoduleWalk.containsGitModulesFile(parentRepository));
    parentProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    assertTrue(childFolder.exists());
    // Let's get rid of the child project imported directly from the child
    // repository.
    childProject = ResourcesPlugin.getWorkspace().getRoot().getProject(CHILDPROJECT);
    childProject.delete(false, true, null);
    // Re-import it from the parent repo's submodule!
    IFile projectFile = childFolder.getFolder(CHILDPROJECT).getFile(IProjectDescription.DESCRIPTION_FILE_NAME);
    assertTrue(projectFile.exists());
    ProjectRecord pr = new ProjectRecord(projectFile.getLocation().toFile());
    ProjectUtils.createProjects(Collections.singleton(pr), null, null);
    assertTrue(childProject.isOpen());
    // Now we have a parent repo in a state as if we had recursively
    // cloned some remote repo with a submodule and then imported all
    // projects. Look up the submodule repository instance through the
    // repository cache, so that we get the same instance that EGit
    // uses.
    subRepository = SubmoduleWalk.getSubmoduleRepository(childFolder.getParent().getLocation().toFile(), CHILD);
    assertNotNull(subRepository);
    subRepositoryGitDir = subRepository.getDirectory();
    subRepository.close();
    subRepository = lookupRepository(subRepositoryGitDir);
    assertNotNull(subRepository);
}