Skip to content

Commit

Permalink
feat: Add option to override macro name (#109)
Browse files Browse the repository at this point in the history
* Add option to override html macro

* Format multiple macros

* Actually support fully qualified macro path

* macro_names as a reference in ViewMacroVisitor
  • Loading branch information
SofusA authored Mar 2, 2024
1 parent ad49901 commit 1c697c4
Show file tree
Hide file tree
Showing 10 changed files with 256 additions and 58 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Options:
-c, --config-file <CONFIG_FILE> Configuration file
-s, --stdin Format stdin and write to stdout
-r, --rustfmt Format with rustfmt after formatting with leptosfmt (requires stdin)
--override-macro-names
<OVERRIDE_MACRO_NAMES>... Override formatted macro names
-q, --quiet
--check Check if the file is correctly formatted. Exit with code 1 if not
-h, --help Print help
Expand Down Expand Up @@ -64,6 +66,7 @@ tab_spaces = 4 # Number of spaces per tab
indentation_style = "Auto" # "Tabs", "Spaces" or "Auto"
newline_style = "Auto" # "Unix", "Windows" or "Auto"
attr_value_brace_style = "WhenRequired" # "Always", "AlwaysUnlessLit", "WhenRequired" or "Preserve"
macro_names = [ "leptos::view, view" ] # Macro names which will be formatted
```

To see what each setting does, the see [configuration docs](./docs/configuration.md)
Expand Down
14 changes: 11 additions & 3 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ struct Args {
#[arg(short, long, default_value = "false", requires = "stdin")]
rustfmt: bool,

/// Override formatted macro names
#[arg(long, num_args=1.., value_delimiter= ' ')]
override_macro_names: Option<Vec<String>>,

#[arg(
short,
long,
Expand Down Expand Up @@ -137,7 +141,7 @@ fn main() {

let format_results = file_paths
.into_par_iter()
.map(|path| (path.clone(), format_file(&path, settings, !args.check)))
.map(|path| (path.clone(), format_file(&path, &settings, !args.check)))
.collect::<Vec<_>>();

let mut check_failed = false;
Expand Down Expand Up @@ -200,7 +204,7 @@ fn format_stdin(settings: FormatterSettings) -> anyhow::Result<FormatOutput> {
let mut stdin = String::new();
let _ = std::io::stdin().read_to_string(&mut stdin);

let formatted = panic::catch_unwind(|| format_file_source(&stdin, settings))
let formatted = panic::catch_unwind(|| format_file_source(&stdin, &settings))
.map_err(|e| anyhow::anyhow!(e.downcast::<String>().unwrap()))??;

Ok(FormatOutput {
Expand All @@ -211,7 +215,7 @@ fn format_stdin(settings: FormatterSettings) -> anyhow::Result<FormatOutput> {

fn format_file(
file: &PathBuf,
settings: FormatterSettings,
settings: &FormatterSettings,
write_result: bool,
) -> anyhow::Result<FormatOutput> {
let file_source = std::fs::read_to_string(file)?;
Expand Down Expand Up @@ -254,6 +258,10 @@ fn create_settings(args: &Args) -> anyhow::Result<FormatterSettings> {
if let Some(tab_spaces) = args.tab_spaces {
settings.tab_spaces = tab_spaces;
}

if let Some(macro_names) = args.override_macro_names.to_owned() {
settings.macro_names = macro_names;
}
Ok(settings)
}

Expand Down
21 changes: 16 additions & 5 deletions formatter/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,22 @@ use syn::{
File, Macro,
};

use crate::{ParentIndent, ViewMacro};
use crate::{view_macro::get_macro_full_path, ParentIndent, ViewMacro};

struct ViewMacroVisitor<'ast> {
macros: Vec<ViewMacro<'ast>>,
struct ViewMacroVisitor<'a> {
macros: Vec<ViewMacro<'a>>,
source: Rope,
macro_names: &'a Vec<String>,
}

impl<'ast> Visit<'ast> for ViewMacroVisitor<'ast> {
fn visit_macro(&mut self, node: &'ast Macro) {
if node.path.is_ident("view") {
let should_format = self
.macro_names
.iter()
.any(|macro_name| &get_macro_full_path(node) == macro_name);

if should_format {
let span_line = node.span().start().line;
let line = self.source.line(span_line - 1);

Expand All @@ -35,10 +41,15 @@ impl<'ast> Visit<'ast> for ViewMacroVisitor<'ast> {
}
}

pub fn collect_macros_in_file(file: &File, source: Rope) -> (Rope, Vec<ViewMacro<'_>>) {
pub fn collect_macros_in_file<'a>(
file: &'a File,
source: Rope,
macro_names: &'a Vec<String>,
) -> (Rope, Vec<ViewMacro<'a>>) {
let mut visitor = ViewMacroVisitor {
source,
macros: Vec::new(),
macro_names,
};

visitor.visit_file(file);
Expand Down
2 changes: 1 addition & 1 deletion formatter/src/formatter/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl Formatter<'_> {
}
}

pub fn children(&mut self, children: &Vec<Node>, attribute_count: usize) {
pub fn children(&mut self, children: &[Node], attribute_count: usize) {
if children.is_empty() {
return;
}
Expand Down
10 changes: 7 additions & 3 deletions formatter/src/formatter/mac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use proc_macro2::{token_stream, Span, TokenStream, TokenTree};
use rstml::node::Node;
use syn::{spanned::Spanned, Macro};

use crate::view_macro::get_macro_full_path;

use super::{Formatter, FormatterSettings};

pub struct ViewMacro<'a> {
Expand Down Expand Up @@ -85,7 +87,9 @@ impl Formatter<'_> {
.cbox((parent_indent.tabs * self.settings.tab_spaces + parent_indent.spaces) as isize);

self.flush_comments(cx.span().start().line - 1);
self.printer.word("view! {");

let macro_word = format!("{}! {{", get_macro_full_path(view_mac.mac));
self.printer.word(macro_word);

if let Some(cx) = cx {
self.printer.word(" ");
Expand Down Expand Up @@ -170,9 +174,9 @@ pub fn format_macro(
mac.mac.tokens.clone(),
);

Formatter::with_source(*settings, &mut printer, source, whitespace)
Formatter::with_source(settings, &mut printer, source, whitespace)
}
None => Formatter::new(*settings, &mut printer),
None => Formatter::new(settings, &mut printer),
};

formatter.view_macro(mac);
Expand Down
13 changes: 8 additions & 5 deletions formatter/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub enum NewlineStyle {
Windows,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default)]
pub struct FormatterSettings {
// Maximum width of each line
Expand All @@ -57,6 +57,9 @@ pub struct FormatterSettings {

// Determines placement of braces around single expression attribute values
pub attr_value_brace_style: AttributeValueBraceStyle,

// Determines macros to be formatted. Default: leptos::view, view
pub macro_names: Vec<String>,
}

impl Default for FormatterSettings {
Expand All @@ -67,6 +70,7 @@ impl Default for FormatterSettings {
attr_value_brace_style: AttributeValueBraceStyle::WhenRequired,
indentation_style: IndentationStyle::Auto,
newline_style: NewlineStyle::Auto,
macro_names: vec!["leptos::view".to_string(), "view".to_string()],
}
}
}
Expand Down Expand Up @@ -110,14 +114,14 @@ impl FormatterSettings {

pub struct Formatter<'a> {
pub printer: &'a mut leptosfmt_pretty_printer::Printer,
pub settings: FormatterSettings,
pub settings: &'a FormatterSettings,
pub(crate) source: Option<&'a Rope>,
pub(crate) whitespace_and_comments: HashMap<usize, Option<String>>,
pub(crate) line_offset: Option<usize>,
}

impl<'a> Formatter<'a> {
pub fn new(settings: FormatterSettings, printer: &'a mut Printer) -> Self {
pub fn new(settings: &'a FormatterSettings, printer: &'a mut Printer) -> Self {
Self {
printer,
settings,
Expand All @@ -127,7 +131,7 @@ impl<'a> Formatter<'a> {
}
}
pub fn with_source(
settings: FormatterSettings,
settings: &'a FormatterSettings,
printer: &'a mut Printer,
source: &'a Rope,
comments: HashMap<usize, Option<String>>,
Expand Down Expand Up @@ -184,4 +188,3 @@ impl<'a> Formatter<'a> {
self.line_offset = Some(line_index);
}
}

2 changes: 1 addition & 1 deletion formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub use formatter::*;

pub fn format_file(path: &Path, settings: FormatterSettings) -> Result<String, FormatError> {
let file = std::fs::read_to_string(path)?;
format_file_source(&file, settings)
format_file_source(&file, &settings)
}

fn get_text_beween_spans(rope: &Rope, start: LineColumn, end: LineColumn) -> RopeSlice<'_> {
Expand Down
Loading

0 comments on commit 1c697c4

Please sign in to comment.