3 * Minify a file or set of files
6 require_once( dirname( __FILE__
) . '/Maintenance.php' );
8 class MinifyScript
extends Maintenance
{
11 public function __construct() {
12 parent
::__construct();
13 $this->addOption( 'outfile',
14 'File for output. Only a single file may be specified for input.',
16 $this->addOption( 'outdir',
17 "Directory for output. If this is not specified, and neither is --outfile, then the\n" .
18 "output files will be sent to the same directories as the input files.",
20 $this->mDescription
= "Minify a file or set of files.\n\n" .
21 "If --outfile is not specified, then the output file names will have a .min extension\n" .
22 "added, e.g. jquery.js -> jquery.min.js.";
26 public function execute() {
27 if ( !count( $this->mArgs
) ) {
28 $this->error( "minify.php: At least one input file must be specified." );
32 if ( $this->hasOption( 'outfile' ) ) {
33 if ( count( $this->mArgs
) > 1 ) {
34 $this->error( '--outfile may only be used with a single input file.' );
39 $this->minify( $this->getArg( 0 ), $this->getOption( 'outfile' ) );
43 $outDir = $this->getOption( 'outdir', false );
45 foreach ( $this->mArgs
as $arg ) {
46 $inPath = realpath( $arg );
47 $inName = basename( $inPath );
48 $inDir = dirname( $inPath );
50 if ( strpos( $inName, '.min.' ) !== false ) {
51 echo "Skipping $inName\n";
55 if ( !file_exists( $inPath ) ) {
56 $this->error( "File does not exist: $arg" );
60 $extension = $this->getExtension( $inName );
61 $outName = substr( $inName, 0, -strlen( $extension ) ) . 'min.' . $extension;
62 if ( $outDir === false ) {
63 $outPath = $inDir . '/' . $outName;
65 $outPath = $outDir . '/' . $outName;
68 $this->minify( $inPath, $outPath );
72 public function getExtension( $fileName ) {
73 $dotPos = strrpos( $fileName, '.' );
74 if ( $dotPos === false ) {
75 $this->error( "No file extension, cannot determine type: $arg" );
78 return substr( $fileName, $dotPos +
1 );
81 public function minify( $inPath, $outPath ) {
82 $extension = $this->getExtension( $inPath );
83 echo basename( $inPath ) . ' -> ' . basename( $outPath ) . '...';
85 $inText = file_get_contents( $inPath );
86 if ( $inText === false ) {
87 $this->error( "Unable to open file $inPath for reading." );
90 $outFile = fopen( $outPath, 'w' );
92 $this->error( "Unable to open file $outPath for writing." );
96 switch ( $extension ) {
98 $outText = JSMin
::minify( $inText );
101 $this->error( "No minifier defined for extension \"$extension\"" );
104 fwrite( $outFile, $outText );
110 $maintClass = 'MinifyScript';
111 require_once( DO_MAINTENANCE
);