Commit cfbc691c authored by liaozan's avatar liaozan 🏀

Polish

parent 336f3f5b
......@@ -63,8 +63,8 @@
<artifactId>integration-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<groupId>io.github.git-commit-id</groupId>
<artifactId>git-commit-id-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
......@@ -93,4 +93,4 @@
</plugins>
</build>
</project>
\ No newline at end of file
</project>
......@@ -3,7 +3,7 @@ package com.schbrain.archetype.initializer.runner;
import cn.hutool.core.io.FileUtil;
import cn.hutool.system.SystemUtil;
import com.schbrain.archetype.initializer.config.properties.ArchetypeProperties;
import com.schbrain.archetype.initializer.maven.MavenUtils;
import com.schbrain.archetype.initializer.util.MavenUtils;
import com.schbrain.common.exception.BaseException;
import com.schbrain.common.util.EnvUtils;
import com.schbrain.framework.support.spring.OnceApplicationContextEventListener;
......
package com.schbrain.archetype.initializer.service;
import cn.hutool.cache.Cache;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.io.file.PathUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.system.SystemUtil;
import com.schbrain.archetype.initializer.maven.MavenUtils;
import com.schbrain.archetype.initializer.param.ArchetypeGenerateParam;
import com.schbrain.archetype.initializer.response.PreviewFileTree;
import com.schbrain.archetype.initializer.util.GitlabUtils;
import com.schbrain.archetype.initializer.util.MavenUtils;
import com.schbrain.common.exception.BaseException;
import com.schbrain.common.web.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
......@@ -24,6 +27,7 @@ import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Arrays;
import java.util.Comparator;
......@@ -41,24 +45,31 @@ public class ArchetypeService {
private static final String GITKEEP = ".gitkeep";
private final TimedCache<String, String> archetypeNameCache = new TimedCache<>(Duration.ofHours(1).toMillis());
private final Cache<String, String> archetypeNameCache = new TimedCache<>(Duration.ofMinutes(5).toMillis());
private final Path gitKeepFile = createGitKeepFile(SystemUtil.getUserInfo().getTempDir());
public String generate(ArchetypeGenerateParam param) throws FileNotFoundException {
String generateId = MavenUtils.generate(param);
archetypeNameCache.put(generateId, param.getArtifactId());
preview(generateId);
return generateId;
Pair<String, File> generated = MavenUtils.generate(param);
String generatedId = generated.getKey();
File generatedFile = generated.getRight();
// generate .gitkeep
preview(generatedId);
archetypeNameCache.put(generatedId, param.getArtifactId());
if (param.isInitGitRepo()) {
Path directory = Paths.get(generatedFile.getAbsolutePath(), param.getArtifactId());
GitlabUtils.initGitRepo(directory, param.getRepoGroupId(), param);
}
return generatedId;
}
public List<PreviewFileTree> preview(String id) throws FileNotFoundException {
File generatedFiles = getGeneratedFiles(id);
public List<PreviewFileTree> preview(String generatedId) throws FileNotFoundException {
File generatedFiles = getGeneratedFiles(generatedId);
return List.of(buildFileTree(generatedFiles));
}
public void download(String id) throws IOException {
File generatedFiles = ZipUtil.zip(getGeneratedFiles(id));
public void download(String generatedId) throws IOException {
File generatedFiles = ZipUtil.zip(getGeneratedFiles(generatedId));
FileInputStream inputStream = new FileInputStream(generatedFiles);
HttpServletResponse response = ServletUtils.getResponse();
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition(generatedFiles));
......@@ -66,10 +77,10 @@ public class ArchetypeService {
StreamUtils.copy(inputStream, response.getOutputStream());
}
private PreviewFileTree buildFileTree(File root) {
File[] fileItems = Optional.ofNullable(root.listFiles()).orElse(new File[0]);
private PreviewFileTree buildFileTree(File directory) {
File[] fileItems = Optional.ofNullable(directory.listFiles()).orElse(new File[0]);
if (fileItems.length == 0) {
Path target = Path.of(root.getPath(), GITKEEP);
Path target = Path.of(directory.getPath(), GITKEEP);
fileItems = new File[]{PathUtil.copy(gitKeepFile, target).toFile()};
}
List<PreviewFileTree> children = Arrays.stream(fileItems)
......@@ -84,7 +95,7 @@ public class ArchetypeService {
})
.sorted(Comparator.comparing(PreviewFileTree::getIsFile))
.collect(Collectors.toList());
return new PreviewFileTree(root, children);
return new PreviewFileTree(directory, children);
}
private Path createGitKeepFile(String directory) {
......@@ -97,12 +108,12 @@ public class ArchetypeService {
}
}
private File getGeneratedFiles(String id) throws FileNotFoundException {
File archetypeDirectory = MavenUtils.getArchetypeDirectory(id);
private File getGeneratedFiles(String generatedId) throws FileNotFoundException {
File archetypeDirectory = MavenUtils.getArchetypeDirectory(generatedId);
if (!archetypeDirectory.exists()) {
throw new FileNotFoundException(archetypeDirectory.getAbsolutePath());
}
String artifactId = archetypeNameCache.get(id);
String artifactId = archetypeNameCache.get(generatedId);
if (!StringUtils.hasText(artifactId)) {
throw new FileNotFoundException("文件已过期,请重新生成");
}
......@@ -110,11 +121,7 @@ public class ArchetypeService {
}
private String contentDisposition(File file) {
return ContentDisposition
.attachment()
.filename(file.getName())
.build()
.toString();
return ContentDisposition.attachment().filename(file.getName()).build().toString();
}
}
package com.schbrain.archetype.initializer.util;
import cn.hutool.extra.spring.SpringUtil;
import com.schbrain.archetype.initializer.param.ArchetypeGenerateParam;
import com.schbrain.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.URIish;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.ProtectedBranchesApi;
import org.gitlab4j.api.models.Group;
import org.gitlab4j.api.models.Project;
import org.gitlab4j.api.models.ProtectedBranch;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.List;
/**
* @author liaozan
* @since 2023/7/26
*/
@Slf4j
public class GitlabUtils {
private static final List<String> ADDITIONAL_BRANCHES = List.of("release", "main");
public static void initGitRepo(Path directory, Long repoGroupId, ArchetypeGenerateParam param) {
try {
Git git = Git.init().setInitialBranch("develop").setDirectory(directory.toFile()).call();
git.add().addFilepattern(".").call();
git.commit().setAllowEmpty(true).setAuthor("initializer", "no-reply@schbrain.com").setMessage("Initial Commit").call();
for (String branch : ADDITIONAL_BRANCHES) {
git.checkout().setName(branch).setCreateBranch(true).call();
}
if (repoGroupId != null) {
GitLabApi gitLabApi = SpringUtil.getBean(GitLabApi.class);
Group group = gitLabApi.getGroupApi().getGroup(repoGroupId);
String groupPath = group.getFullPath();
String projectName = param.getArtifactId();
String repositoryUrl = String.format("%s/%s/%s.git", gitLabApi.getGitLabServerUrl(), groupPath, projectName);
URIish urIish = new URIish(repositoryUrl);
git.remoteSetUrl().setRemoteName("origin").setRemoteUri(urIish).call();
git.push()
.setRemote("origin")
.setCredentialsProvider(SpringUtil.getBean(CredentialsProvider.class))
.setPushAll()
.setForce(true)
.call();
Project project = getProject(gitLabApi, groupPath, projectName);
if (project == null) {
return;
}
updateProtectedBranches(gitLabApi, project);
updateProjectDefaultBranch(gitLabApi, project);
}
} catch (GitAPIException | GitLabApiException | URISyntaxException e) {
log.warn("Git repo init failed", e);
throw new BaseException("Git仓库初始化失败");
}
}
private static Project getProject(GitLabApi gitLabApi, String groupPath, String projectName) throws GitLabApiException {
String projectPath = String.format("%s/%s", groupPath, projectName);
return gitLabApi.getProjectApi().getProject(projectPath);
}
private static void updateProjectDefaultBranch(GitLabApi gitLabApi, Project project) throws GitLabApiException {
project.setDefaultBranch("main");
gitLabApi.getProjectApi().updateProject(project);
}
private static void updateProtectedBranches(GitLabApi gitlabApi, Project project) throws GitLabApiException {
ProtectedBranchesApi protectedBranchesApi = gitlabApi.getProtectedBranchesApi();
String projectPath = project.getPathWithNamespace();
List<ProtectedBranch> protectedBranches = protectedBranchesApi.getProtectedBranches(projectPath);
if (CollectionUtils.isNotEmpty(protectedBranches)) {
for (ProtectedBranch protectedBranch : protectedBranches) {
protectedBranchesApi.unprotectBranch(projectPath, protectedBranch.getName());
}
}
}
}
package com.schbrain.archetype.initializer.maven;
package com.schbrain.archetype.initializer.util;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.schbrain.archetype.initializer.param.ArchetypeGenerateParam;
import com.schbrain.common.exception.BaseException;
import com.schbrain.common.util.IdWorker;
import com.schbrain.common.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.maven.cli.MavenCli;
import org.apache.maven.settings.Mirror;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.io.DefaultSettingsWriter;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.URIish;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.ProtectedBranchesApi;
import org.gitlab4j.api.models.Group;
import org.gitlab4j.api.models.Project;
import org.gitlab4j.api.models.ProtectedBranch;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import static org.apache.maven.cli.MavenCli.MULTIMODULE_PROJECT_DIRECTORY;
......@@ -43,8 +28,6 @@ public class MavenUtils {
private static final File SETTINGS_FILE = new File(MavenCli.USER_MAVEN_CONFIGURATION_HOME, "settings.xml");
private static final List<String> ADDITIONAL_BRANCHES = List.of("release", "main");
static {
System.getProperties().setProperty(MULTIMODULE_PROJECT_DIRECTORY, "$M2_HOME");
initSettingsFile();
......@@ -57,7 +40,7 @@ public class MavenUtils {
log.info("Success install archive from : {}", workDirectory);
}
public static String generate(ArchetypeGenerateParam param) {
public static Pair<String, File> generate(ArchetypeGenerateParam param) {
log.info("Prepare to generate archetype project: {}", JacksonUtils.toJsonString(param, true));
String id = IdWorker.getIdStr();
File archetype = getArchetypeDirectory(id);
......@@ -65,11 +48,7 @@ public class MavenUtils {
String[] args = getArchetypeGenerateArgs(param, SETTINGS_FILE.getAbsolutePath(), outputDirectory);
MavenCli.doMain(args, null);
log.info("Generate archetype project at {}", outputDirectory);
if (param.isInitGitRepo()) {
Path directory = Paths.get(archetype.getAbsolutePath(), param.getArtifactId());
initGitRepo(directory, param.getRepoGroupId(), param);
}
return id;
return ImmutablePair.of(id, archetype);
}
public static File getArchetypeDirectory(String id) {
......@@ -77,52 +56,6 @@ public class MavenUtils {
return new File(tmpDirPath, id);
}
private static void initGitRepo(Path directory, Long repoGroupId, ArchetypeGenerateParam param) {
try {
Git git = Git.init().setInitialBranch("develop").setDirectory(directory.toFile()).call();
git.add().addFilepattern(".").call();
git.commit().setAllowEmpty(true).setAuthor("initializer", "no-reply@schbrain.com").setMessage("Initial Commit").call();
for (String branch : ADDITIONAL_BRANCHES) {
git.checkout().setName(branch).setCreateBranch(true).call();
}
if (repoGroupId != null) {
GitLabApi gitLabApi = SpringUtil.getBean(GitLabApi.class);
Group group = gitLabApi.getGroupApi().getGroup(repoGroupId);
String groupPath = group.getFullPath();
String projectName = param.getArtifactId();
String repositoryUrl = String.format("%s/%s/%s.git", gitLabApi.getGitLabServerUrl(), groupPath, projectName);
URIish urIish = new URIish(repositoryUrl);
git.remoteSetUrl().setRemoteName("origin").setRemoteUri(urIish).call();
git.push()
.setRemote("origin")
.setCredentialsProvider(SpringUtil.getBean(CredentialsProvider.class))
.setPushAll()
.setForce(true)
.call();
Project project = getProject(gitLabApi, groupPath, projectName);
if (project == null) {
return;
}
updateProjectDefaultBranch(gitLabApi, project);
updateProtectedBranches(gitLabApi, project);
}
} catch (GitAPIException | GitLabApiException | URISyntaxException e) {
log.warn("Git repo init failed", e);
throw new BaseException("Git仓库初始化失败");
}
}
private static void updateProjectDefaultBranch(GitLabApi gitLabApi, Project project) throws GitLabApiException {
project.setDefaultBranch("main");
gitLabApi.getProjectApi().updateProject(project);
}
private static Project getProject(GitLabApi gitLabApi, String groupPath, String projectName) throws GitLabApiException {
String projectPath = String.format("%s/%s", groupPath, projectName);
return gitLabApi.getProjectApi().getProject(projectPath);
}
private static void initSettingsFile() {
Settings settings = new Settings();
settings.setLocalRepository("/data/maven/repository");
......@@ -184,15 +117,4 @@ public class MavenUtils {
};
}
private static void updateProtectedBranches(GitLabApi gitlabApi, Project project) throws GitLabApiException {
ProtectedBranchesApi protectedBranchesApi = gitlabApi.getProtectedBranchesApi();
String projectPath = project.getPathWithNamespace();
List<ProtectedBranch> protectedBranches = protectedBranchesApi.getProtectedBranches(projectPath);
if (CollectionUtils.isNotEmpty(protectedBranches)) {
for (ProtectedBranch protectedBranch : protectedBranches) {
protectedBranchesApi.unprotectBranch(projectPath, protectedBranch.getName());
}
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment