Skip to content

Commit e4a89d9

Browse files
committed
diff: Add --cached option and take index into account
1 parent a28ac5c commit e4a89d9

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

src/main/java/club/qqtim/command/Diff.java

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
import club.qqtim.common.ConstantVal;
44
import club.qqtim.context.ZitContext;
5-
import club.qqtim.converter.IdConverter;
6-
import club.qqtim.data.CommitObject;
75
import club.qqtim.diff.DiffUtil;
6+
import club.qqtim.util.FileUtil;
7+
import com.google.gson.Gson;
88
import lombok.Data;
99
import lombok.extern.slf4j.Slf4j;
1010
import picocli.CommandLine;
@@ -34,15 +34,38 @@
3434
@CommandLine.Command(name = "diff")
3535
public class Diff implements Callable<String> {
3636

37-
@CommandLine.Parameters(index = "0", defaultValue = ConstantVal.HEAD_ALIAS, converter = IdConverter.class)
38-
private String id;
37+
@CommandLine.Option(names = {"--cached"})
38+
private boolean cached = false;
39+
40+
41+
@CommandLine.Option(names = {"--commit"})
42+
private String commit;
3943

4044

4145
@Override
4246
public String call() {
43-
final CommitObject commit = Commit.getCommit(id);
44-
final String diffChanges = DiffUtil.diffTrees(
45-
ReadTree.getTree(commit.getTree()), getWorkingTree());
47+
String objectId;
48+
Map<String, String> treeFrom = new HashMap<>(), treeTo;
49+
if (this.commit != null) {
50+
objectId = ZitContext.getId(this.commit);
51+
treeFrom = ReadTree.getTree(Commit.getCommit(objectId).getTree());
52+
}
53+
final String indexContent = FileUtil.getFileAsString(ConstantVal.INDEX, ConstantVal.NONE);
54+
55+
if (cached) {
56+
treeTo = new Gson().fromJson(indexContent, Map.class);
57+
if (this.commit == null) {
58+
objectId = ZitContext.getId(ConstantVal.HEAD_ALIAS);
59+
treeFrom = ReadTree.getTree(Commit.getCommit(objectId).getTree());
60+
}
61+
} else {
62+
treeTo = Diff.getWorkingTree();
63+
if (this.commit == null) {
64+
treeFrom = new Gson().fromJson(indexContent, Map.class);
65+
}
66+
}
67+
68+
final String diffChanges = DiffUtil.diffTrees(treeFrom, treeTo);
4669
log.info(diffChanges);
4770
return diffChanges;
4871
}

0 commit comments

Comments
 (0)