|
5 | 5 | */
|
6 | 6 | const chalk = require( 'chalk' );
|
7 | 7 | const fs = require( 'fs' ); // eslint-disable-line id-length
|
| 8 | +const { sync: glob } = require( 'fast-glob' ); |
| 9 | +const { hashElement } = require( 'folder-hash' ); |
8 | 10 | const path = require( 'path' );
|
9 | 11 | const postcss = require( 'postcss' );
|
10 | 12 | const rtlcss = require( 'rtlcss' );
|
@@ -88,6 +90,43 @@ async function maybeBuildPostCSS( inputDir, outputDir ) {
|
88 | 90 | }
|
89 | 91 | }
|
90 | 92 |
|
| 93 | +/** |
| 94 | + * Update the block.json version field with the hash of the build. |
| 95 | + * |
| 96 | + * @param {string} basePath |
| 97 | + */ |
| 98 | +async function setBlockVersion( basePath ) { |
| 99 | + const project = path.basename( basePath ); |
| 100 | + |
| 101 | + // Find any block.json files under the project's `build` dir. |
| 102 | + const files = glob( '**/build/**/block.json', { |
| 103 | + absolute: true, |
| 104 | + cwd: basePath, |
| 105 | + } ); |
| 106 | + |
| 107 | + if ( ! files.length ) { |
| 108 | + console.log( chalk.red( `Couldn't find block.json for ${ project }` ) ); |
| 109 | + return; |
| 110 | + } |
| 111 | + |
| 112 | + const options = { |
| 113 | + algo: 'sha1', |
| 114 | + encoding: 'hex', |
| 115 | + }; |
| 116 | + |
| 117 | + const hash = await hashElement( basePath, options ); |
| 118 | + |
| 119 | + files.forEach( ( blockJson ) => { |
| 120 | + const blockJsonContents = require( blockJson ); |
| 121 | + blockJsonContents.version = blockJsonContents.version?.replace( /(^|-)[0-9a-f]{40}$/, '' ) || ''; |
| 122 | + blockJsonContents.version += ( blockJsonContents.version ? '-' : '' ) + hash.hash; |
| 123 | + |
| 124 | + fs.writeFileSync( blockJson, JSON.stringify( blockJsonContents, null, '\t' ) ); |
| 125 | + } ); |
| 126 | + |
| 127 | + console.log( chalk.green( `block.json version set for ${ project } to ${ hash.hash }` ) ); |
| 128 | +} |
| 129 | + |
91 | 130 | // If we have more paths that need building, we could switch this to an array.
|
92 | 131 | const projectPath = path.join( path.dirname( __dirname ), 'mu-plugins/blocks' );
|
93 | 132 | const cliProjects = process.argv.slice( 2 );
|
@@ -115,6 +154,8 @@ projects.forEach( async ( file ) => {
|
115 | 154 | await maybeBuildBlock( path.resolve( path.join( basePath, 'src' ) ), outputDir );
|
116 | 155 |
|
117 | 156 | await maybeBuildPostCSS( path.resolve( path.join( basePath, 'postcss' ) ), outputDir );
|
| 157 | + |
| 158 | + await setBlockVersion( basePath ); |
118 | 159 | } catch ( error ) {
|
119 | 160 | console.log( chalk.red( `Error in ${ file }:` ), error.message );
|
120 | 161 | }
|
|
0 commit comments