Run yarn prettify for the first time. (#22)

This commit is contained in:
Dandelion Mané 2018-02-18 08:13:29 -08:00 committed by William Chargin
parent de359dbaa4
commit b367da8568
19 changed files with 418 additions and 410 deletions

View File

@ -1,16 +1,16 @@
'use strict';
"use strict";
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const fs = require("fs");
const path = require("path");
const paths = require("./paths");
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
delete require.cache[require.resolve("./paths")];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
"The NODE_ENV environment variable is required but was not specified."
);
}
@ -21,7 +21,7 @@ var dotenvFiles = [
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
NODE_ENV !== "test" && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);
@ -30,10 +30,10 @@ var dotenvFiles = [
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
dotenvFiles.forEach((dotenvFile) => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
require("dotenv-expand")(
require("dotenv").config({
path: dotenvFile,
})
);
@ -50,10 +50,10 @@ dotenvFiles.forEach(dotenvFile => {
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
process.env.NODE_PATH = (process.env.NODE_PATH || "")
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.filter((folder) => folder && !path.isAbsolute(folder))
.map((folder) => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
@ -62,7 +62,7 @@ const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.filter((key) => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
@ -71,7 +71,7 @@ function getClientEnvironment(publicUrl) {
{
// Useful for determining whether were running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
NODE_ENV: process.env.NODE_ENV || "development",
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
@ -81,13 +81,13 @@ function getClientEnvironment(publicUrl) {
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
"process.env": Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
return {raw, stringified};
}
module.exports = getClientEnvironment;

View File

@ -1,14 +1,14 @@
'use strict';
"use strict";
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
return "module.exports = {};";
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
return "cssTransform";
},
};

View File

@ -1,6 +1,6 @@
'use strict';
"use strict";
const path = require('path');
const path = require("path");
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html

View File

@ -1,18 +1,18 @@
'use strict';
"use strict";
const path = require('path');
const fs = require('fs');
const url = require('url');
const path = require("path");
const fs = require("fs");
const url = require("url");
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
const hasSlash = path.endsWith("/");
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
@ -22,7 +22,7 @@ function ensureSlash(path, needsSlash) {
}
}
const getPublicUrl = appPackageJson =>
const getPublicUrl = (appPackageJson) =>
envPublicUrl || require(appPackageJson).homepage;
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
@ -34,22 +34,22 @@ const getPublicUrl = appPackageJson =>
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : "/");
return ensureSlash(servedUrl, true);
}
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveApp('src/index.js'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('src/setupTests.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
dotenv: resolveApp(".env"),
appBuild: resolveApp("build"),
appPublic: resolveApp("public"),
appHtml: resolveApp("public/index.html"),
appIndexJs: resolveApp("src/index.js"),
appPackageJson: resolveApp("package.json"),
appSrc: resolveApp("src"),
yarnLockFile: resolveApp("yarn.lock"),
testsSetup: resolveApp("src/setupTests.js"),
appNodeModules: resolveApp("node_modules"),
publicUrl: getPublicUrl(resolveApp("package.json")),
servedPath: getServedPath(resolveApp("package.json")),
};

View File

@ -1,22 +1,22 @@
'use strict';
"use strict";
if (typeof Promise === 'undefined') {
if (typeof Promise === "undefined") {
// Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
require("promise/lib/rejection-tracking").enable();
window.Promise = require("promise/lib/es6-extensions.js");
}
// fetch() polyfill for making API calls.
require('whatwg-fetch');
require("whatwg-fetch");
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');
Object.assign = require("object-assign");
// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
// We don't polyfill it in the browser--this is user's responsibility.
if (process.env.NODE_ENV === 'test') {
require('raf').polyfill(global);
if (process.env.NODE_ENV === "test") {
require("raf").polyfill(global);
}

View File

@ -1,24 +1,24 @@
'use strict';
"use strict";
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const autoprefixer = require("autoprefixer");
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin");
const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const WatchMissingNodeModulesPlugin = require("react-dev-utils/WatchMissingNodeModulesPlugin");
const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const getClientEnvironment = require("./env");
const paths = require("./paths");
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
const publicPath = "/";
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
const publicUrl = "";
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
@ -28,13 +28,13 @@ const env = getClientEnvironment(publicUrl);
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
devtool: "cheap-module-source-map",
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
require.resolve("./polyfills"),
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
@ -45,7 +45,7 @@ module.exports = {
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
require.resolve("react-dev-utils/webpackHotDevClient"),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
@ -58,21 +58,21 @@ module.exports = {
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
filename: "static/js/bundle.js",
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
chunkFilename: "static/js/[name].chunk.js",
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
devtoolModuleFilenameTemplate: (info) =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, "/"),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules: ["node_modules", paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
@ -82,12 +82,11 @@ module.exports = {
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
"react-native": "react-native-web",
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
@ -109,15 +108,14 @@ module.exports = {
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
enforce: "pre",
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
eslintPath: require.resolve("eslint"),
},
loader: require.resolve('eslint-loader'),
loader: require.resolve("eslint-loader"),
},
],
include: paths.appSrc,
@ -132,19 +130,18 @@ module.exports = {
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
name: "static/media/[name].[hash:8].[ext]",
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
loader: require.resolve("babel-loader"),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
@ -159,29 +156,29 @@ module.exports = {
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
require.resolve("style-loader"),
{
loader: require.resolve('css-loader'),
loader: require.resolve("css-loader"),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
loader: require.resolve("postcss-loader"),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
ident: "postcss",
plugins: () => [
require('postcss-flexbugs-fixes'),
require("postcss-flexbugs-fixes"),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
">1%",
"last 4 versions",
"Firefox ESR",
"not ie < 9", // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
flexbox: "no-2009",
}),
],
},
@ -199,9 +196,9 @@ module.exports = {
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
loader: require.resolve("file-loader"),
options: {
name: 'static/media/[name].[hash:8].[ext]',
name: "static/media/[name].[hash:8].[ext]",
},
},
],
@ -247,11 +244,11 @@ module.exports = {
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty",
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become

View File

@ -1,26 +1,26 @@
'use strict';
"use strict";
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
const autoprefixer = require("autoprefixer");
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ManifestPlugin = require("webpack-manifest-plugin");
const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const SWPrecacheWebpackPlugin = require("sw-precache-webpack-plugin");
const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const paths = require("./paths");
const getClientEnvironment = require("./env");
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
const shouldUseRelativeAssetPaths = publicPath === "./";
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== "false";
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
@ -30,12 +30,12 @@ const env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
if (env.stringified["process.env"].NODE_ENV !== '"production"') {
throw new Error("Production builds must have NODE_ENV=production.");
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
const cssFilename = "static/css/[name].[contenthash:8].css";
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
@ -43,7 +43,7 @@ const cssFilename = 'static/css/[name].[contenthash:8].css';
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') }
{publicPath: Array(cssFilename.split("/").length).join("../")}
: {};
// This is the production configuration.
@ -54,31 +54,31 @@ module.exports = {
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: shouldUseSourceMap ? 'source-map' : false,
devtool: shouldUseSourceMap ? "source-map" : false,
// In production, we only want to load the polyfills and the app code.
entry: [require.resolve('./polyfills'), paths.appIndexJs],
entry: [require.resolve("./polyfills"), paths.appIndexJs],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
filename: "static/js/[name].[chunkhash:8].js",
chunkFilename: "static/js/[name].[chunkhash:8].chunk.js",
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
devtoolModuleFilenameTemplate: (info) =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/'),
.replace(/\\/g, "/"),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules: ["node_modules", paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
@ -88,12 +88,11 @@ module.exports = {
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
"react-native": "react-native-web",
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
@ -115,15 +114,14 @@ module.exports = {
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
enforce: "pre",
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
eslintPath: require.resolve("eslint"),
},
loader: require.resolve('eslint-loader'),
loader: require.resolve("eslint-loader"),
},
],
include: paths.appSrc,
@ -137,19 +135,18 @@ module.exports = {
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
name: "static/media/[name].[hash:8].[ext]",
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
loader: require.resolve("babel-loader"),
options: {
compact: true,
},
},
@ -171,14 +168,14 @@ module.exports = {
Object.assign(
{
fallback: {
loader: require.resolve('style-loader'),
loader: require.resolve("style-loader"),
options: {
hmr: false,
},
},
use: [
{
loader: require.resolve('css-loader'),
loader: require.resolve("css-loader"),
options: {
importLoaders: 1,
minimize: true,
@ -186,21 +183,21 @@ module.exports = {
},
},
{
loader: require.resolve('postcss-loader'),
loader: require.resolve("postcss-loader"),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
ident: "postcss",
plugins: () => [
require('postcss-flexbugs-fixes'),
require("postcss-flexbugs-fixes"),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
">1%",
"last 4 versions",
"Firefox ESR",
"not ie < 9", // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
flexbox: "no-2009",
}),
],
},
@ -217,14 +214,14 @@ module.exports = {
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
loader: require.resolve("file-loader"),
// Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
name: "static/media/[name].[hash:8].[ext]",
},
},
// ** STOP ** Are you adding a new loader?
@ -291,7 +288,7 @@ module.exports = {
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json',
fileName: "asset-manifest.json",
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
@ -301,13 +298,13 @@ module.exports = {
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js',
filename: "service-worker.js",
logger(message) {
if (message.indexOf('Total precache size is') === 0) {
if (message.indexOf("Total precache size is") === 0) {
// This message occurs for every build and is a bit too noisy.
return;
}
if (message.indexOf('Skipping static resource') === 0) {
if (message.indexOf("Skipping static resource") === 0) {
// This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612
return;
@ -316,7 +313,7 @@ module.exports = {
},
minify: true,
// For unknown URLs, fallback to the index page
navigateFallback: publicUrl + '/index.html',
navigateFallback: publicUrl + "/index.html",
// Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/],
@ -333,10 +330,10 @@ module.exports = {
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty",
},
};

View File

@ -1,13 +1,13 @@
'use strict';
"use strict";
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const config = require('./webpack.config.dev');
const paths = require('./paths');
const errorOverlayMiddleware = require("react-dev-utils/errorOverlayMiddleware");
const noopServiceWorkerMiddleware = require("react-dev-utils/noopServiceWorkerMiddleware");
const ignoredFiles = require("react-dev-utils/ignoredFiles");
const config = require("./webpack.config.dev");
const paths = require("./paths");
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const host = process.env.HOST || '0.0.0.0';
const protocol = process.env.HTTPS === "true" ? "https" : "http";
const host = process.env.HOST || "0.0.0.0";
module.exports = function(proxy, allowedHost) {
return {
@ -28,12 +28,12 @@ module.exports = function(proxy, allowedHost) {
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === "true",
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
clientLogLevel: "none",
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
@ -71,7 +71,7 @@ module.exports = function(proxy, allowedHost) {
ignored: ignoredFiles(paths.appSrc),
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === 'https',
https: protocol === "https",
host: host,
overlay: false,
historyApiFallback: {

View File

@ -1,30 +1,30 @@
'use strict';
"use strict";
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
process.env.BABEL_ENV = "production";
process.env.NODE_ENV = "production";
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
process.on("unhandledRejection", (err) => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
require("../config/env");
const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const path = require("path");
const chalk = require("chalk");
const fs = require("fs-extra");
const webpack = require("webpack");
const config = require("../config/webpack.config.prod");
const paths = require("../config/paths");
const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles");
const formatWebpackMessages = require("react-dev-utils/formatWebpackMessages");
const printHostingInstructions = require("react-dev-utils/printHostingInstructions");
const FileSizeReporter = require("react-dev-utils/FileSizeReporter");
const printBuildError = require("react-dev-utils/printBuildError");
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
@ -43,7 +43,7 @@ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
.then(previousFileSizes => {
.then((previousFileSizes) => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
@ -53,25 +53,25 @@ measureFileSizesBeforeBuild(paths.appBuild)
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
({stats, previousFileSizes, warnings}) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(chalk.yellow("Compiled with warnings.\n"));
console.log(warnings.join("\n\n"));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
"\nSearch for the " +
chalk.underline(chalk.yellow("keywords")) +
" to learn more about each warning."
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
"To ignore, add " +
chalk.cyan("// eslint-disable-next-line") +
" to the line before.\n"
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
console.log(chalk.green("Compiled successfully.\n"));
}
console.log('File sizes after gzip:\n');
console.log("File sizes after gzip:\n");
printFileSizesAfterBuild(
stats,
previousFileSizes,
@ -93,8 +93,8 @@ measureFileSizesBeforeBuild(paths.appBuild)
useYarn
);
},
err => {
console.log(chalk.red('Failed to compile.\n'));
(err) => {
console.log(chalk.red("Failed to compile.\n"));
printBuildError(err);
process.exit(1);
}
@ -102,7 +102,7 @@ measureFileSizesBeforeBuild(paths.appBuild)
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
console.log("Creating an optimized production build...");
let compiler = webpack(config);
return new Promise((resolve, reject) => {
@ -117,21 +117,21 @@ function build(previousFileSizes) {
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
return reject(new Error(messages.errors.join("\n\n")));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
(typeof process.env.CI !== "string" ||
process.env.CI.toLowerCase() !== "false") &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
"\nTreating warnings as errors because process.env.CI = true.\n" +
"Most CI servers set it automatically.\n"
)
);
return reject(new Error(messages.warnings.join('\n\n')));
return reject(new Error(messages.warnings.join("\n\n")));
}
return resolve({
stats,
@ -145,6 +145,6 @@ function build(previousFileSizes) {
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
filter: (file) => file !== paths.appHtml,
});
}

View File

@ -1,35 +1,35 @@
'use strict';
"use strict";
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
process.env.BABEL_ENV = "development";
process.env.NODE_ENV = "development";
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
process.on("unhandledRejection", (err) => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
require("../config/env");
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const fs = require("fs");
const chalk = require("chalk");
const webpack = require("webpack");
const WebpackDevServer = require("webpack-dev-server");
const clearConsole = require("react-dev-utils/clearConsole");
const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles");
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
} = require("react-dev-utils/WebpackDevServerUtils");
const openBrowser = require("react-dev-utils/openBrowser");
const paths = require("../config/paths");
const config = require("../config/webpack.config.dev");
const createDevServerConfig = require("../config/webpackDevServer.config");
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
@ -41,7 +41,7 @@ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
const HOST = process.env.HOST || "0.0.0.0";
if (process.env.HOST) {
console.log(
@ -54,19 +54,19 @@ if (process.env.HOST) {
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
console.log(`Learn more here: ${chalk.yellow("http://bit.ly/2mwWSwH")}`);
console.log();
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
.then((port) => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const protocol = process.env.HTTPS === "true" ? "https" : "http";
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
@ -81,25 +81,25 @@ choosePort(HOST, DEFAULT_PORT)
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
devServer.listen(port, HOST, (err) => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
console.log(chalk.cyan("Starting the development server...\n"));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
["SIGINT", "SIGTERM"].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
.catch((err) => {
if (err && err.message) {
console.log(err.message);
}

View File

@ -1,27 +1,26 @@
'use strict';
"use strict";
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
process.env.BABEL_ENV = "test";
process.env.NODE_ENV = "test";
process.env.PUBLIC_URL = "";
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
process.on("unhandledRejection", (err) => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
require("../config/env");
const jest = require('jest');
const jest = require("jest");
const argv = process.argv.slice(2);
// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
argv.push('--watch');
if (!process.env.CI && argv.indexOf("--coverage") < 0) {
argv.push("--watch");
}
jest.run(argv);

View File

@ -1,9 +1,9 @@
// @flow
import React, { Component } from 'react';
import data from './data.json';
import './App.css';
import { FileExplorer } from './FileExplorer.js';
import { UserExplorer } from './UserExplorer.js';
import React, {Component} from "react";
import data from "./data.json";
import "./App.css";
import {FileExplorer} from "./FileExplorer.js";
import {UserExplorer} from "./UserExplorer.js";
type AppState = {selectedPath: string, selectedUser: ?string};
class App extends Component<{}, AppState> {
@ -18,7 +18,6 @@ class App extends Component<{}, AppState> {
return (
<div className="App" style={{backgroundColor: "#eeeeee"}}>
<header
style={{
backgroundColor: "#01579B",
color: "white",
@ -26,11 +25,8 @@ class App extends Component<{}, AppState> {
textAlign: "center",
boxShadow: "0px 2px 2px #aeaeae",
}}
>
<h1
style={{fontSize: "1.5em"}}
>SourceCred Explorer
</h1>
>
<h1 style={{fontSize: "1.5em"}}>SourceCred Explorer</h1>
</header>
<FileExplorer
className="file-explorer"

View File

@ -1,10 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
// Check that PropTypes check out.
it('renders without crashing', () => {
const div = document.createElement('div');
it("renders without crashing", () => {
const div = document.createElement("div");
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});

View File

@ -1,12 +1,12 @@
// @flow
import React, { Component } from 'react';
import {buildTree} from './commitUtils';
import type {CommitData, FileTree} from './commitUtils';
import React, {Component} from "react";
import {buildTree} from "./commitUtils";
import type {CommitData, FileTree} from "./commitUtils";
export class FileExplorer extends Component<{
selectedPath: string,
onSelectPath: (newPath: string) => void,
data: CommitData,
selectedPath: string,
onSelectPath: (newPath: string) => void,
data: CommitData,
}> {
render() {
// within the FileExplorer, paths start with "./", outside they don't
@ -18,42 +18,46 @@ export class FileExplorer extends Component<{
path = path.slice(2);
}
this.props.onSelectPath(path);
}
return <div className="file-explorer plugin-pane">
<h3 style={{textAlign: "center"}}>File Explorer</h3>
<div style={{fontFamily: "monospace"}}>
<FileEntry
alwaysExpand={true}
name=""
path="."
tree={tree}
onSelectPath={selectPath}
selectedPath={`./${this.props.selectedPath}`}
/>
};
return (
<div className="file-explorer plugin-pane">
<h3 style={{textAlign: "center"}}>File Explorer</h3>
<div style={{fontFamily: "monospace"}}>
<FileEntry
alwaysExpand={true}
name=""
path="."
tree={tree}
onSelectPath={selectPath}
selectedPath={`./${this.props.selectedPath}`}
/>
</div>
</div>
</div>
);
}
}
class FileEntry extends Component<{
name: string,
path: string,
alwaysExpand: bool,
tree: FileTree,
selectedPath: string,
onSelectPath: (newPath: string) => void,
}, {
expanded: bool,
}> {
class FileEntry extends Component<
{
name: string,
path: string,
alwaysExpand: boolean,
tree: FileTree,
selectedPath: string,
onSelectPath: (newPath: string) => void,
},
{
expanded: boolean,
}
> {
constructor() {
super();
this.state = {expanded: false,};
this.state = {expanded: false};
}
render() {
const topLevels = Object.keys(this.props.tree);
const subEntries = topLevels.map((x) =>
const subEntries = topLevels.map((x) => (
<FileEntry
key={x}
name={x}
@ -63,25 +67,29 @@ class FileEntry extends Component<{
selectedPath={this.props.selectedPath}
onSelectPath={this.props.onSelectPath}
/>
)
));
const isFolder = topLevels.length > 0 && !this.props.alwaysExpand;
const toggleExpand = () => this.setState({expanded: !this.state.expanded});
const isSelected = this.props.path === this.props.selectedPath;
const selectTarget = isSelected ? "." : this.props.path;
const onClick = () => this.props.onSelectPath(selectTarget);
return <div
className={isSelected ? 'selected-path' : ''}
return (
<div
className={isSelected ? "selected-path" : ""}
style={{marginLeft: this.props.path === "." ? 0 : 25}}
>
<p>
{isFolder && <button
style={{marginRight: 3}}
onClick={toggleExpand}>»</button>}
<a href="javascript: void 0" onClick={onClick}>{this.props.name}</a>
</p>
{(this.state.expanded || this.props.alwaysExpand) && subEntries}
</div>
<p>
{isFolder && (
<button style={{marginRight: 3}} onClick={toggleExpand}>
»
</button>
)}
<a href="javascript: void 0" onClick={onClick}>
{this.props.name}
</a>
</p>
{(this.state.expanded || this.props.alwaysExpand) && subEntries}
</div>
);
}
}

View File

@ -1,7 +1,7 @@
// @flow
import React, { Component } from 'react';
import {commitWeight, userWeightForPath} from './commitUtils';
import type {CommitData, FileTree} from './commitUtils';
import React, {Component} from "react";
import {commitWeight, userWeightForPath} from "./commitUtils";
import type {CommitData, FileTree} from "./commitUtils";
export class UserExplorer extends Component<{
selectedPath: string,
@ -9,42 +9,41 @@ export class UserExplorer extends Component<{
onSelectUser: (newUser: string) => void,
data: CommitData,
}> {
render() {
const weights = userWeightForPath(this.props.selectedPath, this.props.data, commitWeight);
const sortedUserWeightTuples =
Object.keys(weights)
.map(k => [k, weights[k]])
.sort((a,b) => b[1] - a[1]);
const entries = sortedUserWeightTuples.map(authorWeight => {
const weights = userWeightForPath(
this.props.selectedPath,
this.props.data,
commitWeight
);
const sortedUserWeightTuples = Object.keys(weights)
.map((k) => [k, weights[k]])
.sort((a, b) => b[1] - a[1]);
const entries = sortedUserWeightTuples.map((authorWeight) => {
const [author, weight] = authorWeight;
return <UserEntry userId={author} weight={weight} key={author}/>
return <UserEntry userId={author} weight={weight} key={author} />;
});
return <div
className="user-explorer plugin-pane"
>
<h3 style={{textAlign: "center"}}> User Explorer </h3>
<div style={{marginLeft: 8, marginRight: 8}}>
{entries}
return (
<div className="user-explorer plugin-pane">
<h3 style={{textAlign: "center"}}> User Explorer </h3>
<div style={{marginLeft: 8, marginRight: 8}}>{entries}</div>
</div>
</div>
);
}
}
/**
* Record the cred earned by the user in a given scope.
*/
class UserEntry extends Component<{
userId: string,
weight: number,
userId: string,
weight: number,
}> {
render() {
return <div className="user-entry">
<span> {this.props.userId} </span>
<span> {this.props.weight.toFixed(1)} </span>
</div>
return (
<div className="user-entry">
<span> {this.props.userId} </span>
<span> {this.props.weight.toFixed(1)} </span>
</div>
);
}
}

View File

@ -1,27 +1,27 @@
// @flow
import PropTypes from 'prop-types';
import PropTypes from "prop-types";
export type CommitData = {
// TODO improve variable names
fileToCommits: {[filename: string]: string[]};
commits: {[commithash: string]: Commit};
}
fileToCommits: {[filename: string]: string[]},
commits: {[commithash: string]: Commit},
};
type Commit = {
author: string;
stats: {[filename: string]: FileStats};
}
author: string,
stats: {[filename: string]: FileStats},
};
type FileStats = {
lines: number;
added: number;
deleted: number;
}
lines: number,
added: number,
deleted: number,
};
export function commitWeight(commit: Commit, filepath: string): number {
// hack - GitPython encodes renames in the filepath. ignore for now.
if (filepath.indexOf('=>') !== -1) {
if (filepath.indexOf("=>") !== -1) {
return 0;
}
return Math.sqrt(commit.stats[filepath].lines);
@ -29,10 +29,14 @@ export function commitWeight(commit: Commit, filepath: string): number {
function allSelectedFiles(filepath: string, data: CommitData): string[] {
const fnames = Object.keys(data.fileToCommits);
return fnames.filter(x => x.startsWith(filepath));
return fnames.filter((x) => x.startsWith(filepath));
}
function *userWeights(files: string[], data: CommitData, weightFn: WeightFn): Iterable<[string, number]> {
function* userWeights(
files: string[],
data: CommitData,
weightFn: WeightFn
): Iterable<[string, number]> {
for (const file of files) {
for (const commitHash of data.fileToCommits[file]) {
const commit = data.commits[commitHash];
@ -48,15 +52,19 @@ function *userWeights(files: string[], data: CommitData, weightFn: WeightFn): It
}
}
/**
/**
* A weight function determines how much commit contributes to the importance
* of a particular file. For instance, a weight function might be defined as,
* the number of lines changed in filepath in commit commit, or 1 if
* filepath was changed in commit, else 0.
* filepath was changed in commit, else 0.
*/
type WeightFn = (commit: Commit, filepath: string) => number;
export function userWeightForPath(path: string, data: CommitData, weightFn: WeightFn): {[string]: number} {
export function userWeightForPath(
path: string,
data: CommitData,
weightFn: WeightFn
): {[string]: number} {
const userWeightMap = {};
const files = allSelectedFiles(path, data);
for (const [user, weight] of userWeights(files, data, weightFn)) {
@ -78,15 +86,15 @@ export function buildTree(fileNames: string[]): FileTree {
function _buildTree(sortedFileNames: string[]): FileTree {
const topLevelBuckets: {[root: string]: string[]} = {};
for (const fileName of sortedFileNames) {
const topLevel = fileName.split('/')[0];
const topLevel = fileName.split("/")[0];
const remainder = fileName
.split('/')
.split("/")
.slice(1)
.join('/');
.join("/");
if (topLevelBuckets[topLevel] == null) {
topLevelBuckets[topLevel] = [];
}
if (remainder !== '') {
if (remainder !== "") {
topLevelBuckets[topLevel].push(remainder);
}
}

View File

@ -1,28 +1,28 @@
// @flow
import {userWeightForPath, buildTree} from './commitUtils';
import {userWeightForPath, buildTree} from "./commitUtils";
const exampleData = {
fileToCommits: {
'foo.txt': ['1'],
'bar.txt': ['1', '2']
"foo.txt": ["1"],
"bar.txt": ["1", "2"],
},
commits: {
'1': {
'author': 'dandelionmane',
'stats': {
'foo.txt': {'lines': 5, 'added': 3, 'deleted': 2},
'bar.txt': {'lines': 100, 'added': 100, 'deleted': 0}
}
"1": {
author: "dandelionmane",
stats: {
"foo.txt": {lines: 5, added: 3, deleted: 2},
"bar.txt": {lines: 100, added: 100, deleted: 0},
},
},
'2': {
'author': 'wchargin',
'stats': {
'bar.txt': {'lines': 100, 'added': 50, 'deleted': 50},
}
"2": {
author: "wchargin",
stats: {
"bar.txt": {lines: 100, added: 50, deleted: 50},
},
},
},
authors: ['dandelionmane', 'wchargin']
}
authors: ["dandelionmane", "wchargin"],
};
const emptyData = {fileToCommits: {}, commits: {}, authors: []};
@ -30,41 +30,45 @@ function weightByNumFilesTouched(commit, filepath) {
return 1;
}
describe('userWeightForPath', () => {
it('works on empty data', () => {
const actual = userWeightForPath('', emptyData, weightByNumFilesTouched);
describe("userWeightForPath", () => {
it("works on empty data", () => {
const actual = userWeightForPath("", emptyData, weightByNumFilesTouched);
const expected = {};
expect(actual).toEqual(expected);
});
it('works in simple case', () => {
const actual = userWeightForPath('', exampleData, weightByNumFilesTouched);
const expected = {'dandelionmane': 2, 'wchargin': 1};
it("works in simple case", () => {
const actual = userWeightForPath("", exampleData, weightByNumFilesTouched);
const expected = {dandelionmane: 2, wchargin: 1};
expect(actual).toEqual(expected);
});
it('respects file paths', () => {
const actual = userWeightForPath('bar.txt', exampleData, weightByNumFilesTouched);
const expected = {'dandelionmane': 1, 'wchargin': 1};
it("respects file paths", () => {
const actual = userWeightForPath(
"bar.txt",
exampleData,
weightByNumFilesTouched
);
const expected = {dandelionmane: 1, wchargin: 1};
expect(actual).toEqual(expected);
});
it('uses custom weight function', () => {
it("uses custom weight function", () => {
const myWeight = (commit, filepath) => commit.stats[filepath].lines;
const actual = userWeightForPath('', exampleData, myWeight);
const expected = {'dandelionmane': 105, 'wchargin': 100};
const actual = userWeightForPath("", exampleData, myWeight);
const expected = {dandelionmane: 105, wchargin: 100};
expect(actual).toEqual(expected);
})
})
});
});
describe('buildTree', () => {
it('handles empty tree', () => {
describe("buildTree", () => {
it("handles empty tree", () => {
expect(buildTree([])).toEqual({});
});
it('handles trees', () => {
const names = ['foo', 'bar/zod', 'bar/zoink'];
const expected = {'foo': {}, 'bar': {'zod': {}, 'zoink': {}}};
it("handles trees", () => {
const names = ["foo", "bar/zod", "bar/zoink"];
const expected = {foo: {}, bar: {zod: {}, zoink: {}}};
expect(buildTree(names)).toEqual(expected);
});
});

View File

@ -1,8 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
ReactDOM.render(<App />, document.getElementById('root'));
ReactDOM.render(<App />, document.getElementById("root"));
registerServiceWorker();

View File

@ -9,9 +9,9 @@
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
window.location.hostname === "[::1]" ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
@ -19,7 +19,7 @@ const isLocalhost = Boolean(
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
@ -29,7 +29,7 @@ export default function register() {
return;
}
window.addEventListener('load', () => {
window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
@ -40,8 +40,8 @@ export default function register() {
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
"This web app is being served cache-first by a service " +
"worker. To learn more, visit https://goo.gl/SC7cgQ"
);
});
} else {
@ -55,43 +55,43 @@ export default function register() {
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
console.log("New content is available; please refresh.");
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
console.log("Content is cached for offline use.");
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
.catch((error) => {
console.error("Error during service worker registration:", error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
response.headers.get("content-type").indexOf("javascript") === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
@ -103,14 +103,14 @@ function checkValidServiceWorker(swUrl) {
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
"No internet connection found. App is running in offline mode."
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister();
});
}