Skip to content

Infer file type for CLI Javascript files #5122

@haggholm

Description

@haggholm

Environments:

  • Prettier Version: 1.14.2
  • Running Prettier via: CLI
  • Runtime: Node.js v10
  • Operating System: Linux

Steps to reproduce:

prettier bin/clean

where bin/clean is a Javascript CLI script.

#!/usr/bin/env node
'use strict';

// Do stuff

Actual behavior:

[error] No parser could be inferred for file: bin/clean

Suggested behavior:

I’m guessing that Prettier infers file types from file extension. However, CLI scripts often aren’t given any extensions. It might be fairly easy to infer the type by reading the first line of such files and checking if it’s a common hashbang string, e.g. something like

if (/^#![^\s]*\/node(js)?\b/.test(firstLine)) {
  // ... use a JS parser ...
}

Alternatively, if this is deemed unsafe, perhaps (somewhat less conveniently) the existing pragma could be augmented to accept an optional parameter indicating file type.

#!/usr/bin/env node
/* @prettier:js */
'use strict';

// Do stuff

Not as convenient, and requires scanning more of the file than just the hashbang line to infer type, but if the former proposal is unsafe in some edge case I’m not thinking of (sufficiently common not to be relegated to .prettierignore), it would at last provide a way to opt in.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:apiIssues with Prettier's Application Programming Interfacelocked-due-to-inactivityPlease open a new issue and fill out the template instead of commenting.status:has prIssues with an accompanying pull request. These issues will probably be fixed soon!

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions