# CS61B - Summary and Reflections on the Gitlet Project

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/gitlet-design-note/>). I am continuously working to improve the translation.

# Preface

I had long heard of the great fame of CS61B's Gitlet project, and with a rather apprehensive mindset, I put it off until I had finished all the material up to (but not including) sorting before starting to write Gitlet. As it turned out, I was right—this project is quite comprehensive, and the payoff is substantial. Below I mainly record some of my thoughts and the pitfalls I stumbled into, hoping it can help you all.

**This article is actually a bit stream-of-consciousness; it's mainly a record of my own thoughts and isn't really suitable as a complete tutorial. However, if you find that your approach matches what I consider to be a wrong approach, you can cut your losses in time.**

<img src="https://image.wendaining.top/image-20251109114814513.png" style="zoom:50%;" />

# Common Pitfalls and Suggestions:

1. **Read through the spec first**! Even if you remember nothing after reading it, having a rough impression is always good—it helps you design from a high-level perspective at the very beginning.
2. File contents themselves do not need to be serialized; Java objects (such as Blob, Commit) need to be serialized in order to be saved.
3. Read carefully the part of the Spec about serialization. You need to realize that when these classes store information about other objects, they should store the corresponding hashes, and then read the objects directly from the file system when they are needed.
4. `writeObject()` is used for serialization, and `readObject()` is used for deserialization.
5. `writeObject` is used to save Java objects (serialization); `writeContents` is used to save plain text or binary content.
6. For the persistence of `Commit` and `Blob`, you cannot directly use `sha1(this)`, because it cannot guarantee that identical content <-> identical hash values. You need to write it by hand, and **more importantly, `sha1()` only supports hashing String and byte[] types**.
7. The `Repository` class does not need to be instantiated! In fact, most classes don't need to be instantiated—everything is read from fixed file paths as objects, operated on, and then saved back with persistence! So all methods and members in Repo **should be static!**
8. Keeping the design style of your classes consistent is important.
9. There is a pitfall in `checkout` and `reset`: the check for the risk of untracked files being overwritten must be **performed before doing anything else**!
10. If you write a getter method that fetches an object by hash ID, be careful about the hardcoded path problem—meaning that inside this method, it should not default to only fetching `Commit` objects from the local path. Otherwise, when writing the EC part, you will habitually call this method and run into NPE problems. Of course, at that point you can also skip the getter method and read directly instead (in fact, that's what I did, but the code felt less elegant as a result).
11. For failure checks, think carefully about where to put them. I didn't think it through at first, and had checks both in the command methods themselves and in the `Main` class. In fact, this was redundant and inelegant. I suggest putting them all in the methods themselves—it's actually better.
12. Still on failure checks: you can abstract similar parts into various helper methods.
13. You can put commonly used methods into the `Utils` class, such as the `try-catch` when creating new files (once you write one file-creation routine, you'll know what I mean).
14. When starting your design, if you look at the real git directory, you'll notice that the `.git/objects/` folder actually uses chaining. I suggest you adopt this approach from the start, as it will make the prefix hash indexing easier later.
15. For commands involving `"--"`, remember to check its correctness.
16. If a string might be `null` and you want to check for equality, to avoid an NPE you can call `Objects.equals(...)` instead of `String.equals()`.

# Initial Design—Module Division

**First of all, I strongly recommend watching these four videos** (**if the YouTube links are down, there are archives on Bilibili**)

<img src="https://image.wendaining.top/image-20251108235556246.png" style="zoom:25%;" />

They can help you build a correct understanding of concepts like Commit, Branch, Blob, and Staging Area—**extremely, extremely important**!

Our skeleton basically only provides the `Main`, `Repository` (hereafter abbreviated as `Repo`), and `Commit` classes. The `Main` class goes without saying, and the spec also gives us the suggestion: "You may, of course, write additional Java classes to support your project or remove our suggested classes if you'd like." So, based on my shallow understanding that "Java is a purely OOP language," and with reference to the real `.git` folder, my final implementation includes these classes:

- Main
- Repo
- Commit
- Blob
- Branches
- Head
- StagingArea
- Remote (useful for the EC)

And the `.gitlet` folder is designed as follows:

```TEXT
- .gitlet
	- objects
		- commits
		- blobs
	- HEAD
	- branches
	- staging_area
	- remote
```

> One more reminder here: referring to the real git directory, the `.git/objects/` folder uses chaining. You can adopt this design from the very beginning, and it will greatly improve your Gitlet's performance later.

**But, but—by the time I finished writing, I found that in fact only the Commit and Blob classes were useful; the rest only brought me more pain and could have been entirely merged into the Repo class. And these classes can actually be divided into two categories based on this, which I'll mention shortly**.

## Design of Each Class

### Commit

It mainly has these members:

```java
/**
 * The message of this Commit.
 */
private final String message;
/**
 * The first father of this commit (ID)
 */
private final String parent;
/**
 * The second father of this commit(ID), only appears when merge happens
 */
private final String secondParent;
/**
 * storage blob. Key: fileName, Value: the SHA1 hash of a blob
 */
private final TreeMap<String, String> blobs;
/**
 * The timestamp of this commit
 */
private Date timestamp;
/**
 * the SHA1 hash of this object
 */
```

Take a close look at how I wrote the hash computation:

```java
public String getID() {
    StringBuilder blobStr = new StringBuilder();
    for (Map.Entry<String, String> entry : blobs.entrySet()) {
        blobStr.append(entry.getKey() + entry.getValue());
    }
    String parStr = (parent == null) ? "" : parent;
    String secondParStr = (secondParent == null) ? "" : secondParent;
    String timeStampStr = Long.toString(timestamp.getTime());
    return Utils.sha1(message, parStr, secondParStr, blobStr.toString(), timeStampStr);
}
```

### Blob

```java
private final String filename;
private final byte[] content;
```

The hash computation:

```java
public String getID() {
    return Utils.sha1(filename, content);
}
```

### Head

```java
private String curBranch;
```

### Branches

```java
private TreeMap<String, String> branches;
```

### StagingArea

```Java
/**
 * filename -> blob id
 */
private TreeMap<String, String> stagedFiles;
/**
 * files staged for removal
 */
private TreeSet<String> removedFiles;
```

### Remote

```java
private TreeMap<String, String> remote;
```

## Drawbacks of Splitting into Many Classes

### Initial Thinking

How did I think about it at first? I felt that a Commit contains a lot of necessary information, such as the commit message, the two parent commits (their IDs), the timestamp, and the mapping of Blobs—so obviously creating a class for it seemed good. By the same logic, I extended this to all the remaining structures that needed persistence.

But if you think carefully, you'll find that the existence of `Commit` and `Blob` is necessary, whereas the necessity of `Head`, `Branches`, and `StagingArea` is not that high.

First, `Commit` and `Blob` are classes that get used over and over, whereas `Head`, `Branches`, and `StagingArea` are classes that, once instantiated, will never be instantiated again—afterwards, at most you modify that single object and save it. Second, the essence of these classes is just pointers to some things, and `Head` even more so—it's literally just a `String currentBranchName`. The only benefit of writing them as three separate classes might be convenience of persistence (because you can just write a `save()` that writes `this` directly).

Therefore, I believe that for the latter three classes, the correct approach is to create the files for these things in the `init` method of `Repo`, and afterwards just read from them directly. As for the corresponding persistence methods, in the `Repo` class you can write something like

```java
private static void saveHead(String newBranchName) {
	Utils.writeObject(HEAD_DIR, newBranchName);
}
```

and that's it.

Moreover, splitting into many classes has these other drawbacks:

### Possible Piling Up of `getter` Methods

If you make the core data structures inside these classes `private` (for example, the core data structure of the `Branches` class is `private TreeMap<String, String> branches`), then you need to write many long, ugly getter methods, and these getter methods written in the Repo class will pile up to be very long, for example:

```java
public static commit getHeadCommit() {
	return Utils.readObject(join(COMMITS_DIR, Branches.getBranches().getCommitID(Head.getHead().getCurrentBranch())), Commit.class);
}
```

Then you'll go on to think about writing getters for getters to reduce the logic inside, e.g., writing a `getCommitByID()` method for the Commit class for the code above, and a getter method for the `Branches` class. But this brings new problems:

### Syntactic Sugar with Redundant Logic

Repeatedly writing many `getter` methods is essentially writing yourself a pile of syntactic sugar with redundant logic. By the time you finish writing, you'll forget you wrote this thing, and then reinvent many wheels. From a coding perspective, this is absolutely inelegant.

But this is actually quite ugly, and it will bring many inexplicable problems later, for example:

```Java
/** 获取这个分支上的最新提交的ID
 *
 * @param branch
 */
public String getCommitID(String branch) {
    return branches.get(branch);
}
/** 获取当前分支上的最新提交
 *
 * @param branch
 */
public Commit getCommit(String branch) {
    return Commit.getCommitByID(getCommitID(branch));
}
```

### Reinventing Inexplicable Wheels

For example:

```Java
public void put(String key, String value) {
    branches.put(key, value);
    save();
}
```

### Not Knowing Where to Put Helper Methods

Let me use a personal journey from my own writing process as an example.

At the beginning, I put all the methods that read objects from the file system and return the objects themselves in the Repo class, for example:

```Java
public static Branches getBranches() {
    return Utils.readObject(BRANCHES_DIR, Branches.class);
}
```

But for some reason, I later felt that since these methods relate to a particular class, I should move them into the corresponding classes, so I migrated these methods into their respective classes.

**But in reality, as you keep writing, you'll find that for many methods, you simply don't know where they should go**! For example, `getHeadCommit`, which gets the latest commit of the current branch—should it go in the `Repo` class, the `Head` class, or the `Branches` class? I ended up putting it in the `Branches` class, but I couldn't convince myself why—it was all very forced. This also means that later, when you want to call the corresponding method, you won't even know which class it belongs to. **In my opinion, it would be better to put everything in the `Repo` class**.

### Solutions to the Drawbacks While Keeping the Multi-Class Division

However, the above drawbacks can actually be solved while still writing multiple classes:

- You can solve it by making all members `public`.
- You can solve it by putting all helper methods in the `Repo` class, since the members are all `public` and can be accessed directly.

However, I only realized this when I was almost done writing—the mountain of code had piled up, and it was too late to turn back. So for the rest of this article, I'll still present things in terms of the multi-class structure.

# Implementation of Each Command

I'll only cover the general ideas.

## init

Just create the series of file system structures, then create the initial commit. **Pay attention to the failure checks.**

Here you need to create the files for all the classes mentioned above that only need to be instantiated once. In my multi-class approach, I did this in the constructor; if you didn't write many classes, you need to `new` an object (the corresponding core member) in the `init` method and then write it to a file.

**Here you may need to write a dedicated no-argument constructor for `Commit`.**

## add

My `add` and `rm` methods are mainly written in the `StagingArea` class, with the `Repo` class just making a simple call, but the core idea remains the same either way.

It roughly breaks down into the following steps:

1. First, search under the CWD to see whether the file exists.
2. If the file exists, whether to create a new `Blob` depends on whether the file has actually been modified. The criterion for judging whether the file has been modified: whether the `blobID` is the same (**this involves the requirements for writing the hash functions of the `Commit` and `Blob` classes mentioned in the initial notes**).
3. (As for the logic of whether to create a new `Blob`, I wrote it in the `Blob` class's constructor: if `join(DIR, sha1(filename, content)).exists()` in the file directory, then do nothing.)
4. If the file exists in the HEAD commit with the same content, do nothing.
5. Otherwise, the file has been modified or is new, so do a `stagedFiles.put(filename, curBlobId);`
6. Finally, you also need `removedFiles.remove(filename)`.
7. Remember to maintain persistence.

## rm

Very similar to add, with the core logic as follows:

1. If the file is currently staged for addition, unstage it.
2. If the file is tracked by the HEAD commit (the current commit), add it to the removal set, then delete it from the file system.
3. If the user has not yet deleted the file, remove it from the working directory; **do not delete the file unless it is tracked in the current commit**.
4. If the file is neither in the staging area nor tracked by the HEAD commit, report an error.
5. Finally, remember to maintain persistence.

## commit

Essentially, you construct the contents of the staging area through a `Commit` class constructor, and at the end remember to clear the staging area and update the `Head` pointer.

Roughly: first, push in all the `Blob`s of the parent node, skipping those that are "staged for removal";

Then push in all the `Blob`s of the `stagedFiles` in the staging area;

Finally, take the timestamp, persist, clear the staging area, and update the `Head` pointer.

## log

Essentially, you only need to get all the commits on the current branch (a linked list)—a simple loop suffices.

Get the latest head commit, trace back all the way, and print the information of each `Commit`.

> Printing Commit information here may cause problems, so a hint: mainly two points. First, to determine whether this is a merge node, just check whether both parent commits exist. Second, there's the locale issue—when printing the timestamp, you need to set `Locale.ENGLISH`.

## global-log

The spec hints that there's a method in `Utils` you can use directly. I'm too lazy to explain here, so I'll just present my implementation:

```Java
public static void globalLog() {
    List<String> commitHistory = Utils.plainFilenamesIn(Commit.DIR);
    if (commitHistory != null) {
        for (String commitID : commitHistory) {
            Commit.getCommitByID(commitID).printSingleLog();
        }
    }
}
```

## find

Also quite simple; using the same method from `Utils` makes it easy. Here's my implementation directly:

```java
public static void find(String message) {
    List<String> commitHistory = Utils.plainFilenamesIn(Commit.DIR);
    boolean flag = false;
    if (commitHistory != null) {
        for (String commitID : commitHistory) {
            if (Commit.getCommitByID(commitID).getMessage().equals(message)) {
                flag = true;
                System.out.println(commitID);
            }
        }
    }
    if (!flag) {
        exitWithError("Found no commit with that message.");
    }
}
```

## status

A rather complex command that can be divided into two parts: **printing branches** and **printing the staging area**. Printing the staging area can in turn be divided into four parts: `stagedFiles`, `removedFiles`, `Modifications Not Staged For Commit`, and `Untracked files`—so let's discuss it in six parts for now.

**Note that all these strings must be printed in lexicographic order.**

### Printing Branches

Nothing much to say—just iterate over the branches map, but note that the strings must be printed in lexicographic order, and the `*` for the current branch doesn't count in the ordering (it doesn't affect sorting). **If you read what the spec says:**

> Be careful using a `HashMap` when serializing! The order of things within the `HashMap` is non-deterministic. The solution is to use a `TreeMap` which will always have the same order.

Then simply iterating will give you lexicographic order.

### Printing staged files

Actually very simple—just iterate over the `stagedFiles` hash. But here you can note the syntax for iterating over a `Map` in Java:

```Java
    for (Map.Entry<String, String> entry : stagedFiles.entrySet()) {
        String filename = entry.getKey();
        System.out.println(filename);
    }
```

and

```Java
    for (String filename : stagedFiles.keySet()) {
        System.out.println(filename);
    }
```

Obviously the latter is more elegant.

###  Printing removed files

Almost no different from printing staged files, so I'll skip it.

### Printing Modifications Not Staged For Commit

This part is more complicated. According to the spec, a file is "Modifications Not Staged For Commit" if it satisfies any one of the following four conditions:
1. Tracked in the current latest commit, modified in the CWD, but not yet added.
2. Already added, but modified again after being added.
3. Already added, but now deleted (the file no longer exists in the CWD).
4. Tracked in the current latest commit, not yet added/rm'd, but now deleted (disappeared from the CWD).

So you can first iterate over all files tracked by the current latest commit, handling cases 1 and 4; then iterate over the currently added entries, handling cases 2 and 3.

Among these, judging whether a file has been modified means checking whether the computed blobID is the same, **but here you cannot directly create a new blob, because the work of creating blobs is done in the `add` method**. Consider it from another angle: the status method is just a "read-only" method for getting the current state—how could it change file contents?

One more point: in both loops, if you find that the current file has already been "staged for removal," i.e., `removedFiles.contains(filename)`, **skip it directly**! This is actually not hard to understand—if it has already been pushed into `removedFiles`, how could it still count as a modification "not staged for commit"?

### Printing Untracked Files

Use the method in `Utils` to get all filenames in the CWD; if a file exists neither in `stagedFiles` nor in the head commit, print its filename.

**You need to sort the `List` of all filenames obtained from the `Utils` method first**.

## checkout

Another major highlight. It has three usages:

1. `java gitlet.Main checkout -- [file name]`
2. `java gitlet.Main checkout [commit id] -- [file name]`
3. `java gitlet.Main checkout [branch name]`

We'll solve it in three parts.

**One more reminder of the pitfall: remember to check the correctness of `"--"`!**

### checkout -- [file name]

Roughly, take the file named filename from the head commit, write it into the CWD or overwrite the file with the same name in the CWD, and do not stage the new version of the file.

Just follow the description here, but I recommend writing this helper method in `Utils`:

```Java
public static void overwriteFile(File file, byte[] content) {
    try {
        if (!file.exists()) {
            file.createNewFile();
        }
        Utils.writeContents(file, content);
    } catch (IOException e) {
        Utils.exitWithError(e.toString());
    }
}
```

Meaning: if the file doesn't exist, create it and write the content; otherwise overwrite the content. This logic will be used frequently later.

### checkout [commit id] -- [file name]

There's a special point here: **commit ids support prefix indexing**. The spec hints at looking at the real .git directory here—now you should understand why I suggested implementing chained indexing at the start. I recommend writing a helper method `convertPrefixToCommitID`.

A straightforward brute-force implementation is still easy to write. However, the Spec doesn't seem to mention what to do if the commit obtained by the prefix hash is not unique. I wrote a failure exit for this myself, and the Gradescope test cases didn't seem to cover this situation either.

Back to the command itself: roughly, get the specified file from the commit with the specified `targetIDprefix`, and write/overwrite it into the CWD. Nothing much to say—just follow the instructions. **By this point, you should theoretically have accumulated many convenient helper methods—things like "check whether a file exists in a commit," "get the Blob by filename," and "get file contents from a Blob" should all be readily writable by now.**

### checkout [branch name]

Roughly, it breaks down into these points: take all files from the head commit of this branch and write (overwrite) them into the CWD, delete all files in the CWD that are tracked in the current branch but don't exist in the target branch, and finally point the head pointer to the branch name. Unless the checked-out branch is the current branch, the staging area will be cleared.

We notice that this is essentially taking a specific commit and restoring the entire working directory to the state it was in at that specific commit. Suppose we read the spec thoroughly in advance—we'd realize that the later reset command also needs something similar, so we can abstract this into a helper method `restoreCommitSnapshot`.

Its implementation roughly consists of 4 steps:

1. Check whether any untracked files would be overwritten.
2. Write/overwrite all files of the target Commit.
3. Delete files that exist in the current commit but not in the target commit (here you can call the `Utils.restrictedDelete` method).

As for step one, it was mentioned in the initial pitfalls section, and similar checks will be used repeatedly later, so I suggest writing it as a helper method. Here's my implementation:

```Java
public static void checkUntrackedFiles(Commit target, Commit current) {
    for (String filename : target.getBlobs().keySet()) {
        File file = Utils.join(CWD, filename);
        if (file.exists() && file.isFile() && !current.hasFile(filename)) {
            Utils.exitWithError("There is an untracked file in the way; "
                    + "delete it, or add and commit it first.");
        }
    }
}
```

**Be sure to perform this check before executing steps 2 and 3.**

After restoring the working directory, don't forget to **change the branch the current head pointer points to, and clear the staging area.**

## branch

Here, compared to coding, what matters more is understanding the concept. The spec explains it in great detail; if you understand it, it's really just a one-liner.

```java
branches.put(branchName, headCommitID);
```

Quoting the spec here, also to remind readers to check their earlier implementation:

> Make *sure* that the behavior of your `branch`, `checkout`, and `commit` match what we've described above. This is pretty core functionality of Gitlet that many other commands will depend upon. If any of this core functionality is broken, very many of our autograder tests won't work!

## rm-branch

Same as above—once you understand the concept, it's a one-liner. **Of course, pay attention to failure handling.**

```Java
branches.remove(branchName);
```

## reset

Given a commit id (possibly a prefix), restore the working directory to the state at that time, while also changing the commit the current head pointer points to, and clearing the staging area.

It's almost exactly the same as checkout [branch name]. Just reuse the code. You could even rewrite checkout [branch name] as first finding the branch's head commit and then calling the reset method.

**Why didn't I put "changing the commit the current head pointer points to, and clearing the staging area" into `restoreCommitSnapshot`? Because the logic for modifying the head pointer differs between the two. checkout [branch name] only needs to point the head pointer to the given branch name; whereas reset needs `branches.put(curBranchName, targetCommitID);`**

## merge

**The most complex command, and prone to many bugs—read with patience.**

First, reading the Spec, we find there's a very important concept: the split point. So naturally we'd consider writing a helper method to find the split point of two commits. The specific idea is as follows:

1. Suppose we have two Commits, `c1` and `c2`. First, use DFS to find the set `anc1` of all ancestors of `c1`. Here I suggest converting the recursion into a stack-based form, and writing a helper method that returns a `Set<String>`.
2. Then, use BFS to traverse all ancestors of c2; as soon as during the traversal you find `anc1.contains(c2的某个祖先)`, return that commit directly. Since it's BFS, this process guarantees we get the closest common ancestor.

Then, start handling a series of special cases:

- First, the various failure cases—just check them in order according to the spec.
- Then find the split point commit, and make some further checks.
- First, if the split point commit (`split`) is the given commit (`given`), print `"Given branch is an ancestor of the current branch."` and exit.
- Then there's the fast-forward case: the head pointer is far behind the latest commit, and the head pointer points exactly at the split point. In that case, just move the head pointer forward all the way—aptly called a fast-forward.
    **Here you absolutely, absolutely must check in advance whether untracked files would be overwritten, i.e., call `checkUntrackedFiles()`!**

Then we enter the core `merge` phase. Here we also need to sort out the logic. My thinking was as follows:

All the code mentioned above is in the `merge` method of the `Repo` class. Next, I write another `merge` method in the `Commit` class, whose main purpose is to update the staging area according to the spec's logic.

Finally, back in the `Repo` class, call the constructor to get the new `Commit`.

Now let's focus on writing `public static boolean merge(Commit head, Commit given, Commit split)` in the `Commit` class:

The Spec lists **8 cases**, but you can think about it this way:

- First, get the sets of all filenames of the head commit, the given commit, and the split point commit, then iterate over them, roughly:

    ```Java
    Set<String> filenames = new HashSet<>();
    filenames.addAll(head.blobs.keySet());
    filenames.addAll(given.blobs.keySet());
    filenames.addAll(split.blobs.keySet());
    ```

- In each iteration, let `String H` be the blobID in the head commit, `G` the one in the given commit, and `S` the one in the split point commit;

- Draw a table covering the equality and inequality relationships among `H`, `G`, and `S`, roughly as follows:

    | **Check Order** | **Condition (relationship among H, G, S)**                   | **Logic in Code**           | **Meaning (Action)**                                         |
    | ------------ | ------------------------------------------------------------ | --------------------------- | ------------------------------------------------------------ |
    | **1**        | `H == G`   (H and G are the same)                            | `if (Objects.equals(H, G))` | `continue;`   **(Do Nothing / Follow Head)**                 |
    | **2**        | `H != G` and `H == S`   (Head unchanged, Given changed)      | `if (Objects.equals(H, S))` | (divided into two cases)                                     |
    | **2a**       | (continuing) ...and `G != null`                              | `if (G != null)`            | Change the specified file (by filename) to `G`'s content   **(Take Given's Version)** |
    | **2b**       | (continuing) ...and `G == null`                              | `else`                      | `stagingArea().rm(name);`   **(Delete File)**                |
    | **3**        | `H != G` and `H != S` and `G == S`   (Head changed, Given unchanged) | `if (Objects.equals(G, S))` | `continue;`   **(Do Nothing / Follow Head)**                 |
    | **4**        | `H != G` and `H != S` and `G != S`   (all parties differ)    | `else` (all checks fail)    | `writeConflictFile(name, H, G);`   **(Conflict)**            |

- You'll notice that in fact many cases end up following the head commit, which means you don't need to do anything at all.

Next comes yet another difficulty: how to handle conflicting commits? Actually the spec describes this in great detail too; the only difficulty might be handling possibly empty files. My suggestion here is: first initialize two `""` strings, and only if the corresponding `blobID != null`, read its content. Finally, organize the conflict file's format as required by the spec and write it out—**and don't forget to add it to the staging area at the end.**

Back in the `Repo` class: after calling the `merge` method in `Commit.java`, the staging area has been correctly handled. Next, call the `Commit` constructor, then update `HEAD`, clear the staging area, and print `"Encountered a merge conflict."` depending on whether there was a merge conflict.

> One point worth mentioning here: since Java doesn't support default parameters for functions, you may need to write another constructor for the `Commit` class to support correctly setting the second parent commit.

Having written up to here, congratulations—the 1600 points are in your pocket! *Of course, mind the Style check.*

## add-remote

At this point, instead of directly explaining how to write the command, let me first establish a correct understanding of the Remote concept.

Remote is essentially very similar to Branches—it's really just a `TreeMap<String, String> remote`, except it maps remote names to specific paths.

Once you understand this, many of the helper methods in `Branches.java` can be pulled over and used directly (of course, even better is if you followed my earlier advice and didn't create so many classes and private members, in which case you wouldn't need helper methods at all).

**One very important point: generally, in the Branches class, anything that changes the commit tree calls `save()` to persist. But `save()`'s path usually depends on the CWD, so for the remote part, we need to persist manually—don't forget!**

One more point worth mentioning: the spec says

> Have your program convert all the forward slashes into the path separator character (forward slash on Unix and backslash on Windows). Java helpfully defines the class variable `java.io.File.separator` as this character.

Here we can write a helper method in `Utils`:

```Java
public static String normalizePath(String remoteDir) {
    return remoteDir.replace("/", File.separator);
}
```

This directly implements the conversion.

Once you understand the concept, this command is actually very simple to implement—after converting the path, just `put` it in.

## rm-remote

Also very simple—after doing the corresponding failure checks, just `remote.remove(remoteName);` and you're done.
## push

Yet another rather complex command.

First, quite naturally, by reading from the file system, we obtain a whole bunch of related objects that are convenient to work with.

**There are a few points you must pay attention to here:**

1. The given `remote branch name` already includes the `./.gitlet/` part, so **you don't need to add it yourself**—otherwise it will become `./.gitlet/.gitlet/`

2. If, like me, you used the CWD in the `Repo` class as the base for reading operations on these basic classes, then when reading the various remote objects you'll run into path inconsistency problems. The solution is to not use helper methods, and instead read these objects directly with the most primitive methods in `Utils`, for example:

    ```java
    File remoteBranchesDir = join(remoteDir, "branches");
    Branches remoteBranches = readObject(remoteBranchesDir, Branches.class);
    ```

After obtaining the relevant `Commit headCommit`, `Branches remoteBranches`, `Commit remoteHeadCommit`, and so on, we start analyzing the logic.

The premise of the so-called push operation is that `remoteHeadCommit` is an ancestor of the local head commit `headCommit`, and then all parts of the commit tree after that commit are copied over to the remote.

First, check the premise. Here we can call the method we wrote earlier in the merge section that gets the set of all ancestors of a given commit, and the check becomes effortless.

Then comes the copying part: here we face a core problem—how do we copy **all** commits that exist locally but not remotely?

> You can write a `public static void copyObject(File f1, File f2) {}` method in `Utils` that copies file `f1` into directory `f2`.

A common pitfall is to only backtrack along the first parent commit. **This approach is wrong**, because it will completely miss all the history of the second parent branch of merge commits.

The correct approach is still to use a DFS traversal: we initialize a `Stack` and push the ID of the local `headCommit` onto it.

Then we start the loop while the stack is non-empty:

- Pop a `commitID`;
- Check whether `commitID` equals `remoteHeadID`. If so, it means the remote repository already has this commit and all of its ancestors, so `continue` to stop searching along this path.
- If it is not `remoteHeadID`, this means it's a new commit the remote repository needs, so load this `Commit` and all the `Blob`s it points to from the local repository, and copy these object files (the Commit and Blobs) into the remote repository's corresponding `remoteCommitsDir` and `remoteBlobsDir` directories.
- Finally, push both parents of the current `commitID` onto the stack

Finally, update the remote pointer, **and complete the persistence manually, for example:**

```Java
writeObject(remoteBranchesDir, remoteBranches);
```

## fetch

In fact it's very similar to push, or rather the reverse of it. Here the premise is that **the local repository is behind the remote**, so we copy files from the remote to the local. Just copy the logic from push; I won't go into detail here. **But be sure to pay attention to the difference between reading files from the remote repository and reading them locally.**

## pull

It's simply a piece of syntactic sugar that uses

```Java
public static void pull(String remoteName, String remoteBranchName) {
    fetch(remoteName, remoteBranchName);
    merge(remoteName + "/" + remoteBranchName);
}
```

the two together.

**At this point, the entire EC portion is complete.**

# Epilogue

Originally, because of all the schoolwork, CS61B was left aside for a while (though in reality it was only four or five days), but recently I picked it back up and finished it—perhaps a bit of escapism. I was swept up in all kinds of thoughts, such as "how low the quality of the school's courses is" and "my own thinking about grad school vs. employment," which made me want to find a place where I could temporarily set aside these distracting thoughts and immerse myself in something. But troubles will always find their way to you, and thinking about that made me feel a little like breaking down ;(

All in all, this project probably took me about 30 hours. I never used that Python-based integration tester at all—every test was typed by hand, and whenever I ran into really hard debugging problems I would occasionally put the AI through the wringer too. My skills still have a long way to go.

**Finally, thanks to UCB for providing such a wonderful course**
