Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
- `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.
- `ruby-templates check` prints one note on stderr per Rails-looking app (`app/views` or `config/application.rb`) that has no `Gemfile.lock`, saying that the `Rails/*`, `Stimulus/*` and `Turbo/*` rules are off for lack of it. Exit codes and stdout don't change.
- ERB formatting no longer refuses a file for an inline `<%= tag.style x %>`, `<%= tag.script(src: x) %>`, `<%= javascript_tag "x" %>` or `content_tag :script, x`; only the block forms (`javascript_tag do`) still leave the file as it is.
- `ruby-templates check --help` and the command line guide say that Jbuilder and Builder views get their partial and `locals:` checks, not Ruby syntax errors, which stay with Ruby LSP.
- `insert_final_newline = true` in `.editorconfig` turns `Layout/TrailingEmptyLines` on for ERB (off by default there); `enabled = false` in a `.ruby-templates.toml` still wins.
- `Rails/UnsafeOutput` no longer reports a string whose interpolations are all safe (`"Hi #{h(name)}".html_safe`) or `truncate(...)` without `escape: false`.
- `Rails/UnsafeOutput` quotes long or multi-line code cut with `…` instead of saying "its value".
- **Behaviour change:** `Rails/InstanceVariableInPartial` is information instead of a warning, so `ruby-templates check` no longer fails on it; the editor still shows it.
- **Breaking:** the kebab-case diagnostic codes from before 0.11 (`img-missing-alt`, `unresolved-render`, ...) are no longer accepted in `disabledDiagnostics`, in the VS Code settings or `.ruby-templates.toml`. Use the rule names (`Html/ImgAlt`, `Rails/MissingPartial`), listed in the diagnostics reference; the toml reports an old code as an unknown rule.
- **Breaking:** `ruby-templates-ls --check` and `ruby-templates-ls --format` are removed. Use `ruby-templates check` and `ruby-templates format`.
Expand Down
30 changes: 22 additions & 8 deletions server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::format::SkipKind;
use crate::lang::TemplateLang;
use crate::options::Options;
use crate::rails::paths;
use crate::rails::project::{Project, Projects};
use crate::rails::project::{missing_lockfile_note, Project, Projects};
use crate::rails::view_roots;
use crate::report::{self, Finding, Format, Severity};
use crate::rules::file::ConfigFile;
Expand All @@ -33,8 +33,8 @@ Usage:
ruby-templates format [--check | --write] [--format text|github] [--verbose] [--align-comments] <files|dirs>...
ruby-templates format [--check] [--format text|github] [--verbose] [--align-comments] --stdin-filepath <path> [-]

check prints the diagnostics of ERB, Haml, Slim, Jbuilder and Builder templates, and with Layout/LineLength (off) the lines
over its max.
check prints the diagnostics of ERB, Haml, Slim, Jbuilder and Builder templates (for Jbuilder and Builder, partials and
locals, not Ruby syntax errors), and with Layout/LineLength (off) the lines over its max.
format re-indents HTML ERB, Haml and Slim templates and fixes trailing whitespace. The rules Layout/EmptyLines,
Layout/EmptyLinesAroundBlockBody, Layout/EmptyLinesAroundElementBody and Layout/EmptyLinesAroundBranches (all
off) and Layout/TrailingEmptyLines (on for Haml and Slim, off for ERB) set blank lines and the final newline.
Expand Down Expand Up @@ -297,12 +297,14 @@ struct Checked {
/// The problems of each `.ruby-templates.toml` the file uses; the printer shows a file's once, with its first template.
config: Vec<(PathBuf, Rendered)>,
stderr: String,
/// The Rails-looking app the file is in when it has no `Gemfile.lock`, and its name for the note; the printer notes each app once.
unlocked_app: Option<(PathBuf, PathBuf)>,
code: i32,
}

impl Checked {
fn new(code: i32) -> Self {
Checked { rendered: Rendered::default(), config: Vec::new(), stderr: String::new(), code }
Checked { rendered: Rendered::default(), config: Vec::new(), stderr: String::new(), unlocked_app: None, code }
}
}

Expand All @@ -329,8 +331,15 @@ fn check_file(
let Ok(text) = std::fs::read_to_string(path) else { return failed(format!("cannot read {shown}\n")) };
let Some((uri, lang)) = absolute_file_uri(path).zip(language(path)) else { return failed(format!("{shown}: unknown template type\n")) };
// Every worker's projects of one app share its view roots.
Project::memoized(projects, path, Some(view_roots));
// The path as the diagnostics see it, so a relative `check x/f.erb` finds the app above the working folder.
let real = util::file_path(&uri).unwrap_or_else(|| path.to_path_buf());
let project = Project::memoized(projects, &real, Some(view_roots));
let mut checked = Checked::new(OK);
checked.unlocked_app = project.rails_root_without_lockfile(&real).map(|app| {
let shown = shown_path(&app, output.cwd);
let shown = if shown.as_os_str().is_empty() { Path::new(".") } else { shown };
(app.clone(), shown.to_path_buf())
});
let rules = resolve(&uri, lang, &Options::default(), configs);
for file in rules.files().iter().filter(|file| !file.problems.is_empty()) {
let rendered = render_config_problems(file, output);
Expand Down Expand Up @@ -377,22 +386,27 @@ fn print_in_order(results: mpsc::Receiver<(usize, Checked)>, format: Format) ->
let mut code = OK;
let mut findings = Vec::new();
let mut reported = HashSet::new();
let mut noted_apps = HashSet::new();
for (index, checked) in results {
waiting.insert(index, checked);
while let Some(checked) = waiting.remove(&next) {
next += 1;
code = code.max(checked.code);
let mut stderr = checked.stderr;
if let Some((_, shown)) = checked.unlocked_app.filter(|(app, _)| noted_apps.insert(app.clone())) {
stderr.push_str(&missing_lockfile_note(&shown));
}
let new_config = checked.config.into_iter().filter(|(path, _)| reported.insert(path.clone()));
let shown: Vec<Rendered> = new_config.map(|(_, rendered)| rendered).chain([checked.rendered]).collect();
let text: String = shown.iter().map(|rendered| rendered.stdout.as_str()).collect();
findings.extend(shown.into_iter().flat_map(|rendered| rendered.findings));
let printed = stdout.write_all(text.as_bytes()).and_then(|()| {
if checked.stderr.is_empty() {
if stderr.is_empty() {
return Ok(());
}
// Keep stderr lines in place among the diagnostics.
stdout.flush()?;
std::io::stderr().write_all(checked.stderr.as_bytes())
std::io::stderr().write_all(stderr.as_bytes())
});
if printed.is_err() {
return USAGE;
Expand Down Expand Up @@ -477,7 +491,7 @@ fn format_text(
(Some(uri), Some(lang)) => {
let rules = resolve(&uri, lang, &Options::default(), configs);
let resolved = config::settings_for(&util::file_path(&uri).unwrap_or_else(|| path.to_path_buf()));
let mut settings = rules.format_settings(resolved.settings);
let mut settings = rules.format_settings(resolved.settings, resolved.insert_final_newline);
settings.align_comments |= args.align_comments;
if args.verbose {
print_verbose(&shown.to_string(), &settings, &resolved.notes, (&rules, cwd));
Expand Down
39 changes: 28 additions & 11 deletions server/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! The indentation width and style of a file, from the project's `.editorconfig`. The editor's tab size and `insertSpaces` go on top
//! in the language server (`Settings::with_editor`). Every other property is ignored and listed in the notes.
//! The indentation width and style and the final newline of a file, from the project's `.editorconfig`. The editor's tab size and
//! `insertSpaces` go on top in the language server (`Settings::with_editor`). Every other property is ignored and listed in the notes.

use crate::format::{IndentStyle, Settings};
use crate::glob::Glob;
Expand All @@ -9,23 +9,28 @@ use std::path::Path;
/// Settings for one file, and what was read or ignored to get them.
pub struct Resolved {
pub settings: Settings,
/// `insert_final_newline = true`: turns `Layout/TrailingEmptyLines` on where it is off by default (ERB).
pub insert_final_newline: bool,
pub notes: Vec<String>,
}

pub fn settings_for(path: &Path) -> Resolved {
let mut notes = Vec::new();
let defaults = Settings::default();
let (size, style) = editorconfig_indent(path, &mut notes);
let settings =
Settings { indent_size: size.unwrap_or(defaults.indent_size), indent_style: style.unwrap_or(defaults.indent_style), ..defaults };
Resolved { settings, notes }
let properties = editorconfig_properties(path, &mut notes);
let settings = Settings {
indent_size: indent_size(&properties).unwrap_or(defaults.indent_size),
indent_style: indent_style(&properties).unwrap_or(defaults.indent_style),
..defaults
};
Resolved { settings, insert_final_newline: property(&properties, "insert_final_newline") == Some("true"), notes }
}

/// The indentation width and style from the `.editorconfig` properties that apply to `path`: files from the root (or the topmost
/// `root = true`) down, later sections and nearer files winning, as the EditorConfig spec has it.
fn editorconfig_indent(path: &Path, notes: &mut Vec<String>) -> (Option<usize>, Option<IndentStyle>) {
/// The `.editorconfig` properties that apply to `path`: files from the root (or the topmost `root = true`) down, later sections
/// and nearer files winning, as the EditorConfig spec has it.
fn editorconfig_properties(path: &Path, notes: &mut Vec<String>) -> Vec<(String, String)> {
if path.file_name().is_none() {
return (None, None);
return Vec::new();
}
let mut properties = Vec::new();
for (dir, text) in editorconfig_files(path).iter().rev() {
Expand All @@ -37,7 +42,7 @@ fn editorconfig_indent(path: &Path, notes: &mut Vec<String>) -> (Option<usize>,
for (key, value) in properties.iter().filter(|(k, v)| v != "unset" && !is_understood(k, v)) {
notes.push(format!(".editorconfig: ignored {key} = {value}"));
}
(indent_size(&properties), indent_style(&properties))
properties
}

/// The folders above `path` that hold an `.editorconfig`, with its text: nearest first, up to the first `root = true`.
Expand Down Expand Up @@ -109,6 +114,8 @@ fn is_understood(key: &str, value: &str) -> bool {
"indent_style" => matches!(value, "space" | "tab"),
"indent_size" => value == "tab" || positive_number(value).is_some(),
"tab_width" => positive_number(value).is_some(),
// `false` changes nothing: the final newline is only ever added.
"insert_final_newline" => value == "true",
_ => false,
}
}
Expand Down Expand Up @@ -195,6 +202,16 @@ mod tests {
assert!(project.settings("a.html.erb").notes.iter().all(|n| !n.contains("ignored")), "indent_style is understood");
}

#[test]
fn editorconfig_insert_final_newline_true_is_read() {
let text = "[*.erb]\ninsert_final_newline = true\n[*.slim]\ninsert_final_newline = false\n";
let project = Project::new("newline", &[(".editorconfig", text), ("a.html.erb", ""), ("b.html.slim", ""), ("c.html.haml", "")]);
let newline = |file: &str| project.settings(file).insert_final_newline;
assert_eq!((newline("a.html.erb"), newline("b.html.slim"), newline("c.html.haml")), (true, false, false));
let notes = project.settings("a.html.erb").notes;
assert!(notes.iter().all(|n| !n.contains("ignored")), "{notes:?}");
}

#[test]
fn editorconfig_tab_width_and_unreadable_values() {
let text = "[*]\nindent_style = space\ntab_width = 8\ntrim_trailing_whitespace = yes\n[[z-a].erb]\nindent_size = 3\n";
Expand Down
5 changes: 3 additions & 2 deletions server/src/erb/tags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ pub(crate) fn tag_end(html: &[u8], from: usize) -> Option<TagEnd> {

/// HTML with ERB tags blanked out, plus every ERB tag as an event, in order. Tags are Erubi's; a `<%%` literal
/// renders as text, so it stays in the HTML. With `skip_raw_blocks` the JS/CSS block helpers' bodies are blanked and
/// their events dropped; without, any such helper makes the result `None`.
/// their events dropped; without, any such helper with a block makes the result `None`.
fn split<'a>(
text: &'a str,
analyzed: &[(erb::ruby::ErbTag<'a>, BlockEffect)],
Expand All @@ -423,7 +423,8 @@ fn split<'a>(
(BlockEffect::Neutral, "", "")
} else {
let snippet = &text[tag.code.clone()];
if RAW_BLOCK.is_match(snippet) && (!skip_raw_blocks || BRACE_BLOCK_OPEN.is_match(snippet)) {
let unreadable_block = BRACE_BLOCK_OPEN.is_match(snippet) || (!skip_raw_blocks && matches!(effect, BlockEffect::Open(_)));
if RAW_BLOCK.is_match(snippet) && unreadable_block {
return None;
}
(*effect, snippet.split_whitespace().next().unwrap_or(""), snippet)
Expand Down
8 changes: 8 additions & 0 deletions server/src/format/erb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,14 @@ mod tests {
}
}

#[test]
fn inline_script_and_style_helpers_without_a_block_are_indented() {
for helper in ["tag.style x", "tag.script(src: x)", "javascript_tag \"x\"", "content_tag :script, x"] {
let out = indent(&format!("<div>\n<%= {helper} %>\n</div>\n"), " ", false).unwrap();
assert_eq!(out.text, format!("<div>\n <%= {helper} %>\n</div>\n"), "{helper}");
}
}

fn with_blank_lines(text: &str, settings: &Settings) -> String {
let indented = indent(text, " ", false).unwrap();
crate::format::blank_lines::apply(&indented.text, &indented.lines, settings, text)
Expand Down
6 changes: 4 additions & 2 deletions server/src/lsp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -877,8 +877,10 @@ impl Backend {
if rules.excluded_by().is_some() || !rules.format_enabled() {
return (Arc::new(rules), None);
}
let base = util::file_path(&uri).map_or_else(format::Settings::default, |path| config::settings_for(&path).settings);
let mut settings = rules.format_settings(base.with_editor(&options));
let resolved = util::file_path(&uri).map(|path| config::settings_for(&path));
let insert_final_newline = resolved.as_ref().is_some_and(|resolved| resolved.insert_final_newline);
let base = resolved.map_or_else(format::Settings::default, |resolved| resolved.settings);
let mut settings = rules.format_settings(base.with_editor(&options), insert_final_newline);
if lines_only {
// A range can't add or remove a line, and may hold a comment's inner lines without the line they move with.
settings.trailing_empty_lines = false;
Expand Down
18 changes: 18 additions & 0 deletions server/src/rails/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ use walkdir::WalkDir;
pub const LOCKFILE: &str = "Gemfile.lock";
const RUBY_VERSION_FILE: &str = ".ruby-version";

/// Tells why a Rails-looking app at `root` gets no Rails, Stimulus or Turbo rules.
pub fn missing_lockfile_note(root: &Path) -> String {
format!(
"note: {} looks like a Rails app but has no {LOCKFILE}, so the Rails/*, Stimulus/* and Turbo/* rules are off: they need its actionview gem\n",
root.display()
)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Framework {
Rails,
Expand Down Expand Up @@ -191,6 +199,16 @@ impl Project {
}
}

/// The folder of a Rails-looking app (`app/views` or `config/application.rb`) that holds `template` when no `Gemfile.lock` is
/// above it: its Rails, Stimulus and Turbo rules are off.
pub fn rails_root_without_lockfile(&self, template: &Path) -> Option<PathBuf> {
if self.root.is_some() {
return None;
}
let looks_like_rails = |dir: &&Path| dir.join(APP_VIEWS).is_dir() || dir.join("config/application.rb").is_file();
template.ancestors().skip(1).find(looks_like_rails).map(Path::to_path_buf)
}

/// Is `segment` a template format: one of Rails' own or registered by the app?
pub fn is_format(&self, segment: &str) -> bool {
is_known_format(segment) || self.formats.iter().any(|f| f == segment)
Expand Down
Loading
Loading