Thư viện JGit của Eclipse cho phép tương tác với một hệ thống Git quản lý mã nguồn. Ta thêm dependency của JGit vào tập tin pom.xml để xài thư viện này như sau :
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>6.5.0.202303070854-r</version>
</dependency>
Trong ví dụ dưới đây có dùng thư viện commons-io nên ta cũng thêm thư viện này vào tập tin pom.xml như sau :
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Dưới đây là một ví dụ xài thư viện JGit :
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
public class GitBackUpFile {
public static void main(String[] args) {
File createdFile = new File("example.txt");
try {
Files.write(createdFile.toPath(), "File contents".getBytes());
System.out.println("file path : " + createdFile.getAbsolutePath());
backupInGit(createdFile.getAbsolutePath());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Trong ví dụ trên ta tạo một tập tin example.txt và push nó vào một branch của depository git
private static void backupInGit(String sourceFileName) {
String branchName = "branch-local";
String gitDirectoryPath = "/path/to/repo" + File.separator + branchName;
File gitLocalDirectory = new File(gitDirectoryPath);
try {
FileUtils.deleteDirectory(gitLocalDirectory);
} catch (IOException e) {
System.out.println("Error deleting git local directory : " + e.getMessage());
}
if (!gitLocalDirectory.exists() && !gitLocalDirectory.mkdirs()) {
throw new RuntimeException("Error creating local git directory : " + gitDirectoryPath);
}
String branch = "refs/heads/" + branchName;
UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("username", "password");
try (Git git = Git.cloneRepository().setURI("https://github.com/example-eclipse/jgit.git")
.setDirectory(gitLocalDirectory)
.setBranchesToClone(Arrays.asList(branch))
.setBranch(branch)
.setCredentialsProvider(credentialsProvider)
.call()) {
String fileName = "fileToPushIntoGit.txt";
String fileAbsolutePath = gitDirectoryPath + File.separator + fileName;
Files.copy(Paths.get(sourceFileName), Paths.get(fileAbsolutePath), StandardCopyOption.REPLACE_EXISTING);
LocalDateTime timeStamp = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH");
git.add().addFilepattern(fileName).call();
git.commit().setMessage("Commit file " + fileName + " at " + timeStamp.format(dateTimeFormatter)).call();
PushCommand pushCommand = git.push();
pushCommand.setRemote("origin").setRefSpecs(new RefSpec(branch + ":" + branch));
pushCommand.setForce(true).setPushAll();
pushCommand.setCredentialsProvider(credentialsProvider);
pushCommand.call();
} catch (GitAPIException | IOException e) {
System.out.println("Error when backing up file to git" + e.getMessage());
}
}
}
Để có thể push tập tin này vào Git :
- Trước hết ta tạo một thư mục repository ở local để có thể clone repository từ depos Git về đây.
- Nếu đã có một repos git ở thư mục này từ trước rồi thì ta phải xóa nó đi, rồi tạo mới lại thư mục vì không khi clone sẽ báo lỗi.
- Tiếp theo ta clone về nhánh Git mà ta cần lưu tập tin vừa tạo.
- Sao chép tập tin cần lưu vào repos Git ở local này.
- Commit tập tin này vào repos local.
- Sau đó push nó vào repos ở xa.
Không có nhận xét nào:
Đăng nhận xét