Skip to content

Commit

Permalink
lint all js files in project
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianbenz committed Jan 30, 2019
1 parent 5ee6bfa commit 5a4bd2f
Show file tree
Hide file tree
Showing 19 changed files with 162 additions and 81 deletions.
38 changes: 38 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"extends": "google",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"rules": {
"max-len": [2, 100, {
"ignoreComments": true,
"ignoreUrls": true,
"tabWidth": 2
}],
"no-implicit-coercion": [2, {
"boolean": false,
"number": true,
"string": true
}],
"no-unused-expressions": [2, {
"allowShortCircuit": true,
"allowTernary": false
}],
"no-unused-vars": [2, {
"vars": "all",
"args": "after-used",
"argsIgnorePattern": "(^reject$|^_$)",
"varsIgnorePattern": "(^_$)"
}],
"quotes": [2, "single"],
"require-jsdoc": 0,
"valid-jsdoc": 0,
"prefer-arrow-callback": 1,
"no-var": 1
},
"env": {
"node": true,
"jasmine": true
}
}
5 changes: 3 additions & 2 deletions boilerplate/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@ function initConfig() {
categories: require('./data/categories.json'),
formats: require('./data/formats.json'),
templates: templates.find('./templates/files'),
highlightTheme: io.readFile(path.join(__dirname, '../node_modules/highlight.js/styles/monokai.css')),
highlightTheme:
io.readFile(path.join(__dirname, '../node_modules/highlight.js/styles/monokai.css')),
};
// 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
10 changes: 5 additions & 5 deletions boilerplate/lib/io.js
Original file line number Diff line number Diff line change
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 All @@ -32,12 +32,12 @@ function listFiles(currentDirPath, result = [], recursive = false) {
return result;
}

function writeFile() {
if (arguments.length < 2) {
function writeFile(...args) {
if (args.length < 2) {
throw new Error('expect path segments followed by content');
}
const filePath = Array.prototype.slice.call(arguments, 0, -1).join(path.sep);
const content = arguments[arguments.length - 1];
const filePath = Array.prototype.slice.call(args, 0, -1).join(path.sep);
const content = args[args.length - 1];
mkdir(path.dirname(filePath));
fs.writeFileSync(filePath, content, 'utf-8');
}
Expand Down
22 changes: 11 additions & 11 deletions boilerplate/lib/templates.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ const path = require('path');
const hljs = require('highlight.js');
const sass = require('node-sass');

const FRONTEND_DIR = '../../frontend/scss';
const TEMPLATES_DIR = '../templates';
const NODE_MODULES = '../../node_modules';
const STYLES = path.join(TEMPLATES_DIR, 'styles');
const FRONTEND_DIR = '../../frontend/scss';
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) => {
Expand Down Expand Up @@ -65,7 +65,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 @@ -106,15 +106,15 @@ function replaceEndTag(match) {

function findPartials(dir) {
const partialFiles = io.listFiles(dir, [], true);
return partialFiles.map(f => {
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;
}, {});
.reduce((obj, prop) => {
obj[prop[0]] = prop[1];
return obj;
}, {});
}
module.exports.find = findTemplates;
module.exports.render = renderTemplate;
6 changes: 3 additions & 3 deletions boilerplate/templates/files/serviceworkerJs.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ workbox.clientsClaim();
const OFFLINE_PAGE = '/offline.html';

// Pre-cache the AMP Runtime
self.addEventListener('install', event => {
self.addEventListener('install', (event) => {
const urls = [
'https://cdn.ampproject.org/v0.js',
// Add AMP extensions used on your pages
Expand All @@ -17,7 +17,7 @@ self.addEventListener('install', event => {
urls.push(OFFLINE_PAGE);
}
event.waitUntil(
caches.open(workbox.core.cacheNames.runtime).then(cache => cache.addAll(urls))
caches.open(workbox.core.cacheNames.runtime).then((cache) => cache.addAll(urls))
);
});

Expand All @@ -29,7 +29,7 @@ workbox.navigationPreload.enable();
// network connection
let navigationStrategy;
if (OFFLINE_PAGE) {
const networkFirstWithOfflinePage = async args => {
const networkFirstWithOfflinePage = async (args) => {
const response = await workbox.strategies.networkFirst().handle(args);
if (response) {
return response;
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
"develop": "cd platform && node build.js",
"lint": "npm-run-all lint:*",
"lint:grow": "cd platform && node lib/pipeline/growReferenceChecker.js",
"lint:node": "eslint \"platform/**/*.js\" --ignore-path ./.gitignore",
"fix:node": "eslint \"platform/**/*.js\" --fix --ignore-path ./.gitignore",
"lint:node": "eslint \"**/*.js\" --ignore-path ./.gitignore",
"fix:node": "eslint \"**/*.js\" --fix --ignore-path ./.gitignore",
"build:playground": "cd playground && npm run build",
"build:local": "cd platform && NODE_ENV=local node build.js",
"build:staging": "cd platform && NODE_ENV=staging node build.js",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ In the following example, we send pageview data to [Google Analytics](#google-an
[/tip]

[tip type="note"]
**NOTE –** Vendors that wish to integrate their service with [`<amp-analytics>`](/docs/reference/components/amp-analytics.html) should refer to the details in [Integrate your analytics tools with AMP]({{g.doc('/content/amp-dev/documentation/guides-and-tutorials/integrate/integrate-your-analytics-tools.md', locale=doc.locale).url.path}}).
**NOTE –** Vendors that wish to integrate their service with [`<amp-analytics>`](/docs/reference/components/amp-analytics.html) should refer to the details in [Integrate your analytics tools with AMP]({{g.doc('/content/amp-dev/documentation/guides-and-tutorials/contribute/integrate-your-analytics-tools.md', locale=doc.locale).url.path}}).
[/tip]

<hr>
Expand Down
2 changes: 1 addition & 1 deletion pages/content/amp-dev/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ <h2>compelling, smooth, and instant</h2>

</div>

{% set embed_url = playground_url + '/embed#url=' + podspec.base_urls.platform + doc.sampler[0].url %}
{% set embed_url = playground_url + '/embed#mode=responsive&url=' + podspec.base_urls.platform + doc.sampler[0].url %}
<div class="ad-o-sampler-iframe">
<amp-iframe
width="11"
Expand Down
29 changes: 15 additions & 14 deletions platform/lib/build/pageMinifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,17 @@
* limitations under the License.
*/

/* eslint-disable no-invalid-this */
'use strict';

const {Signale} = require('signale');
const gulp = require('gulp');
const minifyHtml = require('html-minifier').minify;
const through = require('through2');
const CleanCSS = require('clean-css')
const path = require('path');
const CleanCSS = require('clean-css');
const crypto = require('crypto');

const PAGES_DEST = '../platform/pages';

class PageMinifier {
constructor() {
this._log = new Signale({
Expand All @@ -34,11 +35,11 @@ class PageMinifier {
// An instance of CleanCSS
this._cleanCss = new CleanCSS({
2: {
'all': true
'all': true,
},
});
// Holds CSS by hash that has already been minified
this._minifiedCssCache = {}
this._minifiedCssCache = {};
}

/**
Expand All @@ -48,16 +49,16 @@ class PageMinifier {
*/
start(path) {
// Ugly but needed to keep scope for .pipe
let scope = this;
const scope = this;

return gulp.src(`${path}/**/*.html`, {'base': './'})
.pipe(through.obj(function(page, encoding, callback) {
scope._log.await(`Minifying ${page.relative} ...`);
this.push(scope._minifyPage(page));
.pipe(through.obj(function(page, encoding, callback) {
scope._log.await(`Minifying ${page.relative} ...`);
this.push(scope._minifyPage(page));

callback();
}))
.pipe(gulp.dest('./'));
callback();
}))
.pipe(gulp.dest('./'));
}

/**
Expand All @@ -72,7 +73,7 @@ class PageMinifier {
try {
html = this._cleanHtml(html);
html = this._minifyHtml(html);
} catch(e) {
} catch (e) {
this._log.error(`Could not minify ${page.relative} cause of invalid markup.`);
}

Expand Down Expand Up @@ -135,5 +136,5 @@ if (!module.parent) {
}

module.exports = {
'pageMinifier': new PageMinifier()
'pageMinifier': new PageMinifier(),
};
20 changes: 19 additions & 1 deletion platform/lib/config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* 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.
*/

'use strict';

const signale = require('signale');
const fs = require('fs');
const path = require('path');
Expand Down Expand Up @@ -42,7 +60,7 @@ class Config {
*/
_buildUrl(host) {
let url = `${host.scheme}://${host.host}`;
if (host.port && host.port !== "8080") {
if (host.port && host.port !== '8080') {
url = url + `:${host.port}`;
}

Expand Down
2 changes: 1 addition & 1 deletion platform/lib/pipeline/componentReferenceImporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class ComponentReferenceImporter extends GitHubImporter {
// If the extraction of an excerpt was successful write it to the teaser
if (excerpt) {
// Strip out all possible HTML tags
excerpt = excerpt[1].replace(/<\/?[^>]+(>|$)/g, "");
excerpt = excerpt[1].replace(/<\/?[^>]+(>|$)/g, '');
// Unwrap back ticks
excerpt = excerpt.replace(/`(.+)`/g, '$1');
// And unwrap possible markdown links
Expand Down
14 changes: 10 additions & 4 deletions platform/lib/pipeline/componentReferenceLinker.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const fs = require('fs');
const POD_BASE_PATH = path.join(__dirname, '../../../pages/');
// Which documents to check for broken references
// const PAGES_SRC = POD_BASE_PATH + 'content/amp-dev/documentation/guides-and-tutorials/**/*.md';

// eslint-disable-next-line max-len
const PAGES_SRC = POD_BASE_PATH + 'content/amp-dev/documentation/guides-and-tutorials/develop/media_iframes_3p/third_party_components.md';
const COMPONENTS_SRC = POD_BASE_PATH + 'content/amp-dev/documentation/components/';

Expand Down Expand Up @@ -76,6 +78,7 @@ class ComponentReferenceLinker {


// Cases
/* eslint-disable max-len */
const cases = [
content.match(/\[amp-\w*(-\w*)*\]\(\/docs\/reference\/components\/\w*-\w*(-\w*)*\.html\)/gm),
content.match(/\[`amp-\w*(-\w*)*\`]\(\/docs\/reference\/components\/\w*-\w*(-\w*)*\.html\)/gm),
Expand All @@ -84,6 +87,7 @@ class ComponentReferenceLinker {
content.match(/\`amp-\w*(-\w*)*`/gm),
content.match(/amp-\w*(-\w*)*/gm),
];
/* eslint-enable max-len */

for (let i = 0; i < cases.length; i++) {
const results = Array.from(new Set(cases[i]));
Expand Down Expand Up @@ -116,7 +120,8 @@ class ComponentReferenceLinker {


_hash(str) {
const hash = str.split('').reduce((prevHash, currVal) => (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
const hash = str.split('')
.reduce((prevHash, currVal) => (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
this._log.error(hash);
return hash;
}
Expand All @@ -138,13 +143,14 @@ class ComponentReferenceLinker {
}

_componentPath(component) {
const char = component.slice(4, 5).toUpperCase();
const path = `({{g.doc('/content/amp-dev/documentation/components/reference/${component}.md', locale=doc.locale).url.path}})`;
/* eslint-disable max-len */
const path =
`({{g.doc('/content/amp-dev/documentation/components/reference/${component}.md', locale=doc.locale).url.path}})`;
return `[\`${component}\`]${path}`;
/* eslint-enable max-len */
}

_componentExist(component) {
const char = component.slice(4, 5).toUpperCase();
const path = COMPONENTS_SRC + '/reference/' + component + '.md';

this._log.start('Path:', path);
Expand Down
8 changes: 4 additions & 4 deletions platform/lib/pipeline/filteredPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class FilteredPage {
inactiveFormatClasses = Object.values(inactiveFormatClasses);
inactiveFormatClasses = '.' + inactiveFormatClasses.join(', .');

let activeFormatClass = FILTER_CLASSES[this._format];
const activeFormatClass = FILTER_CLASSES[this._format];

// Find all hidden elements and remove them if they aren't matching
// the current filter
Expand Down Expand Up @@ -123,7 +123,7 @@ class FilteredPage {
_rewriteUrls() {
this._dom('a').each((index, a) => {
a = this._dom(a);
let href = a.attr('href') || '';
const href = a.attr('href') || '';
// Check if the link is pointing to a filtered route
// and if the link already has a query parameter
if (!href.includes('?') && isFilterableRoute(href)) {
Expand All @@ -137,7 +137,7 @@ class FilteredPage {
this._dom('.ad-m-format-toggle-link').addClass('inactive');

// The current active format should make it possible to go back to unfiltered
let activeToggle = this._dom(`.ad-m-format-toggle-link-${this._format}`);
const activeToggle = this._dom(`.ad-m-format-toggle-link-${this._format}`);
activeToggle.removeClass('inactive');
activeToggle.addClass('active');
activeToggle.attr('href', '?');
Expand All @@ -152,7 +152,7 @@ class FilteredPage {
let filteredElementsSelector = Object.values(FILTER_CLASSES);
filteredElementsSelector = '.' + filteredElementsSelector.join(', .');

let filterClasses = Object.values(FILTER_CLASSES).join(' ');
const filterClasses = Object.values(FILTER_CLASSES).join(' ');

this._dom(filteredElementsSelector).each((index, filteredElement) => {
filteredElement = this._dom(filteredElement);
Expand Down
2 changes: 1 addition & 1 deletion platform/lib/pipeline/growReferenceChecker.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const REFERENCE_PATTERN = /g.doc\('(.*?)'/g;
const LOOKUP_TABLE = {
'/content/amp-dev/documentation/guides-and-tutorials/learn/validate.md': '/content/amp-dev/documentation/guides-and-tutorials/learn/validation-workflow/index.md',
'/content/amp-dev/documentation/guides-and-tutorials/learn/how_cached.md':
'/content/amp-dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/index.md'
'/content/amp-dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/index.md',
};
/* eslint-enable max-len */

Expand Down
Loading

0 comments on commit 5a4bd2f

Please sign in to comment.