Repository: pdm-project/pdm
Pull request #2702 (2024-03-18 02:11:53)

feat: allow disabling caches with `--no-cache` option or `PDM_NO_CACHE`
Signed-off-by: Frost Ming <me@frostming.com>

## Pull Request Checklist

- [ ] A news fragment is added in `news/` describing what is new.
- [ ] Test cases added for changed code.

## Describe what you have changed in this PR.


codecov[bot]: ## [Codecov](https://app.codecov.io/gh/pdm-project/pdm/pull/2702?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 84.83%. Comparing base [(`6823199`)](https://app.codecov.io/gh/pdm-project/pdm/commit/68231990d2b2526cf178aee2b12ecbacc4939a76?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project) to head [(`e0eef64`)](https://app.codecov.io/gh/pdm-project/pdm/pull/2702?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project).


<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main    #2702      +/-   ##
==========================================
+ Coverage   84.81%   84.83%   +0.01%     
==========================================
  Files         104      104              
  Lines       10316    10326      +10     
  Branches     2239     2242       +3     
==========================================
+ Hits         8750     8760      +10     
  Misses       1096     1096              
  Partials      470      470              
```

| [Flag](https://app.codecov.io/gh/pdm-project/pdm/pull/2702/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project) | Coverage Δ | |
|---|---|---|
| [unittests](https://app.codecov.io/gh/pdm-project/pdm/pull/2702/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project) | `84.62% <100.00%> (+0.01%)` | :arrow_up: |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project#carryforward-flags-in-the-pull-request-comment) to find out more.


</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/pdm-project/pdm/pull/2702?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=pdm-project).


Patch:
diff --git a/news/2702.feature.md b/news/2702.feature.md
new file mode 100644
index 00000000..106b0c76
--- /dev/null
+++ b/news/2702.feature.md
@@ -0,0 +1,1 @@
+Caches can be disabled by using the `--no-cache` option or setting the `PDM_NO_CACHE` environment variable.
diff --git a/src/pdm/cli/completions/pdm.bash b/src/pdm/cli/completions/pdm.bash
index dc44e699..e150b109 100644
--- a/src/pdm/cli/completions/pdm.bash
+++ b/src/pdm/cli/completions/pdm.bash
@@ -24,7 +24,7 @@ _pdm_a919b69078acdf0a_complete()
 
     # completing for an option
     if [[ ${cur} == --* ]] ; then
-        opts="--config --help --ignore-python --pep582 --quiet --verbose --version"
+        opts="--config --help --ignore-python --no-cache --pep582 --quiet --verbose --version"
 
         case "$com" in
 
diff --git a/src/pdm/cli/completions/pdm.fish b/src/pdm/cli/completions/pdm.fish
index c4bbcbf9..2de8065e 100644
--- a/src/pdm/cli/completions/pdm.fish
+++ b/src/pdm/cli/completions/pdm.fish
@@ -14,6 +14,7 @@ end
 complete -c pdm -n '__fish_pdm_a919b69078acdf0a_complete_no_subcommand' -l config -d 'Specify another config file path [env var: PDM_CONFIG_FILE] '
 complete -c pdm -n '__fish_pdm_a919b69078acdf0a_complete_no_subcommand' -l help -d 'Show this help message and exit.'
 complete -c pdm -n '__fish_pdm_a919b69078acdf0a_complete_no_subcommand' -l ignore-python -d 'Ignore the Python path saved in .pdm-python. [env var: PDM_IGNORE_SAVED_PYTHON]'
+complete -c pdm -n '__fish_pdm_a919b69078acdf0a_complete_no_subcommand' -l no-cache -d 'Disable the cache for the current command. [env var: PDM_NO_CACHE]'
 complete -c pdm -n '__fish_pdm_a919b69078acdf0a_complete_no_subcommand' -l pep582 -d 'Print the command line to be eval\'d by the shell'
 complete -c pdm -n '__fish_pdm_a919b69078acdf0a_complete_no_subcommand' -l quiet -d 'Suppress output'
 complete -c pdm -n '__fish_pdm_a919b69078acdf0a_complete_no_subcommand' -l verbose -d 'Use `-v` for detailed output and `-vv` for more detailed'
diff --git a/src/pdm/cli/completions/pdm.ps1 b/src/pdm/cli/completions/pdm.ps1
index befa6843..01ffe864 100644
--- a/src/pdm/cli/completions/pdm.ps1
+++ b/src/pdm/cli/completions/pdm.ps1
@@ -482,7 +482,7 @@ function TabExpansion($line, $lastWord) {
             default {
                 # No command
                 $command = $null
-                $completer.AddOpts(([Option]::new(("--pep582", "-I", "--ignore-python", "-c", "--config"))))
+                $completer.AddOpts(([Option]::new(("--pep582", "-I", "--ignore-python", "-c", "--config", "--no-cache"))))
                 $completer.AddParams($AllCommands, $false)
             }
         }
diff --git a/src/pdm/cli/completions/pdm.zsh b/src/pdm/cli/completions/pdm.zsh
index 14356b1d..c538c36a 100644
--- a/src/pdm/cli/completions/pdm.zsh
+++ b/src/pdm/cli/completions/pdm.zsh
@@ -46,6 +46,7 @@ _pdm() {
     {-c,--config}'[Specify another config file path\[env var: PDM_CONFIG_FILE\]]' \
     {-V,--version}'[Show the version and exit]' \
     {-I,--ignore-python}'[Ignore the Python path saved in .pdm-python]' \
+    '--no-cache:Disable the cache for the current command. [env var: PDM_NO_CACHE]' \
     '--pep582:Print the command line to be eval by the shell:shell:(zsh bash fish tcsh csh)' \
     '*:: :->_subcmds' \
     && return 0
diff --git a/src/pdm/cli/options.py b/src/pdm/cli/options.py
index 60cf0d9b..a2dc935c 100644
--- a/src/pdm/cli/options.py
+++ b/src/pdm/cli/options.py
@@ -152,6 +152,12 @@ verbose_option.add_argument(
 )
 verbose_option.add_argument("-q", "--quiet", action="store_const", const=-1, dest="verbose", help="Suppress output")
 
+no_cache_option = Option(
+    "--no-cache",
+    action="store_true",
+    default=os.getenv("PDM_NO_CACHE"),
+    help="Disable the cache for the current command. [env var: PDM_NO_CACHE]",
+)
 
 dry_run_option = Option(
     "--dry-run",
diff --git a/src/pdm/core.py b/src/pdm/core.py
index 66786353..319d3ca5 100644
--- a/src/pdm/core.py
+++ b/src/pdm/core.py
@@ -23,7 +23,7 @@ from resolvelib import Resolver
 
 from pdm import termui
 from pdm.__version__ import __version__
-from pdm.cli.options import ignore_python_option, pep582_option, verbose_option
+from pdm.cli.options import ignore_python_option, no_cache_option, pep582_option, verbose_option
 from pdm.cli.utils import ArgumentParser, ErrorArgumentParser
 from pdm.compat import importlib_metadata
 from pdm.exceptions import PdmArgumentError, PdmUsageError
@@ -89,6 +89,7 @@ class Core:
             help="Specify another config file path [env var: PDM_CONFIG_FILE] ",
         )
         verbose_option.add_to_parser(self.parser)
+        no_cache_option.add_to_parser(self.parser)
         ignore_python_option.add_to_parser(self.parser)
         pep582_option.add_to_parser(self.parser)
 
@@ -149,6 +150,10 @@ class Core:
 
         command = cast("BaseCommand | None", getattr(options, "command", None))
         self.config_settings = getattr(options, "config_setting", None)
+
+        if options.no_cache:
+            project.cache_dir = Path(self.create_temp_dir(prefix="pdm-cache-"))
+
         hooks = HookManager(project, getattr(options, "skip", None))
         hooks.try_emit("pre_invoke", command=command.name if command else None, options=options)
 
diff --git a/src/pdm/project/core.py b/src/pdm/project/core.py
index 2e681d37..24ca52ac 100644
--- a/src/pdm/project/core.py
+++ b/src/pdm/project/core.py
@@ -77,6 +77,7 @@ class Project:
         self._lockfile: Lockfile | None = None
         self._environment: BaseEnvironment | None = None
         self._python: PythonInfo | None = None
+        self._cache_dir: Path | None = None
         self.core = core
 
         if global_config is None:
@@ -587,7 +588,13 @@ class Project:
 
     @property
     def cache_dir(self) -> Path:
-        return Path(self.config.get("cache_dir", "")).expanduser()
+        if self._cache_dir is None:
+            self._cache_dir = Path(self.config.get("cache_dir", "")).expanduser()
+        return self._cache_dir
+
+    @cache_dir.setter
+    def cache_dir(self, value: Path) -> None:
+        self._cache_dir = value
 
     def cache(self, name: str) -> Path:
         path = self.cache_dir / name


Test patch:
diff --git a/tests/cli/test_add.py b/tests/cli/test_add.py
index 0b2c0c4f..564938e7 100644
--- a/tests/cli/test_add.py
+++ b/tests/cli/test_add.py
@@ -321,3 +321,12 @@ def test_add_update_reuse_installed_config(project, working_set, repository, pdm
     pdm(["add", "foo"], obj=project, strict=True)
     locked_candidates = project.locked_repository.all_candidates
     assert locked_candidates["foo"].version == "1.0.0"
+
+
+def test_add_disable_cache(project, pdm, working_set):
+    cache_dir = project.cache_dir
+    pdm(["--no-cache", "add", "requests"], obj=project, strict=True)
+    assert "requests" in working_set
+
+    files = [file for file in cache_dir.rglob("*") if file.is_file()]
+    assert not files