fix git branch checkout

merge-requests/14/merge
Anton Romanov 3 years ago
parent d2f4363b64
commit dc99cd6ab2

@ -5,6 +5,9 @@
package ru.ulstu.extractor.controller; package ru.ulstu.extractor.controller;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -18,6 +21,7 @@ import ru.ulstu.extractor.model.mvc.RepoForm;
import ru.ulstu.extractor.service.GitRepositoryService; import ru.ulstu.extractor.service.GitRepositoryService;
import ru.ulstu.extractor.service.IndexService; import ru.ulstu.extractor.service.IndexService;
import java.io.IOException;
import java.util.List; import java.util.List;
import static ru.ulstu.extractor.controller.Route.FILTER_COMMITS; import static ru.ulstu.extractor.controller.Route.FILTER_COMMITS;
@ -25,6 +29,7 @@ import static ru.ulstu.extractor.controller.Route.INDEXING_NEW_REPOSITORY;
@Controller @Controller
public class GitIndexingController { public class GitIndexingController {
private final static Logger LOG = LoggerFactory.getLogger(GitIndexingController.class);
private final GitRepositoryService gitRepositoryService; private final GitRepositoryService gitRepositoryService;
private final IndexService indexService; private final IndexService indexService;
@ -43,8 +48,7 @@ public class GitIndexingController {
@RequestMapping(value = INDEXING_NEW_REPOSITORY, method = RequestMethod.POST, params = "send") @RequestMapping(value = INDEXING_NEW_REPOSITORY, method = RequestMethod.POST, params = "send")
public String getBranch(@ModelAttribute RepoForm repoForm, Model model) { public String getBranch(@ModelAttribute RepoForm repoForm, Model model) {
try { try {
gitRepositoryService.cloneOrUpdateRepo(repoForm.getRepo()); List<Branch> branches = gitRepositoryService.getRemoteBranches(repoForm.getRepo());
List<Branch> branches = gitRepositoryService.getBranches(repoForm.getRepo());
model.addAttribute("branches", branches); model.addAttribute("branches", branches);
} catch (Exception ex) { } catch (Exception ex) {
model.addAttribute("error", ex.getMessage()); model.addAttribute("error", ex.getMessage());
@ -53,14 +57,15 @@ public class GitIndexingController {
} }
@RequestMapping(value = INDEXING_NEW_REPOSITORY, method = RequestMethod.POST, params = "next") @RequestMapping(value = INDEXING_NEW_REPOSITORY, method = RequestMethod.POST, params = "next")
public String setBranch(@ModelAttribute RepoForm repoForm, Model model, RedirectAttributes redirectAttributes) { public String indexBranch(@ModelAttribute RepoForm repoForm, Model model, RedirectAttributes redirectAttributes) {
model.addAttribute("filterForm", new FilterForm(repoForm.getRepo())); model.addAttribute("filterForm", new FilterForm(repoForm.getRepo()));
if (repoForm.getBranch() == null) { if (repoForm.getBranch() == null) {
return INDEXING_NEW_REPOSITORY; return INDEXING_NEW_REPOSITORY;
} else { } else {
try { try {
indexService.index(repoForm.getRepo(), repoForm.getBranch()); indexService.index(repoForm.getRepo(), repoForm.getBranch());
} catch (Exception ex) { } catch (IOException | GitAPIException ex) {
ex.printStackTrace();
model.addAttribute("error", ex.getMessage()); model.addAttribute("error", ex.getMessage());
return INDEXING_NEW_REPOSITORY; return INDEXING_NEW_REPOSITORY;
} }

@ -1,3 +1,8 @@
/*
* Copyright (C) 2021 Anton Romanov - All Rights Reserved
* You may use, distribute and modify this code, please write to: romanov73@gmail.com.
*/
package ru.ulstu.extractor.controller; package ru.ulstu.extractor.controller;
import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.GitAPIException;
@ -7,6 +12,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.extractor.model.Commit; import ru.ulstu.extractor.model.Commit;
import ru.ulstu.extractor.service.GitRepositoryService; import ru.ulstu.extractor.service.GitRepositoryService;
import ru.ulstu.extractor.service.IndexService;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@ -18,14 +24,12 @@ import static ru.ulstu.extractor.controller.RepoController.URL;
public class RepoController { public class RepoController {
public static final String URL = "/"; public static final String URL = "/";
private final GitRepositoryService gitRepositoryService; private final GitRepositoryService gitRepositoryService;
private final IndexService indexService;
public RepoController(GitRepositoryService gitRepositoryService) { public RepoController(GitRepositoryService gitRepositoryService,
IndexService indexService) {
this.gitRepositoryService = gitRepositoryService; this.gitRepositoryService = gitRepositoryService;
} this.indexService = indexService;
@GetMapping("clone")
public void cloneRepository(@RequestParam("url") String url) throws GitAPIException, IOException {
gitRepositoryService.cloneOrUpdateRepo(url);
} }
@GetMapping("commits") @GetMapping("commits")
@ -34,4 +38,11 @@ public class RepoController {
return gitRepositoryService.getCommits(repositoryUrl, branchName); return gitRepositoryService.getCommits(repositoryUrl, branchName);
} }
@GetMapping("index")
public Boolean indexRepository(@RequestParam("repositoryUrl") String repositoryUrl,
@RequestParam("branchName") String branchName) throws GitAPIException, IOException {
indexService.index(repositoryUrl, branchName);
return true;
}
} }

@ -1,3 +1,8 @@
/*
* Copyright (C) 2021 Anton Romanov - All Rights Reserved
* You may use, distribute and modify this code, please write to: romanov73@gmail.com.
*/
package ru.ulstu.extractor.service; package ru.ulstu.extractor.service;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
@ -7,7 +12,6 @@ import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevCommit;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -37,39 +41,32 @@ public class GitRepositoryService {
@Value("${extractor.custom-projects-dir}") @Value("${extractor.custom-projects-dir}")
private String customProjectsDir; private String customProjectsDir;
public void cloneOrUpdateRepo(String url) throws GitAPIException, IOException { public List<Branch> getRemoteBranches(String url) throws GitAPIException, IOException {
Git git; cloneOrUpdateRepo(url);
if (projectDirExists(getProjectDirectoryFile(url))) { Repository localRepo = new FileRepository(getProjectGitDirectory(url));
Repository localRepo = new FileRepository(getProjectGitDirectory(url)); Git git = new Git(localRepo);
git = new Git(localRepo); List<Branch> branches = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE)
git.pull().call(); .call()
localRepo.close(); .stream()
} else { .map(r -> new Branch(r.getName().replace(BRANCH_PREFIX, "")))
git = Git.cloneRepository() .collect(Collectors.toList());
.setURI(url)
.setDirectory(getProjectDirectoryFile(url))
.call();
}
git.close(); git.close();
localRepo.close();
return branches;
} }
private String getProjectDirectory(String url) { public List<Branch> getLocalBranches(String url) throws GitAPIException, IOException {
return (isBlank(customProjectsDir) cloneOrUpdateRepo(url);
? System.getProperty("java.io.tmpdir") Repository localRepo = new FileRepository(getProjectGitDirectory(url));
: customProjectsDir) + url.substring(url.lastIndexOf('/')); Git git = new Git(localRepo);
} List<Branch> branches = git.branchList()
.call()
private String getProjectGitDirectory(String url) { .stream()
return getProjectDirectory(url) + "/.git"; .map(r -> new Branch(r.getName().replace(BRANCH_PREFIX, "")))
} .collect(Collectors.toList());
git.close();
private File getProjectDirectoryFile(String url) { localRepo.close();
return Path.of(getProjectDirectory(url)) return branches;
.toFile();
}
private boolean projectDirExists(File file) {
return file.exists();
} }
public List<Commit> getCommits(String repositoryUrl, String branchName) throws GitAPIException, IOException { public List<Commit> getCommits(String repositoryUrl, String branchName) throws GitAPIException, IOException {
@ -78,12 +75,18 @@ public class GitRepositoryService {
Git git = new Git(localRepo); Git git = new Git(localRepo);
git.pull().call(); git.pull().call();
if (!localRepo.getBranch().equals(branchName)) { if (!localRepo.getBranch().equals(branchName)) {
Ref ref = git.checkout(). if (getLocalBranches(repositoryUrl).stream().anyMatch(localBranch -> localBranch.getName().contains(branchName))) {
setCreateBranch(true). git.checkout()
setName(branchName). .setName(branchName)
setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK). .call();
setStartPoint("origin/" + branchName). } else {
call(); git.checkout()
.setCreateBranch(true)
.setName(branchName)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + branchName)
.call();
}
} }
List<RevCommit> commits = new ArrayList<>(); List<RevCommit> commits = new ArrayList<>();
git.log().call().forEach(commits::add); git.log().call().forEach(commits::add);
@ -107,7 +110,46 @@ public class GitRepositoryService {
return list; return list;
} }
public List<FileChange> findDiffBetweenTwoRevisions(RevCommit laterCommit, RevCommit earlierCommit, Repository localRepo) { public void remove(String repositoryUrl) throws IOException {
FileUtils.deleteDirectory(getProjectDirectoryFile(repositoryUrl));
}
private void cloneOrUpdateRepo(String url) throws GitAPIException, IOException {
Git git;
if (projectDirExists(getProjectDirectoryFile(url))) {
Repository localRepo = new FileRepository(getProjectGitDirectory(url));
git = new Git(localRepo);
git.pull().call();
localRepo.close();
} else {
git = Git.cloneRepository()
.setURI(url)
.setDirectory(getProjectDirectoryFile(url))
.call();
}
git.close();
}
private String getProjectDirectory(String url) {
return (isBlank(customProjectsDir)
? System.getProperty("java.io.tmpdir")
: customProjectsDir) + url.substring(url.lastIndexOf('/'));
}
private String getProjectGitDirectory(String url) {
return getProjectDirectory(url) + "/.git";
}
private File getProjectDirectoryFile(String url) {
return Path.of(getProjectDirectory(url))
.toFile();
}
private boolean projectDirExists(File file) {
return file.exists();
}
private List<FileChange> findDiffBetweenTwoRevisions(RevCommit laterCommit, RevCommit earlierCommit, Repository localRepo) {
if (laterCommit == null || earlierCommit == null) { if (laterCommit == null || earlierCommit == null) {
return null; return null;
} }
@ -205,22 +247,4 @@ public class GitRepositoryService {
} }
return Optional.empty(); return Optional.empty();
} }
public List<Branch> getBranches(String url) throws GitAPIException, IOException {
cloneOrUpdateRepo(url);
Repository localRepo = new FileRepository(getProjectGitDirectory(url));
Git git = new Git(localRepo);
List<Branch> branches = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE)
.call()
.stream()
.map(r -> new Branch(r.getName().replace(BRANCH_PREFIX, "")))
.collect(Collectors.toList());
git.close();
localRepo.close();
return branches;
}
public void remove(String repositoryUrl) throws IOException {
FileUtils.deleteDirectory(getProjectDirectoryFile(repositoryUrl));
}
} }

@ -1,3 +1,8 @@
/*
* Copyright (C) 2021 Anton Romanov - All Rights Reserved
* You may use, distribute and modify this code, please write to: romanov73@gmail.com.
*/
package ru.ulstu.extractor.service; package ru.ulstu.extractor.service;
import com.sun.istack.NotNull; import com.sun.istack.NotNull;
@ -5,6 +10,7 @@ import org.eclipse.jgit.api.errors.GitAPIException;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.extractor.model.Author; import ru.ulstu.extractor.model.Author;
import ru.ulstu.extractor.model.Branch; import ru.ulstu.extractor.model.Branch;
import ru.ulstu.extractor.model.Commit; import ru.ulstu.extractor.model.Commit;
@ -38,6 +44,7 @@ public class IndexService {
this.authorRepository = authorRepository; this.authorRepository = authorRepository;
} }
@Transactional
public void index(@NotNull String repositoryUrl, @NotNull String branchName) throws GitAPIException, IOException { public void index(@NotNull String repositoryUrl, @NotNull String branchName) throws GitAPIException, IOException {
Repository repository = repositoryRepository.findByUrl(repositoryUrl); Repository repository = repositoryRepository.findByUrl(repositoryUrl);
if (repository == null) { if (repository == null) {
@ -45,14 +52,13 @@ public class IndexService {
} }
Branch branch = branchRepository.findByRepositoryAndName(repository, branchName); Branch branch = branchRepository.findByRepositoryAndName(repository, branchName);
if (branch == null) { if (branch == null) {
branchRepository.save(new Branch(repository, branchName)); branch = branchRepository.save(new Branch(repository, branchName));
} }
List<Commit> commits = gitRepositoryService.getCommits(repositoryUrl, branchName); List<Commit> commits = gitRepositoryService.getCommits(repositoryUrl, branchName);
commitRepository.deleteAll(branch.getCommits()); commitRepository.deleteAll(branch.getCommits());
branch.getCommits().clear(); branch.getCommits().clear();
branch.setCommits(commits); branch.setCommits(commits);
branchRepository.save(branch); branchRepository.save(branch);
gitRepositoryService.remove(repositoryUrl);
} }
public List<Author> getRepositoryAuthors(@NotNull String repositoryUrl, @NotNull String branchName) { public List<Author> getRepositoryAuthors(@NotNull String repositoryUrl, @NotNull String branchName) {

@ -1,5 +1,11 @@
#
# Copyright (C) 2021 Anton Romanov - All Rights Reserved
# You may use, distribute and modify this code, please write to: romanov73@gmail.com.
#
spring.main.banner-mode=off spring.main.banner-mode=off
server.port=8080 server.port=8080
server.jetty.connection-idle-timeout=1000s
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF # Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.ru.ulstu=DEBUG logging.level.ru.ulstu=DEBUG
extractor.custom-projects-dir= extractor.custom-projects-dir=

@ -48,6 +48,8 @@
</div> </div>
<div class="container-fluid"> <div class="container-fluid">
<ul id="messages" class="feedback-panel"> <ul id="messages" class="feedback-panel">
<div class="alert alert-danger" role="alert" th:if="${error}" th:text="${error}">
</div>
</ul> </ul>
</div> </div>
<div layout:fragment="content"> <div layout:fragment="content">

@ -9,7 +9,6 @@
layout:decorate="~{default}"> layout:decorate="~{default}">
<div class="container" layout:fragment="content"> <div class="container" layout:fragment="content">
<form action="#" th:action="${@route.INDEXING_NEW_REPOSITORY}" th:object="${repoForm}" method="post"> <form action="#" th:action="${@route.INDEXING_NEW_REPOSITORY}" th:object="${repoForm}" method="post">
<p style="color:red" th:text="${error}"></p>
<button class="btn btn-outline-dark dropdown-toggle" type="button" data-toggle="collapse" <button class="btn btn-outline-dark dropdown-toggle" type="button" data-toggle="collapse"
data-target="#collapseOne" aria-expanded="false" aria-controls="collapseExample" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseExample"
th:if="${repoForm.repo != null}" th:if="${repoForm.repo != null}"

Loading…
Cancel
Save