-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatus_manager.py
More file actions
314 lines (251 loc) · 9.85 KB
/
status_manager.py
File metadata and controls
314 lines (251 loc) · 9.85 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""
状态管理模块
用于管理文件的完成状态,使用JSON文件作为数据库
"""
import json
import os
from pathlib import Path
from datetime import datetime
from typing import Dict, Optional, Any
class StatusManager:
"""文件完成状态管理器"""
def __init__(self, db_path: Optional[str] = None):
"""
初始化状态管理器
Args:
db_path: JSON数据库文件路径,如果为None则使用默认路径
(用户目录下的 .file_status.json)
"""
if db_path is None:
# 使用用户目录下的配置文件
user_dir = Path.home()
self.db_path = user_dir / ".file_status.json"
else:
self.db_path = Path(db_path)
# 确保数据库文件存在
self._ensure_db_exists()
def _ensure_db_exists(self):
"""确保数据库文件存在,如果不存在则创建空数据库"""
if not self.db_path.exists():
with open(self.db_path, 'w', encoding='utf-8') as f:
json.dump({}, f, ensure_ascii=False, indent=2)
def _normalize_path(self, file_path: str) -> str:
"""
规范化文件路径为绝对路径
Args:
file_path: 文件路径(相对或绝对)
Returns:
规范化后的绝对路径字符串
"""
return str(Path(file_path).resolve())
def _load_db(self) -> Dict[str, Any]:
"""加载JSON数据库"""
try:
with open(self.db_path, 'r', encoding='utf-8') as f:
return json.load(f)
except (json.JSONDecodeError, IOError) as e:
# 如果数据库损坏,创建新的
print(f"Warning: Database error, creating new database: {e}")
return {}
def _save_db(self, data: Dict[str, Any]):
"""保存JSON数据库"""
try:
with open(self.db_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except IOError as e:
raise IOError(f"Failed to save database: {e}")
def is_completed(self, file_path: str) -> bool:
"""
检查文件是否标记为完成
Args:
file_path: 文件路径
Returns:
True如果文件标记为完成,False否则
"""
normalized_path = self._normalize_path(file_path)
db = self._load_db()
if normalized_path in db:
return db[normalized_path].get("completed", False)
return False
def set_completed(self, file_path: str, completed: bool = True):
"""
设置文件的完成状态
Args:
file_path: 文件路径
completed: 是否完成,默认True
"""
normalized_path = self._normalize_path(file_path)
db = self._load_db()
if normalized_path not in db:
db[normalized_path] = {}
db[normalized_path]["completed"] = completed
db[normalized_path]["date"] = datetime.now().isoformat()
self._save_db(db)
def toggle_completed(self, file_path: str) -> bool:
"""
切换文件的完成状态
Args:
file_path: 文件路径
Returns:
切换后的完成状态
"""
current_status = self.is_completed(file_path)
new_status = not current_status
self.set_completed(file_path, new_status)
return new_status
def get_status(self, file_path: str) -> Optional[Dict[str, Any]]:
"""
获取文件的完整状态信息
Args:
file_path: 文件路径
Returns:
状态字典,包含completed和date,如果文件不存在则返回None
"""
normalized_path = self._normalize_path(file_path)
db = self._load_db()
return db.get(normalized_path)
def remove_status(self, file_path: str):
"""
移除文件的状态记录
Args:
file_path: 文件路径
"""
normalized_path = self._normalize_path(file_path)
db = self._load_db()
if normalized_path in db:
del db[normalized_path]
self._save_db(db)
def get_all_statuses(self) -> Dict[str, Dict[str, Any]]:
"""
获取所有文件的状态
Returns:
所有文件状态的字典
"""
return self._load_db()
def cleanup_missing_files(self):
"""
清理数据库中已经不存在的文件的记录
"""
db = self._load_db()
cleaned_db = {}
for file_path, status in db.items():
if os.path.exists(file_path):
cleaned_db[file_path] = status
if len(cleaned_db) != len(db):
self._save_db(cleaned_db)
return len(db) - len(cleaned_db)
return 0
# 文件名标记相关方法
# 使用明显的标记前缀,在文件资源管理器中易于识别
MARK_PREFIX = "✓完成 "
def _has_mark_prefix(self, file_path: str) -> bool:
"""检查文件名是否已有标记前缀"""
path_obj = Path(file_path)
file_name = path_obj.name
return file_name.startswith(self.MARK_PREFIX)
def _get_original_name(self, file_path: str) -> str:
"""获取去除标记前缀后的原始文件名"""
path_obj = Path(file_path)
file_name = path_obj.name
if file_name.startswith(self.MARK_PREFIX):
return file_name[len(self.MARK_PREFIX):]
return file_name
def _add_mark_to_filename(self, file_path: str) -> str:
"""
在文件名前添加完成标记前缀
Args:
file_path: 文件路径
Returns:
新的文件路径(如果已添加标记则返回原路径)
"""
if self._has_mark_prefix(file_path):
return file_path
path_obj = Path(file_path)
original_name = path_obj.name
new_name = self.MARK_PREFIX + original_name
new_path = path_obj.parent / new_name
try:
path_obj.rename(new_path)
return str(new_path)
except Exception as e:
raise IOError(f"无法重命名文件添加标记: {e}")
def _remove_mark_from_filename(self, file_path: str) -> str:
"""
从文件名中移除完成标记前缀
Args:
file_path: 文件路径
Returns:
新的文件路径(如果已移除标记则返回原路径)
"""
if not self._has_mark_prefix(file_path):
return file_path
path_obj = Path(file_path)
original_name = self._get_original_name(file_path)
new_path = path_obj.parent / original_name
try:
path_obj.rename(new_path)
return str(new_path)
except Exception as e:
raise IOError(f"无法重命名文件移除标记: {e}")
def set_completed_with_mark(self, file_path: str, completed: bool = True):
"""
设置文件的完成状态并更新文件名标记
Args:
file_path: 文件路径(可能已包含标记前缀)
completed: 是否完成,默认True
"""
normalized_path = self._normalize_path(file_path)
# 先更新文件名标记
try:
if completed:
# 添加标记(如果还没有)
new_path = self._add_mark_to_filename(normalized_path)
else:
# 移除标记(如果存在)
new_path = self._remove_mark_from_filename(normalized_path)
# 如果路径改变了,更新数据库中的路径
if new_path != normalized_path:
# 更新数据库:删除旧路径,添加新路径
db = self._load_db()
# 检查旧路径(可能是带标记或不带标记的)
old_path_in_db = None
for db_path in [normalized_path]:
if db_path in db:
old_path_in_db = db_path
break
if old_path_in_db:
status_data = db[old_path_in_db]
del db[old_path_in_db]
else:
status_data = {}
status_data["completed"] = completed
status_data["date"] = datetime.now().isoformat()
db[new_path] = status_data
self._save_db(db)
else:
# 路径没变,正常更新状态
self.set_completed(normalized_path, completed)
except Exception as e:
# 如果重命名失败,至少更新状态
# 静默处理错误,避免影响用户体验
try:
self.set_completed(normalized_path, completed)
except:
pass
if __name__ == "__main__":
# 测试代码
manager = StatusManager()
# 测试设置和获取状态
test_file = __file__ # 使用当前文件作为测试
print(f"Testing with file: {test_file}")
# 初始状态
print(f"Initial status: {manager.is_completed(test_file)}")
# 设置为完成
manager.set_completed(test_file, True)
print(f"After setting completed: {manager.is_completed(test_file)}")
# 切换状态
new_status = manager.toggle_completed(test_file)
print(f"After toggle: {new_status}")
# 获取完整状态
status = manager.get_status(test_file)
print(f"Full status: {status}")