extensions icon indicating copy to clipboard operation
extensions copied to clipboard

Proto extension support Buf formatter

Open 06kellyjac opened this issue 1 year ago • 0 comments

Check for existing issues

  • [x] Completed

Misc notes

It'd be nice, in addition to having buf lsp support (#1928) to also have buf formatter support.

There are a few upstream blockers to this

  • https://github.com/bufbuild/buf/issues/1035
  • Potentially the fact buf wants to be relative to the files it scans, this could be addressed by the above PR too

For now you can hack in support for buf formatting like so (use at your own risk):

  "languages": {
    "Proto": {
      "formatter": {
        "external": {
          "command": "bash",
          "arguments": [
            "-c",
            "INPUT=\"$(cat)\";TMPFILE=\"$(mktemp -u -p /tmp).proto\";echo \"$INPUT\" > $TMPFILE;trap 'rm -rf -- \"$TMPFILE\"' EXIT;cd /tmp;buf format --path $TMPFILE;"
          ]
        }
      }
    }
  },

It executes into bash with a script that:

  • captures stdin, being the file content
  • prepares a filename to use in /tmp
    • -u for dryrun because we need to add a suffix
    • .proto needs to be the suffix or buf format --path doesn't actually read it/run
  • dump the stdin capture to the tmpfile location
  • create a trap so when bash exits it'll clean up the tmpfile
    • this also helps if buf crashes or doesn't exist
  • cd into /tmp because buf wants to be relative to the file
  • run buf pointing at the single file with --path

I imagine this should work on Mac but it certainly works for me on Linux. I think the mktemp usage could be cleaned up a bit but I wanted to avoid using too many features in-case they're GNU mktemp specific. Maybe there should be a check that $TMPFILE gets written to just to double check the right file is being targeted for deletion.

06kellyjac avatar Feb 01 '25 13:02 06kellyjac