From 81df8f26491cb3ea6373977cfed593b44d68e89a Mon Sep 17 00:00:00 2001 From: Muu Date: Sat, 28 Nov 2026 01:23:52 +0800 Subject: [PATCH] feat(python): apply Ruff safe fixes on save and commit (#6540) Adds a "Fix safe lint issues on save" Ruff setting that runs ruff check --fix-only on Python files when saving, and a commit check that applies the same safe fixes before committing. Safe fixes run separately from formatting and Format on save. Also translates the new "No safe lint fixes to apply" message and drops the replaced on-save hint from the ko/ru/tr catalogs. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- crates/ide-core/src/settings.rs | 13 ++ crates/ide-core/src/workflow_settings.rs | 13 ++ crates/ide-host/src/formatter.rs | 136 ++++++++++++++ crates/ide-host/src/ops/lsp.rs | 19 ++ crates/ide-tools/src/formatter.rs | 38 ++++ docs/en/guide/vcs.mdx | 2 +- docs/en/languages/python.mdx | 4 +- docs/en/reference/settings.mdx | 30 +-- docs/zh/guide/vcs.mdx | 2 +- docs/zh/languages/python.mdx | 4 +- docs/zh/reference/settings.mdx | 30 +-- src-tauri/tests/commands.snap | 2 + src/bindings.ts | 8 + src/editor/lsp/actions.ts | 16 +- src/editor/lsp/format.test.ts | 56 +++++- src/editor/lsp/format.ts | 37 +++- .../settings/__tests__/dialog.test.tsx | 26 +++ .../settings/__tests__/languages.test.ts | 5 + .../settings/languages/FormatterPage.tsx | 28 ++- src/features/settings/pages/languages.tsx | 2 + src/features/settings/pages/vcs.tsx | 14 +- src/features/vcs/CommitOptions.tsx | 10 +- .../vcs/__tests__/commitFormat.test.ts | 177 +++++++++++++++++- src/features/vcs/applyCommitChecks.tsx | 18 +- src/features/vcs/commitChecks.tsx | 175 ++++++++++++----- src/platform/languageSettings.ts | 19 +- src/platform/locales/text/en.json | 12 +- src/platform/locales/text/ko.json | 1 - src/platform/locales/text/ru.json | 1 - src/platform/locales/text/tr.json | 1 - src/platform/locales/text/zh-TW.json | 12 +- src/platform/locales/text/zh.json | 12 +- src/platform/workflowSettings.test.ts | 11 ++ src/platform/workflowSettings.ts | 4 + 34 files changed, 820 insertions(+), 118 deletions(-) diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 69aee90229..beced58008 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -1395,6 +1395,8 @@ pub struct ExternalFormatterSettings { /// Prefer this formatter even when a language server offers formatting. pub prefer: bool, pub run_on_save: bool, + /// Ruff only: apply safe lint fixes (`ruff check --fix-only`) on save, independently of formatting. + pub fix_on_save: bool, } impl Default for ExternalFormatterSettings { @@ -1423,6 +1425,7 @@ impl Default for ExternalFormatterSettings { .collect(), prefer: false, run_on_save: false, + fix_on_save: false, } } } @@ -1953,6 +1956,16 @@ impl Settings { mod tests { use super::*; + #[test] + fn ruff_safe_fixes_on_save_default_off_and_round_trip() { + let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap(); + assert!(old.languages.ruff.run_on_save); + assert!(!old.languages.ruff.fix_on_save); + let on: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"fixOnSave":true}}}"#).unwrap(); + assert!(on.languages.ruff.fix_on_save); + assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true); + } + #[test] fn python_interpreter_may_name_a_run_target() { let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() }; diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index 43752cc63d..387a339bf9 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -250,6 +250,8 @@ pub struct CommitSettings { pub reformat: bool, pub optimize_imports: bool, pub cleanup: bool, + /// Apply Ruff's safe lint fixes before composing the commit, independently of formatting. + pub fix_on_commit: bool, pub blank_line_after_subject: bool, pub limit_subject: bool, pub subject_limit: u32, @@ -291,6 +293,7 @@ impl Default for CommitSettings { reformat: false, optimize_imports: false, cleanup: false, + fix_on_commit: false, blank_line_after_subject: true, limit_subject: true, subject_limit: 72, @@ -728,6 +731,16 @@ impl Default for AgentSecuritySettings { mod tests { use super::*; + #[test] + fn ruff_safe_fixes_on_commit_default_off_and_round_trip() { + let old: CommitSettings = serde_json::from_str(r#"{"reformat":true}"#).unwrap(); + assert!(old.reformat); + assert!(!old.fix_on_commit); + let on: CommitSettings = serde_json::from_str(r#"{"fixOnCommit":true}"#).unwrap(); + assert!(on.fix_on_commit); + assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true); + } + #[test] fn clone_submodules_defaults_on_and_can_be_disabled() { let missing: GitSettings = serde_json::from_str("{}").unwrap(); diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index dc6139ebc3..aae7a5ff45 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -480,6 +480,95 @@ pub async fn format_text( format_source(host, window, &project, source, None, options).await } +/// Ruff safe fixes are independent of the formatter selection, language server and format-on-save setting. +fn ruff_fix_enabled(language: &LanguageId, on_save: bool, settings: &Settings) -> bool { + language.as_str() == "python" && (!on_save || settings.languages.ruff.fix_on_save) +} + +/// Apply `ruff check --fix-only` to the supplied (possibly unsaved) text without writing the file. +fn ruff_fix_edits( + tools: &Tools, + settings: &Settings, + root: &Path, + path: &Path, + language: &LanguageId, + text: &str, + on_save: bool, +) -> IdeResult> { + if !ruff_fix_enabled(language, on_save, settings) { + return Ok(Vec::new()); + } + let config_file = ide_sdk::apply::ruff_configuration(root, &settings.languages.ruff.configuration_directory)?; + let custom = ide_sdk::apply::setting_path(root, &settings.languages.ruff.path) + .or_else(|| interpreter_tool(root, path.parent(), settings, "ruff")); + let mut command = tools.formatter_command("ruff", path, custom.as_deref())?; + let dir = config_file.as_deref().and_then(Path::parent).or_else(|| path.parent()); + if let Some(dir) = dir { + command.current_dir(dir); + } + command.args(formatter::ruff_safe_fix_arguments(path, config_file.as_deref())); + let fixed = formatter::run("ruff", command, text, &Default::default())?; + if excluded_output(text, &fixed) { + return Ok(Vec::new()); + } + Ok(diff_edits(&ide_text::Document::new(text), &fixed)) +} + +async fn ruff_fix_source( + host: &Host, + window: &str, + project: &crate::Project, + snap: &FormatSource, + on_save: bool, +) -> IdeResult> { + let settings = project.settings.effective(); + if !ruff_fix_enabled(&snap.language, on_save, &settings) { + return Ok(Vec::new()); + } + host.require_trust(window)?; + if snap.read_only { + return Err(IdeError::invalid("The file is read-only")); + } + let tools = Tools::new(&host.local_data_dir); + let root = project.root.clone(); + let path = snap.path.0.clone(); + let language = snap.language.clone(); + let text = snap.text.clone(); + tokio::task::spawn_blocking(move || ruff_fix_edits(&tools, &settings, &root, &path, &language, &text, on_save)) + .await + .map_err(|e| IdeError::internal(e.to_string()))? + .map_err(|e| e.with_tool("ruff")) +} + +/// Apply Ruff's safe lint fixes to the current unsaved document. +pub async fn ruff_fix(host: &Host, window: &str, doc: DocId) -> IdeResult> { + let project = host.project(window)?; + let snap = project.documents.snapshot(doc)?; + let source = FormatSource { + path: snap.path, + language: snap.language, + text: snap.text, + doc: Some(doc), + version: snap.version, + read_only: snap.read_only, + }; + ruff_fix_source(host, window, &project, &source, true).await +} + +/// Apply Ruff's safe lint fixes to a separate snapshot using the file's language and Ruff settings. +pub async fn ruff_fix_text(host: &Host, window: &str, path: PathBuf, text: String) -> IdeResult> { + let project = host.project(window)?; + if !path.is_absolute() || path.file_name().is_none() { + return Err(IdeError::invalid("Ruff safe fixes require a file path")); + } + if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD { + return Ok(Vec::new()); + } + let language = project.documents.language_of(&path, text.lines().next()).language; + let source = FormatSource { path: path.into(), language, text, doc: None, version: 0, read_only: false }; + ruff_fix_source(host, window, &project, &source, false).await +} + struct FormatSource { path: IpcPath, language: LanguageId, @@ -1325,6 +1414,53 @@ mod tests { assert!(runs_on_save(Prettier, true, false, false)); } + #[test] + fn ruff_safe_fixes_on_save_are_opt_in_and_independent_of_formatting() { + let mut settings = Settings::default(); + let python = LanguageId::new("python"); + assert!(!ruff_fix_enabled(&python, true, &settings)); + assert!(ruff_fix_enabled(&python, false, &settings), "commit fixes do not require the save option"); + settings.editor.format_on_save = true; + settings.languages.ruff.run_on_save = true; + assert!(!ruff_fix_enabled(&python, true, &settings)); + settings.languages.ruff.fix_on_save = true; + assert!(ruff_fix_enabled(&python, true, &settings)); + assert!(!ruff_fix_enabled(&LanguageId::new("typescript"), true, &settings)); + } + + #[cfg(unix)] + #[test] + fn ruff_safe_fixes_use_unsaved_text_and_leave_the_file_on_disk_alone() { + use std::ffi::OsString; + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let file = root.join("main.py"); + std::fs::write(&file, "on disk\n").unwrap(); + let fake = root.join("ruff"); + std::fs::write( + &fake, + "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$0.args\"\nwhile IFS= read -r line || [ -n \"$line\" ]; do\n if [ \"$line\" = 'import os' ]; then printf 'import sys\\n'; else printf '%s\\n' \"$line\"; fi\ndone\n", + ) + .unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + let tools = Tools::with_paths(root.join("tools"), OsString::new(), ide_tools::platform::Platform::current()); + let mut settings = Settings::default(); + settings.languages.ruff.path = fake.to_string_lossy().into_owned(); + let python = LanguageId::new("python"); + let unsaved = "import os\nprint(os.name)\n"; + + assert!(ruff_fix_edits(&tools, &settings, root, &file, &python, unsaved, true).unwrap().is_empty()); + assert!(!root.join("ruff.args").exists()); + settings.languages.ruff.fix_on_save = true; + let edits = ruff_fix_edits(&tools, &settings, root, &file, &python, unsaved, true).unwrap(); + assert_eq!(after(unsaved, &edits), "import sys\nprint(os.name)\n"); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "on disk\n"); + let args = std::fs::read_to_string(root.join("ruff.args")).unwrap(); + assert!(args.starts_with("check\n--fix-only\n--force-exclude\n--stdin-filename\n"), "{args}"); + assert!(args.ends_with(&format!("{}\n-\n", file.display())), "{args}"); + } + #[test] fn forced_tool_runs_that_formatter_or_reports_why_not() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index 4bf652b61a..e2be7224ba 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -1836,6 +1836,23 @@ pub async fn lsp_format_text( crate::formatter::format_text(host, window, path, text, options).await } +/// Apply Ruff's safe lint fixes (`ruff check --fix-only`) to the current unsaved Python document. +#[command(trust = trusted)] +pub async fn ruff_fix(host: &Host, window: &str, doc: DocId) -> IdeResult> { + crate::formatter::ruff_fix(host, window, doc).await +} + +/// Apply Ruff's safe lint fixes to a Python text snapshot without writing the file. +#[command(trust = trusted)] +pub async fn ruff_fix_text( + host: &Host, + window: &str, + path: std::path::PathBuf, + text: String, +) -> IdeResult> { + crate::formatter::ruff_fix_text(host, window, path, text).await +} + #[command(trust = trusted)] pub async fn lsp_source_action_text( host: &Host, @@ -3259,6 +3276,8 @@ ide_command::domain!( lsp_extract_interface_info, lsp_format, lsp_format_text, + ruff_fix, + ruff_fix_text, lsp_snapshot_completion, lsp_snapshot_diagnostics, lsp_source_action_text, diff --git a/crates/ide-tools/src/formatter.rs b/crates/ide-tools/src/formatter.rs index 912f9f5110..48a87b107e 100644 --- a/crates/ide-tools/src/formatter.rs +++ b/crates/ide-tools/src/formatter.rs @@ -247,6 +247,16 @@ pub fn with_python_style(tool: &str, mut args: Vec, style: PythonStyle args } +/// `ruff check --fix-only` over stdin, honoring the project's exclusions and applying no unsafe fixes. +pub fn ruff_safe_fix_arguments(file: &Path, config_file: Option<&Path>) -> Vec { + let mut args: Vec = ["check", "--fix-only", "--force-exclude"].map(OsString::from).into(); + if let Some(config_file) = config_file { + args.extend(["--config".into(), config_file.as_os_str().to_owned()]); + } + args.extend(["--stdin-filename".into(), file.as_os_str().to_owned(), "-".into()]); + args +} + /// `ruff check` that sorts the imports (I) of the text on stdin and removes the unused ones (F401) /// and prints the result, for Optimize Imports where the Ruff server isn't running. Only those two /// are fixed, and F401 only where the project's rules check it (it is in Ruff's defaults; an @@ -596,6 +606,34 @@ mod tests { assert!(supports_range("black", &config)); } + #[test] + fn ruff_applies_only_safe_fixes_to_stdin_with_the_project_config() { + let file = Path::new("/project with spaces/src/example.py"); + let args = |config: Option<&Path>| -> Vec { + ruff_safe_fix_arguments(file, config).into_iter().map(|a| a.to_string_lossy().into_owned()).collect() + }; + assert_eq!( + args(None), + ["check", "--fix-only", "--force-exclude", "--stdin-filename", "/project with spaces/src/example.py", "-"] + ); + assert_eq!( + args(Some(Path::new("/shared/ruff.toml"))), + [ + "check", + "--fix-only", + "--force-exclude", + "--config", + "/shared/ruff.toml", + "--stdin-filename", + "/project with spaces/src/example.py", + "-" + ] + ); + assert!(args(None).contains(&"--force-exclude".into())); + assert!(!args(None).contains(&"--unsafe-fixes".into())); + assert!(!args(None).contains(&"format".into())); + } + #[test] fn ruff_organizes_imports_of_stdin_without_failing_on_what_it_cannot_fix() { let file = Path::new("/project/src/example.py"); diff --git a/docs/en/guide/vcs.mdx b/docs/en/guide/vcs.mdx index bca1da5186..27518b82fa 100644 --- a/docs/en/guide/vcs.mdx +++ b/docs/en/guide/vcs.mdx @@ -91,7 +91,7 @@ Changelists group local changes without touching Git. The default list is called The gear button (**Commit Options**) next to **Commit** has: - **Author:** to commit as someone else (`Name `), and **Sign-off commit**. -- **Commit Checks**: **Reformat code**, **Optimize imports**, **Cleanup** (applies fix-all code actions) and **Run Git hooks** (off adds `--no-verify`). +- **Commit Checks**: **Reformat code**, **Optimize imports**, **Cleanup** (applies fix-all code actions), **Fix Ruff safe lint issues** (`ruff check --fix-only` on Python files before composing the commit, separate from formatting) and **Run Git hooks** (off adds `--no-verify`). - **Advanced Commit Checks**: **Analyze code** (errors and warnings from the language servers) and **Check TODO** (matches from **Settings › Editor › TODO** in changed lines). Create named TODO filters in **Settings › Editor › TODO**. Choose one from **Configure** beside **Check TODO** to check only its patterns. The Commit tool window and TODO tool window save their selections separately for each project. **Review TODOs** opens a tab in the TODO tool window with every finding and a preview of the checked content. Open a finding to jump to its source or diff. If a selected file cannot be checked, the result lists the file and the reason so you can address it before retrying. diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index 7f5ef5a79f..cf8a36ded2 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -94,7 +94,9 @@ Other options on the page: ### Formatting -**Reformat Code** (`⌘⌥L` / `Ctrl+Alt+L`) uses Ruff. In **Settings › Languages & Frameworks › Ruff** you can set the Ruff path, a configuration directory, the **Formatting provider** (**Automatic (language server first)** or Ruff), and **Run on save**. Without a configuration directory, Ruff reads the nearest `pyproject.toml` (`[tool.ruff]`), `ruff.toml` or `.ruff.toml`. When neither the project nor your user configuration has one, Ruff formats with the indentation and line length the editor uses: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the indent, tab character and hard wrap you set in **Settings › Editor › Code Style › Python**. Values set in neither are not passed, so Ruff keeps its own (4 spaces, 88 columns). +**Reformat Code** (`⌘⌥L` / `Ctrl+Alt+L`) uses Ruff. In **Settings › Languages & Frameworks › Ruff** you can set the Ruff path, a configuration directory, the **Formatting provider** (**Automatic (language server first)** or Ruff), and **Format on save**. Without a configuration directory, Ruff reads the nearest `pyproject.toml` (`[tool.ruff]`), `ruff.toml` or `.ruff.toml`. When neither the project nor your user configuration has one, Ruff formats with the indentation and line length the editor uses: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the indent, tab character and hard wrap you set in **Settings › Editor › Code Style › Python**. Values set in neither are not passed, so Ruff keeps its own (4 spaces, 88 columns). + +**Fix safe lint issues on save** is off by default and runs `ruff check --fix-only` on the current unsaved Python text before it is written. It applies only Ruff's safe fixes, not formatting, honors the project's exclusions, and does not depend on the formatting provider or either on-save formatting option. Enable **Fix Ruff safe lint issues** under **Settings › Version Control › Commit › Commit Checks** (or in **Commit Options**) to run the same fixes over each committed Python file before composing a commit. Partial commits keep excluded changes out. Black formats instead of Ruff below a `pyproject.toml` with a `[tool.black]` table, or everywhere when **Formatting provider** is set to Black in **Settings › Languages & Frameworks › Black formatter**. Black reads its `[tool.black]` options itself. The IDE runs the `black` of the project interpreter's environment, else the one in its tools folder or on `PATH`; when none is installed, Reformat Code offers to install it. **Reformat with Black** in Find Action formats with Black whatever the project uses. Black runs on save when its own **Run on save** or the editor's **Format on save** is on. Without a `[tool.black]` (looked up the way Black does: past a `pyproject.toml` without it, up to the repository root) or a user configuration, Black uses that line length too. Files Black's configuration excludes (`force-exclude`) are left unchanged, and Black before 23.11 formats the whole file instead of a selection. diff --git a/docs/en/reference/settings.mdx b/docs/en/reference/settings.mdx index 1983e4fd9e..6d23c524c6 100644 --- a/docs/en/reference/settings.mdx +++ b/docs/en/reference/settings.mdx @@ -206,19 +206,21 @@ Settings › Appearance & Behavior › System Settings › HTTP Proxy. Used by t ### Other sections -| Key | Description | -| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | -| `[actionsOnSave]` | `optimizeImports`, `cleanup` (Tools › Actions on Save). | -| `[mcpServer]` | `enabled`, `backgroundProjects` and the related options (Agents › IDE MCP Server, global only). See [MCP server](/en/guide/mcp). | -| `[agents]` | What agent task headers show (Tools › Agents › Chat). | -| `[languages]` | Interpreters, SDKs and options per language, e.g. `[languages.java]`, `[languages.python]`, `[languages.go]`. | -| `[languageServers]` | Per language server, by name: launch and protocol options, or a server defined here. | -| `[tools]` | Language servers and debug adapters at a location you chose, by command name. | -| `[vcs]`, `[console]`, `[debugger]`, `[run]` | Version Control, Console, Debugger and Run/Debug pages. | -| `[inspections]`, `[spelling]` | Editor › Inspections, Editor › Natural Languages › Spelling. | -| `[ssh]`, `[deployment]`, `runTargets`, `[cmake]` | SSH Configurations, Deployment, Run Targets, CMake. | -| `[projectStructure]` | Source, test, resource and excluded folders (Project Structure). | -| `externalTools` | Tools › External Tools entries. | -| `[plugins.]` | Settings that plugins declare. | +| Key | Description | +| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | +| `[actionsOnSave]` | `optimizeImports`, `cleanup` (Tools › Actions on Save). | +| `[mcpServer]` | `enabled`, `backgroundProjects` and the related options (Agents › IDE MCP Server, global only). See [MCP server](/en/guide/mcp). | +| `[agents]` | What agent task headers show (Tools › Agents › Chat). | +| `[languages]` | Interpreters, SDKs and options per language, e.g. `[languages.java]`, `[languages.python]`, `[languages.go]`. | +| `[languages.ruff]` | Ruff `path`, `configurationDirectory`, `languages`, `prefer`, formatting `runOnSave`, and safe-fix `fixOnSave` (default `false`). | +| `[vcs.commit]` | Before-commit checks and modifications, including `fixOnCommit` for Ruff safe lint fixes (default `false`). | +| `[languageServers]` | Per language server, by name: launch and protocol options, or a server defined here. | +| `[tools]` | Language servers and debug adapters at a location you chose, by command name. | +| `[vcs]`, `[console]`, `[debugger]`, `[run]` | Version Control, Console, Debugger and Run/Debug pages. | +| `[inspections]`, `[spelling]` | Editor › Inspections, Editor › Natural Languages › Spelling. | +| `[ssh]`, `[deployment]`, `runTargets`, `[cmake]` | SSH Configurations, Deployment, Run Targets, CMake. | +| `[projectStructure]` | Source, test, resource and excluded folders (Project Structure). | +| `externalTools` | Tools › External Tools entries. | +| `[plugins.]` | Settings that plugins declare. | The complete list of keys and their defaults is in the source: [`crates/ide-core/src/settings.rs`](https://github.com/l0ng-ai/openidea/blob/main/crates/ide-core/src/settings.rs) and the other `*_settings.rs` files next to it. diff --git a/docs/zh/guide/vcs.mdx b/docs/zh/guide/vcs.mdx index 44cc8bc6b9..1dd05efdc0 100644 --- a/docs/zh/guide/vcs.mdx +++ b/docs/zh/guide/vcs.mdx @@ -89,7 +89,7 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓 **提交** 按钮旁的齿轮按钮(**提交选项**)包含: - **作者:**:以其他身份提交(`Name `),以及 **签署提交**。 -- **提交检查**:**重新格式化代码**、**优化导入**、**清理**(应用 fix-all 代码操作)和 **运行 Git 钩子**(关闭时加 `--no-verify`)。 +- **提交检查**:**重新格式化代码**、**优化导入**、**清理**(应用 fix-all 代码操作)、**修复 Ruff 安全的 lint 问题**(组成提交前对 Python 文件运行 `ruff check --fix-only`,与格式化相互独立)和 **运行 Git 钩子**(关闭时加 `--no-verify`)。 - **高级提交检查**:**分析代码**(语言服务器报告的错误和警告)和 **检查 TODO**(检查改动行是否匹配 **设置 › 编辑器 › TODO** 中的规则)。 在 **设置 › 编辑器 › TODO** 中创建命名筛选器,再通过 **检查 TODO** 旁的 **配置** 选择要检查的模式组。提交工具窗口和 TODO 工具窗口分别按项目保存选择。点击 **查看 TODO** 会在 TODO 工具窗口打开结果标签页,可以浏览全部匹配项和检查时的内容,并跳转到对应源码或差异。若所选文件无法检查,结果会列出文件和原因,便于处理后重试。 diff --git a/docs/zh/languages/python.mdx b/docs/zh/languages/python.mdx index cbc042817c..a249fc78c3 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -94,7 +94,9 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml` ### 格式化 -**重新格式化代码**(`⌘⌥L` / `Ctrl+Alt+L`)使用 Ruff。在 **设置 › 语言和框架 › Ruff** 中可以设置 Ruff 路径、配置目录、**格式化工具**(**自动(优先语言服务器)** 或 Ruff)以及 **保存时运行**。不指定配置目录时,Ruff 读取最近的 `pyproject.toml`(`[tool.ruff]`)、`ruff.toml` 或 `.ruff.toml`。项目和用户配置里都没有时,Ruff 按编辑器使用的缩进和行宽格式化:先看文件的 `.editorconfig`(`indent_size`、`indent_style`、`max_line_length`),再看 **设置 › 编辑器 › 代码样式 › Python** 中设置的缩进、制表符和硬换行。两处都没设置的值不会传给 Ruff,Ruff 仍用自己的默认值(4 个空格、88 列)。 +**重新格式化代码**(`⌘⌥L` / `Ctrl+Alt+L`)使用 Ruff。在 **设置 › 语言和框架 › Ruff** 中可以设置 Ruff 路径、配置目录、**格式化工具**(**自动(优先语言服务器)** 或 Ruff)以及 **保存时格式化**。不指定配置目录时,Ruff 读取最近的 `pyproject.toml`(`[tool.ruff]`)、`ruff.toml` 或 `.ruff.toml`。项目和用户配置里都没有时,Ruff 按编辑器使用的缩进和行宽格式化:先看文件的 `.editorconfig`(`indent_size`、`indent_style`、`max_line_length`),再看 **设置 › 编辑器 › 代码样式 › Python** 中设置的缩进、制表符和硬换行。两处都没设置的值不会传给 Ruff,Ruff 仍用自己的默认值(4 个空格、88 列)。 + +**保存时修复安全的 lint 问题**默认关闭,会在写入前对当前未保存的 Python 文本运行 `ruff check --fix-only`。它只应用 Ruff 的安全修复,不执行格式化,遵循项目的排除配置,并且不依赖所选格式化工具或任一保存时格式化选项。在 **设置 › 版本控制 › 提交 › 提交检查**(或 **提交选项**)中开启 **修复 Ruff 安全的 lint 问题**,会在组成提交前对每个提交的 Python 文件执行相同修复。部分提交不会带入未选择的更改。 在含 `[tool.black]` 表的 `pyproject.toml` 所在目录及其子目录中,或在 **设置 › 语言和框架 › Black 格式化工具** 中把 **格式化工具** 设为 Black 后,由 Black 代替 Ruff 格式化。Black 自己读取 `[tool.black]` 中的选项。IDE 优先使用项目解释器环境中的 `black`,其次是工具文件夹或 `PATH` 中的;都没有安装时,重新格式化代码会提示安装。在查找操作中运行 **使用 Black 重新格式化**,无论项目用什么格式化工具,都会用 Black 格式化。Black 自己的 **保存时运行** 或编辑器的 **保存时格式化** 打开时,保存文件会运行 Black。没有 `[tool.black]`(按 Black 的方式查找:跳过不含它的 `pyproject.toml`,一直到仓库根目录)或用户配置时,Black 也使用这个行宽。Black 配置排除的文件(`force-exclude`)保持不变;23.11 之前的 Black 不能格式化选区,会格式化整个文件。 diff --git a/docs/zh/reference/settings.mdx b/docs/zh/reference/settings.mdx index 7d242bd802..8c2261d935 100644 --- a/docs/zh/reference/settings.mdx +++ b/docs/zh/reference/settings.mdx @@ -206,19 +206,21 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"] ### 其他配置节 -| 键 | 说明 | -| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | -| `[actionsOnSave]` | `optimizeImports`、`cleanup`(工具 › 保存时操作)。 | -| `[mcpServer]` | `enabled`、`backgroundProjects` 等 MCP 服务器的选项(智能体 › IDE MCP 服务器,仅全局)。参见 [MCP Server](/zh/guide/mcp)。 | -| `[agents]` | 智能体任务标题栏显示哪些信息(工具 › 智能体 › 聊天)。 | -| `[languages]` | 各语言的解释器、SDK 和选项,例如 `[languages.java]`、`[languages.python]`、`[languages.go]`。 | -| `[languageServers]` | 按名称配置各语言服务器的启动和协议选项,或在这里定义新的服务器。 | -| `[tools]` | 放在自定义位置的语言服务器和调试适配器,按命令名配置。 | -| `[vcs]`、`[console]`、`[debugger]`、`[run]` | 版本控制、控制台、调试器和运行/调试页面。 | -| `[inspections]`、`[spelling]` | 编辑器 › 检查、编辑器 › 自然语言 › 拼写。 | -| `[ssh]`、`[deployment]`、`runTargets`、`[cmake]` | SSH 配置、部署、运行目标、CMake。 | -| `[projectStructure]` | 源代码、测试、资源和排除文件夹(项目结构)。 | -| `externalTools` | 工具 › 外部工具中的条目。 | -| `[plugins.]` | 插件声明的设置。 | +| 键 | 说明 | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | +| `[actionsOnSave]` | `optimizeImports`、`cleanup`(工具 › 保存时操作)。 | +| `[mcpServer]` | `enabled`、`backgroundProjects` 等 MCP 服务器的选项(智能体 › IDE MCP 服务器,仅全局)。参见 [MCP Server](/zh/guide/mcp)。 | +| `[agents]` | 智能体任务标题栏显示哪些信息(工具 › 智能体 › 聊天)。 | +| `[languages]` | 各语言的解释器、SDK 和选项,例如 `[languages.java]`、`[languages.python]`、`[languages.go]`。 | +| `[languages.ruff]` | Ruff 的 `path`、`configurationDirectory`、`languages`、`prefer`、格式化 `runOnSave`,以及安全修复 `fixOnSave`(默认 `false`)。 | +| `[vcs.commit]` | 提交前检查和修改,包括用于 Ruff 安全 lint 修复的 `fixOnCommit`(默认 `false`)。 | +| `[languageServers]` | 按名称配置各语言服务器的启动和协议选项,或在这里定义新的服务器。 | +| `[tools]` | 放在自定义位置的语言服务器和调试适配器,按命令名配置。 | +| `[vcs]`、`[console]`、`[debugger]`、`[run]` | 版本控制、控制台、调试器和运行/调试页面。 | +| `[inspections]`、`[spelling]` | 编辑器 › 检查、编辑器 › 自然语言 › 拼写。 | +| `[ssh]`、`[deployment]`、`runTargets`、`[cmake]` | SSH 配置、部署、运行目标、CMake。 | +| `[projectStructure]` | 源代码、测试、资源和排除文件夹(项目结构)。 | +| `externalTools` | 工具 › 外部工具中的条目。 | +| `[plugins.]` | 插件声明的设置。 | 完整的配置键和默认值见源码:[`crates/ide-core/src/settings.rs`](https://github.com/l0ng-ai/openidea/blob/main/crates/ide-core/src/settings.rs) 及同目录下的其他 `*_settings.rs` 文件。 diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index f6b0b256f1..9692655d7c 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -601,6 +601,8 @@ remove_recent always project_host bin remove_recent_project always desktop bindings sync replace_in_files trusted project_host bindings async replace_preview trusted project_host bindings async +ruff_fix trusted project_host bindings async +ruff_fix_text trusted project_host bindings async run_application_build trusted project_host bindings async run_application_publish trusted project_host bindings async run_apply_settings trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 32f4914e1b..60b6c36345 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1698,6 +1698,10 @@ export const commands = { replaceInFiles: (request: RequestId, query: SearchQuery, replacement: string, preserveCase: boolean, targets: ReplaceTarget[], allInScope: boolean, onEvent: Channel) => typedError(__TAURI_INVOKE("replace_in_files", { request, query, replacement, preserveCase, targets, allInScope, onEvent })), /** Before / after text of `path` for Replace › Preview (unsaved buffer included). */ replacePreview: (query: SearchQuery, replacement: string, preserveCase: boolean, path: string, only: Pos[] | null) => typedError(__TAURI_INVOKE("replace_preview", { query, replacement, preserveCase, path, only })), + /** Apply Ruff's safe lint fixes (`ruff check --fix-only`) to the current unsaved Python document. */ + ruffFix: (doc: DocId) => typedError(__TAURI_INVOKE("ruff_fix", { doc })), + /** Apply Ruff's safe lint fixes to a Python text snapshot without writing the file. */ + ruffFixText: (path: string, text: string) => typedError(__TAURI_INVOKE("ruff_fix_text", { path, text })), runApplicationBuild: (config: RunConfig_Deserialize, module: string) => typedError(__TAURI_INVOKE("run_application_build", { config, module })), runApplicationPublish: (config: RunConfig_Deserialize, classPaths: string[], mainClass: string) => typedError(__TAURI_INVOKE("run_application_publish", { config, classPaths, mainClass })), /** Kept temporary configurations with the current settings applied. */ @@ -4797,6 +4801,8 @@ export type CommitSettings = { reformat?: boolean, optimizeImports?: boolean, cleanup?: boolean, + /** Apply Ruff's safe lint fixes before composing the commit, independently of formatting. */ + fixOnCommit?: boolean, blankLineAfterSubject?: boolean, limitSubject?: boolean, subjectLimit?: number, @@ -7290,6 +7296,8 @@ export type ExternalFormatterSettings = { /** Prefer this formatter even when a language server offers formatting. */ prefer?: boolean, runOnSave?: boolean, + /** Ruff only: apply safe lint fixes (`ruff check --fix-only`) on save, independently of formatting. */ + fixOnSave?: boolean, }; /** A session on this machine that no task holds yet. */ diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts index 6db23d6300..ec62f7d9aa 100644 --- a/src/editor/lsp/actions.ts +++ b/src/editor/lsp/actions.ts @@ -28,7 +28,7 @@ import { languageSemantics } from "./semantic"; import { caretAnchor, openPopup } from "./popupStore"; import { workflowSettings, type ActionsOnSaveValid } from "@/platform/workflowSettings"; import { startRename } from "./rename"; -import { formatDocument, reformatDialog, type FormatResult } from "./format"; +import { fixRuffDocument, formatDocument, reformatDialog, type FormatResult } from "./format"; import { showHint } from "./hint"; import { refactorThis, @@ -261,14 +261,22 @@ export function formatsOnSave(settings: Settings | null, language: string): bool ); } -/** Format on save (settings.editor.formatOnSave), run by editor/core before writing. */ +/** Whether saving a Python file applies Ruff's safe lint fixes, independently of formatting. */ +export function ruffFixesOnSave(settings: Settings | null, language: string): boolean { + return language === "python" && validateLanguages(settings?.languages).ruff.fixOnSave; +} + +/** Ruff safe fixes, then format on save, run by editor/core before writing the current text. */ export function registerFormatOnSave(): () => void { return registerSaveParticipant({ id: "lsp.formatOnSave", order: 50, beforeSave: async (ctx, handle) => { - if (!handle || ctx.readOnly || !formatsOnSave(useProject.getState().settings, ctx.language)) return; - await formatDocument(handle.view, { explicit: false, selectionOnly: false, onSave: true }); + if (!handle || ctx.readOnly) return; + const settings = useProject.getState().settings; + if (ruffFixesOnSave(settings, ctx.language)) await fixRuffDocument(handle.view); + if (formatsOnSave(settings, ctx.language)) + await formatDocument(handle.view, { explicit: false, selectionOnly: false, onSave: true }); }, }); } diff --git a/src/editor/lsp/format.test.ts b/src/editor/lsp/format.test.ts index f52285ffeb..3613f53588 100644 --- a/src/editor/lsp/format.test.ts +++ b/src/editor/lsp/format.test.ts @@ -1,7 +1,7 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { EditorState, Text } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; -import { CONTRIBUTED_FORMAT } from "@/editor/api"; +import { _saveParticipants, CONTRIBUTED_FORMAT } from "@/editor/api"; import { useProject } from "@/platform/project"; import type { Settings } from "@/bindings"; import { @@ -12,12 +12,21 @@ import { type FormatGuardOptions, } from "@/platform/formatGuard"; import { indentExtension } from "@/editor/core/cm/setup"; -import { IpcError } from "@/platform/ipc"; +import { commands, IpcError } from "@/platform/ipc"; import type { TextEdit } from "@/bindings"; import { dedentsToColumnZero, formatDocument, formatOptionsOf, formattedLines } from "./format"; -import { formatsOnSave } from "./actions"; +import { formatsOnSave, registerFormatOnSave, ruffFixesOnSave } from "./actions"; import * as lsp from "./lsp"; +const ruffFix = vi.hoisted(() => vi.fn()); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + commands: { ...real.commands, ruffFix: (...args: unknown[]) => ruffFix(...args) }, + }; +}); + describe("formatOptionsOf", () => { const stateWith = (...args: Parameters) => EditorState.create({ extensions: indentExtension(...args) }); @@ -188,6 +197,11 @@ describe("format on save provider isolation", () => { expect(formatsOnSave(settings({ biome: { runOnSave: true } }), "markdown")).toBe(false); expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "python")).toBe(true); expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "typescript")).toBe(false); + const safeFixes = settings({ ruff: { runOnSave: false, fixOnSave: true } }); + expect(ruffFixesOnSave(safeFixes, "python")).toBe(true); + expect(ruffFixesOnSave(safeFixes, "typescript")).toBe(false); + expect(formatsOnSave(safeFixes, "python")).toBe(false); + expect(ruffFixesOnSave(settings({ ruff: { runOnSave: true } }), "python")).toBe(false); expect(formatsOnSave(settings({}), "typescript")).toBe(false); // dprint's configuration decides which files it formats. expect(formatsOnSave(settings({ dprint: { runOnSave: true } }), "toml")).toBe(true); @@ -208,6 +222,40 @@ const viewOf = () => const wholeFile = (): TextEdit[] => lines.map((_, line) => ({ range: { start: { line, col: 1 }, end: { line, col: 3 } }, new_text: " " })); +describe("Ruff safe fixes on save", () => { + beforeEach(() => ruffFix.mockReset()); + afterEach(() => vi.restoreAllMocks()); + + it("saving applies the safe-fix command without invoking a formatter", async () => { + const previous = useProject.getState(); + const dispose = registerFormatOnSave(); + const participant = _saveParticipants().find(({ id }) => id === "lsp.formatOnSave")!; + useProject.setState({ + settings: { + editor: { codeStyle: { doNotFormat: ["*.py"] } }, + languages: { ruff: { fixOnSave: true } }, + } as Settings, + }); + const view = viewOf(); + const formatting = vi.spyOn(commands, "lspFormat"); + vi.spyOn(lsp, "lspRequest").mockImplementation(async (run) => { + await run(); + return wholeFile(); + }); + ruffFix.mockResolvedValue({ status: "ok", data: wholeFile() }); + try { + await participant.beforeSave(lsp.docOf(view)!, { view } as never, "explicit"); + expect(ruffFix).toHaveBeenCalledExactlyOnceWith(1); + expect(formatting).not.toHaveBeenCalled(); + expect(view.state.doc.toString()).toBe(["a = 1", "b = 2", "c = 3"].join("\n")); + } finally { + dispose(); + view.destroy(); + useProject.setState(previous); + } + }); +}); + describe("formatting given ranges (Only VCS changed text)", () => { const lineRange = (view: EditorView, n: number) => ({ from: view.state.doc.line(n).from, diff --git a/src/editor/lsp/format.ts b/src/editor/lsp/format.ts index bd5e1912dd..9f70c8d7b9 100644 --- a/src/editor/lsp/format.ts +++ b/src/editor/lsp/format.ts @@ -100,6 +100,8 @@ interface FormatDocumentOptions { tool?: ExternalFormatter; /** Formats only these ranges, e.g. the text changed since the last commit; an empty list formats nothing. */ ranges?: readonly OffsetRange[]; + /** Runs Ruff's safe lint fixes on the whole document instead of any formatting provider. */ + safeFix?: boolean; } interface OffsetRange { @@ -125,6 +127,7 @@ function disjoint(changes: readonly Change[]): Change[] { /** The ranges to format: the given ones, else the selection (when asked for), else the whole file. */ function targetRanges(state: EditorState, opts: FormatDocumentOptions): readonly (OffsetRange | null)[] { + if (opts.safeFix) return [null]; if (opts.ranges) return opts.ranges; const sel = state.selection.main; return (opts.selectionOnly ?? true) && !sel.empty ? [{ from: sel.from, to: sel.to }] : [null]; @@ -139,17 +142,22 @@ export async function formatDocument( return result; } +/** Ruff's safe lint fixes on save, before the file is written and independently of formatting. */ +export async function fixRuffDocument(view: EditorView): Promise { + return format(view, { explicit: false, selectionOnly: false, onSave: true, safeFix: true }); +} + async function format(view: EditorView, opts: FormatDocumentOptions): Promise { const { project, settings } = useProject.getState(); const guard = formatGuardOptions(settings); const path = docOf(view)?.path; - if (path && formatExcluded(path, project?.root ?? null, guard.doNotFormat)) { + if (!opts.safeFix && path && formatExcluded(path, project?.root ?? null, guard.doNotFormat)) { if (opts.explicit) showHint(view, "Formatting is turned off for this file (Code Style › Formatter › Do not format)"); return NOTHING; } const own = contributedAt(view.state, CONTRIBUTED_FORMAT, 0); - if (own && !opts.tool) { + if (own && !opts.tool && !opts.safeFix) { if (opts.onSave && !settings?.editor?.formatOnSave) return NOTHING; return applyContributedFormat(view, own, opts, guard); } @@ -168,7 +176,9 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise { const range = target && { start: offsetToPos(state.doc, target.from), end: offsetToPos(state.doc, target.to) }; return lspRequest(() => - commands.lspFormat(doc.doc, range, { ...options, onSave: opts.onSave, tool: opts.tool }), + opts.safeFix + ? commands.ruffFix(doc.doc) + : commands.lspFormat(doc.doc, range, { ...options, onSave: opts.onSave, tool: opts.tool }), ); }), ); @@ -182,14 +192,21 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise { expect(within(dialog).getByRole("button", { name: "Apply" })).toBeDisabled(); }); + it("keeps Ruff safe fixes on save separate from formatting", async () => { + useProject.setState({ project: { root: "/project" } as never }); + const dialog = await openDialog("python.ruff"); + const format = within(dialog).getByRole("checkbox", { name: "Format on save" }); + const fix = within(dialog).getByRole("checkbox", { name: "Fix safe lint issues on save" }); + expect(format).not.toBeChecked(); + expect(fix).not.toBeChecked(); + expect(within(dialog).getByText(/ruff check --fix-only/)).toBeInTheDocument(); + fireEvent.click(fix); + expect(format).not.toBeChecked(); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" }))); + expect(settingsSet).toHaveBeenCalledExactlyOnceWith("project", "languages.ruff.fixOnSave", "true"); + }); + + it("offers Ruff safe fixes as a distinct before-commit modification", async () => { + const dialog = await openDialog("vcs.commit"); + const fix = within(dialog).getByRole("checkbox", { name: "Fix Ruff safe lint issues" }); + const reformat = within(dialog).getByRole("checkbox", { name: "Reformat code" }); + expect(fix).not.toBeChecked(); + expect(reformat).not.toBeChecked(); + fireEvent.click(fix); + expect(reformat).not.toBeChecked(); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" }))); + expect(settingsSet).toHaveBeenCalledWith("global", "vcs.commit.fixOnCommit", "true"); + }); + it("stages manual editor and proportional CJK fallback names and applies them", async () => { const dialog = await openDialog("editor.font"); fireEvent.change(within(dialog).getByRole("combobox", { name: "Font" }), { target: { value: "Maple Mono NF" } }); diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts index 67d2f850b1..46e7327634 100644 --- a/src/features/settings/__tests__/languages.test.ts +++ b/src/features/settings/__tests__/languages.test.ts @@ -214,6 +214,7 @@ describe("languages settings", () => { languages: ["python"], prefer: false, runOnSave: false, + fixOnSave: false, }); const v = validateLanguages({ ruff: { @@ -222,6 +223,7 @@ describe("languages settings", () => { languages: ["python", null, "python", "pyi"], prefer: true, runOnSave: true, + fixOnSave: true, }, }); expect(v.ruff).toEqual({ @@ -230,8 +232,11 @@ describe("languages settings", () => { languages: ["python", "pyi"], prefer: true, runOnSave: true, + fixOnSave: true, }); expect(v.prettier).toEqual(DEFAULT_LANGUAGES.prettier); + expect(validateLanguages({ ruff: { fixOnSave: "yes" } }).ruff.fixOnSave).toBe(false); + expect(validateLanguages({ ruff: { runOnSave: true } }).ruff.fixOnSave).toBe(false); }); it("leaves the Markdown preview font size unset (editor font) and keeps a set one in 8..72", () => { diff --git a/src/features/settings/languages/FormatterPage.tsx b/src/features/settings/languages/FormatterPage.tsx index fea32ef75d..ca250ffe68 100644 --- a/src/features/settings/languages/FormatterPage.tsx +++ b/src/features/settings/languages/FormatterPage.tsx @@ -1,4 +1,4 @@ -import { useId } from "react"; +import { useId, type ReactNode } from "react"; import type { ExternalFormatter } from "@/bindings"; import { IconButton, Input } from "@/ui"; import { Row, Section, Select, Toggle } from "../components/Form"; @@ -33,7 +33,9 @@ interface FormatterPageProps { configurationDirectory?: boolean; autoLabel?: string; providerHint?: string; + saveLabel?: string; saveHint: string; + children?: ReactNode; } function FormatterPage({ @@ -44,7 +46,9 @@ function FormatterPage({ configurationDirectory = false, autoLabel = "Automatic (language server first)", providerHint, + saveLabel = "Run on save", saveHint, + children, }: FormatterPageProps) { const id = useId(); const [path, setPath] = useSetting(`languages.${tool}.path`); @@ -69,7 +73,8 @@ function FormatterPage({ ]} /> - + + {children} {DEFAULT_LANGUAGES[tool].languages.length > 0 && (
@@ -174,6 +179,18 @@ export function DprintPage() { ); } +function RuffFixOnSave() { + const [fix, setFix] = useSetting("languages.ruff.fixOnSave"); + return ( + + ); +} + export function RuffPage() { return ( + saveLabel="Format on save" + saveHint="Run Ruff formatting on save for enabled languages when it is the selected formatting provider." + > + + ); } diff --git a/src/features/settings/pages/languages.tsx b/src/features/settings/pages/languages.tsx index 699e835bf0..01fad35029 100644 --- a/src/features/settings/pages/languages.tsx +++ b/src/features/settings/pages/languages.tsx @@ -297,6 +297,8 @@ export const LANGUAGE_PAGES: PageSpec[] = [ "pyproject.toml", "ruff.toml", "format on save", + "fix on save", + "safe lint fixes", ], component: RuffPage, }, diff --git a/src/features/settings/pages/vcs.tsx b/src/features/settings/pages/vcs.tsx index a34c88a635..bede8d3ebb 100644 --- a/src/features/settings/pages/vcs.tsx +++ b/src/features/settings/pages/vcs.tsx @@ -679,6 +679,11 @@ function CommitChecks() { /> + } right={ @@ -848,7 +853,14 @@ export const VCS_PAGES: PageSpec[] = [ { kind: "custom", label: "Analyze code", - keywords: ["Check TODO", "Reformat code", "Optimize imports", "Cleanup", "before commit"], + keywords: [ + "Check TODO", + "Reformat code", + "Optimize imports", + "Cleanup", + "Fix Ruff safe lint issues", + "before commit", + ], component: CommitChecks, }, ], diff --git a/src/features/vcs/CommitOptions.tsx b/src/features/vcs/CommitOptions.tsx index d142a94570..052be39cfb 100644 --- a/src/features/vcs/CommitOptions.tsx +++ b/src/features/vcs/CommitOptions.tsx @@ -21,7 +21,14 @@ import { useStagingArea } from "./staging"; import { setCommitTestSelection, useCommitTestSelection } from "./commitTests"; import styles from "./CommitView.module.css"; -type CommitCheck = "reformat" | "optimizeImports" | "cleanup" | "analyzeCode" | "checkTodo" | "postponeSlowChecks"; +type CommitCheck = + | "reformat" + | "optimizeImports" + | "cleanup" + | "fixOnCommit" + | "analyzeCode" + | "checkTodo" + | "postponeSlowChecks"; async function setCheck(key: CommitCheck, value: boolean) { if (!isTauri()) return; @@ -184,6 +191,7 @@ export function CommitOptionsBody({ {check("reformat", "Reformat code")} {check("optimizeImports", "Optimize imports")} {check("cleanup", "Cleanup")} + {check("fixOnCommit", "Fix Ruff safe lint issues")} useCommit.setState({ runHooks: v })} label="Run Git hooks" />
diff --git a/src/features/vcs/__tests__/commitFormat.test.ts b/src/features/vcs/__tests__/commitFormat.test.ts index 92abe1a8bd..204c6a32f1 100644 --- a/src/features/vcs/__tests__/commitFormat.test.ts +++ b/src/features/vcs/__tests__/commitFormat.test.ts @@ -3,11 +3,27 @@ import type { CommitOptions, DocumentInfo, FileStatus, LineHunk, Settings, TextE import { commands } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { runCommitModifications } from "../commitChecks"; +import { modifyReviewedApply } from "../applyCommitChecks"; +import { useVcs } from "../store"; -vi.mock("@/platform/ipc", async (original) => ({ - ...(await original()), - isTauri: () => true, +const ruffFixText = vi.hoisted(() => vi.fn()); +const refreshNow = vi.hoisted(() => vi.fn(async () => {})); +vi.mock("../store", async (original) => ({ + ...(await original()), + refreshNow: () => refreshNow(), })); +vi.mock("../ops", async (original) => ({ + ...(await original()), + runOp: (_label: string, run: () => Promise) => run(), +})); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + isTauri: () => true, + commands: { ...real.commands, ruffFixText: (...args: unknown[]) => ruffFixText(...args) }, + }; +}); const path = "/p/source.ts"; const file: FileStatus = { path, relPath: "source.ts", staged: null, unstaged: "modified", renamedFrom: null }; @@ -36,6 +52,7 @@ const selection = async (options: Partial = {}) => ({ }); beforeEach(() => { + ruffFixText.mockReset().mockResolvedValue(ok([])); useProject.setState({ settings: { vcs: { commit: { reformat: true } } } as Settings }); }); @@ -60,6 +77,160 @@ function mockFormat(hunks: LineHunk[]) { } describe("before-commit formatting", () => { + it("does nothing when every before-commit modification is off", async () => { + useProject.setState({ settings: { vcs: { commit: {} } } as Settings }); + const opened = vi.spyOn(commands, "docOpen"); + expect(await runCommitModifications([file], () => selection())).toEqual([]); + expect(opened).not.toHaveBeenCalled(); + expect(ruffFixText).not.toHaveBeenCalled(); + }); + + it("applies Ruff safe fixes to the whole current unsaved document and saves it", async () => { + const python = { ...file, path: "/p/source.py", relPath: "source.py" }; + useProject.setState({ + settings: { + vcs: { commit: { fixOnCommit: true } }, + editor: { codeStyle: { doNotFormat: ["*.py"] } }, + } as Settings, + }); + const applied = mockFormat([hunk(2, "const c=0;\n")]); + ruffFixText.mockResolvedValue(ok([edit(0, firstEdit), edit(2, lastEdit)])); + + await runCommitModifications([python], () => selection({ stage: [python.path] })); + + expect(ruffFixText).toHaveBeenCalledExactlyOnceWith(python.path, initial); + expect(applied).toHaveBeenCalledWith({ + files: [{ kind: "edit", path: python.path, edits: [edit(0, firstEdit), edit(2, lastEdit)], version: 3 }], + }); + expect(commands.lspFormat).not.toHaveBeenCalled(); + expect(commands.docSave).toHaveBeenCalled(); + }); + + it("fixes a fully staged Python snapshot and syncs the clean working file", async () => { + const python = { ...file, path: "/p/source.py", relPath: "source.py", staged: "modified" as const, unstaged: null }; + useProject.setState({ settings: { vcs: { commit: { fixOnCommit: true } } } as Settings }); + mockFormat([hunk(2, "const c=0;\n")]); + vi.spyOn(commands, "vcsStagedText").mockResolvedValue(ok({ text: initial, version: "stage-zero" })); + vi.spyOn(commands, "docAutosave").mockResolvedValue(ok(true)); + const saved = vi.spyOn(commands, "vcsSaveStagedText").mockResolvedValue(ok("new-version")); + ruffFixText.mockResolvedValue(ok([edit(0, firstEdit), edit(2, lastEdit)])); + + await runCommitModifications([python], () => selection()); + + const fixed = initial.replace("const a=1;", firstEdit).replace("const c=3;", lastEdit); + expect(saved).toHaveBeenCalledExactlyOnceWith(python.path, "stage-zero", fixed); + expect(commands.applyWorkspaceEdit).toHaveBeenCalledWith({ + files: [{ kind: "edit", path: python.path, edits: [edit(0, firstEdit), edit(2, lastEdit)], version: 3 }], + }); + expect(commands.docAutosave).toHaveBeenCalledWith(1); + }); + + it("fixes only the index when the working Python file has unrelated changes", async () => { + const python = { ...file, path: "/p/source.py", relPath: "source.py", staged: "modified" as const }; + useProject.setState({ settings: { vcs: { commit: { fixOnCommit: true } } } as Settings }); + vi.spyOn(commands, "vcsStagedText").mockResolvedValue(ok({ text: initial, version: "stage-zero" })); + vi.spyOn(commands, "vcsFileAt").mockResolvedValue(ok("const a=0;\nconst b=2;\nconst c=0;\n")); + vi.spyOn(commands, "vcsDiffHunks").mockResolvedValue([hunk(2, "const c=0;\n")]); + const saved = vi.spyOn(commands, "vcsSaveStagedText").mockResolvedValue(ok("new-version")); + const opened = vi.spyOn(commands, "docOpen"); + ruffFixText.mockResolvedValue(ok([edit(0, firstEdit), edit(2, lastEdit)])); + + await runCommitModifications([python], () => selection()); + + expect(saved).toHaveBeenCalledExactlyOnceWith( + python.path, + "stage-zero", + initial.replace("const a=1;", firstEdit).replace("const c=3;", lastEdit), + ); + expect(opened).not.toHaveBeenCalled(); + }); + + it("prepares Ruff fixes for only the selected partial-commit hunk", async () => { + const python = { ...file, path: "/p/source.py", relPath: "source.py" }; + useProject.setState({ settings: { vcs: { commit: { fixOnCommit: true } } } as Settings }); + const head = "const a=0;\nconst b=2;\nconst c=0;\n"; + const before = "const a=0;\nconst b=2;\nconst c=3;\n"; + const excluded = hunk(0, "const a=0;\n"); + const selected = hunk(2, "const c=0;\n"); + vi.spyOn(commands, "vcsFileAt").mockResolvedValue(ok(head)); + vi.spyOn(commands, "fsReadText").mockResolvedValue(ok(initial)); + vi.spyOn(commands, "vcsPreviewPartialCommit").mockResolvedValue(ok(before)); + vi.spyOn(commands, "vcsDiffHunks").mockImplementation(async (old, next) => { + if (old === head && next === initial) return [excluded, selected]; + if (old === head && next === before) return [selected]; + return [excluded]; + }); + ruffFixText.mockResolvedValue(ok([edit(0, firstEdit), edit(2, lastEdit)])); + const applied = vi.spyOn(commands, "applyWorkspaceEdit"); + + const result = await runCommitModifications([python], () => + selection({ partial: [{ path: python.path, hunks: [selected] }] }), + ); + + expect(ruffFixText).toHaveBeenCalledExactlyOnceWith(python.path, before); + expect(result).toMatchObject([ + { + path: python.path, + prepared: { before, text: before.replace("const c=3;", lastEdit) }, + workingBefore: initial, + workingEdits: [edit(2, lastEdit)], + }, + ]); + expect(applied).not.toHaveBeenCalled(); + }); + + it("runs Ruff safe fixes before formatting the staged text", async () => { + const python = { ...file, path: "/p/source.py", relPath: "source.py", staged: "modified" as const, unstaged: null }; + useProject.setState({ settings: { vcs: { commit: { fixOnCommit: true, reformat: true } } } as Settings }); + mockFormat([hunk(2, "const c=0;\n")]); + vi.spyOn(commands, "vcsStagedText").mockResolvedValue(ok({ text: initial, version: "stage-zero" })); + vi.spyOn(commands, "docAutosave").mockResolvedValue(ok(true)); + const saved = vi.spyOn(commands, "vcsSaveStagedText").mockResolvedValue(ok("new-version")); + ruffFixText.mockResolvedValue(ok([edit(2, "const c = 3;")])); + const formatting = vi + .spyOn(commands, "lspFormatText") + .mockResolvedValue( + ok([{ range: { start: { line: 2, col: 0 }, end: { line: 2, col: 12 } }, new_text: "const c = 3;" }]), + ); + + await runCommitModifications([python], () => selection()); + + const fixed = initial.replace("const c=3;", "const c = 3;"); + expect(ruffFixText).toHaveBeenCalledExactlyOnceWith(python.path, initial); + expect(formatting).toHaveBeenCalledExactlyOnceWith(python.path, fixed, { tabSize: 4, insertSpaces: true }); + expect(saved).toHaveBeenCalledExactlyOnceWith( + python.path, + "stage-zero", + fixed.replace("const c = 3;", "const c = 3;"), + ); + }); + + it("includes Ruff fixes in the reviewed apply-commit modification flow", async () => { + const python = { ...file, path: "/p/source.py", relPath: "source.py", staged: "modified" as const }; + const review = { kind: "cherry-pick" as const, checkpoint: "one", message: "Apply", paths: [python.path] }; + useVcs.setState({ status: [python] }); + useProject.setState({ settings: { vcs: { commit: { fixOnCommit: true } } } as Settings }); + vi.spyOn(commands, "vcsStagedText").mockResolvedValue(ok({ text: initial, version: "stage-zero" })); + vi.spyOn(commands, "vcsFileAt").mockResolvedValue(ok("const a=0;\nconst b=2;\nconst c=0;\n")); + vi.spyOn(commands, "vcsDiffHunks").mockResolvedValue([hunk(2, "const c=0;\n")]); + const apply = vi.spyOn(commands, "vcsFormatApplyCommit").mockResolvedValue(ok({ ...review, checkpoint: "two" })); + ruffFixText.mockResolvedValue(ok([edit(2, lastEdit)])); + try { + const updated = await modifyReviewedApply("/p", review, () => true); + expect(ruffFixText).toHaveBeenCalledExactlyOnceWith(python.path, initial); + expect(apply).toHaveBeenCalledWith( + "/p", + "one", + [{ path: python.path, version: "stage-zero", text: initial.replace("const c=3;", lastEdit) }], + expect.anything(), + ); + expect(updated?.checkpoint).toBe("two"); + expect(refreshNow).toHaveBeenCalled(); + } finally { + useVcs.setState({ status: [] }); + } + }); + it("organizes imports and cleans up the staged snapshot without applying working-tree edits", async () => { useProject.setState({ settings: { vcs: { commit: { optimizeImports: true, cleanup: true } } } as Settings }); const before = "import unused;\nconst a=1;\n"; diff --git a/src/features/vcs/applyCommitChecks.tsx b/src/features/vcs/applyCommitChecks.tsx index 8de229d706..64131b3486 100644 --- a/src/features/vcs/applyCommitChecks.tsx +++ b/src/features/vcs/applyCommitChecks.tsx @@ -22,10 +22,22 @@ interface WorkingFormat { } export async function modifyReviewedApply(root: string, review: ApplyCommitReview, isCurrent: () => boolean) { - const mods = workflowSettings().vcs.commit; - if (!mods.reformat && !mods.optimizeImports && !mods.cleanup) return review; + const commit = workflowSettings().vcs.commit; + const mods = { + reformat: commit.reformat, + optimizeImports: commit.optimizeImports, + cleanup: commit.cleanup, + ruffFix: commit.fixOnCommit, + }; + if (!mods.reformat && !mods.optimizeImports && !mods.cleanup && !mods.ruffFix) return review; return runOp( - mods.reformat ? "Reformat code" : mods.optimizeImports ? "Optimize imports" : "Cleanup", + mods.reformat + ? "Reformat code" + : mods.optimizeImports + ? "Optimize imports" + : mods.cleanup + ? "Cleanup" + : "Ruff safe fixes", async () => { const staged: StagedTextEdit[] = []; const working: WorkingFormat[] = []; diff --git a/src/features/vcs/commitChecks.tsx b/src/features/vcs/commitChecks.tsx index ffdbc69a7b..86e4d0345f 100644 --- a/src/features/vcs/commitChecks.tsx +++ b/src/features/vcs/commitChecks.tsx @@ -1,7 +1,7 @@ /** * Commit checks (Settings › Version Control › Commit / Git): before-commit - * modifications (Reformat code, Optimize imports, Cleanup) applied through - * the language servers, then the checks registered through + * modifications (Reformat code, Optimize imports, Cleanup, Ruff safe fixes) + * applied through the language servers or Ruff, then the checks registered through * `commitCheckRegistry` (Analyze code, Check TODO) and the Git warnings * (detached HEAD / rebase, file names, large files, CRLF line separators). */ @@ -9,8 +9,8 @@ import type { ReactNode } from "react"; import { ChangeSet, Text } from "@codemirror/state"; import type { FileStatus, - FormatOptions, HunkRange, + LineHunk, PartialCommitFile, Pos, PreparedPartialCommit, @@ -60,6 +60,7 @@ interface Modifications { reformat: boolean; optimizeImports: boolean; cleanup: boolean; + ruffFix: boolean; } const SOURCE_MODIFICATIONS = [ @@ -71,29 +72,32 @@ function sameHunk(a: HunkRange, b: HunkRange): boolean { return a.start === b.start && a.lines === b.lines && a.oldStart === b.oldStart && a.oldLines === b.oldLines; } -async function formatChangedText( +async function changedTextEdits( file: FileStatus, text: string, partial: PartialCommitFile | undefined, - format: (options: FormatOptions) => Promise, + run: () => Promise, + formatting = true, + whole = false, ): Promise<{ edits: TextEdit[]; formatted: string } | null> { const path = stripSlash(file.path); const { project, settings } = useProject.getState(); const guard = formatGuardOptions(settings); - if (formatExcluded(path, project?.root ?? null, guard.doNotFormat)) return null; - const base = (await call(commands.vcsFileAt(renamedFromPath(file) ?? path, "HEAD"))) ?? ""; - const hunks = await commands.vcsDiffHunks(base, text); - const selected = partial ? hunks.filter((h) => partial.hunks.some((want) => sameHunk(want, h))) : hunks; - if (partial && selected.length !== partial.hunks.length) return null; - const changedLines = selected.filter((h) => h.lines > 0); - if (!changedLines.length) return null; - - const editor = settings?.editor; - const edits = guardTextEdits( - text, - await format({ tabSize: editor?.tabSize ?? 4, insertSpaces: editor?.insertSpaces ?? true }), - guard, - ).filter(({ range }) => changedLines.some((h) => range.start.line >= h.start && range.end.line < h.start + h.lines)); + if (formatting && formatExcluded(path, project?.root ?? null, guard.doNotFormat)) return null; + let base = ""; + let hunks: LineHunk[] = []; + let selected: LineHunk[] = []; + let edits = formatting ? guardTextEdits(text, await run(), guard) : await run(); + if (!whole) { + base = (await call(commands.vcsFileAt(renamedFromPath(file) ?? path, "HEAD"))) ?? ""; + hunks = await commands.vcsDiffHunks(base, text); + selected = partial ? hunks.filter((h) => partial.hunks.some((want) => sameHunk(want, h))) : hunks; + if (partial && selected.length !== partial.hunks.length) return null; + const changedLines = selected.filter((h) => h.lines > 0); + edits = edits.filter(({ range }) => + changedLines.some((h) => range.start.line >= h.start && range.end.line < h.start + h.lines), + ); + } if (!edits.length) return null; const document = Text.of(text.split("\n")); const offset = ({ line, col }: Pos) => document.line(line + 1).from + col; @@ -122,10 +126,28 @@ async function formatChangedText( return { edits, formatted }; } -async function previewStagedFormatting(file: FileStatus, before: string) { +async function previewStagedFormatting(file: FileStatus, before: string, mods: Modifications) { if (before.includes("\0")) return; const path = stripSlash(file.path); - return formatChangedText(file, before, undefined, (options) => call(commands.lspFormatText(path, before, options))); + let text = before; + if (mods.ruffFix) { + const fixed = await changedTextEdits( + file, + text, + undefined, + () => call(commands.ruffFixText(path, text)), + false, + true, + ); + if (fixed) text = fixed.formatted; + } + const editor = useProject.getState().settings?.editor; + const options = { tabSize: editor?.tabSize ?? 4, insertSpaces: editor?.insertSpaces ?? true }; + const formatted = await changedTextEdits(file, text, undefined, () => + call(commands.lspFormatText(path, text, options)), + ); + if (formatted) return formatted; + return text === before ? null : { edits: [], formatted: text }; } export async function prepareSnapshotModifications( @@ -134,6 +156,7 @@ export async function prepareSnapshotModifications( mods: Modifications, isCurrent: () => boolean, accept?: (changes: ChangeSet) => boolean, + partial?: PartialCommitFile, ) { const path = stripSlash(file.path); const original = Text.of(before.split("\n")); @@ -167,9 +190,25 @@ export async function prepareSnapshotModifications( } } if (!isCurrent()) return; + if (mods.ruffFix) { + try { + const text = doc.toString(); + // Whole-hunk selections keep fixes inside the selected changed lines. Line-level + // selections use the exclusion projection in `apply` and fail closed on overlap. + const result = + partial && partial.hunks.length + ? await changedTextEdits(file, text, partial, () => call(commands.ruffFixText(path, text)), false) + : { edits: await call(commands.ruffFixText(path, text)) }; + // oxlint-disable-next-line no-await-in-loop -- safe fixes run on the text left by the source actions, before formatting + if (result) await apply(result.edits); + } catch (error) { + logConsole("info", `Ruff safe fixes skipped for ${baseName(path)}: ${failureText(error)}`); + } + } + if (!isCurrent()) return; if (mods.reformat) { try { - const result = await previewStagedFormatting(file, doc.toString()); + const result = await previewStagedFormatting(file, doc.toString(), { ...mods, ruffFix: false }); if (result) await apply(result.edits); } catch (error) { logConsole("info", `Reformat code skipped for ${baseName(path)}: ${failureText(error)}`); @@ -211,7 +250,7 @@ async function preparePartialModifications(file: FileStatus, partial: PartialCom const excluded = partialCommitProjection(working, Text.of(before.split("\n")), hunks, partial); if (!excluded) return; const accept = (changes: ChangeSet) => keepsExcludedChanges(changes, excluded); - const result = await prepareSnapshotModifications(file, before, mods, isCurrent, accept); + const result = await prepareSnapshotModifications(file, before, mods, isCurrent, accept, partial); if (!result) return; const workingEdits = editsFromChanges(working, result.changes.map(excluded)); return { path, prepared: { before, text: result.text }, workingBefore: current, workingEdits }; @@ -230,12 +269,12 @@ export async function syncCommitEdits(path: string, before: string, edits: TextE } } -async function formatStagedText(file: FileStatus, before: string) { +async function formatStagedText(file: FileStatus, before: string, mods: Modifications) { if (before.includes("\0")) return; const path = stripSlash(file.path); const mode = await call(commands.vcsFileMode(path, ":0")); if (mode !== "100644" && mode !== "100755") return; - const result = await previewStagedFormatting(file, before); + const result = await previewStagedFormatting(file, before, mods); if (result) await call(commands.vcsStageFormattedText(path, before, result.formatted)); } @@ -247,7 +286,7 @@ async function modifyFile( index: boolean, ) { const path = stripSlash(file.path); - if (index && (mods.optimizeImports || mods.cleanup)) { + if (index && (mods.optimizeImports || mods.cleanup || mods.ruffFix)) { const project = useProject.getState().project; const isCurrent = () => useProject.getState().project === project; const staged = await call(commands.vcsStagedText(path)); @@ -261,10 +300,10 @@ async function modifyFile( } if (!mods.reformat) return; } - const staged = index ? (await call(commands.vcsFileAt(path, ":0")))?.replace(/\r\n?/g, "\n") : undefined; + let staged = index ? (await call(commands.vcsFileAt(path, ":0")))?.replace(/\r\n?/g, "\n") : undefined; if (index && staged === undefined) return; if (staged !== undefined && file.unstaged !== null) { - await formatStagedText(file, staged); + await formatStagedText(file, staged, mods); return; } let info; @@ -282,31 +321,65 @@ async function modifyFile( logConsole("info", `${label} skipped for ${baseName(path)}: ${e instanceof Error ? e.message : String(e)}`); } }; + const applyChangedText = async ( + run: (text: string, snapshot: boolean) => Promise, + formatting = true, + whole = false, + ) => { + const snapshot = await call(commands.docSnapshot(info.id)); + if (staged !== undefined && snapshot.text !== staged) { + const indexText = staged; + const result = await changedTextEdits( + file, + indexText, + undefined, + () => run(indexText, true), + formatting, + whole, + ); + if (!result) return; + await call(commands.vcsStageFormattedText(path, indexText, result.formatted)); + staged = result.formatted; + return; + } + const result = await changedTextEdits( + file, + snapshot.text, + partial, + () => run(snapshot.text, false), + formatting, + whole, + ); + if (!result) return; + await call( + commands.applyWorkspaceEdit({ + files: [{ kind: "edit", path, edits: result.edits, version: snapshot.version }], + }), + ); + if (staged === undefined) return; + await call(commands.docSave(info.id)); + await call(commands.vcsStageFormattedText(path, staged, result.formatted)); + staged = result.formatted; + }; if (!partial && !index) for (const { setting, kind, title } of SOURCE_MODIFICATIONS) { if (mods[setting]) // oxlint-disable-next-line no-await-in-loop -- code actions are applied to one document in order, each on the state left by the previous action await step(title, async () => applyKind(info.id, (await call(commands.docSnapshot(info.id))).text, kind)); } + if (mods.ruffFix) + await step("Ruff safe fixes", () => + applyChangedText((text) => call(commands.ruffFixText(path, text)), false, true), + ); if (mods.reformat) await step("Reformat code", async () => { - const snapshot = await call(commands.docSnapshot(info.id)); - if (staged !== undefined && snapshot.text !== staged) { - await formatStagedText(file, staged); - return; - } - const result = await formatChangedText(file, snapshot.text, partial, (options) => - call(commands.lspFormat(info.id, null, options)), + const editor = useProject.getState().settings?.editor; + const options = { tabSize: editor?.tabSize ?? 4, insertSpaces: editor?.insertSpaces ?? true }; + await applyChangedText((text, snapshot) => + snapshot + ? call(commands.lspFormatText(path, text, options)) + : call(commands.lspFormat(info.id, null, options)), ); - if (!result) return; - await call( - commands.applyWorkspaceEdit({ - files: [{ kind: "edit", path, edits: result.edits, version: snapshot.version }], - }), - ); - if (staged === undefined) return; - await call(commands.docSave(info.id)); - await call(commands.vcsStageFormattedText(path, staged, result.formatted)); }); if (!index) await call(commands.docSave(info.id)); } finally { @@ -328,8 +401,9 @@ export async function runCommitModifications( reformat: commit.reformat, optimizeImports: commit.optimizeImports, cleanup: commit.cleanup, + ruffFix: commit.fixOnCommit, }; - if (!mods.reformat && !mods.optimizeImports && !mods.cleanup) return []; + if (!mods.reformat && !mods.optimizeImports && !mods.cleanup && !mods.ruffFix) return []; if (!isTauri() || !included.length) return []; const { repositories } = await selection(); const working = new Set(repositories.flatMap(({ options }) => options.stage ?? [])); @@ -339,7 +413,14 @@ export async function runCommitModifications( const prepared: PartialCommitModification[] = []; logConsole( "info", - `Before commit: ${[mods.optimizeImports && "optimize imports", mods.cleanup && "cleanup", mods.reformat && "reformat code"].filter(Boolean).join(", ")}`, + `Before commit: ${[ + mods.optimizeImports && "optimize imports", + mods.cleanup && "cleanup", + mods.ruffFix && "Ruff safe fixes", + mods.reformat && "reformat code", + ] + .filter(Boolean) + .join(", ")}`, ); for (const file of included) { const path = stripSlash(file.path); @@ -347,7 +428,7 @@ export async function runCommitModifications( const index = !working.has(path) && !blocks; if (index ? file.staged === "deleted" : file.unstaged === "deleted") continue; try { - if (blocks && (mods.optimizeImports || mods.cleanup || blocks.lineHunks?.length)) { + if (blocks && (mods.optimizeImports || mods.cleanup || mods.ruffFix || blocks.lineHunks?.length)) { // oxlint-disable-next-line no-await-in-loop -- partial modifications are prepared in order and pushed to the shared result list const modification = await preparePartialModifications(file, blocks, mods); if (modification) prepared.push(modification); diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts index f53a76061d..894d2cd132 100644 --- a/src/platform/languageSettings.ts +++ b/src/platform/languageSettings.ts @@ -72,6 +72,11 @@ const DEFAULT_PYTHON_FORMATTER: ExternalFormatterValid = { languages: ["python"], }; +const DEFAULT_RUFF_FORMATTER: LanguagesValid["ruff"] = { + ...DEFAULT_PYTHON_FORMATTER, + fixOnSave: false, +}; + /** `languages.php.languageLevel` values, newest first; `""` = Auto (from `composer.json`). */ export const PHP_LANGUAGE_LEVELS = [ "", @@ -222,7 +227,7 @@ export interface LanguagesValid { oxfmt: ExternalFormatterValid; biome: ExternalFormatterValid; dprint: ExternalFormatterValid; - ruff: ExternalFormatterValid; + ruff: ExternalFormatterValid & { fixOnSave: boolean }; black: ExternalFormatterValid; java: { jdk: string; @@ -349,7 +354,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = { oxfmt: DEFAULT_FORMATTER, biome: DEFAULT_BIOME_FORMATTER, dprint: DEFAULT_DPRINT_FORMATTER, - ruff: DEFAULT_PYTHON_FORMATTER, + ruff: DEFAULT_RUFF_FORMATTER, black: DEFAULT_PYTHON_FORMATTER, java: { jdk: "", @@ -452,6 +457,14 @@ function validateFormatter(raw: unknown, d = DEFAULT_FORMATTER): ExternalFormatt }; } +function validateRuffFormatter(raw: unknown): LanguagesValid["ruff"] { + const ruff = obj(raw); + return { + ...validateFormatter(ruff, DEFAULT_RUFF_FORMATTER), + fixOnSave: bool(ruff.fixOnSave, DEFAULT_RUFF_FORMATTER.fixOnSave), + }; +} + export function validateLanguages(raw: unknown): LanguagesValid { const d = DEFAULT_LANGUAGES; const l = obj(raw); @@ -535,7 +548,7 @@ export function validateLanguages(raw: unknown): LanguagesValid { oxfmt: validateFormatter(l.oxfmt), biome: validateFormatter(l.biome, DEFAULT_BIOME_FORMATTER), dprint: validateFormatter(l.dprint, DEFAULT_DPRINT_FORMATTER), - ruff: validateFormatter(l.ruff, DEFAULT_PYTHON_FORMATTER), + ruff: validateRuffFormatter(l.ruff), black: validateFormatter(l.black, DEFAULT_PYTHON_FORMATTER), java: { jdk: text(java.jdk, d.java.jdk), diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index fe82d79e15..e054775003 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1194,9 +1194,16 @@ "Select Ruff Configuration Directory": "Select Ruff Configuration Directory", "Empty uses the nearest project pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. A configured directory must contain one of them.": "Empty uses the nearest project pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. A configured directory must contain one of them.", "Ruff reads the nearest pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. Use it before the language server when preferred.": "Ruff reads the nearest pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. Use it before the language server when preferred.", - "Run Ruff on save for enabled languages when it is the selected formatting provider.": "Run Ruff on save for enabled languages when it is the selected formatting provider.", + "Run Ruff formatting on save for enabled languages when it is the selected formatting provider.": "Run Ruff formatting on save for enabled languages when it is the selected formatting provider.", + "Format on save": "Format on save", + "Fix safe lint issues on save": "Fix safe lint issues on save", + "Runs ruff check --fix-only on Python files when saving. This is separate from formatting and from Format on save.": "Runs ruff check --fix-only on Python files when saving. This is separate from formatting and from Format on save.", + "Fix Ruff safe lint issues": "Fix Ruff safe lint issues", + "Runs ruff check --fix-only on Python files before composing the commit. This does not format code.": "Runs ruff check --fix-only on Python files before composing the commit. This does not format code.", "Ruff formatting failed": "Ruff formatting failed", "Ruff formatting timed out": "Ruff formatting timed out", + "Ruff safe fixes failed": "Ruff safe fixes failed", + "Ruff safe fixes timed out": "Ruff safe fixes timed out", "Ruff configuration path does not exist: {path}": "Ruff configuration path does not exist: {path}", "Ruff configuration directory has no ruff.toml, .ruff.toml, or pyproject.toml with [tool.ruff]: {path}": "Ruff configuration directory has no ruff.toml, .ruff.toml, or pyproject.toml with [tool.ruff]: {path}", "Show lines added and deleted": "Show lines added and deleted", @@ -4356,5 +4363,6 @@ "Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND. Off: figures open in matplotlib's own window.": "Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND. Off: figures open in matplotlib's own window.", "cProfile": "cProfile", "py-spy": "py-spy", - "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library." + "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.", + "No safe lint fixes to apply": "No safe lint fixes to apply" } diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index b789312e67..96cdf7f0cd 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -1721,7 +1721,6 @@ "Run on save": "저장 시 실행", "Run Prettier on save for enabled languages when it is the selected formatting provider.": "Prettier가 선택된 서식 지정 제공자일 때 활성화된 언어에 대해 저장 시 Prettier를 실행합니다.", "Run oxfmt on save for enabled languages when it is the selected formatting provider.": "oxfmt가 선택된 서식 지정 제공자인 경우 활성화된 언어에 대해 저장 시 oxfmt를 실행합니다.", - "Run Ruff on save for enabled languages when it is the selected formatting provider.": "Ruff가 선택된 서식 지정 제공자일 때 활성화된 언어에 대해 저장 시 Ruff를 실행합니다.", "oxfmt formats an enabled language instead of Prettier below an oxfmt configuration file (.oxfmtrc.json, oxfmt.config.ts) or when it is the selected provider.": "oxfmt 구성 파일(.oxfmtrc.json, oxfmt.config.ts)이 있는 디렉터리 아래에 있거나 oxfmt가 선택된 서식 지정 제공자이면, 활성화된 언어를 Prettier 대신 oxfmt로 서식 지정합니다.", "Ruff reads the nearest pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. Use it before the language server when preferred.": "Ruff는 가장 가까운 pyproject.toml([tool.ruff]), ruff.toml 또는 .ruff.toml을 읽습니다. 우선 사용하도록 설정하면 언어 서버보다 먼저 실행됩니다.", "Enabled languages": "활성화된 언어", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 490a4bf6e9..e5c5b4d6f9 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -2908,7 +2908,6 @@ "Run on save": "Запускать при сохранении", "Run Prettier on save for enabled languages when it is the selected formatting provider.": "Запускать Prettier при сохранении для включённых языков, если он выбран в качестве поставщика форматирования.", "Run oxfmt on save for enabled languages when it is the selected formatting provider.": "Запускать oxfmt при сохранении для включённых языков, если он выбран в качестве поставщика форматирования.", - "Run Ruff on save for enabled languages when it is the selected formatting provider.": "Запускать Ruff при сохранении для включённых языков, если он выбран в качестве поставщика форматирования.", "oxfmt formats an enabled language instead of Prettier below an oxfmt configuration file (.oxfmtrc.json, oxfmt.config.ts) or when it is the selected provider.": "oxfmt форматирует включённый язык вместо Prettier в каталогах с файлом конфигурации oxfmt (.oxfmtrc.json, oxfmt.config.ts) или когда он выбран в качестве поставщика.", "Ruff reads the nearest pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. Use it before the language server when preferred.": "Ruff считывает ближайший pyproject.toml ([tool.ruff]), ruff.toml или .ruff.toml. Используйте его перед языковым сервером при необходимости.", "Enabled languages": "Включённые языки", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 596804767e..b4ae9e7ea5 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -632,7 +632,6 @@ "Select Ruff Configuration Directory": "Ruff Yapılandırma Dizinini Seç", "Empty uses the nearest project pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. A configured directory must contain one of them.": "Boş bırakıldığında en yakın pyproject.toml ([tool.ruff]), ruff.toml veya .ruff.toml dosyası kullanılır. Belirtilen yapılandırma dizini bunlardan birini içermelidir.", "Ruff reads the nearest pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. Use it before the language server when preferred.": "Ruff en yakın pyproject.toml ([tool.ruff]), ruff.toml veya .ruff.toml dosyasını okur. Tercih ediliyorsa dil sunucusundan önce kullanılır.", - "Run Ruff on save for enabled languages when it is the selected formatting provider.": "Ruff seçili biçimlendirme sağlayıcısıysa, etkin dillerde kaydetme sırasında Ruff'u çalıştır.", "Ruff formatting failed": "Ruff biçimlendirmesi başarısız", "Ruff formatting timed out": "Ruff biçimlendirmesi zaman aşımına uğradı", "Ruff configuration path does not exist: {path}": "Ruff yapılandırma yolu mevcut değil: {path}", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 5360a2b6e7..6712f95844 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -2498,7 +2498,12 @@ "Run on save": "儲存時執行", "Run Prettier on save for enabled languages when it is the selected formatting provider.": "對已啟用的語言,在選擇 Prettier 作為格式化工具時於儲存時執行。", "Run oxfmt on save for enabled languages when it is the selected formatting provider.": "對已啟用的語言,在選擇 oxfmt 作為格式化工具時於儲存時執行。", - "Run Ruff on save for enabled languages when it is the selected formatting provider.": "對已啟用的語言,在選擇 Ruff 作為格式化工具時於儲存時執行。", + "Run Ruff formatting on save for enabled languages when it is the selected formatting provider.": "在選擇 Ruff 作為格式化工具時,於儲存時格式化已啟用的語言。", + "Format on save": "儲存時格式化", + "Fix safe lint issues on save": "儲存時修復安全的 lint 問題", + "Runs ruff check --fix-only on Python files when saving. This is separate from formatting and from Format on save.": "儲存 Python 檔案時執行 ruff check --fix-only。此操作與格式化及「儲存時格式化」相互獨立。", + "Fix Ruff safe lint issues": "修復 Ruff 安全的 lint 問題", + "Runs ruff check --fix-only on Python files before composing the commit. This does not format code.": "提交前對 Python 檔案執行 ruff check --fix-only。此操作不會格式化程式碼。", "oxfmt formats an enabled language instead of Prettier below an oxfmt configuration file (.oxfmtrc.json, oxfmt.config.ts) or when it is the selected provider.": "在 oxfmt 設定檔(.oxfmtrc.json、oxfmt.config.ts)所在目錄及其子目錄中,或選擇 oxfmt 作為格式化工具時,oxfmt 將代替 Prettier 格式化已啟用的語言。", "Ruff reads the nearest pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. Use it before the language server when preferred.": "Ruff 會讀取最近的 pyproject.toml([tool.ruff])、ruff.toml 或 .ruff.toml。選擇優先使用 Ruff 時,將優先於語言伺服器。", "Enabled languages": "啟用的語言", @@ -2510,6 +2515,8 @@ "oxfmt formatting timed out": "oxfmt 格式化逾時", "Ruff formatting failed": "Ruff 格式化失敗", "Ruff formatting timed out": "Ruff 格式化逾時", + "Ruff safe fixes failed": "Ruff 安全修復失敗", + "Ruff safe fixes timed out": "Ruff 安全修復逾時", "Ruff configuration path does not exist: {path}": "Ruff 組態路徑不存在:{path}", "Ruff configuration directory has no ruff.toml, .ruff.toml, or pyproject.toml with [tool.ruff]: {path}": "Ruff 組態目錄中沒有 ruff.toml、.ruff.toml 或包含 [tool.ruff] 的 pyproject.toml:{path}", "{name} does not support selection formatting for this language; formatted the whole file": "{name} 不支援此語言的選取範圍格式化,已格式化整個檔案", @@ -9410,5 +9417,6 @@ "Pull request link {text}": "拉取請求連結 {text}", "Issue link {text}": "Issue 連結 {text}", "Commit link {text}": "提交連結 {text}", - "Link {text}": "連結 {text}" + "Link {text}": "連結 {text}", + "No safe lint fixes to apply": "沒有可套用的安全 lint 修正" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 2ad06b3cf9..17fe371ccd 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3047,7 +3047,12 @@ "Run on save": "保存时运行", "Run Prettier on save for enabled languages when it is the selected formatting provider.": "对已启用的语言,在选择 Prettier 作为格式化工具时于保存时运行。", "Run oxfmt on save for enabled languages when it is the selected formatting provider.": "对已启用的语言,在选择 oxfmt 作为格式化工具时于保存时运行。", - "Run Ruff on save for enabled languages when it is the selected formatting provider.": "对已启用的语言,在选择 Ruff 作为格式化工具时于保存时运行。", + "Run Ruff formatting on save for enabled languages when it is the selected formatting provider.": "在选择 Ruff 作为格式化工具时,于保存时格式化已启用的语言。", + "Format on save": "保存时格式化", + "Fix safe lint issues on save": "保存时修复安全的 lint 问题", + "Runs ruff check --fix-only on Python files when saving. This is separate from formatting and from Format on save.": "保存 Python 文件时运行 ruff check --fix-only。此操作与格式化及“保存时格式化”相互独立。", + "Fix Ruff safe lint issues": "修复 Ruff 安全的 lint 问题", + "Runs ruff check --fix-only on Python files before composing the commit. This does not format code.": "提交前对 Python 文件运行 ruff check --fix-only。此操作不会格式化代码。", "oxfmt formats an enabled language instead of Prettier below an oxfmt configuration file (.oxfmtrc.json, oxfmt.config.ts) or when it is the selected provider.": "在 oxfmt 配置文件(.oxfmtrc.json、oxfmt.config.ts)所在目录及其子目录中,或选择 oxfmt 作为格式化工具时,oxfmt 将代替 Prettier 格式化已启用的语言。", "Ruff reads the nearest pyproject.toml ([tool.ruff]), ruff.toml, or .ruff.toml. Use it before the language server when preferred.": "Ruff 会读取最近的 pyproject.toml([tool.ruff])、ruff.toml 或 .ruff.toml。选择优先使用 Ruff 时,将优先于语言服务器。", "Enabled languages": "启用的语言", @@ -3060,6 +3065,8 @@ "oxfmt formatting timed out": "oxfmt 格式化超时", "Ruff formatting failed": "Ruff 格式化失败", "Ruff formatting timed out": "Ruff 格式化超时", + "Ruff safe fixes failed": "Ruff 安全修复失败", + "Ruff safe fixes timed out": "Ruff 安全修复超时", "Ruff configuration path does not exist: {path}": "Ruff 配置路径不存在:{path}", "Ruff configuration directory has no ruff.toml, .ruff.toml, or pyproject.toml with [tool.ruff]: {path}": "Ruff 配置目录中没有 ruff.toml、.ruff.toml 或包含 [tool.ruff] 的 pyproject.toml:{path}", "{name} does not support selection formatting for this language; formatted the whole file": "{name} 不支持此语言的选区格式化,已格式化整个文件", @@ -10883,5 +10890,6 @@ "Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND. Off: figures open in matplotlib's own window.": "运行、调试会话和 Python 控制台的 matplotlib 图形会发送到“绘图”工具窗口,除非运行自行设置了 MPLBACKEND。关闭后,图形在 matplotlib 自己的窗口中打开。", "cProfile": "cProfile", "py-spy": "py-spy", - "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "自动:已安装 py-spy 且无需 root 即可采样时(macOS 除外)使用 py-spy,否则使用标准库的 cProfile。" + "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "自动:已安装 py-spy 且无需 root 即可采样时(macOS 除外)使用 py-spy,否则使用标准库的 cProfile。", + "No safe lint fixes to apply": "没有可应用的安全 lint 修复" } diff --git a/src/platform/workflowSettings.test.ts b/src/platform/workflowSettings.test.ts index 9b4bb47156..dcd2a906d7 100644 --- a/src/platform/workflowSettings.test.ts +++ b/src/platform/workflowSettings.test.ts @@ -82,6 +82,17 @@ describe("validateWorkflow", () => { expect(inclusion("false")).toBe(true); }); + it("keeps Ruff safe fixes on commit opt-in and separate from reformatting", () => { + expect(DEFAULT_WORKFLOW.vcs.commit.fixOnCommit).toBe(false); + expect(validateWorkflow({ vcs: { commit: { reformat: true } } }).vcs.commit.fixOnCommit).toBe(false); + expect(validateWorkflow({ vcs: { commit: { fixOnCommit: true } } }).vcs.commit).toMatchObject({ + fixOnCommit: true, + reformat: false, + optimizeImports: false, + }); + expect(validateWorkflow({ vcs: { commit: { fixOnCommit: "true" } } }).vcs.commit.fixOnCommit).toBe(false); + }); + it("keeps the double-click choice unset until it is made", () => { expect(DEFAULT_WORKFLOW.vcs.commit.doubleClickOpensDiff).toBeNull(); expect(validateWorkflow(undefined).vcs.commit.doubleClickOpensDiff).toBeNull(); diff --git a/src/platform/workflowSettings.ts b/src/platform/workflowSettings.ts index 60efa43534..c771910f0c 100644 --- a/src/platform/workflowSettings.ts +++ b/src/platform/workflowSettings.ts @@ -70,6 +70,8 @@ export interface CommitSettingsValid { reformat: boolean; optimizeImports: boolean; cleanup: boolean; + /** Apply Ruff's safe lint fixes before composing the commit, independently of formatting. */ + fixOnCommit: boolean; blankLineAfterSubject: boolean; limitSubject: boolean; subjectLimit: number; @@ -345,6 +347,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = { reformat: false, optimizeImports: false, cleanup: false, + fixOnCommit: false, blankLineAfterSubject: true, limitSubject: true, subjectLimit: 72, @@ -536,6 +539,7 @@ export function validateVcs(raw: unknown): VcsSettingsValid { reformat: bool(c.reformat, d.commit.reformat), optimizeImports: bool(c.optimizeImports, d.commit.optimizeImports), cleanup: bool(c.cleanup, d.commit.cleanup), + fixOnCommit: bool(c.fixOnCommit, d.commit.fixOnCommit), blankLineAfterSubject: bool(c.blankLineAfterSubject, d.commit.blankLineAfterSubject), limitSubject: bool(c.limitSubject, d.commit.limitSubject), subjectLimit: num(c.subjectLimit, d.commit.subjectLimit, L.messageLimit, true),