1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
|
<?php
/*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/Task.php';
include_once 'phing/types/FileList.php';
include_once 'phing/types/FileSet.php';
/**
* Executes a command on the (filtered) file list/set.
* (Loosely based on the "Ant Apply" task - http://ant.apache.org/manual/Tasks/apply.html)
*
* @author Utsav Handa <handautsav at hotmail dot com>
* @package phing.tasks.system
*
* @todo Add support for mapper, targetfile expressions
*/
class ApplyTask extends Task {
/**
* Configuration(s)
*
*/
//[TBA]const TARGETFILE_ID = '__TARGETFILE__';
const SOURCEFILE_ID = '__SOURCEFILE__';
/**
* File Set/List of files.
* @var array
*/
protected $filesets = array();
protected $filelists = array();
/**
* Commandline managing object
* @var commandline
*/
protected $commandline;
/**
* Working directory
* @var phingfile
*/
protected $dir;
protected $currentdirectory;
/**
* Command to be executed
* @var string
*/
protected $realCommand;
/**
* Escape (shell) command using 'escapeshellcmd' before execution
* @var boolean
*/
protected $escape = false;
/**
* Where to direct output
* @var phingfile
*/
protected $output;
/**
* Where to direct error
* @var phingfile
*/
protected $error;
/**
* Whether output should be appended to or overwrite an existing file
* @var boolean
*/
protected $appendoutput = false;
/**
* Runs the command only once, appending all files as arguments
* else command will be executed once for every file.
* @var boolean
*/
protected $parallel = false;
/**
* Whether source file name should be added to the end of command automatically
* @var boolean
*/
protected $addsourcefile = true;
/**
* Whether to spawn the command execution as a background process
* @var boolean
*/
protected $spawn = false;
/**
* Property name to set with return value
* @var string
*/
protected $returnProperty;
/**
* Property name to set with output value
* @var string
*/
protected $outputProperty;
/**
* Whether the filenames should be passed on the command line as relative pathnames (relative to the base directory of the corresponding fileset/list)
* @var boolean
*/
protected $relative = false;
/**
* Operating system information
* @var string
*/
protected $os;
protected $currentos;
protected $osvariant;
/**
* Logging level for status messages
* @var integer
*/
protected $loglevel = null;
/**
* Fail on command that exits with a returncode other than zero
* @var boolean
*
*/
protected $failonerror = false;
/**
* Whether to use PHP's passthru() function instead of exec()
* @var boolean
*/
protected $passthru = false;
/**
* Whether to use forward-slash as file-separator on the file names
* @var boolean
*/
protected $forwardslash = false;
/**
* Limit the amount of parallelism by passing at most this many sourcefiles at once
* (Set it to <= 0 for unlimited)
* @var integer
*/
protected $maxparallel = 0;
/**
* Supports embedded <filelist> element.
*
* @return FileList
*/
public function createFileList() {
$num = array_push($this->filelists, new FileList());
return $this->filelists[$num-1];
}
/**
* Nested adder, adds a set of files (nested fileset attribute).
*
* @return void
*/
public function addFileSet(FileSet $fs) {
$this->filesets[] = $fs;
}
/**
* Sets the command executable information
*
* @param string $executable Executable path
*
* @return void
*/
public function setExecutable($executable) {
$this->commandline->setExecutable( (string) $executable);
}
/**
* Specify the working directory for the command execution.
*
* @param PhingFile $dir Set the working directory as specified
*
* @return void
*/
public function setDir(PhingFile $dir) {
$this->dir = $dir;
}
/**
* Escape command using 'escapeshellcmd' before execution
*
* @param boolean $escape Escape command before execution
*
* @return void
*/
public function setEscape($escape) {
$this->escape = (bool) $escape;
}
/**
* File to which output should be written
*
* @param PhingFile $outputfile Output log file
*
* @return void
*/
public function setOutput(PhingFile $outputfile) {
$this->output = $outputfile;
}
/**
* File to which output should be written
*
* @param PhingFile $outputfile Output log file
*
* @return void
*/
public function setAppend($append) {
$this->appendoutput = (bool) $append;
}
/**
* Run the command only once, appending all files as arguments
*
* @param Boolean $parallel Identifier for files as arguments appending
*
* @return void
*/
public function setParallel($parallel) {
$this->parallel = (bool) $parallel;
}
/**
* To add the source filename at the end of command of automatically
*
* @param Boolean $addsourcefile Identifier for adding source file at the end of command
*
* @return void
*/
public function setAddsourcefile($addsourcefile) {
$this->addsourcefile = (bool) $addsourcefile;
}
/**
* File to which error output should be written
*
* @param PhingFile $errorfile Error log file
*
* @return void
*/
public function setError(PhingFile $errorfile) {
$this->error = $errorfile;
}
/**
* Whether to spawn the command and run as background process
*
* @param boolean $spawn If the command is to be run as a background process
*
* @return void
*/
public function setSpawn($spawn) {
$this->spawn = (bool) $spawn;
}
/**
* The name of property to set to return value
*
* @param string $propertyname Property name
*
* @return void
*/
public function setReturnProperty($propertyname) {
$this->returnProperty = (string) $propertyname;
}
/**
* The name of property to set to output value
*
* @param string $propertyname Property name
*
* @return void
*/
public function setOutputProperty($propertyname) {
$this->outputProperty = (string) $propertyname;
}
/**
* Whether the filenames should be passed on the command line as relative
* pathnames (relative to the base directory of the corresponding fileset/list)
*
* @param boolean $escape Escape command before execution
*
* @return void
*/
public function setRelative($relative) {
$this->relative = (bool) $relative;
}
/**
* Specify OS (or muliple OS) that must match in order to execute this command.
*
* @param string $os Operating system string (e.g. "Linux")
*
* @return void
*/
public function setOs($os) {
$this->os = (string) $os;
}
/**
* Whether to use PHP's passthru() function instead of exec()
*
* @param boolean $passthru If passthru shall be used
*
* @return void
*/
public function setPassthru($passthru) {
$this->passthru = (bool) $passthru;
}
/**
* Fail on command exits with a returncode other than zero
*
* @param boolean $failonerror Indicator to fail on error
*
* @return void
*/
public function setFailonerror($failonerror) {
$this->failonerror = (bool) $failonerror;
}
public function setCheckreturn($failonerror) {
$this->setFailonerror($failonerror);
}
/**
* Whether to use forward-slash as file-separator on the file names
*
* @param boolean $forwardslash Indicator to use forward-slash
*
* @return void
*/
public function setForwardslash($forwardslash) {
$this->forwardslash = (bool) $forwardslash;
}
/**
* Limit the amount of parallelism by passing at most this many sourcefiles at once
*
* @param boolean $forwardslash Indicator to use forward-slash
*
* @return void
*/
public function setMaxparallel($max) {
$this->maxparallel = (int) $max;
}
/** [TBA]
* Supports embedded <targetfile> element.
*
* @return void
*/
/**public function createTargetfile() {
return $this->commandline->addArguments( array(self::TARGETFILE_ID) );
}*/
/**
* Supports embedded <srcfile> element.
*
* @return void
*/
public function createSrcfile() {
return $this->commandline->addArguments( array(self::SOURCEFILE_ID) );
}
/**
* Supports embedded <arg> element.
*
* @return void
*/
public function createArg() {
return $this->commandline->createArgument();
}
/**********************************************************************************/
/**************************** T A S K M E T H O D S ******************************/
/**********************************************************************************/
/**
* Class Initialization
* @return void
*/
public function init() {
$this->commandline = new Commandline();
$this->loglevel = Project::MSG_INFO; //VERBOSE;
}
/**
* Do work
* @throws BuildException
*/
public function main() {
// Log
$this->log('Started ', $this->loglevel);
// Initialize //
$this->initialize();
// Validate O.S. applicability
if ($this->validateOS()) {
// Build the command //
$this->buildCommand();
// Process //
// - FileLists
foreach($this->filelists as $fl) {
$this->process( $fl->getFiles($this->project), $fl->getDir($this->project) );
}
unset($this->filelists);
// - FileSets
foreach($this->filesets as $fs) {
$this->process( $fs->getDirectoryScanner($this->project)->getIncludedFiles(), $fs->getDir($this->project) );
}
unset($this->filesets);
}
/// Cleanup //
$this->cleanup();
// Log
$this->log('End ', $this->loglevel);
}
/**********************************************************************************/
/********************** T A S K C O R E M E T H O D S ***************************/
/**********************************************************************************/
/**
* Checks whether the current O.S. should be supported
*
* @return boolean False if the exec command shall not be run
*/
protected function validateOS() {
// Log
$this->log('Validating Operating System information ', $this->loglevel);
// Checking whether'os' information is specified
if (empty($this->os)) {
// Log
$this->log("Operating system information not specified. Skipped checking. ", $this->loglevel);
return true;
}
// Validating the operating system information
$matched = (strpos(strtolower($this->os), strtolower($this->currentos)) !== false) ? true : false;
// Log
$this->log("Operating system '".$this->currentos."' " .($matched ? '' : 'not '). "found in " . $this->os, $this->loglevel);
return $matched;
}
/**
* Initializes the task operations, i.e.
* - Required information validation
* - Working directory
*
* @param none
*
* @return void
*/
private function initialize() {
// Log
$this->log('Initializing started ', $this->loglevel);
///// Validating the required parameters /////
// Executable
if ($this->commandline->getExecutable() === null) {
return $this->throwBuildException('Please provide "executable" information');
}
// Retrieving the current working directory
$this->currentdirectory = getcwd();
// Directory (in which the command should be executed)
if ($this->dir !== null) {
// Try expanding (any) symbolic links
if (! $this->dir->getCanonicalFile()->isDirectory()) {
return $this->throwBuildException("'" . $this->dir . "' is not a valid directory");
}
// Change working directory
$dirchangestatus = @chdir($this->dir->getPath());
// Log
$this->log('Working directory change '.($dirchangestatus ? 'successful' : 'failed') .' to ' . $this->dir->getPath(), $this->loglevel);
}
///// Preparing the task environment /////
// Getting current operationg system
$this->currentos = Phing::getProperty('os.name');
// Log
$this->log('Operating System identified : ' . $this->currentos, $this->loglevel);
// Getting the O.S. type identifier
// Validating the 'filesystem' for determining the OS type [UNIX, WINNT and WIN32]
// (Another usage could be with 'os.name' for determination)
if ('WIN' == strtoupper(substr(Phing::getProperty('host.fstype'), 0, 3))) {
$this->osvariant = 'WIN'; // Probable Windows flavour
} else {
$this->osvariant = 'LIN'; // Probable GNU/Linux flavour
}
// Log
$this->log('Operating System variant identified : ' . $this->osvariant, $this->loglevel);
// Log
$this->log('Initializing completed ', $this->loglevel);
return;
}
/**
* Builds the full command to execute and stores it in $realCommand.
*
* @param none
*
* @return void
*/
private function buildCommand() {
// Log
$this->log('Command building started ', $this->loglevel);
// Building the executable
$this->realCommand = Commandline::toString($this->commandline->getCommandline(), $this->escape);
// Adding the source filename at the end of command, validating the existing
// sourcefile position explicit mentioning
if ( ($this->addsourcefile === true) && (strpos($this->realCommand, self::SOURCEFILE_ID) === false) ) {
$this->realCommand .= ' ' . self::SOURCEFILE_ID;
}
// Setting command output redirection with content appending
if ($this->output !== null) {
$this->realCommand .= ' 1>';
$this->realCommand .= ($this->appendoutput ? '>' : ''); // Append output
$this->realCommand .= ' ' . escapeshellarg($this->output->getPath());
} elseif ($this->spawn) { // Validating the 'spawn' configuration, and redirecting the output to 'null'
// Validating the O.S. variant
if ('WIN' == $this->osvariant) {
$this->realCommand .= ' > NUL'; // MS Windows output nullification
} else {
$this->realCommand .= ' 1>/dev/null'; // GNU/Linux output nullification
}
$this->log("For process spawning, setting Output nullification ", $this->loglevel);
}
// Setting command error redirection with content appending
if ($this->error !== null) {
$this->realCommand .= ' 2>';
$this->realCommand .= ($this->appendoutput ? '>' : ''); // Append error
$this->realCommand .= ' ' . escapeshellarg($this->error->getPath());
}
// Setting the execution as a background process
if ($this->spawn) {
// Validating the O.S. variant
if ('WIN' == $this->osvariant) {
$this->realCommand = 'start /b ' . $this->realcommand; // MS Windows background process forking
} else {
$this->realCommand .= ' &'; // GNU/Linux background process forking
}
}
// Log
$this->log('Command built : ' . $this->realCommand, $this->loglevel);
// Log
$this->log('Command building completed ', $this->loglevel);
return;
}
/**
* Processes the files list with provided information for execution
*
* @param $files File list for processing
* @param #basedir Base directory of the file list
*
* @return void
*/
private function process($files, $basedir) {
// Log
$this->log("Processing Filelist with base directory ($basedir) ", $this->loglevel);
// Process each file in the list for applying the 'realcommand'
foreach ($files as $count => $file) {
// Preparing the absolute filename with relative path information
$absolutefilename = $this->getFilePath($file, $basedir, $this->relative);
// Checking whether 'parallel' information is enabled. If enabled, append all
// the file names as arguments, and run only once.
if ($this->parallel) {
// Checking whether 'maxparallel' setting describes parallelism limitation
// by passing at most 'maxparallel' many sourcefiles at once
$slicedfiles = array_splice($files, 0, (($this->maxparallel > 0) ? $this->maxparallel : count($files)));;
$absolutefilename = implode(' ', $this->getFilePath($slicedfiles, $basedir, $this->relative));
}
// Checking whether the forward-slash as file-separator has been set.
// (Applicability: The source {and target} file names must use the forward slash as file separator)
if ($this->forwardslash) {
$absolutefilename = str_replace(DIRECTORY_SEPARATOR, '/', $absolutefilename);
}
// Preparing the command to be executed
$filecommand = str_replace(array(self::SOURCEFILE_ID), array($absolutefilename), $this->realCommand);
// Command execution
list($returncode, $output) = $this->executeCommand($filecommand);
// Process the stuff on the first command execution only
if (0 == $count) {
// Sets the return property
if ($this->returnProperty) {
$this->project->setProperty($this->returnProperty, $returncode);
}
// Sets the output property
if ($this->outputProperty) {
$this->project->setProperty($this->outputProperty, implode("\n", $output));
}
}
// Validating the 'return-code'
if ( ($this->failonerror) && ($returncode != 0) ) {
return $this->throwBuildException("Task exited with code ($returncode)");
}
// Validate the 'parallel' information for command execution. If the command has been
// executed with the filenames as argument, considering 'maxparallel', just break.
if ( ($this->parallel) && (! array_key_exists($count, $files)) ) {
break;
}
} // Each file processing loop ends
return;
}
/**
* Executes the specified command and returns the return code & output.
*
* @return array array(return code, array with output)
*/
private function executeCommand($command) {
// Var(s)
$output = array();
$return = null;
// Validating the command executor container
($this->passthru ? passthru($command, $return) : exec($command, $output, $return));
// Log
$this->log('Command execution : (' . ($this->passthru ? 'passthru' : 'exec') . ') : ' . $command . " : completed with return code ($return) ", $this->loglevel);
return array($return, $output);
}
/**
* Runs cleanup tasks post execution
* - Restore working directory
*
* @return void
*/
private function cleanup() {
// Restore working directory
if ($this->dir !== null) {
@chdir($this->currentdirectory);
}
return;
}
/**
* Prepares the filename per base directory and relative path information
*
* @param $information Exception information
*
* @return mixed processed filenames
*/
function getFilePath($filename, $basedir, $relative) {
// Var(s)
$files = array();
// Validating the 'file' information
$files = (is_array($filename)) ? $filename : array($filename);
// Processing the file information
foreach($files as $index => $file) {
$absolutefilename = (($relative === false) ? ($basedir . DIRECTORY_SEPARATOR) : '');
$absolutefilename .= $file;
$files[$index] = $absolutefilename;
}
return (is_array($filename) ? $files : $files[0]);
}
/**
* Throws the exception with specified information
*
* @param $information Exception information
*
* @return void
*/
private function throwBuildException($information) {
throw new BuildException('ApplyTask: ' . (string) $information);
}
}
|