@gravityforms/gulp-tasks
Version:
Configurable Gulp tasks for use in Gravity Forms projects.
110 lines (88 loc) • 2.95 kB
JavaScript
import fs from 'node:fs/promises';
import { createRequire } from 'node:module';
import getConfig from '../../config.js';
import getGoogleDriveConfig from '../utils/get-google-drive-config.js';
import sendSlackMessage from '../utils/send-slack-message.js';
import { loadEnv } from '../utils/tools.js';
const cjsRequire = createRequire( import.meta.url );
const { UtilsGDrive } = cjsRequire( 'utils-google-drive' );
const { config } = getConfig();
loadEnv( config.paths.root );
const uploadToDrive = async () => {
if ( process.env.GULP_PRODUCTION_MODE !== 'true' ) {
console.log( 'Skipping uploading to Google Drive because GULP_PRODUCTION_MODE is not set to true.' );
return;
}
const {
files = [],
path: uploadPath = '',
} = await getGoogleDriveConfig();
const credentials = process.env.GOOGLE_DRIVE_CREDENTIALS;
const token = process.env.GOOGLE_DRIVE_TOKEN;
const sharedDriveId = process.env.GOOGLE_DRIVE_SHARED_ID;
if ( ! credentials || ! token || ! sharedDriveId || ! uploadPath || ! files.length ) {
console.log( 'Missing one or more of: google drive credentials, token, files, uploadPath, or driveId, aborting.' );
process.exit( 0 );
}
const utilsGDrive = new UtilsGDrive( {
credentials,
token,
} );
try {
const parentFileId = await utilsGDrive.makeNestedFolder( {
folderPath: uploadPath,
options: {
isSharedDrive: true,
sharedDriveId,
},
} );
let checksumFolderId = '';
const uploadPromises = [];
let firstFileId = '';
if ( files.length ) {
const firstFilePath = files[ 0 ];
await fs.access( firstFilePath );
firstFileId = await utilsGDrive.upload( {
localPath: firstFilePath,
parentIdentifiers: parentFileId,
sharedDriveId,
update: true,
} );
}
await fs.writeFile( 'process_data.json', JSON.stringify( { googleDriveLink: `https://drive.google.com/file/d/${ firstFileId }/view?usp=sharing` } ), 'utf8' );
for ( const filePath of files.slice( 1 ) ) {
let currentParentId = parentFileId;
if ( filePath.includes( 'checksums/' ) ) {
if ( ! checksumFolderId ) {
checksumFolderId = await utilsGDrive.makeNestedFolder( {
folderPath: `${ uploadPath }/checksums`,
options: {
isSharedDrive: true,
sharedDriveId,
},
} );
}
currentParentId = checksumFolderId;
}
try {
await fs.access( filePath );
const uploadPromise = utilsGDrive.upload( {
localPath: filePath,
parentIdentifiers: currentParentId,
sharedDriveId,
update: true,
} );
uploadPromises.push( uploadPromise );
} catch ( err ) {
console.warn( `File ${ filePath } does not exist or couldn't be read.` );
}
}
await Promise.all( uploadPromises );
} catch ( err ) {
console.error( 'An error occurred:', err );
await sendSlackMessage( `Google drive upload failed during build: ${ err.message }`, 'error' );
process.exit( 1 );
}
};
uploadToDrive();