Skip to content

Instantly share code, notes, and snippets.

@pcdinh
Forked from stubbetje/autorun.php
Created December 9, 2009 09:03
Show Gist options
  • Save pcdinh/252354 to your computer and use it in GitHub Desktop.
Save pcdinh/252354 to your computer and use it in GitHub Desktop.
#!/usr/bin/env php
<?php
if( ! function_exists( 'inotify_init' ) ) {
die_with_error( 'This script needs the inotify module' );
}
// usage: $0 path [path ...] -- command
$args = $_SERVER['argv'];
array_shift( $args );
$toWatch = array();
while( false !== ( $arg = array_shift( $args ) ) ) {
if( $arg === '--' ) {
break;
} else {
if( ! file_exists( $arg ) ) {
die_with_error( 'Cannot watch "%s", file or directory doest not exist' , $arg );
}
$toWatch[] = $arg;
}
}
$command = implode( ' ' , array_map( 'escapeshellarg' , $args ) );
if( false === ( $fd = inotify_init() ) ) {
die_with_error( 'inotify_init() failed' );
}
$countFile = $countDir = 0;
foreach( $toWatch as $watchThis ) {
//echo 'watching: ' , $watchThis , PHP_EOL;
inotify_add_watch( $fd , $watchThis , IN_MODIFY );
if( is_dir( $watchThis ) ) {
$countDir++;
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $watchThis ) , RecursiveIteratorIterator::SELF_FIRST ) as $it ) {
if( $it->isDir() ) {
//echo 'watching: ' , $it->getPathname() , PHP_EOL;
inotify_add_watch( $fd , $it->getPathname() , IN_MODIFY );
$countDir++;
}
}
} else {
$countFile++;
}
}
echo 'watching ' , ( $countDir ? $countDir . ' directories' : null ) , ( $countFile ? ( $countDir ? ' and ' : null ) . $countFile . ' files' : null ) , PHP_EOL;
echo 'waiting for changes...' , PHP_EOL;
while( false !== ( $events = inotify_read( $fd ) ) ) {
foreach( $events as $event ) {
echo '[' , translate_inotify_constant( $event['mask'] ) , '] ' , $event['name'] , ' : ' , json_encode( $event ) , PHP_EOL;
echo 'executing: ' , $command , PHP_EOL;
system( $command );
/* eat up events that may have been triggered by the command */
while( inotify_queue_len( $fd ) > 0 ) {
$events = inotify_read( $fd );
}
}
echo 'waiting for changes...' , PHP_EOL;
}
fclose( $fd );
function die_with_error( $msg )
{
$args = func_get_args();
array_shift( $args );
vprintf( $msg . PHP_EOL , $args );
exit -1;
}
function translate_inotify_constant( $value )
{
static $const = null;
if( null === $const ) {
$const = get_defined_constants( true );
$const = array_flip( $const['inotify'] );
}
return array_key_exists( $value , $const ) ? $const[ $value ] : $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment