@@ -40,13 +40,23 @@ public String format(String raw) {
40
40
int firstImportLine = 0 ;
41
41
int lastImportLine = 0 ;
42
42
int line = 0 ;
43
+ boolean isMultiLineComment = false ;
43
44
List <String > imports = new ArrayList <>();
44
45
while (scanner .hasNext ()) {
45
46
line ++;
46
47
String next = scanner .nextLine ();
47
48
if (next == null ) {
48
49
break ;
49
50
}
51
+ //Since we have no AST, we only consider the most common use cases.
52
+ isMultiLineComment |= next .contains ("/*" );
53
+ if (isMultiLineComment && next .contains ("*/" )) {
54
+ isMultiLineComment = false ;
55
+ if (!next .contains ("/*" )) {
56
+ continue ;
57
+ }
58
+ }
59
+
50
60
if (next .startsWith ("import " )) {
51
61
int i = next .indexOf ("." );
52
62
if (isNotValidImport (i )) {
@@ -59,17 +69,28 @@ public String format(String raw) {
59
69
int endIndex = next .indexOf (";" );
60
70
61
71
String imprt = next .substring (START_INDEX_OF_IMPORTS_PACKAGE_DECLARATION , endIndex != -1 ? endIndex : next .length ());
62
- if (!imports .contains (imprt )) {
72
+ if (!isMultiLineComment && ! imports .contains (imprt )) {
63
73
imports .add (imprt );
64
74
}
65
75
}
76
+ if (!isMultiLineComment && isBeginningOfScope (next )) {
77
+ break ; //Don't dare to touch lines after a scope started
78
+ }
66
79
}
67
80
scanner .close ();
68
81
69
82
List <String > sortedImports = ImportSorterImpl .sort (imports , importsOrder );
70
83
return applyImportsToDocument (raw , firstImportLine , lastImportLine , sortedImports );
71
84
}
72
85
86
+ private static boolean isBeginningOfScope (String line ) {
87
+ int scope = line .indexOf ("{" );
88
+ if (0 <= scope ) {
89
+ return !line .substring (0 , scope ).contains ("//" );
90
+ }
91
+ return false ;
92
+ }
93
+
73
94
private static String applyImportsToDocument (final String document , int firstImportLine , int lastImportLine , List <String > strings ) {
74
95
boolean importsAlreadyAppended = false ;
75
96
Scanner scanner = new Scanner (document );
0 commit comments