Skip to content

Commit

Permalink
several improvements to make this project more flexible
Browse files Browse the repository at this point in the history
  • Loading branch information
porcelli committed Mar 15, 2019
1 parent b2a5f57 commit fd739a1
Show file tree
Hide file tree
Showing 10 changed files with 155 additions and 57 deletions.
5 changes: 0 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,5 @@ target/
# Repository wide ignore mac DS_Store files
.DS_Store

# Created by Zanata
/org.uberfire
/org.dashbuilder

# Live editing asciidoc leaves .html files behind in the source dir
uberfire-docs/src/main/asciidoc/*.html
**/dependency-reduced-pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,30 @@

public class GitHook {

private enum SyncMode {
ALWAYS,
ON_SYNC
}

public static void main(String[] args) throws IOException, GitAPIException {
final String username = System.getProperty("gh.username");
final String password = System.getProperty("gh.password");
final String bcurl = System.getProperty("bc.url");

final SyncMode syncMode = getSyncMode();

if (bcurl == null) {
System.err.println("System property 'bc.url' not provided.");
System.exit(1);
}
System.out.println("'gh.username' " + username);
System.out.println("'gh.password' " + password);
System.out.println("'bc.url' " + bcurl);

final Path currentPath = new File("").toPath().toAbsolutePath();
final String parentFolderName = currentPath.getParent().getName(currentPath.getParent().getNameCount() - 1).toString();
if (parentFolderName.equalsIgnoreCase("system")) {
if (parentFolderName.equalsIgnoreCase("system") ||
parentFolderName.equalsIgnoreCase("config")) {
return;
}
final Repository repo = new FileRepositoryBuilder()
Expand Down Expand Up @@ -66,15 +86,14 @@ public static void main(String[] args) throws IOException, GitAPIException {
})
.max(comparing((RevCommit commit) -> commit.getAuthorIdent().getWhen()))
.ifPresent(newestCommit -> {
RevCommit commit = newestCommit;
try {
boolean hasSyncOnCommitMessage = commit.getFullMessage().trim().startsWith("sync:");
boolean executeRemoteSync = syncMode.equals(SyncMode.ALWAYS) || newestCommit.getFullMessage().trim().startsWith("sync:");

if (hasSyncOnCommitMessage) {
if (executeRemoteSync) {
final Map<ObjectId, String> branchesAffected = git
.nameRev()
.addPrefix("refs/heads")
.add(commit)
.add(newestCommit)
.call();

for (String remoteName : remotes) {
Expand All @@ -96,11 +115,13 @@ public static void main(String[] args) throws IOException, GitAPIException {
}
} else {
git.fetch().call();
final TrackingStatusCommand trackingStatusCommand = new TrackingStatusCommand(git.getRepository());
final TrackingStatus counts = trackingStatusCommand.getCounts(ref);
if (counts.getCommitsAhead() > 0) {
final RevCommit id = new GetPreviousCommitCommand(repo).execute(commit, counts.getCommitsAhead() - 1);
new SquashCommand(git, ref, id.name(), commit.getFullMessage()).execute(commit);
if (!syncMode.equals(SyncMode.ALWAYS)) {
final TrackingStatusCommand trackingStatusCommand = new TrackingStatusCommand(git.getRepository());
final TrackingStatus counts = trackingStatusCommand.getCounts(ref);
if (counts.getCommitsAhead() > 0) {
final RevCommit id = new GetPreviousCommitCommand(repo).execute(newestCommit, counts.getCommitsAhead() - 1);
new SquashCommand(git, ref, id.name(), newestCommit.getFullMessage()).execute(newestCommit);
}
}
git.push()
.setRefSpecs(new RefSpec(ref + ":" + ref))
Expand All @@ -116,4 +137,12 @@ public static void main(String[] args) throws IOException, GitAPIException {
}
});
}

private static SyncMode getSyncMode() {
try {
return SyncMode.valueOf(System.getProperty("sync.mode", SyncMode.ALWAYS.name()).toUpperCase());
} catch (Exception ex) {
return SyncMode.ALWAYS;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package porcelli.me.git.integration.githook.command;

import java.nio.file.Path;

public class GetSpaceName implements Command {

public String execute(final Path currentPath) {
return currentPath.getName(currentPath.getNameCount() - 2).toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ public String execute(final Git git,
final Path currentPath) throws IOException, GitAPIException {
final StoredConfig storedConfig = git.getRepository().getConfig();

final String spaceName = new GetSpaceName().execute(currentPath);
final String repoName = new GetRepoName().execute(currentPath);
final String remoteURL = integration.createRepository(repoName);
final String remoteURL = integration.createRepository(spaceName, repoName);
storedConfig.setString("remote", "origin", "url", remoteURL);
storedConfig.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,25 @@ public class GitHubCredentials {
private String space = null;

public GitHubCredentials() {
File homeDir = new File(System.getProperty("user.home"));
File propertyFile = new File(homeDir, ".github");

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(propertyFile)) {
props.load(in);
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
final String username = System.getProperty("gh.username");
final String password = System.getProperty("gh.password");

if (username != null && password != null) {
credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);
} else {
File homeDir = new File(System.getProperty("user.home"));
File propertyFile = new File(homeDir, ".github");

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(propertyFile)) {
props.load(in);
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
space = props.getProperty("login");
this.credentialsProvider = new UsernamePasswordCredentialsProvider(props.getProperty("login"), props.getProperty("password"));
}
space = props.getProperty("login");
this.credentialsProvider = new UsernamePasswordCredentialsProvider(props.getProperty("login"), props.getProperty("password"));
}

public CredentialsProvider getCredentials() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,38 @@

public class GitHubIntegration {

private static final String BC_URL = System.getProperty("bc.url");
private static final String WH_URL = System.getProperty("wh.url", null);
private static final String GH_USERNAME = System.getProperty("gh.username");
private static final String GH_PASSWORD = System.getProperty("gh.password");

private final GitHubCredentials credentials;

public GitHubIntegration(final GitHubCredentials credentials) {
this.credentials = credentials;
}

public String createRepository(final String repoName) throws IOException {
final GitHub github = GitHub.connect();
public String createRepository(final String spaceName, final String repoName) throws IOException {
final GitHub github = GitHub.connect(GH_USERNAME, GH_PASSWORD);
final GHRepository repo = github.createRepository(repoName)
.description("ssh://localhost:8001/MySpace/" + repoName)
.description("ssh://" + BC_URL + "/" + spaceName + "/" + repoName)
.autoInit(false)
.create();

final Map<String, String> config = new HashMap<String, String>() {{
put("url", new URL("http://e5997029.ngrok.io/api/hook/").toExternalForm());
put("content_type", "json");
}};
repo.createHook("web", config, asList(GHEvent.PULL_REQUEST, GHEvent.PUSH), true);
if (WH_URL != null) {
final Map<String, String> config = new HashMap<String, String>() {{
put("url", new URL(WH_URL).toExternalForm());
put("content_type", "json");
}};
repo.createHook("web", config, asList(GHEvent.PULL_REQUEST, GHEvent.PUSH), true);
}

return repo.getHttpTransportUrl();
}

public void createPR(final String repoName,
final String sourceBranch) throws IOException {
final GitHub github = GitHub.connect();
final GitHub github = GitHub.connect(GH_USERNAME, GH_PASSWORD);
final GHPullRequest pullRequest = github.getRepository(credentials.getSpace() + "/" + repoName).createPullRequest("PR from RHPAM", sourceBranch, "master", sourceBranch);
}
}
13 changes: 13 additions & 0 deletions bc-github-webhook/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
FROM fabric8/java-centos-openjdk8-jre
ENV PORT=9090

USER root
RUN yum install -y openssh-server
RUN mkdir -p /root/.ssh
RUN ssh-keygen -t rsa -N "" -f /root/.ssh/id_rsa
RUN echo -e "Host * \nStrictHostKeyChecking no" > /root/.ssh/config
RUN cat /root/.ssh/id_rsa.pub

COPY target/bc-github-webhook-1.0-SNAPSHOT.jar .

CMD java -jar -Dport=$PORT bc-github-webhook-1.0-SNAPSHOT.jar
26 changes: 26 additions & 0 deletions bc-github-webhook/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,32 @@
</executions>
</plugin>

<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.28.0</version>
<!--<configuration>-->
<!--<images>-->
<!--<image>-->
<!--<name>porcelli.me/bc-github-webhook:${project.version}</name>-->
<!--<alias>bc-github-webhook</alias>-->
<!--<build>-->
<!--<env>-->
<!--<BC_USERNAME>adminUser</BC_USERNAME>-->
<!--<BC_PASSWORD>password</BC_PASSWORD>-->
<!--<PORT>9090</PORT>-->
<!--</env>-->
<!--<from>adoptopenjdk/openjdk8:alpine-jre</from>-->
<!--<assembly>-->
<!--<descriptorRef>artifact</descriptorRef>-->
<!--</assembly>-->
<!--<cmd>java -jar -Dbc.username=$BC_USERNAME -Dbc.password=$BC_PASSWORD -Dport=$PORT maven/${project.name}-${project.version}.jar</cmd>-->
<!--</build>-->
<!--</image>-->
<!--</images>-->
<!--</configuration>-->
</plugin>

</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,12 @@
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.SshTransport;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import porcelli.me.git.integration.webhook.model.PullRequestEvent;
import porcelli.me.git.integration.webhook.model.PushEvent;

public class BCIntegration {

private final Map<String, Repository> repositoryMap = new HashMap<>();
private final UsernamePasswordCredentialsProvider bcCredentials = new UsernamePasswordCredentialsProvider("porcelli", "pw");

public void onPush(final PushEvent pushEvent) throws GitAPIException, URISyntaxException, IOException {
if (!pushEvent.getRef().contains("master")) {
Expand All @@ -34,16 +32,16 @@ public void onPush(final PushEvent pushEvent) throws GitAPIException, URISyntaxE
final Git git = getGit(pushEvent.getRepository());

try {
git.pull().setRemote("origin").setCredentialsProvider(bcCredentials).setRebase(true).call();
git.pull().setRemote("origin").setRebase(true).call();
git.pull().setRemote("github").setRebase(true).call();
git.push().setRemote("origin").setForce(true).setCredentialsProvider(bcCredentials).call();
git.push().setRemote("origin").setForce(true).call();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public void onPullRequest(final PullRequestEvent pullRequestEvent) throws GitAPIException, IOException, URISyntaxException {
if (!pullRequestEvent.getAction().equals(PullRequestEvent.Action.CLOSED)){
if (!pullRequestEvent.getAction().equals(PullRequestEvent.Action.CLOSED)) {
return;
}
final String branchName = pullRequestEvent.getPullRequest().getBody();
Expand All @@ -52,28 +50,32 @@ public void onPullRequest(final PullRequestEvent pullRequestEvent) throws GitAPI
git.branchDelete().setBranchNames("refs/heads/" + branchName).call();

final RefSpec refSpec = new RefSpec().setSource(null).setDestination("refs/heads/" + branchName);
git.push().setRefSpecs(refSpec).setRemote("origin").setCredentialsProvider(bcCredentials).call();
git.push().setRefSpecs(refSpec).setRemote("origin").call();
}

private Git getGit(porcelli.me.git.integration.webhook.model.Repository repository) throws GitAPIException, URISyntaxException, IOException {
final Git git;
if (!repositoryMap.containsKey(repository.getDescription())) {
final String bcRepo = repository.getDescription();

SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
}
};
try {
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
}
};

git = Git.cloneRepository()
.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
}).setURI(bcRepo)
.setCredentialsProvider(bcCredentials)
.setDirectory(tempDir(repository.getFullName()))
.call();
git = Git.cloneRepository()
.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
}).setURI(bcRepo)
.setDirectory(tempDir(repository.getFullName()))
.call();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}

final RemoteAddCommand remoteAddCommand = git.remoteAdd();
remoteAddCommand.setName("github");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package porcelli.me.git.integration.webhook;

import java.io.File;

import com.jcraft.jsch.JSch;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
Expand All @@ -16,14 +18,20 @@ public static void main(String[] args) {
JSch.setConfig("StrictHostKeyChecking", "no");
try {
new WebHook().run();
System.out.println("WebHook Up and running!");
} catch (Throwable t) {
t.printStackTrace();
}
}

public void run() throws Exception {

final int port = 9090;
int _port;
try {
_port = Integer.valueOf(System.getProperty("port", "9090"));
} catch (final Exception ex) {
_port = 9090;
}
final int port = _port;
final Server server = new Server(port);

// Setup the basic Application "context" at "/".
Expand Down

0 comments on commit fd739a1

Please sign in to comment.