Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format import statements #5493

Merged
merged 4 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from a import aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa
from a import aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa, aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa
from a import aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa as dfgsdfgsd, aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa as sdkjflsdjlahlfd
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from a import aksjdhflsakhdflkjsadlfajkslhf
from a import (
aksjdhflsakhdflkjsadlfajkslhf,
)
from a import (
aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa,
)
from a import (
aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa,
aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa,
)
from a import (
aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa as dfgsdfgsd,
aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa as sdkjflsdjlahlfd,
)
from aksjdhflsakhdflkjsadlfajkslhfdkjsaldajlahflashdfljahlfksajlhfajfjfsaahflakjslhdfkjalhdskjfa import *
16 changes: 13 additions & 3 deletions crates/ruff_python_formatter/src/other/alias.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
use crate::{not_yet_implemented, FormatNodeRule, PyFormatter};
use ruff_formatter::{write, Buffer, FormatResult};
use crate::{AsFormat, FormatNodeRule, PyFormatter};
use ruff_formatter::prelude::{space, text};
use ruff_formatter::{write, Buffer, Format, FormatResult};
use rustpython_parser::ast::Alias;

#[derive(Default)]
pub struct FormatAlias;

impl FormatNodeRule<Alias> for FormatAlias {
fn fmt_fields(&self, item: &Alias, f: &mut PyFormatter) -> FormatResult<()> {
write!(f, [not_yet_implemented(item)])
let Alias {
range: _,
name,
asname,
} = item;
name.format().fmt(f)?;
if let Some(asname) = asname {
write!(f, [space(), text("as"), space(), asname.format()])?;
}
Ok(())
}
}
11 changes: 9 additions & 2 deletions crates/ruff_python_formatter/src/statement/stmt_import.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{not_yet_implemented, FormatNodeRule, PyFormatter};
use crate::{FormatNodeRule, FormattedIterExt, PyFormatter};
use ruff_formatter::prelude::{format_args, format_with, space, text};
use ruff_formatter::{write, Buffer, FormatResult};
use rustpython_parser::ast::StmtImport;

Expand All @@ -7,6 +8,12 @@ pub struct FormatStmtImport;

impl FormatNodeRule<StmtImport> for FormatStmtImport {
fn fmt_fields(&self, item: &StmtImport, f: &mut PyFormatter) -> FormatResult<()> {
write!(f, [not_yet_implemented(item)])
let StmtImport { names, range: _ } = item;
let names = format_with(|f| {
f.join_with(&format_args![text(","), space()])
.entries(names.iter().formatted())
.finish()
});
write!(f, [text("import"), space(), names])
}
}
43 changes: 40 additions & 3 deletions crates/ruff_python_formatter/src/statement/stmt_import_from.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,49 @@
use crate::{not_yet_implemented, FormatNodeRule, PyFormatter};
use ruff_formatter::{write, Buffer, FormatResult};
use crate::builders::{optional_parentheses, PyFormatterExtensions};
use crate::{AsFormat, FormatNodeRule, PyFormatter};
use ruff_formatter::prelude::{dynamic_text, format_with, space, text};
use ruff_formatter::{write, Buffer, Format, FormatResult};
use rustpython_parser::ast::StmtImportFrom;
use std::iter;

#[derive(Default)]
pub struct FormatStmtImportFrom;

impl FormatNodeRule<StmtImportFrom> for FormatStmtImportFrom {
fn fmt_fields(&self, item: &StmtImportFrom, f: &mut PyFormatter) -> FormatResult<()> {
write!(f, [not_yet_implemented(item)])
let StmtImportFrom {
module,
names,
range: _,
level,
} = item;

let level_str = level
.map(|level| ".".repeat(level.to_usize()))
.unwrap_or(String::default());

write!(
f,
[
text("from"),
space(),
dynamic_text(&level_str, None),
module.as_ref().map(AsFormat::format),
Copy link
Member Author

@konstin konstin Jul 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i was surprised there wasn't a blanket Option<T>: T: AsFormat impl for .format()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I ran into issues when I tried adding it last time because Rust doesn't know that T doesn't implement Format and AsFormat at the same time

space(),
text("import"),
space(),
]
)?;
if let [name] = names.as_slice() {
// star can't be surrounded by parentheses
if name.name.as_str() == "*" {
return text("*").fmt(f);
}
}
let names = format_with(|f| {
f.join_comma_separated()
.entries(names.iter().map(|name| (name, name.format())))
.finish()
});
optional_parentheses(&names).fmt(f)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,20 @@ def eggs() -> Union[str, int]: ...
--- Black
+++ Ruff
@@ -1,32 +1,58 @@
-from typing import Union
+NOT_YET_IMPLEMENTED_StmtImportFrom
+
from typing import Union

+
@bird
-def zoo(): ...
+def zoo():
+ ...
+
+
+class A:
+ ...

-class A: ...

+class A:
+ ...
+
+
@bar
class B:
- def BMethod(self) -> None: ...
Expand Down Expand Up @@ -94,14 +93,14 @@ def eggs() -> Union[str, int]: ...
+
+class F(A, C):
+ ...
+
+
+def spam() -> None:
+ ...
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to this PR: interesting, black sometimes keeps the single statement formatting


-class F(A, C): ...

-def spam() -> None: ...
+def spam() -> None:
+ ...
+
+
@overload
-def spam(arg: str) -> str: ...
+def spam(arg: str) -> str:
Expand All @@ -120,7 +119,7 @@ def eggs() -> Union[str, int]: ...
## Ruff Output

```py
NOT_YET_IMPLEMENTED_StmtImportFrom
from typing import Union


@bird
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ match bar1:
--- Black
+++ Ruff
@@ -1,119 +1,43 @@
-import match
+NOT_YET_IMPLEMENTED_StmtImport
import match

-match something:
- case [a as b]:
Expand Down Expand Up @@ -208,10 +207,11 @@ match bar1:
- ),
- ):
- pass
-
+NOT_YET_IMPLEMENTED_StmtMatch

- case [a as match]:
- pass
-
- case case:
- pass
+NOT_YET_IMPLEMENTED_StmtMatch
Expand All @@ -220,8 +220,9 @@ match bar1:
-match match:
- case case:
- pass
-
-
+NOT_YET_IMPLEMENTED_StmtMatch


-match a, *b(), c:
- case d, *f, g:
- pass
Expand All @@ -236,30 +237,28 @@ match bar1:
- pass
- case {"maybe": something(complicated as this) as that}:
- pass
-
+NOT_YET_IMPLEMENTED_StmtMatch


-match something:
- case 1 as a:
- pass
+NOT_YET_IMPLEMENTED_StmtMatch

- case 2 as b, 3 as c:
- pass
+NOT_YET_IMPLEMENTED_StmtMatch

- case 4 as d, (5 as e), (6 | 7 as g), *h:
- pass
+NOT_YET_IMPLEMENTED_StmtMatch


-
-match bar1:
- case Foo(aa=Callable() as aa, bb=int()):
- print(bar1.aa, bar1.bb)
- case _:
- print("no match", "\n")
+NOT_YET_IMPLEMENTED_StmtMatch


-
-
-match bar1:
- case Foo(
- normal=x, perhaps=[list, {"x": d, "y": 1.0}] as y, otherwise=something, q=t as u
Expand All @@ -271,7 +270,7 @@ match bar1:
## Ruff Output

```py
NOT_YET_IMPLEMENTED_StmtImport
import match

NOT_YET_IMPLEMENTED_StmtMatch

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,31 +83,9 @@ if True:
```diff
--- Black
+++ Ruff
@@ -1,40 +1,22 @@
-import core, time, a
+NOT_YET_IMPLEMENTED_StmtImport

-from . import A, B, C
+NOT_YET_IMPLEMENTED_StmtImportFrom

# keeps existing trailing comma
-from foo import (
- bar,
-)
+NOT_YET_IMPLEMENTED_StmtImportFrom

# also keeps existing structure
-from foo import (
- baz,
- qux,
-)
+NOT_YET_IMPLEMENTED_StmtImportFrom

# `as` works as well
-from foo import (
- xyzzy as magic,
-)
+NOT_YET_IMPLEMENTED_StmtImportFrom
@@ -18,23 +18,12 @@
xyzzy as magic,
)

-a = {
- 1,
Expand All @@ -132,7 +110,7 @@ if True:
nested_no_trailing_comma = {(1, 2, 3), (4, 5, 6)}
nested_long_lines = [
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
@@ -52,10 +34,7 @@
@@ -52,10 +41,7 @@
y = {
"oneple": (1,),
}
Expand All @@ -149,18 +127,25 @@ if True:
## Ruff Output

```py
NOT_YET_IMPLEMENTED_StmtImport
import core, time, a

NOT_YET_IMPLEMENTED_StmtImportFrom
from . import A, B, C

# keeps existing trailing comma
NOT_YET_IMPLEMENTED_StmtImportFrom
from foo import (
bar,
)

# also keeps existing structure
NOT_YET_IMPLEMENTED_StmtImportFrom
from foo import (
baz,
qux,
)

# `as` works as well
NOT_YET_IMPLEMENTED_StmtImportFrom
from foo import (
xyzzy as magic,
)

a = {1, 2, 3}
b = {1, 2, 3}
Expand Down
Loading