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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530 | class FileBundle(KiaraModel):
"""Describes properties for the 'file_bundle' value type."""
_kiara_model_id = "instance.data.file_bundle"
@classmethod
def create_tmp_dir(self) -> Path:
"""Utility method to create a temp folder that gets deleted when kiara exits."""
temp_f = tempfile.mkdtemp()
def cleanup():
shutil.rmtree(temp_f, ignore_errors=True)
atexit.register(cleanup)
return Path(temp_f)
@classmethod
def import_folder(
cls,
source: str,
bundle_name: Union[str, None] = None,
import_config: Union[None, Mapping[str, Any], FolderImportConfig] = None,
# import_time: Optional[datetime.datetime] = None,
) -> "FileBundle":
if not source:
raise ValueError("No source path provided.")
if not os.path.exists(os.path.realpath(source)):
raise ValueError(f"Path does not exist: {source}")
if not os.path.isdir(os.path.realpath(source)):
raise ValueError(f"Path is not a folder: {source}")
if source.endswith(os.path.sep):
source = source[0:-1]
abs_path = os.path.abspath(source)
if import_config is None:
_import_config = FolderImportConfig()
elif isinstance(import_config, Mapping):
_import_config = FolderImportConfig(**import_config)
elif isinstance(import_config, FolderImportConfig):
_import_config = import_config
else:
raise TypeError(
f"Invalid type for folder import config: {type(import_config)}."
)
included_files: Dict[str, FileModel] = {}
exclude_dirs = _import_config.exclude_dirs
invalid_extensions = _import_config.exclude_files
valid_extensions = _import_config.include_files
# if import_time:
# bundle_import_time = import_time
# else:
# bundle_import_time = datetime.datetime.now() # TODO: timezone
sum_size = 0
def include_file(filename: str) -> bool:
if invalid_extensions and any(
filename.endswith(ext) for ext in invalid_extensions
):
return False
if not valid_extensions:
return True
else:
return any(filename.endswith(ext) for ext in valid_extensions)
for root, dirnames, filenames in os.walk(abs_path, topdown=True):
if exclude_dirs:
dirnames[:] = [d for d in dirnames if d not in exclude_dirs]
for filename in [
f
for f in filenames
if os.path.isfile(os.path.join(root, f)) and include_file(f)
]:
full_path = os.path.join(root, filename)
rel_path = os.path.relpath(full_path, abs_path)
file_model = FileModel.load_file(full_path)
sum_size = sum_size + file_model.size
included_files[rel_path] = file_model
if bundle_name is None:
bundle_name = os.path.basename(source)
bundle = FileBundle.create_from_file_models(
files=included_files,
path=abs_path,
bundle_name=bundle_name,
sum_size=sum_size,
)
return bundle
@classmethod
def create_from_file_models(
cls,
files: Mapping[str, FileModel],
bundle_name: str,
path: Union[str, None] = None,
sum_size: Union[int, None] = None,
# import_time: Optional[datetime.datetime] = None,
) -> "FileBundle":
# if import_time:
# bundle_import_time = import_time
# else:
# bundle_import_time = datetime.datetime.now() # TODO: timezone
result: Dict[str, Any] = {}
result["included_files"] = files
# result["import_time"] = datetime.datetime.now().isoformat()
result["number_of_files"] = len(files)
result["bundle_name"] = bundle_name
# result["import_time"] = bundle_import_time
if sum_size is None:
sum_size = 0
for f in files.values():
sum_size = sum_size + f.size
result["size"] = sum_size
bundle = FileBundle(**result)
bundle._path = path
return bundle
_file_bundle_hash: Union[int, None] = PrivateAttr(default=None)
bundle_name: str = Field(description="The name of this bundle.")
# import_time: datetime.datetime = Field(
# description="The time when the file bundle was imported."
# )
number_of_files: int = Field(
description="How many files are included in this bundle."
)
included_files: Dict[str, FileModel] = Field(
description="A map of all the included files, incl. their properties. Uses the relative path of each file as key."
)
size: int = Field(description="The size of all files in this folder, combined.")
metadata: Dict[str, Any] = Field(
description="Additional, ustructured, user-defined metadata.",
default_factory=dict,
)
_path: Union[str, None] = PrivateAttr(default=None)
@property
def path(self) -> str:
if self._path is None:
# TODO: better explanation, offer remedy like copying into temp folder
raise Exception(
"File bundle path not set, it appears this bundle is comprised of symlinks only."
)
return self._path
def _retrieve_id(self) -> str:
return str(self.file_bundle_hash)
# @property
# def model_data_hash(self) -> int:
# return self.file_bundle_hash
def _retrieve_data_to_hash(self) -> Any:
return {
"bundle_name": self.bundle_name,
"included_files": {
k: v.instance_cid for k, v in self.included_files.items()
},
}
def get_relative_path(self, file: FileModel):
return os.path.relpath(file.path, self.path)
def read_text_file_contents(self, ignore_errors: bool = False) -> Mapping[str, str]:
content_dict: Dict[str, str] = {}
def read_file(rel_path: str, full_path: str):
with open(full_path, encoding="utf-8") as f:
try:
content = f.read()
content_dict[rel_path] = content # type: ignore
except Exception as e:
if ignore_errors:
log_message(f"Can't read file: {e}")
logger.warning("ignore.file", path=full_path, reason=str(e))
else:
raise Exception(f"Can't read file (as text) '{full_path}: {e}")
# TODO: common ignore files and folders
for rel_path, f in self.included_files.items():
if f._path:
path = f._path
else:
path = self.get_relative_path(f)
read_file(rel_path=rel_path, full_path=path)
return content_dict
@property
def file_bundle_hash(self) -> int:
# TODO: use sha256?
if self._file_bundle_hash is not None:
return self._file_bundle_hash
obj = {k: v.file_hash for k, v in self.included_files.items()}
h = DeepHash(obj, hasher=KIARA_HASH_FUNCTION)
self._file_bundle_hash = h[obj]
return self._file_bundle_hash
def copy_bundle(
self, target_path: str, bundle_name: Union[str, None] = None
) -> "FileBundle":
if target_path == self.path:
raise Exception(f"Target path and current path are the same: {target_path}")
result = {}
for rel_path, item in self.included_files.items():
_target_path = os.path.join(target_path, rel_path)
new_fm = item.copy_file(_target_path)
result[rel_path] = new_fm
if bundle_name is None:
bundle_name = os.path.basename(target_path)
fb = FileBundle.create_from_file_models(
files=result,
bundle_name=bundle_name,
path=target_path,
sum_size=self.size,
# import_time=self.import_time,
)
if self._file_bundle_hash is not None:
fb._file_bundle_hash = self._file_bundle_hash
return fb
def create_renderable(self, **config: Any) -> RenderableType:
show_bundle_hash = config.get("show_bundle_hash", False)
table = Table(show_header=False, box=box.SIMPLE)
table.add_column("key")
table.add_column("value", style="i")
table.add_row("bundle name", self.bundle_name)
# table.add_row("import_time", str(self.import_time))
table.add_row("number_of_files", str(self.number_of_files))
table.add_row("size", str(self.size))
if show_bundle_hash:
table.add_row("bundle_hash", str(self.file_bundle_hash))
content = self._create_content_table(**config)
table.add_row("included files", content)
return table
def _create_content_table(self, **render_config: Any) -> Table:
# show_content = render_config.get("show_content_preview", False)
max_no_included_files = render_config.get("max_no_files", 40)
table = Table(show_header=True, box=box.SIMPLE)
table.add_column("(relative) path")
table.add_column("size")
# if show_content:
# table.add_column("content preview")
if (
max_no_included_files < 0
or len(self.included_files) <= max_no_included_files
):
for f, model in self.included_files.items():
row = [f, str(model.size)]
table.add_row(*row)
else:
files = list(self.included_files.keys())
half = int((max_no_included_files - 1) / 2)
head = files[0:half]
tail = files[-1 * half :]
for rel_path in head:
model = self.included_files[rel_path]
row = [rel_path, str(model.size)]
table.add_row(*row)
table.add_row(" ... output skipped ...", "")
table.add_row(" ... output skipped ...", "")
for rel_path in tail:
model = self.included_files[rel_path]
row = [rel_path, str(model.size)]
table.add_row(*row)
return table
def __repr__(self):
return f"FileBundle(name={self.bundle_name})"
def __str__(self):
return self.__repr__()
|