Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 360 lines (308 sloc) 7.331 kb
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
#!/usr/bin/env node

/**
* Module dependencies.
*/

var fs = require('fs')
  , basename = require('path').basename
  , dirname = require('path').dirname
  , join = require('path').join
  , growl = require('growl');

try {
  var stylus = require('stylus');
} catch (err) {
  var stylus = require('../lib/stylus');
}

/**
* Arguments.
*/

var args = process.argv.slice(2);

/**
* Compare flag.
*/

var compare = false;

/**
* Compress flag.
*/

var compress = false;

/**
* CSS conversion flag.
*/

var convertCSS = false;

/**
* Files to processes.
*/

var files = [];

/**
* Destination directory.
*/

var dest;

/**
* Watcher hash.
*/

var watchers;

/**
* Usage docs.
*/

var usage = [
    ''
  , ' Usage: stylus [options] [command] [< in [> out]]'
  , ' [file|dir ...]'
  , ''
  , ' Commands:'
  , ''
  , ' help <prop> Opens help info for <prop> in'
  , ' your default browser. (osx only)'
  , ''
  , ' Options:'
  , ''
  , ' -w, --watch Watch file(s) for changes and re-compile'
  , ' -o, --out <dir> Output to <dir> when passing files'
  , ' -c, --css <src> [dest] Convert css input to stylus'
  , ' -C, --compress Compress css output'
  , ' -d, --compare Display input along with output'
  , ' -V, --version Display the version of stylus'
  , ' -h, --help Display help information'
  , ''
].join('\n');

/**
* Handle arguments.
*/

var arg;
while (args.length) {
  arg = args.shift();
  switch (arg) {
    case '-h':
    case '--help':
      console.log(usage);
      process.exit(1);
    case '-d':
    case '--compare':
      compare = true;
      break;
    case '-C':
    case '--compress':
      compress = true;
      break;
    case '-c':
    case '--css':
      convertCSS = true;
      break;
    case '-V':
    case '--version':
      console.log(stylus.version);
      process.exit(0);
      break;
    case '-o':
    case '--out':
      dest = args.shift();
      if (!dest) throw new Error('--out <dir> required');
      break;
    case 'help':
      var name = args.shift();
      if (!name) throw new Error('help <property> required');
      help(name);
      break;
    case '-w':
    case '--watch':
      watchers = {};
      break;
    default:
      files.push(arg);
  }
}

// if --watch is used, assume we are
// not working with stdio

if (watchers && !files.length) {
  files = fs.readdirSync(process.cwd())
    .filter(function(file){
    return file.match(/\.styl$/);
  });
}

/**
* Open the default browser to the CSS property `name`.
*
* @param {String} name
*/

function help(name) {
  var url = 'https://developer.mozilla.org/en/CSS/' + name
    , exec = require('child_process').exec;
  exec('open "' + url + '"', function(){
    process.exit(0);
  });
}

// Compilation options

var options = {
    filename: 'stdin'
  , compress: compress
  , paths: [process.cwd()]
};

// Buffer stdin

var str = '';

// Convert css to stylus

if (convertCSS) {
switch (files.length) {
    case 2:
      compileCSSFile(files[0], files[1]);
      break;
    case 1:
      compileCSSFile(files[0], files[0].replace('.css', '.styl'));
      break;
    default:
      var stdin = process.openStdin();
      stdin.setEncoding('utf8');
      stdin.on('data', function(chunk){ str += chunk; });
      stdin.on('end', function(){
        var out = stylus.convertCSS(str);
        console.log(out);
      });
  }
} else {
  if (files.length) {
    compileFiles(files);
  } else {
    compileStdio();
  }
}


/**
* Convert a CSS file to a Styl file
*/

function compileCSSFile(file, fileOut) {
  fs.lstat(file, function(err, stat){
    if (err) throw err;
    if (stat.isFile()) {
      fs.readFile(file, 'utf8', function(err, str){
        if (err) throw err;
        var styl = stylus.convertCSS(str);
        fs.writeFile(fileOut, styl, function(err){
         if (err) throw err;
        });
      });
    }
  });
}


/**
* Compile with stdio.
*/

function compileStdio() {
  var stdin = process.openStdin();
  stdin.setEncoding('utf8');
  stdin.on('data', function(chunk){ str += chunk; });
  stdin.on('end', function(){
    // Compile to css
    stylus(str, options).render(function(err, css){
      if (err) throw err;
      if (compare) {
        console.log('\n\x1b[1mInput:\x1b[0m');
        console.log(str);
        console.log('\n\x1b[1mOutput:\x1b[0m');
      }
      console.log(css);
      if (compare) console.log();
    });
  });
}

/**
* Compile the given files.
*/

function compileFiles(files) {
  files.forEach(compileFile);
}

/**
* Compile the given file.
*/

function compileFile(file) {
  // ensure file exists
  fs.lstat(file, function(err, stat){
    if (err) throw err;
    // file
    if (stat.isFile()) {
      fs.readFile(file, 'utf8', function(err, str){
        if (err) throw err;
        options.filename = file;
        stylus(str, options).render(function(err, css){
          if (err) {
            if (watchers) {
              console.error(err.stack || err.message);
              growl.notify(err.message, { title: 'Stylus error' });
            } else {
              throw err;
            }
          } else {
            writeFile(file, css);
          }
        });
      });
    // directory
    } else if (stat.isDirectory()) {
      fs.readdir(file, function(err, files){
        if (err) throw err;
        files.filter(function(path){
          return path.match(/\.styl$/);
        }).map(function(path){
          return file + '/' + path;
        }).forEach(compileFile);
      });
    }
  });
}

/**
* Write the given css output.
*/

function writeFile(file, css) {
  // --out support
  var path = dest
    ? dest + '/' + basename(file, '.styl') + '.css'
    : file.replace('.styl', '.css');
  fs.writeFile(path, css, function(err){
    if (err) throw err;
    console.log(' \033[90mcompiled\033[0m %s', path);
    // --watch support
    watch(file);
  });
}

/**
* Watch the given `file` and re-compile when modified.
*/

function watch(file) {
  // not watching
  if (!watchers) return;
  // already watched
  if (watchers[file]) return;

  // watch the file itself
  watchers[file] = true;
  fs.watchFile(file, { interval: 50 }, function(curr, prev){
    if (curr.mtime > prev.mtime) {
      compileFile(file);
    }
  });

  // watch imports, re-compiling
  // this file when its deps change
  watchImports(file);
}

/**
* Watch @import nodes in the given `file`.
*/

function watchImports(file, target) {
  var str = fs.readFileSync(file, 'utf8')
    , ast = stylus.parse(str, { filename: file })
    , target = target || file
    , dir = dirname(file);

  (function search(nodes){
    nodes.forEach(function(node){
      if (node.nodes) {
        search(node.nodes);
      } else if ('import' == node.nodeName && !node.literal) {
        var path = join(dir, node.path + '.styl');

        // watch the file, compiling the target
        console.log(' \033[90mwatching\033[0m %s', path);
        fs.watchFile(path, { interval: 50 }, function(curr, prev){
          if (curr.mtime > prev.mtime) {
            compileFile(target);
          }
        });

        // watch this import's deps
        watchImports(path, target);
      }
    });
  })(ast.nodes)
}
Something went wrong with that request. Please try again.