|
| 1 | +import os |
| 2 | +import sqlite3 |
| 3 | + |
| 4 | +from jupyter_core.paths import jupyter_data_dir |
| 5 | +from traitlets import Unicode |
| 6 | +from traitlets.config.configurable import LoggingConfigurable |
| 7 | + |
| 8 | + |
| 9 | +class FileIdManager(LoggingConfigurable): |
| 10 | + db_path = Unicode( |
| 11 | + default_value=os.path.join(jupyter_data_dir(), "file_id_manager.db"), |
| 12 | + help=( |
| 13 | + "The path of the DB file used by `FileIdManager`. " |
| 14 | + "Defaults to `jupyter_data_dir()/file_id_manager.db`." |
| 15 | + ), |
| 16 | + config=True, |
| 17 | + ) |
| 18 | + |
| 19 | + def __init__(self, *args, **kwargs): |
| 20 | + # pass args and kwargs to parent Configurable |
| 21 | + super().__init__(*args, **kwargs) |
| 22 | + # initialize connection with db |
| 23 | + self.con = sqlite3.connect(self.db_path) |
| 24 | + self.log.debug("Creating File ID tables and indices") |
| 25 | + self.con.execute( |
| 26 | + "CREATE TABLE IF NOT EXISTS Files(id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE)" |
| 27 | + ) |
| 28 | + self.con.execute("CREATE INDEX IF NOT EXISTS ix_Files_path ON FILES (path)") |
| 29 | + self.con.commit() |
| 30 | + |
| 31 | + def _normalize_path(self, path): |
| 32 | + """Normalizes a given file path.""" |
| 33 | + path = os.path.normcase(path) |
| 34 | + path = os.path.normpath(path) |
| 35 | + return path |
| 36 | + |
| 37 | + def index(self, path): |
| 38 | + """Adds the file path to the Files table, then returns the file ID. If |
| 39 | + the file is already indexed, the file ID is immediately returned.""" |
| 40 | + path = self._normalize_path(path) |
| 41 | + existing_id = self.get_id(path) |
| 42 | + if existing_id is not None: |
| 43 | + return existing_id |
| 44 | + |
| 45 | + cursor = self.con.execute("INSERT INTO Files (path) VALUES (?)", (path,)) |
| 46 | + self.con.commit() |
| 47 | + return cursor.lastrowid |
| 48 | + |
| 49 | + def get_id(self, path): |
| 50 | + """Retrieves the file ID associated with a file path. Returns None if |
| 51 | + the file path has not yet been indexed.""" |
| 52 | + path = self._normalize_path(path) |
| 53 | + row = self.con.execute("SELECT id FROM Files WHERE path = ?", (path,)).fetchone() |
| 54 | + self.con.commit() |
| 55 | + return row[0] if row else None |
| 56 | + |
| 57 | + def get_path(self, id): |
| 58 | + """Retrieves the file path associated with a file ID. Returns None if |
| 59 | + the ID does not exist in the Files table.""" |
| 60 | + row = self.con.execute("SELECT path FROM Files WHERE id = ?", (id,)).fetchone() |
| 61 | + self.con.commit() |
| 62 | + return row[0] if row else None |
| 63 | + |
| 64 | + def move(self, old_path, new_path, recursive=False): |
| 65 | + """Handles file moves by updating the file path of the associated file |
| 66 | + ID. Returns the file ID.""" |
| 67 | + old_path = self._normalize_path(old_path) |
| 68 | + new_path = self._normalize_path(new_path) |
| 69 | + self.log.debug(f"Moving file from ${old_path} to ${new_path}") |
| 70 | + |
| 71 | + if recursive: |
| 72 | + old_path_glob = os.path.join(old_path, "*") |
| 73 | + self.con.execute( |
| 74 | + "UPDATE Files SET path = ? || substr(path, ?) WHERE path GLOB ?", |
| 75 | + (new_path, len(old_path) + 1, old_path_glob), |
| 76 | + ) |
| 77 | + self.con.commit() |
| 78 | + |
| 79 | + id = self.get_id(old_path) |
| 80 | + if id is None: |
| 81 | + return self.index(new_path) |
| 82 | + else: |
| 83 | + self.con.execute("UPDATE Files SET path = ? WHERE id = ?", (new_path, id)) |
| 84 | + self.con.commit() |
| 85 | + return id |
| 86 | + |
| 87 | + def copy(self, from_path, to_path, recursive=False): |
| 88 | + """Handles file copies by creating a new record in the Files table. |
| 89 | + Returns the file ID associated with `new_path`. Also indexes `old_path` |
| 90 | + if record does not exist in Files table. TODO: emit to event bus to |
| 91 | + inform client extensions to copy records associated with old file ID to |
| 92 | + the new file ID.""" |
| 93 | + from_path = self._normalize_path(from_path) |
| 94 | + to_path = self._normalize_path(to_path) |
| 95 | + self.log.debug(f"Copying file from ${from_path} to ${to_path}") |
| 96 | + |
| 97 | + if recursive: |
| 98 | + from_path_glob = os.path.join(from_path, "*") |
| 99 | + self.con.execute( |
| 100 | + "INSERT INTO Files (path) SELECT (? || substr(path, ?)) FROM Files WHERE path GLOB ?", |
| 101 | + (to_path, len(from_path) + 1, from_path_glob), |
| 102 | + ) |
| 103 | + self.con.commit() |
| 104 | + |
| 105 | + self.index(from_path) |
| 106 | + return self.index(to_path) |
| 107 | + |
| 108 | + def delete(self, path, recursive=False): |
| 109 | + """Handles file deletions by deleting the associated record in the File |
| 110 | + table. Returns None.""" |
| 111 | + path = self._normalize_path(path) |
| 112 | + self.log.debug(f"Deleting file {path}") |
| 113 | + |
| 114 | + if recursive: |
| 115 | + path_glob = os.path.join(path, "*") |
| 116 | + self.con.execute("DELETE FROM Files WHERE path GLOB ?", (path_glob,)) |
| 117 | + self.con.commit() |
| 118 | + |
| 119 | + self.con.execute("DELETE FROM Files WHERE path = ?", (path,)) |
| 120 | + self.con.commit() |
| 121 | + |
| 122 | + def _cleanup(self): |
| 123 | + """Cleans up `FileIdManager` by committing any pending transactions and |
| 124 | + closing the connection.""" |
| 125 | + self.con.commit() |
| 126 | + self.con.close() |
0 commit comments