11import { rangePadding } from '../range_padding.ts' ;
22
3+ const spaceBeforeColon = 1 ;
4+
35/**
46 * This plugin ensures consistent spacing before and after the colon for type definitions.
57 */
@@ -9,13 +11,42 @@ const colonSpacing : Deno.lint.Plugin = {
911 'before-colon' : {
1012 create ( context ) : Deno . lint . LintVisitor {
1113 return {
12- TSTypeAnnotation ( node ) : void {
13- if ( [ 'FunctionDeclaration' , 'FunctionExpression' , 'TSPropertySignature' , 'Identifier' , 'PropertyDefinition' ] . includes ( node . parent . type ) ) {
14+ Identifier ( node ) : void {
15+ if ( node . typeAnnotation ) {
16+ const section : Deno . lint . Range = [ node . range [ 1 ] , node . typeAnnotation . range [ 0 ] ]
17+
18+ // Text _ from "<name>___?__:<type>"
19+ const text = context . sourceCode . getText ( node . parent ) . substring (
20+ node . range [ 1 ] - node . parent . range [ 0 ] ,
21+ node . typeAnnotation . range [ 0 ] - node . parent . range [ 0 ]
22+ )
23+
24+ if ( node . optional ) {
25+ // Index of ? from "<name>?__:<type>"
26+ const textAfterOptionalIndex = text . search ( / \? / ) + 1
1427
15- const index = context . sourceCode . getText ( node . parent ) . substring (
28+ section [ 0 ] += textAfterOptionalIndex
29+ }
30+
31+ if ( section [ 1 ] - section [ 0 ] !== spaceBeforeColon ) {
32+ context . report ( {
33+ message : `Wrong colon spacing. Expected ${ spaceBeforeColon } space before colon.` ,
34+ range : rangePadding ( section ) ,
35+ fix ( fixer ) : Deno . lint . Fix {
36+ return fixer . replaceTextRange ( section , ' ' ) ;
37+ }
38+ } ) ;
39+ }
40+ }
41+ } ,
42+ TSTypeAnnotation ( node ) : void {
43+ if ( [ 'FunctionDeclaration' , 'FunctionExpression' , 'TSPropertySignature' , 'PropertyDefinition' ] . includes ( node . parent . type ) ) {
44+ const text = context . sourceCode . getText ( node . parent ) . substring (
1645 0 ,
1746 node . range [ 0 ] - node . parent . range [ 0 ]
18- ) . search ( / (?: \) | .) * $ / ) + 1 ;
47+ ) ;
48+
49+ const index = text . search ( / . * $ / gm) + 1 ;
1950
2051 const section : Deno . lint . Range = [
2152 node . parent . range [ 0 ] + index ,
@@ -111,3 +142,7 @@ const colonSpacing : Deno.lint.Plugin = {
111142} ;
112143
113144export default colonSpacing ;
145+
146+ function _foo ( _e ? : string ) : void {
147+
148+ }
0 commit comments