or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdcore-formatting.mddocument-builders.mdfile-analysis.mdindex.mdplugin-development.mdutilities.md

file-analysis.mddocs/

0

# File Analysis and Language Support

1

2

Prettier provides comprehensive APIs for analyzing files, determining appropriate parsers, checking ignore status, and discovering supported languages and formatting options.

3

4

## File Analysis Functions

5

6

### getFileInfo

7

```javascript { .api }

8

async function getFileInfo(

9

file: string | URL,

10

options?: FileInfoOptions

11

): Promise<FileInfoResult>

12

```

13

14

Get comprehensive information about a file including inferred parser, ignore status, and configuration resolution.

15

16

**Parameters:**

17

- `file` (string | URL): File path or URL to analyze

18

- `options` (FileInfoOptions, optional): Analysis options

19

20

**Returns:** Promise resolving to FileInfoResult with file analysis data

21

22

**Types:**

23

```javascript { .api }

24

interface FileInfoOptions {

25

ignorePath?: string | URL | (string | URL)[]; // Custom ignore file paths

26

withNodeModules?: boolean; // Include node_modules (default: false)

27

plugins?: Array<string | URL | Plugin>; // Plugins for parser inference

28

resolveConfig?: boolean; // Resolve config for file (default: false)

29

}

30

31

interface FileInfoResult {

32

ignored: boolean; // Whether file should be ignored

33

inferredParser: string | null; // Inferred parser name or null

34

}

35

```

36

37

**Example:**

38

```javascript { .api }

39

// Basic file analysis

40

const fileInfo = await prettier.getFileInfo('/project/src/component.tsx');

41

// Result: { ignored: false, inferredParser: 'typescript' }

42

43

// With ignore file and config resolution

44

const fileInfo = await prettier.getFileInfo('/project/src/utils.js', {

45

ignorePath: '/project/.prettierignore',

46

resolveConfig: true,

47

withNodeModules: false

48

});

49

50

// Check multiple ignore files

51

const fileInfo = await prettier.getFileInfo('/project/src/file.js', {

52

ignorePath: ['/project/.prettierignore', '/project/.gitignore']

53

});

54

```

55

56

### getSupportInfo

57

```javascript { .api }

58

async function getSupportInfo(options?: SupportInfoOptions): Promise<SupportInfo>

59

```

60

61

Get comprehensive information about supported languages, parsers, and formatting options.

62

63

**Parameters:**

64

- `options` (SupportInfoOptions, optional): Options for support information

65

66

**Returns:** Promise resolving to SupportInfo with languages and options data

67

68

**Types:**

69

```javascript { .api }

70

interface SupportInfoOptions {

71

plugins?: Array<string | URL | Plugin>; // Include plugin-provided languages

72

showDeprecated?: boolean; // Include deprecated options (default: false)

73

}

74

75

interface SupportInfo {

76

languages: SupportLanguage[]; // Supported languages

77

options: SupportOption[]; // Available formatting options

78

}

79

```

80

81

**Example:**

82

```javascript { .api }

83

// Get all supported languages and options

84

const supportInfo = await prettier.getSupportInfo();

85

console.log(supportInfo.languages.length); // Number of supported languages

86

console.log(supportInfo.options.length); // Number of formatting options

87

88

// Include deprecated options

89

const fullInfo = await prettier.getSupportInfo({

90

showDeprecated: true

91

});

92

93

// Include plugin-provided languages

94

const pluginInfo = await prettier.getSupportInfo({

95

plugins: ['prettier-plugin-java', 'prettier-plugin-kotlin']

96

});

97

```

98

99

## Language Support Information

100

101

### SupportLanguage Interface

102

```javascript { .api }

103

interface SupportLanguage {

104

name: string; // Language display name

105

parsers: string[]; // Available parser names

106

group?: string; // Language group

107

tmScope?: string; // TextMate scope

108

aceMode?: string; // Ace editor mode

109

codemirrorMode?: string; // CodeMirror mode

110

codemirrorMimeType?: string; // CodeMirror MIME type

111

aliases?: string[]; // Language aliases

112

extensions?: string[]; // File extensions

113

filenames?: string[]; // Specific filenames

114

linguistLanguageId?: number; // GitHub Linguist ID

115

vscodeLanguageIds?: string[]; // VS Code language IDs

116

interpreters?: string[]; // Interpreter names

117

isSupported?: (options: { filepath: string }) => boolean; // Custom support check

118

}

119

```

120

121

**Example Language Objects:**

122

```javascript { .api }

123

// JavaScript language support

124

{

125

"name": "JavaScript",

126

"parsers": ["babel", "acorn", "espree"],

127

"group": "JavaScript",

128

"tmScope": "source.js",

129

"aceMode": "javascript",

130

"codemirrorMode": "javascript",

131

"codemirrorMimeType": "text/javascript",

132

"extensions": [".js", ".jsx", ".mjs", ".cjs"],

133

"filenames": [],

134

"linguistLanguageId": 183,

135

"vscodeLanguageIds": ["javascript", "javascriptreact"]

136

}

137

138

// TypeScript language support

139

{

140

"name": "TypeScript",

141

"parsers": ["typescript", "babel-ts"],

142

"group": "JavaScript",

143

"extensions": [".ts", ".tsx", ".cts", ".mts"],

144

"vscodeLanguageIds": ["typescript", "typescriptreact"]

145

}

146

```

147

148

### Built-in Language Support

149

150

**JavaScript Family:**

151

```javascript { .api }

152

const jsLanguages = supportInfo.languages.filter(lang =>

153

lang.group === 'JavaScript' || lang.parsers.includes('babel')

154

);

155

// Includes: JavaScript, TypeScript, JSX, Flow

156

```

157

158

**CSS Family:**

159

```javascript { .api }

160

const cssLanguages = supportInfo.languages.filter(lang =>

161

lang.parsers.some(p => ['css', 'scss', 'less'].includes(p))

162

);

163

// Includes: CSS, SCSS, Less

164

```

165

166

**Markup Languages:**

167

```javascript { .api }

168

const markupLanguages = supportInfo.languages.filter(lang =>

169

['HTML', 'Vue', 'Angular'].includes(lang.name)

170

);

171

// Includes: HTML, Vue, Angular templates, LWC

172

```

173

174

**Data Formats:**

175

```javascript { .api }

176

const dataLanguages = supportInfo.languages.filter(lang =>

177

lang.parsers.some(p => ['json', 'json5', 'yaml'].includes(p))

178

);

179

// Includes: JSON, JSON5, JSONC, YAML

180

```

181

182

## Parser Inference

183

184

### Automatic Parser Detection

185

```javascript { .api }

186

// Parser inferred from file extension

187

const info1 = await prettier.getFileInfo('component.tsx');

188

// Result: { inferredParser: 'typescript' }

189

190

const info2 = await prettier.getFileInfo('styles.scss');

191

// Result: { inferredParser: 'scss' }

192

193

const info3 = await prettier.getFileInfo('data.json');

194

// Result: { inferredParser: 'json' }

195

```

196

197

### Custom Parser Mapping

198

```javascript { .api }

199

// Use plugins to extend parser inference

200

import javaPlugin from 'prettier-plugin-java';

201

202

const info = await prettier.getFileInfo('App.java', {

203

plugins: [javaPlugin]

204

});

205

// Result: { inferredParser: 'java' } (if plugin provides java parser)

206

```

207

208

### Manual Parser Override

209

```javascript { .api }

210

// Override inferred parser

211

const formatted = await prettier.format(code, {

212

parser: 'babel', // Force babel parser regardless of file extension

213

filepath: 'file.unknown'

214

});

215

```

216

217

## Ignore File Processing

218

219

### Default Ignore Patterns

220

Prettier automatically respects these ignore files:

221

- `.prettierignore`

222

- `.gitignore` (when no .prettierignore exists)

223

224

### Custom Ignore Files

225

```javascript { .api }

226

// Single custom ignore file

227

const info = await prettier.getFileInfo('/project/src/file.js', {

228

ignorePath: '/project/custom.ignore'

229

});

230

231

// Multiple ignore files (precedence order)

232

const info = await prettier.getFileInfo('/project/src/file.js', {

233

ignorePath: [

234

'/project/.prettierignore',

235

'/project/.gitignore',

236

'/project/custom.ignore'

237

]

238

});

239

```

240

241

### Ignore File Format

242

```gitignore

243

# .prettierignore - supports .gitignore syntax

244

node_modules/

245

dist/

246

build/

247

*.min.js

248

*.bundle.js

249

coverage/

250

.next/

251

.nuxt/

252

253

# Negative patterns (re-include)

254

!src/important.min.js

255

256

# Comments and blank lines are ignored

257

```

258

259

### Node Modules Handling

260

```javascript { .api }

261

// By default, files in node_modules are ignored

262

const info1 = await prettier.getFileInfo('node_modules/package/file.js');

263

// Result: { ignored: true, inferredParser: 'babel' }

264

265

// Include node_modules files

266

const info2 = await prettier.getFileInfo('node_modules/package/file.js', {

267

withNodeModules: true

268

});

269

// Result: { ignored: false, inferredParser: 'babel' }

270

```

271

272

## Formatting Options Information

273

274

### SupportOption Interface

275

```javascript { .api }

276

interface SupportOption {

277

name: string; // Option name

278

category: string; // Option category

279

type: string; // Option type (int, string, boolean, choice, path)

280

description?: string; // Option description

281

deprecated?: boolean | string; // Deprecation status

282

default?: any; // Default value

283

range?: { // For int type

284

start: number;

285

end: number;

286

step: number;

287

};

288

choices?: Array<{ // For choice type

289

value: any;

290

description: string;

291

}>;

292

}

293

```

294

295

### Querying Available Options

296

```javascript { .api }

297

const supportInfo = await prettier.getSupportInfo();

298

299

// Find specific option

300

const semiOption = supportInfo.options.find(opt => opt.name === 'semi');

301

console.log(semiOption);

302

// Result: { name: 'semi', type: 'boolean', default: true, ... }

303

304

// Get options by category

305

const formatOptions = supportInfo.options.filter(opt =>

306

opt.category === 'Format'

307

);

308

309

// Get choice options

310

const choiceOptions = supportInfo.options.filter(opt =>

311

opt.type === 'choice'

312

);

313

```

314

315

## Usage Patterns

316

317

### File Type Detection

318

```javascript { .api }

319

async function detectFileType(filepath) {

320

const fileInfo = await prettier.getFileInfo(filepath);

321

322

if (fileInfo.ignored) {

323

return 'ignored';

324

}

325

326

if (!fileInfo.inferredParser) {

327

return 'unsupported';

328

}

329

330

const supportInfo = await prettier.getSupportInfo();

331

const language = supportInfo.languages.find(lang =>

332

lang.parsers.includes(fileInfo.inferredParser)

333

);

334

335

return language ? language.name : 'unknown';

336

}

337

```

338

339

### Bulk File Analysis

340

```javascript { .api }

341

async function analyzeProjectFiles(pattern) {

342

const files = await glob(pattern);

343

const results = [];

344

345

for (const file of files) {

346

const info = await prettier.getFileInfo(file, {

347

resolveConfig: true

348

});

349

350

results.push({

351

file,

352

ignored: info.ignored,

353

parser: info.inferredParser,

354

supported: info.inferredParser !== null

355

});

356

}

357

358

return results;

359

}

360

```

361

362

### Plugin Integration

363

```javascript { .api }

364

async function getSupportedExtensions(plugins = []) {

365

const supportInfo = await prettier.getSupportInfo({ plugins });

366

367

const extensions = new Set();

368

supportInfo.languages.forEach(lang => {

369

if (lang.extensions) {

370

lang.extensions.forEach(ext => extensions.add(ext));

371

}

372

});

373

374

return Array.from(extensions).sort();

375

}

376

377

// Usage

378

const extensions = await getSupportedExtensions([

379

'prettier-plugin-java',

380

'prettier-plugin-kotlin'

381

]);

382

console.log(extensions); // ['.java', '.kt', '.js', '.ts', ...]

383

```

384

385

### Configuration Validation

386

```javascript { .api }

387

async function validateConfig(config) {

388

const supportInfo = await prettier.getSupportInfo({ showDeprecated: true });

389

const errors = [];

390

391

for (const [key, value] of Object.entries(config)) {

392

const option = supportInfo.options.find(opt => opt.name === key);

393

394

if (!option) {

395

errors.push(`Unknown option: ${key}`);

396

continue;

397

}

398

399

if (option.deprecated) {

400

errors.push(`Deprecated option: ${key}`);

401

}

402

403

// Validate option value based on type

404

if (option.type === 'choice' && option.choices) {

405

const validValues = option.choices.map(c => c.value);

406

if (!validValues.includes(value)) {

407

errors.push(`Invalid value for ${key}: ${value}`);

408

}

409

}

410

}

411

412

return errors;

413

}

414

```