Skip to content

Commit

Permalink
feat!: add toml plugin, use taplo inside instead (#314)
Browse files Browse the repository at this point in the history
Co-authored-by: JounQin <admin@1stg.me>
  • Loading branch information
so1ve and JounQin authored Nov 27, 2023
1 parent ac2b2fb commit 7db8ba4
Show file tree
Hide file tree
Showing 19 changed files with 431 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/honest-pigs-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"prettier-plugin-toml": patch
---

fix: do not remove blank lines after comments - close https://github.com/un-ts/toml-tools/issues/74
5 changes: 5 additions & 0 deletions .changeset/purple-years-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"prettier-plugin-toml": major
---

feat!: add `toml` plugin, use `taplo` inside instead
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ This repository is a monorepo managed by [changesets][] what means we actually p
| [`prettier-plugin-pkg`](/packages/pkg) | An opinionated package.json formatter plugin for Prettier | [![npm](https://img.shields.io/npm/v/prettier-plugin-pkg.svg)](https://www.npmjs.com/package/prettier-plugin-pkg) |
| [`prettier-plugin-sh`](/packages/sh) | An opinionated `shellscript` formatter plugin for Prettier, also support simple format of `Dockerfile`, `properties`, `gitignore`, `dotenv`, `hosts`, `jvmoptions`... | [![npm](https://img.shields.io/npm/v/prettier-plugin-sh.svg)](https://www.npmjs.com/package/prettier-plugin-sh) |
| [`prettier-plugin-sql`](/packages/sql) | An opinionated sql formatter plugin for Prettier | [![npm](https://img.shields.io/npm/v/prettier-plugin-sql.svg)](https://www.npmjs.com/package/prettier-plugin-sql) |
| [`prettier-plugin-toml`](/packages/toml) | An opinionated `toml` formatter plugin for Prettier | [![npm](https://img.shields.io/npm/v/prettier-plugin-toml.svg)](https://www.npmjs.com/package/prettier-plugin-toml) |

## Sponsors

Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"prettier-plugin-pkg": "workspace:*",
"prettier-plugin-sh": "workspace:*",
"prettier-plugin-sql": "workspace:*",
"prettier-plugin-toml": "workspace:*",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.18.0",
Expand All @@ -75,7 +76,8 @@
"prettier-plugin-autocorrect": "workspace:*",
"prettier-plugin-pkg": "workspace:*",
"prettier-plugin-sh": "workspace:*",
"prettier-plugin-sql": "workspace:*"
"prettier-plugin-sql": "workspace:*",
"prettier-plugin-toml": "workspace:*"
},
"browserslist": [
"extends @1stg/browserslist-config/modern"
Expand Down
1 change: 1 addition & 0 deletions packages/toml/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Change Log
21 changes: 21 additions & 0 deletions packages/toml/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 UnTS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
76 changes: 76 additions & 0 deletions packages/toml/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# prettier-plugin-toml ![npm bundle size](https://img.shields.io/bundlephobia/min/prettier-plugin-toml) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/prettier-plugin-toml)

> An opinionated `toml` formatter plugin for [Prettier][]
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing, taking various rules into account.

This plugin adds support for `toml` through [taplo][].

## Notice

This plugin is still under development, its printer just wraps [taplo][]'s default printer.
Of course it should just work, but may not match [prettier][]'s format sometimes.

## Requirements

`prettier-plugin-toml` is an evergreen module. 🌲 This module requires an [LTS](https://github.com/nodejs/Release) Node version (v16.0.0+).

## Install

Using npm:

```sh
# npm
npm i -D prettier prettier-plugin-toml

# yarn
yarn add -D prettier prettier-plugin-toml
```

## Usage

Once installed, [Prettier plugins](https://prettier.io/docs/en/plugins.html) must be added to `.prettierrc`:

```json
{
"plugins": ["prettier-plugin-toml"]
}
```

Then:

```sh
# npx
npx prettier --write foo.toml

# yarn
yarn prettier --write foo.toml
```

## Sponsors

| 1stG | RxTS | UnTS |
| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| [![1stG Open Collective backers and sponsors](https://opencollective.com/1stG/organizations.svg)](https://opencollective.com/1stG) | [![RxTS Open Collective backers and sponsors](https://opencollective.com/rxts/organizations.svg)](https://opencollective.com/rxts) | [![UnTS Open Collective backers and sponsors](https://opencollective.com/unts/organizations.svg)](https://opencollective.com/unts) |

## Backers

[![Backers](https://raw.githubusercontent.com/1stG/static/master/sponsors.svg)](https://github.com/sponsors/JounQin)

| 1stG | RxTS | UnTS |
| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| [![1stG Open Collective backers and sponsors](https://opencollective.com/1stG/individuals.svg)](https://opencollective.com/1stG) | [![RxTS Open Collective backers and sponsors](https://opencollective.com/rxts/individuals.svg)](https://opencollective.com/rxts) | [![UnTS Open Collective backers and sponsors](https://opencollective.com/unts/individuals.svg)](https://opencollective.com/unts) |

## Changelog

Detailed changes for each release are documented in [CHANGELOG.md](./CHANGELOG.md).

## License

[MIT][] © [Ray][]@[mk1.io][]

[mk1.io]: https://mk1.io
[mit]: http://opensource.org/licenses/MIT
[prettier]: https://prettier.io
[ray]: https://github.com/so1ve
[taplo]: https://github.com/tamasfe/taplo
40 changes: 40 additions & 0 deletions packages/toml/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "prettier-plugin-toml",
"version": "1.0.0",
"type": "module",
"description": "An opinionated `toml` formatter plugin for Prettier",
"repository": "git@github.com/un-ts/prettier.git",
"homepage": "https://github.com/un-ts/prettier/tree/master/packages/prettier",
"author": "Ray (https://mk1.io) <i@mk1.io>",
"contributors": [
"JounQin (https://www.1stG.me) <admin@1stg.me>"
],
"funding": "https://opencollective.com/unts",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
},
"main": "./lib/index.cjs",
"module": "./lib/index.js",
"exports": {
"types": "./lib/index.d.ts",
"import": "./lib/index.js",
"require": "./lib/index.cjs"
},
"types": "./lib/index.d.ts",
"files": [
"lib"
],
"keywords": [
"toml",
"plugin",
"prettier",
"prettier-plugin"
],
"peerDependencies": {
"prettier": "^3.0.3"
},
"dependencies": {
"@taplo/lib": "^0.4.0-alpha.2"
}
}
51 changes: 51 additions & 0 deletions packages/toml/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Taplo } from '@taplo/lib'
import type { Plugin } from 'prettier'

import { languages } from './languages.js'
import { prettierOptionsDefinitions } from './options.js'
import type { PrettierOptions, TaploOptions } from './types.js'

const PLUGIN_NAME = 'toml'

let taplo: Taplo | undefined

async function format(code: string, options: TaploOptions) {
if (!taplo) {
taplo = await Taplo.initialize()
}

return taplo.format(code, { options })
}

const TomlPlugin: Plugin<string> = {
languages,
parsers: {
[PLUGIN_NAME]: {
async parse(code: string, options: PrettierOptions) {
const indentString = options.useTabs
? '\t'
: ' '.repeat(options.tabWidth)

return await format(code.trim(), {
...options,
columnWidth: options.printWidth,
indentString,
trailingNewline: true,
arrayTrailingComma: options.trailingComma !== 'none',
crlf: options.endOfLine === 'crlf',
})
},
astFormat: PLUGIN_NAME,
locStart: () => -1,
locEnd: () => -1,
},
},
printers: {
[PLUGIN_NAME]: {
print: ({ node }) => node,
},
},
options: prettierOptionsDefinitions,
}

export default TomlPlugin
93 changes: 93 additions & 0 deletions packages/toml/src/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { SupportOption } from 'prettier'

import type { PrettierTaploOptions } from './types'

/**
* @see https://github.com/tamasfe/taplo/blob/848722f2c604de68535e5a3e0bb2a2c1d3c7dc74/crates/taplo/src/formatter/mod.rs#L150-L168
*/
export const prettierOptionsDefinitions = {
alignEntries: {
name: 'alignEntries',
type: 'boolean',
category: 'taplo',
default: false,
description: 'Align consecutive entries vertically.',
},
alignComments: {
name: 'alignComments',
type: 'boolean',
category: 'taplo',
default: true,
description:
'Align consecutive comments after entries and items vertically. This applies to comments that are after entries or array items.',
},
arrayAutoExpand: {
name: 'arrayAutoExpand',
type: 'boolean',
category: 'taplo',
default: true,
description:
'Expand arrays to multiple lines that exceed the maximum column width.',
},
arrayAutoCollapse: {
name: 'arrayAutoCollapse',
type: 'boolean',
category: 'taplo',
default: true,
description:
"Collapse arrays that don't exceed the maximum column width and don't contain comments.",
},
compactArrays: {
name: 'compactArrays',
type: 'boolean',
category: 'taplo',
default: true,
description: 'Omit white space padding from single-line arrays.',
},
compactInlineTables: {
name: 'compactInlineTables',
type: 'boolean',
category: 'taplo',
default: false,
description:
'Omit white space padding from the start and end of inline tables.',
},
compactEntries: {
name: 'compactEntries',
type: 'boolean',
category: 'taplo',
default: false,
description: 'Omit white space around `=`.',
},
indentTables: {
name: 'indentTables',
type: 'boolean',
category: 'taplo',
default: false,
description:
'Indent based on tables and arrays of tables and their subtables, subtables out of order are not indented.',
},
indentEntries: {
name: 'indentEntries',
type: 'boolean',
category: 'taplo',
default: false,
description: 'Indent entries under tables.',
},
reorderKeys: {
name: 'reorderKeys',
type: 'boolean',
category: 'taplo',
default: false,
description:
'Alphabetically reorder keys that are not separated by empty lines.',
},
allowedBlankLines: {
name: 'allowedBlankLines',
type: 'int',
category: 'taplo',
default: 1,
description:
'The maximum number of allowed blank lines between entries and tables.',
},
} satisfies Record<keyof PrettierTaploOptions, SupportOption>
13 changes: 13 additions & 0 deletions packages/toml/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { FormatOptions } from '@taplo/lib'
import type { ParserOptions } from 'prettier'

export type TaploOptions = NonNullable<FormatOptions['options']>
export type PrettierTaploOptions = Omit<
TaploOptions,
| 'arrayTrailingComma'
| 'columnWidth'
| 'crlf'
| 'indentString'
| 'trailingNewline'
>
export type PrettierOptions = ParserOptions & PrettierTaploOptions
22 changes: 22 additions & 0 deletions packages/toml/test/__snapshots__/fixtures.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`parser and printer > should format all fixtures > comments.toml 1`] = `
"# This is a TOML comment
# This is a multiline
# TOML comment
str1 = \\"I'm a string.\\"
"
`;

exports[`parser and printer > should format all fixtures > fixture1.toml 1`] = `
"[foo]
asfd = 1
bar = [
'averyloooooooooooooooooooooooooooooooooooooooooooooooooooong',
\\"arrrrrrrrrrrrrrrrrrrrrrrray\\",
'thatexceedsthemaximumcolumnwidth',
]
"
`;
34 changes: 34 additions & 0 deletions packages/toml/test/fixtures.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import { format } from 'prettier'

import TomlPlugin from 'prettier-plugin-toml'

const _dirname =
typeof __dirname === 'undefined'
? path.dirname(fileURLToPath(import.meta.url))
: __dirname

describe('parser and printer', () => {
it('should format all fixtures', async () => {
const fixtures = path.resolve(_dirname, 'fixtures')
for (const relativeFilepath of fs.readdirSync(fixtures)) {
const filepath = path.resolve(fixtures, relativeFilepath)
const input = fs.readFileSync(filepath, 'utf8')

try {
const output = await format(input, {
filepath,
parser: 'toml',
plugins: [TomlPlugin],
})

expect(output).toMatchSnapshot(relativeFilepath)
} catch (err: unknown) {
expect((err as Error).message).toMatchSnapshot(relativeFilepath)
}
}
})
})
Loading

0 comments on commit 7db8ba4

Please sign in to comment.