-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add gh service #75
Merged
Merged
Add gh service #75
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
826828d
Add forking, cloning and PR creation services
sridamul 2170b2e
Remove redundant file
sridamul ff70480
change original repo owner to jenkinsci
sridamul de778fa
Extract constants to settings
sridamul 89c8983
Refactor and resolve review comments
sridamul File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
159 changes: 159 additions & 0 deletions
159
...odernizer-core/src/main/java/io/jenkins/tools/pluginmodernizer/core/github/GHService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
package io.jenkins.tools.pluginmodernizer.core.github; | ||
|
||
import java.io.IOException; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
import java.util.List; | ||
import java.util.Optional; | ||
|
||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | ||
import io.jenkins.tools.pluginmodernizer.core.config.Config; | ||
import io.jenkins.tools.pluginmodernizer.core.config.Settings; | ||
import org.eclipse.jgit.api.Git; | ||
import org.eclipse.jgit.api.errors.GitAPIException; | ||
import org.eclipse.jgit.api.errors.RefAlreadyExistsException; | ||
import org.eclipse.jgit.transport.RefSpec; | ||
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; | ||
import org.kohsuke.github.GHIssueState; | ||
import org.kohsuke.github.GHPullRequest; | ||
import org.kohsuke.github.GHRepository; | ||
import org.kohsuke.github.GitHub; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "false positive") | ||
public class GHService { | ||
|
||
private static final Logger LOG = LoggerFactory.getLogger(GHService.class); | ||
|
||
private final Config config; | ||
|
||
public GHService(Config config) { | ||
this.config = config; | ||
} | ||
|
||
private static final String GITHUB_TOKEN = Settings.GITHUB_TOKEN; | ||
private static final String FORKED_REPO_OWNER = Settings.GITHUB_USERNAME; | ||
private static final String ORIGINAL_REPO_OWNER = Settings.ORGANIZATION; | ||
// TODO: Change commit message and PR title based on applied recipes | ||
private static final String COMMIT_MESSAGE = "Applied transformations with specified recipes"; | ||
private static final String PR_TITLE = "Automated PR"; | ||
|
||
public void forkCloneAndCreateBranch(String pluginName, String branchName) throws IOException, GitAPIException, InterruptedException { | ||
Path pluginDirectory = Paths.get(Settings.TEST_PLUGINS_DIRECTORY, pluginName); | ||
|
||
GitHub github = GitHub.connectUsingOAuth(GITHUB_TOKEN); | ||
GHRepository originalRepo = github.getRepository(ORIGINAL_REPO_OWNER + "/" + pluginName); | ||
|
||
getOrCreateForkedRepo(github, originalRepo); | ||
|
||
cloneRepositoryIfNeeded(pluginDirectory, pluginName); | ||
|
||
createAndCheckoutBranch(pluginDirectory, branchName); | ||
} | ||
|
||
private void getOrCreateForkedRepo(GitHub github, GHRepository originalRepo) throws IOException, InterruptedException { | ||
GHRepository forkedRepo = github.getMyself().getRepository(originalRepo.getName()); | ||
if (forkedRepo == null) { | ||
LOG.info("Forking the repository..."); | ||
originalRepo.fork(); | ||
Thread.sleep(5000); // Ensure the completion of Fork | ||
LOG.info("Repository forked successfully."); | ||
} else { | ||
LOG.info("Repository already forked."); | ||
} | ||
} | ||
|
||
private void cloneRepositoryIfNeeded(Path pluginDirectory, String pluginName) throws GitAPIException { | ||
if (!Files.exists(pluginDirectory) || !Files.isDirectory(pluginDirectory)) { | ||
LOG.info("Cloning {}", pluginName); | ||
Git.cloneRepository() | ||
.setURI("https://github.com/" + FORKED_REPO_OWNER + "/" + pluginName + ".git") | ||
.setDirectory(pluginDirectory.toFile()) | ||
.call(); | ||
LOG.info("Cloned successfully."); | ||
} | ||
} | ||
|
||
private void createAndCheckoutBranch(Path pluginDirectory, String branchName) throws IOException, GitAPIException { | ||
try (Git git = Git.open(pluginDirectory.toFile())) { | ||
try { | ||
git.checkout().setCreateBranch(true).setName(branchName).call(); | ||
} catch (RefAlreadyExistsException e) { | ||
LOG.info("Branch already exists. Checking out the branch."); | ||
git.checkout().setName(branchName).call(); | ||
} | ||
} | ||
} | ||
|
||
public void commitAndCreatePR(String pluginName, String branchName) throws IOException, GitAPIException { | ||
if (config.isDryRun()) { | ||
LOG.info("[Dry Run] Skipping commit and pull request creation for {}", pluginName); | ||
return; | ||
} | ||
|
||
LOG.info("Creating pull request for plugin: {}", pluginName); | ||
|
||
Path pluginDirectory = Paths.get(Settings.TEST_PLUGINS_DIRECTORY, pluginName); | ||
|
||
commitChanges(pluginDirectory); | ||
|
||
pushBranch(pluginDirectory, branchName); | ||
|
||
createPullRequest(pluginName, branchName); | ||
} | ||
|
||
private void commitChanges(Path pluginDirectory) throws IOException, GitAPIException { | ||
try (Git git = Git.open(pluginDirectory.toFile())) { | ||
git.add().addFilepattern(".").call(); | ||
|
||
git.commit() | ||
.setMessage(COMMIT_MESSAGE) | ||
.setSign(false) // Maybe a new option to sign commit? | ||
.call(); | ||
|
||
LOG.info("Changes committed"); | ||
} | ||
} | ||
|
||
private void pushBranch(Path pluginDirectory, String branchName) throws IOException, GitAPIException { | ||
try (Git git = Git.open(pluginDirectory.toFile())) { | ||
git.push() | ||
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(GITHUB_TOKEN, "")) | ||
.setRemote("origin") | ||
.setRefSpecs(new RefSpec(branchName + ":" + branchName)) | ||
.call(); | ||
|
||
LOG.info("Pushed changes to forked repository."); | ||
} | ||
} | ||
|
||
private void createPullRequest(String pluginName, String branchName) throws IOException { | ||
GitHub github = GitHub.connectUsingOAuth(GITHUB_TOKEN); | ||
GHRepository originalRepo = github.getRepository(ORIGINAL_REPO_OWNER + "/" + pluginName); | ||
|
||
Optional<GHPullRequest> existingPR = checkIfPullRequestExists(originalRepo, branchName); | ||
|
||
if (existingPR.isPresent()) { | ||
LOG.info("Pull request already exists: {}", existingPR.get().getHtmlUrl()); | ||
} else { | ||
String prBody = String.format("Applied the following recipes: %s", String.join(", ", config.getRecipes())); | ||
GHPullRequest pr = originalRepo.createPullRequest( | ||
PR_TITLE, | ||
FORKED_REPO_OWNER + ":" + branchName, | ||
originalRepo.getDefaultBranch(), | ||
prBody | ||
); | ||
|
||
LOG.info("Pull request created: {}", pr.getHtmlUrl()); | ||
} | ||
} | ||
|
||
private Optional<GHPullRequest> checkIfPullRequestExists(GHRepository originalRepo, String branchName) throws IOException { | ||
List<GHPullRequest> pullRequests = originalRepo.getPullRequests(GHIssueState.OPEN); | ||
return pullRequests.stream() | ||
.filter(pr -> pr.getHead().getRef().equals(branchName) && pr.getTitle().equals(PR_TITLE)) | ||
.findFirst(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you please track an issue to ensure the GH repo is in sync with upstream. It should be possible via API
I'm using generally the
gh repo sync username/repo
Without sync existing repo there is a risk to open branches from outdated main branch