Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
adamzapasnik committed Feb 7, 2021
0 parents commit 291f98f
Show file tree
Hide file tree
Showing 22 changed files with 5,381 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
end_of_line = lf
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
22 changes: 22 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"env": {
"node": true,
"es6": true,
"jest": true
},
"extends": ["eslint:recommended", "prettier"],
"plugins": ["prettier"],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
"run_spec": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"rules": {
"prettier/prettier": ["error"],
"no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": false }]
}
}
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
- package-ecosystem: 'npm'
directory: '/'
schedule:
interval: 'weekly'
47 changes: 47 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: CI

on:
push:
branches:
- master
pull_request:
branches:
- master

jobs:
test:
name: Test
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
node: ['10', '12', '14']
ruby: ["2.5", "2.6", "2.7", "3.0"]

steps:
- uses: actions/checkout@v1

- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
ruby-version: ${{ matrix.ruby }}

- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node }}

- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"

- uses: actions/cache@v1
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- run: yarn install --frozen-lockfile
- run: yarn lint
- run: yarn test
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.DS_Store
node_modules/
.vscode/
coverage/
4 changes: 4 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"printWidth": 120
}
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Changelog

All notable changes to the prettier-plugin-erb will be documented in this file.

## v.0.1.0 - 7 February 2021

Initial release
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2021 Adam Zapaśnik

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.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Prettier ERB Plugin

## How to install?

```sh
yarn add -D prettier @prettier/plugin-ruby prettier-plugin-erb
```

`@prettier/plugin-ruby` is used for formatting multiline expressions

Available configuration options for plugin-ruby are available [here](https://github.com/prettier/plugin-ruby#configuration)

## How to deal with bugs?

Your code wasn't formatted correctly or there was an error? Add the problematic file to .prettierignore and submit an Issue.
11 changes: 11 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';
const ENABLE_CODE_COVERAGE = !!process.env.ENABLE_CODE_COVERAGE;

module.exports = {
setupFiles: ['<rootDir>/tests_config/run_spec.js'],
snapshotSerializers: ['jest-snapshot-serializer-raw'],
testRegex: 'jsfmt\\.spec\\.js$|tests/.*\\.js$',
collectCoverage: ENABLE_CODE_COVERAGE,
testEnvironment: 'node',
transform: {},
};
19 changes: 19 additions & 0 deletions lib/expression_type_matcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const expressionTypeMatcher = (expression) => {
let type;

if (/<%-?\s*(if|unless)\s[\s\S]*?end\s*-?%>/.test(expression)) {
type = 'plain';
} else if (/<%-?\s*(if|unless|case)\s/.test(expression) || /<%[^#][\S\s]*(\sdo|\|)\s*-?%>/.test(expression)) {
type = 'start';
} else if (/<%-?\s*end\s*-?%>/.test(expression)) {
type = 'end';
} else if (/<%-?\s*else\s*-?%>/.test(expression) || /<%-?\s*(elsif|when)\s/.test(expression)) {
type = 'middle';
} else {
type = 'plain';
}

return { type };
};

module.exports = expressionTypeMatcher;
32 changes: 32 additions & 0 deletions lib/formatter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { concat, indent, hardline, group } = require('prettier').doc.builders;
const { format } = require('prettier');

const formatMultilineExpressions = (tokens, options) => {
return tokens
.map((token) => ({ ...token }))
.map((token) => {
// TODO: currently doesn't support multiline block opening expressions
if (token.type === 'plain' && token.content.match(/\r?\n/)) {
const matcher = token.content.match(/<%(=|#|-|#-|#=)?([\S\s]*?)\s*(#|-|#-)?%>/m);
const openingTag = matcher[1] || '';
const expression = matcher[2];
const closingTag = matcher[3] || '';
const openingFullTag = `<%${openingTag}`;
const closingFullTag = `${closingTag}%>`;
const formattedExpression = format(expression, { ...options, parser: 'ruby' })
.trim()
.split(/\r?\n/)
.map((s) => [s, hardline])
.reduce((acc, val) => acc.concat(val)) // .flat() isn't supported by node 10
.slice(0, -1); // remove last hardline

token.content = group(
concat([openingFullTag, indent(concat([hardline, concat(formattedExpression)])), hardline, closingFullTag])
);
}

return token;
});
};

module.exports = formatMultilineExpressions;
17 changes: 17 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const parser = require('./parser');
const printers = require('./printers');

module.exports = {
defaultOptions: {},
parsers: {
erb: parser,
},
printers,
languages: [
{
name: 'html-erb',
parsers: ['erb'],
extensions: ['.html.erb'],
},
],
};
11 changes: 11 additions & 0 deletions lib/parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const { tokenizeHTML } = require('prettier-html-templates');
const expressionTypeMatcher = require('./expression_type_matcher');

function parse(text, parsers, options) {
return tokenizeHTML(text, /<%[\s\S]*?%>/gm, expressionTypeMatcher);
}

module.exports = {
parse,
astFormat: 'erb-ast',
};
35 changes: 35 additions & 0 deletions lib/printers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { encodeExpressions, decodeExpressions } = require('prettier-html-templates');
const { mapDoc } = require('prettier').doc.utils;
const formatMultilineExpressions = require('./formatter');
const prettier = require('prettier');

function embed(path, _print, textToDoc, options) {
const tokens = path.stack[0];

const isTextWithExpressions = tokens.find((token) => token.type !== 'text');

if (!isTextWithExpressions) {
return prettier.format(options.originalText, { ...options, parser: 'html' });
}

const formattedTokens = formatMultilineExpressions(tokens, options);
const [text, expressionMap] = encodeExpressions(formattedTokens);
const htmlDoc = textToDoc(text, { parser: 'html' });

const callback = decodeExpressions(expressionMap);

return mapDoc(htmlDoc, callback);
}

module.exports = {
'erb-ast': {
embed: (path, _print, textToDoc, options) => {
try {
return embed(path, _print, textToDoc, options);
} catch (e) {
console.error(e);
return options.originalText;
}
},
},
};
60 changes: 60 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"name": "prettier-plugin-erb",
"version": "0.1.0",
"license": "MIT",
"description": "Prettier plugin for .html.erb files",
"repository": {
"type": "git",
"url": "https://github.com/adamzapasnik/prettier-plugin-erb"
},
"author": {
"name": "Adam Zapaśnik",
"email": "[email protected]",
"url": "https://adamzapasnik.io"
},
"bugs": {
"url": "https://github.com/adamzapasnik/prettier-plugin-erb/issues"
},
"homepage": "https://github.com/adamzapasnik/prettier-plugin-erb#readme",
"keywords": [
"plugin",
"prettier",
"erb",
"ruby",
"html-erb"
],
"main": "./lib/index.js",
"scripts": {
"test": "jest",
"lint": "eslint ."
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": [
"eslint —-fix"
]
},
"devDependencies": {
"@prettier/plugin-ruby": "^1.5.1",
"eslint": "^7.18.0",
"eslint-config-prettier": "^7.2.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.3.1",
"husky": "^4.3.8",
"jest": "^26.6.3",
"jest-snapshot-serializer-raw": "^1.1.0",
"lint-staged": "^10.5.3",
"prettier": "^2.2.1"
},
"peerDependencies": {
"@prettier/plugin-ruby": "^1.0.0",
"prettier": "^2.0.0"
},
"dependencies": {
"prettier-html-templates": "^0.1.0"
}
}
Loading

0 comments on commit 291f98f

Please sign in to comment.