diff --git a/CHANGELOG.md b/CHANGELOG.md index 9844494..8433b5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,19 @@ ## Unreleased -- `ruby-templates check` is faster on apps with many locale files or a large `app/javascript` (one template: about 700 ms to 45 ms on an app with 500 locale files, 700 scripts and `config.i18n.fallbacks = true`): `Rails/I18nMissingKey` reads the default locale's files, once, and the other locales only when a key is missing there; the Stimulus check runs its patterns only over scripts that can register controllers. +- **Breaking:** a department's `enabled = true` in a `.ruby-templates.toml` (`[Layout]`, `[Style]`, `[Turbo]`, ...) only turns back on the rules that are on by default, cancelling an `enabled = false` from a file above. A rule that is off by default (`Layout/EmptyLines`, `Turbo/PreferTurboAttributes`, `Layout/LineLength`, ...) needs its own `[Layout.EmptyLines] enabled = true`, so rules added later can't start rewriting files. +- **Breaking:** `disabled_diagnostics` and the `[jbuilder]` table are removed from `.ruby-templates.toml`; the file reports them as a problem that names the replacement, `[Html.ImgAlt] enabled = false` (or `exclude = [...]` for some files). The VS Code `rubyTemplates..disabledDiagnostics` settings stay. +- A rule that a `.ruby-templates.toml` enables with `enabled = true` stays on when `rubyTemplates..disabledDiagnostics` lists it, as the documented precedence says (the file beats the editor). +- **Breaking:** `ruby-templates check` prints the rule at the end of each text line, `file:line:col: severity: message [Html/ImgAlt]`, and `[Config/Invalid]` for a problem in a `.ruby-templates.toml`. `format --verbose` and the config problems `format` prints on stderr read the same way. +- **Breaking:** the columns of `ruby-templates check` text output count characters from 1 (a byte order mark takes none), as `github`, `json` and `sarif` do, instead of UTF-16 units. +- **Breaking:** the `info` severity is `info` in the text and JSON output (JSON said `note`); GitHub annotations keep `notice` and SARIF `note`, the words they require. +- **Breaking:** the `source` of every diagnostic is `ruby-templates`, for templates and for problems in a `.ruby-templates.toml` (it was `erb`, `haml`, `slim`, `ruby`, `liquid` and `ruby-templates-ls`). +- **Breaking:** `Rails/I18nMissingKey` is renamed `Rails/MissingTranslation`, in diagnostics, `.ruby-templates.toml` and `disabledDiagnostics`; the old name is an unknown rule. +- **Breaking:** the `rubyTemplates.reindentHaml` command is removed; Format Document and Format Selection do the same. +- Liquid is documented as experimental: the `liquid` language id, its extensions and its grammar are outside the 1.0 stability guarantees. +- The rules reference and the guides no longer describe shipped rules as a draft, a roadmap or planned, and no longer mention `ruby-templates-ls --check`. +- `ruby-templates --version` and `ruby-templates-ls --version` (or `-V`) print the version and exit 0 (the language server no longer starts for them); `ruby-templates --help`, `check --help` and `format --help` exit 0 instead of 2. +- `ruby-templates check` is faster on apps with many locale files or a large `app/javascript` (one template: about 700 ms to 45 ms on an app with 500 locale files, 700 scripts and `config.i18n.fallbacks = true`): `Rails/MissingTranslation` reads the default locale's files, once, and the other locales only when a key is missing there; the Stimulus check runs its patterns only over scripts that can register controllers. - `Rails/MissingPartial` finds a partial in the format of the template that renders it, whichever gem or initializer registered that format: `index.mobile.haml` renders `_card.mobile.haml` (`mobile-fu`'s `:mobile`, a custom `.amp`) without a report. - `Rails/UnsafeOutput` no longer reports a safe call with a trailing `if` or `unless` (`== render "a" if x`, `<%== render "a" unless x %>`, `!= render "a" if x`). - `ruby-templates check` and `format` skip `lib/templates` (Rails generator templates), `vendor`, `tmp`, `public` and `log` when walking a folder, as well as hidden folders and `node_modules`; `app/views` may hold folders with those names, and files named on the command line are always processed. `.gitignore` is not read. diff --git a/demo/README.md b/demo/README.md index d2d61db..5621fa0 100644 --- a/demo/README.md +++ b/demo/README.md @@ -6,25 +6,25 @@ ## Що тут лежить -| Папка | Для чого | -| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `rails_app/` | Мінімальний Rails-застосунок без Rails: `Gemfile.lock` з `actionview 8.0`, контролери, хелпери, компоненти, Stimulus, локалі, `config/application.rb` (без нього Rails/I18nMissingKey мовчить), `db/schema.rb`, маршрути | -| `rails_app/app/views/users`, `shared`, `admin`, `layouts`, `user_mailer` | В'ю для навігації, автодоповнення й hover (ERB, Haml, Slim, Jbuilder) | -| `rails_app/engines/blog`, `rails_app/app/views/blog` | Engine в репозиторії (`path:`-гем у `Gemfile`) з `blog/_post` і `blog/_sidebar`; застосунок перекриває `_sidebar` (`users/engines.html.erb`) | -| `rails_app/lib/reports` | ERB з рядками `%` для мови `erb-percent` (її вмикає `files.associations` у `.vscode/settings.json`) | -| `shop_app/`, `demo.code-workspace` | Другий Rails-застосунок для вікна з двома застосунками: свої партіали, переклади, маршрути, `render "x"` без папки | -| `rails_app/app/views/playground/broken` | По одній проблемі на файл для перевірки діагностики | -| `rails_app/app/views/playground/format` | Погано відформатовані файли та файли, які форматер має лишити без змін | -| `rails_app/app/views/playground/editing` | Команди редагування: toggle, wrap, extract partial, коментарі в `.js.erb`, `.css.erb`… і в багаторядкових тегах | -| `rails_app/app/views/playground/editorconfig` | Однаковий файл під чотирма секціями `.editorconfig` (глоби) | -| `rails_app/app/views/playground/liquid` | Liquid: тема магазину й Jekyll-include (`_includes/header.html`) | -| `rails_app/app/views/playground/highlight` | Зразки підсвітки (копії `test/sample.*`) | -| `rails_app/app/views/playground/preview` | Шаблони без Rails-хелперів для Preview / Show Compiled Ruby Source | -| `rails_app/app/views/playground/stimulus` | Атрибути Stimulus-контролерів елемента (`search_controller.js`) в ERB, Haml і Slim | -| `rails_app/app/views/playground/rules` | Правила 0.11–0.14 (Rails, Turbo, Stimulus, Html, A11y): у ERB, Haml і Slim, у кожному файлі спершу рядки, що попереджають, потім ті, що ні (розділ 9) | -| `rails_app/app/views/playground/rules/format` | Правила форматування, вимкнені за замовчуванням, і lint-и `Style/ErbTrimMode`, `Layout/LineLength`; власний `.ruby-templates.toml` вмикає їх усі (розділ 9) | -| `rails_app/bin/rails` | Заглушка: відповідає лише на запит маршрутів, щоб `*_path` працювали без встановленого Rails | -| `no_rails/` | Шаблони без `Gemfile.lock`: Rails-перевірки тут вимкнені | +| Папка | Для чого | +| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `rails_app/` | Мінімальний Rails-застосунок без Rails: `Gemfile.lock` з `actionview 8.0`, контролери, хелпери, компоненти, Stimulus, локалі, `config/application.rb` (без нього Rails/MissingTranslation мовчить), `db/schema.rb`, маршрути | +| `rails_app/app/views/users`, `shared`, `admin`, `layouts`, `user_mailer` | В'ю для навігації, автодоповнення й hover (ERB, Haml, Slim, Jbuilder) | +| `rails_app/engines/blog`, `rails_app/app/views/blog` | Engine в репозиторії (`path:`-гем у `Gemfile`) з `blog/_post` і `blog/_sidebar`; застосунок перекриває `_sidebar` (`users/engines.html.erb`) | +| `rails_app/lib/reports` | ERB з рядками `%` для мови `erb-percent` (її вмикає `files.associations` у `.vscode/settings.json`) | +| `shop_app/`, `demo.code-workspace` | Другий Rails-застосунок для вікна з двома застосунками: свої партіали, переклади, маршрути, `render "x"` без папки | +| `rails_app/app/views/playground/broken` | По одній проблемі на файл для перевірки діагностики | +| `rails_app/app/views/playground/format` | Погано відформатовані файли та файли, які форматер має лишити без змін | +| `rails_app/app/views/playground/editing` | Команди редагування: toggle, wrap, extract partial, коментарі в `.js.erb`, `.css.erb`… і в багаторядкових тегах | +| `rails_app/app/views/playground/editorconfig` | Однаковий файл під чотирма секціями `.editorconfig` (глоби) | +| `rails_app/app/views/playground/liquid` | Liquid: тема магазину й Jekyll-include (`_includes/header.html`) | +| `rails_app/app/views/playground/highlight` | Зразки підсвітки (копії `test/sample.*`) | +| `rails_app/app/views/playground/preview` | Шаблони без Rails-хелперів для Preview / Show Compiled Ruby Source | +| `rails_app/app/views/playground/stimulus` | Атрибути Stimulus-контролерів елемента (`search_controller.js`) в ERB, Haml і Slim | +| `rails_app/app/views/playground/rules` | Правила 0.11–0.14 (Rails, Turbo, Stimulus, Html, A11y): у ERB, Haml і Slim, у кожному файлі спершу рядки, що попереджають, потім ті, що ні (розділ 9) | +| `rails_app/app/views/playground/rules/format` | Правила форматування, вимкнені за замовчуванням, і lint-и `Style/ErbTrimMode`, `Layout/LineLength`; власний `.ruby-templates.toml` вмикає їх усі (розділ 9) | +| `rails_app/bin/rails` | Заглушка: відповідає лише на запит маршрутів, щоб `*_path` працювали без встановленого Rails | +| `no_rails/` | Шаблони без `Gemfile.lock`: Rails-перевірки тут вимкнені | ## 0. Підготовка diff --git a/demo/rails_app/app/views/playground/rules/i18n.html.erb b/demo/rails_app/app/views/playground/rules/i18n.html.erb index 21d7a27..98b6abe 100644 --- a/demo/rails_app/app/views/playground/rules/i18n.html.erb +++ b/demo/rails_app/app/views/playground/rules/i18n.html.erb @@ -1,4 +1,4 @@ -<%# Rails/I18nMissingKey: the key is playground.rules.i18n.; line 3 warns %> +<%# Rails/MissingTranslation: the key is playground.rules.i18n.; line 3 warns %>

<%= t(".title") %>

<%= t(".titel") %>

diff --git a/demo/rails_app/app/views/playground/rules/i18n.html.haml b/demo/rails_app/app/views/playground/rules/i18n.html.haml index 91952e0..4ec47f5 100644 --- a/demo/rails_app/app/views/playground/rules/i18n.html.haml +++ b/demo/rails_app/app/views/playground/rules/i18n.html.haml @@ -1,4 +1,4 @@ --# Rails/I18nMissingKey: the key is playground.rules.i18n.; line 3 warns +-# Rails/MissingTranslation: the key is playground.rules.i18n.; line 3 warns %h1= t(".title") %h2= t(".titel") diff --git a/demo/rails_app/app/views/playground/rules/i18n.html.slim b/demo/rails_app/app/views/playground/rules/i18n.html.slim index 9b9ac9e..66975b3 100644 --- a/demo/rails_app/app/views/playground/rules/i18n.html.slim +++ b/demo/rails_app/app/views/playground/rules/i18n.html.slim @@ -1,4 +1,4 @@ -/ Rails/I18nMissingKey: the key is playground.rules.i18n.; line 3 warns +/ Rails/MissingTranslation: the key is playground.rules.i18n.; line 3 warns h1 = t(".title") h2 = t(".titel") diff --git a/demo/rails_app/config/application.rb b/demo/rails_app/config/application.rb index 067847e..05919b3 100644 --- a/demo/rails_app/config/application.rb +++ b/demo/rails_app/config/application.rb @@ -1,4 +1,4 @@ -# Marks the folder as a Rails app, so the extension reads config/locales for Rails/I18nMissingKey. +# Marks the folder as a Rails app, so the extension reads config/locales for Rails/MissingTranslation. module Demo class Application < Rails::Application config.i18n.default_locale = :en diff --git a/package.json b/package.json index f71534d..a1bd848 100644 --- a/package.json +++ b/package.json @@ -470,10 +470,6 @@ "command": "rubyTemplates.toggleHamlPrefix", "title": "Ruby Templates: Toggle Haml Line Prefix (- / = / -#)" }, - { - "command": "rubyTemplates.reindentHaml", - "title": "Ruby Templates: Re-indent Haml (Document or Selection)" - }, { "command": "rubyTemplates.convertToSlim", "title": "Ruby Templates: Convert ERB/Haml → Slim" @@ -624,10 +620,6 @@ { "command": "rubyTemplates.toggleHamlPrefix", "when": "editorLangId == haml" - }, - { - "command": "rubyTemplates.reindentHaml", - "when": "editorLangId == haml" } ] }, @@ -725,7 +717,7 @@ "Rails/RenderInLoop", "Rails/OutputControlFlow", "Rails/UnsafeOutput", - "Rails/I18nMissingKey", + "Rails/MissingTranslation", "Rails/UnknownRoute", "Turbo/PermanentRequiresId", "Stimulus/UnknownController", @@ -736,7 +728,7 @@ }, "default": [], "uniqueItems": true, - "description": "Built-in ERB diagnostics to turn off, by rule name (`Department/Name`). The `.ruby-templates.toml` file overrides this list." + "description": "Built-in ERB diagnostics to turn off, by rule name (`Department/Name`). A rule a `.ruby-templates.toml` switches with `enabled` follows the file." }, "rubyTemplates.haml.disabledDiagnostics": { "type": "array", @@ -773,7 +765,7 @@ "Rails/UnusedBlockArgument", "Rails/RenderInLoop", "Rails/UnsafeOutput", - "Rails/I18nMissingKey", + "Rails/MissingTranslation", "Rails/UnknownRoute", "Turbo/PermanentRequiresId", "Stimulus/UnknownController", @@ -783,7 +775,7 @@ }, "default": [], "uniqueItems": true, - "description": "Built-in Haml diagnostics to turn off, by rule name (`Department/Name`). The `.ruby-templates.toml` file overrides this list." + "description": "Built-in Haml diagnostics to turn off, by rule name (`Department/Name`). A rule a `.ruby-templates.toml` switches with `enabled` follows the file." }, "rubyTemplates.jbuilder.disabledDiagnostics": { "type": "array", @@ -797,7 +789,7 @@ }, "default": [], "uniqueItems": true, - "description": "Built-in diagnostics to turn off in Jbuilder and Builder views, by rule name (`Department/Name`). The `.ruby-templates.toml` file overrides this list." + "description": "Built-in diagnostics to turn off in Jbuilder and Builder views, by rule name (`Department/Name`). A rule a `.ruby-templates.toml` switches with `enabled` follows the file." }, "rubyTemplates.slim.disabledDiagnostics": { "type": "array", @@ -829,7 +821,7 @@ "Rails/UnusedBlockArgument", "Rails/RenderInLoop", "Rails/UnsafeOutput", - "Rails/I18nMissingKey", + "Rails/MissingTranslation", "Rails/UnknownRoute", "Turbo/PermanentRequiresId", "Stimulus/UnknownController", @@ -839,7 +831,7 @@ }, "default": [], "uniqueItems": true, - "description": "Built-in Slim diagnostics to turn off, by rule name (`Department/Name`). The `.ruby-templates.toml` file overrides this list." + "description": "Built-in Slim diagnostics to turn off, by rule name (`Department/Name`). A rule a `.ruby-templates.toml` switches with `enabled` follows the file." }, "rubyTemplates.erb.diagnostics.enabled": { "type": "boolean", diff --git a/server/src/checks.rs b/server/src/checks.rs index f9635db..d1d4009 100644 --- a/server/src/checks.rs +++ b/server/src/checks.rs @@ -27,6 +27,8 @@ use tower_lsp_server::ls_types::{Diagnostic, Uri}; /// Diagnostic codes every language shares, with `ruby::generated::RUBY_SYNTAX`. pub(crate) const UNRESOLVED_RENDER: &str = "Rails/MissingPartial"; pub(crate) const STRICT_LOCALS: &str = "Rails/StrictLocals"; +/// The `source` of every diagnostic, template or config problem. +pub const DIAGNOSTIC_SOURCE: &str = "ruby-templates"; /// Layouts take what the controller sets; their partials are the page's frame. const LAYOUTS_FOLDER: &str = "layouts"; const ELEMENT_LINTS: [&str; 7] = [ @@ -121,7 +123,7 @@ pub(crate) fn diagnostics_in( // Rails escapes nothing in a text or other non-HTML template, so nothing is left unescaped. out.retain(|d| (html || util::code(d) != Some(unsafe_output::UNSAFE_OUTPUT)) && util::code(d).is_none_or(|code| rules.reports(code))); for d in &mut out { - d.source = Some(doc.lang.diagnostic_source().into()); + d.source = Some(DIAGNOSTIC_SOURCE.into()); } out } @@ -148,7 +150,7 @@ fn view_lints_root(rules: &ResolvedRules, project: &Project, path: &Path) -> Opt attribute_lints::PERMANENT_REQUIRES_ID, attribute_lints::UNKNOWN_CONTROLLER, attribute_lints::UNKNOWN_TARGET_OR_ACTION, - missing_translation::I18N_MISSING_KEY, + missing_translation::MISSING_TRANSLATION, unknown_route::UNKNOWN_ROUTE, ]; let views_root = paths::views_root(path)?; @@ -203,7 +205,7 @@ fn reference_diagnostics( .file_name() .and_then(|name| name.to_str()) .is_some_and(|name| name.split('.').skip(1).any(|segment| paths::is_locale(segment) && !project.is_format(segment))); - if rules.reports(missing_translation::I18N_MISSING_KEY) && !localized { + if rules.reports(missing_translation::MISSING_TRANSLATION) && !localized { if let Some(catalog) = i18n::catalog(project, path) { out.extend(missing_translation::diagnostics(&doc.text, path, project, &catalog, tree.compiled, &tree.root)); } @@ -881,11 +883,11 @@ mod tests { let view = "app/views/users/index.html.erb"; let options = Options::default(); i18n::clear_catalogs(); - assert_eq!(codes(view, &routes, &options), ["Rails/I18nMissingKey", "Rails/UnknownRoute"]); - assert_eq!(codes(view, &[], &options), ["Rails/I18nMissingKey"], "routes not sent"); + assert_eq!(codes(view, &routes, &options), ["Rails/MissingTranslation", "Rails/UnknownRoute"]); + assert_eq!(codes(view, &[], &options), ["Rails/MissingTranslation"], "routes not sent"); assert!(codes("lib/templates/index.html.erb", &routes, &options).is_empty(), "not a view"); let off = Options::from_init(Some( - &serde_json::json!({ "erb": { "disabledDiagnostics": ["Rails/UnknownRoute", "Rails/I18nMissingKey"] } }), + &serde_json::json!({ "erb": { "disabledDiagnostics": ["Rails/UnknownRoute", "Rails/MissingTranslation"] } }), )) .0; assert!(codes(view, &routes, &off).is_empty()); @@ -910,21 +912,21 @@ mod tests { } #[test] - fn diagnostic_source_is_the_file_language() { + fn diagnostic_source_is_the_tool_for_every_language() { let root = std::env::temp_dir().join(format!("rt-source-{}", std::process::id())); let views = root.join("app/views/users"); std::fs::create_dir_all(&views).unwrap(); std::fs::write(root.join("Gemfile.lock"), format!("{GEM_LOCK} actionview (8.0.2)\n")).unwrap(); let render = "<%= render \"users/gone\" %>"; let cases = [ - ("a.html.erb", TemplateLang::Erb, "<% end %>\n
\n", "erb"), - ("b.html.erb", TemplateLang::Erb, render, "erb"), - ("c.haml", TemplateLang::Haml, "%p hi\n %b x\n= render \"users/gone\"\n", "haml"), - ("d.slim", TemplateLang::Slim, "p\n a\n b\n= render \"users/gone\"\n", "slim"), - ("e.skim", TemplateLang::Skim, "p\n a\n b\n", "slim"), - ("f.jbuilder", TemplateLang::Ruby, "json.partial! \"users/gone\"\n", "ruby"), + ("a.html.erb", TemplateLang::Erb, "<% end %>\n
\n"), + ("b.html.erb", TemplateLang::Erb, render), + ("c.haml", TemplateLang::Haml, "%p hi\n %b x\n= render \"users/gone\"\n"), + ("d.slim", TemplateLang::Slim, "p\n a\n b\n= render \"users/gone\"\n"), + ("e.skim", TemplateLang::Skim, "p\n a\n b\n"), + ("f.jbuilder", TemplateLang::Ruby, "json.partial! \"users/gone\"\n"), ]; - for (name, lang, text, source) in cases { + for (name, lang, text) in cases { let uri = crate::util::file_uri(views.join(name)).unwrap(); let found = diagnostics( &uri, @@ -933,14 +935,14 @@ mod tests { ); assert!(!found.is_empty(), "{name}"); for d in found { - assert_eq!(d.source.as_deref(), Some(source), "{name}: {}", d.message); + assert_eq!(d.source.as_deref(), Some(DIAGNOSTIC_SOURCE), "{name}: {}", d.message); } } let uri = crate::util::file_uri(views.join("g.html.erb")).unwrap(); let html = Doc { lang: TemplateLang::Erb, text: "
\n".into(), plain_erb: false, percent_lines: false, version: 0 }; let found = diagnostics(&uri, &html, &Options::default()); assert_eq!(found.iter().filter_map(util::code).collect::>(), [tags::code::UNCLOSED_ELEMENT]); - assert_eq!(found[0].source.as_deref(), Some("erb")); + assert_eq!(found[0].source.as_deref(), Some("ruby-templates")); std::fs::remove_dir_all(&root).unwrap(); } diff --git a/server/src/cli.rs b/server/src/cli.rs index ad1800a..2b5b79c 100644 --- a/server/src/cli.rs +++ b/server/src/cli.rs @@ -29,6 +29,7 @@ const WORKER_STACK: usize = 8 << 20; const HELP: &str = "\ Usage: + ruby-templates --version ruby-templates check [--format text|github|sarif|json] ... ruby-templates format [--check | --write] [--format text|github] [--verbose] [--align-comments] ... ruby-templates format [--check] [--format text|github] [--verbose] [--align-comments] --stdin-filepath [-] @@ -52,9 +53,9 @@ format re-indents HTML ERB, Haml and Slim templates and fixes trailing whitespa the result goes to stdout. --align-comments moves the lines inside ERB comments with the line the comment opens on. ---format picks how check prints: text (the default), github (workflow commands that annotate a pull request), sarif +--format picks how check prints: text (the default; file:line:col: severity: message [Rule]), github (workflow commands that annotate a pull request), sarif (SARIF 2.1.0 for code scanning) or json (one object per line). With format --check, github prints a warning per file that -would change. In github, sarif and json the columns count characters and start at 1. +would change. Columns count characters and start at 1. Severities are error, warning and info, as GitHub's notice and SARIF's note. Both read .ruby-templates.toml files, from the file's folder up. Exit codes: 0 ok, 1 diagnostics (errors or warnings), a problem in a .ruby-templates.toml, or files that would change, 2 usage or I/O error, a formatter bug, @@ -63,6 +64,10 @@ or (for check) a named file that isn't a template. pub fn run(args: &[String]) -> i32 { match args.split_first() { + Some((command, rest)) if matches!(command.as_str(), "check" | "format") && asks_for_help(rest) => { + print!("{HELP}"); + OK + } Some((command, rest)) if command == "check" => match CheckArgs::parse(rest) { Ok(parsed) => check(&parsed.paths, parsed.format), Err(message) => usage(&message), @@ -71,14 +76,31 @@ pub fn run(args: &[String]) -> i32 { Ok(parsed) => format_command(&parsed), Err(message) => usage(&message), }, - Some((flag, _)) if flag == "--help" || flag == "-h" || flag == "help" => { + Some((flag, _)) if is_help(flag) || flag == "help" => { print!("{HELP}"); OK } + Some((flag, _)) if flag == "--version" || flag == "-V" => { + println!("ruby-templates {}", env!("CARGO_PKG_VERSION")); + OK + } _ => usage("expected a command"), } } +/// `--help` or `-h`, unless it is the value of an option. +fn asks_for_help(args: &[String]) -> bool { + let values = args.iter().scan(false, |after_option, arg| { + let is_value = std::mem::replace(after_option, matches!(arg.as_str(), "--format" | "--stdin-filepath")); + Some((arg, is_value)) + }); + values.into_iter().any(|(arg, is_value)| !is_value && is_help(arg)) +} + +fn is_help(arg: &str) -> bool { + arg == "--help" || arg == "-h" +} + fn usage(message: &str) -> i32 { eprintln!("ruby-templates: {message}\n\n{HELP}"); USAGE @@ -226,7 +248,7 @@ struct Source<'a> { text: &'a str, } -/// Prints diagnostics as `file:line:col: severity: message`; 1 when one is a warning or an error, 2 +/// Prints diagnostics as `file:line:col: severity: message [Rule]`; 1 when one is a warning or an error, 2 /// for a file that can't be read or isn't a template. fn check(paths: &[PathBuf], format: Format) -> i32 { let files = template_files(paths); @@ -271,13 +293,7 @@ struct Rendered { impl Rendered { fn add(&mut self, output: Output, source: &Source, (severity, rule, message): (Severity, Option<&str>, &str), range: Range) { if output.format == Format::Text { - let name = match severity { - Severity::Error => "error", - Severity::Warning => "warning", - Severity::Note => "info", - }; - let (line, col) = (range.start.line + 1, range.start.character + 1); - let _ = writeln!(self.stdout, "{}:{line}:{col}: {name}: {message}", source.shown.display()); + let _ = writeln!(self.stdout, "{}", report::text_line(source.shown, source.text, (severity, rule, message), range)); return; } let relative = relative_path(source.path, output.cwd); @@ -309,8 +325,7 @@ impl Checked { } fn render_config_problems(file: &ConfigFile, output: Output) -> Rendered { - // Only the formats that show columns need the file's text. - let text = if output.format == Format::Text { String::new() } else { std::fs::read_to_string(&file.path).unwrap_or_default() }; + let text = std::fs::read_to_string(&file.path).unwrap_or_default(); let shown = shown_path(&file.path, output.cwd); let source = Source { shown, path: &file.path, text: &text }; let mut rendered = Rendered::default(); @@ -373,13 +388,6 @@ fn relative_path(path: &Path, cwd: Option<&Path>) -> PathBuf { from_cwd.components().filter(|part| *part != Component::CurDir).collect() } -fn print_problems(file: &ConfigFile, cwd: Option<&Path>, out: &mut String) { - for problem in &file.problems { - let (line, col) = (problem.range.start.line + 1, problem.range.start.character + 1); - let _ = writeln!(out, "{}:{line}:{col}: warning: {}", shown_path(&file.path, cwd).display(), problem.message); - } -} - /// Prints each file's result in walk order as it arrives; the worst exit code, `USAGE` once stdout is closed. fn print_in_order(results: mpsc::Receiver<(usize, Checked)>, format: Format) -> i32 { let mut stdout = BufWriter::new(std::io::stdout().lock()); @@ -462,9 +470,7 @@ fn print_verbose(shown: &str, settings: &format::Settings, notes: &[String], (ru notes.iter().for_each(|note| eprintln!("{shown}: {note}")); for file in rules.files() { eprintln!("{shown}: read {}", shown_path(&file.path, cwd).display()); - let mut problems = String::new(); - print_problems(file, cwd, &mut problems); - eprint!("{problems}"); + eprint!("{}", render_config_problems(file, Output { format: Format::Text, cwd }).stdout); } } @@ -474,9 +480,7 @@ fn report_config_problems(file: &ConfigFile, args: &FormatArgs, cwd: Option<&Pat print!("{}", render_config_problems(file, Output { format: Format::Github, cwd }).stdout); return; } - let mut problems = String::new(); - print_problems(file, cwd, &mut problems); - eprint!("{problems}"); + eprint!("{}", render_config_problems(file, Output { format: Format::Text, cwd }).stdout); } fn format_text( @@ -588,6 +592,14 @@ mod tests { } } + #[test] + fn help_is_not_an_option_value() { + assert!(asks_for_help(&args(&["--format", "json", "-h"]))); + assert!(asks_for_help(&args(&["--help"]))); + assert!(!asks_for_help(&args(&["--format", "-h"]))); + assert!(!asks_for_help(&args(&["--stdin-filepath", "--help", "-"]))); + } + #[test] fn output_format_arguments() { let parsed = CheckArgs::parse(&args(&["--format", "sarif", "app/views"])).unwrap(); diff --git a/server/src/lang.rs b/server/src/lang.rs index 5858aba..3383a1a 100644 --- a/server/src/lang.rs +++ b/server/src/lang.rs @@ -19,17 +19,6 @@ pub enum TemplateLang { } impl TemplateLang { - /// The `source` of this language's diagnostics; Skim is Slim syntax. - pub fn diagnostic_source(self) -> &'static str { - match self { - Self::Erb => "erb", - Self::Haml => "haml", - Self::Slim | Self::Skim => "slim", - Self::Ruby => "ruby", - Self::Liquid => "liquid", - } - } - pub fn from_uri_or_id(uri: &Uri, language_id: Option<&str>) -> Option { match language_id { Some(id) if id == "erb" || id.starts_with("erb-") => return Some(Self::Erb), diff --git a/server/src/lsp.rs b/server/src/lsp.rs index 648eaf8..62bf5b3 100644 --- a/server/src/lsp.rs +++ b/server/src/lsp.rs @@ -2,7 +2,7 @@ mod complete; mod fixes; mod locals; -use crate::checks::{diagnostics_in, Doc, STRICT_LOCALS, UNRESOLVED_RENDER}; +use crate::checks::{diagnostics_in, Doc, DIAGNOSTIC_SOURCE, STRICT_LOCALS, UNRESOLVED_RENDER}; use crate::code_context; use crate::code_context::{block_locals, code_at, line_roles, render_filter}; use crate::completion::helpers_for; @@ -24,7 +24,7 @@ use crate::rules::resolve::{resolve, Configs, ResolvedRules}; use crate::slim; use crate::slim::hover; use crate::util::{file_location, line_location}; -use crate::{config, erb, format, haml, helpers, outline, partial_rename, ruby, semantic_tokens, signature_help, util}; +use crate::{config, erb, format, haml, helpers, outline, partial_rename, report, ruby, semantic_tokens, signature_help, util}; use dashmap::mapref::entry::Entry; use dashmap::{DashMap, DashSet}; use haml::indent::LineRole; @@ -1178,12 +1178,13 @@ impl ConfigReports { if file.problems.is_empty() || !self.logged.insert(file.path.clone()) { continue; } - let shown = file.path.display(); + let text = std::fs::read_to_string(&file.path).unwrap_or_default(); let mut diagnostics = Vec::new(); for problem in &file.problems { - let (line, col) = (problem.range.start.line + 1, problem.range.start.character + 1); - client.log_message(MessageType::WARNING, format!("{shown}:{line}:{col}: {}", problem.message)).await; - diagnostics.push(Diagnostic { source: Some(SERVER_NAME.into()), ..util::warning(problem.range, problem.message.clone()) }); + let found = (report::Severity::Warning, Some(report::CONFIG_PROBLEM), problem.message.as_str()); + client.log_message(MessageType::WARNING, report::text_line(&file.path, &text, found, problem.range)).await; + let diagnostic = util::coded(util::warning(problem.range, problem.message.clone()), report::CONFIG_PROBLEM); + diagnostics.push(Diagnostic { source: Some(DIAGNOSTIC_SOURCE.into()), ..diagnostic }); } let Some(uri) = util::file_uri(&file.path) else { continue }; client.publish_diagnostics(uri.clone(), diagnostics, None).await; diff --git a/server/src/lsp/fixes.rs b/server/src/lsp/fixes.rs index 962b945..291b4b9 100644 --- a/server/src/lsp/fixes.rs +++ b/server/src/lsp/fixes.rs @@ -6,7 +6,7 @@ use super::{off_server_task, Backend}; use crate::checks::Doc; use crate::erb::html_lint::code::IMG_MISSING_ALT; use crate::rails::attribute_lints::{PERMANENT_REQUIRES_ID, UNKNOWN_CONTROLLER, UNKNOWN_TARGET_OR_ACTION}; -use crate::rails::missing_translation::I18N_MISSING_KEY; +use crate::rails::missing_translation::MISSING_TRANSLATION; use crate::rails::project::Project; use crate::rails::unknown_route::UNKNOWN_ROUTE; use crate::rails::{i18n, locale_edit, paths, stimulus_edit}; @@ -30,7 +30,7 @@ fn is_confident(flagged: &str, suggestion: &str) -> bool { /// Whether the quick fixes of `d` read files, which is done off the server task. fn reads_files(d: &Diagnostic) -> bool { - matches!(util::code(d), Some(I18N_MISSING_KEY | UNKNOWN_CONTROLLER | UNKNOWN_TARGET_OR_ACTION)) + matches!(util::code(d), Some(MISSING_TRANSLATION | UNKNOWN_CONTROLLER | UNKNOWN_TARGET_OR_ACTION)) } fn quick_fix(title: String, d: &Diagnostic, edit: WorkspaceEdit, preferred: bool) -> CodeAction { @@ -66,7 +66,7 @@ pub(super) fn document_fixes(uri: &Uri, doc: &Doc, diagnostics: &[Diagnostic]) - let route = data_str(d, "replace")?; replace(d, format!("Replace with `{route}`"), route.to_string(), route) } - I18N_MISSING_KEY => { + MISSING_TRANSLATION => { let key = data_str(d, "suggest")?; let range = util::position_to_offset(&doc.text, d.range.start)?..util::position_to_offset(&doc.text, d.range.end)?; let quote = doc.text.get(range)?.chars().next().filter(|quote| matches!(quote, '"' | '\''))?; @@ -100,7 +100,7 @@ impl Backend { let diagnostics: Vec = diagnostics.iter().filter(|d| reads_files(d)).cloned().collect(); off_server_task(move || { let fixes = diagnostics.iter().filter_map(|d| match util::code(d)? { - I18N_MISSING_KEY => add_translation(&project, &path, d, can_create), + MISSING_TRANSLATION => add_translation(&project, &path, d, can_create), UNKNOWN_CONTROLLER => create_controller(&path, d, can_create), _ => add_member(&path, d), }); @@ -248,9 +248,10 @@ mod tests { fixed("<%= link_to x, usrs_path %>", &[route]), [("Replace with `users_path`".into(), true, "<%= link_to x, users_path %>".into())] ); - let double = diagnostic("Rails/I18nMissingKey", range(0, 6, 14), json!({ "key": "a.titel", "locale": "en", "suggest": ".title" })); + let double = + diagnostic("Rails/MissingTranslation", range(0, 6, 14), json!({ "key": "a.titel", "locale": "en", "suggest": ".title" })); assert_eq!(fixed("<%= t(\".titel\") %>", &[double]), [("Use `.title`".into(), true, "<%= t(\".title\") %>".into())]); - let single = diagnostic("Rails/I18nMissingKey", range(0, 6, 14), json!({ "suggest": ".title" })); + let single = diagnostic("Rails/MissingTranslation", range(0, 6, 14), json!({ "suggest": ".title" })); assert_eq!(fixed("<%= t('.titel') %>", &[single])[0].2, "<%= t('.title') %>"); let controller = diagnostic("Stimulus/UnknownController", range(0, 22, 27), json!({ "controller": "serch", "suggest": "search" })); assert_eq!( @@ -266,7 +267,7 @@ mod tests { let key = |flagged: &str, suggest: &str| { let text = format!("<%= t(\"{flagged}\") %>"); let end = 7 + flagged.chars().count() as u32; - fixed(&text, &[diagnostic("Rails/I18nMissingKey", range(0, 6, end + 1), json!({ "suggest": suggest }))])[0].1 + fixed(&text, &[diagnostic("Rails/MissingTranslation", range(0, 6, end + 1), json!({ "suggest": suggest }))])[0].1 }; assert!(!key(".x", ".a"), "too short"); assert!(!key(".ab", ".ac"), "a third of a short name"); @@ -285,13 +286,12 @@ mod tests { fn nothing_is_replaced_without_a_name_to_use() { let none = |code: &str, data: serde_json::Value| fixed("<%= t(\".titel\") %>", &[diagnostic(code, range(0, 6, 14), data)]); assert!(none("Rails/UnknownRoute", json!({})).is_empty()); - assert!(none("Rails/I18nMissingKey", json!({ "suggest": null })).is_empty()); + assert!(none("Rails/MissingTranslation", json!({ "suggest": null })).is_empty()); assert!(none("Stimulus/UnknownController", json!({ "suggest": null })).is_empty()); assert!(none("Stimulus/UnknownTargetOrAction", json!({ "controller": "search" })).is_empty()); // The key isn't a string literal there: no quote to keep. - assert!( - fixed("<%= t(:titel) %>", &[diagnostic("Rails/I18nMissingKey", range(0, 6, 12), json!({ "suggest": ".title" }))]).is_empty() - ); + assert!(fixed("<%= t(:titel) %>", &[diagnostic("Rails/MissingTranslation", range(0, 6, 12), json!({ "suggest": ".title" }))]) + .is_empty()); assert!(none("Html/ImgAlt", json!({})).is_empty()); assert!(none("Turbo/PermanentRequiresId", json!(null)).is_empty()); } @@ -323,7 +323,7 @@ mod tests { } fn missing_key(key: &str) -> Diagnostic { - diagnostic("Rails/I18nMissingKey", Range::default(), json!({ "key": key, "locale": "en", "suggest": null })) + diagnostic("Rails/MissingTranslation", Range::default(), json!({ "key": key, "locale": "en", "suggest": null })) } /// The files an action edits, with what the edit made of each one's text, and the files it creates. @@ -423,7 +423,7 @@ mod tests { let (root, view) = app(&[("config/application.rb", ""), ("config/locales/en.yml", "en:\n users:\n index: { title: Users }\n")]); let project = Project::unknown(); assert!(add_translation(&project, &view, &missing_key("users.index.heading"), true).is_none()); - let other_locale = diagnostic("Rails/I18nMissingKey", Range::default(), json!({ "key": "a.b", "locale": "fr" })); + let other_locale = diagnostic("Rails/MissingTranslation", Range::default(), json!({ "key": "a.b", "locale": "fr" })); assert!(add_translation(&project, &view, &other_locale, true).is_none()); std::fs::remove_dir_all(root).unwrap(); } diff --git a/server/src/main.rs b/server/src/main.rs index 526cf29..b90497e 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -1,4 +1,8 @@ #[tokio::main] async fn main() { + if std::env::args().nth(1).is_some_and(|arg| arg == "--version" || arg == "-V") { + println!("ruby-templates-ls {}", env!("CARGO_PKG_VERSION")); + return; + } ruby_templates::serve().await; } diff --git a/server/src/rails/missing_translation.rs b/server/src/rails/missing_translation.rs index 22aadb7..5f145f7 100644 --- a/server/src/rails/missing_translation.rs +++ b/server/src/rails/missing_translation.rs @@ -10,7 +10,7 @@ use ruby_prism::{CallNode, Node, Visit}; use std::path::Path; use tower_lsp_server::ls_types::Diagnostic; -pub(crate) const I18N_MISSING_KEY: &str = "Rails/I18nMissingKey"; +pub(crate) const MISSING_TRANSLATION: &str = "Rails/MissingTranslation"; const TRANSLATIONS: [&[u8]; 2] = [b"t", b"translate"]; /// Options that make the key resolve somewhere else, or not need an entry. @@ -46,7 +46,7 @@ pub(crate) fn diagnostics( let hint = near.as_deref().map(|near| format!("; did you mean `{near}`?")).unwrap_or_default(); let locale = catalog.default_locale(); let message = format!("Translation `{full}` is missing in the `{locale}` locale{hint}"); - let found = util::coded(util::warning(index.range(start, end), message), I18N_MISSING_KEY); + let found = util::coded(util::warning(index.range(start, end), message), MISSING_TRANSLATION); Some(util::with_data(found, serde_json::json!({ "key": full, "locale": locale, "suggest": near }))) }) .collect() diff --git a/server/src/report.rs b/server/src/report.rs index 10f3711..c3a7465 100644 --- a/server/src/report.rs +++ b/server/src/report.rs @@ -50,12 +50,20 @@ impl Severity { } } - /// The SARIF `level`, also used by the JSON lines. - fn level(self) -> &'static str { + /// The word the text and JSON lines use; the LSP's "Information". + pub fn word(self) -> &'static str { match self { Self::Error => "error", Self::Warning => "warning", + Self::Note => "info", + } + } + + /// SARIF's `level` has no `info`. + fn level(self) -> &'static str { + match self { Self::Note => "note", + _ => self.word(), } } @@ -101,13 +109,20 @@ impl Finding { } /// The 1-based line and character column of an LSP position in `text`; a leading byte order mark takes no column. -fn character_position(text: &str, position: Position) -> (u32, u32) { +pub fn character_position(text: &str, position: Position) -> (u32, u32) { let (_, line, byte) = util::line_at(text, position); let column = line[..byte].chars().count() as u32 + 1; let marked = position.line == 0 && text.starts_with(BYTE_ORDER_MARK); (position.line + 1, if marked { column.saturating_sub(1).max(1) } else { column }) } +/// `file:line:col: severity: message [Rule]`. +pub fn text_line(shown: &Path, text: &str, (severity, rule, message): (Severity, Option<&str>, &str), range: Range) -> String { + let (line, column) = character_position(text, range.start); + let rule = rule.map(|rule| format!(" [{rule}]")).unwrap_or_default(); + format!("{}:{line}:{column}: {}: {message}{rule}", shown.display(), severity.word()) +} + /// Escapes a workflow command's message, or its property value when `property` (which also holds `:` and `,`). fn escape(value: &str, property: bool) -> String { let mut out = String::with_capacity(value.len()); @@ -146,7 +161,7 @@ pub fn json_line(finding: &Finding) -> String { "column": finding.column, "endLine": finding.end_line, "endColumn": finding.end_column, - "severity": finding.severity.level(), + "severity": finding.severity.word(), "rule": finding.rule, "message": finding.message, }) @@ -298,5 +313,19 @@ mod tests { assert_eq!(value["rule"], Value::Null); assert_eq!((value["line"].as_u64(), value["endColumn"].as_u64()), (Some(12), Some(18))); assert_eq!(value["severity"], "warning"); + let note = Finding { severity: Severity::Note, ..finding(None, "m") }; + let value: Value = serde_json::from_str(&json_line(¬e)).unwrap(); + assert_eq!(value["severity"], "info"); + let log: Value = serde_json::from_str(&sarif(&[note])).unwrap(); + assert_eq!(log["runs"][0]["results"][0]["level"], "note", "SARIF's own word"); + } + + #[test] + fn text_line_names_the_rule_and_counts_characters() { + let text = "

😀д

\n"; + let range = Range::new(Position::new(0, 3 + 2 + 1), Position::new(0, 3 + 2 + 1 + 5)); + let line = text_line(Path::new("a.erb"), text, (Severity::Note, Some("Html/ImgAlt"), "No alt"), range); + assert_eq!(line, "a.erb:1:6: info: No alt [Html/ImgAlt]"); + assert_eq!(text_line(Path::new("a.erb"), text, (Severity::Error, None, "m"), range), "a.erb:1:6: error: m"); } } diff --git a/server/src/rules.rs b/server/src/rules.rs index 9761e0e..f54dfba 100644 --- a/server/src/rules.rs +++ b/server/src/rules.rs @@ -172,7 +172,7 @@ pub const RULES: &[Rule] = &[ lint("Rails/RenderInLoop", "A partial rendered once per item inside a loop.", TEMPLATES), lint("Rails/OutputControlFlow", "Control flow in an output tag.", &[Erb]), lint("Rails/UnsafeOutput", "Output that skips Rails' HTML escaping.", TEMPLATES), - lint("Rails/I18nMissingKey", "A lazy translation key with no entry in `config/locales`.", TEMPLATES), + lint("Rails/MissingTranslation", "A lazy translation key with no entry in `config/locales`.", TEMPLATES), lint("Rails/UnknownRoute", "A `*_path` or `*_url` helper that the app's routes don't define.", TEMPLATES), lint("Turbo/PermanentRequiresId", "An element with `data-turbo-permanent` and no `id`.", TEMPLATES), lint("Stimulus/UnknownController", "A `data-controller` name that no Stimulus controller has.", TEMPLATES), diff --git a/server/src/rules/file.rs b/server/src/rules/file.rs index 86b62c8..5e18630 100644 --- a/server/src/rules/file.rs +++ b/server/src/rules/file.rs @@ -1,6 +1,6 @@ //! `.ruby-templates.toml`, read against the rule registry. A part that can't be read is dropped with a `Problem`; the rest is kept. -use super::{by_name, departments, ChoiceOption, CountOption, Kind, ListOption, Rule}; +use super::{by_name, departments, ChoiceOption, CountOption, ListOption, Rule}; use crate::glob::Glob; use crate::util::LineIndex; use std::ops::Range as Span; @@ -12,12 +12,18 @@ use tower_lsp_server::ls_types::Range; pub const FILE_NAME: &str = ".ruby-templates.toml"; /// The language tables, and the keys each takes. -const LANGUAGE_TABLES: [(&str, &[&str]); 4] = [ - ("erb", &["format.enabled", "format.align_comments", "diagnostics.enabled", "disabled_diagnostics"]), - ("haml", &["format.enabled", "diagnostics.enabled", "disabled_diagnostics"]), - ("slim", &["extra_engines", "format.enabled", "diagnostics.enabled", "disabled_diagnostics"]), - ("jbuilder", &["disabled_diagnostics"]), +const LANGUAGE_TABLES: [(&str, &[&str]); 3] = [ + ("erb", &["format.enabled", "format.align_comments", "diagnostics.enabled"]), + ("haml", &["format.enabled", "diagnostics.enabled"]), + ("slim", &["extra_engines", "format.enabled", "diagnostics.enabled"]), ]; +/// A key older versions took; it gets a problem that names the replacement. +const REMOVED_DISABLED_DIAGNOSTICS: &str = "disabled_diagnostics"; +/// Old rule names, for the problem that names the new one; they don't resolve. +const RENAMED_RULES: [(&str, &str); 1] = [("Rails/I18nMissingKey", "Rails/MissingTranslation")]; +const SWITCH_RULE_OFF_JBUILDER: &str = + "switch a rule off with `[Rails.MissingPartial] enabled = false`, or `exclude = [\"**/*.jbuilder\", \"**/*.builder\"]` for some files"; +const SWITCH_RULE_OFF: &str = "switch a rule off with `[Html.ImgAlt] enabled = false`, or `exclude = [\"**/*.haml\"]` for some files"; const RULE_KEYS: [&str; 3] = ["enabled", "include", "exclude"]; #[derive(Debug)] @@ -39,14 +45,12 @@ pub struct RuleTable { pub lists: Vec<(&'static str, Vec)>, } -/// One of `[erb]`, `[haml]`, `[slim]` (Skim too), `[jbuilder]`. +/// One of `[erb]`, `[haml]`, `[slim]` (Skim too). #[derive(Debug, Default)] pub struct LanguageTable { pub format_enabled: Option, pub align_comments: Option, pub diagnostics_enabled: Option, - /// Rule names. - pub disabled_diagnostics: Option>, pub extra_engines: Option>, } @@ -113,11 +117,13 @@ impl Reader<'_> { } else if let Some((section, allowed)) = LANGUAGE_TABLES.iter().find(|(section, _)| *section == name) { let language = self.language(section, allowed, value); file.languages.push((section, language)); + } else if name == "jbuilder" { + self.problem(key.span(), format!("`[jbuilder]` is removed; {SWITCH_RULE_OFF_JBUILDER}")); } else if name.starts_with(|c: char| c.is_ascii_uppercase()) || name.contains('/') { self.department(file, key, value); } else { let message = format!( - "unknown key `{name}`; it takes root, exclude, the tables [erb], [haml], [slim] and [jbuilder], and a department such as [Html]" + "unknown key `{name}`; it takes root, exclude, the tables [erb], [haml] and [slim], and a department such as [Html]" ); self.problem(key.span(), message); } @@ -128,6 +134,10 @@ impl Reader<'_> { let mut language = LanguageTable::default(); let Some(table) = self.as_table(section, value) else { return language }; for (path, key, value) in leaves(table, allowed) { + if path == REMOVED_DISABLED_DIAGNOSTICS { + self.problem(key.span(), format!("`{path}` is removed; {SWITCH_RULE_OFF}")); + continue; + } if !allowed.contains(&path.as_str()) { let home = LANGUAGE_TABLES.iter().find(|(_, keys)| keys.contains(&path.as_str())); let message = match home { @@ -142,7 +152,7 @@ impl Reader<'_> { "format.align_comments" => language.align_comments = self.boolean(&path, value), "diagnostics.enabled" => language.diagnostics_enabled = self.boolean(&path, value), "extra_engines" => language.extra_engines = self.strings(&path, value).map(|v| v.into_iter().map(|(s, _)| s).collect()), - _ => language.disabled_diagnostics = self.rule_names(&path, value), + _ => {} } } language @@ -169,7 +179,10 @@ impl Reader<'_> { let rule_table = self.rule_table(&format!("{department}.{sub_name}"), rule, value); file.rules.push((rule, rule_table)); } - None => self.problem(sub.span(), format!("unknown rule `{full}`")), + None => { + let renamed = RENAMED_RULES.iter().find(|(old, _)| *old == full).map(|(_, new)| format!("; renamed `{new}`")); + self.problem(sub.span(), format!("unknown rule `{full}`{}", renamed.unwrap_or_default())); + } } } else { let message = @@ -281,25 +294,6 @@ impl Reader<'_> { } Some(globs) } - - /// Rule names; anything else is reported and dropped. - fn rule_names(&mut self, name: &str, value: Value) -> Option> { - let mut names = Vec::new(); - for (rule_name, span) in self.strings(name, value)? { - match by_name(&rule_name) { - Some(rule) if rule.kind == Kind::Lint => names.push(rule.name.to_string()), - Some(rule) => self.problem( - span, - format!("`{}` formats, it has no diagnostic; switch it in [{}]", rule.name, rule.name.replace('/', ".")), - ), - None if rule_name.contains('-') => { - self.problem(span, format!("unknown rule `{rule_name}`; diagnostics are named by rule (`Html/ImgAlt`) since 0.11")) - } - None => self.problem(span, format!("unknown rule `{rule_name}`")), - } - } - Some(names) - } } /// The entries of `table` with tables flattened one level, as `format.enabled` is written under `[erb]`. @@ -344,7 +338,6 @@ exclude = ["vendor/**", "tmp/**"] format.enabled = false format.align_comments = true diagnostics.enabled = true -disabled_diagnostics = ["Html/ImgAlt", "Html/UnclosedElement"] [slim] extra_engines = ["mjml"] @@ -362,7 +355,6 @@ exclude = ["**/*.haml"] assert!(file.root && file.exclude.as_ref().is_some_and(|globs| globs.len() == 2)); let erb = &file.languages.iter().find(|(name, _)| *name == "erb").unwrap().1; assert_eq!((erb.format_enabled, erb.align_comments, erb.diagnostics_enabled), (Some(false), Some(true), Some(true))); - assert_eq!(erb.disabled_diagnostics.as_deref(), Some(&["Html/ImgAlt".to_string(), "Html/UnclosedElement".to_string()][..])); assert_eq!(file.languages.iter().find(|(name, _)| *name == "slim").unwrap().1.extra_engines, Some(vec!["mjml".to_string()])); assert_eq!(file.departments, [("Html", false)]); let (rule, table) = &file.rules[0]; @@ -409,16 +401,28 @@ colour = 1 } #[test] - fn a_code_from_before_0_11_is_an_unknown_rule_that_says_so() { - let file = read("[erb]\ndisabled_diagnostics = [\"img-missing-alt\", \"Html/ImgAltt\"]\n"); + fn disabled_diagnostics_is_removed_and_points_to_the_rule_tables() { + let file = read( + "[erb]\ndisabled_diagnostics = [\"Html/ImgAlt\"]\n[haml]\ndisabled_diagnostics = 3\n[jbuilder]\ndisabled_diagnostics = []\n", + ); + let fix = "switch a rule off with `[Html.ImgAlt] enabled = false`, or `exclude = [\"**/*.haml\"]` for some files"; assert_eq!( messages(&file), [ - "2:25: unknown rule `img-missing-alt`; diagnostics are named by rule (`Html/ImgAlt`) since 0.11", - "2:44: unknown rule `Html/ImgAltt`" + format!("2:1: `disabled_diagnostics` is removed; {fix}"), + format!("4:1: `disabled_diagnostics` is removed; {fix}"), + "5:2: `[jbuilder]` is removed; switch a rule off with `[Rails.MissingPartial] enabled = false`, or `exclude = [\"**/*.jbuilder\", \"**/*.builder\"]` for some files".to_string(), ] ); - assert_eq!(file.languages[0].1.disabled_diagnostics.as_deref(), Some(&[][..])); + } + + #[test] + fn a_renamed_rule_names_its_new_name() { + let file = read("[Rails.I18nMissingKey]\nenabled = false\n[Rails.Nope]\n"); + assert_eq!( + messages(&file), + ["1:8: unknown rule `Rails/I18nMissingKey`; renamed `Rails/MissingTranslation`", "3:8: unknown rule `Rails/Nope`"] + ); } #[test] @@ -503,32 +507,22 @@ colour = 1 ); } - #[test] - fn a_formatting_rule_is_not_a_disabled_diagnostic() { - let file = read("[erb]\ndisabled_diagnostics = [\"Layout/EmptyLines\", \"Html/ImgAlt\"]\n"); - assert_eq!(messages(&file), ["2:25: `Layout/EmptyLines` formats, it has no diagnostic; switch it in [Layout.EmptyLines]"]); - assert_eq!(file.languages[0].1.disabled_diagnostics.as_deref(), Some(&["Html/ImgAlt".to_string()][..])); - } - #[test] fn languages_take_their_own_keys() { - let file = read( - "[erb]\nextra_engines = [\"mjml\"]\nformat.enable = true\n[jbuilder]\nformat.enabled = false\n[haml]\ndisabled_diagnostics = [\"nope\", 3]\n[Nope]\n", - ); + let file = read("[erb]\nextra_engines = [\"mjml\"]\nformat.enable = true\n[haml]\nformat.enabled = \"no\"\n[Nope]\n"); assert_eq!( messages(&file), [ "2:1: `extra_engines` belongs in [slim]", - "3:8: unknown key `format.enable` in [erb]; it takes format.enabled, format.align_comments, diagnostics.enabled, disabled_diagnostics", - "5:8: `format.enabled` belongs in [erb]", - "7:24: `disabled_diagnostics` must be a list of strings", - "8:2: unknown department `Nope`; the departments are Syntax, Html, A11y, Rails, Turbo, Stimulus, Layout, Style", + "3:8: unknown key `format.enable` in [erb]; it takes format.enabled, format.align_comments, diagnostics.enabled", + "5:18: `format.enabled` must be true or false", + "6:2: unknown department `Nope`; the departments are Syntax, Html, A11y, Rails, Turbo, Stimulus, Layout, Style", ] ); let empty_sub = read("[erb]\n[erb.unknown]\n"); assert_eq!( messages(&empty_sub), - ["2:6: unknown key `unknown` in [erb]; it takes format.enabled, format.align_comments, diagnostics.enabled, disabled_diagnostics"] + ["2:6: unknown key `unknown` in [erb]; it takes format.enabled, format.align_comments, diagnostics.enabled"] ); } diff --git a/server/src/rules/resolve.rs b/server/src/rules/resolve.rs index 94d8406..16eb202 100644 --- a/server/src/rules/resolve.rs +++ b/server/src/rules/resolve.rs @@ -106,19 +106,18 @@ impl ResolvedRules { let excluded_by = nearest(&files, |f| f.exclude.as_ref().map(|globs| (f, globs))) .filter(|(file, globs)| matches_any(file, globs, template)) .map(|(file, _)| file.path.clone()); - let disabled = in_lists(|t| t.disabled_diagnostics.as_ref()).unwrap_or_else(|| { - let codes = editor.disabled(lang).iter(); - let lint_name = |code: &String| match by_name(code) { - Some(rule) => (rule.kind == Kind::Lint).then(|| rule.name.to_string()), - None => Some(code.clone()), - }; - codes.filter_map(lint_name).collect() - }); + let disabled_by_editor = |code: &String| match by_name(code) { + Some(rule) => { + let enabled_by_file = file_setting(&files, rule, rule.is_on_by_default(lang)) == Some(true); + (rule.kind == Kind::Lint && !enabled_by_file).then(|| rule.name.to_string()) + } + None => Some(code.clone()), + }; let off: HashSet = RULES .iter() .filter(|rule| !rule_on(&files, template, lang, rule, rule.is_on_by_default(lang))) .map(|rule| rule.name.to_string()) - .chain(disabled) + .chain(editor.disabled(lang).iter().filter_map(disabled_by_editor)) .collect(); let trailing_empty_lines_with_final_newline = by_name(TRAILING_EMPTY_LINES).is_some_and(|rule| rule_on(&files, template, lang, rule, true)); @@ -255,8 +254,7 @@ fn section(lang: TemplateLang) -> Option<&'static str> { TemplateLang::Erb => Some("erb"), TemplateLang::Haml => Some("haml"), TemplateLang::Slim | TemplateLang::Skim => Some("slim"), - TemplateLang::Ruby => Some("jbuilder"), - TemplateLang::Liquid => None, + TemplateLang::Ruby | TemplateLang::Liquid => None, } } @@ -315,12 +313,24 @@ fn style(files: &[Arc], off: &HashSet, name: &str) -> Option enabled_choice(files, off, name).map(|word| if word == EMPTY_LINES_STYLE { Style::EmptyLines } else { Style::NoEmptyLines }) } -/// The nearest file that sets the rule's `enabled` or its department's decides, the rule's beating the department's within -/// that file; unset means the rule's default. Then the rule's `include` and `exclude`. +/// What the nearest file that sets the rule's `enabled` or its department's says, the rule's beating the department's within +/// that file; `None` when no file does. A department's `enabled = true` only counts for a rule that is on by default (it cancels +/// an outer `false`), so a rule that is off by default needs its own switch. +fn file_setting(files: &[Arc], rule: &Rule, default_on: bool) -> Option { + let department = |file: &ConfigFile| { + file.departments + .iter() + .find(|(d, _)| *d == rule.department()) + .map(|&(_, enabled)| enabled) + .filter(|&enabled| !enabled || default_on) + }; + nearest(files, |f| rule_table(f, rule).and_then(|table| table.enabled).or_else(|| department(f))) +} + +/// The files' setting, else the rule's default, then the rule's `include` and `exclude`. /// `default_on` is what a rule the config doesn't mention is. fn rule_on(files: &[Arc], template: &Path, lang: TemplateLang, rule: &Rule, default_on: bool) -> bool { - let department = |file: &ConfigFile| file.departments.iter().find(|(d, _)| *d == rule.department()).map(|&(_, enabled)| enabled); - let enabled = nearest(files, |f| rule_table(f, rule).and_then(|table| table.enabled).or_else(|| department(f))).unwrap_or(default_on); + let enabled = file_setting(files, rule, default_on).unwrap_or(default_on); let included = nearest(files, |f| Some((f, rule_table(f, rule)?.include.as_ref()?))).is_none_or(|(f, globs)| matches_any(f, globs, template)); let excluded = @@ -387,14 +397,17 @@ mod tests { #[test] fn nested_files_override_key_by_key() { - let outer = "[erb]\nformat.enabled = false\ndisabled_diagnostics = [\"Html/DuplicateId\"]\n[Html.ImgAlt]\nenabled = false\n"; - let inner = "[erb]\ndisabled_diagnostics = [\"Html/UnclosedElement\"]\n[Html.ImgAlt]\nenabled = true\n"; + let outer = "[erb]\nformat.enabled = false\n[Html.DuplicateId]\nenabled = false\n[Html.ImgAlt]\nenabled = false\n"; + let inner = "[Html.UnclosedElement]\nenabled = false\n[Html.ImgAlt]\nenabled = true\n"; let files = [(".ruby-templates.toml", outer), ("app/views/.ruby-templates.toml", inner), ("app/views/a.html.erb", ""), ("b.html.erb", "")]; let project = Project::new("nested", &files); let inner_rules = project.erb("app/views/a.html.erb"); assert!(inner_rules.reports(IMG), "the nearest file wins the rule"); - assert!(!inner_rules.reports("Html/UnclosedElement") && inner_rules.reports("Html/DuplicateId"), "lists are replaced"); + assert!( + !inner_rules.reports("Html/UnclosedElement") && !inner_rules.reports("Html/DuplicateId"), + "a rule the nearest file leaves out comes from the one above" + ); assert!(!inner_rules.format_enabled(), "a key the nearest file leaves out comes from the one above"); let outer_rules = project.erb("b.html.erb"); assert!(!outer_rules.reports(IMG) && !outer_rules.reports("Html/DuplicateId") && outer_rules.reports("Html/UnclosedElement")); @@ -470,7 +483,7 @@ mod tests { #[test] fn the_file_beats_the_editor_which_applies_where_the_file_is_silent() { let toml = - "[erb]\nformat.enabled = true\nformat.align_comments = false\ndisabled_diagnostics = []\n[slim]\nextra_engines = [\"mjml\"]\n"; + "[erb]\nformat.enabled = true\nformat.align_comments = false\n[Html.ImgAlt]\nenabled = true\n[slim]\nextra_engines = [\"mjml\"]\n"; let project = Project::new("editor", &[(".ruby-templates.toml", toml), ("a.html.erb", ""), ("b.html.slim", ""), ("c.html.haml", "")]); let settings = editor(serde_json::json!({ @@ -489,6 +502,41 @@ mod tests { assert!(!without.format_enabled() && !without.reports(IMG) && without.format_settings(Settings::default(), false).align_comments); } + #[test] + fn a_department_switch_only_restores_the_defaults() { + let files = [ + ( + ".ruby-templates.toml", + "[Html]\nenabled = false\n[Layout]\nenabled = false\n[Layout.ElementContentOnOwnLine]\nenabled = true\n", + ), + ("on/.ruby-templates.toml", "[Html]\nenabled = true\n[Layout]\nenabled = true\n"), + ("on/a.html.erb", ""), + ("a.html.erb", ""), + ]; + let project = Project::new("dept-true", &files); + let on = project.erb("on/a.html.erb"); + assert!(on.reports(IMG), "on by default: back on"); + assert!(on.format_settings(Settings::default(), false).trailing_whitespace); + let own_line = |file: &str| project.erb(file).format_settings(Settings::default(), false).content_on_own_line.is_some(); + assert!(own_line("on/a.html.erb"), "an outer rule's own switch isn't cancelled by the department's true"); + let off = Project::new("dept-true-off", &[(".ruby-templates.toml", "[Layout]\nenabled = true\n"), ("a.html.erb", "")]); + let settings = off.erb("a.html.erb").format_settings(Settings::default(), false); + assert_eq!((settings.content_on_own_line, settings.attributes_per_line, off.erb("a.html.erb").line_length()), (None, None, None)); + assert!(!project.erb("a.html.erb").reports(IMG)); + } + + #[test] + fn the_file_enabling_a_rule_beats_the_editors_list_of_disabled_ones() { + let toml = "[Html.ImgAlt]\nenabled = true\n[Html]\nenabled = true\n"; + let project = Project::new("editor-list", &[(".ruby-templates.toml", toml), ("a.html.erb", "")]); + let settings = + editor(serde_json::json!({ "erb": { "disabledDiagnostics": ["Html/ImgAlt", "Html/DuplicateId", "Html/AnchorHref"] } })); + let rules = project.resolve("a.html.erb", TemplateLang::Erb, &settings); + assert!(rules.reports(IMG) && rules.reports("Html/DuplicateId"), "the rule's or the department's enabled = true"); + let silent = Project::new("editor-list-silent", &[("a.html.erb", "")]).resolve("a.html.erb", TemplateLang::Erb, &settings); + assert!(!silent.reports(IMG) && !silent.reports("Html/DuplicateId")); + } + #[test] fn a_rule_is_off_outside_its_languages() { let project = Project::new("langs", &[("a.html.haml", "")]); @@ -525,7 +573,7 @@ mod tests { assert_eq!((settings.max_empty_lines, settings.trailing_empty_lines), (Some(1), false), "max defaults to 1"); let files = [ - (".ruby-templates.toml", "[Layout]\nenabled = true\n[Layout.EmptyLines]\nmax = 3\n"), + (".ruby-templates.toml", "[Layout]\nenabled = true\n[Layout.EmptyLines]\nenabled = true\nmax = 3\n"), ("inner/.ruby-templates.toml", "[Layout.EmptyLines]\nmax = 0\nexclude = [\"**/*.slim\"]\n"), ("a.html.erb", ""), ("inner/a.html.erb", ""), @@ -534,10 +582,10 @@ mod tests { let nested = Project::new("format-rules-nested", &files); let max = |file: &str, lang| nested.resolve(file, lang, &Options::default()).format_settings(Settings::default(), false).max_empty_lines; - assert_eq!(max("a.html.erb", TemplateLang::Erb), Some(3), "the department switch turns a formatting rule on"); + assert_eq!(max("a.html.erb", TemplateLang::Erb), Some(3), "the rule's own switch turns a formatting rule on"); assert_eq!(max("inner/a.html.erb", TemplateLang::Erb), Some(0), "the nearest file sets max"); assert_eq!(max("inner/b.html.slim", TemplateLang::Slim), None, "its exclude"); - let toml = "[Layout]\nenabled = true\n[Layout.EmptyLinesAroundBranches]\nstyle = \"empty_lines\"\n[Layout.EmptyLinesAroundElementBody]\nenabled = false\n"; + let toml = "[Layout.EmptyLinesAroundBlockBody]\nenabled = true\n[Layout.EmptyLinesAroundBranches]\nenabled = true\nstyle = \"empty_lines\"\n[Layout.EmptyLinesAroundElementBody]\nenabled = false\n"; let around = Project::new("format-rules-around", &[(".ruby-templates.toml", toml), ("a.html.haml", "")]); let settings = around.resolve("a.html.haml", TemplateLang::Haml, &Options::default()).format_settings(Settings::default(), false); let styles = (settings.around_block_body, settings.around_element_body, settings.around_branches); @@ -572,7 +620,7 @@ mod tests { let own_limit = Project::new("per-line-set", &[(".ruby-templates.toml", limit), ("a.html.erb", "")]); assert_eq!(per_line(&own_limit), Some(60)); let disabled = editor(serde_json::json!({ "erb": { "disabledDiagnostics": ["Layout/LineLength"] } })); - assert_eq!(set.resolve("a.html.erb", TemplateLang::Erb, &disabled).line_length(), None); + assert_eq!(set.resolve("a.html.erb", TemplateLang::Erb, &disabled).line_length(), Some(80), "the file enables it"); } #[test] diff --git a/site/src/components/RuleRoster.astro b/site/src/components/RuleRoster.astro index ac17377..89f4755 100644 --- a/site/src/components/RuleRoster.astro +++ b/site/src/components/RuleRoster.astro @@ -38,7 +38,7 @@ const codeParts = (text: string) => backtickParts(text);
diff --git a/site/src/content/docs/guides/checks.md b/site/src/content/docs/guides/checks.md index ef60b2b..68a4db0 100644 --- a/site/src/content/docs/guides/checks.md +++ b/site/src/content/docs/guides/checks.md @@ -73,7 +73,7 @@ Here the `render` passes the `user:` the partial declares. A `render` of `users/ How partials are looked up in engines, packs, components and gems, and when the missing-partial check stays off, is described in [Compatibility](/vscode-ruby-templates/guides/compatibility/#partials-and-formats). -The [rules reference](/vscode-ruby-templates/reference/rules/) also covers the checks that are planned, such as a `render` in a tag that outputs nothing, and unsafe output. +The [rules reference](/vscode-ruby-templates/reference/rules/) lists every check, such as a `render` in a tag that outputs nothing, and unsafe output. ## Turning checks off diff --git a/site/src/content/docs/guides/command-line.md b/site/src/content/docs/guides/command-line.md index d53758c..9b71d1b 100644 --- a/site/src/content/docs/guides/command-line.md +++ b/site/src/content/docs/guides/command-line.md @@ -13,6 +13,8 @@ The same checks and formatter run outside the editor, from npm, with no gems to npm install --save-dev @x-ror/ruby-templates ``` +`npx ruby-templates --version` prints the version and `--help`, also after `check` or `format`, the usage; both exit with 0. + ## Check templates ```sh @@ -22,11 +24,11 @@ npx ruby-templates check app/views `check` prints the diagnostics (errors and warnings) of ERB, Haml, Slim, Jbuilder and Builder templates, one per line with the file, line and column. Jbuilder and Builder views are plain Ruby: `check` reports their partial and `locals:` problems, as the editor does, and leaves their Ruby syntax errors to Ruby LSP or `ruby -c`: ```text -app/views/users/index.html.erb:4:3: error: unexpected end-of-input, assuming it is closing the parent top level context -app/views/users/index.html.erb:3:5: warning: `` without `alt`: the alt attribute must be specified (HTML 4.8.4.4.1) +app/views/users/index.html.erb:4:3: error: unexpected end-of-input, assuming it is closing the parent top level context [Syntax/Ruby] +app/views/users/index.html.erb:3:5: warning: `` without `alt`: the alt attribute must be specified (HTML 4.8.4.4.1) [Html/ImgAlt] ``` -It exits with 1 if there are any, or if a `.ruby-templates.toml` has a problem (printed the same way, once per file). The checks are the ones described in [Errors as you type](/vscode-ruby-templates/guides/checks/); the command line checker reads ERB as Erubi does, so `erb-percent` `%` lines are not modelled. +The rule at the end is the name to use in a [`.ruby-templates.toml`](/vscode-ruby-templates/reference/rules/#configuration); a problem in the file itself ends in `[Config/Invalid]`. It exits with 1 if there are any, or if a `.ruby-templates.toml` has a problem (printed the same way, once per file). The checks are the ones described in [Errors as you type](/vscode-ruby-templates/guides/checks/); the command line checker reads ERB as Erubi does, so `erb-percent` `%` lines are not modelled. ## Format templates @@ -86,12 +88,12 @@ Each step fails the job when the command exits with a non-zero code. | Format | Output | | -------- | ----------------------------------------------------------------------------------------------------------------- | -| `text` | `file:line:column: severity: message`, the default | +| `text` | `file:line:column: severity: message [Rule]`, the default | | `github` | GitHub Actions workflow commands, which annotate the files of a pull request | | `sarif` | One SARIF 2.1.0 log, for code scanning | | `json` | One JSON object per line, with `file`, `line`, `column`, `endLine`, `endColumn`, `severity`, `rule` and `message` | -In `github`, `sarif` and `json` the paths are relative to the current folder, so run the command from the repository root for GitHub to find the files; SARIF carries absolute `file:` URIs, which code scanning maps to the repository. Columns count characters from 1, as GitHub shows them, and a leading byte order mark takes none; `text` keeps the editor's UTF-16 columns. These formats also carry the rule: `Html/ImgAlt` is the `title` of an annotation, the `rule` of a JSON line, and a SARIF rule with its summary and a link to the [diagnostics reference](/vscode-ruby-templates/reference/diagnostics/). A problem in a `.ruby-templates.toml` has the rule `Config/Invalid`. Errors are `error`, warnings `warning` and the Rails `info` diagnostics `notice` (`note` in SARIF and JSON). A problem in a `.ruby-templates.toml` is reported the same way, against that file, before the results of the first template that uses it. +In `github`, `sarif` and `json` the paths are relative to the current folder, so run the command from the repository root for GitHub to find the files; SARIF carries absolute `file:` URIs, which code scanning maps to the repository. Columns count characters from 1 in every format, as GitHub shows them, and a leading byte order mark takes none. Every format carries the rule: `Html/ImgAlt` is the `title` of an annotation, the `rule` of a JSON line, and a SARIF rule with its summary and a link to the [diagnostics reference](/vscode-ruby-templates/reference/diagnostics/). A problem in a `.ruby-templates.toml` has the rule `Config/Invalid`. Errors are `error`, warnings `warning` and information (such as `Rails/InstanceVariableInPartial`) `info`, in `text` and `json`; GitHub and SARIF use their own words for it, `notice` and `note`. A problem in a `.ruby-templates.toml` is reported the same way, against that file, before the results of the first template that uses it. Annotations on the pull request: diff --git a/site/src/content/docs/guides/commands.md b/site/src/content/docs/guides/commands.md index 5de6cd4..f44ac90 100644 --- a/site/src/content/docs/guides/commands.md +++ b/site/src/content/docs/guides/commands.md @@ -15,7 +15,6 @@ Run any command from the Command Palette (Ctrl+Shift+ | Wrap Selection in ERB / Slim Output | Ctrl+Alt+W | Cmd+Alt+W | `foo` → `<%= foo %>`, `= foo` or `#{foo}` | | Extract Selection to Partial | none | none | Moves the selection into `_name.html.erb` (or Haml, Slim) and leaves a `render` | | Switch to Related File | none | none | View ↔ other formats ↔ controller action; ViewComponent class ↔ template ↔ preview | -| Re-indent Haml (Document or Selection) | none | none | Re-indents a Haml document or the selection | In ERB, Ctrl+/ (Cmd+/ on macOS) is bound to the extension's line comment toggle, which follows the file's host language; see [Comment toggling](/vscode-ruby-templates/guides/file-types/#comment-toggling). diff --git a/site/src/content/docs/guides/file-types.md b/site/src/content/docs/guides/file-types.md index 69a0a4e..e4c6cbc 100644 --- a/site/src/content/docs/guides/file-types.md +++ b/site/src/content/docs/guides/file-types.md @@ -22,7 +22,7 @@ The file name picks the language id, which decides the comment syntax and the `[ | `.md.erb` | `erb-markdown` | `` | Markdown + Ruby | none | no | | `.rb.erb` | `erb-ruby` | `#` | Ruby | none | no | | `.yml.erb`, `.yaml.erb` | `erb-yaml` | `#` | YAML + Ruby | none | no | -| `.liquid`, `.html.liquid` | `liquid` | `{% comment %}` | HTML + Liquid | none | no | +| `.liquid`, `.html.liquid` | `liquid` (experimental) | `{% comment %}` | HTML + Liquid | none | no | Every ERB row gets the ERB and Ruby checks and, under `app/views`, the `render` checks (`unresolved-render`, `strict-locals`). Only HTML hosts add the HTML ones (unclosed or unbalanced tags, missing `alt`, duplicate `id`), linked tag renaming and attribute completion. Any other bare `.erb` (`nginx.conf.erb`) gets the ERB and Ruby checks only. @@ -80,6 +80,8 @@ Items: <%= @items.size %> ## Liquid +Liquid support is experimental and not covered by the 1.0 stability guarantees: the `liquid` language id, its file extensions and its grammar may change in a minor release. + `liquid` (Shopify themes, Jekyll) is highlighting, comment toggling, bracket and `{{ }}` / `{% %}` auto-closing and indentation only: none of the Rails lookups or checks apply to it. ```liquid title="_includes/card.html.liquid" diff --git a/site/src/content/docs/guides/formatting.md b/site/src/content/docs/guides/formatting.md index 1a902bb..a49ee20 100644 --- a/site/src/content/docs/guides/formatting.md +++ b/site/src/content/docs/guides/formatting.md @@ -49,7 +49,7 @@ ul A file Haml or Slim would reject is left unchanged, and so is any result that wouldn't compile to the same output. -The [rules reference](/vscode-ruby-templates/reference/rules/) lists the formatting rules the extension has and the ones planned, which are configured in a `.ruby-templates.toml`. +The [rules reference](/vscode-ruby-templates/reference/rules/) lists the formatting rules, which are configured in a `.ruby-templates.toml`. ## Blank lines diff --git a/site/src/content/docs/guides/highlighting-and-editing.md b/site/src/content/docs/guides/highlighting-and-editing.md index 03010c1..81e0eeb 100644 --- a/site/src/content/docs/guides/highlighting-and-editing.md +++ b/site/src/content/docs/guides/highlighting-and-editing.md @@ -1,13 +1,13 @@ --- title: Highlighting and editing -description: Syntax highlighting, semantic colours, tag closing, linked editing, snippets and Emmet for ERB, Haml, Slim, Skim and Liquid. +description: Syntax highlighting, semantic colours, tag closing, linked editing, snippets and Emmet for ERB, Haml, Slim, Skim and Liquid (experimental). sidebar: order: 4 --- ## Syntax highlighting -Full syntax highlighting for ERB (`.html.erb`, `.erubi`, `.js.erb`, `.css.erb`, `.json.erb`, `.yml.erb`, …), Haml, Slim, Skim and Liquid, including embedded JavaScript, CSS, SCSS, CoffeeScript and Markdown blocks. Every code example on this site is highlighted with the extension's own grammars. +Full syntax highlighting for ERB (`.html.erb`, `.erubi`, `.js.erb`, `.css.erb`, `.json.erb`, `.yml.erb`, …), Haml, Slim, Skim and Liquid (experimental), including embedded JavaScript, CSS, SCSS, CoffeeScript and Markdown blocks. Every code example on this site is highlighted with the extension's own grammars. ```slim title="app/views/users/show.html.slim" .card diff --git a/site/src/content/docs/guides/settings.md b/site/src/content/docs/guides/settings.md index dd86927..e173cfe 100644 --- a/site/src/content/docs/guides/settings.md +++ b/site/src/content/docs/guides/settings.md @@ -31,7 +31,7 @@ Editor settings for one template language use its language id, such as `[erb]`, | `rubyTemplates.haml.diagnostics.enabled` | `true` | Show the language server's diagnostics in Haml files. Turn off to silence them all. | | `rubyTemplates.slim.diagnostics.enabled` | `true` | Show the language server's diagnostics in Slim and Skim files. Turn off to silence them all. | -Each `disabledDiagnostics` setting takes the rule names of that language's checks (`Html/ImgAlt`); the [diagnostics reference](/vscode-ruby-templates/reference/diagnostics/) lists them. [Errors as you type](/vscode-ruby-templates/guides/checks/#turning-checks-off) shows examples. +Each `disabledDiagnostics` setting takes the rule names of that language's checks (`Html/ImgAlt`); the [diagnostics reference](/vscode-ruby-templates/reference/diagnostics/) lists them. A rule that a `.ruby-templates.toml` enables with `enabled = true` stays on even when the list names it; the file's `enabled = false` also applies. [Errors as you type](/vscode-ruby-templates/guides/checks/#turning-checks-off) shows examples. ## Formatting diff --git a/site/src/content/docs/reference/diagnostics.mdx b/site/src/content/docs/reference/diagnostics.mdx index b987016..a05c8b5 100644 --- a/site/src/content/docs/reference/diagnostics.mdx +++ b/site/src/content/docs/reference/diagnostics.mdx @@ -6,7 +6,7 @@ tableOfContents: false import DiagnosticRoster from "../../../components/DiagnosticRoster.astro"; -Every check the language server runs reports its problems under a stable code, which is the name of its rule: `Html/ImgAlt`, `Syntax/Ruby`. In VS Code the code appears next to the message in the Problems panel and in the hover over the underlined text, with the language as the source (`erb`, `haml`, `slim`, or `ruby` for Jbuilder and Builder views). The `ruby-templates check` command prints the same messages as `file:line:column: severity: message`, without the code (`--format github`, `json` and `sarif` include it), and exits with 1 when it finds an error or a warning (not for information, such as `Rails/InstanceVariableInPartial`), or a problem in a `.ruby-templates.toml`. +Every check the language server runs reports its problems under a stable code, which is the name of its rule: `Html/ImgAlt`, `Syntax/Ruby`. In VS Code the code appears next to the message in the Problems panel and in the hover over the underlined text, with `ruby-templates` as the source. The `ruby-templates check` command prints the same messages as `file:line:column: severity: message [Code]`, and exits with 1 when it finds an error or a warning (not for information, such as `Rails/InstanceVariableInPartial`), or a problem in a `.ruby-templates.toml`. The messages are those of Erubi, Rails, Haml 7, Slim 5 and Prism, or quote the section of the HTML standard that is broken. Each entry below shows a template that triggers the code and the message `ruby-templates check` prints for it, at the same line and column. @@ -21,11 +21,11 @@ enabled = false [Html.DuplicateId] exclude = ["app/views/legacy/**"] -[haml] -disabled_diagnostics = ["Rails/MissingPartial"] +[Rails.MissingPartial] +exclude = ["**/*.haml"] ``` -The file is read by the editor and by `ruby-templates check`, and it beats the settings below. The [rules reference](/vscode-ruby-templates/reference/rules/#configuration) describes the file. +The file is read by the editor and by `ruby-templates check`, and it beats the settings below: a rule the file switches with `enabled` stays as the file says. The [rules reference](/vscode-ruby-templates/reference/rules/#configuration) describes the file. Or list the codes to turn off for a language in your `settings.json`: @@ -36,6 +36,6 @@ Or list the codes to turn off for a language in your `settings.json`: `rubyTemplates.slim.disabledDiagnostics` also applies to Skim templates, and `rubyTemplates.jbuilder.disabledDiagnostics` to Jbuilder and Builder views. To silence a whole language, set `rubyTemplates.erb.diagnostics.enabled`, `rubyTemplates.haml.diagnostics.enabled` or `rubyTemplates.slim.diagnostics.enabled` to `false` (in a `.ruby-templates.toml`: `diagnostics.enabled = false` under `[erb]`, `[haml]` or `[slim]`). Liquid templates and Thor templates (`*.tt`) get no diagnostics. -The [rules reference](/vscode-ruby-templates/reference/rules/) lists the checks and formatter rules planned next, next to the ones that report these codes. +The [rules reference](/vscode-ruby-templates/reference/rules/) lists the formatter rules next to the ones that report these codes. diff --git a/site/src/content/docs/reference/rules.mdx b/site/src/content/docs/reference/rules.mdx index 0a88e3e..9f98a45 100644 --- a/site/src/content/docs/reference/rules.mdx +++ b/site/src/content/docs/reference/rules.mdx @@ -1,12 +1,12 @@ --- title: Rules -description: The formatting and lint rules of Ruby Templates for ERB, Haml and Slim, the ones that work today and the ones planned, each with an example. +description: The formatting and lint rules of Ruby Templates for ERB, Haml and Slim, each with an example. tableOfContents: false --- import RuleRoster from "../../../components/RuleRoster.astro"; -This page is the catalogue of rules, and a public roadmap. Rules marked _Available_ or _Partial_ work in the extension today. Rules marked _Planned_ do not exist yet; they are listed with a phase number, and lower phases come first. Rule names are the diagnostic codes, and the config file described below is read for the rules that exist. +This page is the catalogue of rules, each with an example. Rule names are the diagnostic codes, and the config file described below is read for them. The formatter and the checks work without configuration, and a `.ruby-templates.toml` changes them. [Formatting](/vscode-ruby-templates/guides/formatting/) describes what the formatter does, and the [diagnostics reference](/vscode-ruby-templates/reference/diagnostics/) lists every code the checks report. @@ -14,8 +14,8 @@ The formatter and the checks work without configuration, and a `.ruby-templates. - **Type.** An _autofix_ is a formatter rule that rewrites the template. A _warning_ is a check that reports a problem and rewrites nothing. - **Rendered output.** _Safe_ means the rule leaves the rendered page as it is: it only changes whitespace the browser ignores, or changes markup into an equal form. _Not safe_ says what can change. -- **Examples.** An autofix shows the template before and after. A warning shows a flagged template and a fine one. The examples of available rules are run through `ruby-templates format` and `ruby-templates check` by the tests; the ones of planned rules are written by hand. -- **Defaults.** A formatting rule says whether it is on by default. `Layout/TrailingEmptyLines` is, for Haml and Slim, and so are `Layout/TrailingWhitespace` (all three languages) and `Layout/IndentationStyle` (ERB, which writes spaces unless the editor, `.editorconfig` or its `style` say tabs); the others, `Layout/EmptyLines` among them, are off until you turn them on, so a file is never changed beyond what the entry says unless you ask. The planned Rails checks are on. +- **Examples.** An autofix shows the template before and after. A warning shows a flagged template and a fine one. The examples are run through `ruby-templates format` and `ruby-templates check` by the tests. +- **Defaults.** A formatting rule says whether it is on by default. `Layout/TrailingEmptyLines` is, for Haml and Slim, and so are `Layout/TrailingWhitespace` (all three languages) and `Layout/IndentationStyle` (ERB, which writes spaces unless the editor, `.editorconfig` or its `style` say tabs); the others, `Layout/EmptyLines` among them, are off until you turn them on, so a file is never changed beyond what the entry says unless you ask. The checks (lint rules) are on, except `Style/ErbTrimMode` and `Layout/LineLength`. ## Configuration @@ -26,7 +26,7 @@ Rules, and the switches that VS Code has as settings, are configured in a `.ruby enabled = false ``` -A department table with only `enabled` switches all its rules; a rule's own `enabled` beats it: +A department table with only `enabled` switches its rules: `enabled = false` turns them all off, `enabled = true` turns back on the ones that are on by default (cancelling a `false` from a file above) and never one that is off by default, which needs its own `enabled = true`. A rule's own `enabled` beats its department's: ```toml [Html] @@ -69,24 +69,23 @@ exclude = ["vendor/**", "tmp/**"] # no checks and no formatting for these files format.enabled = false # no formatting for ERB format.align_comments = true # same as --align-comments diagnostics.enabled = true # false: no diagnostics for ERB -disabled_diagnostics = ["Html/ImgAlt", "Html/UnclosedElement"] -[haml] # format.enabled, diagnostics.enabled, disabled_diagnostics +[haml] # format.enabled, diagnostics.enabled [slim] # the same, and: extra_engines = ["mjml"]; Skim files too -[jbuilder] # disabled_diagnostics, for Jbuilder and Builder views ``` -The language tables take the keys of the `rubyTemplates..*` settings, in snake case. A key under the wrong table (`extra_engines` under `[erb]`) is reported. +Lowercase tables are languages and take the keys of the `rubyTemplates..*` settings, in snake case; capitalised tables are departments and rules. A key under the wrong table (`extra_engines` under `[erb]`) is reported. To switch a rule off for one language, give it `exclude` globs (`[Html.ImgAlt] exclude = ["**/*.haml"]`); the former `disabled_diagnostics` key and `[jbuilder]` table are reported as problems. ### Which file applies - The file looks for `.ruby-templates.toml` in the template's folder and every folder above it, nearest first, and stops at one with `root = true`. -- The files merge key by key: the nearest file that sets a key wins. A list (`exclude`, `include`, `disabled_diagnostics`, `extra_engines`) is replaced, not extended. Globs are relative to the folder of the file that holds them. +- The files merge key by key: the nearest file that sets a key wins. A list (`exclude`, `include`, `extra_engines`) is replaced, not extended. Globs are relative to the folder of the file that holds them. - The file is stronger than VS Code: precedence is the nearest file, then the VS Code settings (where no file says anything), then `.editorconfig` for the indentation width and, for ERB, `indent_style` (the editor's `insertSpaces` counts as VS Code here), then the defaults. `style` of `Layout.IndentationStyle` is a file setting, so it beats `insertSpaces` and `indent_style`. -- A rule is on, if it is on by default, unless the nearest file that sets either its `enabled` or its department's `enabled` says `false`, and a formatting rule that is off by default is on when that file says `true`; within that one file, the rule's own `enabled` beats the department's. A root file with `[Html.ImgAlt] enabled = true` and a `legacy/` file with `[Html] enabled = false` therefore leave `Html/ImgAlt` off under `legacy/`. A rule that is off (its own or its department's `enabled = false`, or left out by `include`/`exclude`) does nothing, which for the two rules that are on by default means the old behaviour: `Layout/IndentationStyle` off writes spaces whatever the editor or `.editorconfig` say, and `Layout/TrailingWhitespace` off keeps the whitespace at the line ends, so `[Layout] enabled = false` stops that trimming too. Then the rule's `include` and `exclude` apply, and the rule must exist for the file's language. A file in the global `exclude` gets no diagnostics and is not formatted. +- A rule listed in `rubyTemplates..disabledDiagnostics` is off, unless the nearest file that sets the rule's `enabled` or its department's says `true` (a department's `true` counts for a rule that is on by default only). A rule that file switches off is off whatever the setting says. +- The switch of a rule is the `enabled` of the nearest file that sets the rule's own or its department's; within that one file, the rule's own beats the department's. Without one, the rule's default applies. A department's `enabled = true` only counts for a rule that is on by default; a rule that is off by default (most formatting rules, `Layout/LineLength`, `Style/ErbTrimMode`) is turned on by its own `enabled = true` only. A root file with `[Html.ImgAlt] enabled = true` and a `legacy/` file with `[Html] enabled = false` therefore leave `Html/ImgAlt` off under `legacy/`. A rule that is off (its own or its department's `enabled = false`, or left out by `include`/`exclude`) does nothing, which for the two rules that are on by default means the old behaviour: `Layout/IndentationStyle` off writes spaces whatever the editor or `.editorconfig` say, and `Layout/TrailingWhitespace` off keeps the whitespace at the line ends, so `[Layout] enabled = false` stops that trimming too. Then the rule's `include` and `exclude` apply, and the rule must exist for the file's language. A file in the global `exclude` gets no diagnostics and is not formatted. ### Problems in the file -A key or a value the server can't read is dropped, and the rest of the file is used. A file that exists but can't be read (not UTF-8, no permission, a folder with that name) is one problem at its first line. Problems show on the `.ruby-templates.toml` itself in the Problems panel, and in the _Ruby Templates_ output, once a template it applies to is open or formatted; they refresh when the file is saved. A `.ruby-templates.toml` above the workspace folders is watched too, if the editor allows it. `ruby-templates check` prints a problem as `file:line:column: warning: message` and exits with 1 (the legacy `ruby-templates-ls --check` prints it but doesn't fail on it), and `format --verbose` prints it too. A file that isn't valid TOML is ignored whole. +A key or a value the server can't read is dropped, and the rest of the file is used. A file that exists but can't be read (not UTF-8, no permission, a folder with that name) is one problem at its first line. Problems show on the `.ruby-templates.toml` itself in the Problems panel, and in the _Ruby Templates_ output, once a template it applies to is open or formatted; they refresh when the file is saved. A `.ruby-templates.toml` above the workspace folders is watched too, if the editor allows it. `ruby-templates check` prints a problem as `file:line:column: warning: message [Config/Invalid]` and exits with 1, and `format --verbose` prints it too. A file that isn't valid TOML is ignored whole. diff --git a/site/src/data/diagnostics.ts b/site/src/data/diagnostics.ts index 7690b99..486a33e 100644 --- a/site/src/data/diagnostics.ts +++ b/site/src/data/diagnostics.ts @@ -686,7 +686,7 @@ export const diagnostics: Diagnostic[] = [ column: 5, }, { - code: "Rails/I18nMissingKey", + code: "Rails/MissingTranslation", languages: ["erb", "haml", "slim"], summary: "A lazy translation key with no entry in `config/locales`.", explanation: diff --git a/site/src/data/rules.ts b/site/src/data/rules.ts index 733fc4d..80b7a2b 100644 --- a/site/src/data/rules.ts +++ b/site/src/data/rules.ts @@ -1,5 +1,4 @@ -// The formatting and lint rules: the ones the extension has today and the ones planned. Names, options and the -// config file are a draft. `checklist()` turns the list into a Markdown task list for a tracking issue: +// The formatting and lint rules, with their options and examples. `checklist()` turns the list into a Markdown task list for a tracking issue: // cd site && bun -e 'import { checklist } from "./src/data/rules.ts"; console.log(checklist())' import { diagnostics, LANGUAGE_NAMES, type Language } from "./diagnostics"; @@ -1817,19 +1816,19 @@ enabled = false`, ], }, { - name: "Rails/I18nMissingKey", + name: "Rails/MissingTranslation", summary: 'A lazy translation key, such as `t(".title")`, with no entry in `config/locales`.', languages: ["erb", "haml", "slim"], type: "warning", safe: true, status: "available", - code: "Rails/I18nMissingKey", + code: "Rails/MissingTranslation", today: 'A literal lazy key (`t(".title")`, `translate`, with or without parentheses) is turned into its full key as Rails does (`users/_form` gives `users.form.title`, a layout keeps its folder) and must be in the default locale of the YAML files under config/locales: `config.i18n.default_locale`, `en` without one. Absolute keys (`t("users.index.title")`) are not checked, since gems supply keys such as `date.formats` and `helpers.submit.create`; nor is a key with `default:`, `scope:` or `locale:`, a key with interpolation, or one in a view named for a gem in the Gemfile.lock (`devise/sessions/new`, a copy of the gem\'s view). The closest key of the view within two edits is offered. Nothing is reported without a config/application.rb or a locale file for the default locale, when the app has Ruby locale files, adds to `I18n.load_path`, sets `I18n.backend` (also `config.i18n.load_path`, `railties_load_path`) or uses a gem that keeps translations in a store (`i18n-active_record`, `redis-i18n`). Quick fixes: "Use `.title`" replaces the key with the closest one, and "Add `users.index.title` to config/locales/en.yml" inserts it with an empty value below its closest group in the default locale\'s file, or into `config/locales/.yml`, which is created when it is absent and the editor can create files. The file is edited as text, so its comments, quotes and line endings stay, and nothing is offered where the key can\'t be placed with certainty: a flow mapping, an alias, an anchor or a merge key on the way, a list, or a value where the group should be. Rails projects only, in templates under app/views.', setting: { label: "Turn it off", - code: `[Rails.I18nMissingKey] + code: `[Rails.MissingTranslation] enabled = false`, }, examples: [ @@ -1845,7 +1844,7 @@ enabled = false`, line: 1, column: 11, message: I18N_MESSAGE, - code: "Rails/I18nMissingKey", + code: "Rails/MissingTranslation", }, ], }, @@ -1860,7 +1859,7 @@ enabled = false`, line: 1, column: 8, message: I18N_MESSAGE, - code: "Rails/I18nMissingKey", + code: "Rails/MissingTranslation", }, ], }, @@ -1875,7 +1874,7 @@ enabled = false`, line: 1, column: 8, message: I18N_MESSAGE, - code: "Rails/I18nMissingKey", + code: "Rails/MissingTranslation", }, ], }, diff --git a/src/client.js b/src/client.js index 73d39ea..ba396f8 100644 --- a/src/client.js +++ b/src/client.js @@ -228,38 +228,6 @@ const onServerStarted = (listener) => { const notifyServer = (method, params) => client?.isRunning() ? client.sendNotification(method, params) : undefined; -/** - * The server's formatting edits for `doc`: the whole document, or only the lines of `range`. `null` while the - * server isn't running, when the request fails, or when the server leaves the file as it is (it logs why). - */ -async function serverFormatEdits(doc, { tabSize, insertSpaces }, range) { - if (!client?.isRunning()) return null; - const c2p = client.code2ProtocolConverter; - // The file options vscode-languageclient sends with its own formatting requests: only those that are on. - const files = vscode.workspace.getConfiguration("files", doc); - const fileOptions = Object.fromEntries( - ["trimTrailingWhitespace", "insertFinalNewline", "trimFinalNewlines"] - .filter((key) => files.get(key) === true) - .map((key) => [key, true]), - ); - const params = { - textDocument: { uri: c2p.asUri(doc.uri) }, - options: { tabSize, insertSpaces, ...fileOptions }, - }; - try { - const edits = range - ? await client.sendRequest("textDocument/rangeFormatting", { - ...params, - range: c2p.asRange(range), - }) - : await client.sendRequest("textDocument/formatting", params); - return edits && (await client.protocol2CodeConverter.asTextEdits(edits)); - } catch (e) { - log(`formatting: ${e?.message ?? e}`); - return null; - } -} - /** Starts the server, restarting it on the restart command or a change to a setting it reads; returns its log. */ function registerServer(context) { output = vscode.window.createOutputChannel("Ruby Templates", { log: true }); @@ -276,11 +244,4 @@ function registerServer(context) { void startClient(context); } -export { - registerServer, - log, - serverFormatEdits, - stopClient, - onServerStarted, - notifyServer, -}; +export { registerServer, log, stopClient, onServerStarted, notifyServer }; diff --git a/src/extension.js b/src/extension.js index 1e59c3c..7fd6682 100644 --- a/src/extension.js +++ b/src/extension.js @@ -6,7 +6,7 @@ import { toggleErbLineComment, wrapInErb, } from "./erbCommands.js"; -import { toggleActiveHamlLines, reindentActiveHaml } from "./hamlCommands.js"; +import { toggleActiveHamlLines } from "./hamlCommands.js"; import { toggleSlimTag, wrapInSlim } from "./slimCommands.js"; import { extractPartial } from "./extractPartial.js"; import { switchRelated } from "./relatedFile.js"; @@ -25,7 +25,6 @@ const COMMANDS = { "rubyTemplates.extractPartial": extractPartial, "rubyTemplates.switchRelated": switchRelated, "rubyTemplates.toggleHamlPrefix": toggleActiveHamlLines, - "rubyTemplates.reindentHaml": reindentActiveHaml, "rubyTemplates.toggleSlimTag": toggleSlimTag, "rubyTemplates.wrapInSlim": wrapInSlim, // The former Slim-only id, kept for keybindings that still name it. diff --git a/src/hamlCommands.js b/src/hamlCommands.js index 8d5a107..ff98ced 100644 --- a/src/hamlCommands.js +++ b/src/hamlCommands.js @@ -1,7 +1,6 @@ -// Haml editing commands: cycle the Ruby prefix, re-indent through the server. +// Haml editing commands: cycle the Ruby prefix. import * as vscode from "vscode"; -import { serverFormatEdits } from "./client.js"; import { toggleHamlLines } from "./haml.js"; import { selectedLines, documentLines } from "./editor.js"; @@ -17,30 +16,4 @@ async function toggleActiveHamlLines() { ); } -/** Re-indents the selected lines, or the whole document, through the server's formatter. */ -async function reindentActiveHaml() { - const ed = vscode.window.activeTextEditor; - if (ed?.document.languageId !== "haml") return; - const { selection, document: doc } = ed; - const lines = selectedLines(selection); - const range = selection.isEmpty - ? undefined - : new vscode.Range(lines[0], 0, lines.at(-1), 0); - const { tabSize, insertSpaces } = ed.options; - const options = { - tabSize: Number(tabSize), - insertSpaces: insertSpaces === true, - }; - const edits = await serverFormatEdits(doc, options, range); - if (!edits) { - vscode.window.showInformationMessage( - "Re-indent Haml: the language server is not running, or left this file unchanged (the reason is in the Ruby Templates output).", - ); - return; - } - await ed.edit((eb) => - edits.forEach(({ range, newText }) => eb.replace(range, newText)), - ); -} - -export { toggleActiveHamlLines, reindentActiveHaml }; +export { toggleActiveHamlLines }; diff --git a/test/cli.js b/test/cli.js index 03faa8f..52e71a6 100644 --- a/test/cli.js +++ b/test/cli.js @@ -225,6 +225,32 @@ try { assert.strictEqual(r.stdout, "div\n p\n"); assert.match(r.stderr, /\.editorconfig: ignored max_line_length = 100/); + const version = run(["--version"]); + assert.strictEqual(version.status, 0); + assert.match(version.stdout, /^ruby-templates \d+\.\d+\.\d+\S*\n$/); + assert.strictEqual(run(["-V"]).stdout, version.stdout); + for (const args of [ + ["--help"], + ["check", "--help"], + ["format", "-h"], + ["format", "--check", "--help"], + ]) { + const help = run(args); + assert.strictEqual(help.status, 0, `help: ${args.join(" ")}`); + assert.match(help.stdout, /^Usage:/); + } + + assert.strictEqual( + run(["check", "--format", "-h"]).status, + 2, + "-h is the value of --format", + ); + const lsBin = path.join(path.dirname(bin), `ruby-templates-ls${exe}`); + if (fs.existsSync(lsBin)) { + const ls = spawnSync(lsBin, ["--version"], { encoding: "utf8" }); + assert.match(ls.stdout, /^ruby-templates-ls \d+\.\d+\.\d+\S*\n$/); + } + for (const args of [ [], ["lint"], @@ -302,8 +328,23 @@ try { assert.strictEqual(r.status, 0, r.stdout + r.stderr); assert.match( r.stdout, - /_card\.html\.erb:1:\d+: info: `@user` is read in a partial/, - ); + /_card\.html\.erb:1:\d+: info: `@user` is read in a partial.* \[Rails\/InstanceVariableInPartial\]\n/, + ); + // One word for the lowest severity in text and JSON; GitHub and SARIF keep their own. + const card = path.join(app, "app/views/users/_card.html.erb"); + const severities = { + json: JSON.parse(run(["check", card, "--format", "json"]).stdout).severity, + github: run(["check", card, "--format", "github"]).stdout.match( + /^::(\w+) /, + )[1], + sarif: JSON.parse(run(["check", card, "--format", "sarif"]).stdout).runs[0] + .results[0].level, + }; + assert.deepStrictEqual(severities, { + json: "info", + github: "notice", + sarif: "note", + }); assert.doesNotMatch(r.stdout, /_form|show\.html\.slim/); assert.strictEqual( run(["check", generator]).status, @@ -383,6 +424,13 @@ try { const problem = /\.ruby-templates\.toml:1:7: warning: unknown rule `Html\/ImgAltt`/g; assert.strictEqual(r.stdout.match(problem)?.length, 1, "printed once"); + fs.writeFileSync(toml, '[erb]\ndisabled_diagnostics = ["Html/ImgAlt"]\n'); + r = run(["check", noAlt, inner]); + assert.strictEqual(r.status, 1, "the removed key is a finding"); + assert.match( + r.stdout, + /\.ruby-templates\.toml:2:1: warning: `disabled_diagnostics` is removed; switch a rule off with `\[Html\.ImgAlt\] enabled = false`.* \[Config\/Invalid\]\n/, + ); fs.writeFileSync(toml, "[Html.ImgAlt\n"); r = run(["check", clean, path.join(project, "messy.html.erb")]); assert.strictEqual(r.status, 1, "invalid TOML is a finding"); @@ -782,9 +830,9 @@ try { assert.strictEqual(r.status, 1); assert.strictEqual( r.stdout, - `.ruby-templates.toml:1:13: warning: ${tomlProblem}\n` + - `${path.join("app", "views", "a b.html.erb")}:1:11: warning: ${imgAlt}\n`, - "text keeps UTF-16 columns and the platform's separators", + `.ruby-templates.toml:1:13: warning: ${tomlProblem} [Config/Invalid]\n` + + `${path.join("app", "views", "a b.html.erb")}:1:10: warning: ${imgAlt} [Html/ImgAlt]\n`, + "text names the rule, counts characters like the other formats, and keeps the platform's separators", ); r = checkCi("github"); assert.strictEqual(r.status, 1); diff --git a/test/e2e.js b/test/e2e.js index 02c1b60..cbcfcf7 100644 --- a/test/e2e.js +++ b/test/e2e.js @@ -916,7 +916,7 @@ const check = (label, actual, expected) => { ?.params.diagnostics.map((d) => d.source), ), ]; - check("erb diagnostics source", sources(uri), ["erb"]); + check("diagnostics source", sources(uri), ["ruby-templates"]); const strictUri = fileUri(path.join(views, "strict", "show.html.erb")); await send( @@ -1323,7 +1323,7 @@ const check = (label, actual, expected) => { }, true, ); - check("haml diagnostics source", sources(hamlUri), ["haml"]); + check("haml diagnostics source", sources(hamlUri), ["ruby-templates"]); await new Promise((r) => setTimeout(r, 200)); const slimDiag = notes.find( @@ -1347,7 +1347,7 @@ const check = (label, actual, expected) => { "8:1 Syntax/Ruby", ], ); - check("slim diagnostics source", sources(slimUri), ["slim"]); + check("slim diagnostics source", sources(slimUri), ["ruby-templates"]); // Haml's Ruby is checked once Haml accepts the template: an error in code, and a `rescue` inside an `if`. const hamlRubyUri = fileUri(path.join(views, "users", "ruby.html.haml")); @@ -3227,6 +3227,16 @@ const check = (label, actual, expected) => { ], ], ); + check( + "toml: problems have the rule as code", + rulesPublished(tomlUri)?.map((d) => d.code), + ["Config/Invalid"], + ); + check( + "toml: problems have the tool as source", + rulesPublished(tomlUri)?.map((d) => d.source), + ["ruby-templates"], + ); check( "toml: problems are logged", rulesServer.notes.some( @@ -3407,8 +3417,8 @@ const check = (label, actual, expected) => { check( "quick fixes: a missing key is replaced or added to the default locale's file", [ - edited(await withFiles.actions("Rails/I18nMissingKey", 1)), - edited(await withFiles.actions("Rails/I18nMissingKey", 2)), + edited(await withFiles.actions("Rails/MissingTranslation", 1)), + edited(await withFiles.actions("Rails/MissingTranslation", 2)), ], [ [ diff --git a/test/vscode/run.js b/test/vscode/run.js index 5073091..5e5f26a 100644 --- a/test/vscode/run.js +++ b/test/vscode/run.js @@ -63,7 +63,6 @@ write( ); write("app/views/users/wrap.html.slim", "p\n hello world\n"); write("app/views/users/toggle.html.haml", "- foo\n= bar\n-# baz\n%p\n"); -write("app/views/users/reindent.html.haml", "%div\n %p\n %b x\n"); write("app/views/users/format.html.haml", "%ul\n %li\n %b x\n"); write("app/views/users/format.html.slim", "div\n p= x\n p y\n"); write( diff --git a/test/vscode/suite.js b/test/vscode/suite.js index b43e5a9..9f2202f 100644 --- a/test/vscode/suite.js +++ b/test/vscode/suite.js @@ -221,7 +221,7 @@ const checks = { const served = () => vscode.languages .getDiagnostics(editor.document.uri) - .filter((d) => d.source === "erb"); + .filter((d) => d.source === "ruby-templates"); const key = "erb.diagnostics.enabled"; const global = vscode.ConfigurationTarget.Global; try { @@ -485,18 +485,6 @@ const checks = { assert.strictEqual(text, "= foo\n-# bar\n- baz\n%p\n"); }, - async "reindent Haml command"() { - const editor = await open("app/views/users/reindent.html.haml"); - try { - editor.options = { tabSize: 2, insertSpaces: true }; - select(editor, 0, 0, 0, 0); - await vscode.commands.executeCommand("rubyTemplates.reindentHaml"); - assert.strictEqual(editor.document.getText(), "%div\n %p\n %b x\n"); - } finally { - await revert(editor); - } - }, - async "Haml Format Document reindents"() { const editor = await open("app/views/users/format.html.haml"); try {
- {rules.length} rules: {countOf("available")} available, {countOf("partial")} partial, {countOf("planned")} planned + {rules.length} rules{countOf("partial") + countOf("planned") > 0 && `: ${countOf("available")} available, ${countOf("partial")} partial, ${countOf("planned")} planned`}