forked from krathjen/studiolibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary.py
More file actions
437 lines (325 loc) · 10.3 KB
/
Copy pathlibrary.py
File metadata and controls
437 lines (325 loc) · 10.3 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# This library is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
import os
import logging
import studiolibrary
from studioqt import QtCore
__all__ = [
"Library",
]
logger = logging.getLogger(__name__)
class Library(QtCore.QObject):
ColumnLabels = [
"icon",
"name",
"path",
"type",
"category",
"folder",
# "modified"
]
SortLabels = [
"name",
"path",
"type",
"category",
"folder",
# "modified"
]
GroupLabels = [
"type",
"category",
# "modified",
]
DatabasePath = "{path}/.studiolibrary/database.json"
dataChanged = QtCore.Signal()
def __init__(self, path, *args):
QtCore.QObject.__init__(self, *args)
self._path = None
self._mtime = None
self._data = {}
self._items = []
self._currentItems = []
self.setPath(path)
self.setDirty(True)
def currentItems(self):
"""
The items that are displayed in the view.
:rtype: list[studiolibrary.LibraryItem]
"""
return self._currentItems
def recursiveDepth(self):
"""
Return the recursive search depth.
:rtype: int
"""
return studiolibrary.config().get('recursiveSearchDepth')
def path(self):
"""
Return the disc location of the db.
:rtype: str
"""
return self._path
def setPath(self, path):
"""
Set the disc location of the db.
:type path: str
"""
self._path = path
def databasePath(self):
"""
Return the path to the database.
:rtype: str
"""
return studiolibrary.formatPath(self.DatabasePath, path=self.path())
def mtime(self):
"""
Return when the database was last modified.
:rtype: float or None
"""
path = self.databasePath()
mtime = None
if os.path.exists(path):
mtime = os.path.getmtime(path)
return mtime
def setDirty(self, value):
"""
Update the model object with the current database timestamp.
:type: bool
"""
if value:
self._mtime = None
else:
self._mtime = self.mtime()
def isDirty(self):
"""
Return True if the database has changed on disc.
:rtype: bool
"""
return not self._items or self._mtime != self.mtime()
def read(self):
"""
Read the database from disc and return a dict object.
:rtype: dict
"""
if self.isDirty():
self._data = studiolibrary.readJson(self.databasePath())
self.setDirty(False)
return self._data
def save(self, data):
"""
Write the given dict object to the database on disc.
:type data: dict
:rtype: None
"""
studiolibrary.saveJson(self.databasePath(), data)
self.setDirty(True)
def sync(self):
"""Sync the file system with the database."""
data = self.read()
for path in data.keys():
if not os.path.exists(path):
del data[path]
depth = self.recursiveDepth()
items = studiolibrary.findItems(
self.path(),
depth=depth,
)
for item in items:
path = item.path()
itemData = data.get(path, {})
itemData.update(item.itemData())
data[path] = itemData
self.save(data)
self.dataChanged.emit()
def findItems(self, queries, libraryWidget=None):
"""
Get the items that match the given queries.
Examples:
queries = [
{
'operator': 'or',
'filters': [
('folder', 'is' '/library/proj/test'),
('folder', 'startswith', '/library/proj/test'),
]
},
{
'operator': 'and',
'filters': [
('path', 'contains' 'test'),
('path', 'contains', 'run'),
]
}
]
print(library.find(queries))
:type queries: list[dict]
:type libraryWidget: studiolibrary.LibraryWIdget or None
:rtype: list[studiolibrary.LibraryItem]
"""
items = self.createItems(libraryWidget=libraryWidget)
self._currentItems = []
for item in items:
matches = []
for query in queries:
filters = query.get('filters')
operator = query.get('operator', 'and')
if not filters:
continue
match = False
for key, cond, value in filters:
value = value.lower()
itemValue = item.itemData().get(key)
if itemValue:
itemValue = itemValue.lower()
if not itemValue:
match = False
elif cond == 'contains':
match = value in itemValue
elif cond == 'is':
match = value == itemValue
elif cond == 'startswith':
match = itemValue.startswith(value)
if operator == 'or' and match:
break
if operator == 'and' and not match:
break
matches.append(match)
if all(matches):
self._currentItems.append(item)
return self._currentItems
def updateItem(self, item):
"""
Update the given item in the database.
:type item: studiolibrary.LibraryItem
:rtype: None
"""
self.addItems([item])
def addItem(self, item):
"""
Add the given item to the database.
:type item: studiolibrary.LibraryItem
:rtype: None
"""
self.addItems([item])
def addItems(self, items):
"""
Add the given items to the database.
:type items: list[studiolibrary.LibraryItem]
"""
logger.info("Add items %s", items)
data_ = self.read()
for item in items:
path = item.path()
data = item.itemData()
data_.setdefault(path, {})
data_[path].update(data)
self.save(data_)
self.dataChanged.emit()
def createItems(self, libraryWidget=None):
"""
Create all the items for the model.
:rtype: list[studiolibrary.LibraryItem]
"""
# Check if the database has changed since the last read call
if self.isDirty():
paths = self.read().keys()
items = studiolibrary.itemsFromPaths(
paths,
library=self,
libraryWidget=libraryWidget
)
self._items = list(items)
self.loadItemData(self._items)
return self._items
def saveItemData(self, items):
"""
Save the item data to the database for the given items and columns.
:type items: list[studiolibrary.LibraryItem]
"""
data = {}
for item in items:
path = item.path()
itemData = item.itemData()
data.setdefault(path, itemData)
studiolibrary.updateJson(self.databasePath(), data)
def loadItemData(self, items):
"""
Load the item data from the database to the given items.
:type items: list[studiolibrary.LibraryItem]
"""
data = self.read()
for item in items:
key = item.id()
if key in data:
item.setItemData(data[key])
def addPaths(self, paths, data=None):
"""
Add the given path and the given data to the database.
:type paths: list[str]
:type data: dict or None
:rtype: None
"""
data = data or {}
self.updatePaths(paths, data)
def updatePaths(self, paths, data):
"""
Update the given paths with the given data in the database.
:type paths: list[str]
:type data: dict
:rtype: None
"""
data_ = self.read()
paths = studiolibrary.normPaths(paths)
for path in paths:
if path in data_:
data_[path].update(data)
else:
data_[path] = data
self.save(data_)
def copyPath(self, src, dst):
"""
Copy the given source path to the given destination path.
:type src: str
:type dst: str
:rtype: str
"""
self.addPaths([dst])
return dst
def renamePath(self, src, dst):
"""
Rename the source path to the given name.
:type src: str
:type dst: str
:rtype: str
"""
studiolibrary.renamePathInFile(self.databasePath(), src, dst)
self.setDirty(True)
return dst
def removePath(self, path):
"""
Remove the given path from the database.
:type path: str
:rtype: None
"""
self.removePaths([path])
def removePaths(self, paths):
"""
Remove the given paths from the database.
:type paths: list[str]
:rtype: None
"""
data = self.read()
paths = studiolibrary.normPaths(paths)
for path in paths:
if path in data:
del data[path]
self.save(data)