from dataclasses import dataclass import logging import os import pathlib from typing import List from typing_extensions import Dict, Iterable, Optional import fs.osfs from fs.base import FS as FileSystem from fs.info import Info from plumbum import cli # type: ignore from dolt_annex import importers from dolt_annex.commands import CommandGroup from dolt_annex.datatypes.async_utils import as_acm from dolt_annex.config.base import Config from dolt_annex.datatypes.repo import Repo from dolt_annex.datatypes.table import DatasetSchema from dolt_annex.file_keys import FileKeyType, get_file_key_type from dolt_annex.file_keys.base import FileKey from dolt_annex.filestore.cas import ContentAddressableStorage from dolt_annex.datatypes.file_stream import path_file_source from dolt_annex.importers.base import get_importer from dolt_annex.replicated_db.dolt import DatabaseConnection, DatasetReplica from dolt_annex.datatypes.file_io import Path logger = logging.getLogger(__name__) class AnnexImportError(Exception): pass MAX_EXTENSION_LENGTH = 4 @dataclass class ImportConfig: """Configuration for the import command""" batch_size: int follow_symlinks: bool file_key_type: FileKeyType move: bool copy: bool symlink: bool class Import(cli.Application): """ Import a file or directory into the filestore and dataset. This command is leftover from an older version of dolt-annex and you likely don't need to use it. """ parent: CommandGroup batch_size = cli.SwitchAttr( "--batch_size", int, help="The number of files to process at once", default = 10000, ) move = cli.Flag( "--move", help="Ensures that imported files are deleted from their original location after being moved into the annex", excludes = ["--copy", "--symlink"], ) copy = cli.Flag( "--copy", help="Ensures that imported files are copied into the annex and original files are retained", excludes = ["--move", "--symlink"], ) symlink = cli.Flag( "--symlink", help="Moves imported files into the annex and creates symlinks at the original file locations", excludes = ["--move", "--copy"], ) symlinks = cli.SwitchAttr( "--symlinks", cli.Set("follow", "skip"), help="Whether to follow or skip symlinks", default = "skip", ) importer = cli.SwitchAttr( "--importer", str, ) dataset = cli.SwitchAttr( "--dataset", str, help="The name of the dataset being imported to", ) file_key_type = cli.SwitchAttr( "--file-key-type", str, help="The type of file key to use", default = "SHA256E", ) repo = cli.SwitchAttr( "--repo", str, help="If set, use the specified repo instead of the default repo", ) async def main(self, *files_or_directories: str): base_config: Config = self.parent.config if not self.copy and not self.move and not self.symlink: raise ValueError("Must specify --copy, --move, or --symlink") follow_symlinks = (self.symlinks == "follow") import_config = ImportConfig( batch_size = self.batch_size, follow_symlinks = follow_symlinks, file_key_type = get_file_key_type(self.file_key_type), move=self.move, copy=self.copy, symlink=self.symlink, ) dataset_schema = DatasetSchema.must_load(self.dataset) async with ( Repo.open(base_config, self.repo) as repo, DatabaseConnection.open(base_config) as conn, as_acm(conn.open_dataset(dataset_schema)) as dataset, dataset.with_repo(repo.uuid) as dataset_replica, ): importer = get_importer(*self.importer.split()) await do_import(dataset_replica, repo, import_config, importer, files_or_directories) return 0 async def do_import(dataset_replica: DatasetReplica, file_store: ContentAddressableStorage, import_config: ImportConfig, importer: importers.Importer, files_or_directories: Iterable[str]): key_paths: Dict[str, Dict[Path, FileKey]] = {} for table_name, table in dataset_replica.tables.items(): key_paths[table_name] = {} table.add_flush_hook(move_files, file_store, import_config,key_paths[table_name]) async def import_path(file_or_directory: pathlib.Path): """Import a file or directory into the annex""" if file_or_directory.is_file(): source_file_system = fs.osfs.OSFS(os.fspath(file_or_directory.parent)) await import_file(Path(source_file_system, pathlib.Path(file_or_directory.name))) elif file_or_directory.is_dir(): source_file_system = fs.osfs.OSFS(os.fspath(file_or_directory)) await import_directory(source_file_system) else: raise ValueError(f"Path {file_or_directory} is not a file or directory") async def import_directory(file_system: FileSystem, directory_path: Optional[Path] = None): """Import a directory into the annex""" if directory_path is None: directory_path = Path(file_system, pathlib.Path('/')) root: str files: List[Info] for root, _, files in file_system.walk(os.fspath(directory_path)): root_path = Path(file_system, root) for file in files: await import_file(root_path / file.name) async def import_file(path: Path): """Import a file into the annex""" extension = path.suffix[1:] if len(extension) > MAX_EXTENSION_LENGTH+1: return if path.is_symlink(): if not import_config.follow_symlinks: return else: path = path.readlink() if importer and importer.skip(path): return logger.info("Importing file %s", path) key = await import_config.file_key_type.from_file(path, importer.extension(path)) if importer: key_columns = await importer.key_columns(path) if key_columns: key_columns["submission_file_key"] = bytes(key) table_name = importer.table_name(path) table = dataset_replica.get_table(table_name) await table.insert(key_columns) key_paths[table_name][path] = key if not key_columns: raise AnnexImportError("Importer did not produce a set of key columns, it is not safe to import") for file_or_directory in files_or_directories: await import_path(pathlib.Path(file_or_directory)) async def move_files(file_store: ContentAddressableStorage, import_config: ImportConfig, files: Dict[Path, FileKey]): """Move files to the annex""" logger.debug("moving annex files") for file_path, key in files.items(): uploader = path_file_source(file_path, import_config.file_key_type, file_path.suffix[1:]) await file_store.put_file(uploader) if import_config.move: # TODO: Add an extra check here that the file was added successfully, then delete the file # os.remove(file_path) pass elif import_config.symlink: # TODO: If the filestore doesn't support symlinks, that should have been caught earlier. # Otherwise, verify that the file was successfully moved, get the new path, and create the symlink pass files.clear() Command = Import