1
1
use ruff_formatter:: PrintedRange ;
2
2
use ruff_python_ast:: PySourceType ;
3
- use ruff_python_formatter:: format_module_source;
3
+ use ruff_python_formatter:: { format_module_source, FormatModuleError } ;
4
4
use ruff_text_size:: TextRange ;
5
5
use ruff_workspace:: FormatterSettings ;
6
6
@@ -10,23 +10,49 @@ pub(crate) fn format(
10
10
document : & TextDocument ,
11
11
source_type : PySourceType ,
12
12
formatter_settings : & FormatterSettings ,
13
- ) -> crate :: Result < String > {
13
+ ) -> crate :: Result < Option < String > > {
14
14
let format_options = formatter_settings. to_format_options ( source_type, document. contents ( ) ) ;
15
- let formatted = format_module_source ( document. contents ( ) , format_options) ?;
16
- Ok ( formatted. into_code ( ) )
15
+ match format_module_source ( document. contents ( ) , format_options) {
16
+ Ok ( formatted) => {
17
+ let formatted = formatted. into_code ( ) ;
18
+ if formatted == document. contents ( ) {
19
+ Ok ( None )
20
+ } else {
21
+ Ok ( Some ( formatted) )
22
+ }
23
+ }
24
+ // Special case - syntax/parse errors are handled here instead of
25
+ // being propagated as visible server errors.
26
+ Err ( FormatModuleError :: ParseError ( error) ) => {
27
+ tracing:: warn!( "Unable to format document: {error}" ) ;
28
+ Ok ( None )
29
+ }
30
+ Err ( err) => Err ( err. into ( ) ) ,
31
+ }
17
32
}
18
33
19
34
pub ( crate ) fn format_range (
20
35
document : & TextDocument ,
21
36
source_type : PySourceType ,
22
37
formatter_settings : & FormatterSettings ,
23
38
range : TextRange ,
24
- ) -> crate :: Result < PrintedRange > {
39
+ ) -> crate :: Result < Option < PrintedRange > > {
25
40
let format_options = formatter_settings. to_format_options ( source_type, document. contents ( ) ) ;
26
41
27
- Ok ( ruff_python_formatter:: format_range (
28
- document. contents ( ) ,
29
- range,
30
- format_options,
31
- ) ?)
42
+ match ruff_python_formatter:: format_range ( document. contents ( ) , range, format_options) {
43
+ Ok ( formatted) => {
44
+ if formatted. as_code ( ) == document. contents ( ) {
45
+ Ok ( None )
46
+ } else {
47
+ Ok ( Some ( formatted) )
48
+ }
49
+ }
50
+ // Special case - syntax/parse errors are handled here instead of
51
+ // being propagated as visible server errors.
52
+ Err ( FormatModuleError :: ParseError ( error) ) => {
53
+ tracing:: warn!( "Unable to format document range: {error}" ) ;
54
+ Ok ( None )
55
+ }
56
+ Err ( err) => Err ( err. into ( ) ) ,
57
+ }
32
58
}
0 commit comments