Skip to content

Commit

Permalink
Derek non generic feat/adopt prettier (#3426)
Browse files Browse the repository at this point in the history
* Install & implement prettier

* Run `npm run fix:node`

* Fix remaining errors

* fixed lint errors

Co-authored-by: Derek Lewis <DerekNonGeneric@inf.is>
  • Loading branch information
sebastianbenz and DerekNonGeneric committed Jan 28, 2020
1 parent 779134b commit 3bf1d09
Show file tree
Hide file tree
Showing 159 changed files with 3,651 additions and 2,326 deletions.
13 changes: 10 additions & 3 deletions .eslintrc.json
@@ -1,12 +1,19 @@
{
"extends": "google",
"extends": [
"google",
"prettier"
],
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"prettier"
],
"rules": {
"max-len": [2, 100, {
"ignoreComments": true,
"ignoreComments": true,
"ignoreRegExpLiterals": true,
"ignoreUrls": true,
"tabWidth": 2
}],
Expand All @@ -25,7 +32,7 @@
"argsIgnorePattern": "(^reject$|^_$)",
"varsIgnorePattern": "(^_$)"
}],
"quotes": [2, "single"],
"prettier/prettier": 2,
"require-jsdoc": 0,
"valid-jsdoc": 0,
"prefer-arrow-callback": 1,
Expand Down
20 changes: 20 additions & 0 deletions .prettierrc
@@ -0,0 +1,20 @@
{
"bracketSpacing": false,
"singleQuote": true,
"trailingComma": "es5",
"quoteProps": "preserve",
"overrides": [
{
"files": "*.md",
"options": {"parser": "markdown"}
},
{
"files": [".eslintrc", ".prettierrc", "*.json"],
"options": {"parser": "json"}
},
{
"files": [".travis.yml", "*.yaml", "*.yml"],
"options": {"parser": "yaml"}
}
]
}
36 changes: 18 additions & 18 deletions boilerplate/backend/index.js
@@ -1,27 +1,27 @@
/**
* Copyright 2019 The AMPHTML Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
* Copyright 2019 The AMPHTML Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

const path = require('path');
const express = require('express');
// eslint-disable-next-line new-cap
const playground = express.Router();

playground.use('/boilerplate', express.static(
path.join(__dirname, '../dist'),
{extensions: ['html']},
));
playground.use(
'/boilerplate',
express.static(path.join(__dirname, '../dist'), {extensions: ['html']})
);

module.exports = playground;
7 changes: 4 additions & 3 deletions boilerplate/build.js
Expand Up @@ -37,12 +37,13 @@ function initConfig() {
categories: require('./data/categories.json'),
formats: require('./data/formats.json'),
templates: templates.find('./templates/files'),
highlightTheme:
io.readFile(path.join(__dirname, './templates/styles/code-snippet.scss')),
highlightTheme: io.readFile(
path.join(__dirname, './templates/styles/code-snippet.scss')
),
};
// assign default template
let defaultTemplate;
config.formats.forEach((format) => {
config.formats.forEach(format => {
format.template = config.templates[format.id];
if (format.default) {
defaultTemplate = format.template;
Expand Down
2 changes: 1 addition & 1 deletion boilerplate/lib/io.js
Expand Up @@ -20,7 +20,7 @@ const fs = require('fs');
const path = require('path');

function listFiles(currentDirPath, result = [], recursive = false) {
fs.readdirSync(currentDirPath).forEach((name) => {
fs.readdirSync(currentDirPath).forEach(name => {
const filePath = path.join(currentDirPath, name);
const stat = fs.statSync(filePath);
if (stat.isFile() && !path.basename(filePath).startsWith('.')) {
Expand Down
32 changes: 18 additions & 14 deletions boilerplate/lib/templates.js
Expand Up @@ -27,18 +27,21 @@ const TEMPLATES_DIR = '../templates';
const NODE_MODULES = '../../node_modules';
const STYLES = path.join(TEMPLATES_DIR, 'styles');

const INCLUDE_PATHS = [FRONTEND_DIR, NODE_MODULES, STYLES].map((dir) => path.join(__dirname, dir));
const INCLUDE_PATHS = [FRONTEND_DIR, NODE_MODULES, STYLES].map(dir =>
path.join(__dirname, dir)
);


Handlebars.registerHelper('scss', (scssPath) => {
Handlebars.registerHelper('scss', scssPath => {
for (const includePath of INCLUDE_PATHS) {
const templatePath = path.join(includePath, scssPath);
if (io.fileExists(templatePath)) {
const result = sass.renderSync({
file: templatePath,
includePaths: INCLUDE_PATHS,
});
return new Handlebars.SafeString(result.css.toString().replace('@charset "UTF-8";', ''));
return new Handlebars.SafeString(
result.css.toString().replace('@charset "UTF-8";', '')
);
}
}
throw new Error('File not found ' + scssPath);
Expand All @@ -60,7 +63,7 @@ function findTemplates(dir) {
Handlebars.registerPartial(partials);
const icons = findPartials(path.join(dir, ICONS_DIR));
Handlebars.registerPartial(icons);
io.listFiles(dir).forEach((name) => {
io.listFiles(dir).forEach(name => {
const templateName = path.basename(name, path.extname(name));
templates[templateName] = readTemplate(name);
});
Expand Down Expand Up @@ -98,15 +101,16 @@ function replaceEndTag(match) {

function findPartials(dir) {
const partialFiles = io.listFiles(dir, [], true);
return partialFiles.map((f) => {
const name = f.replace(dir, '');
const content = io.readFile(f, 'utf-8');
return [name, content];
})
.reduce((obj, prop) => {
obj[prop[0]] = prop[1];
return obj;
}, {});
return partialFiles
.map(f => {
const name = f.replace(dir, '');
const content = io.readFile(f, 'utf-8');
return [name, content];
})
.reduce((obj, prop) => {
obj[prop[0]] = prop[1];
return obj;
}, {});
}
module.exports.find = findTemplates;
module.exports.render = renderTemplate;
20 changes: 14 additions & 6 deletions examples/api/amp-access/index.js
Expand Up @@ -24,9 +24,11 @@ const path = require('path');
// eslint-disable-next-line new-cap
const examples = express.Router();
examples.use(cookieParser());
examples.use(express.urlencoded({
extended: true,
}));
examples.use(
express.urlencoded({
extended: true,
})
);

const AMP_ACCESS_COOKIE = 'ABE_LOGGED_IN';
const VALID_USERS = {
Expand All @@ -36,7 +38,7 @@ const VALID_USERS = {
const POWER_USERS = {
'Jane@gmail.com': true,
};
const EXPIRATION_DATE = 24*60*60*1000; // 1 day in ms
const EXPIRATION_DATE = 24 * 60 * 60 * 1000; // 1 day in ms
const LOGIN_FILE_PATH = path.join(__dirname, 'login.html');

examples.get('/authorization', handleAuthorization);
Expand Down Expand Up @@ -91,7 +93,11 @@ function handleSubmit(request, response) {
response.status(401).send('Invalid email');
return;
}
response.cookie(AMP_ACCESS_COOKIE, {email}, {expires: new Date(Date.now() + EXPIRATION_DATE)});
response.cookie(
AMP_ACCESS_COOKIE,
{email},
{expires: new Date(Date.now() + EXPIRATION_DATE)}
);
let returnUrl = request.body.returnurl;
if (!isValidURL(returnUrl)) {
response.status(500).send('Invalid return URL');
Expand All @@ -103,7 +109,9 @@ function handleSubmit(request, response) {

function isValidURL(url) {
const a = URL.parse(url);
return (a.host && a.protocol && (a.protocol === 'http:' || a.protocol === 'https:'));
return (
a.host && a.protocol && (a.protocol === 'http:' || a.protocol === 'https:')
);
}

module.exports = examples;
20 changes: 15 additions & 5 deletions examples/api/amp-form.js
Expand Up @@ -21,16 +21,26 @@ const upload = multer();

// eslint-disable-next-line new-cap
const examples = express.Router();
examples.use(express.urlencoded({
extended: false,
}));
examples.use(
express.urlencoded({
extended: false,
})
);

const ERROR_CASE_AMP_FORM = 'error';

examples.get('/submit-form', submitForm);
examples.post('/submit-form-xhr', upload.none(), submitFormXHR);
examples.post('/submit-form-input-text-xhr', upload.none(), submitFormXHRInputText);
examples.post('/verify-form-input-text-xhr', upload.none(), verifyFormXHRInputText);
examples.post(
'/submit-form-input-text-xhr',
upload.none(),
submitFormXHRInputText
);
examples.post(
'/verify-form-input-text-xhr',
upload.none(),
verifyFormXHRInputText
);

function submitForm(request, response) {
response.redirect(303, '/static/samples/files/amp-form-success.html');
Expand Down
10 changes: 5 additions & 5 deletions examples/api/autosuggest.js
Expand Up @@ -81,25 +81,25 @@ examples.post('/autosuggest/address', upload.none(), handleAddressRequest);
function handleSearchRequest(request, response) {
const query = request.query ? request.query.q : '';

let results = US_CAPITAL_CITIES.filter((key) => {
let results = US_CAPITAL_CITIES.filter(key => {
return key.toUpperCase().includes(query.toUpperCase());
});

if (results.length > MAX_RESULT_SIZE) {
results = results.slice(0, MAX_RESULT_SIZE);
}

const items = ({
const items = {
items: [
{
query,
results,
},
],
});
};

response.json(items);
};
}

function handleAddressRequest(request, response) {
const city = request.body ? request.body.city : '';
Expand All @@ -114,6 +114,6 @@ function handleAddressRequest(request, response) {
response.json({
result,
});
};
}

module.exports = examples;
4 changes: 3 additions & 1 deletion examples/api/cache.js
Expand Up @@ -108,7 +108,9 @@ examples.get('/not-found', (request, response) => {
examples.get('/redirect', (request, response) => {
setImmutable(response);
if (!request.query.url) {
response.status().send('No url specified via <code>?url=https://example.com</code>');
response
.status()
.send('No url specified via <code>?url=https://example.com</code>');
return;
}
try {
Expand Down
20 changes: 14 additions & 6 deletions examples/api/photo-stream.js
Expand Up @@ -53,16 +53,24 @@ examples.all('/photo-stream', (req, res) => {
items = items[0];
}

const nextUrl = req.baseUrl + '/photo-stream?items=' +
numberOfItems + '&left=' + JSON.stringify(pagesLeft - 1);
const nextUrl =
req.baseUrl +
'/photo-stream?items=' +
numberOfItems +
'&left=' +
JSON.stringify(pagesLeft - 1);

const randomFalsy = () => {
const rand = Math.floor(Math.random() * Math.floor(3));
switch (rand) {
case 1: return null;
case 2: return undefined;
case 3: return '';
default: return false;
case 1:
return null;
case 2:
return undefined;
case 3:
return '';
default:
return false;
}
};

Expand Down

0 comments on commit 3bf1d09

Please sign in to comment.