-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit.cpp
More file actions
68 lines (59 loc) · 1.82 KB
/
commit.cpp
File metadata and controls
68 lines (59 loc) · 1.82 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
string getCurrentBranch() {
ifstream headIn(HEAD_FILE);
string branch;
getline(headIn, branch);
return branch;
}
string getBranchHead(const string& branchName) {
ifstream branchesIn(BRANCHES_FILE);
string line;
while (getline(branchesIn, line)) {
size_t sep = line.find(":");
if (line.substr(0, sep) == branchName) {
return line.substr(sep + 1);
}
}
return "null";
}
void updateBranchHead(const string& branch, const string& newHash) {
ifstream in(BRANCHES_FILE);
stringstream updated;
string line;
while (getline(in, line)) {
size_t sep = line.find(":");
string name = line.substr(0, sep);
if (name == branch) {
updated << name << ":" << newHash << "\n";
} else {
updated << line << "\n";
}
}
ofstream out(BRANCHES_FILE);
out << updated.str();
}
void commit(const string& message) {
ifstream indexIn(INDEX_FILE);
if (!indexIn) {
cout << "There is nothing to commit." << endl;
return;
}
stringstream commitData;
string line;
while (getline(indexIn, line)) {
commitData << line << endl;
}
string timestamp = getCurrentTime();
string branch = getCurrentBranch();
string parent = getBranchHead(branch);
string metadata = "message: " + message + "\n" +
"timestamp: " + timestamp +
"parent: " + parent + "\n" +
"branch: " + branch + "\n";
string commitHash = Hash(metadata + commitData.str());
ofstream commitOut(COMMITS_DIR + "/" + commitHash);
commitOut << metadata;
commitOut << commitData.str();
updateBranchHead(branch, commitHash);
ofstream(INDEX_FILE); // clear staging area
cout << "Committed. Hash: " << commitHash << endl;
}