hudson.plugins.git.GitException Java Examples

The following examples show how to use hudson.plugins.git.GitException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public ObjectId mergeBase(ObjectId id1, ObjectId id2) throws InterruptedException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk walk = new RevWalk(or)) {
        walk.setRetainBody(false);  // we don't need the body for this computation
        walk.setRevFilter(RevFilter.MERGE_BASE);

        walk.markStart(walk.parseCommit(id1));
        walk.markStart(walk.parseCommit(id2));

        RevCommit base = walk.next();
        if (base==null)     return null;    // no common base
        return base.getId();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #2
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public List<IndexEntry> lsTree(String treeIsh, boolean recursive) throws GitException, InterruptedException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk w = new RevWalk(or)) {
        TreeWalk tree = new TreeWalk(or);
        tree.addTree(w.parseTree(repo.resolve(treeIsh)));
        tree.setRecursive(recursive);

        List<IndexEntry> r = new ArrayList<>();
        while (tree.next()) {
            RevObject rev = w.parseAny(tree.getObjectId(0));
            r.add(new IndexEntry(
                    String.format("%06o", tree.getRawMode(0)),
                    typeString(rev.getType()),
                    tree.getObjectId(0).name(),
                    tree.getNameString()));
        }
        return r;
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #3
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public void push(RemoteConfig repository, String refspec) throws GitException, InterruptedException {
    ArgumentListBuilder args = new ArgumentListBuilder();
    URIish uri = repository.getURIs().get(0);
    String url = uri.toPrivateString();
    StandardCredentials cred = credentials.get(url);
    if (cred == null) cred = defaultCredentials;

    args.add("push");
    addCheckedRemoteUrl(args, url);

    if (refspec != null)
        args.add(refspec);

    launchCommandWithCredentials(args, workspace, cred, uri);
    // Ignore output for now as there's many different formats
    // That are possible.

}
 
Example #4
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public List<String> showRevision(ObjectId from, ObjectId to, Boolean useRawOutput) throws GitException, InterruptedException {
    ArgumentListBuilder args = new ArgumentListBuilder("log", "--full-history", "--no-abbrev", "--format=raw", "-M", "-m");
    if (useRawOutput) {
        args.add("--raw");
    }

	if (from != null){
        args.add(from.name() + ".." + to.name());
    } else {
        args.add("-1", to.name());
	}

    StringWriter writer = new StringWriter();
    writer.write(launchCommand(args));
    return new ArrayList<>(Arrays.asList(writer.toString().split("\\n")));
}
 
Example #5
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Map<String, ObjectId> getHeadRev(String url) throws GitException, InterruptedException {
    ArgumentListBuilder args = new ArgumentListBuilder("ls-remote");
    args.add("-h");
    addCheckedRemoteUrl(args, url);

    StandardCredentials cred = credentials.get(url);
    if (cred == null) cred = defaultCredentials;

    String result = launchCommandWithCredentials(args, null, cred, url);

    Map<String, ObjectId> heads = new HashMap<>();
    String[] lines = result.split("\n");
    for (String line : lines) {
        if (line.length() >= 41) {
            heads.put(line.substring(41), ObjectId.fromString(line.substring(0, 40)));
        } else {
            listener.getLogger().println("Unexpected ls-remote output line '" + line + "'");
        }
    }
    return heads;
}
 
Example #6
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void reset(boolean hard) throws GitException, InterruptedException {
	try {
		validateRevision("HEAD");
	} catch (GitException e) {
		listener.getLogger().println("No valid HEAD. Skipping the resetting");
		return;
	}
    listener.getLogger().println("Resetting working tree");

    ArgumentListBuilder args = new ArgumentListBuilder();
    args.add("reset");
    if (hard) {
        args.add("--hard");
    }

    launchCommand(args);
}
 
Example #7
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public String getRemoteUrl(String name, String GIT_DIR) throws GitException, InterruptedException {
    final String remoteNameUrl = "remote." + name + ".url";
    String result;
    if (StringUtils.isBlank(GIT_DIR)) { /* Match JGitAPIImpl */
        result = launchCommand("config", "--get", remoteNameUrl);
    } else {
        final String dirArg = "--git-dir=" + GIT_DIR;
        result = launchCommand(dirArg, "config", "--get", remoteNameUrl);
    }
    String line = firstLine(result);
    if (line == null)
        throw new GitException("No output from git config check for " + GIT_DIR);
    return line.trim();
}
 
Example #8
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Set<String> getTagNames(String tagPattern) throws GitException {
    try {
        ArgumentListBuilder args = new ArgumentListBuilder();
        args.add("tag", "-l", tagPattern);

        String result = launchCommandIn(args, workspace);

        Set<String> tags = new HashSet<>();
        BufferedReader rdr = new BufferedReader(new StringReader(result));
        String tag;
        while ((tag = rdr.readLine()) != null) {
            // Add the SHA1
            tags.add(tag);
        }
        return tags;
    } catch (GitException | IOException | InterruptedException e) {
        throw new GitException("Error retrieving tag names", e);
    }
}
 
Example #9
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public List<IndexEntry> getSubmodules(String treeIsh) throws GitException {
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         RevWalk w = new RevWalk(or)) {
        List<IndexEntry> r = new ArrayList<>();

        RevTree t = w.parseTree(repo.resolve(treeIsh));
        SubmoduleWalk walk = new SubmoduleWalk(repo);
        walk.setTree(t);
        walk.setRootTree(t);
        while (walk.next()) {
            r.add(new IndexEntry(walk));
        }

        return r;
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #10
Source File: GitCommandsExecutorTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Test
public void lastCommandFails() throws Exception {
    List<Callable<String>> commands = asList(
            successfulCommand("some value"),
            successfulCommand("some value"),
            erroneousCommand(new RuntimeException("some error"))
    );

    try {
        new GitCommandsExecutor(threads, listener).invokeAll(commands);
        fail("Expected an exception but none was thrown");
    } catch (Exception e) {
        assertThat(e, instanceOf(GitException.class));
        assertThat(e.getMessage(), is("java.lang.RuntimeException: some error"));
        assertThat(e.getCause(), instanceOf(RuntimeException.class));
    }

    for (Callable<String> command : commands) {
        verify(command).call();
    }
}
 
Example #11
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
   @Override
   public Set<String> getRefNames(String refPrefix) throws GitException, InterruptedException {
if (refPrefix.isEmpty()) {
    refPrefix = RefDatabase.ALL;
} else {
    refPrefix = refPrefix.replace(' ', '_');
}
try (Repository repo = getRepository()) {
    List<Ref> refList = repo.getRefDatabase().getRefsByPrefix(refPrefix);
    Set<String> refs = new HashSet<>(refList.size());
    for (Ref ref : refList) {
	refs.add(ref.getName());
    }
    return refs;
} catch (IOException e) {
    throw new GitException("Error retrieving refs with prefix " + refPrefix, e);
}
   }
 
Example #12
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void addNote(String note, String namespace) throws GitException {
    try (Repository repo = getRepository()) {
        ObjectId head = repo.resolve(HEAD); // commit to put a note on

        AddNoteCommand cmd = git(repo).notesAdd();
        cmd.setMessage(normalizeNote(note));
        cmd.setNotesRef(qualifyNotesNamespace(namespace));
        try (ObjectReader or = repo.newObjectReader();
             RevWalk walk = new RevWalk(or)) {
            cmd.setObjectId(walk.parseAny(head));
            cmd.call();
        }
    } catch (GitAPIException | IOException e) {
        throw new GitException(e);
    }
}
 
Example #13
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public List<IndexEntry> lsTree(String treeIsh, boolean recursive) throws GitException, InterruptedException {
    List<IndexEntry> entries = new ArrayList<>();
    String result = launchCommand("ls-tree", recursive?"-r":null, treeIsh);

    BufferedReader rdr = new BufferedReader(new StringReader(result));
    String line;
    try {
        while ((line = rdr.readLine()) != null) {
            String[] entry = line.split("\\s+");
            entries.add(new IndexEntry(entry[0], entry[1], entry[2],
                                       entry[3]));
        }
    } catch (IOException e) {
        throw new GitException("Error parsing ls tree", e);
    }

    return entries;
}
 
Example #14
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void addRemoteUrl(String name, String url) throws GitException, InterruptedException {
    try (Repository repo = getRepository()) {
        StoredConfig config = repo.getConfig();

        List<String> urls = new ArrayList<>();
        urls.addAll(Arrays.asList(config.getStringList("remote", name, "url")));
        urls.add(url);

        config.setStringList("remote", name, "url", urls);
        config.save();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #15
Source File: GitClientTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Deprecated
@Test
public void testIsBareRepositoryWorkingNull() throws IOException, InterruptedException {
    gitClient.init_().workspace(repoRoot.getAbsolutePath()).bare(true).execute();
    IGitAPI gitAPI = (IGitAPI) gitClient;
    FilePath gitClientFilePath = gitClient.getWorkTree();
    gitClientFilePath.createTextTempFile("aPre", ".txt", "file contents");
    gitClient.add(".");
    gitClient.commit("Not-a-bare-repository-working-null");
    try {
        assertFalse("null is a bare repository", gitAPI.isBareRepository(null));
        fail("Did not throw expected exception");
    } catch (GitException ge) {
        assertExceptionMessageContains(ge, "not a git repository");
    }
}
 
Example #16
Source File: RemoteGitImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
public void execute() throws GitException, InterruptedException {
    try {
        channel.call(new GitCommandMasterToSlaveCallable());
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #17
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void submoduleClean(boolean recursive) throws GitException {
    try {
        for (JGitAPIImpl sub : submodules()) {
            sub.clean();
            if (recursive) {
                sub.submoduleClean(true);
            }
        }
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #18
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testAutocreateFailsOnMultipleMatchingOrigins() throws Exception {
    File repoRootTemp = tempFolder.newFolder();
    GitClient gitClientTemp = Git.with(TaskListener.NULL, new EnvVars()).in(repoRootTemp).using(gitImplName).getClient();
    gitClientTemp.init();
    FilePath gitClientFilePath = gitClientTemp.getWorkTree();
    FilePath gitClientTempFile = gitClientFilePath.createTextTempFile("aPre", ".txt", "file contents");
    gitClientTemp.add(".");
    gitClientTemp.commit("Added " + gitClientTempFile.toURI().toString());
    gitClient.clone_().url("file://" + repoRootTemp.getPath()).execute();
    final URIish remote = new URIish(Constants.DEFAULT_REMOTE_NAME);

    try ( // add second remote
          FileRepository repo = new FileRepository(new File(repoRoot, ".git"))) {
        StoredConfig config = repo.getConfig();
        config.setString("remote", "upstream", "url", "file://" + repoRootTemp.getPath());
        config.setString("remote", "upstream", "fetch", "+refs/heads/*:refs/remotes/upstream/*");
        config.save();
    }

    // fill both remote branches
    List<RefSpec> refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/origin/*"));
    gitClient.fetch_().from(remote, refspecs).execute();
    refspecs = Collections.singletonList(new RefSpec(
            "refs/heads/*:refs/remotes/upstream/*"));
    gitClient.fetch_().from(remote, refspecs).execute();

    // checkout will fail
    try {
        gitClient.checkout().ref(Constants.MASTER).execute();
    } catch (GitException e) {
        // expected
        Set<String> refNames = gitClient.getRefNames("refs/heads/");
        assertFalse("RefNames will not contain master", refNames.contains("refs/heads/master"));
    }

}
 
Example #19
Source File: GitClientSecurityTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("SECURITY-1534")
public void testGetRemoteSymbolicReferences_SECURITY_1534() throws Exception {
    assumeTrue(CLI_GIT_SUPPORTS_SYMREF);
    String expectedMessage = enableRemoteCheckUrl ? "Invalid remote URL: " + badRemoteUrl : badRemoteUrl.trim();
    GitException e = assertThrows(GitException.class,
                                  () -> {
                                      gitClient.getRemoteSymbolicReferences(badRemoteUrl, "master");
                                  });
    assertThat(e.getMessage(), containsString(expectedMessage));
}
 
Example #20
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * submoduleSync.
 *
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 * @throws java.lang.InterruptedException if interrupted.
 */
@Deprecated
@Override
public void submoduleSync() throws GitException, InterruptedException {
    try (Repository repo = getRepository()) {
        git(repo).submoduleSync().call();
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #21
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * submoduleInit.
 *
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 * @throws java.lang.InterruptedException if interrupted.
 */
@Deprecated
@Override
public void submoduleInit() throws GitException, InterruptedException {
    try (Repository repo = getRepository()) {
        git(repo).submoduleInit().call();
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #22
Source File: LegacyCompatibleGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
public void clone(RemoteConfig rc, boolean useShallowClone) throws GitException, InterruptedException {
    // Assume only 1 URL for this repository
    final String source = rc.getURIs().get(0).toPrivateString();
    clone(source, rc.getName(), useShallowClone, null);
}
 
Example #23
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void addSubmodule(String remoteURL, String subdir) throws GitException {
    try (Repository repo = getRepository()) {
        git(repo).submoduleAdd().setPath(subdir).setURI(remoteURL).call();
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #24
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
@SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
                              "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE" },
                    justification = "Java 11 spotbugs error and JGit interaction with spotbugs")
public void setRemoteUrl(String name, String url, String GIT_DIR) throws GitException, InterruptedException {
    try (Repository repo = new RepositoryBuilder().setGitDir(new File(GIT_DIR)).build()) {
        StoredConfig config = repo.getConfig();
        config.setString("remote", name, "url", url);
        config.save();
    } catch (IOException ioe) {
        throw new GitException(ioe);
    }
}
 
Example #25
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Set<GitObject> getTags() throws GitException, InterruptedException {
    Set<GitObject> peeledTags = new HashSet<>();
    Set<String> tagNames = new HashSet<>();
    try (Repository repo = getRepository()) {
        Map<String, Ref> tagsRead = repo.getTags();
        for (Map.Entry<String, Ref> entry : tagsRead.entrySet()) {
            /* Prefer peeled ref if available (for tag commit), otherwise take first tag reference seen */
            String tagName = entry.getKey();
            Ref tagRef = entry.getValue();
            if (!tagRef.isPeeled()) {
                Ref peeledRef = repo.peel(tagRef);
                if (peeledRef.getPeeledObjectId() != null) {
                    tagRef = peeledRef; // Use peeled ref instead of annotated ref
                }
            }
            /* Packed lightweight (non-annotated) tags can wind up peeled with no peeled obj ID */
            if (tagRef.isPeeled() && tagRef.getPeeledObjectId() != null) {
                peeledTags.add(new GitObject(tagName, tagRef.getPeeledObjectId()));
            } else if (!tagNames.contains(tagName)) {
                peeledTags.add(new GitObject(tagName, tagRef.getObjectId()));
            }
            tagNames.add(tagName);
        }
    }
    return peeledTags;
}
 
Example #26
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * clean.
 *
 * @param cleanSubmodule flag to add extra -f
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 */
@Override
public void clean(boolean cleanSubmodule) throws GitException {
    try (Repository repo = getRepository()) {
        Git git = git(repo);
        git.reset().setMode(HARD).call();
        git.clean().setCleanDirectories(true).setIgnore(false).setForce(cleanSubmodule).call();
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #27
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * hasGitRepo.
 *
 * @return true if this workspace has a git repository
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 * @throws java.lang.InterruptedException if interrupted.
 */
@Override
public boolean hasGitRepo() throws GitException, InterruptedException {
    if (hasGitRepo(".git")) {
        // Check if this is a valid git repo with --is-inside-work-tree
        try {
            launchCommand("rev-parse", "--is-inside-work-tree");
        } catch (Exception ex) {
            ex.printStackTrace(listener.error("Workspace has a .git repository, but it appears to be corrupt."));
            return false;
        }
        return true;
    }
    return false;
}
 
Example #28
Source File: GitClientSecurityTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("SECURITY-1534")
public void testGetHeadRev_String_SECURITY_1534() throws Exception {
    String expectedMessage = enableRemoteCheckUrl ? "Invalid remote URL: " + badRemoteUrl : badRemoteUrl.trim();
    GitException e = assertThrows(GitException.class,
                                  () -> {
                                      gitClient.getHeadRev(badRemoteUrl);
                                  });
    assertThat(e.getMessage(), containsString(expectedMessage));
}
 
Example #29
Source File: PushSimpleTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void pushBadURIThrows() throws IOException, GitException, InterruptedException, URISyntaxException {
    checkoutBranchAndCommitFile();
    URIish bad = new URIish(bareURI.toString() + "-bad");
    assertThrows(GitException.class,
                 () -> {
                     workingGitClient.push().to(bad).ref(refSpec).execute();
                 });
}
 
Example #30
Source File: MergeCommandTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testRecursiveTheirsStrategy() throws GitException, InterruptedException, FileNotFoundException, IOException {
    mergeCmd.setStrategy(MergeCommand.Strategy.RECURSIVE_THEIRS).setRevisionToMerge(commit1Branch2).execute();
    assertTrue("branch 2 commit 1 not on master branch after merge", git.revList("master").contains(commit1Branch2));
    assertTrue("README.adoc is missing on master", readme.exists());
    try(FileReader reader = new FileReader(readme); BufferedReader br = new BufferedReader(reader)) {
        assertTrue("README.adoc does not contain expected content", br.readLine().startsWith(BRANCH_2_README_CONTENT));
    }
}