Commit 711d45b6 authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Use next.config env and packages to calculate hashes (#7001)

* Use next.config env and packages to calculate
hashes for chunk-graph

* Remove example from testing

* remove left over import

* Tweak behavior
parent c2d0a4ef
...@@ -33,6 +33,7 @@ export class FlyingShuttle { ...@@ -33,6 +33,7 @@ export class FlyingShuttle {
private buildId: string private buildId: string
private pagesDirectory: string private pagesDirectory: string
private distDirectory: string private distDirectory: string
private cacheIdentifier: string
private _shuttleBuildId: string | undefined private _shuttleBuildId: string | undefined
private _restoreSema = new Sema(1) private _restoreSema = new Sema(1)
...@@ -47,10 +48,12 @@ export class FlyingShuttle { ...@@ -47,10 +48,12 @@ export class FlyingShuttle {
buildId, buildId,
pagesDirectory, pagesDirectory,
distDirectory, distDirectory,
cacheIdentifier,
}: { }: {
buildId: string buildId: string
pagesDirectory: string pagesDirectory: string
distDirectory: string distDirectory: string
cacheIdentifier: string
}) { }) {
this.shuttleDirectory = findCacheDir({ this.shuttleDirectory = findCacheDir({
name: 'next-flying-shuttle', name: 'next-flying-shuttle',
...@@ -60,6 +63,7 @@ export class FlyingShuttle { ...@@ -60,6 +63,7 @@ export class FlyingShuttle {
this.buildId = buildId this.buildId = buildId
this.pagesDirectory = pagesDirectory this.pagesDirectory = pagesDirectory
this.distDirectory = distDirectory this.distDirectory = distDirectory
this.cacheIdentifier = cacheIdentifier
} }
hasShuttle = async () => { hasShuttle = async () => {
...@@ -110,9 +114,9 @@ export class FlyingShuttle { ...@@ -110,9 +114,9 @@ export class FlyingShuttle {
return return
} }
// TODO: hash needs to include Next.js environment variables and packages
const hash = crypto const hash = crypto
.createHash('sha1') .createHash('sha1')
.update(this.cacheIdentifier)
.update(await fsReadFile(filePath)) .update(await fsReadFile(filePath))
.digest('hex') .digest('hex')
fileChanged.set(file, hash !== hashes[file]) fileChanged.set(file, hash !== hashes[file])
......
...@@ -13,6 +13,7 @@ import { generateBuildId } from './generate-build-id' ...@@ -13,6 +13,7 @@ import { generateBuildId } from './generate-build-id'
import { isWriteable } from './is-writeable' import { isWriteable } from './is-writeable'
import { import {
collectPages, collectPages,
getCacheIdentifier,
getFileForPage, getFileForPage,
getSpecifiedPages, getSpecifiedPages,
printTreeView, printTreeView,
...@@ -61,6 +62,13 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -61,6 +62,13 @@ export default async function build(dir: string, conf = null): Promise<void> {
) )
} }
const selectivePageBuildingCacheIdentifier = selectivePageBuilding
? await getCacheIdentifier({
pagesDirectory: pagesDir,
env: config.env || {},
})
: 'noop'
let flyingShuttle: FlyingShuttle | undefined let flyingShuttle: FlyingShuttle | undefined
if (isFlyingShuttle) { if (isFlyingShuttle) {
console.log(chalk.magenta('Building with Flying Shuttle enabled ...')) console.log(chalk.magenta('Building with Flying Shuttle enabled ...'))
...@@ -72,6 +80,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -72,6 +80,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
buildId, buildId,
pagesDirectory: pagesDir, pagesDirectory: pagesDir,
distDirectory: distDir, distDirectory: distDir,
cacheIdentifier: selectivePageBuildingCacheIdentifier,
}) })
} }
...@@ -139,6 +148,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -139,6 +148,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
isServer: false, isServer: false,
config, config,
target: config.target, target: config.target,
selectivePageBuildingCacheIdentifier,
entrypoints: entrypoints.client, entrypoints: entrypoints.client,
selectivePageBuilding, selectivePageBuilding,
}), }),
...@@ -148,6 +158,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -148,6 +158,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
isServer: true, isServer: true,
config, config,
target: config.target, target: config.target,
selectivePageBuildingCacheIdentifier,
entrypoints: entrypoints.server, entrypoints: entrypoints.server,
selectivePageBuilding, selectivePageBuilding,
}), }),
......
import crypto from 'crypto'
import findUp from 'find-up'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { promisify } from 'util'
import { recursiveReadDir } from '../lib/recursive-readdir' import { recursiveReadDir } from '../lib/recursive-readdir'
const fsExists = promisify(fs.exists)
const fsReadFile = promisify(fs.readFile)
export function collectPages( export function collectPages(
directory: string, directory: string,
pageExtensions: string[] pageExtensions: string[]
...@@ -102,3 +108,44 @@ export async function getSpecifiedPages( ...@@ -102,3 +108,44 @@ export async function getSpecifiedPages(
.map(page => '/' + path.relative(pagesDir, page.resolved!)) .map(page => '/' + path.relative(pagesDir, page.resolved!))
return resolvedPagePaths.sort() return resolvedPagePaths.sort()
} }
export async function getCacheIdentifier({
pagesDirectory,
env = {},
}: {
pagesDirectory: string
env?: any
}) {
let selectivePageBuildingCacheIdentifier = ''
const envObject = env
? Object.keys(env)
.sort()
// eslint-disable-next-line
.reduce((a, c) => ((a[c] = env[c]), a), {} as any)
: {}
selectivePageBuildingCacheIdentifier += JSON.stringify(envObject)
const pkgPath = await findUp('package.json', { cwd: pagesDirectory })
if (pkgPath) {
const yarnLock = path.join(path.dirname(pkgPath), 'yarn.lock')
const packageLock = path.join(path.dirname(pkgPath), 'package-lock.json')
if (await fsExists(yarnLock)) {
selectivePageBuildingCacheIdentifier += await fsReadFile(yarnLock, 'utf8')
} else if (await fsExists(packageLock)) {
selectivePageBuildingCacheIdentifier += await fsReadFile(
packageLock,
'utf8'
)
} else {
selectivePageBuildingCacheIdentifier += JSON.stringify(require(pkgPath))
}
}
return crypto
.createHash('sha1')
.update(selectivePageBuildingCacheIdentifier)
.digest('hex')
}
...@@ -18,7 +18,7 @@ import { ChunkGraphPlugin } from './webpack/plugins/chunk-graph-plugin' ...@@ -18,7 +18,7 @@ import { ChunkGraphPlugin } from './webpack/plugins/chunk-graph-plugin'
import { WebpackEntrypoints } from './entries' import { WebpackEntrypoints } from './entries'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
export default function getBaseWebpackConfig (dir: string, {dev = false, debug = false, isServer = false, buildId, config, target = 'server', entrypoints, selectivePageBuilding = false}: {dev?: boolean, debug?: boolean, isServer?: boolean, buildId: string, config: any, target?: string, entrypoints: WebpackEntrypoints, selectivePageBuilding?: boolean}): webpack.Configuration { export default function getBaseWebpackConfig (dir: string, {dev = false, debug = false, isServer = false, buildId, config, target = 'server', entrypoints, selectivePageBuilding = false, selectivePageBuildingCacheIdentifier = ''}: {dev?: boolean, debug?: boolean, isServer?: boolean, buildId: string, config: any, target?: string, entrypoints: WebpackEntrypoints, selectivePageBuilding?: boolean, selectivePageBuildingCacheIdentifier?: string}): webpack.Configuration {
const defaultLoaders = { const defaultLoaders = {
babel: { babel: {
loader: 'next-babel-loader', loader: 'next-babel-loader',
...@@ -277,7 +277,7 @@ export default function getBaseWebpackConfig (dir: string, {dev = false, debug = ...@@ -277,7 +277,7 @@ export default function getBaseWebpackConfig (dir: string, {dev = false, debug =
!isServer && new ReactLoadablePlugin({ !isServer && new ReactLoadablePlugin({
filename: REACT_LOADABLE_MANIFEST filename: REACT_LOADABLE_MANIFEST
}), }),
!isServer && selectivePageBuilding && new ChunkGraphPlugin(buildId, path.resolve(dir), { filename: CHUNK_GRAPH_MANIFEST }), !isServer && selectivePageBuilding && new ChunkGraphPlugin(buildId, path.resolve(dir), { filename: CHUNK_GRAPH_MANIFEST, selectivePageBuildingCacheIdentifier }),
...(dev ? (() => { ...(dev ? (() => {
// Even though require.cache is server only we have to clear assets from both compilations // Even though require.cache is server only we have to clear assets from both compilations
// This is because the client compilation generates the build manifest that's used on the server side // This is because the client compilation generates the build manifest that's used on the server side
......
...@@ -50,15 +50,21 @@ export class ChunkGraphPlugin implements Plugin { ...@@ -50,15 +50,21 @@ export class ChunkGraphPlugin implements Plugin {
private buildId: string private buildId: string
private dir: string private dir: string
private filename: string private filename: string
private selectivePageBuildingCacheIdentifier: string
constructor( constructor(
buildId: string, buildId: string,
dir: string, dir: string,
{ filename }: { filename?: string } = {} {
filename,
selectivePageBuildingCacheIdentifier,
}: { filename?: string; selectivePageBuildingCacheIdentifier?: string } = {}
) { ) {
this.buildId = buildId this.buildId = buildId
this.dir = dir this.dir = dir
this.filename = filename || 'chunk-graph-manifest.json' this.filename = filename || 'chunk-graph-manifest.json'
this.selectivePageBuildingCacheIdentifier =
selectivePageBuildingCacheIdentifier || ''
} }
apply(compiler: Compiler) { apply(compiler: Compiler) {
...@@ -186,6 +192,7 @@ export class ChunkGraphPlugin implements Plugin { ...@@ -186,6 +192,7 @@ export class ChunkGraphPlugin implements Plugin {
fs.existsSync(path.join(dir, cur)) fs.existsSync(path.join(dir, cur))
? { ? {
[cur]: createHash('sha1') [cur]: createHash('sha1')
.update(this.selectivePageBuildingCacheIdentifier)
.update(fs.readFileSync(path.join(dir, cur))) .update(fs.readFileSync(path.join(dir, cur)))
.digest('hex'), .digest('hex'),
} }
......
...@@ -105,6 +105,7 @@ ...@@ -105,6 +105,7 @@
"@types/cross-spawn": "6.0.0", "@types/cross-spawn": "6.0.0",
"@types/etag": "1.8.0", "@types/etag": "1.8.0",
"@types/find-cache-dir": "2.0.0", "@types/find-cache-dir": "2.0.0",
"@types/find-up": "2.1.1",
"@types/fresh": "0.5.0", "@types/fresh": "0.5.0",
"@types/loader-utils": "1.1.3", "@types/loader-utils": "1.1.3",
"@types/mkdirp": "0.5.2", "@types/mkdirp": "0.5.2",
......
...@@ -1583,6 +1583,11 @@ ...@@ -1583,6 +1583,11 @@
resolved "https://registry.yarnpkg.com/@types/find-cache-dir/-/find-cache-dir-2.0.0.tgz#6ee79b947b8e51ce8c565fc8278822b2605609db" resolved "https://registry.yarnpkg.com/@types/find-cache-dir/-/find-cache-dir-2.0.0.tgz#6ee79b947b8e51ce8c565fc8278822b2605609db"
integrity sha512-LHAReDNv7IVTE2Q+nPcRBgUZAUKPJIvR7efMrWgx69442KMoMK+QYjtTtK9WGUdaqUYVLkd/0cvCfb55LFWsVw== integrity sha512-LHAReDNv7IVTE2Q+nPcRBgUZAUKPJIvR7efMrWgx69442KMoMK+QYjtTtK9WGUdaqUYVLkd/0cvCfb55LFWsVw==
"@types/find-up@2.1.1":
version "2.1.1"
resolved "https://registry.yarnpkg.com/@types/find-up/-/find-up-2.1.1.tgz#1cd2d240f1ad1f48d32346074724dc3107248a11"
integrity sha512-60LC501bQRN9/3yfVaEEMd7IndaufffL56PBRAejPpUrY304Ps1jfnjNqPw5jmM5R8JHWiKBAe5IHzNcPV41AA==
"@types/fresh@0.5.0": "@types/fresh@0.5.0":
version "0.5.0" version "0.5.0"
resolved "https://registry.yarnpkg.com/@types/fresh/-/fresh-0.5.0.tgz#4d09231027d69c4369cfb01a9af5ef083d0d285f" resolved "https://registry.yarnpkg.com/@types/fresh/-/fresh-0.5.0.tgz#4d09231027d69c4369cfb01a9af5ef083d0d285f"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment