Skip to content
This repository
tag: v0.2
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 545 lines (471 sloc) 23.433 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 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
/*jslint regexp: true */
/*global define, console, process */

    var connect = require('connect'),
        crypto = require('crypto'),
        fs = require('fs'),
        path = require('path'),
        buildDir = 'www-built',
        pagesDir = 'www-ghpages';

    module.exports = {
        // Installs twitter bootstrap
        install_twbootstrap: {
            run: function (d, v, namedArgs, nowrap) {
                var tempName = 'tempbootstrap',
                    jsNameRegExp = /bootstrap-(\w*)\.js$/;

                function finished_message() {
                    console.log('\nTwitter Bootstrap installed.\n' +
                                'Add this css in your <head>:\n' +
                                '<link rel="stylesheet"' +
                                ' href="css/bootstrap.css">\n\n' +
                                'If you want the responsive styles, ' +
                                'add this also:\n' +
                                '<link rel="stylesheet"' +
                                ' href="css/bootstrap-responsive.css">\n');

                    if(nowrap) {
                        console.log('You also need to include any ' +
                                    'js for components you use, like so:\n' +
                                    '<script src="js/lib/bootstrap/button.js">' +
                                    '</script>');
                    }
                    else {
                        // Double-quoting the require command is
                        // necessary so that require.js doesn't strip
                        // it out
                        console.log('You also need to install any ' +
                                    'js components by just requiring ' +
                                    'them, like so:\n' +
                                    "require(\"bootstrap/button\");");
                    }
                }

                v.command('create', tempName, 'twitter/bootstrap')
                .then(function () {
                    //Move the JS to the right location.
                    var jsFiles = v.getFilteredFileList(tempName + '/js', /\.js$/, /js\/tests\//),
                        promises = [];

                    jsFiles.forEach(function (file) {
                        //Pull off the name part from bootstrap-name.js pattern.
                        var match = jsNameRegExp.exec(file),
                            name, destName, damd;

                        if (!match) {
                            return;
                        }

                        name = jsNameRegExp.exec(file)[1];
                        destName = 'www/js/lib/bootstrap/' + name + '.js';
                        damd = q.defer();

                        v.copyFile(file, destName);

                        if(nowrap != 'nowrap') {
                            //Convert the file to AMD style
                            amdify.run.apply(amdify, [damd, v, {
                                depends: 'jquery'
                            }, destName]);
                        }

                        promises.push(damd);
                    });

                    //Wait for all the amdify calls to finish.
                    return q.all(promises);
                })
                .then(function () {
                    //Copy the images over.
                    v.copyDir(tempName + '/img', 'www/img');

                    //Copy the less files.
                    v.copyDir(tempName + '/less', 'tools/less');

                    //Compile the CSS.
                    return v.command('less').then(function () {
                        v.rm(tempName);
                        finished_message();
                    });
                })
                .then(d.resolve, d.reject);
            }
        },

        install_xtags: {
            run: function(d, v, namedArgs) {
                var tempName = 'tempxtags',
                    jsNameRegExp = /\/([^\/]*)\.js$/;

                function finished_message() {
                    console.log('x-tags is installed.\n' +
                                'You need to include the js and css for ' +
                                'each component you want to use, like so:\n\n' +
                               '<link rel="stylesheet"' +
                               ' href="css/lib/x-tag/accordion.css">\n' +
                               '<script src="js/lib/x-tag/accordion.js></script>');
                }
                
                v.command('create', tempName, 'csuwldcat/x-tag/gh-pages')
                .then(function() {
                    //Move the JS to the right location.
                    v.copyFile(tempName + '/x-tag.js', 'www/js/lib/x-tag.js');

                    var jsFiles = v.getFilteredFileList(tempName + '/elements',
                                                        /\.js$/);
                    v.mkdir('www/js/lib/x-tag');
                    jsFiles.forEach(function(file) {
                        var matches = file.match(jsNameRegExp);
                        if(!matches) {
                            return;
                        }

                        var damd = q.defer();
                        var path = 'www/js/lib/x-tag/' + matches[1] + '.js';
                        v.copyFile(file, path);
                    });

                   //Copy the css
                   var files = v.getFilteredFileList(tempName + '/elements',
                                                     /\.css$/);
                   var basenameRegExp = /\/([^\/]*.css)/;

                   v.mkdir('www/css/lib/x-tag');
                   files.forEach(function(file) {
                       var matches = file.match(basenameRegExp);
                       if(!matches) {
                           return;
                       }

                       v.copyFile(file, 'www/css/lib/x-tag/' + matches[1]);
                   });

                   v.rm(tempName);

                   finished_message();
               })
               .then(d.resolve, d.reject);
            }
        },

        //Builds the JS and CSS into one file each. If you want to do
        //dynamic loading of scripts, pass -dynamic to the build, and
        //require.js will be used to load scripts.
        build: {
            flags: {
                //Does not print the build output.
                'q': 'quiet',
                //Uses dynamic loading via require.js instead of building
                //all the modules in with almond.
                'dynamic': 'dynamic'
            },

            run: function (d, v, namedArgs) {
                var q = v.require('q');
                q.call(function () {
                    //Remove the old dir
                    v.rm(buildDir);

                    if (!namedArgs.dynamic) {
                        //Copy the directory for output.
                        v.copyDir('www', buildDir);

                        //Remove the js dir from the built area, will be
                        //replaced by an optimized app.js
                        v.rm(buildDir + '/js');

                        //Do the CSS optimization
                        return v.spawn('node', ['tools/r.js', '-o',
                                                'cssIn=www/css/app.css',
                                                'out=' + buildDir + '/css/app.css'], {
                            useConsole: !namedArgs.quiet
                        });
                    }
                    return undefined;
                })
                .then(function () {
                    //JS go time
                    var optimize = namedArgs.optimize || 'uglify';

                    if (namedArgs.dynamic) {
                        //Still use require.js to load the app.js file.
                        return v.spawn('node', ['tools/r.js', '-o',
                                        'appDir=www',
                                        'baseUrl=js/lib',
                                        'paths.app=../app',
                                        'name=app',
                                        'dir=' + buildDir,
                                        'optimize=' + optimize], {
                            useConsole: !namedArgs.quiet
                        });
                    } else {
                        //The all-in-one option.
                        return v.spawn('node', ['tools/r.js', '-o',
                                        'baseUrl=www/js/lib',
                                        'paths.app=../app',
                                        'paths.almond=../../../tools/almond',
                                        'name=almond',
                                        'include=app',
                                        'out=' + buildDir + '/js/app.js',
                                        'optimize=' + optimize], {
                            useConsole: !namedArgs.quiet
                        });
                    }
                })
                .then(function (buildOutput) {
                    //Remove all the CSS except for the app.css, since it
                    //inlines all the other ones.
                    v.getFilteredFileList(buildDir + '/css').forEach(function (path) {
                        if (!/app\.css$/.test(path)) {
                            v.rm(path);
                        }
                    });


                    v.copyFile(path.join('www', 'js', 'lib', 'modernizr-2.5.3.min.js'), path.join(buildDir, 'js', 'lib', 'modernizr-2.5.3.min.js'));
                    v.copyFile(path.join('www', 'js', 'lib', 'require.js'), path.join(buildDir, 'js', 'lib', 'require.js'));

                    //If almond is in use, it is built into app.js, so need
                    //to update the script tag to just load app.js instead.
                    if (!namedArgs.dynamic) {
                        var indexName = buildDir + '/index.html',
                            contents = v.read(indexName),
                            scriptRegExp = /(<script[^>]+data-main="[^"]+"[^>]+)(src="[^"]+")([^>]*>\s*<\/script>)/;

                        contents = contents.replace(scriptRegExp,
                            function (match, pre, script, post) {
                            return pre + 'src="js/app.js"' + post;
                        });

                        v.write(indexName, contents);
                    }
                    return buildOutput;
                })
                .then(function (buildOutput) {
                    d.resolve(buildOutput);
                }, d.reject);
            }
        },

        //Generates an SHA1 digest that represents the contents of the
        //a directory. Call it like so: "volo digest dir=path/to/directory"
        digest: {
            validate: function (namedArgs) {
                var dir = namedArgs.dir;
                if (!dir) {
                    return new Error('Please specify a target directory for ' +
                                     'the digest');
                }
                if (!path.existsSync(dir)) {
                    return new Error('Target directory for digest does ' +
                                     'not exist: ' + dir);
                }
                return undefined;
            },

            run: function (d, v, namedArgs) {

                var q = v.require('q');

                var dir = namedArgs.dir,
                    files = v.getFilteredFileList(dir),
                    digests = [],
                    i = 0;

                function getDigest(fileName) {
                    var shaSum = crypto.createHash('sha1'),
                        d = q.defer(),
                        stream = fs.ReadStream(fileName);

                    stream.on('data', function(data) {
                        shaSum.update(data);
                    });

                    stream.on('end', function() {
                        d.resolve(shaSum.digest('base64'));
                    });

                    return d.promise;
                }

                function digestFile(fileName) {
                    getDigest(fileName).then(function (digest) {
                        var shaSum;

                        digests[i] = digest;
                        i += 1;

                        if (i < files.length) {
                            digestFile(files[i]);
                        } else {
                            //All done, now generate the final digest,
                            //using the combination of the other digests
                            shaSum = crypto.createHash('sha1');
                            shaSum.update(digests.join(','));
                            d.resolve(shaSum.digest('base64'));
                        }
                    });
                }

                digestFile(files[0]);
            }
        },

        ghdeploy: {
            run: function (d, v, namedArgs) {
                var spawnOptions = {
                    useConsole: !namedArgs.quiet
                },
                authInfo, repoName, hasGhPages;

                var q = v.require('q'),
                    github = v.require('volo/lib/github')
                    githubAuth = v.require('volo/lib/github/auth');

                q.call(function () {
                    //First check if there is already a repo
                    if (!v.exists(buildDir)) {
                        throw new Error('Run build or appcache first to generate a deploy target in "www-built".');
                    }

                    //If already have gh-pages dir, go to next step.
                    if (v.exists(pagesDir)) {
                        return;
                    }

                    //Figure out if already in a github repo.
                    return githubAuth.fetch({ v: v })
                    .then(function (info) {
                        authInfo = info;

                        //Suggest the current directory name as the repo name.
                        repoName = path.basename(process.cwd());

                        return v.prompt(authInfo.user +
                                        ', name of github repo [' +
                                        repoName + ']:');
                    })
                    .then(function (promptRepoName) {
                        var dfd = q.defer();

                        if (promptRepoName) {
                            repoName = promptRepoName;
                        }

                        //First check to see if it exists.
                        github('repos/' + authInfo.user + '/' + repoName)
                        .then(function (data) {
                            var sshUrl = data.ssh_url;

                            //Repo exists, see if there is a gh-pages branch
                            //already
                            github('repos/' + authInfo.user + '/' + repoName + '/branches')
                            .then(function (data) {
                                if (data && data.length) {
                                    hasGhPages = data.some(function (branch) {
                                        return branch.name === 'gh-pages';
                                    });
                                }
                                dfd.resolve(sshUrl);
                            }, dfd.reject);
                        }, function (err) {
                            if (err.response.statusCode === 404) {
                                github('user/repos', {
                                    method: 'POST',
                                    token: authInfo.token,
                                    content: {
                                        name: repoName
                                    }
                                })
                                .then(function (data) {
                                    dfd.resolve(data.ssh_url);
                                }, function (err) {
                                   dfd.reject(err);
                                });
                            } else {
                                dfd.reject(err);
                            }
                        });
                        return dfd.promise;
                    })
                    .then(function (sshUrl) {
                        //Set up .git.
                        v.mkdir(pagesDir);

                        //Set up the gh-pages repo in the built area.
                        return v.withDir(pagesDir, function () {
                            if (hasGhPages) {
                                //Set up the git repo locally. Just commit a file
                                //to get the repo prepped and sent to GitHub.
                                return v.sequence([
                                    ['git', 'init'],
                                    ['git', 'remote', 'add', 'origin', sshUrl],
                                    //This step mandated by:
                                    //http://help.github.com/pages/#project_pages_manually
                                    ['git', 'symbolic-ref', 'HEAD', 'refs/heads/gh-pages'],
                                    [v, 'rm', '.git/index'],
                                    ['git', 'clean', '-fdx'],

                                    ['git', 'pull', 'origin', 'gh-pages']
                                ], spawnOptions);
                            } else {
                                //Set up the git repo locally. Just commit a file
                                //to get the repo prepped and sent to GitHub.
                                return v.sequence([
                                    ['git', 'init'],
                                    ['git', 'remote', 'add', 'origin', sshUrl],
                                    //This step mandated by:
                                    //http://help.github.com/pages/#project_pages_manually
                                    ['git', 'symbolic-ref', 'HEAD', 'refs/heads/gh-pages'],
                                    [v, 'rm', '.git/index'],
                                    ['git', 'clean', '-fdx'],

                                    [v, 'write', 'index.html', 'Setting up pages...'],
                                    ['git', 'add', 'index.html'],
                                    ['git', 'commit', '-m', 'Create branch.'],
                                    ['git', 'push', 'origin', 'gh-pages']
                                ], spawnOptions);
                            }
                        });
                    });
                })
                .then(function () {
                    var message = namedArgs.m;
                    if (!message) {
                        message = 'Deploy';
                    }

                    //Clean up www-ghpages first, but keep .git
                    if (v.exists(pagesDir)) {
                        fs.readdirSync(pagesDir).forEach(function (name) {
                            if (name !== '.git') {
                                v.rm(pagesDir + '/' + name);
                            }
                        });
                    }

                    //Copy the contents of www-built to www-ghpages
                    //Copy the directory for output.
                    v.copyDir(buildDir, pagesDir);

                    //Trigger update to origin.
                    return v.withDir(pagesDir, function () {
                        return v.sequence([
                            //Add any new files
                            ['git', 'add', '.'],
                            //Remove any files from git that are not on on disk
                            ['git', 'add', '-u'],
                            ['git', 'commit', '-m', message],
                            ['git', 'push', 'origin', 'gh-pages'],
                        ], spawnOptions);
                    });
                })
                .then(function () {
                    // return the main repo in the state it started in
                    v.sequence([['git', 'reset', 'HEAD']]);
                    
                    if (repoName) {
                        return 'GitHub Pages is set up. Check http://' +
                                authInfo.user + '.github.com/' + repoName +
                                '/ in about 10-15 minutes.';
                    }
                })
                .then(d.resolve, d.reject);
            }
        },

        //Runs less on the .less files in tools/less to generate the CSS files.
        less: function (d, v, namedArgs) {
            q.all([
                v.exec('node tools/oneless.js tools/less/bootstrap.less > www/css/bootstrap.css'),
                v.exec('node tools/oneless.js tools/less/responsive.less > www/css/bootstrap-responsive.css')
            ])
            .then(function () {
                d.resolve();
            })
            .fail(d.reject);
        },

        appcache: function (d, v, namedArgs) {
            var hasBuilt = v.exists(buildDir);

            v.command('build')
            .then(function () {
                var manifest = v.read('tools/manifest.appcache'),
                    master = v.read(buildDir + '/index.html'),
                    appFiles;

                appFiles = v.getFilteredFileList(buildDir, null, /\.htaccess/);
                appFiles = appFiles.map(function (file) {
                    var start = file.indexOf('/' + buildDir + '/');
                    start = (start !== -1) ? (start + 11) : 0;
                    return file.substr(start, file.length);
                });

                master = master
                        .replace(/<html\s?/, '<html manifest="manifest.appcache" ')
                        .replace(/manifest\.appcache"\s>/, 'manifest.appcache">');
                v.write(buildDir + '/index.html', master);

                return v.command('digest', 'dir=' + buildDir)
                .then(function (stamp) {
                    manifest = v.template(manifest, {
                        files : appFiles.join('\n'),
                        stamp : stamp
                    });
                    v.write(buildDir + '/manifest.appcache', manifest);
                });
            })
            .then(function () {
                //Inform the user of the right mime type, but only do it if
                //there was not a previous build done.
                d.resolve(hasBuilt ? '': 'Be sure to set the mime type for ' +
                          '.appcache files to be: text/cache-manifest');
            })
            .fail(d.reject);
        },
        
        serve: function( d, v, namedArgs ) {
            var port = 8086;
            var base = process.cwd();

            var middleware = [
                connect.static( base ),
                connect.directory( base )
            ];
            connect.logger.format( "WebGameStub", ("[D] server :method :url :status " +
                ":res[content-length] - :response-time ms" ));
            middleware.unshift( connect.logger( "WebGameStub" ) );

            console.log( "starting web server on port " + port );
            connect.apply( null, middleware ).listen( port );
        }
    };
Something went wrong with that request. Please try again.