pyBiocFileCache 0.2.1__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/.github/workflows/pypi-publish.yml +1 -1
  2. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/.github/workflows/pypi-test.yml +8 -3
  3. pybiocfilecache-0.3.0/.pre-commit-config.yaml +52 -0
  4. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/AUTHORS.md +1 -1
  5. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/CHANGELOG.md +1 -1
  6. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/PKG-INFO +12 -3
  7. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/README.md +5 -1
  8. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/authors.md +1 -1
  9. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/changelog.md +1 -1
  10. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/readme.md +5 -1
  11. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/requirements.txt +1 -1
  12. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/pyproject.toml +15 -0
  13. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/setup.cfg +1 -1
  14. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/setup.py +5 -6
  15. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pyBiocFileCache.egg-info/PKG-INFO +12 -3
  16. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pyBiocFileCache.egg-info/SOURCES.txt +2 -0
  17. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pyBiocFileCache.egg-info/requires.txt +1 -1
  18. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pybiocfilecache/BiocFileCache.py +88 -49
  19. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pybiocfilecache/__init__.py +8 -1
  20. pybiocfilecache-0.3.0/src/pybiocfilecache/_exceptions.py +15 -0
  21. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pybiocfilecache/db/Base.py +1 -1
  22. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pybiocfilecache/db/schema.py +2 -2
  23. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pybiocfilecache/utils.py +2 -2
  24. pybiocfilecache-0.3.0/tests/conftest.py +9 -0
  25. pybiocfilecache-0.3.0/tests/data/test1.txt +1 -0
  26. pybiocfilecache-0.3.0/tests/data/test2.txt +1 -0
  27. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/tests/test_cache.py +8 -9
  28. pyBiocFileCache-0.2.1/tests/conftest.py +0 -10
  29. pyBiocFileCache-0.2.1/tests/data/test1.txt +0 -1
  30. pyBiocFileCache-0.2.1/tests/data/test2.txt +0 -1
  31. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/.coveragerc +0 -0
  32. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/.gitignore +0 -0
  33. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/.readthedocs.yml +0 -0
  34. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/CONTRIBUTING.rst +0 -0
  35. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/LICENSE.txt +0 -0
  36. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/Makefile +0 -0
  37. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/_static/.gitignore +0 -0
  38. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/conf.py +0 -0
  39. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/contributing.rst +0 -0
  40. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/index.md +0 -0
  41. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/docs/license.rst +0 -0
  42. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pyBiocFileCache.egg-info/dependency_links.txt +0 -0
  43. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pyBiocFileCache.egg-info/not-zip-safe +0 -0
  44. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pyBiocFileCache.egg-info/top_level.txt +0 -0
  45. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/src/pybiocfilecache/db/__init__.py +0 -0
  46. {pyBiocFileCache-0.2.1 → pybiocfilecache-0.3.0}/tox.ini +0 -0
@@ -48,4 +48,4 @@ jobs:
48
48
  uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
49
49
  with:
50
50
  user: __token__
51
- password: ${{ secrets.PYPI_PASSWORD }}
51
+ password: ${{ secrets.PYPI_PASSWORD }}
@@ -13,13 +13,18 @@ jobs:
13
13
  build:
14
14
 
15
15
  runs-on: ubuntu-latest
16
+ strategy:
17
+ matrix:
18
+ python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12' ]
16
19
 
20
+ name: Python ${{ matrix.python-version }}
17
21
  steps:
18
22
  - uses: actions/checkout@v2
19
- - name: Set up Python 3.9
23
+ - name: Setup Python
20
24
  uses: actions/setup-python@v2
21
25
  with:
22
- python-version: 3.9
26
+ python-version: ${{ matrix.python-version }}
27
+ cache: 'pip'
23
28
  - name: Install dependencies
24
29
  run: |
25
30
  python -m pip install --upgrade pip
@@ -32,4 +37,4 @@ jobs:
32
37
  # # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
33
38
  - name: Test with tox
34
39
  run: |
35
- tox
40
+ tox
@@ -0,0 +1,52 @@
1
+ exclude: '^docs/conf.py'
2
+
3
+ repos:
4
+ - repo: https://github.com/pre-commit/pre-commit-hooks
5
+ rev: v4.6.0
6
+ hooks:
7
+ - id: trailing-whitespace
8
+ - id: check-added-large-files
9
+ - id: check-ast
10
+ - id: check-json
11
+ - id: check-merge-conflict
12
+ - id: check-xml
13
+ - id: check-yaml
14
+ - id: debug-statements
15
+ - id: end-of-file-fixer
16
+ - id: requirements-txt-fixer
17
+ - id: mixed-line-ending
18
+ args: ['--fix=auto'] # replace 'auto' with 'lf' to enforce Linux/Mac line endings or 'crlf' for Windows
19
+
20
+ - repo: https://github.com/PyCQA/docformatter
21
+ rev: v1.7.5
22
+ hooks:
23
+ - id: docformatter
24
+ additional_dependencies: [tomli]
25
+ args: [--in-place, --wrap-descriptions=120, --wrap-summaries=120]
26
+ # --config, ./pyproject.toml
27
+
28
+ - repo: https://github.com/psf/black
29
+ rev: 24.4.0
30
+ hooks:
31
+ - id: black
32
+ language_version: python3
33
+
34
+ - repo: https://github.com/astral-sh/ruff-pre-commit
35
+ # Ruff version.
36
+ rev: v0.3.7
37
+ hooks:
38
+ - id: ruff
39
+ args: [--fix, --exit-non-zero-on-fix]
40
+
41
+ ## If like to embrace black styles even in the docs:
42
+ # - repo: https://github.com/asottile/blacken-docs
43
+ # rev: v1.13.0
44
+ # hooks:
45
+ # - id: blacken-docs
46
+ # additional_dependencies: [black]
47
+
48
+ ## Check for misspells in documentation files:
49
+ # - repo: https://github.com/codespell-project/codespell
50
+ # rev: v2.2.5
51
+ # hooks:
52
+ # - id: codespell
@@ -1,4 +1,4 @@
1
1
  # Contributors
2
2
 
3
3
  * Jayaram Kancherla <jayaram.kancherla@gmail.com>
4
- * Max Hargreaves <max_hargreaves@outlook.com>
4
+ * Max Hargreaves <max_hargreaves@outlook.com>
@@ -2,4 +2,4 @@
2
2
 
3
3
  ## Version 0.1 (development)
4
4
 
5
- - Initial release
5
+ - Initial release
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -11,9 +11,18 @@ Platform: any
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Programming Language :: Python
13
13
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
- Provides-Extra: testing
15
14
  License-File: LICENSE.txt
16
15
  License-File: AUTHORS.md
16
+ Requires-Dist: importlib-metadata; python_version < "3.8"
17
+ Requires-Dist: sqlalchemy<2.1,>=2
18
+ Provides-Extra: testing
19
+ Requires-Dist: setuptools; extra == "testing"
20
+ Requires-Dist: pytest; extra == "testing"
21
+ Requires-Dist: pytest-cov; extra == "testing"
22
+
23
+ [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
24
+ [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
25
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
17
26
 
18
27
  # pyBiocFileCache
19
28
 
@@ -29,7 +38,7 @@ Package is published to [PyPI](https://pypi.org/project/pyBiocFileCache/)
29
38
  pip install pybiocfilecache
30
39
  ```
31
40
 
32
- #### Initialize a cache directory
41
+ #### Initialize a cache directory
33
42
 
34
43
  ```
35
44
  from pybiocfilecache import BiocFileCache
@@ -1,3 +1,7 @@
1
+ [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
2
+ [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
3
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
4
+
1
5
  # pyBiocFileCache
2
6
 
3
7
  File system based cache for resources & metadata. Compatible with [BiocFileCache R package](https://github.com/Bioconductor/BiocFileCache)
@@ -12,7 +16,7 @@ Package is published to [PyPI](https://pypi.org/project/pyBiocFileCache/)
12
16
  pip install pybiocfilecache
13
17
  ```
14
18
 
15
- #### Initialize a cache directory
19
+ #### Initialize a cache directory
16
20
 
17
21
  ```
18
22
  from pybiocfilecache import BiocFileCache
@@ -1,4 +1,4 @@
1
1
  # Contributors
2
2
 
3
3
  * Jayaram Kancherla <jayaram.kancherla@gmail.com>
4
- * Max Hargreaves <max_hargreaves@outlook.com>
4
+ * Max Hargreaves <max_hargreaves@outlook.com>
@@ -2,4 +2,4 @@
2
2
 
3
3
  ## Version 0.1 (development)
4
4
 
5
- - Initial release
5
+ - Initial release
@@ -1,3 +1,7 @@
1
+ [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
2
+ [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
3
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
4
+
1
5
  # pyBiocFileCache
2
6
 
3
7
  File system based cache for resources & metadata. Compatible with [BiocFileCache R package](https://github.com/Bioconductor/BiocFileCache)
@@ -12,7 +16,7 @@ Package is published to [PyPI](https://pypi.org/project/pyBiocFileCache/)
12
16
  pip install pybiocfilecache
13
17
  ```
14
18
 
15
- #### Initialize a cache directory
19
+ #### Initialize a cache directory
16
20
 
17
21
  ```
18
22
  from pybiocfilecache import BiocFileCache
@@ -1,7 +1,7 @@
1
+ furo
1
2
  # Requirements file for ReadTheDocs, check .readthedocs.yml.
2
3
  # To build the module reference correctly, make sure every external package
3
4
  # under `install_requires` in `setup.cfg` is also listed here!
4
5
  # sphinx_rtd_theme
5
6
  recommonmark
6
7
  sphinx>=3.2.1
7
- furo
@@ -6,3 +6,18 @@ build-backend = "setuptools.build_meta"
6
6
  [tool.setuptools_scm]
7
7
  # See configuration details in https://github.com/pypa/setuptools_scm
8
8
  version_scheme = "no-guess-dev"
9
+
10
+ [tool.ruff]
11
+ line-length = 120
12
+ src = ["src"]
13
+ exclude = ["tests"]
14
+ extend-ignore = ["F821"]
15
+
16
+ [tool.ruff.pydocstyle]
17
+ convention = "google"
18
+
19
+ [tool.ruff.per-file-ignores]
20
+ "__init__.py" = ["E402", "F401"]
21
+
22
+ [tool.black]
23
+ force-exclude = "__init__.py"
@@ -22,7 +22,7 @@ package_dir =
22
22
  =src
23
23
  install_requires =
24
24
  importlib-metadata; python_version<"3.8"
25
- sqlalchemy>=1.4,<2.0
25
+ sqlalchemy>=2,<2.1
26
26
 
27
27
  [options.packages.find]
28
28
  where = src
@@ -1,11 +1,10 @@
1
- """
2
- Setup file for pyBiocFileCache.
3
- Use setup.cfg to configure your project.
1
+ """Setup file for pyBiocFileCache. Use setup.cfg to configure your project.
4
2
 
5
- This file was generated with PyScaffold 4.1.
6
- PyScaffold helps you to put up the scaffold of your new Python project.
7
- Learn more under: https://pyscaffold.org/
3
+ This file was generated with PyScaffold 4.1.
4
+ PyScaffold helps you to put up the scaffold of your new Python project.
5
+ Learn more under: https://pyscaffold.org/
8
6
  """
7
+
9
8
  from setuptools import setup
10
9
 
11
10
  if __name__ == "__main__":
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -11,9 +11,18 @@ Platform: any
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Programming Language :: Python
13
13
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
- Provides-Extra: testing
15
14
  License-File: LICENSE.txt
16
15
  License-File: AUTHORS.md
16
+ Requires-Dist: importlib-metadata; python_version < "3.8"
17
+ Requires-Dist: sqlalchemy<2.1,>=2
18
+ Provides-Extra: testing
19
+ Requires-Dist: setuptools; extra == "testing"
20
+ Requires-Dist: pytest; extra == "testing"
21
+ Requires-Dist: pytest-cov; extra == "testing"
22
+
23
+ [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
24
+ [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
25
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
17
26
 
18
27
  # pyBiocFileCache
19
28
 
@@ -29,7 +38,7 @@ Package is published to [PyPI](https://pypi.org/project/pyBiocFileCache/)
29
38
  pip install pybiocfilecache
30
39
  ```
31
40
 
32
- #### Initialize a cache directory
41
+ #### Initialize a cache directory
33
42
 
34
43
  ```
35
44
  from pybiocfilecache import BiocFileCache
@@ -1,5 +1,6 @@
1
1
  .coveragerc
2
2
  .gitignore
3
+ .pre-commit-config.yaml
3
4
  .readthedocs.yml
4
5
  AUTHORS.md
5
6
  CHANGELOG.md
@@ -30,6 +31,7 @@ src/pyBiocFileCache.egg-info/requires.txt
30
31
  src/pyBiocFileCache.egg-info/top_level.txt
31
32
  src/pybiocfilecache/BiocFileCache.py
32
33
  src/pybiocfilecache/__init__.py
34
+ src/pybiocfilecache/_exceptions.py
33
35
  src/pybiocfilecache/utils.py
34
36
  src/pybiocfilecache/db/Base.py
35
37
  src/pybiocfilecache/db/__init__.py
@@ -1,4 +1,4 @@
1
- sqlalchemy<2.0,>=1.4
1
+ sqlalchemy<2.1,>=2
2
2
 
3
3
  [:python_version < "3.8"]
4
4
  importlib-metadata
@@ -1,10 +1,8 @@
1
- """
2
- Python Implementation of BiocFileCache
3
- """
1
+ """Python Implementation of BiocFileCache."""
4
2
 
5
- import logging
6
3
  import os
7
4
  from pathlib import Path
5
+ from time import sleep, time
8
6
  from typing import List, Optional, Union
9
7
 
10
8
  from sqlalchemy import func
@@ -13,24 +11,21 @@ from sqlalchemy.orm import Session
13
11
  from .db import create_schema
14
12
  from .db.schema import Resource
15
13
  from .utils import copy_or_move, create_tmp_dir, generate_id
14
+ from ._exceptions import NoFpathError, RnameExistsError, RpathTimeoutError
16
15
 
17
16
  __author__ = "jkanche"
18
17
  __copyright__ = "jkanche"
19
18
  __license__ = "MIT"
20
19
 
21
- _logger = logging.getLogger(__name__)
22
-
23
20
 
24
21
  class BiocFileCache:
25
- """
26
- Class to manage and cache files.
27
- """
22
+ """Class to manage and cache files."""
28
23
 
29
24
  def __init__(self, cacheDirOrPath: Union[str, Path] = create_tmp_dir()):
30
25
  """Initialize BiocFileCache.
31
26
 
32
27
  Args:
33
- cacheDirOrPath (Union[str, Path], optional): Path to cache
28
+ cacheDirOrPath (Union[str, Path], optional): Path to cache.
34
29
  directory. Defaults to tmp location, `create_tmp_dir()`.
35
30
 
36
31
  Raises:
@@ -65,54 +60,74 @@ class BiocFileCache:
65
60
  Args:
66
61
  rname (str): Name of the resource to add to cache.
67
62
  fpath (Union[str, Path]): Location of the resource.
68
- rtype (str, optional): One of `local`, `web`, or `relative`.
63
+ rtype (str, optional): One of `"local"`, `"web"`, or `"relative"`.
69
64
  Defaults to `"local"`.
70
- action (str, optional): Either `copy`, `move` or `asis`.
65
+ action (str, optional): Either `"copy"`, `"move"` or `"asis"`.
71
66
  Defaults to `"copy"`.
72
67
  ext (bool, optional): Use filepath extension when storing in cache.
73
68
  Defaults to `False`.
74
69
 
75
70
  Returns:
76
- Resource: Database record of the new resource in cache
77
- """
71
+ Resource: Database record of the new resource in cache.
78
72
 
73
+ Raises:
74
+ NoFpathError: When the `fpath` does not exist.
75
+ RnameExistsError: When the `rname` already exists in the cache.
76
+ sqlalchemy exceptions: When something is up with the cache.
77
+ """
79
78
  if isinstance(fpath, str):
80
79
  fpath = Path(fpath)
81
80
 
82
81
  if not fpath.exists():
83
- raise Exception(f"Resource at {fpath} does not exist.")
84
-
85
- existing_cache = self.get(rname)
86
- if existing_cache is not None:
87
- _logger.info(f"File with {rname} already exists, updating instead")
88
- return self.update(rname, fpath, action)
82
+ raise NoFpathError(f"Resource at {fpath} does not exist.")
89
83
 
90
84
  rid = generate_id()
91
- rpath = f"{self.cache}/{rid}.{fpath.suffix}" if ext else f"{self.cache}/{rid}"
92
-
93
- copy_or_move(str(fpath), rpath, rname, action)
85
+ rpath = f"{self.cache}/{rid}" + (f".{fpath.suffix}" if ext else "")
94
86
 
95
87
  # create new record in the database
96
88
  res = Resource(
97
- **dict(rid=rid, rname=rname, rpath=rpath, rtype=rtype, fpath=str(fpath))
89
+ **dict(
90
+ rid=rid,
91
+ rname=rname,
92
+ rpath=rpath,
93
+ rtype=rtype,
94
+ fpath=str(fpath),
95
+ )
98
96
  )
99
97
 
98
+ # If this was higher up a parallel process could have added the key to
99
+ # the cache in the meantime as the above takes a bit, so checking here
100
+ # reduces the odds of this happening
101
+ # Redirecting to update was removed as it is a scenario better handled
102
+ # by the caller.
103
+ if self.get(rname) is not None:
104
+ raise RnameExistsError("Resource already exists in cache!")
105
+
100
106
  with self.sessionLocal() as session:
101
107
  session.add(res)
102
108
  session.commit()
103
109
  session.refresh(res)
104
110
 
111
+ # In the "move" scenario if we move the file to rpath before rpath is
112
+ # part of the cache and then when trying to add it to the cache an
113
+ # exception is raised (such as if it is locked by another process) the
114
+ # data essentially disappears to rpath with no way of retrieving its
115
+ # location. Thus we add rpath to the cache first, then move the data
116
+ # into it so that the data at source does not disappear if accessing
117
+ # the cache raises an exception.
118
+ copy_or_move(str(fpath), rpath, rname, action)
119
+
105
120
  return res
106
121
 
107
122
  def query(self, query: str, field: str = "rname") -> List[Resource]:
108
123
  """Search cache for a resource.
109
124
 
110
125
  Args:
111
- query (str): query to search
126
+ query (str): query or keywords to search.
112
127
  field (str, optional): Field to search. Defaults to "rname".
113
128
 
114
129
  Returns:
115
- List[Resource]: list of matching resources from cache
130
+ List[Resource]: list of matching resources from cache.
116
131
  """
117
132
  with self.sessionLocal() as session:
118
133
  return (
@@ -129,15 +144,32 @@ class BiocFileCache:
129
144
  rname (str): The `rname` of the `Resource` to get.
130
145
 
131
146
  Returns:
132
- res (Resource, optional): The `Resource` for the `rname` if any.
147
+ (Resource, optional): The `Resource` for the `rname` if any.
133
148
  """
134
- return session.query(Resource).filter(Resource.rname == rname).first()
149
+ resource: Optional[Resource] = (
150
+ session.query(Resource).filter(Resource.rname == rname).first()
151
+ )
152
+
153
+ if resource is not None:
154
+ # `Resource` may exist but `rpath` could still be being
155
+ # moved/copied into by `add`, wait until `rpath` exists
156
+ start = time()
157
+ timeout = 30
158
+ while not Path(str(resource.rpath)).exists():
159
+ if time() - start >= timeout:
160
+ raise RpathTimeoutError(
161
+ f"For resource: '{rname}' the rpath does not exist "
162
+ f"after {timeout} seconds."
163
+ )
164
+ sleep(0.1)
165
+
166
+ return resource
135
167
 
136
168
  def get(self, rname: str) -> Optional[Resource]:
137
- """get resource by name from cache.
169
+ """Get resource by name from cache.
138
170
 
139
171
  Args:
140
- rname (str): Name of the file to search
172
+ rname (str): Name of the file to search.
141
173
 
142
174
  Returns:
143
175
  Optional[Resource]: matched resource from cache if exists.
@@ -148,14 +180,16 @@ class BiocFileCache:
148
180
  """Remove a resource from cache by name.
149
181
 
150
182
  Args:
151
- rname (str): Name of the resource to remove
183
+ rname (str): Name of the resource to remove.
152
184
  """
153
185
  with self.sessionLocal() as session:
154
- res: Resource = self._get(session, rname)
155
- session.delete(res)
156
- session.commit()
157
- # remove file
158
- Path(res.rpath).unlink()
186
+ res: Optional[Resource] = self._get(session, rname)
187
+
188
+ if res is not None:
189
+ session.delete(res)
190
+ session.commit()
191
+ # remove file
192
+ Path(res.rpath).unlink()
159
193
 
160
194
  def purge(self):
161
195
  """Remove all files from cache."""
@@ -168,12 +202,12 @@ class BiocFileCache:
168
202
  """Update a resource in cache.
169
203
 
170
204
  Args:
171
- rname (str): name of the resource in cache
205
+ rname (str): name of the resource in cache.
172
206
  fpath (Union[str, Path]): new resource to replace existing file in cache.
173
- action (str, optional): either copy of move. defaults to copy
207
+ action (str, optional): either copy of move. defaults to copy.
174
208
 
175
209
  Returns:
176
- Resource: Updated resource record in cache
210
+ Resource: Updated resource record in cache.
177
211
  """
178
212
 
179
213
  if isinstance(fpath, str):
@@ -183,13 +217,18 @@ class BiocFileCache:
183
217
  raise Exception(f"File: '{fpath}' does not exist")
184
218
 
185
219
  with self.sessionLocal() as session:
186
- res: Resource = self._get(session, rname)
187
- # copy the file to cache
188
- copy_or_move(str(fpath), str(res.rpath), rname, action)
189
- # TODO: is this needed?
190
- res.create_time = res.access_time = res.last_modified_time = func.now()
191
- session.merge(res)
192
- session.commit()
193
- session.refresh(res)
194
-
195
- return res
220
+ res = self._get(session, rname)
221
+
222
+ if res is not None:
223
+ # copy the file to cache
224
+ copy_or_move(str(fpath), str(res.rpath), rname, action)
225
+ res.access_time = res.last_modified_time = func.now()
226
+ session.merge(res)
227
+ session.commit()
228
+ session.refresh(res)
229
+ else:
230
+ # technically an error since update shouldn't be called on
231
+ # non-existent resources in cache.
232
+ # but lets just add it to the cache.
233
+ res = self.add(rname=rname, fpath=fpath, action=action)
234
+ return res
@@ -15,4 +15,11 @@ except PackageNotFoundError: # pragma: no cover
15
15
  finally:
16
16
  del version, PackageNotFoundError
17
17
 
18
- from .BiocFileCache import BiocFileCache
18
+ from .BiocFileCache import BiocFileCache as BiocFileCache
19
+
20
+ from .db.schema import Metadata as Metadata
21
+ from .db.schema import Resource as Resource
22
+
23
+ from ._exceptions import NoFpathError as NoFpathError
24
+ from ._exceptions import RnameExistsError as RnameExistsError
25
+ from ._exceptions import RpathTimeoutError as RpathTimeoutError
@@ -0,0 +1,15 @@
1
+ __author__ = "jkanche"
2
+ __copyright__ = "jkanche"
3
+ __license__ = "MIT"
4
+
5
+
6
+ class NoFpathError(Exception):
7
+ """An error for when the source file does not exist."""
8
+
9
+
10
+ class RnameExistsError(Exception):
11
+ """An error for when the key already exists in the cache."""
12
+
13
+
14
+ class RpathTimeoutError(Exception):
15
+ """An error for when the 'rpath' does not exist after a timeout."""
@@ -13,7 +13,7 @@ Base = declarative_base()
13
13
 
14
14
 
15
15
  def create_schema(cache_dir: str) -> Tuple[Engine, sessionmaker]:
16
- """Create the schema in the sqlite database
16
+ """Create the schema in the sqlite database.
17
17
 
18
18
  Args:
19
19
  cache_dir (str): Location where the cache directory
@@ -1,5 +1,6 @@
1
- from sqlalchemy import Column, Integer, String, DateTime
1
+ from sqlalchemy import Column, DateTime, Integer, String
2
2
  from sqlalchemy.sql import func
3
+
3
4
  from .Base import Base
4
5
 
5
6
  __author__ = "jkanche"
@@ -32,4 +33,3 @@ class Resource(Base):
32
33
 
33
34
  def __repr__(self):
34
35
  return "<Resource(id='%s', rname='%s')>" % (self.id, self.rname)
35
-
@@ -9,7 +9,7 @@ import sys
9
9
 
10
10
 
11
11
  def create_tmp_dir() -> str:
12
- """create a temporary directory.
12
+ """Create a temporary directory.
13
13
 
14
14
  Returns:
15
15
  str: path to the directory
@@ -57,7 +57,7 @@ def copy_or_move(
57
57
 
58
58
 
59
59
  def setup_logging(loglevel):
60
- """Setup basic logging
60
+ """Setup basic logging.
61
61
 
62
62
  Args:
63
63
  loglevel (int): minimum loglevel for emitting messages
@@ -0,0 +1,9 @@
1
+ """Dummy conftest.py for pybiocfilecache.
2
+
3
+ If you don't know what this is for, just leave it empty.
4
+ Read more about conftest.py under:
5
+ - https://docs.pytest.org/en/stable/fixture.html
6
+ - https://docs.pytest.org/en/stable/writing_plugins.html
7
+ """
8
+
9
+ # import pytest
@@ -0,0 +1 @@
1
+ test1
@@ -0,0 +1 @@
1
+ test2
@@ -1,5 +1,4 @@
1
1
  import os
2
- import shutil
3
2
 
4
3
  from pybiocfilecache.BiocFileCache import BiocFileCache
5
4
 
@@ -12,7 +11,7 @@ CACHE_DIR = os.getcwd() + "/cache"
12
11
 
13
12
  def test_create_cache():
14
13
  bfc = BiocFileCache(CACHE_DIR)
15
- assert os.path.exists(CACHE_DIR == True)
14
+ assert os.path.exists(CACHE_DIR)
16
15
 
17
16
  bfc.purge()
18
17
 
@@ -22,16 +21,16 @@ def test_add_get_operations():
22
21
 
23
22
  bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
24
23
  rec1 = bfc.get("test1")
25
- assert rec1 != None
24
+ assert rec1 is not None
26
25
 
27
26
  bfc.add("test2", os.getcwd() + "/tests/data/test2.txt")
28
27
  rec2 = bfc.get("test2")
29
- assert rec2 != None
28
+ assert rec2 is not None
30
29
 
31
- frec1 = open(rec1.rpath, "r").read()
30
+ frec1 = open(rec1.rpath, "r").read().strip()
32
31
  assert frec1 == "test1"
33
32
 
34
- frec2 = open(rec2.rpath, "r").read()
33
+ frec2 = open(rec2.rpath, "r").read().strip()
35
34
  assert frec2 == "test2"
36
35
 
37
36
  bfc.purge()
@@ -42,14 +41,14 @@ def test_remove_operations():
42
41
 
43
42
  bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
44
43
  rec1 = bfc.get("test1")
45
- assert rec1 != None
44
+ assert rec1 is not None
46
45
 
47
46
  bfc.add("test2", os.getcwd() + "/tests/data/test2.txt")
48
47
  rec2 = bfc.get("test2")
49
- assert rec2 != None
48
+ assert rec2 is not None
50
49
 
51
50
  bfc.remove("test1")
52
51
  rec1 = bfc.get("test1")
53
- assert rec1 == None
52
+ assert rec1 is None
54
53
 
55
54
  bfc.purge()
@@ -1,10 +0,0 @@
1
- """
2
- Dummy conftest.py for pybiocfilecache.
3
-
4
- If you don't know what this is for, just leave it empty.
5
- Read more about conftest.py under:
6
- - https://docs.pytest.org/en/stable/fixture.html
7
- - https://docs.pytest.org/en/stable/writing_plugins.html
8
- """
9
-
10
- # import pytest
@@ -1 +0,0 @@
1
- test1
@@ -1 +0,0 @@
1
- test2
File without changes