1- import { dirname } from 'node:path' ;
1+ import { dirname , relative } from 'node:path' ;
2+ import micromatch from 'micromatch' ;
3+ import type { Options as PrettierOptions } from 'prettier' ;
24import type { FmtConfig , FmtConfigDefinition , ResolvedFmtConfig } from './types.ts' ;
35
46type ResolveFmtConfigOptions = {
@@ -19,6 +21,47 @@ const normalizeFmtConfig = (config: FmtConfig | undefined, rootPath: string): Re
1921 } ;
2022} ;
2123
24+ const pathMatchesGlobs = (
25+ filePath : string ,
26+ patterns : string | string [ ] ,
27+ excludedPatterns ?: string | string [ ] ,
28+ ) : boolean => {
29+ const patternList = Array . isArray ( patterns ) ? patterns : [ patterns ] ;
30+ const withSlashes = patternList . filter ( ( pattern ) => pattern . includes ( '/' ) ) ;
31+ const withoutSlashes = patternList . filter ( ( pattern ) => ! pattern . includes ( '/' ) ) ;
32+
33+ return (
34+ micromatch . isMatch ( filePath , withoutSlashes , {
35+ ignore : excludedPatterns ,
36+ basename : true ,
37+ dot : true ,
38+ } ) ||
39+ micromatch . isMatch ( filePath , withSlashes , {
40+ ignore : excludedPatterns ,
41+ basename : false ,
42+ dot : true ,
43+ } )
44+ ) ;
45+ } ;
46+
47+ /** Applies matching overrides to the shared formatter options. */
48+ const resolveFmtOptions = ( filePath : string , config : ResolvedFmtConfig ) : PrettierOptions => {
49+ if ( config . overrides . length === 0 ) {
50+ return config . baseOptions ;
51+ }
52+
53+ const options = { ...config . baseOptions } ;
54+ const relativeFilePath = relative ( config . rootPath , filePath ) ;
55+
56+ for ( const override of config . overrides ) {
57+ if ( pathMatchesGlobs ( relativeFilePath , override . files , override . excludeFiles ) ) {
58+ Object . assign ( options , override . options ) ;
59+ }
60+ }
61+
62+ return options ;
63+ } ;
64+
2265/** Resolves a formatter config definition and its project root. */
2366const resolveFmtConfig = async ( {
2467 definition,
@@ -31,4 +74,4 @@ const resolveFmtConfig = async ({
3174 return normalizeFmtConfig ( config , rootPath ) ;
3275} ;
3376
34- export { normalizeFmtConfig , resolveFmtConfig } ;
77+ export { normalizeFmtConfig , resolveFmtConfig , resolveFmtOptions } ;
0 commit comments