Skip to content

Commit

Permalink
Improved cheerpj publish to github pages action
Browse files Browse the repository at this point in the history
  • Loading branch information
shannah committed Oct 2, 2023
1 parent 4a48a5c commit ca1315b
Show file tree
Hide file tree
Showing 3 changed files with 123 additions and 80 deletions.
93 changes: 13 additions & 80 deletions cli/src/main/java/ca/weblite/jdeploy/services/CheerpjService.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
package ca.weblite.jdeploy.services;

import ca.weblite.jdeploy.cheerpj.services.BuildCheerpjAppService;
import ca.weblite.tools.io.FileUtil;
import org.json.JSONObject;

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class CheerpjService extends BaseService {
private BuildCheerpjAppService buildCheerpjAppService;

public CheerpjService(File packageJSONFile, JSONObject packageJSON) throws IOException {
super(packageJSONFile, packageJSON);
buildCheerpjAppService = new BuildCheerpjAppService();

}


public boolean isEnabled() {
return getJDeployObject().has("cheerpj");
}
Expand Down Expand Up @@ -138,10 +132,16 @@ private String getGithubPagesPublishPath() throws IOException, InterruptedExcept
}

public boolean isGithubPagesEnabled() {
if (!getGithubPagesConfig().has("enabled")) {
return false;
}
return getGithubPagesConfig().getBoolean("enabled");
}

private String getGithubPagesBranch() {
if (!getGithubPagesConfig().has("branch")) {
return null;
}
return getGithubPagesConfig().getString("branch");
}

Expand All @@ -161,20 +161,6 @@ private String getCurrentGitBranch() throws IOException, InterruptedException {
return branchName;
}

private void checkoutBranch(String branch, boolean fetch, boolean pull) throws IOException, InterruptedException {
if (fetch) {
executeGitCommand("git", "fetch", "--all");
}

// Checkout gh-pages branch
executeGitCommand("git", "checkout", branch);

// Pull the latest
if (pull) {
executeGitCommand("git", "pull");
}
}

public static void generateGitignoreFile(String directoryPath) throws IOException {
File gitignore = new File(directoryPath, ".gitignore");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(gitignore))) {
Expand All @@ -186,70 +172,17 @@ public static void generateGitignoreFile(String directoryPath) throws IOExceptio
// Do not ignore directories, so we can traverse them
writer.write("\n");
}
System.out.println(".gitignore file created at: " + gitignore.getAbsolutePath());
}


private void publishToGithubPages() throws IOException, InterruptedException {
String currentBranch = getCurrentGitBranch();
String githubPagesBranch = getGithubPagesBranch();
String githubPagesPublishPath = getGithubPagesPublishPath();
if (githubPagesPublishPath == null) {
throw new IOException("Github pages publish path is null.");
if (getCurrentGitBranch() != null && getCurrentGitBranch().equals(getGithubPagesBranch())) {
System.out.println("Cannot publish to github pages from the same branch");
return;
}
File publishPath = new File(packageJSONFile.getParentFile(), githubPagesPublishPath);
boolean stashed = false;
if (!currentBranch.equals(githubPagesBranch)) {
executeGitCommand("git", "stash");
stashed = true;
checkoutBranch(githubPagesBranch, true, true);
}
try {
if (publishPath.exists()) {
FileUtil.delTree(publishPath);
}
publishPath.getParentFile().mkdirs();
publishToCurrentBranch(publishPath);
} finally {
if (stashed) {
executeGitCommand("git", "stash", "pop");
}
if (!currentBranch.equals(githubPagesBranch)) {
checkoutBranch(currentBranch, false, false);
}
}


}

private void executeGitCommand(String... commands) throws IOException, InterruptedException {
System.out.println("Running git command: " + Arrays.toString(commands));
ProcessBuilder processBuilder = new ProcessBuilder(commands);
processBuilder.inheritIO();
Process process = processBuilder.start();
int result = process.waitFor();

// Output the command result for debugging purpose
try (InputStream inputStream = process.getInputStream();
Scanner scanner = new Scanner(inputStream)) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
if (result != 0) {
throw new IOException("Error while executing git command: " + Arrays.toString(commands));
}
}

private void publishToCurrentBranch(File publishPath) throws IOException, InterruptedException {

FileUtil.copy(getDestDirectory(), publishPath);
generateGitignoreFile(publishPath.getAbsolutePath());

executeGitCommand("git", "add", getGithubPagesPublishPath());
executeGitCommand("git", "commit", "-m", "Publish to github pages.");
executeGitCommand("git", "push", "origin", getCurrentGitBranch());
GithubPagesPublisher publisher = new GithubPagesPublisher();
generateGitignoreFile(getDestDirectory().getAbsolutePath());
System.out.println("Publishing to github pages");
publisher.publishToGithubPages(getDestDirectory(), null, getGithubPagesBranch(), getGithubPagesPublishPath());

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package ca.weblite.jdeploy.services;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.Scanner;

public class GithubPagesPublisher {
private GithubService githubService = new GithubService();
/**
* Publishes the contents of a directory to a github pages branch.
*
* @param sourceDirectory The directory containing the files to publish.
* @param repoUrl The URL of the github repository
* @param branchName The branch-name to publish to
* @param destPath The destination path within the repo where the files should be published.
* @throws IOException, InterruptedException
*/
public void publishToGithubPages(File sourceDirectory, String repoUrl, String branchName, String destPath) throws IOException, InterruptedException {
if (repoUrl == null) {
repoUrl = githubService.getRepoURL(sourceDirectory);
}
File tempDir = null;
try {
// Create a temporary directory
tempDir = Files.createTempDirectory("tempRepoDir").toFile();

// Clone the repository to a temporary directory
ProcessBuilder builder = new ProcessBuilder();
builder.command("git", "clone", "--depth", "1", "-b", branchName, repoUrl, tempDir.getAbsolutePath())
.inheritIO()
.start()
.waitFor();

// Copy the contents of sourceDirectory to the temporary directory at destPath
File destDir = new File(tempDir, destPath);
copyDirectory(sourceDirectory, destDir);

// Add, commit and push the changes
builder.command("git", "add", ".")
.directory(tempDir)
.inheritIO()
.start()
.waitFor();
builder.command("git", "commit", "-m", "Update GitHub Pages")
.directory(tempDir)
.inheritIO()
.start()
.waitFor();
builder.command("git", "push")
.directory(tempDir)
.inheritIO()
.start()
.waitFor();
} finally {
// Delete the temporary directory
if (tempDir != null) {
deleteDirectory(tempDir);
}
}
}

// Copy the source directory to the destination directory
private void copyDirectory(File source, File dest) throws IOException {
if (source.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
}
for (String child : source.list()) {
copyDirectory(new File(source, child), new File(dest, child));
}
} else {
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}

// Delete a directory recursively
private void deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
directoryToBeDeleted.delete();
}

public static void main(String[] args) {
GithubPagesPublisher publisher = new GithubPagesPublisher();
try {
publisher.publishToGithubPages(new File("sourceDirectory"), "https://github.com/user/repo.git", "gh-pages", "destPath");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
14 changes: 14 additions & 0 deletions cli/src/main/java/ca/weblite/jdeploy/services/GithubService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import ca.weblite.jdeploy.helpers.PackageInfoBuilder;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class GithubService {

private String token;
Expand All @@ -13,5 +17,15 @@ public PackageInfoBuilder createPackageInfoBuilder(String source) {
return builder;
}

public String getRepoURL(File repoDir) throws IOException {
ProcessBuilder builder = new ProcessBuilder();
builder.command("git", "config", "--get", "remote.origin.url")
.directory(repoDir);
Process process = builder.start();
Scanner scanner = new Scanner(process.getInputStream());
String url = scanner.nextLine();
scanner.close();
return url;
}

}

0 comments on commit ca1315b

Please sign in to comment.