Skip to content

Commit

Permalink
Merge pull request #47 from dc7290/feature/bench
Browse files Browse the repository at this point in the history
chore: 🤖 Enable benchmark testing
  • Loading branch information
dc7290 authored May 24, 2022
2 parents fd97e69 + e8b2a81 commit 8e1a4d3
Show file tree
Hide file tree
Showing 13 changed files with 106 additions and 16 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ dist
/__tests__/cli/cache/results
/__tests__/components/image/manifest.json

# benchmark
/bench/fixtures/results

# next.js
.next
out
Expand Down
Binary file added bench/fixtures/default.avif
Binary file not shown.
Binary file added bench/fixtures/default.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added bench/fixtures/default.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added bench/fixtures/default.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added bench/fixtures/default.webp
Binary file not shown.
43 changes: 43 additions & 0 deletions bench/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import path from 'path'

import Benchmark from 'benchmark'
import sharp from 'sharp'

import { optimizeImages } from '../src/cli'

sharp.cache(false)

const suite = new Benchmark.Suite()

suite
.add('current', async () => {
await optimizeImages({
manifestJsonPath: path.resolve(__dirname, 'manifest.json'),
noCache: true,
config: {
outDir: 'bench/fixtures',
},
terse: true,
})
})
.add('new', async () => {
// await newOptimizeImages({
// manifestJsonPath: path.resolve(__dirname, 'manifest.json'),
// noCache: true,
// config: {
// outDir: 'bench/fixtures',
// },
// terse: true,
// })
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.on('cycle', (event: any) => {
// eslint-disable-next-line no-console
console.log(String(event.target))
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.on('complete', function (this: any) {
// eslint-disable-next-line no-console
console.log(`Fastest is ${this.filter('fastest').map('name')}`)
})
.run({ async: true })
9 changes: 9 additions & 0 deletions bench/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

{"output":"/results/images/default_640_75.png","src":"/default.png","width":640,"quality":75,"extension":"png"}
{"output":"/results/images/default_750_75.png","src":"/default.png","width":750,"quality":75,"extension":"png"}
{"output":"/results/images/default_828_75.png","src":"/default.png","width":828,"quality":75,"extension":"png"}
{"output":"/results/images/default_1080_75.png","src":"/default.png","width":1080,"quality":75,"extension":"png"}
{"output":"/results/images/default_1200_75.png","src":"/default.png","width":1200,"quality":75,"extension":"png"}
{"output":"/results/images/default_1920_75.png","src":"/default.png","width":1920,"quality":75,"extension":"png"}
{"output":"/results/images/default_2048_75.png","src":"/default.png","width":2048,"quality":75,"extension":"png"}
{"output":"/results/images/default_3840_75.png","src":"/default.png","width":3840,"quality":75,"extension":"png"}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"@swc/core": "1.2.189",
"@testing-library/react": "13.2.0",
"@tsconfig/strictest": "1.0.1",
"@types/benchmark": "2.1.1",
"@types/cli-progress": "3.11.0",
"@types/jest": "27.5.1",
"@types/lodash.uniqwith": "4.5.7",
Expand All @@ -62,6 +63,7 @@
"@types/sharp": "0.30.2",
"@typescript-eslint/eslint-plugin": "5.25.0",
"@typescript-eslint/parser": "5.25.0",
"benchmark": "2.1.4",
"chokidar": "3.5.3",
"conventional-changelog-conventionalcommits": "4.6.3",
"eslint": "8.16.0",
Expand Down
43 changes: 29 additions & 14 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,12 @@ export const getOptimizeResult: GetOptimizeResult = async ({
const outputDir = outputPath.split('/').slice(0, -1).join('/')
fs.mkdirSync(outputDir, { recursive: true })

const imageBuffer = fs.readFileSync(originalFilePath)

// Cache process
if (!noCache) {
const cacheImagesFindIndex = cacheImages.findIndex((cacheImage) => cacheImage.output === output)
const hash = createHash('sha256').update(fs.readFileSync(originalFilePath)).digest('hex')
const hash = createHash('sha256').update(imageBuffer).digest('hex')

if (cacheImagesFindIndex === -1) {
cacheImages.push({ output, hash })
Expand All @@ -70,7 +72,6 @@ export const getOptimizeResult: GetOptimizeResult = async ({
}
}

const imageBuffer = fs.readFileSync(originalFilePath)
const image = sharp(imageBuffer, { sequentialRead: true })

image.rotate().resize({ width, withoutEnlargement: true })
Expand Down Expand Up @@ -110,9 +111,10 @@ type OptimizeImagesProps = {
manifestJsonPath: string
noCache: boolean
config: Config
terse?: boolean
}

export const optimizeImages = async ({ manifestJsonPath, noCache, config }: OptimizeImagesProps) => {
export const optimizeImages = async ({ manifestJsonPath, noCache, config, terse = false }: OptimizeImagesProps) => {
const destDir = path.resolve(cwd, config.outDir ?? 'out')

let manifest: Manifest
Expand All @@ -122,10 +124,17 @@ export const optimizeImages = async ({ manifestJsonPath, noCache, config }: Opti
throw Error(typeof error === 'string' ? error : 'Unexpected error.')
}

cliProgressBarStart(manifest.length)
if (!terse) {
cliProgressBarStart(manifest.length)
}

let cacheImages: CacheImages = []

if (!noCache) {
createCacheDir()
cacheImages = readCacheManifest()
}

createCacheDir()
const cacheImages = readCacheManifest()
const promises: Promise<void>[] = []

let measuredCache = 0
Expand All @@ -142,7 +151,7 @@ export const optimizeImages = async ({ manifestJsonPath, noCache, config }: Opti
cacheDir: defaultCacheDir,
cacheMeasurement: () => (measuredCache += 1),
nonCacheMeasurement: () => (measuredNonCache += 1),
cliProgressBarIncrement,
cliProgressBarIncrement: terse ? () => undefined : cliProgressBarIncrement,
originalFilePath,
sharpOptions: config.sharpOptions ?? {},
...item,
Expand All @@ -152,13 +161,19 @@ export const optimizeImages = async ({ manifestJsonPath, noCache, config }: Opti

try {
await Promise.all(promises)
writeCacheManifest(cacheImages)
// eslint-disable-next-line no-console
console.log(
`Cache assets: ${measuredCache}, NonCache assets: ${measuredNonCache}\n`,
'\x1b[35m\nSuccessful optimization!',
'\x1b[39m'
)

if (!noCache) {
writeCacheManifest(cacheImages)
}

if (!terse) {
// eslint-disable-next-line no-console
console.log(
`Cache assets: ${measuredCache}, NonCache assets: ${measuredNonCache}\n`,
'\x1b[35m\nSuccessful optimization!',
'\x1b[39m'
)
}
} catch (error) {
console.error('Error processing files', error)
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/getConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export type Config = {

const getConfig = (): Config => {
try {
if (process.env.NODE_ENV === 'test') {
if (process.env['NODE_ENV'] === 'test') {
return require(`../../${process.env['TEST_CONFIG_PATH']}`)
}

Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
"compilerOptions": {
"jsx": "react"
},
"include": ["./src/**/*.ts", "./src/**/*.tsx", "./__tests__/**/*.test.ts", "./__tests__/**/*.test.tsx"]
"include": ["./src/**/*.ts", "./src/**/*.tsx", "./__tests__/**/*.test.ts", "./__tests__/**/*.test.tsx", "bench/index.ts"]
}
18 changes: 18 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,11 @@
dependencies:
"@babel/types" "^7.3.0"

"@types/[email protected]":
version "2.1.1"
resolved "https://registry.yarnpkg.com/@types/benchmark/-/benchmark-2.1.1.tgz#d763df29717d93aa333eb11f421ef383a5df5673"
integrity sha512-XmdNOarpSSxnb3DE2rRFOFsEyoqXLUL+7H8nSGS25vs+JS0018bd+cW5Ma9vdlkPmoTHSQ6e8EUFMFMxeE4l+g==

"@types/[email protected]":
version "3.11.0"
resolved "https://registry.yarnpkg.com/@types/cli-progress/-/cli-progress-3.11.0.tgz#ec79df99b26757c3d1c7170af8422e0fc95eef7e"
Expand Down Expand Up @@ -2166,6 +2171,14 @@ before-after-hook@^2.2.0:
resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.2.tgz#a6e8ca41028d90ee2c24222f201c90956091613e"
integrity sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ==

[email protected]:
version "2.1.4"
resolved "https://registry.yarnpkg.com/benchmark/-/benchmark-2.1.4.tgz#09f3de31c916425d498cc2ee565a0ebf3c2a5629"
integrity sha512-l9MlfN4M1K/H2fbhfMy3B7vJd6AGKJVQn2h6Sg/Yx+KckoUA7ewS5Vv6TjSq18ooE1kS9hhAlQRH3AkXIh/aOQ==
dependencies:
lodash "^4.17.4"
platform "^1.3.3"

bin-links@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/bin-links/-/bin-links-3.0.1.tgz#cc70ffb481988b22c527d3e6e454787876987a49"
Expand Down Expand Up @@ -6072,6 +6085,11 @@ pkg-dir@^4.2.0:
dependencies:
find-up "^4.0.0"

platform@^1.3.3:
version "1.3.6"
resolved "https://registry.yarnpkg.com/platform/-/platform-1.3.6.tgz#48b4ce983164b209c2d45a107adb31f473a6e7a7"
integrity sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==

[email protected]:
version "8.4.5"
resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.5.tgz#bae665764dfd4c6fcc24dc0fdf7e7aa00cc77f95"
Expand Down

1 comment on commit 8e1a4d3

@vercel
Copy link

@vercel vercel bot commented on 8e1a4d3 May 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.