Skip to content

[RFC] Editor Integration #918

Closed

Description

@vjeux

Editors are the main place where we want people to use prettier, in order for it to be a great experience it should have the following properties:

  • Use the version of prettier that the project uses. If not, fall back to an arbitrary version.
  • When saving, use the options specified by the project, otherwise fall back to an arbitrary configuration.
  • When reading a file that is inside of a project using prettier, and if an option is enabled, reformat the code using the local user preferences.

Proposal

Allow people adding their configuration options inside of prettier in package.json:

{
  ...

  "prettier": {
    "bracketSpacing": false,
    "trailingComma": "all"
  }
}

How to find a package version of prettier?

Given a file with a path a/b/c/d/e.js, we want to crawl up the tree up until we find a file package.json.

It should check in this order:

  • a/b/c/d/package.json
  • a/b/c/package.json
  • a/b/package.json
  • a/package.json
  • package.json

If it doesn't find one, then the file isn't inside of a prettier repo.

If it finds one in a/b/package.json, then look at the file a/b/node_modules/.bin/prettier. If it finds one, then use this prettier binary.

How to deal with caching?

This is a fair amount of io to be done for each invocation. If you want to add caching, you want to be careful, here are the things to watch out for:

  • a/b/package.json is updated
  • a/b/node_modules/.bin/prettier is updated
  • a/b/c/package.json or a/b/c/d/package.json is created

How to find the configuration associated to a package version of prettier?

Given that a package version of prettier is always in a/b/node_modules/.bin/prettier and the package configuration is always in a/b/package.json, we can inside of prettier check if ../../package.json exists, and if it does read it and use the prettier key.

If prettier is being used as a CLI with require('prettier'), I'm not sure how to find it and if it's even a good idea to.

How do you resolve conflicting rules?

I suggest that we merge rules one by one and the order they are loaded in/override each other is:

  • First load package.json rules
  • Then load CLI arguments which override the one above

For example,

// package.json
{ "prettier": {"trailingComma": "all", "singleQuote": true} }
prettier --trailing-comma es5 --parser flow

would result in

{singleQuote: true, trailingComma: 'es5', parser: 'flow'}

How to make it fast?

Because all the integrations now have to use the cli and can no longer just use the local require version, we're going to pay js/node startup time on every single invocation.

I recommend adding an option to prettier bin --json-rpc. With this, you can open the prettier process once and send formatting commands through stdin/stdout without having to restart it every time.

A sample connection looks like this:

-->
Content Length: xxx
{"jsonrpc": "2.0", "method": "format", "params": ["abc", {"trailingComma": "es6"}], "id": 1}

<--
Content Length: xxx
{"jsonrpc": "2.0", "result": {"formatted": "abc;", "error": null}, "id": 1}

Conclusion

Let me know what you think :)

Activity

  1. added
    status:needs discussion
    on Mar 6, 2017
  2. vjeux commented on Mar 6, 2017

    @vjeux
    ContributorAuthor
  3. robwise commented on Mar 6, 2017

    @robwise

    Wow, great work writing all of this up.

    How to find a package version of prettier?

    This is something a number of users are requesting on prettier-atom. We haven't implemented yet, but what you're describing sounds about right to me.

    If prettier is being used as a CLI with require('prettier'), I'm not sure how to find it and if it's even a good idea to.

    I believe @kentcdodds solved this issue in a similar case where he needed to find the ESlint configuration for prettier-eslint. He solved it by optionally passing the filepath of the file as an option. Then the tool knows where to start recursively checking from.

    I suggest that we merge rules one by one and the order they are loaded in/override each other is:

    First load package.json rules
    Then load CLI arguments which override the one above

    I vote for this also.

    How to deal with caching?

    This is definitely something we will need to watch out for.

    How to make it fast?

    Have we determined that performance is a problem? The jsonrpc thing sounds like a good idea when doing multiple files at once, but inside of editors, I assume the use cases are just to do the single file or even only part of the file.

  4. kentcdodds commented on Mar 6, 2017

    @kentcdodds
    Member

    How to find a package version of prettier?

    Great way to do that is with find-up

  5. lydell commented on Mar 6, 2017

    @lydell
    Member

    There's also read-pkg-up.

  6. SimenB commented on Mar 6, 2017

    @SimenB
    Contributor
  7. vjeux commented on Mar 8, 2017

    @vjeux
    ContributorAuthor

    Previous discussions on the prettier repo: #753 #735

  8. millermedeiros commented on Mar 9, 2017

    @millermedeiros

    One thing I added o esformatter was the concept of a root config to avoid merging other settings and to speed up the lookup a little bit (as soon as it finds a config with root: true don't need to keep looking up the file tree).

    This is basically how I decided to implement it: millermedeiros/esformatter#76 (comment) - cli options always take precedence (assumes user is overriding the defaults on purpose)

    The whole user config logic is handled by the getRc method, I expose it so that plugins and other consumers can reuse it (see: source)

    The package version logic I do inside the bin file using the resolve module - it starts looking for the locally installed module based on the config file (if user provides one) or the cwd.

    jsonrpc is a good idea (was going to do the same for esformatter but never found the time), I would implement it as a dedicated bin tho.

  9. bakkot commented on Mar 25, 2017

    @bakkot
    Collaborator

    Most JS I write does not live in an npm package, so this would do nothing for me.

    I know that's kind of unusual, but I thought it worth mentioning - package.json is an npm thing, not a JS thing.

  10. gustavnikolaj commented on Mar 28, 2017

    @gustavnikolaj

    Instead of implementing a JSON RPC protocol through stdin/stdout you could also just create a programmatic API like the one eslint has.

    var eslint = require('eslint')
    eslint.lintText(text, options, callback);

    Both eslint and standard-engine-based linters implement similar APIs. I wrote a plugin for integrating standard-engine linters into Atom which use this API to implement a worker to avoid the node.js startup cost on each lint.

    It allows for the same separation as the stdin/stdout protocol, but is more flexible in my opinion, and probably a bit easier to do as well :-) It also won't rule out the stdin/stdout based solution, but rather be the first step to implement it.

  11. SimenB commented on Mar 28, 2017

    @SimenB
    Contributor

    @gustavnikolaj that's only useful for editors written in JS (so atom and code?), not for emacs, vim, intellij, webstorm, sublime etc.

    And prettier already has a programatic API, so those integrations can be done today

  12. gustavnikolaj commented on Mar 28, 2017

    @gustavnikolaj

    @SimenB Oh sorry, I should have checked whether it was already there.

  13. vjeux commented on Mar 28, 2017

    @vjeux
    ContributorAuthor

    We also need it for atom. It has chrome flags enabled that prevent doing eval(), so you can't just require a js file found in package.json. What the current atom editor plugin does is to use a specific version, which isn't ideal since you may have multiple projects using different versions.

    So the workaround is to shell out and use stdio

  14. gustavnikolaj commented on Mar 28, 2017

    @gustavnikolaj

    @vjeux child_process.fork can be used from within atom to sidestep the CSP that prevents use of eval. Had to do the same thing to be able to use the projects linter instead of bundling them in the plugin.

  15. kentcdodds commented on Mar 28, 2017

    @kentcdodds
    Member

    Yeah, most atom packages that need to do this use loophole. In fact, prettier-atom does this :)

  16. 22 remaining items

  17. AxelTheGerman commented on May 11, 2017

    @AxelTheGerman

    @danawoodman would love to see exactly that!

  18. chrisui commented on May 25, 2017

    @chrisui

    Been mentioned already but I would push for using something such as cosmiconfig which implements the config formats commonly seen across the ecosystem. Imo it gives the most predictable way for writing and consuming configuration for tools in the js world.

    From the README:

    Find and load a configuration object from

    • a package.json property (anywhere down the file tree)
    • a JSON or YAML "rc file" (anywhere down the file tree)
    • a .config.js CommonJS module (anywhere down the file tree)
    • a CLI --config argument

    For example, if your module's name is "prettier," cosmiconfig will search out configuration in the following places:

    • a "prettier" property in package.json (anywhere down the file tree)
    • a .prettierrc file in JSON or YAML format (anywhere down the file tree)
    • a prettier.config.js file exporting a JS object (anywhere down the file tree)
    • a CLI --config argument
  19. chrisui commented on Jun 13, 2017

    @chrisui

    Is there anything we can do to help move configuration/editor support along?

    We seem to be getting in a bit of a muddle moving around projects with tools using different prettier versions (global vs project vs tool/editor vs ci) and it's causing us some degree of pain.

  20. chrisui commented on Jun 13, 2017

    @chrisui

    I reckon we should be able to specify the prettier "version" in the config (wherever it lives) so that if someone attempts to use prettier with the wrong version we can fail loudly. This is the same as happens with using the incorrect version of flow to what is specified in configuration.

    Ie.

    {
      "version": "1.2.2"
    }
    
  21. chrisblossom commented on Jun 14, 2017

    @chrisblossom
    Contributor

    I think it is fairly important to be able to flag subdirectories with a new prettier config/overrides because not all JS features are supported per directory, specifically --trailing-comma all. The current Node LTS's (4 & 6) do not support this feature. If using it, at least part of your build chain will need an exception of some sort.

    IMO don't reinvent the wheel...copy how eslintrc.js works. Nested .eslintrc.js inherit from configs further down the line but overwrite any settings.

  22. vjeux commented on Jun 14, 2017

    @vjeux
    ContributorAuthor

    Fyi, node 8 that was just released supports trailing comma!!

  23. chrisblossom commented on Jun 14, 2017

    @chrisblossom
    Contributor

    @vjeux Yeah it will be nice when it is LTS in October! nodejs/LTS#lts-schedule has Node 4 supported until April 2018 and Node 6 until April 2019.

    Because Node's LTS, I don't think Prettier should adopt a configuration style that makes it more difficult to use until April 2019. I think the configuration decisions should follow the Node LTS schedule.

    Here is my current configuration...
    .prettierignore

    .cache
    .idea
    .vscode
    node_modules
    build
    static
    flow-typed
    flow
    npm-packages-offline-cache
    tools

    package.json

        "prettier": "find . -name \"*.js\" | grep -v -f .prettierignore | xargs prettier --tab-width 4 --single-quote --trailing-comma all --write",
        "prettier:tools": "find ./tools -name \"*.js\" | xargs prettier --tab-width 4 --single-quote --trailing-comma es5 --write",
        "precommit": "lint-staged"
      },
      "lint-staged": {
        "./*.js": [
          "prettier --tab-width 4 --single-quote --trailing-comma es5 --write",
          "git add"
        ],
        "tools/**/*.js": [
          "prettier --tab-width 4 --single-quote --trailing-comma es5 --write",
          "git add"
        ],
        "src/**/*.js": [
          "prettier --tab-width 4 --single-quote --trailing-comma all --write",
          "git add"
        ],
        "server/**/*.js": [
          "prettier --tab-width 4 --single-quote --trailing-comma all --write",
          "git add"
        ]
      },

    Because of the "no configuration" philosophy, there ends up being more hacks/workarounds getting Prettier to work with a modern build setup. Not to mention the editor's plugin has no idea what config to use. End up having to run yarn run prettier:tools after saving any file in the tools directory if I don't commit right away otherwise the trailing comma will error node out.

    If anyone has any suggestion on how to better handle this I'd love to hear how.

  24. josephfrazier commented on Jun 14, 2017

    @josephfrazier
    Collaborator

    @chrisblossom, since you're already using eslint, you could use eslint-plugin-prettier and eslint-config-prettier, add your prettier configuration to .eslintrc.jsfiles, then have lint-staged run eslint --fix instead of prettier.

  25. rattrayalex commented on Jul 6, 2017

    @rattrayalex
    Collaborator

    I'm a pretty big +1 to allowing .prettier config files, if for no other reason than that they function as great marketing on Github. But also because there are many times when there simply isn't a simpler way for people to use it.

    Sharing bash files or "always run it with args --x --y z" within a company really isn't wonderful, and package.json simply doesn't work in all cases.

  26. Ciantic commented on Jul 8, 2017

    @Ciantic

    Is this thread mostly about agreeing to filename (e.g. .prettierrc / package.json) and format in it, like opts or JSON?

    If so I think this should be decided by one maintainer, just do it.

    There is already a cottage industry of these non-standards, one example from VSCode extension here:

    {
        "prettier.tabWidth": 4,
        "prettier.typescriptEnable": [
            "typescript",
            "typescriptreact"
        ],
        "prettier.trailingComma": "es5",
        "prettier.printWidth": 100
    }
    

    This is not good! We need standard for this, such a simple thing should not be outsourced when in the end it's maintainers that decide these simple things.

  27. rattrayalex commented on Jul 8, 2017

    @rattrayalex
    Collaborator

    @Ciantic yes, I am planning on doing exactly that this weekend 😄 and it seems @azz has the same idea

  28. rattrayalex commented on Jul 8, 2017

    @rattrayalex
    Collaborator

    EDIT: moved a proposal regarding perf to #2434 (comment) as more relevant conversations are happening there.

  29. added
    locked-due-to-inactivity
    on Jul 7, 2018
  30. locked as resolved and limited conversation to collaborators on Jul 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    locked-due-to-inactivitystatus:needs discussion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions