Clone PR using java program or JGIT - java

I wanted to clone a specific pull request using java JGit API. Does anyone have an idea about it? Or any alternate way to clone Pull request using java program.
Let's consider below is the code to checkout or clone PR from GitHub,
1: git clone https://github.com/deepak-kumbhar/spring-boot-logging-example.git
2. cd PROJECT_NAME
3. git fetch origin pull/1/head:pr-1 (Where 1 is number or PR)
4. git checkout pr-1 (To activate the PR)
The same functionality I want using JGit. Does anyone have an idea about it?
Thanks in advance!

You can do this as described at https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/checking-out-pull-requests-locally
The basic steps for pulling PR #6 from https://github.com/github/testrepo/pull/6/commits are
System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);
try (Git result = Git.cloneRepository()
.setURI(REMOTE_URL)
.setDirectory(localPath)
.setProgressMonitor(new SimpleProgressMonitor())
.call()) {
// Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
System.out.println("Having repository: " + result.getRepository().getDirectory());
FetchResult fetchResult = result.fetch()
.setRemote(REMOTE_URL)
.setRefSpecs("+refs/pull/6/head:pr_6")
.call();
System.out.println("Result when fetching the PR: " + fetchResult.getMessages());
Ref checkoutRef = result.checkout()
.setName("pr_6")
.call();
System.out.println("Checked out PR, now printing log, it should include two commits from the PR on top");
Iterable<RevCommit> logs = result.log()
.call();
for (RevCommit rev : logs) {
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
}
}
See the ready-to-run snippet at https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/CheckoutGitHubPullRequest.java

Related

How to use github java API (org.eclipse.egit.github.*) to search for a given commit hash

It is possible to receive details regarding a given commit from calling github Search API found in here with providing the relevant commit hash, Now I need to get the same response by using github java API (org.eclipse.egit.github.*) which can be found in here. According to their documentation of the version 2.1.5 found in here, there is no method in CommitService class to get commit information by providing only the commit hash . Is there a workaround to reach them? Thanks in advance
You can use the CommitService.getCommit(IRepositoryIdProvider, String) method, just feed in one more argument, the repository where the commit will be searched. For example,
GitHubClient client = new GitHubClient(server).setCredentials(login, token);
RepositoryService repoService = new RepositoryService(client);
// If you know which repository to search (you know the owner and repo name)
Repository repository = repoService.getRepository(owner, repoName);
CommitService commitService = new CommitService(client)
Commit commit1 = commitService.getCommit(repository, sha).getCommit();
System.out.println("Author: " + commit1.getAuthor().getName());
System.out.println("Message: " + commit1.getMessage());
System.out.println("URL: " + commit1.getUrl());
Or you may just loop through each repository returned from the RepositoryService.getRepositories() method, if you don't know which repository to search. For example,
List<Repository> repositories = repoService.getRepositories();
Commit commit2 = null;
for (Repository repo : repositories) {
try {
commit2 = commitService.getCommit(repo, sha).getCommit();
System.out.println("Repo: " + repo.getName());
System.out.println("Author: " + commit2.getAuthor().getName());
System.out.println("Message: " + commit2.getMessage());
System.out.println("URL: " + commit2.getUrl());
break;
} catch (RequestException re) {
if (re.getMessage().endsWith("Not Found (404)")) {
continue;
} else {
throw re;
}
}
}

No query defined for that name [getAuditTaskById]

When I tried to start a task using taskService.start(task.getId(), "krisv");, I get No query defined for that name [getAuditTaskById]. The bpmn file is very similar to the Evaluation.bpmn file. My current version of jbpmn is 6.2.
The code snippet is the following:
List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("krisv", "en-UK");
if (tasks.size() > 0) {
TaskSummary task = tasks.get(0);
System.out.println("Task id: " + task.getId());
System.out.println("'krisv' completing task " + task.getName() + ": " + task.getDescription());
System.out.println("Task status: " + task.getStatus().name());
System.out.println("Potential owners: " + task.getActualOwner().getId());
taskService.start(task.getId(), "krisv");
Map<String, Object> results = new HashMap<String, Object>();
results.put("performance", "exceeding");
taskService.complete(task.getId(), "krisv", results);
System.out.println("Completed task");
} else {
System.out.println("No tasks!");
}
The code above is almost a replicate of the ProcessTest.java file in the sample folder. The ProcessTest.java allows the completion of the tasks, but the exact same code doesn't in my custom java file.
Also, the current task's status is "reserved" if that is of any help. Thanks!
The query is defined in the jbpm-human-task-audit-audit jar, you need that on your classpath:
https://github.com/droolsjbpm/jbpm/blob/6.2.0.Final/jbpm-human-task/jbpm-human-task-audit/src/main/resources/META-INF/TaskAuditorm.xml#L40
And you need to make sure this file is referenced in your persistence.xml, like for example here:
https://github.com/droolsjbpm/jbpm/blob/6.2.0.Final/jbpm-test/src/main/resources/META-INF/persistence.xml#L15

SVN log using SVNKit

I'm sure this question will be silly or annoying on multiple levels....
I am using SVNKit in Java.
I want to get the list of files committed in a particular commit. I have the release ID. Normally I would run something like
svn log url/to/repository -qv -r12345
And I would get the list of commands as normal.
I can't puzzle out how to do a similar thing in SVNKit. Any tips? :)
final SvnOperationFactory svnOperationFactory = new SvnOperationFactory();
final SvnLog log = svnOperationFactory.createLog();
log.setSingleTarget(SvnTarget.fromURL(url));
log.addRange(SvnRevisionRange.create(SVNRevision.create(12345), SVNRevision.create(12345)));
log.setDiscoverChangedPaths(true);
final SVNLogEntry logEntry = log.run();
final Map<String,SVNLogEntryPath> changedPaths = logEntry.getChangedPaths();
for (Map.Entry<String, SVNLogEntryPath> entry : changedPaths.entrySet()) {
final SVNLogEntryPath svnLogEntryPath = entry.getValue();
System.out.println(svnLogEntryPath.getType() + " " + svnLogEntryPath.getPath() +
(svnLogEntryPath.getCopyPath() == null ?
"" : (" from " + svnLogEntryPath.getCopyPath() + ":" + svnLogEntryPath.getCopyRevision())));
}
If you want to run one log request for a revision range, you should use log.setReceiver() call with your receiver implemetation.

Jenkins/Hudson CLI API to modify the node labels using Groovy

Does anyone know how to modify the Jenkins/Hudson node labels in a non-manually way? I mean, thorough an API like the CLI API that this tool offers (without restarting Jenkins/Hudson of course).
My guess is that the best option is using a Groovy script to enter into the Jenkins/Hudson guts. Executing something like:
java -jar -s HUDSON_URL:8080 groovy /path/to/groovy.groovy
Being the content of that script something like:
for (aSlave in hudson.model.Hudson.instance.slaves) {
labels = aSlave.getAssignedLabels()
println labels
**aSlave.setLabel("blabla")** // this method doesn't exist, is there any other way???
}
Thanks in advance!
Victor
Note: the other answers are a bit old, so it could be that the API has appeared since then.
Node labels are accessed in the API as a single string, just like in the Configure screen.
To read and write labels: Node.getLabelString() and Node.setLabelString(String).
Note that you can get the effective labels as well via: Node.getAssignedLabels(), which returns a Collection of LabelAtom that includes dynamically computed labels such as the 'self-label' (representing the node name itself).
Last, these methods on the Node class are directly accessible from the slave objects also, e.g. as a System Groovy Script:
hudson = hudson.model.Hudson.instance
hudson.slaves.findAll { it.nodeName.equals("slave4") }.each { slave ->
print "Slave $slave.nodeName : Labels: $slave.labelString"
slave.labelString = slave.labelString + " " + "offline"
println " --> New labels: $slave.labelString"
}
hudson.save()
I've found a way to do this using the Groovy Postbuild Plugin.
I have a Jenkins job that takes a few parameters (NodeToUpdate, LabelName, DesiredState) and executes this content in the Groovy Postbuild Plugin:
nodeName = manager.envVars['NodeToUpdate']
labelName = manager.envVars['LabelName']
set = manager.envVars['DesiredState']
for (node in jenkins.model.Jenkins.instance.nodes) {
if (node.getNodeName().equals(nodeName)) {
manager.listener.logger.println("Found node to update: " + nodeName)
oldLabelString = node.getLabelString()
if (set.equals('true')) {
if (!oldLabelString.contains(labelName)) {
manager.listener.logger.println("Adding label '" + labelName + "' from node " + nodeName);
newLabelString = oldLabelString + " " + labelName
node.setLabelString(newLabelString)
node.save()
} else {
manager.listener.logger.println("Label '" + labelName + "' already exists on node " + nodeName)
}
}
else {
if (oldLabelString.contains(labelName)) {
manager.listener.logger.println("Removing label '" + labelName + "' from node " + nodeName)
newLabelString = oldLabelString.replaceAll(labelName, "")
node.setLabelString(newLabelString)
node.save()
} else {
manager.listener.logger.println("Label '" + labelName + "' doesn't exist on node " + nodeName)
}
}
}
}
I've not seen a way yet to change the slave label either.
I've taken to editing the main config.xml file and issuing a reload from the CLI.
This has it's own problems though - any jobs currently running are lost until the next jenkins restart - see https://issues.jenkins-ci.org/browse/JENKINS-3265

Obtain a share UpdateKey from LinkedIn using LinkedIn J and getNetworkUpdates() with Coldfusion

Using the "Network Updates API" example at the following link I am able to post network updates with no problem using client.postNetworkUpdate(updateText).
http://code.google.com/p/linkedin-j/wiki/GettingStarted
So posting works great.. However posting an update does not return an "UpdateKey" which is used to retrieve stats for post itself such as comments, likes, etc. Without the UpdateKey I cannot retrieve stats. So what I would like to do is post, then retrieve the last post using the getNetworkUpdates() function, and in that retrieval will be the UpdateKey that I need to use later to retrieve stats. Here's a sample script in Java on how to get network updates, but I need to do this in Coldfusion instead of Java.
Network network = client.getNetworkUpdates(EnumSet.of(NetworkUpdateType.STATUS_UPDATE));
System.out.println("Total updates fetched:" + network.getUpdates().getTotal());
for (Update update : network.getUpdates().getUpdateList()) {
System.out.println("-------------------------------");
System.out.println(update.getUpdateKey() + ":" + update.getUpdateContent().getPerson().getFirstName() + " " + update.getUpdateContent().getPerson().getLastName() + "->" + update.getUpdateContent().getPerson().getCurrentStatus());
if (update.getUpdateComments() != null) {
System.out.println("Total comments fetched:" + update.getUpdateComments().getTotal());
for (UpdateComment comment : update.getUpdateComments().getUpdateCommentList()) {
System.out.println(comment.getPerson().getFirstName() + " " + comment.getPerson().getLastName() + "->" + comment.getComment());
}
}
}
Anyone have any thoughts on how to accomplish this using Coldfusion?
Thanks
I have not used that api, but I am guessing you could use the first two lines to grab the number of updates. Then use the overloaded client.getNetworkUpdates(start, end) method to retrieve the last update and obtain its key.
Totally untested, but something along these lines:
<cfscript>
...
// not sure about accessing the STATUS_UPDATE enum. One of these should work:
// method 1
STATUS_UPDATE = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType$STATUS_UPDATE");
// method 2
NetworkUpdateType = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType");
STATUS_UPDATE = NetworkUpdateType.valueOf("STATUS_UPDATE");
enumSet = createObject("java", "java.util.EnumSet");
network = yourClientObject.getNetworkUpdates(enumSet.of(STATUS_UPDATE));
numOfUpdates = network.getUpdates().getTotal();
// Add error handling in case numOfUpdates = 0
result = yourClientObject.getNetworkUpdates(numOfUpdates, numOfUpdates);
lastUpdate = result.getUpdates().getUpdateList().get(0);
key = lastUpdate.getUpdateKey();
</cfscript>
You can also use socialauth library to retrieve updates and post status on linkedin.
http://code.google.com/p/socialauth

Categories

Resources