Skip to content

Commit

Permalink
Add cache-dir to command-line and pyproject.toml
Browse files Browse the repository at this point in the history
Refs #1313
  • Loading branch information
squiddy committed Dec 23, 2022
1 parent e290050 commit 83a9836
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 10 deletions.
19 changes: 19 additions & 0 deletions README.md
Expand Up @@ -336,6 +336,8 @@ Options:
The name of the file when passing it through stdin
--explain <EXPLAIN>
Explain a rule
--cache-dir <CACHE_DIR>
Path to the cache directory
-h, --help
Print help information
-V, --version
Expand Down Expand Up @@ -1594,6 +1596,23 @@ allowed-confusables = ["−", "ρ", "∗"]

---

#### [`cache-dir`](#cache-dir)

A path to the cache directory.

**Default value**: `.ruff_cache`

**Type**: `PathBuf`

**Example usage**:

```toml
[tool.ruff]
cache-dir = "~/.cache/ruff"
```

---

#### [`dummy-variable-rgx`](#dummy-variable-rgx)

A regular expression used to identify "dummy" variables, or those which should be
Expand Down
7 changes: 7 additions & 0 deletions flake8_to_ruff/src/converter.rs
Expand Up @@ -315,6 +315,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -369,6 +370,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -423,6 +425,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -477,6 +480,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -531,6 +535,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -629,6 +634,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -684,6 +690,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Expand Up @@ -33,6 +33,7 @@ bindings = "bin"
strip = true

[tool.ruff]
cache-dir = "/tmp/ruff"

[tool.ruff.isort]
force-wrap-aliases = true
Expand Down
17 changes: 8 additions & 9 deletions src/cache.rs
Expand Up @@ -36,7 +36,7 @@ struct CheckResult {
messages: Vec<Message>,
}

fn cache_dir() -> &'static Path {
pub fn cache_dir() -> &'static Path {
Path::new(CACHE_DIR.as_ref().map_or(".ruff_cache", String::as_str))
}

Expand All @@ -54,9 +54,7 @@ fn cache_key<P: AsRef<Path>>(path: P, settings: &Settings, autofix: fixer::Mode)
}

/// Initialize the cache directory.
pub fn init() -> Result<()> {
let path = cache_dir();

pub fn init(path: &Path) -> Result<()> {
// Create the cache directories.
create_dir_all(path.join(content_dir()))?;

Expand All @@ -75,15 +73,15 @@ pub fn init() -> Result<()> {
Ok(())
}

fn write_sync(key: u64, value: &[u8]) -> Result<(), std::io::Error> {
fn write_sync(cache_dir: &Path, key: u64, value: &[u8]) -> Result<(), std::io::Error> {
fs::write(
cache_dir().join(content_dir()).join(format!("{key:x}")),
cache_dir.join(content_dir()).join(format!("{key:x}")),
value,
)
}

fn read_sync(key: u64) -> Result<Vec<u8>, std::io::Error> {
fs::read(cache_dir().join(content_dir()).join(format!("{key:x}")))
fn read_sync(cache_dir: &Path, key: u64) -> Result<Vec<u8>, std::io::Error> {
fs::read(cache_dir.join(content_dir()).join(format!("{key:x}")))
}

/// Get a value from the cache.
Expand All @@ -98,7 +96,7 @@ pub fn get<P: AsRef<Path>>(
return None;
};

let encoded = read_sync(cache_key(path, settings, autofix)).ok()?;
let encoded = read_sync(&settings.cache_dir, cache_key(path, settings, autofix)).ok()?;
let (mtime, messages) = match bincode::deserialize::<CheckResult>(&encoded[..]) {
Ok(CheckResult {
metadata: CacheMetadata { mtime },
Expand Down Expand Up @@ -135,6 +133,7 @@ pub fn set<P: AsRef<Path>>(
messages,
};
if let Err(e) = write_sync(
&settings.cache_dir,
cache_key(path, settings, autofix),
&bincode::serialize(&check_result).unwrap(),
) {
Expand Down
5 changes: 5 additions & 0 deletions src/cli.rs
Expand Up @@ -133,6 +133,9 @@ pub struct Cli {
/// Generate shell completion
#[arg(long, hide = true, value_name = "SHELL")]
pub generate_shell_completion: Option<clap_complete_command::Shell>,
/// Path to the cache directory.
#[arg(long)]
pub cache_dir: Option<PathBuf>,
}

impl Cli {
Expand Down Expand Up @@ -180,6 +183,7 @@ impl Cli {
fix: resolve_bool_arg(self.fix, self.no_fix),
format: self.format,
force_exclude: resolve_bool_arg(self.force_exclude, self.no_force_exclude),
cache_dir: self.cache_dir,
},
)
}
Expand Down Expand Up @@ -238,6 +242,7 @@ pub struct Overrides {
pub fix: Option<bool>,
pub format: Option<SerializationFormat>,
pub force_exclude: Option<bool>,
pub cache_dir: Option<PathBuf>,
}

/// Map the CLI settings to a `LogLevel`.
Expand Down
6 changes: 5 additions & 1 deletion src/main.rs
Expand Up @@ -138,8 +138,12 @@ fn inner_main() -> Result<ExitCode> {
}

// Initialize the cache.
let cache_dir = match &pyproject_strategy {
PyprojectDiscovery::Fixed(settings) => &settings.cache_dir,
PyprojectDiscovery::Hierarchical(settings) => &settings.cache_dir,
};
let mut cache_enabled: bool = !cli.no_cache;
if cache_enabled && cache::init().is_err() {
if cache_enabled && cache::init(cache_dir).is_err() {
eprintln!("Unable to initialize cache; disabling...");
cache_enabled = false;
}
Expand Down
13 changes: 13 additions & 0 deletions src/settings/configuration.rs
Expand Up @@ -46,6 +46,7 @@ pub struct Configuration {
pub src: Option<Vec<PathBuf>>,
pub target_version: Option<PythonVersion>,
pub unfixable: Option<Vec<CheckCodePrefix>>,
pub cache_dir: Option<PathBuf>,
// Plugins
pub flake8_annotations: Option<flake8_annotations::settings::Options>,
pub flake8_bugbear: Option<flake8_bugbear::settings::Options>,
Expand Down Expand Up @@ -130,6 +131,14 @@ impl Configuration {
.transpose()?,
target_version: options.target_version,
unfixable: options.unfixable,
cache_dir: options
.cache_dir
.map(|dir| {
let dir = shellexpand::full(&dir);
dir.map(|dir| PathBuf::from(dir.as_ref()))
})
.transpose()
.map_err(|e| anyhow!("Invalid `cache-dir` value: {e}"))?,
// Plugins
flake8_annotations: options.flake8_annotations,
flake8_bugbear: options.flake8_bugbear,
Expand Down Expand Up @@ -184,6 +193,7 @@ impl Configuration {
src: self.src.or(config.src),
target_version: self.target_version.or(config.target_version),
unfixable: self.unfixable.or(config.unfixable),
cache_dir: self.cache_dir.or(config.cache_dir),
// Plugins
flake8_annotations: self.flake8_annotations.or(config.flake8_annotations),
flake8_bugbear: self.flake8_bugbear.or(config.flake8_bugbear),
Expand Down Expand Up @@ -254,6 +264,9 @@ impl Configuration {
if let Some(unfixable) = overrides.unfixable {
self.unfixable = Some(unfixable);
}
if let Some(cache_dir) = overrides.cache_dir {
self.cache_dir = Some(cache_dir);
}
// Special-case: `extend_ignore` and `extend_select` are parallel arrays, so
// push an empty array if only one of the two is provided.
match (overrides.extend_ignore, overrides.extend_select) {
Expand Down
7 changes: 7 additions & 0 deletions src/settings/mod.rs
Expand Up @@ -13,6 +13,7 @@ use path_absolutize::path_dedot;
use regex::Regex;
use rustc_hash::FxHashSet;

use crate::cache::cache_dir;
use crate::checks::CheckCode;
use crate::checks_gen::{CheckCodePrefix, SuffixLength, CATEGORIES};
use crate::settings::configuration::Configuration;
Expand Down Expand Up @@ -49,6 +50,7 @@ pub struct Settings {
pub show_source: bool,
pub src: Vec<PathBuf>,
pub target_version: PythonVersion,
pub cache_dir: PathBuf,
// Plugins
pub flake8_annotations: flake8_annotations::settings::Settings,
pub flake8_bugbear: flake8_bugbear::settings::Settings,
Expand Down Expand Up @@ -140,6 +142,9 @@ impl Settings {
.unwrap_or_else(|| vec![project_root.to_path_buf()]),
target_version: config.target_version.unwrap_or(PythonVersion::Py310),
show_source: config.show_source.unwrap_or_default(),
cache_dir: config
.cache_dir
.unwrap_or_else(|| cache_dir().to_path_buf()),
// Plugins
flake8_annotations: config
.flake8_annotations
Expand Down Expand Up @@ -209,6 +214,7 @@ impl Settings {
show_source: false,
src: vec![path_dedot::CWD.clone()],
target_version: PythonVersion::Py310,
cache_dir: cache_dir().to_path_buf(),
flake8_annotations: flake8_annotations::settings::Settings::default(),
flake8_bugbear: flake8_bugbear::settings::Settings::default(),
flake8_errmsg: flake8_errmsg::settings::Settings::default(),
Expand Down Expand Up @@ -242,6 +248,7 @@ impl Settings {
show_source: false,
src: vec![path_dedot::CWD.clone()],
target_version: PythonVersion::Py310,
cache_dir: cache_dir().to_path_buf(),
flake8_annotations: flake8_annotations::settings::Settings::default(),
flake8_bugbear: flake8_bugbear::settings::Settings::default(),
flake8_errmsg: flake8_errmsg::settings::Settings::default(),
Expand Down
7 changes: 7 additions & 0 deletions src/settings/options.rs
Expand Up @@ -321,6 +321,13 @@ pub struct Options {
"#
)]
pub unfixable: Option<Vec<CheckCodePrefix>>,
#[option(
doc = "A path to the cache directory.",
default = ".ruff_cache",
value_type = "PathBuf",
example = r#"cache-dir = "~/.cache/ruff""#
)]
pub cache_dir: Option<String>,
// Plugins
#[option_group]
pub flake8_annotations: Option<flake8_annotations::settings::Options>,
Expand Down
6 changes: 6 additions & 0 deletions src/settings/pyproject.rs
Expand Up @@ -141,6 +141,7 @@ mod tests {
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -189,6 +190,7 @@ line-length = 79
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -237,6 +239,7 @@ exclude = ["foo.py"]
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_errmsg: None,
flake8_bugbear: None,
Expand Down Expand Up @@ -285,6 +288,7 @@ select = ["E501"]
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -334,6 +338,7 @@ ignore = ["E501"]
src: None,
target_version: None,
unfixable: None,
cache_dir: None,
flake8_annotations: None,
flake8_bugbear: None,
flake8_errmsg: None,
Expand Down Expand Up @@ -415,6 +420,7 @@ other-attribute = 1
format: None,
force_exclude: None,
unfixable: None,
cache_dir: None,
per_file_ignores: Some(FxHashMap::from_iter([(
"__init__.py".to_string(),
vec![CheckCodePrefix::F401]
Expand Down

0 comments on commit 83a9836

Please sign in to comment.