Procházet zdrojové kódy

feat: `--inline-attributes` option for autofmt

marc2332 před 1 rokem
rodič
revize
52cb5ff951

+ 13 - 3
packages/autofmt/src/component.rs

@@ -67,7 +67,7 @@ impl Writer<'_> {
         }
 
         // multiline handlers bump everything down
-        if attr_len > 1000 {
+        if attr_len > 1000 || self.out.indent.inline_attributes() {
             opt_level = ShortOptimization::NoOpt;
         }
 
@@ -154,11 +154,17 @@ impl Writer<'_> {
         manual_props: &Option<syn::Expr>,
         sameline: bool,
     ) -> Result {
+        println!("fields {fields:?}");
+        println!("manual_props {manual_props:?}");
+
         let mut field_iter = fields.iter().peekable();
 
         while let Some(field) = field_iter.next() {
+            println!("{:?}", field);
             if !sameline {
-                self.out.indented_tabbed_line()?;
+                self.out.indented_tabbed_line().unwrap();
+            } else {
+                println!("not  line????");
             }
 
             let name = &field.name;
@@ -200,13 +206,17 @@ impl Writer<'_> {
 
                 if sameline {
                     write!(self.out, " ")?;
+                    println!("not  line-----");
                 }
             }
         }
 
         if let Some(exp) = manual_props {
+            println!("{:?}", exp);
             if !sameline {
-                self.out.indented_tabbed_line()?;
+                self.out.indented_tabbed_line().unwrap();
+            } else {
+                println!("not  line!!!!!!");
             }
             self.write_manual_props(exp)?;
         }

+ 1 - 1
packages/autofmt/src/element.rs

@@ -102,7 +102,7 @@ impl Writer<'_> {
         }
 
         // multiline handlers bump everything down
-        if attr_len > 1000 {
+        if attr_len > 1000 || self.out.indent.inline_attributes() {
             opt_level = ShortOptimization::NoOpt;
         }
 

+ 15 - 9
packages/autofmt/src/indent.rs

@@ -8,10 +8,11 @@ pub enum IndentType {
 pub struct IndentOptions {
     width: usize,
     indent_string: String,
+    inline_attributes: bool,
 }
 
 impl IndentOptions {
-    pub fn new(typ: IndentType, width: usize) -> Self {
+    pub fn new(typ: IndentType, width: usize, inline_attributes: bool) -> Self {
         assert_ne!(width, 0, "Cannot have an indent width of 0");
         Self {
             width,
@@ -19,6 +20,7 @@ impl IndentOptions {
                 IndentType::Tabs => "\t".into(),
                 IndentType::Spaces => " ".repeat(width),
             },
+            inline_attributes,
         }
     }
 
@@ -62,11 +64,15 @@ impl IndentOptions {
         }
         indent
     }
+
+    pub fn inline_attributes(&self) -> bool {
+        self.inline_attributes
+    }
 }
 
 impl Default for IndentOptions {
     fn default() -> Self {
-        Self::new(IndentType::Spaces, 4)
+        Self::new(IndentType::Spaces, 4, false)
     }
 }
 
@@ -77,31 +83,31 @@ mod tests {
     #[test]
     fn count_indents() {
         assert_eq!(
-            IndentOptions::new(IndentType::Spaces, 4).count_indents("no indentation here!"),
+            IndentOptions::new(IndentType::Spaces, 4, false).count_indents("no indentation here!"),
             0
         );
         assert_eq!(
-            IndentOptions::new(IndentType::Spaces, 4).count_indents("    v += 2"),
+            IndentOptions::new(IndentType::Spaces, 4, false).count_indents("    v += 2"),
             1
         );
         assert_eq!(
-            IndentOptions::new(IndentType::Spaces, 4).count_indents("        v += 2"),
+            IndentOptions::new(IndentType::Spaces, 4, false).count_indents("        v += 2"),
             2
         );
         assert_eq!(
-            IndentOptions::new(IndentType::Spaces, 4).count_indents("          v += 2"),
+            IndentOptions::new(IndentType::Spaces, 4, false).count_indents("          v += 2"),
             2
         );
         assert_eq!(
-            IndentOptions::new(IndentType::Spaces, 4).count_indents("\t\tv += 2"),
+            IndentOptions::new(IndentType::Spaces, 4, false).count_indents("\t\tv += 2"),
             2
         );
         assert_eq!(
-            IndentOptions::new(IndentType::Spaces, 4).count_indents("\t\t  v += 2"),
+            IndentOptions::new(IndentType::Spaces, 4, false).count_indents("\t\t  v += 2"),
             2
         );
         assert_eq!(
-            IndentOptions::new(IndentType::Spaces, 2).count_indents("    v += 2"),
+            IndentOptions::new(IndentType::Spaces, 2, false).count_indents("    v += 2"),
             2
         );
     }

+ 16 - 7
packages/cli/src/cli/autoformat.rs

@@ -22,6 +22,10 @@ pub struct Autoformat {
     /// Input file
     #[clap(short, long)]
     pub file: Option<String>,
+
+    /// Inline attributes or not
+    #[clap(short, long)]
+    pub inline_attributes: bool,
 }
 
 impl Autoformat {
@@ -29,14 +33,14 @@ impl Autoformat {
     pub async fn autoformat(self) -> Result<()> {
         // Default to formatting the project
         if self.raw.is_none() && self.file.is_none() {
-            if let Err(e) = autoformat_project(self.check).await {
+            if let Err(e) = autoformat_project(self.check, self.inline_attributes).await {
                 eprintln!("error formatting project: {}", e);
                 exit(1);
             }
         }
 
         if let Some(raw) = self.raw {
-            let indent = indentation_for(".")?;
+            let indent = indentation_for(".", self.inline_attributes)?;
             if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) {
                 println!("{}", inner);
             } else {
@@ -51,12 +55,12 @@ impl Autoformat {
             let file_content;
             let indent;
             if file == "-" {
-                indent = indentation_for(".")?;
+                indent = indentation_for(".", self.inline_attributes)?;
                 let mut contents = String::new();
                 std::io::stdin().read_to_string(&mut contents)?;
                 file_content = Ok(contents);
             } else {
-                indent = indentation_for(".")?;
+                indent = indentation_for(".", self.inline_attributes)?;
                 file_content = fs::read_to_string(&file);
             };
 
@@ -93,7 +97,7 @@ impl Autoformat {
 /// Runs using Tokio for multithreading, so it should be really really fast
 ///
 /// Doesn't do mod-descending, so it will still try to format unreachable files. TODO.
-async fn autoformat_project(check: bool) -> Result<()> {
+async fn autoformat_project(check: bool, inline_attributes: bool) -> Result<()> {
     let crate_config = crate::CrateConfig::new(None)?;
 
     let mut files_to_format = vec![];
@@ -103,7 +107,7 @@ async fn autoformat_project(check: bool) -> Result<()> {
         return Ok(());
     }
 
-    let indent = indentation_for(&files_to_format[0])?;
+    let indent = indentation_for(&files_to_format[0], inline_attributes)?;
 
     let counts = files_to_format
         .into_iter()
@@ -164,7 +168,10 @@ async fn autoformat_project(check: bool) -> Result<()> {
     Ok(())
 }
 
-fn indentation_for(file_or_dir: impl AsRef<Path>) -> Result<IndentOptions> {
+fn indentation_for(
+    file_or_dir: impl AsRef<Path>,
+    inline_attributes: bool,
+) -> Result<IndentOptions> {
     let out = std::process::Command::new("cargo")
         .args(["fmt", "--", "--print-config", "current"])
         .arg(file_or_dir.as_ref())
@@ -204,6 +211,7 @@ fn indentation_for(file_or_dir: impl AsRef<Path>) -> Result<IndentOptions> {
             IndentType::Spaces
         },
         tab_spaces,
+        inline_attributes,
     ))
 }
 
@@ -254,6 +262,7 @@ async fn test_auto_fmt() {
         check: false,
         raw: Some(test_rsx),
         file: None,
+        inline_attributes: false,
     };
 
     fmt.autoformat().await.unwrap();

+ 3 - 0
packages/extension/src/lib.rs

@@ -15,6 +15,7 @@ pub fn format_rsx(raw: String, use_tabs: bool, indent_size: usize) -> String {
                 IndentType::Spaces
             },
             indent_size,
+            false,
         ),
     );
     block.unwrap()
@@ -32,6 +33,7 @@ pub fn format_selection(raw: String, use_tabs: bool, indent_size: usize) -> Stri
                 IndentType::Spaces
             },
             indent_size,
+            false,
         ),
     );
     block.unwrap()
@@ -67,6 +69,7 @@ pub fn format_file(contents: String, use_tabs: bool, indent_size: usize) -> Form
                 IndentType::Spaces
             },
             indent_size,
+            false,
         ),
     );
     let out = dioxus_autofmt::apply_formats(&contents, _edits.clone());