下面列出了hudson.model.UserProperty#org.jenkinsci.plugins.gitclient.Git 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private GitClient createGitClient(Job job) throws IOException, InterruptedException {
EnvVars env = Objects.requireNonNull(Objects.requireNonNull(Jenkins.getInstance()).toComputer()).getEnvironment();
Git git = Git.with(TaskListener.NULL, env);
GitClient c = git.getClient();
List<StandardUsernameCredentials> urlCredentials = CredentialsProvider.lookupCredentials(
StandardUsernameCredentials.class, job, ACL.SYSTEM, URIRequirementBuilder.fromUri(remoteURL).build()
);
CredentialsMatcher ucMatcher = CredentialsMatchers.withId(credentialsId);
CredentialsMatcher idMatcher = CredentialsMatchers.allOf(ucMatcher, GitClient.CREDENTIALS_MATCHER);
StandardUsernameCredentials credentials = CredentialsMatchers.firstOrNull(urlCredentials, idMatcher);
if (credentials != null) {
c.addCredentials(remoteURL, credentials);
if (job != null && job.getLastBuild() != null) {
CredentialsProvider.track(job.getLastBuild(), credentials);
}
}
return c;
}
public static void fetch(final Repository repo, final StandardCredentials credential) {
try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
FetchCommand fetchCommand = git.fetch();
addCredential(repo, fetchCommand, credential);
fetchCommand.setRemote("origin")
.setRemoveDeletedRefs(true)
.setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*"))
.call();
} catch (GitAPIException ex) {
if (ex.getMessage().contains("Auth fail")) {
throw new ServiceException.UnauthorizedException("Not authorized", ex);
}
throw new RuntimeException(ex);
}
}
public TestGitRepo(String name, File tmpDir, TaskListener listener) throws IOException, InterruptedException {
this.name = name;
this.listener = listener;
envVars = new EnvVars();
gitDir = tmpDir;
User john = User.get(johnDoe.getName(), true);
UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress());
john.addProperty(johnsMailerProperty);
User jane = User.get(janeDoe.getName(), true);
UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress());
jane.addProperty(janesMailerProperty);
// initialize the git interface.
gitDirPath = new FilePath(gitDir);
git = Git.with(listener, envVars).in(gitDir).getClient();
// finally: initialize the repo
git.init();
}
/**
* We want to create a temporary local git repository after each iteration of the benchmark, works just like
* "before" and "after" JUnit annotations.
*/
@Setup(Level.Iteration)
public void doSetup() throws Exception {
tmp.before();
gitDir = tmp.newFolder();
gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using(gitExe).getClient();
// fetching all branches
refSpecs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
// initialize the test folder for git fetch
gitClient.init();
System.out.println("Do Setup for: " + gitExe);
}
/**
* Attempts to push to a non-existent branch to validate the user actually has push access
*
* @param repo local repository
* @param remoteUrl git repo url
* @param credential credential to use when accessing git
*/
public static void validatePushAccess(@Nonnull Repository repo, @Nonnull String remoteUrl, @Nullable StandardCredentials credential) throws GitException {
try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
// we need to perform an actual push, so we try a deletion of a very-unlikely-to-exist branch
// which needs to have push permissions in order to get a 'branch not found' message
String pushSpec = ":this-branch-is-only-to-test-if-jenkins-has-push-access";
PushCommand pushCommand = git.push();
addCredential(repo, pushCommand, credential);
Iterable<PushResult> resultIterable = pushCommand
.setRefSpecs(new RefSpec(pushSpec))
.setRemote(remoteUrl)
.setDryRun(true) // we only want to test
.call();
PushResult result = resultIterable.iterator().next();
if (result.getRemoteUpdates().isEmpty()) {
System.out.println("No remote updates occurred");
} else {
for (RemoteRefUpdate update : result.getRemoteUpdates()) {
if (!RemoteRefUpdate.Status.NON_EXISTING.equals(update.getStatus()) && !RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
throw new ServiceException.UnexpectedErrorException("Expected non-existent ref but got: " + update.getStatus().name() + ": " + update.getMessage());
}
}
}
} catch (GitAPIException e) {
if (e.getMessage().toLowerCase().contains("auth")) {
throw new ServiceException.UnauthorizedException(e.getMessage(), e);
}
throw new ServiceException.UnexpectedErrorException("Unable to access and push to: " + remoteUrl + " - " + e.getMessage(), e);
}
}
/**
* Determines if the repository is using an SSH URL
* @param repo repository to
* @return true if there appears to be an SSH style remote URL
*/
private static boolean isSshUrl(Repository repo) {
try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
return isSshUrl(git.remoteList().call().get(0).getURIs().get(0).toString());
} catch (IndexOutOfBoundsException | GitAPIException e) {
return false;
}
}
public static void push(String remoteUrl, Repository repo, StandardCredentials credential, String localBranchRef, String remoteBranchRef) {
try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
String pushSpec = "+" + localBranchRef + ":" + remoteBranchRef;
PushCommand pushCommand = git.push();
addCredential(repo, pushCommand, credential);
Iterable<PushResult> resultIterable = pushCommand
.setRefSpecs(new RefSpec(pushSpec))
.setRemote(remoteUrl)
.call();
PushResult result = resultIterable.iterator().next();
if (result.getRemoteUpdates().isEmpty()) {
throw new RuntimeException("No remote updates occurred");
} else {
for (RemoteRefUpdate update : result.getRemoteUpdates()) {
if (!RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
throw new ServiceException.UnexpectedErrorException("Remote update failed: " + update.getStatus().name() + ": " + update.getMessage());
}
}
}
} catch (GitAPIException e) {
if (e.getMessage().toLowerCase().contains("auth")) {
throw new ServiceException.UnauthorizedException(e.getMessage(), e);
}
throw new ServiceException.UnexpectedErrorException("Unable to save and push to: " + remoteUrl + " - " + e.getMessage(), e);
}
}
public GitConfig getGitConfig() throws AbortException {
try {
GitClient client = Git.with(listener, env).in(workspace).getClient();
return client.withRepository(new GitInfoCallback(listener));
} catch (Exception e) {
throw new AbortException("Error getting git config " + e);
}
}
protected String getHeadRevision(AbstractBuild build, final String branch) throws IOException, InterruptedException {
return build.getWorkspace().act(new MasterToSlaveFileCallable<String>() {
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
try {
ObjectId oid = Git.with(null, null).in(f).getClient().getRepository().resolve("refs/heads/" + branch);
return oid.name();
} catch (GitException e) {
throw new RuntimeException(e);
}
}
});
}
/** {@inheritDoc} */
public void commit(String message, PersonIdent author, PersonIdent committer) throws GitException, InterruptedException {
if (Git.USE_CLI) {
super.setAuthor(author);
super.setCommitter(committer);
super.commit(message);
} else {
jgit.setAuthor(author);
jgit.setCommitter(committer);
jgit.commit(message);
}
}
@Test
public void initCliImplThrowsGitException() throws GitAPIException, IOException, InterruptedException {
String fileName = isWindows() ? "\\\\badserver\\badshare\\bad\\dir" : "/this/is/a/bad/dir";
final File badDirectory = new File(fileName);
assumeFalse("running as root?", new File("/").canWrite());
GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(badDirectory).using("git").getClient();
assertNotNull(defaultClient);
assertThrows(GitException.class,
() -> {
defaultClient.init_().workspace(badDirectory.getAbsolutePath()).execute();
});
}
@Test
public void initJGitImplThrowsGitException() throws GitAPIException, IOException, InterruptedException {
String fileName = isWindows() ? "\\\\badserver\\badshare\\bad\\dir" : "/this/is/a/bad/dir";
final File badDirectory = new File(fileName);
assumeFalse("running as root?", new File("/").canWrite());
GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(badDirectory).using("jgit").getClient();
assertNotNull(defaultClient);
JGitInternalException e = assertThrows(JGitInternalException.class,
() -> {
defaultClient.init_().workspace(badDirectory.getAbsolutePath()).execute();
});
assertThat(e.getCause(), isA(IOException.class));
}
@Test
public void initCliImplCollisionThrowsGitException() throws GitAPIException, IOException, InterruptedException {
File dir = folder.getRoot();
File dotGit = folder.newFile(".git");
Files.write(dotGit.toPath(), "file named .git".getBytes("UTF-8"), APPEND);
GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(dir).using("git").getClient();
assertThrows(GitException.class,
() -> {
defaultClient.init_().workspace(dir.getAbsolutePath()).execute();
});
}
@Test
public void initJGitImplCollisionThrowsGitException() throws GitAPIException, IOException, InterruptedException {
File dir = folder.getRoot();
File dotGit = folder.newFile(".git");
Files.write(dotGit.toPath(), "file named .git".getBytes("UTF-8"), APPEND);
GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(dir).using("jgit").getClient();
JGitInternalException e = assertThrows(JGitInternalException.class,
() -> {
defaultClient.init_().workspace(dir.getAbsolutePath()).execute();
});
assertThat(e.getCause(), isA(IOException.class));
}
/**
* We want to create a temporary local git repository after each iteration of the benchmark, similar to
* "before" and "after" JUnit annotations.
*/
@Setup(Level.Iteration)
public void doSetup() throws Exception {
tmp.before();
gitDir = tmp.newFolder();
gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using(gitExe).getClient();
System.out.println("Do Setup");
}
private File cloneUpstreamRepositoryLocally(File parentDir, String repoUrl) throws Exception {
String repoName = repoUrl.split("/")[repoUrl.split("/").length - 1];
File gitRepoDir = new File(parentDir, repoName);
gitRepoDir.mkdir();
GitClient cloningGitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitRepoDir).using("git").getClient();
cloningGitClient.clone_().url(repoUrl).execute();
// assertTrue("Unable to create git repo", gitRepoDir.exists());
return gitRepoDir;
}
GitClient cloneRepo() throws InterruptedException, IOException {
EnvVars environment = new EnvVars();
TaskListener taskListener = new LogTaskListener(Logger.getAnonymousLogger(), Level.ALL);
String gitExe = gitTool.getGitExe();
GitClient git = Git.with(taskListener, environment)
.in(repositoryPath)
.using(gitExe)
.getClient();
git.addCredentials(gitSource.getRemote(), getCredential());
try {
git.clone(gitSource.getRemote(), "origin", true, null);
log.fine("Repository " + gitSource.getRemote() + " cloned to: " + repositoryPath.getCanonicalPath());
} catch(GitException e) {
// check if this is an empty repository
boolean isEmptyRepo = false;
try {
if (git.getRemoteReferences(gitSource.getRemote(), null, true, false).isEmpty()) {
isEmptyRepo = true;
}
} catch(GitException ge) {
// *sigh* @ this necessary hack; {@link org.jenkinsci.plugins.gitclient.CliGitAPIImpl#getRemoteReferences}
if ("unexpected ls-remote output ".equals(ge.getMessage())) { // blank line, command succeeded
isEmptyRepo = true;
}
// ignore other reasons
}
if(isEmptyRepo) {
git.init();
git.addRemoteUrl("origin", gitSource.getRemote());
log.fine("Repository " + gitSource.getRemote() + " not found, created new to: " + repositoryPath.getCanonicalPath());
} else {
throw e;
}
}
return git;
}
/** {@inheritDoc} */
public void add(String filePattern) throws GitException, InterruptedException {
if (Git.USE_CLI) super.add(filePattern); else jgit.add(filePattern);
}
/** {@inheritDoc} */
public String getRemoteUrl(String name) throws GitException, InterruptedException {
return Git.USE_CLI ? super.getRemoteUrl(name) : jgit.getRemoteUrl(name);
}
/** {@inheritDoc} */
public void push(String remoteName, String refspec) throws GitException, InterruptedException {
if (Git.USE_CLI) super.push(remoteName, refspec); else jgit.push(remoteName, refspec);
}
/** {@inheritDoc} */
public String getTagMessage(String tagName) throws GitException, InterruptedException {
return Git.USE_CLI ? super.getTagMessage(tagName) : jgit.getTagMessage(tagName);
}
/** {@inheritDoc} */
public GitClient subGit(String subdir) {
return Git.USE_CLI ? super.subGit(subdir) : jgit.subGit(subdir);
}
/** {@inheritDoc} */
public void setRemoteUrl(String name, String url) throws GitException, InterruptedException {
if (Git.USE_CLI) super.setRemoteUrl(name, url); else jgit.setRemoteUrl(name, url);
}
/** {@inheritDoc} */
public Set<Branch> getBranches() throws GitException, InterruptedException {
return Git.USE_CLI ? super.getBranches() : jgit.getBranches();
}
/** {@inheritDoc} */
public Set<Branch> getRemoteBranches() throws GitException, InterruptedException {
return Git.USE_CLI ? super.getRemoteBranches() : jgit.getRemoteBranches();
}
/** {@inheritDoc} */
public void init() throws GitException, InterruptedException {
if (Git.USE_CLI) super.init(); else jgit.init();
}
/** {@inheritDoc} */
public void deleteBranch(String name) throws GitException, InterruptedException {
if (Git.USE_CLI) super.deleteBranch(name); else jgit.deleteBranch(name);
}
/** {@inheritDoc} */
public void checkout(String ref, String branch) throws GitException, InterruptedException {
if (Git.USE_CLI) super.checkout().ref(ref).branch(branch).execute(); else jgit.checkout().ref(ref).branch(branch).execute();
}
/** {@inheritDoc} */
public boolean hasGitRepo() throws GitException, InterruptedException {
return Git.USE_CLI ? super.hasGitRepo() : jgit.hasGitRepo();
}
/** {@inheritDoc} */
public boolean isCommitInRepo(ObjectId commit) throws GitException, InterruptedException {
return Git.USE_CLI ? super.isCommitInRepo(commit) : jgit.isCommitInRepo(commit);
}