@gravityforms/gulp-tasks
Version:
Configurable Gulp tasks for use in Gravity Forms projects.
81 lines (69 loc) • 2.79 kB
JavaScript
const fs = require( 'fs' );
const fsp = require( 'fs' ).promises;
const path = require( 'path' );
const sendSlackMessage = require( '../utils/send-slack-message' );
const { loadEnv } = require( '../utils/tools' );
const getConfig = require('../../config');
const { config } = getConfig();
const { exec } = require( 'child_process' );
const { promisify } = require( 'util' );
const execAsync = promisify( exec );
loadEnv( config.paths.root );
const rootPath = config?.paths?.root || '';
const fileName = config?.settings?.rootPluginFile || '';
const restoreRootFile = async () => {
const rootFilePath = path.join( rootPath, fileName );
const backupFilePath = path.join( rootPath, `${ fileName }.old` );
if ( fs.existsSync( backupFilePath ) ) {
await fsp.copyFile( backupFilePath, rootFilePath );
await fsp.unlink( backupFilePath );
}
};
const removePublishFiles = async () => {
// Check if in production mode and exit early
if ( process.env.GULP_PRODUCTION_MODE === 'true' ) {
console.log( 'Skipping deleting production files because GULP_PRODUCTION_MODE is set to true.' );
return;
}
// Read .gitignore file and parse its content into an array
const gitignorePath = path.join( rootPath, '.gitignore' );
let ignoredPaths = [];
if ( fs.existsSync( gitignorePath ) ) {
const gitignoreContent = await fsp.readFile( gitignorePath, 'utf8' );
ignoredPaths = gitignoreContent
.split( /\r?\n/ )
.filter( line => ! line.startsWith( '#' ) && line.trim() !== '' )
.map( line => line.startsWith( '/' ) ? line.substring( 1 ) : line );
}
const directoriesToRemove = [ 'checksums', 'environment', 'vendor-environments' ]
.filter( dir => ignoredPaths.some( ignoredPath => dir.includes( ignoredPath ) || ignoredPath.includes( dir ) ) );
// Remove directories if they exist and are matched in .gitignore
for ( const directory of directoriesToRemove ) {
const dirPath = path.join( rootPath, directory );
if ( fs.existsSync( dirPath ) ) {
await fsp.rm( dirPath, { recursive: true, force: true } );
console.log( `Removed directory: ${ directory }` );
}
}
};
const restoreDevFiles = async () => {
// Check if in production mode and exit early
if ( process.env.GULP_PRODUCTION_MODE === 'true' ) {
console.log( 'Skipping recreating dev files because GULP_PRODUCTION_MODE is set to true.' );
return;
}
await execAsync( `cd "${ rootPath }" && npm run dist` );
};
( async () => {
try {
await restoreRootFile();
await removePublishFiles();
await restoreDevFiles();
console.log( 'Restored project state.' );
} catch ( err ) {
console.error( 'An error occurred during restoration:', err );
await sendSlackMessage( `Failed to restore state during build: ${ err.message }`, 'error' );
process.exit( 1 );
}
} )();