Skip to content

Commit 291f98f

Browse files
committed
Initial commit
0 parents  commit 291f98f

22 files changed

+5381
-0
lines changed

.editorconfig

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
root = true
2+
3+
[*]
4+
charset = utf-8
5+
indent_style = space
6+
indent_size = 2
7+
trim_trailing_whitespace = true
8+
end_of_line = lf
9+
insert_final_newline = true
10+
11+
[*.md]
12+
trim_trailing_whitespace = false

.eslintrc.json

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"env": {
3+
"node": true,
4+
"es6": true,
5+
"jest": true
6+
},
7+
"extends": ["eslint:recommended", "prettier"],
8+
"plugins": ["prettier"],
9+
"globals": {
10+
"Atomics": "readonly",
11+
"SharedArrayBuffer": "readonly",
12+
"run_spec": "readonly"
13+
},
14+
"parserOptions": {
15+
"ecmaVersion": 2018,
16+
"sourceType": "module"
17+
},
18+
"rules": {
19+
"prettier/prettier": ["error"],
20+
"no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": false }]
21+
}
22+
}

.github/dependabot.yml

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# To get started with Dependabot version updates, you'll need to specify which
2+
# package ecosystems to update and where the package manifests are located.
3+
# Please see the documentation for all configuration options:
4+
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5+
6+
version: 2
7+
updates:
8+
- package-ecosystem: 'npm'
9+
directory: '/'
10+
schedule:
11+
interval: 'weekly'

.github/workflows/ci.yml

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
name: CI
2+
3+
on:
4+
push:
5+
branches:
6+
- master
7+
pull_request:
8+
branches:
9+
- master
10+
11+
jobs:
12+
test:
13+
name: Test
14+
runs-on: ubuntu-latest
15+
timeout-minutes: 10
16+
strategy:
17+
matrix:
18+
node: ['10', '12', '14']
19+
ruby: ["2.5", "2.6", "2.7", "3.0"]
20+
21+
steps:
22+
- uses: actions/checkout@v1
23+
24+
- uses: ruby/setup-ruby@v1
25+
with:
26+
bundler-cache: true
27+
ruby-version: ${{ matrix.ruby }}
28+
29+
- uses: actions/setup-node@v2
30+
with:
31+
node-version: ${{ matrix.node }}
32+
33+
- name: Get yarn cache directory path
34+
id: yarn-cache-dir-path
35+
run: echo "::set-output name=dir::$(yarn cache dir)"
36+
37+
- uses: actions/cache@v1
38+
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
39+
with:
40+
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
41+
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
42+
restore-keys: |
43+
${{ runner.os }}-yarn-
44+
45+
- run: yarn install --frozen-lockfile
46+
- run: yarn lint
47+
- run: yarn test

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
.DS_Store
2+
node_modules/
3+
.vscode/
4+
coverage/

.prettierrc.json

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"singleQuote": true,
3+
"printWidth": 120
4+
}

CHANGELOG.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Changelog
2+
3+
All notable changes to the prettier-plugin-erb will be documented in this file.
4+
5+
## v.0.1.0 - 7 February 2021
6+
7+
Initial release

LICENSE

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright 2021 Adam Zapaśnik
2+
3+
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:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
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.

README.md

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Prettier ERB Plugin
2+
3+
## How to install?
4+
5+
```sh
6+
yarn add -D prettier @prettier/plugin-ruby prettier-plugin-erb
7+
```
8+
9+
`@prettier/plugin-ruby` is used for formatting multiline expressions
10+
11+
Available configuration options for plugin-ruby are available [here](https://github.com/prettier/plugin-ruby#configuration)
12+
13+
## How to deal with bugs?
14+
15+
Your code wasn't formatted correctly or there was an error? Add the problematic file to .prettierignore and submit an Issue.

jest.config.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
'use strict';
2+
const ENABLE_CODE_COVERAGE = !!process.env.ENABLE_CODE_COVERAGE;
3+
4+
module.exports = {
5+
setupFiles: ['<rootDir>/tests_config/run_spec.js'],
6+
snapshotSerializers: ['jest-snapshot-serializer-raw'],
7+
testRegex: 'jsfmt\\.spec\\.js$|tests/.*\\.js$',
8+
collectCoverage: ENABLE_CODE_COVERAGE,
9+
testEnvironment: 'node',
10+
transform: {},
11+
};

lib/expression_type_matcher.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const expressionTypeMatcher = (expression) => {
2+
let type;
3+
4+
if (/<%-?\s*(if|unless)\s[\s\S]*?end\s*-?%>/.test(expression)) {
5+
type = 'plain';
6+
} else if (/<%-?\s*(if|unless|case)\s/.test(expression) || /<%[^#][\S\s]*(\sdo|\|)\s*-?%>/.test(expression)) {
7+
type = 'start';
8+
} else if (/<%-?\s*end\s*-?%>/.test(expression)) {
9+
type = 'end';
10+
} else if (/<%-?\s*else\s*-?%>/.test(expression) || /<%-?\s*(elsif|when)\s/.test(expression)) {
11+
type = 'middle';
12+
} else {
13+
type = 'plain';
14+
}
15+
16+
return { type };
17+
};
18+
19+
module.exports = expressionTypeMatcher;

lib/formatter.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const { concat, indent, hardline, group } = require('prettier').doc.builders;
2+
const { format } = require('prettier');
3+
4+
const formatMultilineExpressions = (tokens, options) => {
5+
return tokens
6+
.map((token) => ({ ...token }))
7+
.map((token) => {
8+
// TODO: currently doesn't support multiline block opening expressions
9+
if (token.type === 'plain' && token.content.match(/\r?\n/)) {
10+
const matcher = token.content.match(/<%(=|#|-|#-|#=)?([\S\s]*?)\s*(#|-|#-)?%>/m);
11+
const openingTag = matcher[1] || '';
12+
const expression = matcher[2];
13+
const closingTag = matcher[3] || '';
14+
const openingFullTag = `<%${openingTag}`;
15+
const closingFullTag = `${closingTag}%>`;
16+
const formattedExpression = format(expression, { ...options, parser: 'ruby' })
17+
.trim()
18+
.split(/\r?\n/)
19+
.map((s) => [s, hardline])
20+
.reduce((acc, val) => acc.concat(val)) // .flat() isn't supported by node 10
21+
.slice(0, -1); // remove last hardline
22+
23+
token.content = group(
24+
concat([openingFullTag, indent(concat([hardline, concat(formattedExpression)])), hardline, closingFullTag])
25+
);
26+
}
27+
28+
return token;
29+
});
30+
};
31+
32+
module.exports = formatMultilineExpressions;

lib/index.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const parser = require('./parser');
2+
const printers = require('./printers');
3+
4+
module.exports = {
5+
defaultOptions: {},
6+
parsers: {
7+
erb: parser,
8+
},
9+
printers,
10+
languages: [
11+
{
12+
name: 'html-erb',
13+
parsers: ['erb'],
14+
extensions: ['.html.erb'],
15+
},
16+
],
17+
};

lib/parser.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const { tokenizeHTML } = require('prettier-html-templates');
2+
const expressionTypeMatcher = require('./expression_type_matcher');
3+
4+
function parse(text, parsers, options) {
5+
return tokenizeHTML(text, /<%[\s\S]*?%>/gm, expressionTypeMatcher);
6+
}
7+
8+
module.exports = {
9+
parse,
10+
astFormat: 'erb-ast',
11+
};

lib/printers.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const { encodeExpressions, decodeExpressions } = require('prettier-html-templates');
2+
const { mapDoc } = require('prettier').doc.utils;
3+
const formatMultilineExpressions = require('./formatter');
4+
const prettier = require('prettier');
5+
6+
function embed(path, _print, textToDoc, options) {
7+
const tokens = path.stack[0];
8+
9+
const isTextWithExpressions = tokens.find((token) => token.type !== 'text');
10+
11+
if (!isTextWithExpressions) {
12+
return prettier.format(options.originalText, { ...options, parser: 'html' });
13+
}
14+
15+
const formattedTokens = formatMultilineExpressions(tokens, options);
16+
const [text, expressionMap] = encodeExpressions(formattedTokens);
17+
const htmlDoc = textToDoc(text, { parser: 'html' });
18+
19+
const callback = decodeExpressions(expressionMap);
20+
21+
return mapDoc(htmlDoc, callback);
22+
}
23+
24+
module.exports = {
25+
'erb-ast': {
26+
embed: (path, _print, textToDoc, options) => {
27+
try {
28+
return embed(path, _print, textToDoc, options);
29+
} catch (e) {
30+
console.error(e);
31+
return options.originalText;
32+
}
33+
},
34+
},
35+
};

package.json

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
{
2+
"name": "prettier-plugin-erb",
3+
"version": "0.1.0",
4+
"license": "MIT",
5+
"description": "Prettier plugin for .html.erb files",
6+
"repository": {
7+
"type": "git",
8+
"url": "https://github.com/adamzapasnik/prettier-plugin-erb"
9+
},
10+
"author": {
11+
"name": "Adam Zapaśnik",
12+
"email": "[email protected]",
13+
"url": "https://adamzapasnik.io"
14+
},
15+
"bugs": {
16+
"url": "https://github.com/adamzapasnik/prettier-plugin-erb/issues"
17+
},
18+
"homepage": "https://github.com/adamzapasnik/prettier-plugin-erb#readme",
19+
"keywords": [
20+
"plugin",
21+
"prettier",
22+
"erb",
23+
"ruby",
24+
"html-erb"
25+
],
26+
"main": "./lib/index.js",
27+
"scripts": {
28+
"test": "jest",
29+
"lint": "eslint ."
30+
},
31+
"husky": {
32+
"hooks": {
33+
"pre-commit": "lint-staged"
34+
}
35+
},
36+
"lint-staged": {
37+
"*.js": [
38+
"eslint —-fix"
39+
]
40+
},
41+
"devDependencies": {
42+
"@prettier/plugin-ruby": "^1.5.1",
43+
"eslint": "^7.18.0",
44+
"eslint-config-prettier": "^7.2.0",
45+
"eslint-plugin-import": "^2.22.1",
46+
"eslint-plugin-prettier": "^3.3.1",
47+
"husky": "^4.3.8",
48+
"jest": "^26.6.3",
49+
"jest-snapshot-serializer-raw": "^1.1.0",
50+
"lint-staged": "^10.5.3",
51+
"prettier": "^2.2.1"
52+
},
53+
"peerDependencies": {
54+
"@prettier/plugin-ruby": "^1.0.0",
55+
"prettier": "^2.0.0"
56+
},
57+
"dependencies": {
58+
"prettier-html-templates": "^0.1.0"
59+
}
60+
}

0 commit comments

Comments
 (0)