Skip to content

Commit

Permalink
correct cit clone
Browse files Browse the repository at this point in the history
  • Loading branch information
witchpou committed Dec 14, 2019
1 parent dec41c8 commit 16900a8
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 97 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package de.starwit.generator.services;

import org.apache.log4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

/** Class for running git commands. */
public class Git {

private final static Logger LOG = Logger.getLogger("Git");

public static void gitInit(Path directory) throws IOException, InterruptedException {
runCommand(directory, "git", "init");
}

public static void gitStage(Path directory) throws IOException, InterruptedException {
runCommand(directory, "git", "add", "-A");
}

public static void gitCommit(Path directory, String message) throws IOException, InterruptedException {
runCommand(directory, "git", "commit", "-m", message);
}

public static void gitPush(Path directory) throws IOException, InterruptedException {
runCommand(directory, "git", "push");
}

public static void gitClone(Path directory, String originUrl) throws IOException, InterruptedException {
runCommand(directory, "git", "clone", originUrl);
}

public static void gitClone(Path directory, String originUrl, String branch) throws IOException, InterruptedException {
runCommand(directory, "git", "clone", "-b", branch, originUrl);
}

public static void runCommand(Path directory, String... command) throws IOException, InterruptedException {
Objects.requireNonNull(directory, "directory");
if (!Files.exists(directory)) {
throw new RuntimeException("can't run command in non-existing directory '" + directory + "'");
}
ProcessBuilder pb = new ProcessBuilder()
.command(command)
.directory(directory.toFile());
Process p = pb.start();
int exitVal = p.waitFor();

if (exitVal == 0) {
LOG.info("git commad SUCCESS in directory " + directory.toFile().toString());
} else {
p.destroy();
throw new RuntimeException("Process ends with errors.");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package de.starwit.generator.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Locale;

import javax.inject.Named;

Expand All @@ -25,124 +22,81 @@

@Named("ProjectCheckout")
public class ProjectCheckout {

public final static Logger LOG = Logger.getLogger(ProjectCheckout.class);
public String createTempProjectDirectory(ProjectEntity project) throws NotificationException {

public String createTempProjectDirectory(final ProjectEntity project) throws NotificationException {
try {
Path destDir = null;
destDir = Files.createTempDirectory(Constants.LJ_PREFIX + project.getTitle());
return destDir.getFileName().toString();
} catch (IOException e) {
return destDir.toString();
} catch (final IOException e) {
LOG.error("Error creating temporary folder for project", e);
ResponseMetadata data = new ResponseMetadata(ResponseCode.ERROR, "error.projectcheckout.createtempprojectfolder");
final ResponseMetadata data = new ResponseMetadata(ResponseCode.ERROR,
"error.projectcheckout.createtempprojectfolder");
throw new NotificationException(data);
}
}
public void deleteTempProject(String oldDestDirUrl) {
File oldDestDir = new File(oldDestDirUrl);
if (!oldDestDir.exists()) {
return;
}
Path oldDestDirPath = Paths.get(oldDestDirUrl);
try {
Files.walkFileTree(oldDestDirPath, new DeleteFileVisitor());
} catch (IOException e) {
LOG.error("Error deleting temporary folder for project", e);
}

public void deleteTempProject(final String oldDestDirUrl) {
final File oldDestDir = new File(oldDestDirUrl);
if (!oldDestDir.exists()) {
return;
}
final Path oldDestDirPath = Paths.get(oldDestDirUrl);
try {
Files.walkFileTree(oldDestDirPath, new DeleteFileVisitor());
} catch (final IOException e) {
LOG.error("Error deleting temporary folder for project", e);
}
}

private class DeleteFileVisitor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
File file1 = new File(file.toUri());
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) throws IOException {
final File file1 = new File(file.toUri());
file1.setWritable(true);
Files.deleteIfExists(file);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
Files.deleteIfExists(dir); // this will work because Files in the directory are already deleted
return FileVisitResult.CONTINUE;
}
}

/**
* Copies the project template and tomee to an new project location.
*
* @param entity
* @return
* @throws NotificationException
* @return
* @throws NotificationException
*/
@SuppressWarnings("unused")
public void checkoutProjectTemplate(GeneratorDto dto) throws NotificationException {
ProjectEntity entity = dto.getProject();
String destDirString = Constants.TMP_DIR + entity.getTargetPath();
File destDir = new File (destDirString);
public void checkoutProjectTemplate(final GeneratorDto dto) throws NotificationException {
final ProjectEntity entity = dto.getProject();
final String destDirString = entity.getTargetPath();
final File destDir = new File(destDirString);
String srcDir = entity.getTemplate().getLocation();
String branch = Constants.DEFAULT_BRANCH;
if (entity.getTemplate().getBranch() != null) {
branch = entity.getTemplate().getBranch();
}

if (dto.getProject().getTemplate().isCredentialsRequired()) {
dto.setPassword(dto.getPassword().replaceAll("@", "%40"));
srcDir = srcDir.replaceAll("://", "://" + dto.getUsername() + ":" + dto.getPassword() + "@");
}

gitCloneCommand(srcDir, destDirString, branch);
}

public void gitCloneCommand(String srcDir, String destDirString, String branch) throws NotificationException {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.directory(new File(destDirString));
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (OS.indexOf("win") >= 0) {
// Run a windows command
processBuilder.command("cmd.exe", "/c", "git clone -b " + branch + " " + srcDir);
} else {
// Run a shell command
processBuilder.command("bash", "-c", "git clone -b " + branch + " " + srcDir);
}

try {

Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}

int exitVal = process.waitFor();
if (exitVal == 0) {
LOG.info("git clone SUCCESS with directory " + srcDir);
} else {
process.destroy();
this.deleteTempProject(destDirString);
LOG.error("Error copying files for project template.");
ResponseMetadata data = new ResponseMetadata(ResponseCode.ERROR,
"error.projectcheckout.checkoutprojecttemplate.transport");
throw new NotificationException(data);
}

} catch (IOException e) {
Git.gitClone(destDir.toPath(), srcDir, branch);
} catch (IOException | InterruptedException e) {
this.deleteTempProject(destDirString);
LOG.error("Error copying files for project template.", e);
ResponseMetadata data = new ResponseMetadata(ResponseCode.ERROR,
"error.projectcheckout.checkoutprojecttemplate.transport");
throw new NotificationException(data);
} catch (InterruptedException e) {
this.deleteTempProject(destDirString);
LOG.error("Error copying files for project template.", e);
ResponseMetadata data = new ResponseMetadata(ResponseCode.ERROR,
final ResponseMetadata data = new ResponseMetadata(ResponseCode.ERROR,
"error.projectcheckout.checkoutprojecttemplate.transport");
throw new NotificationException(data);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public void renameProjectTitle(ProjectEntity entity) throws NotificationExceptio
LOG.info("Try to rename project " + entity.getTemplate().getPackagePrefix() + ".");

File parentdirectory;
parentdirectory = new File(Constants.TMP_DIR + Constants.FILE_SEP + entity.getTargetPath());
parentdirectory = new File(entity.getTargetPath());
String currentProjectName = entity.getTemplate().getTitle();
renameDirectories(currentProjectName, entity.getTitle(), parentdirectory, false);
renameFiles(currentProjectName, entity.getTitle(), parentdirectory);
Expand All @@ -50,7 +50,7 @@ public void renamePackage(ProjectEntity entity) throws NotificationException {
LOG.info("Try to rename package " + entity.getTitle() + ".");

File parentdirectory;
parentdirectory = new File(Constants.TMP_DIR + Constants.FILE_SEP + entity.getTargetPath());
parentdirectory = new File(entity.getTargetPath());
renameDirectories(entity.getTemplate().getPackagePrefix(), entity.getPackagePrefix(), parentdirectory, true);
renameFiles(entity.getTemplate().getPackagePrefix(), entity.getPackagePrefix(), parentdirectory);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

import org.apache.log4j.Logger;

import de.starwit.generator.config.Constants;
import de.starwit.generator.dto.GeneratorDto;
import de.starwit.ljprojectbuilder.ejb.DomainService;
import de.starwit.ljprojectbuilder.ejb.ProjectService;
Expand Down Expand Up @@ -60,7 +59,7 @@ public class ProjectSetupService implements Serializable {
@TransactionAttribute(TransactionAttributeType.NEVER)
public void setupAndGenerateProject(GeneratorDto dto) throws NotificationException {
ProjectEntity project = projectService.findProjectByIdOrThrowExeption(dto.getProject().getId());
String destDirString = Constants.TMP_DIR + project.getTargetPath();
String destDirString = project.getTargetPath();
projectCheckout.deleteTempProject(destDirString);
String newProjectFolder = projectCheckout.createTempProjectDirectory(project);
project.setTargetPath(newProjectFolder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,45 @@

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.apache.log4j.Logger;
import org.junit.Test;

import de.starwit.generator.config.Constants;
import de.starwit.generator.services.Git;
import de.starwit.generator.services.ProjectCheckout;
import de.starwit.generator.services.StartupShutdownService;
import de.starwit.ljprojectbuilder.exception.NotificationException;
import static org.junit.Assert.*;

public class ProjectCheckoutTest {

protected ProjectCheckout checkout = new ProjectCheckout();
protected StartupShutdownService startup = new StartupShutdownService();


private final static Logger LOG = Logger.getLogger("ProjectCheckoutTest");

@Test
public void cloneGitRepoWithoutAuthTest() throws NotificationException, IOException {
Files.createDirectory(new File(Constants.TMP_DIR + "lirejarp").toPath());
checkout.gitCloneCommand("https://github.com/witchpou/lirejarp.git", Constants.TMP_DIR + "lirejarp", "master");
checkout.deleteTempProject(Constants.TMP_DIR + "lirejarp");
public void cloneGitRepoWithoutAuthTest() throws NotificationException, IOException, InterruptedException {
final Path destDir = this.createDirectory("tmplirejarp").toPath();
String dir = destDir.toAbsolutePath().toString();
LOG.info("Path is " + dir);
Git.gitClone(destDir, "https://github.com/witchpou/lirejarp.git", "master");

String[] dirContent = destDir.toFile().list();
assertTrue("Cloning repository results in an empty directory.", (dirContent != null && dirContent.length > 0));
checkout.deleteTempProject("tmplirejarp");
}





private File createDirectory(final String location) {
final File file = new File(location);
if (file.exists()) {
checkout.deleteTempProject("tmplirejarp");
fail("Directory " + location + "should not exist.");
}
final boolean iscreated = file.mkdir();
assertTrue(iscreated);
return file;
}

}

0 comments on commit 16900a8

Please sign in to comment.