chore: blog post publish cleanup (#7873)

This commit is contained in:
Joshua Chen 2022-08-01 18:00:01 +08:00 committed by GitHub
parent e8a11da805
commit 1a62b41e31
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 106 additions and 110 deletions

View file

@ -8,46 +8,95 @@
import fs from 'fs-extra'; import fs from 'fs-extra';
import path from 'path'; import path from 'path';
import {fileURLToPath} from 'url'; import {fileURLToPath} from 'url';
import {program} from 'commander';
import logger from '@docusaurus/logger'; import logger from '@docusaurus/logger';
import sharp from 'sharp'; import sharp from 'sharp';
import imageSize from 'image-size'; import imageSize from 'image-size';
const allImages = ( // You can use it as:
await fs.readdir(new URL('../../website/src/data/showcase', import.meta.url)) //
).filter((file) => ['.png', 'jpg', '.jpeg'].includes(path.extname(file))); // # Resize all images in showcase (which is most likely)
// node admin/scripts/resizeImage.js
//
// # Resize specified images / all images in a folder
// # This does not read folders recursively as of now
// node admin/scripts/resizeImage.js image1.png some-folder ...
//
// By default, showcase images are resized to 640×320; everything else is
// resized to width 1000. You can explicitly give a width/height as arguments.
// node admin/scripts/resizeImage.js --width 640 --height 320 image1.png
const [, , ...selectedImages] = process.argv; function maybeParseInt(n) {
const images = selectedImages.length > 0 ? selectedImages : allImages; const res = Number.parseInt(n, 10);
if (Number.isNaN(res)) {
return undefined;
}
return res;
}
const stats = { const showcasePath = 'website/src/data/showcase';
program
.arguments('[imagePaths...]')
.option('-w, --width <width>', 'Image width', maybeParseInt)
.option('-h, --height <height>', 'Image height', maybeParseInt)
.action(async (imagePaths, options) => {
if (imagePaths.length === 0) {
imagePaths.push(showcasePath);
}
const rootDir = fileURLToPath(new URL('../..', import.meta.url));
const images = (
await Promise.all(
imagePaths.map(async (p) =>
path.extname(p)
? [path.resolve(rootDir, p)]
: (await fs.readdir(p)).map((f) => path.resolve(rootDir, p, f)),
),
)
)
.flat()
.filter((p) => ['.png', 'jpg', '.jpeg'].includes(path.extname(p)));
const stats = {
skipped: 0, skipped: 0,
resized: 0, resized: 0,
}; };
await Promise.all( await Promise.all(
images.map(async (img) => { images.map(async (imgPath) => {
const imgPath = fileURLToPath(
new URL(`../../website/src/data/showcase/${img}`, import.meta.url),
);
const {width, height} = imageSize(imgPath); const {width, height} = imageSize(imgPath);
if (width === 640 && height === 320 && imgPath.endsWith('.png')) { const targetWidth =
options.width ?? (imgPath.includes(showcasePath) ? 640 : 1000);
const targetHeight =
options.height ?? (imgPath.includes(showcasePath) ? 320 : undefined);
if (
width <= targetWidth &&
(!targetHeight || height <= targetHeight) &&
imgPath.endsWith('.png')
) {
// Do not emit if not resized. Important because we can't guarantee // Do not emit if not resized. Important because we can't guarantee
// idempotency during resize -> optimization // idempotency during resize -> optimization
stats.skipped += 1; stats.skipped += 1;
return; return;
} }
logger.info`Resized path=${imgPath}: Before number=${width}×number=${height}`; logger.info`Resized path=${imgPath}: before number=${width}×number=${height}; now number=${targetWidth}×number=${
targetHeight ?? Math.floor((height / width) * targetWidth)
}`;
const data = await sharp(imgPath) const data = await sharp(imgPath)
.resize(640, 320, {fit: 'cover', position: 'top'}) .resize(targetWidth, targetHeight, {fit: 'cover', position: 'top'})
.png() .png()
.toBuffer(); .toBuffer();
await fs.writeFile(imgPath.replace(/jpe?g/, 'png'), data); await fs.writeFile(imgPath.replace(/jpe?g/, 'png'), data);
stats.resized += 1; stats.resized += 1;
}), }),
); );
console.log(`Showcase images resizing complete. logger.info`Images resizing complete.
${JSON.stringify(stats, null, 2)}`); resized: number=${stats.resized}
skipped: number=${stats.skipped}`;
});
program.parse(process.argv);
// You should also run // You should also run
// optimizt `find website/src/data/showcase -type f -name '*.png'`. // optimizt `find website/src/data/showcase -type f -name '*.png'`.

View file

@ -1,53 +0,0 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import fs from 'fs-extra';
import path from 'path';
import logger from '@docusaurus/logger';
import sharp from 'sharp';
import imageSize from 'image-size';
import globby from 'globby';
// TODO duplicate temporary script: factorize!
const imgDir = 'website/blog/2022-08-01-announcing-docusaurus-2.0/img';
const imgWidth = 1200;
const allImages = (await globby(`${imgDir}/**`)).filter((file) =>
['.png', 'jpg', '.jpeg'].includes(path.extname(file)),
);
const [, , ...selectedImages] = process.argv;
const images = selectedImages.length > 0 ? selectedImages : allImages;
const stats = {
skipped: 0,
resized: 0,
};
await Promise.all(
images.map(async (imgPath) => {
const {width, height} = imageSize(imgPath);
if (width === imgWidth && imgPath.endsWith('.png')) {
// Do not emit if not resized. Important because we can't guarantee
// idempotency during resize -> optimization
stats.skipped += 1;
return;
}
logger.info`Resized path=${imgPath}: Before number=${width}×number=${height}`;
const data = await sharp(imgPath)
.resize(imgWidth)
.png({quality: 100})
.toBuffer();
await fs.writeFile(imgPath.replace(/jpe?g/, 'png'), data);
stats.resized += 1;
}),
);
console.log(`Blog images resizing complete.
${JSON.stringify(stats, null, 2)}`);

View file

@ -1,6 +1,7 @@
abernathyca abernathyca
adriaan adriaan
agan agan
alexbdebrie
alexey alexey
algoliasearch algoliasearch
anonymized anonymized
@ -50,9 +51,12 @@ contravariance
corejs corejs
crawlable crawlable
creativecommons creativecommons
csapo
cssnano cssnano
csvg csvg
customizability customizability
dabit
dabit
daishi daishi
datagit datagit
datas datas
@ -63,6 +67,7 @@ deduplicated
déja déja
deps deps
devcontainers devcontainers
devs
devspace devspace
devto devto
dmitry dmitry
@ -100,6 +105,7 @@ formik
fouc fouc
froms froms
funboxteam funboxteam
gabrielcsapo
getopts getopts
gitpod gitpod
globbing globbing
@ -109,7 +115,10 @@ goyal
gruntfuggly gruntfuggly
gtag gtag
hahaha hahaha
hamel
hardcoding hardcoding
hasura
heavener
héctor héctor
héllô héllô
heuristical heuristical
@ -118,6 +127,7 @@ hola
horiz horiz
hostman hostman
hoverable hoverable
husain
ianad ianad
idempotency idempotency
immer immer
@ -126,11 +136,13 @@ inlines
intelli intelli
interactiveness interactiveness
interpolatable interpolatable
investec
jakepartusch jakepartusch
jamstack jamstack
janvier janvier
javadoc javadoc
jmarcey jmarcey
jodyheavener
joshcena joshcena
jscodeshift jscodeshift
jssdk jssdk
@ -157,6 +169,7 @@ marcey
marocchino marocchino
massoud massoud
mathjax mathjax
maxlynch
maxresdefault maxresdefault
mdast mdast
mdxa mdxa
@ -195,7 +208,7 @@ npmrc
nprogress nprogress
ntfs ntfs
nuxt nuxt
OShannessy oshannessy
onboarded onboarded
openapi openapi
opensearch opensearch
@ -204,6 +217,7 @@ opensource
optimizt optimizt
optind optind
orta orta
outerbounds
overrideable overrideable
pageview pageview
palenight palenight
@ -212,6 +226,7 @@ palo
paraiso paraiso
pathinfo pathinfo
pathnames pathnames
paularmstrong
pbcopy pbcopy
pcss pcss
peaceiris peaceiris
@ -222,6 +237,7 @@ picomatch
playbtn playbtn
pluggable pluggable
plushie plushie
plushies
pnpm pnpm
posthog posthog
preactjs preactjs
@ -250,6 +266,7 @@ qovery
quasis quasis
quddus quddus
quddús quddús
quickwit
quotify quotify
rachelnabors rachelnabors
ramón ramón
@ -281,6 +298,8 @@ sensical
serializers serializers
setaf setaf
setext setext
shiki
shiki
showinfo showinfo
sida sida
simen simen
@ -288,11 +307,14 @@ slorber
sluggified sluggified
sluggifies sluggifies
sluggify sluggify
solana
solana
spâce spâce
stackblitz stackblitz
stackblitzrc stackblitzrc
strikethrough strikethrough
strikethroughs strikethroughs
styl
stylelint stylelint
stylelintrc stylelintrc
subdir subdir
@ -310,11 +332,11 @@ subsubsubfolder
sucipto sucipto
supabase supabase
svgr svgr
styl
swizzlable swizzlable
teik teik
templating templating
thanos thanos
therox
toolset toolset
toplevel toplevel
transifex transifex
@ -325,6 +347,7 @@ treeify
treosh treosh
triaging triaging
tses tses
twoslash
typecheck typecheck
typechecks typechecks
typedoc typedoc
@ -348,6 +371,7 @@ vetter
vfile vfile
vicenti vicenti
vieira vieira
viet
viewports viewports
vinnik vinnik
vjeux vjeux
@ -367,27 +391,3 @@ yangshunz
zhou zhou
zoomable zoomable
zpao zpao
paularmstrong
devs
Viet
dabit
Dabit
alexbdebrie
Investec
Quickwit
Hamel
Husain
Outerbounds
jodyheavener
Heavener
maxlynch
gabrielcsapo
Csapo
Hasura
Solana
solana
shiki
twoslash
Shiki
Therox
plushies