Git Product home page Git Product logo

prettierd's Introduction

prettierd

Build Status

Wanna run prettier in your editor, but fast? Welcome to prettierd!

This is built on top of core_d.js and integrates with prettier.

Installation guide

$ npm install -g @fsouza/prettierd

NOTE: npm comes builtin to node.

Alternatively, users may also use homebrew:

$ brew install fsouza/prettierd/prettierd

Using in the command line with node.js

The prettierd script always takes the file in the standard input and the positional parameter with the name of the file:

$ cat file.ts | prettierd file.ts

Supported languages / plugins

Many parsers ship with prettierd, including JavaScript, TypeScript, GraphQL, CSS, HTML and YAML. Please notice that starting with version 0.12.0, prettierd now supports invoking the local version of prettier, so instead of adding new languages to prettierd, you should rely on that feature to use it locally with your custom version of prettier and enabled plugins.

Additional plugins

Additional plugins can be supported by installing them and adding them to the prettier configuration. For example, to use the Ruby plugin, install @prettier/plugin-ruby and add it to your configuration:

{
  // ... other settings
  "plugins": ["@prettier/plugin-ruby"]
}

Then formatting Ruby files should be possible.

Provide Default Configuration

You can provide a default configuration for the prettier via setting the environment variable PRETTIERD_DEFAULT_CONFIG to the exact path of the prettier configuration file.

Local Instance

If you have locally installed prettier in your package, it will use that. Otherwise, it will use the one bundled with the package itself.

If you want to use prettierd exclusively with the locally installed prettier package, you can set the environment variable PRETTIERD_LOCAL_PRETTIER_ONLY (any truthy value will do, good examples are true or 1).

Editor integration

Vim / Neovim

I use this directly with neovim's LSP client, via efm-langserver:

local prettier = {
  formatCommand = 'prettierd "${INPUT}"',
  formatStdin = true,
  env = {
    string.format('PRETTIERD_DEFAULT_CONFIG=%s', vim.fn.expand('~/.config/nvim/utils/linter-config/.prettierrc.json')),
  },
}

Alternatively, you can use prettierme to integrate directly with other editors.

Or, as a third option for users of Vim/Neovim plugins such as formatter.nvim or vim-codefmt, you can configure prettierd in the stdin mode. Below is an example with formatter.nvim:

require('formatter').setup({
  logging = false,
  filetype = {
    javascript = {
        -- prettierd
       function()
          return {
            exe = "prettierd",
            args = {vim.api.nvim_buf_get_name(0)},
            stdin = true
          }
        end
    },
    -- other formatters ...
  }
})

Sublime Text

Prettierd Format

You can use Prettierd Format to format your files with prettierd. After installation, it enables format-on-save for any file supported by Prettier by default.

Fmt

Alternatively, if you're looking for something more advanced that supports multiple formatters, you can use Fmt and configure prettierd for each language scope you wish to format:

{
  "rules": [
    {
      "selector": "source.ts",
      "cmd": ["prettierd", "--stdin-filepath", "$file"],
      "format_on_save": true
    },
    {
      "selector": "source.json"
      // ...
    }
    // ...
  ]
}

Zed

To use Prettierd with Zed, you need to configure the language_overrides adding a format_on_save command for each of the languages you wish to be handling.

Note

Configuration below assumes you have installed prettierd and gives an example of its path from Homebrew installation. You can check path on your system by running which prettierd.

Example configuration:

{
  "language_overrides": {
    "TypeScript": {
      "format_on_save": {
        "external": {
          "command": "/opt/homebrew/bin/prettierd",
          "arguments": ["--stdin-filepath", "{buffer_path}"]
        }
      }
    }
  }
}

Saveyour configuration file, and provided you've installed and set the correct path to prettierd program, Zed will start formatting your files on save action.

Other editors

I don't know much about other editors, but feel free to send a pull requests on instructions.

prettierd's People

Contributors

cenk1cenk2 avatar christianalfoni avatar dependabot[bot] avatar fsouza avatar gelio avatar joao-vitor-sr avatar kunish avatar matthewmorek avatar mkdynamic avatar muniftanjim avatar sentriz avatar smastrom avatar sqve avatar tlvince avatar vatosarmat avatar williamboman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

prettierd's Issues

Opt-in to use included prettier version

Hey ๐Ÿ‘‹๐Ÿผ,

If prettierd doesn't find a local version is falls back to the included version in this package. This is an issue in cases where a project doesn't run prettier and you introduce a lot of changes, which mainly is due to formatting.

I would argue that this is unwanted behavior and should not be the default but rather an opt-in option. What are your thoughts?

This is the only reason I'm currently using prettier_d_slim instead of this project, but since my PR (mikew/prettier_d_slim#11) never get merged I'd like to move over to this project and help out when I can.

prettierd doesn't work on version 0.22.1 and beyond

Hi @fsouza, thank you very much for the amazing project ๐Ÿ‘

I tried to update prettierd today and find out it doesn't work. No formatting at all.

Then I tried older versions using sudo npm install -g @fsouza/[email protected] and the code formatting works as expected.

As far as I can tell, when I install version 0.22.1 and the latest version 0.22.2, it won't work. Older versions work fine.

LOCAL_PRETTIER_ONLY not working as expected

If I am in a project that does not have a prettier config and/or prettier is not installed, I do not want to run prettier when formatting my code using neovims LSP client. This sometimes happens thoguh. What would be the correct configuration to acheive this?
My current config is:

local prettier = { 
  formatCommand = 'prettierd "${INPUT}"', 
  formatStdin = true, 
  env = { 'PRETTIERD_LOCAL_PRETTIER_ONLY=true' } 
}

lspconfig.efm.setup {
  init_options = { documentFormatting = true },
  filetypes = { 'typescript', 'typescriptreact', 'javascript', 'javascriptreact' },
  settings = {
    rootMarkers = { '.git/' },
    languages = {
      javascript = { prettier },
      javascriptreact = { prettier },
      typescript = { prettier },
      typescriptreact = { prettier },
    },
  },
}


Code is still formatted if there's no local prettier and PRETTIERD_LOCAL_PRETTIER_ONLY is set

Steps to reproduce:

  1. Create a lone TypeScript file that could use some formatting
  2. set -Ux PRETTIERD_LOCAL_PRETTIER_ONLY 1 (I'm using fish)
  3. cat lonely.ts | prettierd lonely.ts

Expected behavior:
The contents of the file would not be formatted.

Actual behavior:
The contents of the file is formatted.

I'm mainly running into this using Neovim and null-ls; I've set them up to format on save, so I'm running into problems with files getting formatted that shouldn't be (mainly YAML and Markdown files).

Add a CHANGELOG

Hey! Thanks for putting together this awesome service!

I have been using it for quite some time and I have upgraded the package a few times already. Before upgrading, I would love to know what has changed, if there are breaking changes or some new features I may want to check out. I did not notice any CHANGELOG / change list for releases, so I have to compare the commits between the 2 versions, which is not as convenient as having a summary in the changelog.

Can you consider adding a CHANGELOG.md or describing the changes between releases when releasing new versions (maybe using GitHub Releases)?

Cannot find module './parser-typescript.js' when running prettierd

Encountered the below error when running prettierd. Tried to Google but couldn't find anyone else who had the same issue.

Error: Cannot find module './parser-typescript.js'
Require stack:
- /opt/homebrew/Cellar/prettierd/0.22.3/libexec/lib/node_modules/@fsouza/prettierd/node_modules/prettier/index.js
- /opt/homebrew/Cellar/prettierd/0.22.3/libexec/lib/node_modules/@fsouza/prettierd/dist/service.js
- /opt/homebrew/Cellar/prettierd/0.22.3/libexec/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/server.js
- /opt/homebrew/Cellar/prettierd/0.22.3/libexec/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/daemon.js

Trying my luck here to see if there is a resolution? Am only encountering this issue when trying to format typescript or tsx files.

Edit:
I realise that after upgrading to 0.22.4, prettierd is still looking for 0.22.3. I have done a brew link --overwrite prettierd after renaming 0.22.4 to 0.22.3 and it works. But I am sure there is a cleaner and more proper way to do this?

No installation guide?

Please put installation instructions in the README for โ€œNewbiesโ€ not familiar with Node development.

Can't set default configuration

Hi!
I'm trying to set a default configuration for prettierd, using the environment variable from the README:

PRETTIERD_DEFAULT_CONFIG="$HOME/config.json"

then I tried using cat test.js | prettierd test.js but my config didn't work.

But only when I changed the config file name to .prettierrc.json it worked, but only inside that directory.

What could be done?

[Feature Request] Accept stdin or files with different extensions

Why?

  • Case 1: I use a program to edit browser inputs with my text editor. It saves the active input as a .txt file and opens it in the editor, then fills the input with the text once the editor exits. I cannot use prettierd to format the text in these files. Prettierd returns "no files specified" when passed a .txt file.

  • Case 2: There is currently no way for me to use prettierd to only format a certain selection of code as with kakoune's format-selection command. In it's current form prettierd only takes a file as input and output.

How?

  • Option 1: Accept text from stdin using -f or --format to designate the format:

    cat file.txt | prettierd --format html -
    
  • Option 2: Accept files with any extension using -f or --format to designate the format:

    prettierd --format html file.txt
    

Option 1 would be the most optimal since it would solve both of the above cases.

Support returning cursor offset

I have monkey patched locally (see below), but would be great to have a better solution upstream. Any ideas on how to include support for this in a nicer way?

async function run(cwd, { args, clientEnv }, text) {
    //...

    const opts = {
        ...options,
        filepath: fullPath
    };

    return JSON.stringify(prettier.formatWithCursor(text, opts));
}

Use local installation of prettier when possible

Hi, thank you for the amazing tool. It was something that was really lacking!

There's an important feature that is missing though (in my opinion). If I'm correct, prettierd currently embeds prettier with a locked version.
This has multiple issues:

  • I'm stuck with a prettier version (in my case there is a problem with prettier 2.2.1)
  • I am not guaranteed that I use the same version as my coworkers
  • prettierd has to be maintained to increment the prettier version on each upgrade

If you look at eslint_d, the tool uses the local version of eslint inside node_modules/.bin/eslint if it is detected (or an embedded eslint 7 otherwise).

What do you think?

Cheers!

Support for --version

Thank you for making prettierd!

I found that prettierd --version returns an error:

โ€บ prettierd --version
Error: No parser could be inferred for file: /home/r/project/--version

The --version flag is used by some projects like ale.vim to identify if prettier is working.

Differences between prettier_d_slim?

Hey, trying to decide which project to use. What was your idea behind this project? As in, was there something that other project couldn't do? Would you mind outlining differences and advantages of using your project over the other one?

Thanks a lot!

how to confirm proper configuration

Thank you for putting this together. Using "format on save" and the like is a big productivity gain for me. I've recently migrated to lsp... (like many). I'm still getting my "bearings". I'm doing some work with css and html. I was using the online prettier parser and decided to see if I could get it running in nvim.

Prettierd is working (status running). I understand where the port and instance id are located to call it via a TCP request.

This said, in my nvim config I'm using the following documented snippet:

-- Prettier
local prettier = require("prettier")
prettier.setup({
    bin = 'prettierd', 
    formatCommand = 'prettierd "${INPUT}"',
    formatStdin = true,
    env = {string.format('PRETTIERD_DEFAULT_CONFIG=%s', vim.fn.expand('~/.config/nvim/utils/linter-config/.prettierrc.json'))},
    filetypes = {
        "css", "graphql", "html", "javascript", "javascriptreact", "json", "less", "markdown", "scss", "typescript", "typescriptreact", "yaml"
    },
})

As a "first go" I chose to use the null-ls plugin as an interface:

--
-- Linters and formatters that do not have an LSP interface; use null-ls to
-- bridge the gap.
local null_ls = require("null-ls")
require("null-ls").setup({
    capabilities = capabilities,
    on_attach = on_attach,
    sources = {
        null_ls.builtins.diagnostics.flake8, -- python
        null_ls.builtins.formatting.rustfmt, -- rust
        null_ls.builtins.formatting.brittany, -- haskell
        null_ls.builtins.diagnostics.yamllint, -- yaml
        null_ls.builtins.formatting.prettierd -- fast prettier
        -- null_ls.builtins.code_actions.eslint, -- html, css, js
    }
})

The nvim :checkhealth reports all is good with prettierd:

null-ls: require("null-ls.health").check()
========================================================================
  - ....
  - OK: yamllint: the command "yamllint" is executable.
  - OK: prettierd: the command "prettierd" is executable.

Yet, when I hit the <leader>f command, I don't see the css "straighten-up" (i.e., clean-up the formatting).

The mapping is is used by many lsp:

    -- bind conditional on server capabilities
    if client.resolved_capabilities.document_formatting then
        buf_set_keymap('n', '<Leader>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
    elseif client.resolved_capabilities.document_range_formatting then
        buf_set_keymap('n', '<Leader>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
    end

Have I failed to "connect all the dots"? How can I tell that prettierd has been invoked when I call <leader>f?

Thanks in advance for any pointers.

Is it possible to package the project for Homebrew?

The Current Issue I'm Facing

I use Homebrew to install most if not all of my CLI-based software including Node, npm & prettier (the non-daemon version). This allows me to update "everything" at one go using the set of commands brew upgrade && brew update. Not making prettierd available via Homebrew means I now have to remember to update my global npm packages (which doesn't include anything for obvious reasons).

So, I was wondering if its possible to package the project for Homebrew & make it installable by simply invoking the brew install prettierd command?

Also a heads up, you can find more detailed instructions on how to package a Node-based tools here - "Node for Formula Authors"

How to use with prettier plugins?

I'm trying to setup @prettier/plugin-ruby, and it's not immediately clear to me how to integrate this with prettierd. I have them both installed globally, and my setup looks like this:

local prettier = {
  formatCommand = 'prettierd ${INPUT}',
  formatStdin = true,
  env = {
    string.format('PRETTIERD_DEFAULT_CONFIG=%s', vim.fn.expand('~/.config/.prettierrc.json')),
  },
}

return {
  ruby = { prettier }
}

Should this 'just work'? Do I need to update the formatCommand somehow?

are prettier plugins supported?

hi! thanks for the cool project :)

I am wondering if prettier plugins are supported?
for example I use prettier-plugin-organize-imports from npm, which seems to work for prettier but not prettierd

thanks!

How to use with efm-langserver

That looks great, thanks! I am having trouble configuring it to work with efm via lspconfig. Tried simply that which wipes buffer empty (I would like to keep one passing those parameters as well, is it possible?):

return {
  formatCommand = ([[
    prettierd
    ${--config-precedence:configPrecedence}
    ${--tab-width:tabWidth}
    ${--single-quote:singleQuote}
    ${--prose-wrap:proseWrap}
    ${--trailing-comma:trailingComma}
    ${INPUT}
  ]]):gsub(
    "\n",
    ""
  ),
  formatStdin = true
}

Cannot find local prettier plugins when prettierd is started in another directory

I ran into an issue where prettierd would lose the ability to find local plugins when restarted (running prettierd restart) in a directory that is outside of the project containing the plugins.

Let's say I have a SvelteKit project at ~/repos/svelte-example/ that contains the prettier plugin prettier-plugin-svelte. If I cd into the project directory and run cat src/hooks.client.ts | prettierd src/hooks.client.ts while prettierd is not yet running, it works as expected. Subsequent formats in the project directory also work as expected.

However, if I cd into a directory that is outside of the root directory of the project, let's say the home directory ~/, and run prettierd restart, prettierd loses the ability to find plugins in ~/repos/svelte-example/ where it previously worked. It just crashes, returning the following error:

Error: Cannot find module 'prettier-plugin-svelte'
Require stack:
- /home/username/repos/svelte-example/node_modules/.pnpm/[email protected]/node_modules/prettier/index.js
- /home/username/.nvm/versions/node/v19.2.0/lib/node_modules/@fsouza/prettierd/dist/service.js
- /home/username/.nvm/versions/node/v19.2.0/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/server.js
- /home/username/.nvm/versions/node/v19.2.0/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/daemon.js

I did some digging and found a possible cause for this behavior. When prettier resolves plugins, it uses process.cwd() as the directory it looks for the plugins (source here) which just so happens to be dependant on where the prettierd/core_d daemon was started/restarted. So if I (re)start prettierd in the home directory ~/ by running prettierd restart, the next time prettierd tries to resolve plugins, it tries to look for them relative to the ~/ directory instead of the current working directory, and thus can't find them. This can be temporarily "fixed" by running prettierd restart again in the project directory which makes the process.cwd() match the project's directory again.

This behavior becomes really apparent when working on multiple projects that have different prettier plugins (E.g. backend and frontend) simultaniously, since prettierd can only find the plugins of one project at a time (the one which the process.cwd() matches).

This behavior could probably be fixed by restarting the prettierd daemon every time the working directory changes, which could be identified somehow. Though I don't know if this would be the optimal solution since it would introduce the same latency that the original prettier has, but only when switching directories.

Steps to reproduce

  1. Restart prettierd by running prettierd restart in a directory outside the root of the project that contains prettier plugins (E.g. ~/).
  2. cd into a project that has prettier plugins installed and defined in its .prettierrc file. (E.g. { "plugins": ["prettier-plugin-svelte"] })
  3. Try to format a file in the project directory. E.g. cat src/hooks.client.ts | prettierd src/hooks.client.ts
  4. It should fail because prettierd can't resolve the installed plugin, since the daemonized core_d service's process.cwd() is pointing to a completely different directory outside the project root because of step 1.

.prettierd file in $HOME

My prettierd was not formatting correctly after the most recent change--v0.23.2. I checked the change log and noticed the new runtime folder location. I had a .prettierd in my $HOME folder, but it was a file, not a directory. Once I removed the file and restarted neovim everything worked as expected. The .prettierd directory was created and is being populated.

I'm not sure if this was my fault or if this is directly related to the recent changes with the location of the runtime files--I've been doing an overhaul on my neovim setup lately. Looking at the changelog I can not see where this file would have been created.

It might be worth adding a check to see if the .prettierd in $HOME is a folder and not a file.

Setting environment variable PRETTIERD_DEFAULT_CONFIG doesn't appear to do anything

.prettierrc.json

{
    "tabWidth": 4,
    "overrides": [
        {
            "files": [
                "*.yaml",
                "*.yml"
            ],
            "options": {
                "tabWidth": 2
            }
        }
    ]
}

Running cat /tmp/test.yaml | prettierd test.yaml (PRETTIERD_DEFAULT_CONFIG
environment variable set to where .prettierrc.json is located) doesn't work but when test.yaml is in same directory as .prettierrc.json it works

Also doesn't work when I use the same config as https://github.com/fsouza/prettierd#editor-integration for efm-langserver + neovim lsp

Does not seem to work with overrides

I can't seem to get overrides to work with this config (.prettierrc.json). Changing the root tabWidth works but my overrides do not work for the specific files.

{
    "tabWidth": 4,
    "overrides": [
        {
            "files": [
                "*.yaml",
                "*.yml",
                "*.md"
            ],
            "options": {
                "tabWidth": 2
            }
        }
    ]
}

Resolve prettier config and binary from the file to format, not from cwd

Hey hey! Thanks once again for making this awesome CLI tool!

Today I have encountered a problem related to my (possibly unconventional) project structure.

The structure is as follows

.
โ”œโ”€โ”€ .git
โ””โ”€โ”€ src
   โ””โ”€โ”€ js
      โ”œโ”€โ”€ .prettierrc
      โ”œโ”€โ”€ node_modules
      โ”‚  โ”œโ”€โ”€ .bin
      โ”‚  โ””โ”€โ”€ prettier
      โ”œโ”€โ”€ package-lock.json
      โ””โ”€โ”€ some-dir
         โ””โ”€โ”€ some-file.ts

Everything works well when running prettierd on some-dir/some-file.ts from the src/js directory - both prettier config and prettier version are as expected - from the src/js directory.

However, the problem happens when the same command is run from the root of the repository. Running cat src/js/some-dir/some-file.ts | prettierd src/js/some-dir/some-file.ts results in prettierd using its built-in prettier version and the default prettier config. It does not respect that there is prettier installed and configured in src/js.

Normally that would not be a problem when using the CLI, but I am using neovim + null-ls that runs prettierd for formatting, and null-ls starts with its cwd pointed to the root of the repository. Adding a special .nvimrc configuration to make it start in src/js would be quite cumbersome to get right in all cases.

As far as I have read the source code, this is because when trying to resolve prettier and the config, prettierd starts from $CWD (which in this case is the root of the repository). If it started from the file location (src/js/some-dir/some-file.ts), it would stop at src/js and notice that prettier is installed there.

I am aware that changing this logic could introduce performance problems (resolving prettier would happen much more often, for different files in the repo). That could be solved by approaching caching a bit differently:

  1. Split the file path by / (in the example above, that would be home, ubuntu, myrepo, src, js, some-dir)
  2. Is there a cache entry (with prettier config and binary) for the whole path? If yes, go to point 4. If no, continue.
  3. Remove the last part of the file path (essentially, use the parent directory). If reached root of the filesystem, to point 3. If there are still directories to traverse, go to point 2.
  4. Try to resolve prettier config and prettier binary using existing methods (require.resolve), but starting from the file path, not cwd.
  5. Set the resolved prettier config and binary for each subpaths of the file path (in the example above, for both
    src/js, src/js/some-dir).

Let me know what do you think about changing the approach. If you'd like, I can try to make a PR changing this logic.

suggestion: possibility of having `~/.prettierd@` files nested inside a `~/.prettierd/` directory

Suggestion

At first, thank a lot for building prettierd!

Since v.0.23.0 to start a new daemon per working directory, I noticed many .prettierd@absolute-path files in the home directory.

I have no idea if there's a cleanup method involved to clean stale/old files, for me it looks something like that:

ยป ls -la ~ | grep .prettierd 

.prettierd@absolute-path-to-one-project
.prettierd@absolute-path-to-another-project
.prettierd@...
.prettierd@...
.prettierd@...
.prettierd@...
...

I was wondering if it would be possible to nest all those files inside one .prettierd/ directory instead?

Thanks!

Global plugins not being found

Hi, currently trying to use prettier-plugin-style-order and prettier-plugin-tailwindcss (both installed globally via npm), currently using neovim and null-ls to run prettierd.

local config = require("user.lsp.null-ls.formatting")
local formatting = null_ls.builtins.formatting
local sources = {
	formatting.prettierd.with({
		env = {
			PRETTIERD_DEFAULT_CONFIG = vim.fn.expand("$HOME/.config/nvim/.prettierrc.json"),
		},
	}),
}
null_ls.setup({
	sources = sources,
	debounce = 200,
	autostart = true,
	debug = true,
	on_attach = function(client, bufnr)
		config.setup(client, bufnr)
	end,
})

This is the prettier config

{
  "arrowParens": "avoid",
  "bracketSpacing": true,
  "endOfLine": "auto",
  "printWidth": 80,
  "semi": true,
  "tabWidth": 2,
  "bracketSameLine": true,
  "embeddedLanguageFormatting": "auto",
  "htmlWhitespaceSensitivity": "css",
  "insertPragma": false,
  "jsxSingleQuote": false,
  "proseWrap": "preserve",
  "quoteProps": "as-needed",
  "requirePragma": false,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "none",
  "useTabs": false,
  "configPrecedence": "prefer-file",
  "plugins": ["prettier-plugin-style-order", "prettier-plugin-tailwindcss"]
}

and the error log

[TRACE qua 25 mai 2022 20:35:50] .../site/pack/packer/start/null-ls.nvim/lua/null-ls/rpc.lua:121: received LSP request for method textDocument/formatting
[TRACE qua 25 mai 2022 20:35:50] ...ack/packer/start/null-ls.nvim/lua/null-ls/generators.lua:21: running generators for method NULL_LS_FORMATTING
[DEBUG qua 25 mai 2022 20:35:50] ...rt/null-ls.nvim/lua/null-ls/helpers/command_resolver.lua:35: attempting to find local executable node_modules/.bin/prettierd
[DEBUG qua 25 mai 2022 20:35:50] ...rt/null-ls.nvim/lua/null-ls/helpers/command_resolver.lua:41: Unable to resolve command [node_modules/.bin/prettierd], skipping further lookups
[DEBUG qua 25 mai 2022 20:35:50] ...t/null-ls.nvim/lua/null-ls/helpers/generator_factory.lua:286: Using dynamic command for [prettierd], got: "prettierd"
[DEBUG qua 25 mai 2022 20:35:50] ...t/null-ls.nvim/lua/null-ls/helpers/generator_factory.lua:346: spawning command "prettierd" at /home/todomir with args { "/home/todomir/dev/react/testing-fe/src/index.css" }
[TRACE qua 25 mai 2022 20:35:50] ...t/null-ls.nvim/lua/null-ls/helpers/generator_factory.lua:217: error output: Error: Cannot find module 'prettier-plugin-style-order'
Require stack:
- /home/todomir/.nvm/versions/node/v18.0.0/lib/node_modules/@fsouza/prettierd/node_modules/prettier/index.js
- /home/todomir/.nvm/versions/node/v18.0.0/lib/node_modules/@fsouza/prettierd/dist/service.js
- /home/todomir/.nvm/versions/node/v18.0.0/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/server.js
- /home/todomir/.nvm/versions/node/v18.0.0/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/daemon.js

[TRACE qua 25 mai 2022 20:35:50] ...t/null-ls.nvim/lua/null-ls/helpers/generator_factory.lua:218: output: nil
[TRACE qua 25 mai 2022 20:35:50] ...t/null-ls.nvim/lua/null-ls/helpers/generator_factory.lua:222: ignoring stderr due to generator options
[TRACE qua 25 mai 2022 20:35:50] .../site/pack/packer/start/null-ls.nvim/lua/null-ls/rpc.lua:146: received LSP notification for method textDocument/didSave
[TRACE qua 25 mai 2022 20:35:50] ...ack/packer/start/null-ls.nvim/lua/null-ls/generators.lua:21: running generators for method NULL_LS_DIAGNOSTICS_ON_SAVE
[DEBUG qua 25 mai 2022 20:35:50] ...ack/packer/start/null-ls.nvim/lua/null-ls/generators.lua:24: no generators available

Error when trying to run prettierd

Hey! I just installed prettierd and whenever I try to run it I have this error:

[Error: EAGAIN: resource temporarily unavailable, read] {
    errno: -11,
   code: 'EAGAIN',
   syscall: 'read'
}

The only thing I tried to do is uninstall and reinstall but it didn't change anything, what can I do?
Thank you for your time and have a great day! (:

Prettierd cannot find prettier plugins

Hello!

I am currently trying to use the plugin @trivago/prettier-plugin-sort-imports. As you can see in this test repository I created, both prettier and the prettier plugin are installed:

{
  "name": "prettierd_plugin_issue",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@trivago/prettier-plugin-sort-imports": "^3.2.0",
    "@types/chai": "^4.3.0",
    "@types/mocha": "^9.1.0",
    "chai": "^4.3.6",
    "mocha": "^9.2.2",
    "prettier": "^2.6.0",
    "typescript": "^4.6.2"
  }
}

When I try to format the package using prettier it works properly, using the plugin:

foo@bar:~$ npx prettier . --write
.prettierrc.json 40ms
package-lock.json 117ms
package.json 12ms
src/module.ts 206ms
test/module.spec.ts 23ms
tsconfig.json 5ms

image

But when I try to format the file test/module.spec.ts using prettierd the normal formatting for ; happens, but the imports are not ordered.

foo@bar:~$ cat test/module.spec.ts | prettierd test/module.spec.ts
import hello_world from "@src/module";
import { expect } from "chai";

describe("the module module", function () {
  it("should not return anything", function () {
    const returnValue = hello_world();
    expect(returnValue).to.be.undefined;
  });
});

image

If I try to manually specify the plugin in the .prettierrc.json file, this happens:

foo@bar:~$ cat test/module.spec.ts | prettierd test/module.spec.ts
Error: Cannot find module '@trivago/prettier-plugin-sort-imports'
Require stack:
- /home/datwaft/Issues/prettierd_plugin_issue/node_modules/prettier/index.js
- /home/datwaft/.nvm/versions/node/v17.1.0/lib/node_modules/@fsouza/prettierd/dist/service.js
- /home/datwaft/.nvm/versions/node/v17.1.0/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/server.js
- /home/datwaft/.nvm/versions/node/v17.1.0/lib/node_modules/@fsouza/prettierd/node_modules/core_d/lib/daemon.js

image

The test repository can be found here: https://github.com/datwaft/prettierd_plugin_issue

Automate GH releases

Idea is that when we push a tag, we'd use GH Actions to create the GitHub release.

Could use GitHub's new API for generating the description!

I assume there's already some GH action ready for this :)

Add `--help` flag

Now that prettierd supports command line arguments, it would be nice to have a --help flag that would show a bit of documentation about the possible core_d subcommands (like restart or stop) and also flags (e.g. --ignore-path)

Unable to run prettierd run with a prettierrc configuration.

Prettierd runs fine when I provide no .prettierrc.json, but when I add the file in my root I get the following error -

C:\Users\yashg\AppData\Local\nvim>prettierd test\foo.ts
TypeError [ERR_INVALID_ARG_TYPE]: The "list" argument must be an instance of Array. Received null
    at Function.concat (buffer.js:550:11)
    at Object.readFileAfterClose (internal/fs/read_file_context.js:51:23)
    at tick (internal/fs/read_file_context.js:105:28)
    at processTicksAndRejections (internal/process/task_queues.js:79:21) {
  code: 'ERR_INVALID_ARG_TYPE'
}

I am using Neovim in Windows along with efm-language-server
My configuration of prettier looks like -

{formatCommand = "prettierd ${INPUT}", formatStdin = true}

Any idea?

0.21.0 doesn't format anymore?

Hi,
I just noticed that in my case prettierd doesn't format files anymore. I have integrated it with the nvim-lspconfig plugin into Neovim but even when I just try to prettierd package.json (for instance), the file stays unchanged.

Here is the debug-info when trying to format package.json (I have replaced the actual path with [local-project])

$ prettierd --debug-info package.json
prettierd 0.21.0
prettier version: 2.6.2
  Loaded from: [local-project]/node_modules/prettier/index.js
  Cache: miss

Cache information:
- "configCache" contains 0 items
- "importCache" contains 1 items
- "parentCache" contains 0 items

I'm not sure what I can do to provide further info, please let me know, also if you think it is user error. The formatting has worked since about a week ago, I've only noticed the difference today when updating my tools, including prettierd.

Best,
Daniel

Passing CLI options to prettier

Hello @fsouza ,

Is it possible to pass configuration options to prettier itself via flags? Or even enabling a global fallback prettierrc creating .prettierrc on ~?

Prettier errors cause prettierd to hang

Hey,

First of all, thanks for the great tool!

I've been experimenting with it for a few hours and found out that formatting stops working for me after I try to format a file with a syntax error. Later I found out that running prettierd on an invalid file (when prettier would normally report a syntax error), causes the process to hang, without returning any output.

Reproduction steps:

echo "export }" > test.ts
npx prettier test.ts     # Shows an error message
cat test.ts | prettierd test.ts         # Hangs

0.23.* releases are not working with Neovim nor Zed

I've been using [email protected] for quite some time and I absolutely love it.

However, when I upgraded it to the latest version I realized that formatting stopped working for both Neovim and Zed. I tried to install 0.23.0 and faced the same issue, so I guess something changed on this minor and it isn't working as it used to.

I have a feeling that I'm probably missing something, but couldn't find it, unfortunately.

When saving a file, I have both mentioned editors configured to run prettierd. I didn't see any error message when I was using 0.23.*, but the files were never formatted. Switching back to 0.22.5 solved it.

Here is my Neovim config related to prettierd:

local group = vim.api.nvim_create_augroup("lsp_format_on_save", { clear = false })
local event = "BufWritePre" -- or "BufWritePost"
local async = event == "BufWritePost"

local lsp_buf_format = function(bufnr)
  vim.lsp.buf.format({
    filter = function(client)
      return client.name == "null-ls"
    end,
    bufnr = bufnr,
    async = async
  })
end

return {
  'jose-elias-alvarez/null-ls.nvim',
  dependencies = { 'nvim-lua/plenary.nvim' },
  config = function()
    local null_ls = require('null-ls')

    local sources = {
      null_ls.builtins.formatting.prettierd,
      null_ls.builtins.diagnostics.eslint_d.with({
        -- #{m}: message, #{s}: source name (defaults to null-ls), #{c}: code (if available)
        diagnostics_format = '#{m} eslint(#{c})',
      }),
    }

    null_ls.setup {
      sources = sources,
      on_attach = function(client, bufnr)
        if client.supports_method("textDocument/formatting") then
          vim.api.nvim_clear_autocmds({ buffer = bufnr, group = group })
          vim.api.nvim_create_autocmd(event, {
            buffer = bufnr,
            group = group,
            callback = function()
              lsp_buf_format(bufnr)
            end,
            desc = "[lsp] format on save",
          })
        end
      end,
    }
  end,
}

Also, here is my Zed config:

{
    "format_on_save": {
        "external": {
            "command": "prettierd",
            "arguments": ["{buffer_path}"]
        }
    }
}

Prettierd requires manual restart when prettier version changes

When I update prettier version in my repo, I need to manually kill prettierd process to have it use the new version.

Would be nice if it could detect that the version loaded in cache is not the same as the installed.

Or at least, document this. Because it is not obvious

Steps to reproduce

  1. npm i -D [email protected]
  2. See that prettierd uses this version to format
  3. npm i -D [email protected]
  4. npx prettier -c [file]
  5. There should be warning if you have things that are formatted differently in 2.3
  6. prettierd doesn't format with 2.3 even when you restart neovim
  7. killall prettierd
  8. Now it formats correctly

Prettierd hangs

I think I'm doing something wrong, but prettierd hangs.
What I did:

$ npm install -g fsouza@prettierd
$ npm install -g prettier
$ cd /tmp && echo '\t\t\t\t<html></html>' > index.html
$ touch output.html
$ prettierd <index.html output.html

The result: prettierd hangs
image
I use nvm, if it matters:
image

Support all of prettier flags

We should support the same flags that are supported by prettier, and build the Options object from that.

Ideally we can share some code with prettier instead of actually implementing the parsing. Need some investigation.

Local configuration changes takes a long time to take effect

After making changes to the configurations in package.json or .prettierrc.json (such as changing tabWidth from 2 to 4), I kept running the command cat FILE | prettierd FILE. It's taking almost a minute for the output to reflect the changes I made.

I'd appreciate any help you can offer in resolving this issue. Thank you!

TypeError: arg.startsWith is not a function

Hello, I seem to be running into an issue with v0.22.1 on macOS 12.5.1. When trying to pass input through, it's reporting TypeError: arg.startsWith is not a function. This seems to be isolated to macOS only as 0.22.1 works fine on my Ubuntu 22.04 machine.

Downgrading to v0.22.0 seems to run fine without any issues on macOS.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.