forked from reposense/RepoSense
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GitCheckout.java
64 lines (52 loc) · 2.01 KB
/
GitCheckout.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package reposense.git;
import static reposense.system.CommandRunner.runCommand;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.logging.Logger;
import reposense.commits.model.CommitResult;
import reposense.system.LogsManager;
/**
* Contains git checkout related functionalities.
* Git branch is responsible for switch branches, revision or restore working tree files.
*/
public class GitCheckout {
private static final Logger logger = LogsManager.getLogger(GitCheckout.class);
public static void checkoutRecentBranch(String root) {
checkout(root, "-");
}
public static void checkoutBranch(String root, String branch) {
checkout(root, branch);
}
/**
* Checkouts to the hash revision given in the {@code commit}.
*/
public static void checkoutCommit(String root, CommitResult commit) {
logger.info("Checking out " + commit.getHash() + "time:" + commit.getTime());
checkout(root, commit.getHash());
}
/**
* Checkouts to the given {@code hash} revision.
*/
public static void checkout(String root, String hash) {
Path rootPath = Paths.get(root);
runCommand(rootPath, "git checkout " + hash);
}
/**
* Checks out to the latest commit before {@code untilDate} in {@code branchName} branch
* if {@code untilDate} is not null.
* @throws CommitNotFoundException if commits before {@code untilDate} cannot be found.
*/
public static void checkoutDate(String root, String branchName, Date untilDate) throws CommitNotFoundException {
if (untilDate == null) {
return;
}
String hash = GitRevList.getCommitHashUntilDate(root, branchName, untilDate);
if (hash.isEmpty()) {
throw new CommitNotFoundException("Commit before until date is not found.");
}
Path rootPath = Paths.get(root);
String checkoutCommand = "git checkout " + hash;
runCommand(rootPath, checkoutCommand);
}
}