This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TodoList.cpp
113 lines (91 loc) · 2.25 KB
/
TodoList.cpp
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "TodoList.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
TodoList::TodoList() {
path = std::string(getenv("HOME")) + "/todo.txt";
parse();
}
void TodoList::add(std::string task) {
if (task.find_first_not_of("1234567890. ") == std::string::npos) return;
std::cout << "Added #" << first_unset() << ": " << task << std::endl;
tasks.insert(std::make_pair(first_unset(), task));
write();
}
void TodoList::erase(int num) {
if (tasks.count(num)) {
std::cout << "Erased #" << num << ": " << tasks[num] << std::endl;
tasks.erase(num);
write();
} else {
std::cerr << "There is no task #" << num << "." << std::endl;
}
}
std::string TodoList::get(int num) {
std::ostringstream oss;
oss << num;
oss << ". ";
oss << tasks[num];
return oss.str();
}
void TodoList::dump() {
tmap::iterator it;
for (it = tasks.begin(); it != tasks.end(); ++it) {
std::cout << get(it->first) << std::endl;
}
}
std::map<int, std::string>::size_type TodoList::count() {
return tasks.size();
}
void TodoList::reorder() {
int i = 1;
tmap tnew;
tmap::iterator it;
for (it = tasks.begin(); it != tasks.end(); ++it) {
tnew[i] = it->second;
i++;
}
tasks = tnew;
write();
}
void TodoList::parse() {
tasks.clear();
std::ifstream ifs(path.c_str());
if (!ifs.good()) {
std::cerr << "Fatal: Can't open " << path.c_str() << "." << std::endl;
exit(1);
}
while (ifs.good()) {
std::string line = "";
getline(ifs, line);
if (line != "") {
int taskno = atoi(line.c_str());
std::string::size_type taskdesc = line.find_first_not_of("1234567890. ");
if (taskdesc == std::string::npos) continue;
tasks[taskno] = std::string(line, taskdesc);
}
}
}
void TodoList::edit() {
std::string cmd = "env $EDITOR " + path;
system(cmd.c_str());
}
void TodoList::write() {
std::ofstream ofs(path.c_str());
tmap::iterator it;
for (it = tasks.begin(); it != tasks.end(); ++it) {
ofs << get(it->first) << std::endl;
}
ofs.close();
}
int TodoList::first_unset() {
if (tasks.size()) {
for (int i = 1; i < tasks.rbegin()->first; i++) {
if (!tasks.count(i)) return i;
}
return tasks.rbegin()->first + 1;
} else {
return 1;
}
}