Gatsby build script using php
Recently i was creating a gatsby static site with product pages. I used gatsby + strapi for generating the static pages. Whenever i update the product details in strapi i need generate / build the static pages using gatsby clean and build commands.
To automate the gatsby clean, build, moving the files from one folder another folder (as my gatsby folder and static site folder are different) i created a php script.
First create shell script (ex:gatsbybuild.sh) with proper permission
//gatsbybuild.sh
gatsby clean
gatsby build
Next create php file to gatsby build and move the static pages to respective folder in sever
Assuming 'gatsbyserver' folder is the gatsby setup.
<?php
//gatsbybuild.php
$output = shell_exec('./gatsbybuild.sh');
print_r($output);
//after gatsby build move the generated static pages to site root folder.
rcopy("/var/www/html/gatsbyserver/public", "/var/www/html/");
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir."/".$object) && !is_link($dir."/".$object))
rrmdir($dir."/".$object);
else
unlink($dir."/".$object);
}
}
rmdir($dir);
}
}
// Function to Copy folders and files
function rcopy($src, $dst) {
if (file_exists ( $dst ))
rrmdir ( $dst );
if (is_dir ( $src )) {
mkdir ( $dst );
$files = scandir ( $src );
foreach ( $files as $file )
if ($file != "." && $file != "..")
rcopy ( "$src/$file", "$dst/$file" );
} else if (file_exists ( $src ))
copy ( $src, $dst );
}
?>
Important Note: Make sure the permissions for the folders are www-data:www-data.