-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGitWrapper.java
More file actions
83 lines (77 loc) · 2.9 KB
/
GitWrapper.java
File metadata and controls
83 lines (77 loc) · 2.9 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.File;
import java.io.IOException;
public class GitWrapper {
/**
* Initializes a new Git repository.
* This method creates the necessary directory structure
* and initial files (index, HEAD) required for a Git repository.
*/
public void init() {
Git.deleteIfExists(Git.git);
Git.git = Git.makeFolder("git");
Git.objects = Git.makeFolder("objects", Git.git);
try {
Git.index = Git.makeFile("index", Git.git);
Git.HEAD = Git.makeFile("HEAD", Git.git);
} catch (IOException e) {
throw new RuntimeException("Failed to initialize Git repository", e);
}
};
/**
* Stages a file for the next commit.
* This method adds a file to the index file.
* If the file does not exist, it throws an IOException.
* If the file is a directory, it throws an IOException.
* If the file is already in the index, it does nothing.
* If the file is successfully staged, it creates a blob for the file.
* @param filePath The path to the file to be staged.
*/
public void add(String filePath) {
File f = new File(filePath);
if (!f.exists() || !f.isFile()) throw new IllegalArgumentException("File has to exist and be a file " + filePath);
try {
Git.addToIndex(f);
} catch (IOException e) {
throw new RuntimeException("Failed add file to index " + filePath, e);
}
};
/**
* Creates a commit with the given author and message.
* It should capture the current state of the repository by building trees based on the index file,
* writing the tree to the objects directory,
* writing the commit to the objects directory,
* updating the HEAD file,
* and returning the commit hash.
*
* The commit should be formatted as follows:
* tree: <tree_sha>
* parent: <parent_sha>
* author: <author>
* date: <date>
* summary: <summary>
*
* @param author The name of the author making the commit.
* @param message The commit message describing the changes.
* @return The SHA1 hash of the new commit.
*/
public String commit(String author, String message) {
try {
return Git.commit(author, message);
} catch (IOException e) {
throw new RuntimeException("Failed to create commit", e);
}
};
/**
* EXTRA CREDIT:
* Checks out a specific commit given its hash.
* This method should read the HEAD file to determine the "checked out" commit.
* Then it should update the working directory to match the
* state of the repository at that commit by tracing through the root tree and
* all its children.
*
* @param commitHash The SHA1 hash of the commit to check out.
*/
public void checkout(String commitHash) {
// to-do: implement functionality here
};
}