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

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

Introduction

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

Prototype

public RmCommand rm() 

Source Link

Document

Return a command object to execute a rm command

Usage

From source file:org.eclipse.mylyn.gerrit.tests.support.GerritProject.java

License:Open Source License

public void removeFile(String fileName) throws Exception {
    Git gitProject = getGitProject();
    gitProject.rm().addFilepattern(fileName).call();
}

From source file:org.eclipse.orion.server.git.servlets.GitSubmoduleHandlerV1.java

License:Open Source License

public static void removeSubmodule(Repository db, Repository parentRepo, String pathToSubmodule)
        throws Exception {
    pathToSubmodule = pathToSubmodule.replace("\\", "/");
    StoredConfig gitSubmodulesConfig = getGitSubmodulesConfig(parentRepo);
    gitSubmodulesConfig.unsetSection(CONFIG_SUBMODULE_SECTION, pathToSubmodule);
    gitSubmodulesConfig.save();//w  ww  .j a  va  2  s . c  o  m
    StoredConfig repositoryConfig = parentRepo.getConfig();
    repositoryConfig.unsetSection(CONFIG_SUBMODULE_SECTION, pathToSubmodule);
    repositoryConfig.save();
    Git git = Git.wrap(parentRepo);
    git.add().addFilepattern(DOT_GIT_MODULES).call();
    RmCommand rm = git.rm().addFilepattern(pathToSubmodule);
    if (gitSubmodulesConfig.getSections().size() == 0) {
        rm.addFilepattern(DOT_GIT_MODULES);
    }
    rm.call();
    FileUtils.delete(db.getWorkTree(), FileUtils.RECURSIVE);
    FileUtils.delete(db.getDirectory(), FileUtils.RECURSIVE);
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitStatusTest.java

License:Open Source License

@Test
public void testFileLogFromStatus() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject projectTop = createProjectOrLink(workspaceLocation, getMethodName() + "-top", null);
    IPath clonePathTop = new Path("file").append(projectTop.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    JSONObject projectFolder = createProjectOrLink(workspaceLocation, getMethodName() + "-folder", null);
    IPath clonePathFolder = new Path("file").append(projectFolder.getString(ProtocolConstants.KEY_ID))
            .append("folder").makeAbsolute();

    IPath[] clonePaths = new IPath[] { clonePathTop, clonePathFolder };

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project/folder metadata
        WebRequest request = getGetFilesRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());
        String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
        String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);

        // add new files to the local repository so they can be deleted and removed in the test later on
        // missing
        String missingFileName = "missing.txt";
        request = getPutFileRequest(folderLocation + "/" + missingFileName, "you'll miss me");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // git section for the 'missing' file
        request = getGetFilesRequest(folderChildrenLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));
        JSONObject missingFile = getChildByName(children, missingFileName);
        JSONObject gitSection = missingFile.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

        // "git add {path}"
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        String removedFileName = "removed.txt";
        request = getPutFileRequest(folderLocation + "/" + removedFileName, "I'll be removed");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // refresh children
        request = getGetFilesRequest(folderChildrenLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        children = getDirectoryChildren(new JSONObject(response.getText()));

        JSONObject removedFile = getChildByName(children, removedFileName);
        gitSection = removedFile.getJSONObject(GitConstants.KEY_GIT);
        gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

        // "git add {path}"
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // git section for the folder
        gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "committing all changes", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // make the file missing
        request = getDeleteFilesRequest(missingFile.getString(ProtocolConstants.KEY_LOCATION));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // remove the file
        Repository repository = getRepositoryForContentLocation(cloneContentLocation);
        Git git = new Git(repository);
        RmCommand rm = git.rm();
        rm.addFilepattern(removedFileName);
        rm.call();//from  w  ww  . j  av  a 2 s.  c om

        // untracked file
        String untrackedFileName = "untracked.txt";
        request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(untrackedFileName).toString(),
                untrackedFileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        // added file
        String addedFileName = "added.txt";
        request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(addedFileName).toString(),
                addedFileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        request = getGetFilesRequest(folderChildrenLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        children = getDirectoryChildren(new JSONObject(response.getText()));
        JSONObject addedFile = getChildByName(children, addedFileName);
        gitSection = addedFile.getJSONObject(GitConstants.KEY_GIT);
        gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

        request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // changed file
        JSONObject testTxt = getChildByName(children, "test.txt");
        request = getPutFileRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION), "change");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        request = GitAddTest.getPutGitIndexRequest(
                testTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_INDEX));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modified file
        request = getPutFileRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION),
                "second change, in working tree");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // get status
        request = getGetGitStatusRequest(
                folder.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_STATUS));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject statusResponse = new JSONObject(response.getText());
        JSONArray statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_ADDED);
        assertEquals(1, statusArray.length());
        assertEquals(addedFileName, statusArray.getJSONObject(0).getString(ProtocolConstants.KEY_NAME));
        gitSection = statusArray.getJSONObject(0).getJSONObject(GitConstants.KEY_GIT);
        String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);
        JSONArray log = log(gitCommitUri, false);
        assertEquals(0, log.length());
        statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_CHANGED);
        assertEquals(1, statusArray.length());
        assertEquals("test.txt", statusArray.getJSONObject(0).getString(ProtocolConstants.KEY_NAME));
        gitSection = statusArray.getJSONObject(0).getJSONObject(GitConstants.KEY_GIT);
        gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);
        log = log(gitCommitUri, false);
        assertEquals(1, log.length());
        statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_MISSING);
        assertEquals(1, statusArray.length());
        assertEquals(missingFileName, statusArray.getJSONObject(0).getString(ProtocolConstants.KEY_NAME));
        gitSection = statusArray.getJSONObject(0).getJSONObject(GitConstants.KEY_GIT);
        gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);
        log = log(gitCommitUri, false);
        assertEquals(1, log.length());
        statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_MODIFIED);
        assertEquals(1, statusArray.length());
        assertEquals("test.txt", statusArray.getJSONObject(0).getString(ProtocolConstants.KEY_NAME));
        gitSection = statusArray.getJSONObject(0).getJSONObject(GitConstants.KEY_GIT);
        gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);
        log = log(gitCommitUri, false);
        assertEquals(1, log.length());
        statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_REMOVED);
        assertEquals(1, statusArray.length());
        assertEquals(removedFileName, statusArray.getJSONObject(0).getString(ProtocolConstants.KEY_NAME));
        gitSection = statusArray.getJSONObject(0).getJSONObject(GitConstants.KEY_GIT);
        gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);
        log = log(gitCommitUri, false);
        assertEquals(1, log.length());
        statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_UNTRACKED);
        assertEquals(1, statusArray.length());
        assertEquals(untrackedFileName, statusArray.getJSONObject(0).getString(ProtocolConstants.KEY_NAME));
        gitSection = statusArray.getJSONObject(0).getJSONObject(GitConstants.KEY_GIT);
        gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);
        log = log(gitCommitUri, false);
        assertEquals(0, log.length());
    }
}

From source file:org.exist.git.xquery.Remove.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/*from  w  w w. j  av a 2  s . c  o m*/
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        Git git = Git.open(new Resource(localPath), FS);

        git.rm().addFilepattern(args[1].getStringValue()).call();

        return BooleanValue.TRUE;
    } catch (Throwable e) {
        throw new XPathException(this, Module.EXGIT001, e);
    }
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

public void testWithProfiles() throws Exception {
    String testProfileNameBase = "mytestprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult()
            .build();//from   www .  j  a v a  2s .com
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());

    GitUtils.waitForBranchUpdate(getCurator(), "1.0");

    Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo)
            .setCredentialsProvider(getCredentialsProvider()).call();
    Git git = Git.open(testrepo);
    GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0");
    git.fetch().setCredentialsProvider(getCredentialsProvider());
    GitUtils.checkoutBranch(git, "origin", "1.0");

    //Check that the default profile exists
    assertTrue(new File(testrepo, "default").exists());

    //Create test profile
    for (int i = 1; i <= 3; i++) {
        String testProfileName = testProfileNameBase + i;
        System.err.println("Create test profile:" + testProfileName + " in zookeeper");
        getFabricService().getVersion("1.0").createProfile(testProfileName);
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        git.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call();
        //Check that a newly created profile exists
        assertTrue(new File(testrepo, testProfileName).exists());
        //Delete test profile
        System.err.println("Delete test profile:" + testProfileName + " in git.");
        git.rm().addFilepattern(testProfileName).call();
        git.commit().setMessage("Delete " + testProfileName).call();
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        Thread.sleep(5000);
        assertFalse(new File(testrepo, testProfileName).exists());
        assertNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));

        //Create the test profile in git
        System.err.println("Create test profile:" + testProfileName + " in git.");
        File testProfileDir = new File(testrepo, testProfileName);
        testProfileDir.mkdirs();
        File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
        testProfileConfig.createNewFile();
        Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
        git.add().addFilepattern(testProfileName).call();
        RevCommit commit = git.commit().setMessage("Create " + testProfileName).call();
        FileTreeIterator fileTreeItr = new FileTreeIterator(git.getRepository());
        IndexDiff indexDiff = new IndexDiff(git.getRepository(), commit.getId(), fileTreeItr);
        System.out.println(indexDiff.getChanged());
        System.out.println(indexDiff.getAdded());
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        //Check that it has been bridged in zookeeper
        Thread.sleep(15000);
        assertNotNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));
    }
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Move file in test repository/*from  w ww  .  ja va  2  s.  c  om*/
 *
 * @param repo
 * @param from
 * @param to
 * @param message
 * @return commit
 * @throws Exception
 */
protected RevCommit mv(File repo, String from, String to, String message) throws Exception {
    File file = new File(repo.getParentFile(), from);
    file.renameTo(new File(repo.getParentFile(), to));
    Git git = Git.open(repo);
    git.rm().addFilepattern(from);
    git.add().addFilepattern(to).call();
    RevCommit commit = git.commit().setAll(true).setMessage(message).setAuthor(author).setCommitter(committer)
            .call();
    assertNotNull(commit);
    return commit;
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Delete and commit file at path/*from ww  w.  j a  v  a 2  s .c o  m*/
 *
 * @param path
 * @return commit
 * @throws Exception
 */
protected RevCommit delete(String path) throws Exception {
    String message = MessageFormat.format("Committing {0} at {1}", path, new Date());
    Git git = Git.open(testRepo);
    git.rm().addFilepattern(path).call();
    RevCommit commit = git.commit().setOnly(path).setMessage(message).setAuthor(author).setCommitter(committer)
            .call();
    assertNotNull(commit);
    return commit;
}

From source file:org.kaazing.bower.dependency.maven.plugin.UploadBowerArtifactMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);
    File repoDir = new File(outputDir);
    Git repo = checkoutGitRepo(repoDir, gitBowerUrl, credentialsProvider);
    if (preserveFiles == null || preserveFiles.isEmpty()) {
        preserveFiles = new ArrayList<String>();
        preserveFiles.add("README.md");
        preserveFiles.add("bower.json");
        preserveFiles.add("package.json");
        preserveFiles.add(".git");

    }// ww  w  . ja  v a  2  s.com
    for (File file : repoDir.listFiles()) {
        if (!preserveFiles.contains(file.getName())) {
            file.delete();
            try {
                repo.rm().addFilepattern(file.getName()).call();
            } catch (GitAPIException e) {
                throw new MojoExecutionException("Failed to reset repo", e);
            }
        }
    }

    for (String include : includes) {
        File includedFile = new File(includeBaseDir, include);
        if (!includedFile.exists()) {
            throw new MojoExecutionException("Included file \"" + include
                    + "\" does not exist at includeBaseDir/{name}: " + includedFile.getAbsolutePath());
        }
        if (includedFile.isDirectory()) {
            throw new MojoExecutionException("Included files can not be directory: " + includedFile);
        }
        try {
            Files.copy(includedFile.toPath(), new File(outputDir, include).toPath());
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to copy included resource", e);
        }
        try {
            repo.add().addFilepattern(include).call();
        } catch (GitAPIException e) {
            throw new MojoExecutionException("Failed to add included file", e);
        }
    }

    if (directoryToInclude != null && !directoryToInclude.equals("")) {
        File includedDir = new File(directoryToInclude);
        if (!includedDir.exists() && includedDir.isDirectory()) {
            throw new MojoExecutionException(
                    "Included directory \"" + directoryToInclude + "\" does not exist");
        }
        for (File includedFile : includedDir.listFiles()) {
            String include = includedFile.getName();
            if (includedFile.isDirectory()) {
                throw new MojoExecutionException("Included files can not be directory: " + includedFile);
            }
            try {
                Files.copy(includedFile.toPath(), new File(outputDir, include).toPath());
            } catch (IOException e) {
                throw new MojoExecutionException("Failed to copy included resource", e);
            }
            try {
                repo.add().addFilepattern(include).call();
            } catch (GitAPIException e) {
                throw new MojoExecutionException("Failed to add included file", e);
            }
        }
    }

    try {
        repo.commit().setMessage("Added files for next release of " + version).call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to commit to repo with changes", e);
    }
    try {
        repo.tag().setName(version).setMessage("Releasing version: " + version).call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to tag release", e);
    }
    try {
        repo.push().setPushTags().setCredentialsProvider(credentialsProvider).call();
        repo.push().setPushAll().setCredentialsProvider(credentialsProvider).call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to push changes", e);
    }
}

From source file:org.ms123.common.git.GitServiceImpl.java

License:Open Source License

public void rm(@PName("name") String name, @PName("pattern") String pattern) throws RpcException {
    try {//from   w ww . j  ava2 s. c  o  m
        String gitSpace = System.getProperty("git.repos");
        File dir = new File(gitSpace, name);
        if (!dir.exists()) {
            throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.rm:Repo(" + name + ") not exists");
        }
        Git git = Git.open(dir);
        RmCommand rm = git.rm();
        rm.addFilepattern(pattern);
        rm.call();
        return;
    } catch (Exception e) {
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.rm:", e);
    } finally {
    }
}

From source file:org.obiba.git.command.DeleteFilesCommand.java

License:Open Source License

@Override
public Iterable<PushResult> execute(Git git) {
    try {/*from ww  w.j a  va2s  .co m*/
        git.rm().addFilepattern(filePattern).call();
        return commitAndPush(git);
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}