<commit_before>import fs from 'fs';
// import moment from 'moment';
import parseSyndicationFeed from '../../src/feed-parser';

const expect = global.expect;
const TEST_FEEDS_DIRECTORY = './tests/syndication-feeds/';

function loadTestSyndicationFeed(type, name) {
  return fs.readFileSync(`${TEST_FEEDS_DIRECTORY}${type}/${name}.${type}`, { encoding: 'utf8' });
}

describe('feed-parser', () => {
  describe('parseSyndicationFeed(feedString)', () => {
    it('should throw if feedString is null, empty or not a string', () =>
      Promise.all([
        expect(parseSyndicationFeed(null)).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed(1)).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should throw if feedString is not a valid XML document', () =>
      Promise.all([
        expect(parseSyndicationFeed('{data: \'This is JSON not XML\'}')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('<?xml version = "1.0"?><data><<</data>')).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should correctly parse minimum.rss', () => {
      const minimumRSS = loadTestSyndicationFeed('rss', 'minimum');
      const expectedItems = [
        {
          title: 'You won\'t believe what happened next!',
          link: 'http://example.com/what-happened-next',
          description: 'Something uninteresting, you got click baited!'
        },
        {
          title: 'Blog Authors hate him!',
          link: 'http://example.com/blog-authors-hate-him'
        }
      ];
      return expect(parseSyndicationFeed(minimumRSS)).to.eventually.deep.equal(expectedItems);
    });

    // it('should correctly parse wordpress.com.rss', () => {
    //   const wordpressComRSS = loadTestSyndicationFeed('rss', 'wordpress.com');
    //   const expectedItems = [
    //     {
    //       title: 'Graduating from York',
    //       link: 'https://dannycomputerscientist.wordpress.com/2016/02/05/graduating-from-york/',
    //       description: 'On January 23rd I graduated with an MSc in Advanced Computer Science from The University of York. It was a nice occasion to get together and be merry with the family, and of course for some photos in my cap and gown — this time they were grey and blue. My parents took my degree',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2016/02/img_0091.jpg',
    //       datePublished: moment(new Date('Fri, 05 Feb 2016 18:05:12 +0000'))
    //     },
    //     {
    //       title: 'HackTrain 2.0',
    //       link: 'https://dannycomputerscientist.wordpress.com/2016/01/10/hacktrain-2-0/',
    //       description: 'It seems like a lifetime ago, but the first HackTrain event was actually only 9 months ago — It probably feels so long ago to me as so much has change in the interim, including me getting a job as a result of the first event. When an opportunity came up to represent Trainline at',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/12304083_786742814805282_703787864428458423_o.jpg',
    //       datePublished: moment(new Date('Sun, 10 Jan 2016 22:01:22 +0000'))
    //     },
    //     {
    //       title: 'Centre for Computing History',
    //       link: 'https://dannycomputerscientist.wordpress.com/2016/01/10/centre-for-computing-history/',
    //       description: 'Since September, Charlotte and I have lived about a minutes walk from the UK Computer Museum (which also seems to go by the name Centre for Computing History), but we\'d never actually gone inside. Today after my flying lesson we went to have a quick look. Whilst it made me feel old to see things I',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2016/01/bbc-micro.jpg',
    //       datePublished: moment(new Date('Sun, 10 Jan 2016 17:39:38 +0000'))
    //     },
    //     {
    //       title: 'Tracking Moving Trains (with the minimum possible effort)',
    //       link: 'https://dannycomputerscientist.wordpress.com/2015/12/22/tracking-moving-trains-with-minimum-possible-effort/',
    //       description: 'Trains are, in many respects, wonderful machines. They\'re simultaneously both the most romantic form of travel and the most grueling way to get to work every morning. One thing trains are not however, is up-to-date with modern technology. Whilst you can follow the course, in real time, of a plane soaring at 36,000 feet above',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/12106848_1494412047526257_4658382875925199724_n.jpg',
    //       datePublished: moment(new Date('Tue, 22 Dec 2015 01:52:55 +0000'))
    //     },
    //     {
    //       title: 'Captain Danny',
    //       link: 'https://dannycomputerscientist.wordpress.com/2015/12/09/captain-danny/',
    //       description: 'One of the nice things about working, opposed to studying, is that I now don\'t feel guilty about not spending all my time working on coursework. Time for a hobby! Living 15 minutes walk from Cambridge Airport I quite often see people learning to fly, and thought it looked like fun — so decided to start',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/img_05611.jpg',
    //       datePublished: moment(new Date('Wed, 09 Dec 2015 21:12:16 +0000'))
    //     },
    //     {
    //       title: 'Trainline at Silicon Milkroundabout',
    //       link: 'https://dannycomputerscientist.wordpress.com/2015/12/04/trainline-at-silicon-milkroundabout/',
    //       description: 'A few weeks ago I was lucky enought to be part of the team that tried, and hopefully succeeded, to entice more developers to come and work with us at Trainline at the Silicon Milkroundabout tech recruitment event. I really enjoy talking to people about technology and it was especially nice to talk to people who',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/img_0521.jpg',
    //       datePublished: moment(new Date('Fri, 04 Dec 2015 23:12:03 +0000'))
    //     },
    //     {
    //       title: 'On-boarding at Trainline',
    //       link: 'https://dannycomputerscientist.wordpress.com/2015/10/29/on-boarding-at-trainline/',
    //       description: 'I\'m now entering the sixth week of my time at Trainline. It\'s been quite the experience, due to it being my first full-time job and it being a time of significant changes at Trainline in terms of technology, branding and even an expansion into the European rail market. It\'s been great to be in a',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/10/trainline-homepage.png',
    //       datePublished: moment(new Date('Thu, 29 Oct 2015 17:57:27 +0000'))
    //     },
    //     {
    //       title: 'MSc Finished',
    //       link: 'https://dannycomputerscientist.wordpress.com/2015/09/13/msc-finished/',
    //       description: 'Last week I submitted my thesis, workshop report and conference presentation for my MSc in Advanced Computer Science. Two days after my submission I was also required to present my research and answer a few questions fielded from a lecturer in Yorks Department of Computer Science who had not previously seen my work. The',
    //       datePublished: moment(new Date('Sun, 13 Sep 2015 01:13:58 +0000'))
    //     },
    //     {
    //       title: 'Expect the unexpected',
    //       link: 'https://dannycomputerscientist.wordpress.com/2015/08/02/expect-the-unexpected/',
    //       description: 'When you design software you usually have a few use cases in mind, in the case of EpsilonGit the use case I keep coming back to is a project lead who wants an overview of how his team is working and how they are using their version control software. Back in second year when I',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/08/screen-shot-2015-08-02-at-21-16-29.png',
    //       datePublished: moment(new Date('Sun, 02 Aug 2015 20:19:55 +0000'))
    //     },
    //     {
    //       title: 'Thesis writing begins',
    //       link: 'https://dannycomputerscientist.wordpress.com/2015/07/27/thesis-writing-begins/',
    //       description: 'Today I started work on my masters thesis covering my research for and development of EpsilonGit. There\'s no template provided for the layout of such reports, so today I\'ve been sketching out a rough outline of what I hope to include in the report. e.g. Chapter names, section headings and comments for things to talk',
    //       imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/07/screen-shot-2015-07-27-at-22-02-20.png',
    //       datePublished: moment(new Date('Mon, 27 Jul 2015 21:13:14 +0000'))
    //     }
    //   ];
    //   return expect(parseSyndicationFeed(wordpressComRSS)).to.eventually.deep.equal(expectedItems);
    // });
  });
});
<commit_msg>Reenabled wordpress.com.rss test<commit_after>import fs from 'fs';
import moment from 'moment';
import parseSyndicationFeed from '../../src/feed-parser';

const expect = global.expect;
const TEST_FEEDS_DIRECTORY = './tests/syndication-feeds/';

function loadTestSyndicationFeed(type, name) {
  return fs.readFileSync(`${TEST_FEEDS_DIRECTORY}${type}/${name}.${type}`, { encoding: 'utf8' });
}

describe('feed-parser', () => {
  describe('parseSyndicationFeed(feedString)', () => {
    it('should throw if feedString is null, empty or not a string', () =>
      Promise.all([
        expect(parseSyndicationFeed(null)).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed(1)).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should throw if feedString is not a valid XML document', () =>
      Promise.all([
        expect(parseSyndicationFeed('{data: \'This is JSON not XML\'}')).to.be.rejectedWith('Valid RSS/ATOM Required'),
        expect(parseSyndicationFeed('<?xml version = "1.0"?><data><<</data>')).to.be.rejectedWith('Valid RSS/ATOM Required')
      ])
    );

    it('should correctly parse minimum.rss', () => {
      const minimumRSS = loadTestSyndicationFeed('rss', 'minimum');
      const expectedItems = [
        {
          title: 'You won\'t believe what happened next!',
          link: 'http://example.com/what-happened-next',
          description: 'Something uninteresting, you got click baited!'
        },
        {
          title: 'Blog Authors hate him!',
          link: 'http://example.com/blog-authors-hate-him'
        }
      ];
      return expect(parseSyndicationFeed(minimumRSS)).to.eventually.deep.equal(expectedItems);
    });

    // it('should correctly parse blogger atom', () => {
    //   const bloggerATOM = loadTestSyndicationFeed('atom', 'blogger');
    //   const expectedItems = [];
    //   return expect(parseSyndicationFeed(bloggerATOM)).to.eventually.deep.equal(expectedItems);
    // });

    it('should correctly parse wordpress.com.rss', () => {
      const wordpressComRSS = loadTestSyndicationFeed('rss', 'wordpress.com');
      const expectedItems = [
        {
          title: 'Graduating from York',
          link: 'https://dannycomputerscientist.wordpress.com/2016/02/05/graduating-from-york/',
          description: 'On January 23rd I graduated with an MSc in Advanced Computer Science from The University of York. It was a nice occasion to get together and be merry with the family, and of course for some photos in my cap and gown — this time they were grey and blue. My parents took my degree',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2016/02/img_0091.jpg',
          datePublished: moment(new Date('Fri, 05 Feb 2016 18:05:12 +0000'))
        },
        {
          title: 'HackTrain 2.0',
          link: 'https://dannycomputerscientist.wordpress.com/2016/01/10/hacktrain-2-0/',
          description: 'It seems like a lifetime ago, but the first HackTrain event was actually only 9 months ago — It probably feels so long ago to me as so much has change in the interim, including me getting a job as a result of the first event. When an opportunity came up to represent Trainline at',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/12304083_786742814805282_703787864428458423_o.jpg',
          datePublished: moment(new Date('Sun, 10 Jan 2016 22:01:22 +0000'))
        },
        {
          title: 'Centre for Computing History',
          link: 'https://dannycomputerscientist.wordpress.com/2016/01/10/centre-for-computing-history/',
          description: 'Since September, Charlotte and I have lived about a minutes walk from the UK Computer Museum (which also seems to go by the name Centre for Computing History), but we’d never actually gone inside. Today after my flying lesson we went to have a quick look. Whilst it made me feel old to see things I',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2016/01/bbc-micro.jpg',
          datePublished: moment(new Date('Sun, 10 Jan 2016 17:39:38 +0000'))
        },
        {
          title: 'Tracking Moving Trains (with the minimum possible effort)',
          link: 'https://dannycomputerscientist.wordpress.com/2015/12/22/tracking-moving-trains-with-minimum-possible-effort/',
          description: 'Trains are, in many respects, wonderful machines. They’re simultaneously both the most romantic form of travel and the most grueling way to get to work every morning. One thing trains are not however, is up-to-date with modern technology. Whilst you can follow the course, in real time, of a plane soaring at 36,000 feet above',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/12106848_1494412047526257_4658382875925199724_n.jpg',
          datePublished: moment(new Date('Tue, 22 Dec 2015 01:52:55 +0000'))
        },
        {
          title: 'Captain Danny',
          link: 'https://dannycomputerscientist.wordpress.com/2015/12/09/captain-danny/',
          description: 'One of the nice things about working, opposed to studying, is that I now don’t feel guilty about not spending all my time working on coursework. Time for a hobby! Living 15 minutes walk from Cambridge Airport I quite often see people learning to fly, and thought it looked like fun — so decided to start',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/img_05611.jpg',
          datePublished: moment(new Date('Wed, 09 Dec 2015 21:12:16 +0000'))
        },
        {
          title: 'Trainline at Silicon Milkroundabout',
          link: 'https://dannycomputerscientist.wordpress.com/2015/12/04/trainline-at-silicon-milkroundabout/',
          description: 'A few weeks ago I was lucky enought to be part of the team that tried, and hopefully succeeded, to entice more developers to come and work with us at Trainline at the Silicon Milkroundabout tech recruitment event. I really enjoy talking to people about technology and it was especially nice to talk to people who',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/12/img_0521.jpg',
          datePublished: moment(new Date('Fri, 04 Dec 2015 23:12:03 +0000'))
        },
        {
          title: 'On-boarding at Trainline',
          link: 'https://dannycomputerscientist.wordpress.com/2015/10/29/on-boarding-at-trainline/',
          description: 'I’m now entering the sixth week of my time at Trainline. It’s been quite the experience, due to it being my first full-time job and it being a time of significant changes at Trainline in terms of technology, branding and even an expansion into the European rail market. It’s been great to be in a',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/10/trainline-homepage.png',
          datePublished: moment(new Date('Thu, 29 Oct 2015 17:57:27 +0000'))
        },
        {
          title: 'MSc Finished',
          link: 'https://dannycomputerscientist.wordpress.com/2015/09/13/msc-finished/',
          description: 'Last week I submitted my thesis, workshop report and conference presentation for my MSc in Advanced Computer Science. Two days after my submission I was also required to present my research and answer a few questions fielded from a lecturer in Yorks Department of Computer Science who had not previously seen my work. The',
          datePublished: moment(new Date('Sun, 13 Sep 2015 01:13:58 +0000'))
        },
        {
          title: 'Expect the unexpected',
          link: 'https://dannycomputerscientist.wordpress.com/2015/08/02/expect-the-unexpected/',
          description: 'When you design software you usually have a few use cases in mind, in the case of EpsilonGit the use case I keep coming back to is a project lead who wants an overview of how his team is working and how they are using their version control software. Back in second year when I',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/08/screen-shot-2015-08-02-at-21-16-29.png',
          datePublished: moment(new Date('Sun, 02 Aug 2015 20:19:55 +0000'))
        },
        {
          title: 'Thesis writing begins',
          link: 'https://dannycomputerscientist.wordpress.com/2015/07/27/thesis-writing-begins/',
          description: 'Today I started work on my masters thesis covering my research for and development of EpsilonGit. There’s no template provided for the layout of such reports, so today I’ve been sketching out a rough outline of what I hope to include in the report. e.g. Chapter names, section headings and comments for things to talk',
          imageURI: 'https://dannycomputerscientist.files.wordpress.com/2015/07/screen-shot-2015-07-27-at-22-02-20.png',
          datePublished: moment(new Date('Mon, 27 Jul 2015 21:13:14 +0000'))
        }
      ];
      return expect(parseSyndicationFeed(wordpressComRSS)).to.eventually.deep.equal(expectedItems);
    });
  });
});
<|endoftext|>


<commit_before>/*
 * slush-focusnetworks
 * https://github.com/focusnetworks/slush-focusnetworks
 *
 * Copyright (c) 2015, Focusnetworks
 * Licensed under the MIT license.
 */

'use strict';

var gulp        = require('gulp'),
    install     = require('gulp-install'),
    conflict    = require('gulp-conflict'),
    template    = require('gulp-template'),
    rename      = require('gulp-rename'),
    _           = require('underscore.string'),
    inquirer    = require('inquirer');

function format(string) {
    var username = string.toLowerCase();
    return username.replace(/\s/g, '');
}

var defaults = (function() {
    var homeDir         = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
        workingDirName  = process.cwd().split('/').pop().split('\\').pop(),
        osUserName      = homeDir && homeDir.split('/').pop() || 'root',
        configFile      = homeDir + '/.gitconfig',
        user            = {};
    if (require('fs').existsSync(configFile)) {
        user = require('iniparser').parseSync(configFile).user;
    }
    return {
        appName: workingDirName,
        userName: format(user.name) || osUserName,
        authorEmail: user.email || ''
    };
})();

gulp.task('default', function (done) {
    inquirer.prompt([
        {
            type: 'input',
            name: 'appName',
            message: 'Qual o nome do projeto?',
            default: defaults.appName
        },
        {
            type: 'list',
            name: 'typeProject',
            message: 'Qual linguagem?',
            choices: ['HTML', 'Rails', 'cakePHP', 'MEAN', 'AngularJS'],
            default: 'HTML'
        },
        {
          type: 'checkbox',
          name: 'frameworkCSS',
          message: 'Gostaria de adicionar um Framework CSS?',
          choices: [{
            name: 'Foundation',
            value: 'includeFoundation',
            checked: false
          }, {
            name: 'Bootstrap',
            value: 'includeBootstrap',
            checked: false
          }]
        },
        {
          type: 'checkbox',
          name: 'generateDoc',
          message: 'Gostaria de gerar um FRONTEND.md?',
          choices: [{
            name: 'Yes',
            value: 'docYes',
            checked: false
          }, {
            name: 'No',
            value: 'docNo',
            checked: false
          }]
        },
        {
            type: 'confirm',
            name: 'moveon',
            message: 'Gerar scaffolding?'
        }
    ],
    function (answers) {
        var frameworkCSS  = answers.frameworkCSS,
            documentFront = answers.generateDoc,
        hasFrameworkCSS = function (feat) {
          return frameworkCSS.indexOf(feat) !== -1;
        },
        hasDoc = function (feat) {
          return generateDoc.indexOf(feat) !== -1;
        };
        answers.appNameSlug = _.slugify(answers.appName);

        if (!answers.moveon) {
            return done();
        }

        answers.includeFoundation = hasFrameworkCSS('includeFoundation');
        answers.includeBootstrap  = hasFrameworkCSS('includeBootstrap');
        answers.docYes            = hasDoc('docYes');
        answers.docNo            = hasDoc('docNo');

        var pattern = [__dirname + '/templates/' + answers.typeProject + '/**',  '!' + __dirname + '/templates/' + answers.typeProject + '/{css,css/**}'];

        if (answers.includeBootstrap) {
          pattern = [__dirname + '/templates/' + answers.typeProject + '/**', '!' + __dirname + '/templates/' + answers.typeProject +  '/{css,css/vendor/bootstrap/**}'];
        }

        if (answers.includeFoundation) {
          pattern = [__dirname + '/templates/' + answers.typeProject + '/**', '!' + __dirname + '/templates/' + answers.typeProject +  '/{css,css/vendor/foundation/**}'];
        }

        if (answers.docYes) {
            run('npm install frontend-md').exec()  // prints "Hello World\n".
            .pipe(gulp.dest('output'));   // Writes "Hello World\n" to output/echo.
        }

        if (answers.typeProject == 'HTML') {
            console.log("HTML");
            gulp.src(pattern)
                .pipe(template(answers))
                .pipe(rename(function(file) {
                    if (file.basename[0] === '_') {
                        file.basename = '.' + file.basename.slice(1);
                    }
                }))
                .pipe(conflict('./'))
                .pipe(gulp.dest('./'))
                .pipe(install())
                .on('finish', function () {
                    done();
            });
        }
        if (answers.typeProject == 'Rails') {
            gulp.src(__dirname + '/templates/rails/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
        if (answers.typeProject == 'cakePHP') {
            gulp.src(__dirname + '/templates/cakePHP/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
        if (answers.typeProject == 'MEAN') {
            gulp.src(__dirname + '/templates/MEAN/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
        if (answers.typeProject == 'AngularJS') {
            gulp.src(__dirname + '/templates/angularJS/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
    });
});
<commit_msg>v0.0.5 - Fix bugs<commit_after>/*
 * slush-focusnetworks
 * https://github.com/focusnetworks/slush-focusnetworks
 *
 * Copyright (c) 2015, Focusnetworks
 * Licensed under the MIT license.
 */

'use strict';

var gulp        = require('gulp'),
    install     = require('gulp-install'),
    conflict    = require('gulp-conflict'),
    template    = require('gulp-template'),
    rename      = require('gulp-rename'),
    _           = require('underscore.string'),
    inquirer    = require('inquirer'),
    run         = require('gulp-run');

function format(string) {
    var username = string.toLowerCase();
    return username.replace(/\s/g, '');
}

var defaults = (function() {
    var homeDir         = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
        workingDirName  = process.cwd().split('/').pop().split('\\').pop(),
        osUserName      = homeDir && homeDir.split('/').pop() || 'root',
        configFile      = homeDir + '/.gitconfig',
        user            = {};
    if (require('fs').existsSync(configFile)) {
        user = require('iniparser').parseSync(configFile).user;
    }
    return {
        appName: workingDirName,
        userName: format(user.name) || osUserName,
        authorEmail: user.email || ''
    };
})();

gulp.task('default', function (done) {
    inquirer.prompt([
        {
            type: 'input',
            name: 'appName',
            message: 'Qual o nome do projeto?',
            default: defaults.appName
        },
        {
            type: 'list',
            name: 'typeProject',
            message: 'Qual linguagem?',
            choices: ['HTML', 'Rails', 'cakePHP', 'MEAN', 'AngularJS'],
            default: 'HTML'
        },
        {
          type: 'checkbox',
          name: 'frameworkCSS',
          message: 'Gostaria de adicionar um Framework CSS?',
          choices: [{
            name: 'Foundation',
            value: 'includeFoundation',
            checked: false
          }, {
            name: 'Bootstrap',
            value: 'includeBootstrap',
            checked: false
          }]
        },
        {
          type: 'checkbox',
          name: 'generateDoc',
          message: 'Gostaria de gerar um FRONTEND.md?',
          choices: [{
            name: 'Yes',
            value: 'docYes',
            checked: false
          }, {
            name: 'No',
            value: 'docNo',
            checked: false
          }]
        },
        {
            type: 'confirm',
            name: 'moveon',
            message: 'Gerar scaffolding?'
        }
    ],
    function (answers) {
        var frameworkCSS  = answers.frameworkCSS,
            documentFront = answers.generateDoc,
        hasFrameworkCSS = function (feat) {
          return frameworkCSS.indexOf(feat) !== -1;
        },
        hasDoc = function (feat) {
          return generateDoc.indexOf(feat) !== -1;
        };
        answers.appNameSlug = _.slugify(answers.appName);

        if (!answers.moveon) {
            return done();
        }

        answers.includeFoundation = hasFrameworkCSS('includeFoundation');
        answers.includeBootstrap  = hasFrameworkCSS('includeBootstrap');
        answers.docYes            = hasDoc('docYes');
        answers.docNo            = hasDoc('docNo');

        var pattern = [__dirname + '/templates/' + answers.typeProject + '/**',  '!' + __dirname + '/templates/' + answers.typeProject + '/{css,css/**}'];

        if (answers.includeBootstrap) {
          pattern = [__dirname + '/templates/' + answers.typeProject + '/**', '!' + __dirname + '/templates/' + answers.typeProject +  '/{css,css/vendor/bootstrap/**}'];
        }

        if (answers.includeFoundation) {
          pattern = [__dirname + '/templates/' + answers.typeProject + '/**', '!' + __dirname + '/templates/' + answers.typeProject +  '/{css,css/vendor/foundation/**}'];
        }

        if (answers.docYes) {
            run('npm install frontend-md').exec()  // prints "Hello World\n".
            .pipe(gulp.dest('output'));   // Writes "Hello World\n" to output/echo.
        }

        if (answers.typeProject == 'HTML') {
            console.log("HTML");
            gulp.src(pattern)
                .pipe(template(answers))
                .pipe(rename(function(file) {
                    if (file.basename[0] === '_') {
                        file.basename = '.' + file.basename.slice(1);
                    }
                }))
                .pipe(conflict('./'))
                .pipe(gulp.dest('./'))
                .pipe(install())
                .on('finish', function () {
                    done();
            });
        }
        if (answers.typeProject == 'Rails') {
            gulp.src(__dirname + '/templates/rails/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
        if (answers.typeProject == 'cakePHP') {
            gulp.src(__dirname + '/templates/cakePHP/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
        if (answers.typeProject == 'MEAN') {
            gulp.src(__dirname + '/templates/MEAN/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
        if (answers.typeProject == 'AngularJS') {
            gulp.src(__dirname + '/templates/angularJS/**')
            .pipe(template(answers))
            .pipe(rename(function(file) {
                if (file.basename[0] === '_') {
                    file.basename = '.' + file.basename.slice(1);
                }
            }))
            .pipe(conflict('./'))
            .pipe(gulp.dest('./'))
            .pipe(install())
                .on('finish', function () {
            done();
            });
        }
    });
});
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const path = require('path');
const fs = require('fs');
const async = require('async');
const install = require('gulp-install');
const conflict = require('gulp-conflict');
const rename = require('gulp-rename');
const template = require('gulp-template');
const jeditor = require('gulp-json-editor');
const clone = require('lodash.clone');
const merge = require('lodash.merge');
const slugify = require('uslug');
const inquirer = require('inquirer');
const iniparser = require('iniparser');
const moment = require('moment-timezone');

const pkg = require('./package.json');

const TEMPLATE_SETTINGS = {
  evaluate: /\{SLUSH\{(.+?)\}\}/g,
  interpolate: /\{SLUSH\{=(.+?)\}\}/g,
  escape: /\{SLUSH\{-(.+?)\}\}/g
};

const format = function (string) {
  if (string) {
    return string.toLowerCase().replace(/\s/g, '');
  }
  return '';
};

const dest = function (filepath) {
  return path.resolve(process.cwd(), filepath || './');
};

const defaults = (function () {
  const homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
  const workingDirName = process.cwd().split('/').pop().split('\\').pop();
  const workingDirNoExt = workingDirName.replace(/\.[a-z]{2,3}$/, '');
  const osUserName = homeDir && homeDir.split('/').pop() || 'root';
  const configFile = `${homeDir}/.gitconfig`;

  let user = {};

  if (require('fs').existsSync(configFile)) {
    user = iniparser.parseSync(configFile).user;
  }

  return {
    name: workingDirName,
    slug: slugify(workingDirNoExt),
    userName: format(user.name) || osUserName,
    authorEmail: user.email || '',
    timezone: moment.tz.guess()
  };
})();

const parseGithubRepo = function (str) {
  const githubRe = /(?:https?:\/\/github.com)?\/?([^\/.]+\/[^\/.]+)(?:\.git)?$/i;
  const match = str.match(githubRe);

  if (match && match[1]) {
    return match[1];
  }

  return null;
};

gulp.task('default', done => {
  const prompts = [{
    name: 'name',
    message: 'What is the PRETTY name of your site?',
    default: defaults.name
  }, {
    name: 'slug',
    message: 'What is the name SLUG for your site?',
    default: defaults.slug,
    validate(slug) {
      return slug === slugify(slug);
    }
  }, {
    name: 'url',
    message: 'What is the url for your site?',
    default(answers) {
      return `http://www.${answers.slug}.com`;
    }
  }, {
    name: 'staging',
    message: 'Do you want a separate staging site?',
    type: 'confirm',
    default() {
      return false;
    }
  }, {
    name: 'stagingUrl',
    message: 'What is the staging url?',
    when(answers) {
      return answers.staging;
    },
    default(answers) {
      return `http://stage-www.${answers.slug}.com`;
    }
  }, {
    name: 'author',
    message: 'Who is authoring the site?',
    default() {
      let author = defaults.userName;
      if (defaults.authorEmail) {
        author += ` <${defaults.authorEmail}>`;
      }
      return author;
    }
  }, {
    name: 'description',
    message: 'Please describe your site.'
  }, {
    name: 'keywords',
    message: 'Please enter some site keywords.'
  }, {
    name: 'timezone',
    message: 'What is the timezone for your site?',
    default: defaults.timezone
  }, {
    name: 'version',
    message: 'What is the version of your site?',
    default: '0.1.0'
  }, {
    name: 'github',
    message: 'GitHub repo name? (e.g. foo/bar, https://github.com/foo/bar.git)',
    validate(str) {
      if (str === null) {
        return false;
      }
      return true;
    },
    filter(str) {
      if (str) {
        return parseGithubRepo(str);
      }
    }
  }, {
    name: 'framework',
    message: 'Which framework would you like to use?',
    type: 'list',
    choices: [{
      name: 'Starter Kit (BEM-based styles, Knockout scripts, Lost grid system)',
      value: 'starter-kit'
    }, {
      name: 'Bootstrap (Bootstrap v4, jQuery and support scripts)',
      value: 'bootstrap'
    }, {
      name: 'Blank (nothing at all, just a stub to start with, and some script polyfills)',
      value: 'blank'
    }]
  }, {
    name: 'spa',
    message: 'Is this a single-page application?',
    type: 'confirm',
    default() {
      return false;
    }
  }, {
    name: 'deployer',
    message: 'How would you like to deploy your site?',
    type: 'list',
    choices: [{
      name: 'Amazon AWS / S3 Bucket',
      value: 'aws'
    }, {
      name: 'FTP',
      value: 'ftp'
    }, {
      name: 'None',
      value: 'none'
    }]
  }, {
    name: 'awsBucket',
    message: 'What bucket name would you like to use? (otherwise it will be derived from the url)',
    when(answers) {
      return answers.deployer === 'aws';
    },
    default(answers) {
      return answers.url;
    }
  }, {
    name: 'ftpHost',
    message: 'What is your FTP hostname?',
    when(answers) {
      return answers.deployer === 'ftp';
    }
  }, {
    name: 'ftpDirectory',
    message: 'What is your FTP directory?',
    when(answers) {
      return answers.deployer === 'ftp';
    },
    default() {
      return '/public_html';
    }
  }, {
    type: 'confirm',
    name: 'moveon',
    message: 'Continue?'
  }];

  // Ask
  inquirer.prompt(prompts).then(answers => {
    if (!answers.moveon) {
      return done();
    }

    const config = clone(answers);

    config.deployer = config.deployer || 'none';
    config.generatorVersion = pkg.version;
    config.year = moment.tz(new Date(), answers.timezone).format('YYYY');

    const binaryFileExtensions = 'png|ico|gif|jpg|jpeg|svg|psd|bmp|webp|webm';

    const srcDir = path.join(__dirname, 'templates');
    const destDir = dest();

    const installTextFiles = function (cb) {
      const src = [
        `**/*.!(${binaryFileExtensions})`,
        '!tasks',
        '!tasks/**',
        '!site/_styles',
        '!site/_styles/**',
        '!site/_scripts',
        '!site/_scripts/**',
        '!.DS_Store',
        '!**/.DS_Store',
        '!package.json'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installBinaryFiles = function (cb) {
      const src = [
        `**/*.+(${binaryFileExtensions})`,
        '!tasks',
        '!tasks/**',
        '!site/_styles',
        '!site/_styles/**',
        '!site/_scripts',
        '!site/_scripts/**',
        '!.DS_Store',
        '!**/.DS_Store',
        '!package.json'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installStyleCommonFiles = function (cb) {
      const src = [
        'site/_styles/*',
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installStyleFiles = function (cb) {
      const src = [
        `site/_styles/${config.framework}/**/*`,
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(rename(filepath => {
          filepath.dirname = filepath.dirname.replace(`/${config.framework}`, '');
          return;
        }))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installScriptCommonFiles = function (cb) {
      const src = [
        'site/_scripts/*',
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installScriptFiles = function (cb) {
      const src = [
        `site/_scripts/${config.framework}/**/*`,
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(rename(filepath => {
          filepath.dirname = filepath.dirname.replace(`/${config.framework}`, '');
          return;
        }))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installTaskCommonFiles = function (cb) {
      const src = [
        'tasks/*',
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installTaskDeployFiles = function (cb) {
      const src = [
        `tasks/deployer/${config.deployer}.js`
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(rename(filepath => {
          filepath.dirname = filepath.dirname.replace(`/deployer`, '');
          filepath.basename = 'deployer';
          return;
        }))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const mergePackageAndInstall = function (cb) {
      const pkgMerge = function (pkg) {
        if (fs.existsSync(dest('package.json'))) {
          const existingPkg = require(dest('package.json'));
          return merge(existingPkg, pkg);
        }
        return pkg;
      };

      gulp.src('package.json', {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(jeditor(pkgMerge, {
          'indent_char': ' ',
          'indent_size': 2
        }))
        .pipe(gulp.dest(destDir))
        .pipe(install())
        .on('end', cb);
    };

    const tasks = [
      installTextFiles,
      installBinaryFiles,
      installStyleCommonFiles,
      installStyleFiles,
      installScriptCommonFiles,
      installScriptFiles,
      installTaskCommonFiles,
      installTaskDeployFiles,
      mergePackageAndInstall
    ];

    async.series(tasks, done);
  });
});
<commit_msg>tweaks for releaser and bucket name<commit_after>'use strict';

const gulp = require('gulp');
const path = require('path');
const fs = require('fs');
const async = require('async');
const install = require('gulp-install');
const conflict = require('gulp-conflict');
const rename = require('gulp-rename');
const template = require('gulp-template');
const jeditor = require('gulp-json-editor');
const clone = require('lodash.clone');
const merge = require('lodash.merge');
const slugify = require('uslug');
const inquirer = require('inquirer');
const iniparser = require('iniparser');
const moment = require('moment-timezone');

const pkg = require('./package.json');

const TEMPLATE_SETTINGS = {
  evaluate: /\{SLUSH\{(.+?)\}\}/g,
  interpolate: /\{SLUSH\{=(.+?)\}\}/g,
  escape: /\{SLUSH\{-(.+?)\}\}/g
};

const format = function (string) {
  if (string) {
    return string.toLowerCase().replace(/\s/g, '');
  }
  return '';
};

const dest = function (filepath) {
  return path.resolve(process.cwd(), filepath || './');
};

const defaults = (function () {
  const homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
  const workingDirName = process.cwd().split('/').pop().split('\\').pop();
  const workingDirNoExt = workingDirName.replace(/\.[a-z]{2,3}$/, '');
  const osUserName = homeDir && homeDir.split('/').pop() || 'root';
  const configFile = `${homeDir}/.gitconfig`;

  let user = {};

  if (require('fs').existsSync(configFile)) {
    user = iniparser.parseSync(configFile).user;
  }

  return {
    name: workingDirName,
    slug: slugify(workingDirNoExt),
    userName: format(user.name) || osUserName,
    authorEmail: user.email || '',
    timezone: moment.tz.guess()
  };
})();

const parseGithubRepo = function (str) {
  const githubRe = /(?:https?:\/\/github.com)?\/?([^\/.]+\/[^\/.]+)(?:\.git)?$/i;
  const match = str.match(githubRe);

  if (match && match[1]) {
    return match[1];
  }

  return null;
};

gulp.task('default', done => {
  const prompts = [{
    name: 'name',
    message: 'What is the PRETTY name of your site?',
    default: defaults.name
  }, {
    name: 'slug',
    message: 'What is the name SLUG for your site?',
    default: defaults.slug,
    validate(slug) {
      return slug === slugify(slug);
    }
  }, {
    name: 'url',
    message: 'What is the url for your site?',
    default(answers) {
      return `http://www.${answers.slug}.com`;
    }
  }, {
    name: 'staging',
    message: 'Do you want a separate staging site?',
    type: 'confirm',
    default() {
      return false;
    }
  }, {
    name: 'stagingUrl',
    message: 'What is the staging url?',
    when(answers) {
      return answers.staging;
    },
    default(answers) {
      return `http://stage-www.${answers.slug}.com`;
    }
  }, {
    name: 'author',
    message: 'Who is authoring the site?',
    default() {
      let author = defaults.userName;
      if (defaults.authorEmail) {
        author += ` <${defaults.authorEmail}>`;
      }
      return author;
    }
  }, {
    name: 'description',
    message: 'Please describe your site.'
  }, {
    name: 'keywords',
    message: 'Please enter some site keywords.'
  }, {
    name: 'timezone',
    message: 'What is the timezone for your site?',
    default: defaults.timezone
  }, {
    name: 'version',
    message: 'What is the version of your site?',
    default: '0.1.0'
  }, {
    name: 'github',
    message: 'GitHub repo name? (e.g. foo/bar, https://github.com/foo/bar.git)',
    validate(str) {
      if (str === null) {
        return false;
      }
      return true;
    },
    filter(str) {
      if (str) {
        return parseGithubRepo(str);
      }
    }
  }, {
    name: 'githubToken',
    message: 'GitHub token for the releaser?',
    when(answers) {
      return answers.github;
    },
    default: ''
  }, {
    name: 'framework',
    message: 'Which framework would you like to use?',
    type: 'list',
    choices: [{
      name: 'Starter Kit (BEM-based styles, Knockout scripts, Lost grid system)',
      value: 'starter-kit'
    }, {
      name: 'Bootstrap (Bootstrap v4, jQuery and support scripts)',
      value: 'bootstrap'
    }, {
      name: 'Blank (nothing at all, just a stub to start with, and some script polyfills)',
      value: 'blank'
    }]
  }, {
    name: 'spa',
    message: 'Is this a single-page application?',
    type: 'confirm',
    default() {
      return false;
    }
  }, {
    name: 'deployer',
    message: 'How would you like to deploy your site?',
    type: 'list',
    choices: [{
      name: 'Amazon AWS / S3 Bucket',
      value: 'aws'
    }, {
      name: 'FTP',
      value: 'ftp'
    }, {
      name: 'None',
      value: 'none'
    }]
  }, {
    name: 'awsBucket',
    message: 'What bucket name would you like to use? (otherwise it will be derived from the url)',
    when(answers) {
      return answers.deployer === 'aws';
    },
    default(answers) {
      return url.parse(answers.url).hostname;
    }
  }, {
    name: 'ftpHost',
    message: 'What is your FTP hostname?',
    when(answers) {
      return answers.deployer === 'ftp';
    }
  }, {
    name: 'ftpDirectory',
    message: 'What is your FTP directory?',
    when(answers) {
      return answers.deployer === 'ftp';
    },
    default() {
      return '/public_html';
    }
  }, {
    type: 'confirm',
    name: 'moveon',
    message: 'Continue?'
  }];

  // Ask
  inquirer.prompt(prompts).then(answers => {
    if (!answers.moveon) {
      return done();
    }

    const config = clone(answers);

    config.deployer = config.deployer || 'none';
    config.generatorVersion = pkg.version;
    config.year = moment.tz(new Date(), answers.timezone).format('YYYY');

    const binaryFileExtensions = 'png|ico|gif|jpg|jpeg|svg|psd|bmp|webp|webm';

    const srcDir = path.join(__dirname, 'templates');
    const destDir = dest();

    const installTextFiles = function (cb) {
      const src = [
        `**/*.!(${binaryFileExtensions})`,
        '!tasks',
        '!tasks/**',
        '!site/_styles',
        '!site/_styles/**',
        '!site/_scripts',
        '!site/_scripts/**',
        '!.DS_Store',
        '!**/.DS_Store',
        '!package.json'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installBinaryFiles = function (cb) {
      const src = [
        `**/*.+(${binaryFileExtensions})`,
        '!tasks',
        '!tasks/**',
        '!site/_styles',
        '!site/_styles/**',
        '!site/_scripts',
        '!site/_scripts/**',
        '!.DS_Store',
        '!**/.DS_Store',
        '!package.json'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installStyleCommonFiles = function (cb) {
      const src = [
        'site/_styles/*',
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installStyleFiles = function (cb) {
      const src = [
        `site/_styles/${config.framework}/**/*`,
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(rename(filepath => {
          filepath.dirname = filepath.dirname.replace(`/${config.framework}`, '');
          return;
        }))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installScriptCommonFiles = function (cb) {
      const src = [
        'site/_scripts/*',
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installScriptFiles = function (cb) {
      const src = [
        `site/_scripts/${config.framework}/**/*`,
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(rename(filepath => {
          filepath.dirname = filepath.dirname.replace(`/${config.framework}`, '');
          return;
        }))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installTaskCommonFiles = function (cb) {
      const src = [
        'tasks/*',
        '!.DS_Store',
        '!**/.DS_Store'
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const installTaskDeployFiles = function (cb) {
      const src = [
        `tasks/deployer/${config.deployer}.js`
      ];

      gulp.src(src, {dot: true, nodir: true, cwd: srcDir, base: srcDir})
        .pipe(rename(filepath => {
          filepath.dirname = filepath.dirname.replace(`/deployer`, '');
          filepath.basename = 'deployer';
          return;
        }))
        .pipe(conflict(destDir, {logger: console.log}))
        .pipe(gulp.dest(destDir))
        .on('end', cb);
    };

    const mergePackageAndInstall = function (cb) {
      const pkgMerge = function (pkg) {
        if (fs.existsSync(dest('package.json'))) {
          const existingPkg = require(dest('package.json'));
          return merge(existingPkg, pkg);
        }
        return pkg;
      };

      gulp.src('package.json', {dot: true, cwd: srcDir, base: srcDir})
        .pipe(template(config, TEMPLATE_SETTINGS))
        .pipe(jeditor(pkgMerge, {
          'indent_char': ' ',
          'indent_size': 2
        }))
        .pipe(gulp.dest(destDir))
        .pipe(install())
        .on('end', cb);
    };

    const tasks = [
      installTextFiles,
      installBinaryFiles,
      installStyleCommonFiles,
      installStyleFiles,
      installScriptCommonFiles,
      installScriptFiles,
      installTaskCommonFiles,
      installTaskDeployFiles,
      mergePackageAndInstall
    ];

    async.series(tasks, done);
  });
});
<|endoftext|>


<commit_before>module.exports = exports = global['SNAKESKIN_DEBUG'] || require('./dist/snakeskin.min');

var path = require('path'),
	fs = require('fs'),
	cache = {};

function clone(obj) {
	return JSON.parse(JSON.stringify(obj));
}

/**
 * Вернуть true, если заданный файл шаблонов соответствует скомпилированному
 * по временной метке
 *
 * @param {string} source - путь к исходному файлу
 * @param {string} result - путь к скомпилированному файлу
 * @param {(string|boolean|null)=} [opt_key] - ключ параметров компиляции
 * @param {?boolean=} [opt_includes=false] - если true, то в случае успешного результата
 *     вернётся массив подключаемых файлов
 *
 * @return {(boolean|!Array)}
 */
exports.check = function (source, result, opt_key, opt_includes) {
	source = path.normalize(path.resolve(source));
	result = path.normalize(path.resolve(result));

	if (!fs.existsSync(source) || !fs.existsSync(result)) {
		return false;
	}

	var code = fs.readFileSync(result).toString(),
		label = /label <([\d]+)>/.exec(code);

	if (opt_key === null || !label || fs.statSync(source).mtime.valueOf() != label[1]) {
		return false;
	}

	if (opt_key) {
		var key = /key <(.*?)>/.exec(code);

		if (!key || key[1] != opt_key) {
			return false;
		}
	}

	var includes = /includes <(.*?)>/.exec(code);

	if (!includes) {
		return false;
	}

	if (includes[1]) {
		includes = JSON.parse(includes[1]);

		for (var i = 0; i < includes.length; i++) {
			var el = includes[i];

			if (fs.existsSync(el[0])) {
				if (fs.statSync(el[0]).mtime.valueOf() != el[1]) {
					return false;
				}

			} else {
				return false;
			}
		}

		if (opt_includes) {
			return includes.map(function (el) {
				return el[0];
			});
		}
	}

	return opt_includes ? [] : true;
};

/**
 * Скомпилировать заданный файл и вернуть ссылку на полученный объект
 * или false, если произошла ошибка при компиляции
 *
 * @param {string} src - путь к файлу шаблонов
 *
 * @param {Object=} [opt_params] - дополнительные параметры компиляции
 * @see Snakeskin.compile
 *
 * @return {(!Object|boolean)}
 */
exports.compileFile = function (src, opt_params) {
	src = path.normalize(path.resolve(src));

	var p = opt_params || {};
	p.exports = 'commonJS';

	var cacheEnabled = p.cache !== false;
	var cacheKey = this.compile(null, p, null, {cacheKey: true}),
		fromCache = cacheEnabled &&
			cache[cacheKey] &&
			cache[cacheKey][src];

	if (fromCache) {
		var tmp = fromCache;

		if (p.words) {
			if (!tmp.words) {
				fromCache = false;

			} else {
				p.words = clone(tmp.words);
			}
		}

		if (p.debug) {
			if (!tmp.debug) {
				fromCache = false;

			} else {
				p.debug = clone(tmp.debug);
			}
		}

		if (fromCache) {
			return tmp.tpls;
		}
	}

	var source = fs.readFileSync(src).toString(),
		resSrc = src + '.js';

	var tpls,
		res = true,
		that = this;

	var compile = function () {
		res = that.compile(source, p, {file: src});

		if (res !== false) {
			fs.writeFileSync(resSrc, res);
		}
	};

	if (cacheEnabled) {
		if (!this.check(src, resSrc, cacheKey)) {
			compile();
		}

	} else {
		compile();
	}

	if (res !== false) {
		delete require.cache[require.resolve(resSrc)];
		tpls = require(resSrc);

		if (cacheKey && (cacheEnabled || cache[cacheKey])) {
			cache[cacheKey] = cache[cacheKey] || {};
			cache[cacheKey][src] = {
				tpls: tpls,
				debug: p.debug,
				words: p.words
			};
		}

		if (tpls.init) {
			tpls.init(this);
		}

		return tpls;
	}

	return false;
};

/**
 * Вернуть ссылку на главный шаблон
 *
 * @param {!Object} tpls - таблица шаблонов
 * @param {?string=} [opt_src] - путь к файлу шаблонов
 * @param {?string=} [opt_tplName] - имя главного шаблона
 * @return {Function}
 */
exports.returnMainTpl = function (tpls, opt_src, opt_tplName) {
	var tpl;

	if (opt_tplName) {
		tpl = tpls[opt_tplName];

	} else {
		tpl = opt_src && tpls[path.basename(opt_src, path.extname(opt_src))] ||
			tpls.main ||
			tpls.index ||
			tpls[Object.keys(tpls)[0]];
	}

	return tpl || null;
};

/**
 * Скомпилировать заданный файл и вернуть ссылку на главный шаблон (функцию)
 *
 * @param {string} src - путь к файлу шаблонов
 *
 * @param {Object=} [opt_params] - дополнительные параметры компиляции
 * @see Snakeskin.compile
 *
 * @param {?string=} [opt_tplName] - имя главного шаблона
 * @return {Function}
 */
exports.execFile = function (src, opt_params, opt_tplName) {
	var tpls = this.compileFile(src, opt_params);

	if (!tpls) {
		return null;
	}

	return this.returnMainTpl(tpls, src, opt_tplName);
};

/**
 * Скомпилировать заданный текст и вернуть ссылку на главный шаблон (функцию)
 *
 * @param {string} txt - исходный текст
 *
 * @param {Object=} [opt_params] - дополнительные параметры компиляции
 * @see Snakeskin.compile
 *
 * @param {?string=} [opt_tplName] - имя главного шаблона
 * @return {Function}
 */
exports.exec = function (txt, opt_params, opt_tplName) {
	var tpls = {};

	opt_params = opt_params || {};
	opt_params.context = tpls;

	this.compile(txt, opt_params);
	return this.returnMainTpl(tpls, null, opt_tplName);
};
<commit_msg>Добавлена сортировка имён шаблонов<commit_after>module.exports = exports = global['SNAKESKIN_DEBUG'] || require('./dist/snakeskin.min');

var path = require('path'),
	fs = require('fs'),
	cache = {};

function clone(obj) {
	return JSON.parse(JSON.stringify(obj));
}

/**
 * Вернуть true, если заданный файл шаблонов соответствует скомпилированному
 * по временной метке
 *
 * @param {string} source - путь к исходному файлу
 * @param {string} result - путь к скомпилированному файлу
 * @param {(string|boolean|null)=} [opt_key] - ключ параметров компиляции
 * @param {?boolean=} [opt_includes=false] - если true, то в случае успешного результата
 *     вернётся массив подключаемых файлов
 *
 * @return {(boolean|!Array)}
 */
exports.check = function (source, result, opt_key, opt_includes) {
	source = path.normalize(path.resolve(source));
	result = path.normalize(path.resolve(result));

	if (!fs.existsSync(source) || !fs.existsSync(result)) {
		return false;
	}

	var code = fs.readFileSync(result).toString(),
		label = /label <([\d]+)>/.exec(code);

	if (opt_key === null || !label || fs.statSync(source).mtime.valueOf() != label[1]) {
		return false;
	}

	if (opt_key) {
		var key = /key <(.*?)>/.exec(code);

		if (!key || key[1] != opt_key) {
			return false;
		}
	}

	var includes = /includes <(.*?)>/.exec(code);

	if (!includes) {
		return false;
	}

	if (includes[1]) {
		includes = JSON.parse(includes[1]);

		for (var i = 0; i < includes.length; i++) {
			var el = includes[i];

			if (fs.existsSync(el[0])) {
				if (fs.statSync(el[0]).mtime.valueOf() != el[1]) {
					return false;
				}

			} else {
				return false;
			}
		}

		if (opt_includes) {
			return includes.map(function (el) {
				return el[0];
			});
		}
	}

	return opt_includes ? [] : true;
};

/**
 * Скомпилировать заданный файл и вернуть ссылку на полученный объект
 * или false, если произошла ошибка при компиляции
 *
 * @param {string} src - путь к файлу шаблонов
 *
 * @param {Object=} [opt_params] - дополнительные параметры компиляции
 * @see Snakeskin.compile
 *
 * @return {(!Object|boolean)}
 */
exports.compileFile = function (src, opt_params) {
	src = path.normalize(path.resolve(src));

	var p = opt_params || {};
	p.exports = 'commonJS';

	var cacheEnabled = p.cache !== false;
	var cacheKey = this.compile(null, p, null, {cacheKey: true}),
		fromCache = cacheEnabled &&
			cache[cacheKey] &&
			cache[cacheKey][src];

	if (fromCache) {
		var tmp = fromCache;

		if (p.words) {
			if (!tmp.words) {
				fromCache = false;

			} else {
				p.words = clone(tmp.words);
			}
		}

		if (p.debug) {
			if (!tmp.debug) {
				fromCache = false;

			} else {
				p.debug = clone(tmp.debug);
			}
		}

		if (fromCache) {
			return tmp.tpls;
		}
	}

	var source = fs.readFileSync(src).toString(),
		resSrc = src + '.js';

	var tpls,
		res = true,
		that = this;

	var compile = function () {
		res = that.compile(source, p, {file: src});

		if (res !== false) {
			fs.writeFileSync(resSrc, res);
		}
	};

	if (cacheEnabled) {
		if (!this.check(src, resSrc, cacheKey)) {
			compile();
		}

	} else {
		compile();
	}

	if (res !== false) {
		delete require.cache[require.resolve(resSrc)];
		tpls = require(resSrc);

		if (cacheKey && (cacheEnabled || cache[cacheKey])) {
			cache[cacheKey] = cache[cacheKey] || {};
			cache[cacheKey][src] = {
				tpls: tpls,
				debug: p.debug,
				words: p.words
			};
		}

		if (tpls.init) {
			tpls.init(this);
		}

		return tpls;
	}

	return false;
};

/**
 * Вернуть ссылку на главный шаблон
 *
 * @param {!Object} tpls - таблица шаблонов
 * @param {?string=} [opt_src] - путь к файлу шаблонов
 * @param {?string=} [opt_tplName] - имя главного шаблона
 * @return {Function}
 */
exports.returnMainTpl = function (tpls, opt_src, opt_tplName) {
	var tpl;

	if (opt_tplName) {
		tpl = tpls[opt_tplName];

	} else {
		tpl = opt_src && tpls[path.basename(opt_src, path.extname(opt_src))] ||
			tpls.main ||
			tpls.index ||
			tpls[Object.keys(tpls).sort()[0]];
	}

	return tpl || null;
};

/**
 * Скомпилировать заданный файл и вернуть ссылку на главный шаблон (функцию)
 *
 * @param {string} src - путь к файлу шаблонов
 *
 * @param {Object=} [opt_params] - дополнительные параметры компиляции
 * @see Snakeskin.compile
 *
 * @param {?string=} [opt_tplName] - имя главного шаблона
 * @return {Function}
 */
exports.execFile = function (src, opt_params, opt_tplName) {
	var tpls = this.compileFile(src, opt_params);

	if (!tpls) {
		return null;
	}

	return this.returnMainTpl(tpls, src, opt_tplName);
};

/**
 * Скомпилировать заданный текст и вернуть ссылку на главный шаблон (функцию)
 *
 * @param {string} txt - исходный текст
 *
 * @param {Object=} [opt_params] - дополнительные параметры компиляции
 * @see Snakeskin.compile
 *
 * @param {?string=} [opt_tplName] - имя главного шаблона
 * @return {Function}
 */
exports.exec = function (txt, opt_params, opt_tplName) {
	var tpls = {};

	opt_params = opt_params || {};
	opt_params.context = tpls;

	this.compile(txt, opt_params);
	return this.returnMainTpl(tpls, null, opt_tplName);
};
<|endoftext|>


<commit_before>"use strict";
var px = require("./px");
var etg = require("./etg");
var gfx = require("./gfx");
var chat = require("./chat");
var sock = require("./sock");
module.exports = function(reward, numberofcopies, code) {
	if (!numberofcopies) numberofcopies = 1;
	if (reward.type !== undefined) reward = reward.type;
	var rewardList, chosenReward;
	if (typeof reward == "string") {
		var upped = reward.substring(0, 5) == "upped";
		var rarity = userutil.rewardwords[upped ? reward.substring(5) : reward];
		rewardList = etg.filtercards(upped, function(x) { return x.rarity == rarity }).map(function(card){ return card.code });
	}else if (reward instanceof Array){
		rewardList = reward;
	}else{
		console.log("Unknown reward", reward);
		return;
	}
	var rewardui = px.mkView();

	if (numberofcopies > 1) {
		var infotext = new px.MenuText(20, 100, "You will get " + numberofcopies + " copies of the card you choose")
		rewardui.addChild(infotext);
	}

	if (code){
		var exitButton = px.mkButton(10, 10, "Exit");
		px.setClick(exitButton, startMenu);
		rewardui.addChild(exitButton);
	}

	var confirmButton = px.mkButton(10, 40, "Done");
	px.setClick(confirmButton, function() {
		if (chosenReward) {
			if (code === undefined) {
				sock.userExec("addbound", { c: etgutil.encodeCount(numberofcopies) + chosenReward });
				require("./MainMenu")();
			}
			else {
				sock.userEmit("codesubmit2", { code: code, card: chosenReward });
			}
		}
	});
	rewardui.addChild(confirmButton);

	var chosenRewardImage = new PIXI.Sprite(gfx.nopic);
	chosenRewardImage.position.set(450, 20);
	rewardui.addChild(chosenRewardImage);
	rewardList.forEach(function(reward, i){
		var card = new PIXI.Sprite(getCardImage(reward));
		card.position.set(100 + Math.floor(i/12) * 130, 272 + (i%12) * 20);
		px.setClick(card, function(){
			chosenReward = reward;
			chosenRewardImage.setTexture(gfx.getArt(chosenReward));
		}, "cardClick");
		rewardui.addChild(card);
		px.setInteractive(card);
	});

	rewardui.cmds = {
		codedone:function(data) {
			sock.user.pool = etgutil.addcard(sock.user.pool, data.card);
			chat(Cards.Codes[data.card].name + " added!");
			require("./MainMenu")();
		},
	}

	px.refreshRenderer(rewardui);
}<commit_msg>Fix Reward.js<commit_after>"use strict";
var px = require("./px");
var etg = require("./etg");
var gfx = require("./gfx");
var chat = require("./chat");
var sock = require("./sock");
var etgutil = require("./etgutil");
var userutil = require("./userutil");
module.exports = function(reward, numberofcopies, code) {
	if (!numberofcopies) numberofcopies = 1;
	var rewardList, chosenReward;
	if (typeof reward == "string") {
		var upped = reward.substring(0, 5) == "upped";
		var rarity = userutil.rewardwords[upped ? reward.substring(5) : reward];
		rewardList = etg.filtercards(upped, function(x) { return x.rarity == rarity }).map(function(card){ return card.code });
	}else if (reward instanceof Array){
		rewardList = reward;
	}else{
		console.log("Unknown reward", reward);
		return;
	}
	var rewardui = px.mkView();

	if (numberofcopies > 1) {
		var infotext = new px.MenuText(20, 100, "You will get " + numberofcopies + " copies of the card you choose")
		rewardui.addChild(infotext);
	}

	if (code){
		var exitButton = px.mkButton(10, 10, "Exit");
		px.setClick(exitButton, startMenu);
		rewardui.addChild(exitButton);
	}

	var confirmButton = px.mkButton(10, 40, "Done");
	px.setClick(confirmButton, function() {
		if (chosenReward) {
			if (code === undefined) {
				sock.userExec("addbound", { c: etgutil.encodeCount(numberofcopies) + chosenReward });
				require("./MainMenu")();
			}
			else {
				sock.userEmit("codesubmit2", { code: code, card: chosenReward });
			}
		}
	});
	rewardui.addChild(confirmButton);

	var chosenRewardImage = new PIXI.Sprite(gfx.nopic);
	chosenRewardImage.position.set(450, 20);
	rewardui.addChild(chosenRewardImage);
	rewardList.forEach(function(reward, i){
		var card = new PIXI.Sprite(gfx.getCardImage(reward));
		card.position.set(100 + Math.floor(i/12) * 130, 272 + (i%12) * 20);
		px.setClick(card, function(){
			chosenReward = reward;
			chosenRewardImage.setTexture(gfx.getArt(chosenReward));
		}, "cardClick");
		rewardui.addChild(card);
		px.setInteractive(card);
	});

	rewardui.cmds = {
		codedone:function(data) {
			sock.user.pool = etgutil.addcard(sock.user.pool, data.card);
			chat(Cards.Codes[data.card].name + " added!");
			require("./MainMenu")();
		},
	}

	px.refreshRenderer(rewardui);
}<|endoftext|>


<commit_before>#!/usr/bin/env node

var routes = require('../index.js');
var async = require('async');

var sourceIndividual;
var seenIndividuals = [];
var seenTracks = [];

var error = function (err) {
	if (err) {
		console.log('Error: ', err.message);
		process.exit(1);
	}
};

var random = function (array) {
	return array[Math.floor(Math.random()*array.length)];
};

var valuesNotIn = function (values, notIn) {
	// returns values from values that are not in notIn
	return values.filter( function (value) {
		return notIn.indexOf( value ) === -1;
	});
};

var generatePlaylist = function (individual, done) {
	async.parallel([
		routes.getTracksWithContributors.bind(undefined, [individual]),
		routes.getTracksByArtists.bind(undefined, [individual])
	],
	function (err, tracks) {
		var track;
		error(err);
		tracks = tracks[0].concat(tracks[1]);
		var notSeenTracks = valuesNotIn(tracks, seenTracks);
		if (notSeenTracks.length > 0) {
			track = random(notSeenTracks);
			seenTracks.push(track);
		} else {
			track = random(tracks);
		}
		if (!track) {
			error(new Error('Could not find a track for ' + individual));
		}
		routes.getTrackDetails(track, function (err, details) {
			error(err);

			if (!details) {
				error(new Error('No details for ' + track));
			}

			var name = details.name || 'WHOOPS, FREEBASE DOES NOT APPEAR TO HAVE AN ENGLISH NAME FOR THIS TRACK';
			var artist = details.artists.map(function (value) {
				return value.name || 'WHOOPS, FREEBASE DOES NOT APPEAR TO HAVE AN ENGLISH NAME FOR THIS ARTIST';
			}).join(' & ');
			var release = random(details.releases).name || 'WHOOPS, FREEBASE DOES NOT APPEAR TO HAVE AN ENGLISH NAME FOR THIS RELEASE';

			var output = '"' + name + '"';
			output += '\n' + artist;
			output += '\n_' + release + '_';
			console.log(output);

			routes.getArtistsAndContributorsFromTracks([track], function (err, contributors) {
				error(err);
				var contributor;
				var notSeen = valuesNotIn(contributors, seenIndividuals);
				if (notSeen.length > 0) {
					contributor = random(notSeen);
					seenIndividuals.push(contributor);
				} else {
					contributor = random(contributors);
				}
				routes.getArtistDetails(contributor, function (err, details) {
					var name = details.name || 'WHOOPS, FREEBASE DOES NOT HAVE AN ENGLISH NAME FOR THIS PERSON';
					console.log('\n ... with ' + name + ' ... \n');
					sourceIndividual = contributor;
					done();
				});
			});
		});
	});
};

var startingPoint = process.argv[2] || 'Todd Rundgren';
routes.getMids(startingPoint, '/music/artist', function (err, mids) {
	error(err);
	sourceIndividual = mids[0];
	if (! sourceIndividual) {
		console.log('Could not find an artist named ' + process.argv[2]);
		process.exit(0);
	}
	seenIndividuals.push(sourceIndividual);
	async.forever(
		function (next) {
			generatePlaylist(sourceIndividual, next);
		},
		error
	);
});<commit_msg>favor tracks by artists we haven't seen yet<commit_after>#!/usr/bin/env node

var routes = require('../index.js');
var async = require('async');

var sourceIndividual;
var seenIndividuals = [];
var seenTracks = [];
var seenArtists = [];

var error = function (err) {
	if (err) {
		console.log('Error: ', err.message);
		process.exit(1);
	}
};

var random = function (array) {
	return array[Math.floor(Math.random()*array.length)];
};

var valuesNotIn = function (values, notIn) {
	// returns values from values that are not in notIn
	return values.filter( function (value) {
		return notIn.indexOf( value ) === -1;
	});
};

var generatePlaylist = function (individual, done) {
	var callback = 	function (err, tracks) {
		error(err);
		var track;

		var notSeenTracks = valuesNotIn(tracks, seenTracks);
		if (notSeenTracks.length > 0) {
			track = random(notSeenTracks);
			seenTracks.push(track);
		} else {
			track = random(tracks);
		}
		if (! track) {
			nextIndex = nextIndex +1;
			next[nextIndex]();
			return;
		}
		routes.getTrackDetails(track, function (err, details) {
			error(err);

			if (!details) {
				error(new Error('No details for ' + track));
			}

			var theseArtistMids = details.artists.map(function (value) { return value.mid; });
			seenArtists = seenArtists.concat(valuesNotIn(theseArtistMids, seenArtists));
			var name = details.name || 'WHOOPS, FREEBASE DOES NOT APPEAR TO HAVE AN ENGLISH NAME FOR THIS TRACK';
			var artist = details.artists.map(function (value) {
				return value.name || 'WHOOPS, FREEBASE DOES NOT APPEAR TO HAVE AN ENGLISH NAME FOR THIS ARTIST';
			}).join(' & ');
			var release = random(details.releases).name || 'WHOOPS, FREEBASE DOES NOT APPEAR TO HAVE AN ENGLISH NAME FOR THIS RELEASE';

			var output = '"' + name + '"';
			output += '\n' + artist;
			output += '\n_' + release + '_';
			console.log(output);

			routes.getArtistsAndContributorsFromTracks([track], function (err, contributors) {
				error(err);
				var contributor;
				var notSeen = valuesNotIn(contributors, seenIndividuals);
				if (notSeen.length > 0) {
					contributor = random(notSeen);
					seenIndividuals.push(contributor);
				} else {
					contributor = random(contributors);
				}
				routes.getArtistDetails(contributor, function (err, details) {
					var name = details.name || 'WHOOPS, FREEBASE DOES NOT HAVE AN ENGLISH NAME FOR THIS PERSON';
					console.log('\n ... with ' + name + ' ... \n');
					sourceIndividual = contributor;
					done();
				});
			});
		});
	};

	var options = seenArtists.length === 0 ? {} : {subquery: {
		artist: [{
					'mid|=': seenArtists,
					optional: 'forbidden'
		}]
	}};

	// next[nextIndex] = what function to invoke if the current one doesn't find a track
	var nextIndex = 0;
	var next = [
		// Find a track by an artist we haven't seen yet.
		routes.getTracksWithContributors.bind(undefined, [individual], options, callback),
		// Look for any track with this contributor credited as a contributor regardless if we've seen the artist already.
		routes.getTracksWithContributors.bind(undefined, [individual], {}, callback),
		// Look for any tracks actually credited to this contributor as the main artist. We are desperate!
		routes.getTracksByArtists.bind(undefined, [individual], {}, callback),
		// Give up
		error.bind(undefined, new Error('Could not find any tracks for contributor ' + individual))
	];

	// Kick it off
	next[nextIndex]();
};

var startingPoint = process.argv[2] || 'Todd Rundgren';
routes.getMids(startingPoint, '/music/artist', function (err, mids) {
	error(err);
	sourceIndividual = mids[0];
	if (! sourceIndividual) {
		console.log('Could not find an artist named ' + process.argv[2]);
		process.exit(0);
	}
	seenIndividuals.push(sourceIndividual);
	async.forever(
		function (next) {
			generatePlaylist(sourceIndividual, next);
		},
		error
	);
});<|endoftext|>


<commit_before>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * @namespace
 *
Using Camera API allows to invoke the native camera application to record video or take a picture and receive a path to the file stored.

 *
The methods are static and don't required to create an instance of a camera.

 * @toc {Media} Camera
 * @featureID blackberry.media.camera
 * @permission use_camera Permits the user to invoke the native camera application.
 * @permission [access_shared] Permits the user to retrieve a path to the file stored in the system.
 */
blackberry.media.camera = {

    /**
     * @function
     * @description Opens the camera and return a path to the onCaptured callback when a photo is taken.
     * @callback {function} onCaptured Method will be invoked when a picture is captured.
Expected signature: function onCaptured(filePath)
     * @callback {String} [onCaptured.filePath] Path to a picture captured by the camera.
     * @callback {function} [onCameraClosed] Method will be invoked on camera closed event.
Expected signature: function onCameraClosed()
     * @callback {function} [onError] Method will be invoked when an error occurs.
Expected signature: function onError()
     * @BB50+
     * @PB10
     */
    takePicture: function(onCaptured, onCameraClosed, onError) {
    },
    /**
     * @function
     * @description Opens the camera and return a path to the onCaptured callback when a video is taken.
     * @callback {function} onCaptured Method will be invoked when a video is recorded.
Expected signature: function onCaptured(filePath)
     * @callback {String} [onCaptured.filePath] Path to a video captured by the camera.
     * @callback {function} [onCameraClosed] Method will be invoked on camera closed event.
Expected signature: function onCameraClosed()
     * @callback {function} [onError] Method will be invoked when an error occurs.
Expected signature: function onError()
     * @BB50+
     * @PB10
     * @example
     * function takeVideo() {
     *   try {
     *     blackberry.media.camera.takeVideo(successCB, closedCB, errorCB);
     *   } catch(e) {
     *     alert("Error in supported: " + e);
     *   }
     * }
     *
     * function successCB(filePath) {
     *   alert("Succeed: " + filePath);
     * }
     *
     * function closedCB() {
     *   alert("Camera closed event");
     * }
     *
     * function errorCB() {
     *   alert("Error occured");
     * }
     */
    takeVideo: function(onCaptured, onCameraClosed, onError) {
    }
}<commit_msg>Made access_shared permission be a required parameter<commit_after>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * @namespace
 *
Using Camera API allows to invoke the native camera application to record video or take a picture and receive a path to the file stored.

 *
The methods are static and don't required to create an instance of a camera.

 * @toc {Media} Camera
 * @featureID blackberry.media.camera
 * @permission use_camera Permits your app to use the camera.
 * @permission access_shared Permits your app to retrieve a path to the file saved.
 */
blackberry.media.camera = {

    /**
     * @function
     * @description Opens the camera and return a path to the onCaptured callback when a photo is taken.
     * @callback {function} onCaptured Method will be invoked when a picture is captured.
Expected signature: function onCaptured(filePath)
     * @callback {String} [onCaptured.filePath] Path to a picture captured by the camera.
     * @callback {function} [onCameraClosed] Method will be invoked on camera closed event.
Expected signature: function onCameraClosed()
     * @callback {function} [onError] Method will be invoked when an error occurs.
Expected signature: function onError()
     * @BB50+
     * @PB10
     */
    takePicture: function(onCaptured, onCameraClosed, onError) {
    },
    /**
     * @function
     * @description Opens the camera and return a path to the onCaptured callback when a video is taken.
     * @callback {function} onCaptured Method will be invoked when a video is recorded.
Expected signature: function onCaptured(filePath)
     * @callback {String} [onCaptured.filePath] Path to a video captured by the camera.
     * @callback {function} [onCameraClosed] Method will be invoked on camera closed event.
Expected signature: function onCameraClosed()
     * @callback {function} [onError] Method will be invoked when an error occurs.
Expected signature: function onError()
     * @BB50+
     * @PB10
     * @example
     * function takeVideo() {
     *   try {
     *     blackberry.media.camera.takeVideo(successCB, closedCB, errorCB);
     *   } catch(e) {
     *     alert("Error in supported: " + e);
     *   }
     * }
     *
     * function successCB(filePath) {
     *   alert("Succeed: " + filePath);
     * }
     *
     * function closedCB() {
     *   alert("Camera closed event");
     * }
     *
     * function errorCB() {
     *   alert("Error occured");
     * }
     */
    takeVideo: function(onCaptured, onCameraClosed, onError) {
    }
}<|endoftext|>


<commit_before>var Boom = require('boom');
var Promise = require('bluebird');
var Tar = require('tar-stream');
var errors = require('./errors');

function BaseController(model)  {
  this.Model = model;
}

BaseController.prototype.formatRequestData = function(req) {
  // Abstract base method,
  // formats data for database entry
};

BaseController.prototype.formatResponseData = function(model) {
  // Base method to format data that will be sent in the response
  // By default, it returns the model as is
  return model;
};

BaseController.prototype.getOne = function(req, reply) {
  var record = this.formatResponseData(req.pre.records.models[0].toJSON());
  reply(req.generateResponse(record)
    .code(200));
};

BaseController.prototype.getAll = function(req, reply) {
  var records = req.pre.records.toJSON().map(this.formatResponseData);
  reply(req.generateResponse(records));
};

BaseController.prototype.update = function(req, reply) {
  var reqData = this.formatRequestData(req);

  var result = Promise.resolve().then(function() {
    var record = req.pre.records.models[0];

    record.set(reqData);
    if (!record.hasChanged()) {
      return record;
    }

    return record
      .save(record.changed, { patch: true, method: 'update' });
  })
  .then(function (updatedState) {
    return req.generateResponse(updatedState.toJSON()).code(200);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.create = function(req, reply) {
  var result = this.Model
    .forge(this.formatRequestData(req))
    .save()
    .then(function(record) {
      if (!record) {
        throw Boom.notFound(null, {
          error: 'Bookshelf error creating a resource'
        });
      }
      return req.generateResponse(record.toJSON())
        .code(201);
    })
    .catch(errors.generateErrorResponse);
  reply(result);
};

BaseController.prototype.delete = function(req, reply) {
  var record = req.pre.records.models[0];

  var result = Promise.resolve().then(function() {
    return record.destroy();
  })
  .then(function() {
    return req.generateResponse(record.toJSON())
      .code(204);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.getAllAsMeta = function(req, reply) {
  reply(req.generateResponse(req.pre.records.toJSON()));
};

BaseController.prototype.getAllAsTar = function(req, reply) {
  var files = req.pre.records.models;
  var tarStream = Tar.pack();
  var self = this;

  function startStreaming(files, model) {
    return Promise.map(files, function(file) {
      return model.query({
        where: {
          id: file.get('id')
        },
        columns: ['buffer']
      }).fetch().then(function(model) {
        tarStream.entry({ name: file.get('path') }, model.get('buffer'));
      });
    }).then(function() {
      tarStream.finalize();
    });
  }

  startStreaming(files, self.Model).catch(errors.generateErrorResponse);

  // Normally this type would be application/x-tar, but IE refuses to
  // decompress a gzipped stream when this is the type.
  return reply(tarStream)
    .header('Content-Type', 'application/octet-stream');
};

module.exports = BaseController;
<commit_msg>Distribute tar file creation across multiple turns of the event loop<commit_after>var Boom = require('boom');
var Promise = require('bluebird');
var Tar = require('tar-stream');
var errors = require('./errors');

function BaseController(model)  {
  this.Model = model;
}

BaseController.prototype.formatRequestData = function(req) {
  // Abstract base method,
  // formats data for database entry
};

BaseController.prototype.formatResponseData = function(model) {
  // Base method to format data that will be sent in the response
  // By default, it returns the model as is
  return model;
};

BaseController.prototype.getOne = function(req, reply) {
  var record = this.formatResponseData(req.pre.records.models[0].toJSON());
  reply(req.generateResponse(record)
    .code(200));
};

BaseController.prototype.getAll = function(req, reply) {
  var records = req.pre.records.toJSON().map(this.formatResponseData);
  reply(req.generateResponse(records));
};

BaseController.prototype.update = function(req, reply) {
  var reqData = this.formatRequestData(req);

  var result = Promise.resolve().then(function() {
    var record = req.pre.records.models[0];

    record.set(reqData);
    if (!record.hasChanged()) {
      return record;
    }

    return record
      .save(record.changed, { patch: true, method: 'update' });
  })
  .then(function (updatedState) {
    return req.generateResponse(updatedState.toJSON()).code(200);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.create = function(req, reply) {
  var result = this.Model
    .forge(this.formatRequestData(req))
    .save()
    .then(function(record) {
      if (!record) {
        throw Boom.notFound(null, {
          error: 'Bookshelf error creating a resource'
        });
      }
      return req.generateResponse(record.toJSON())
        .code(201);
    })
    .catch(errors.generateErrorResponse);
  reply(result);
};

BaseController.prototype.delete = function(req, reply) {
  var record = req.pre.records.models[0];

  var result = Promise.resolve().then(function() {
    return record.destroy();
  })
  .then(function() {
    return req.generateResponse(record.toJSON())
      .code(204);
  })
  .catch(errors.generateErrorResponse);

  reply(result);
};

BaseController.prototype.getAllAsMeta = function(req, reply) {
  reply(req.generateResponse(req.pre.records.toJSON()));
};

// NOTE: creating the tarball for a project can be a lengthy process, so
// we do it in multiple turns of the event loop, so that other requests
// don't get blocked.
BaseController.prototype.getAllAsTar = function(req, reply) {
  var files = req.pre.records.models;
  var tarStream = Tar.pack();
  var model = this.Model;

  function processFile(file) {
    return model.query({
      where: {
        id: file.get('id')
      },
      columns: ['buffer']
    }).fetch().then(function(model) {
      setImmediate(function() {
        tarStream.entry({ name: file.get('path') }, model.get('buffer'));
      });
    });
  }

  setImmediate(function() {
    Promise.map(files, processFile, { concurrency: 2 })
      .then(function() { tarStream.finalize(); })
      .catch(errors.generateErrorResponse);
  });

  // Normally this type would be application/x-tar, but IE refuses to
  // decompress a gzipped stream when this is the type.
  return reply(tarStream)
    .header('Content-Type', 'application/octet-stream');
};

module.exports = BaseController;
<|endoftext|>


<commit_before>const stripe = require( 'stripe' ),
      moment = require( 'moment' ),
      donation = require( '../models/Donation' );

/* define subscription plan types as per stripe API: https://stripe.com/docs/api#create_plan */
const plan_types = {

    monthly: {
        id: 'monthly',
        interval: 'month'
    },

    annual: {
        id: 'annual',
        interval: 'year'
    },

    semiannual: {
        id: 'semiannual',
        interval: 'month',
        interval_count: '6'  /* interval_count: The number of intervals between each subscription billing.
                                                For example, interval = month and interval_count = 3 bills every 3 months.
                                                Maximum of one year interval allowed (1 year, 12 months, or 52 weeks).*/
    }
};

// some helper functions
function createStripeCustomer( stripeToken, email ) {

    // create stripe customer
    return stripe.customers.create({
            email: email,
            source: stripeToken
    });
}

function createCharge( customer, amount ) {

    return stripe.charges.create({
        amount: amount,
        currency: 'usd',
        customer: customer.id
    });
}

function createPlan( customer, amount, plan_type ) {

    return stripe.plans.create({
        amount: amount,
        name: plan_type.id,
        id: plan_type.id,
        currency: 'usd',
        interval: plan_type.interval,
        interval_count: plan_type.interval_count ? plan_type.interval_count : 1
    });
}

function oneTimeCharge( stripeToken, email, amount ) {

    return new Promise( ( resolve, reject ) => {

            createStripeCustomer( stripeToken, email )
            .then( customer => createCharge( customer,amount ) )
            .then( charge => {
                // log the customer has been charged x
                resolve();
            })
            .catch( error => {
                // log the error
                reject();
            });
    });
}

function recurringCharge( stripeToken, email, amount, plan_type ) {

    return new Promise( ( resolve,reject ) => {

            createStripeCustomer( stripeToken, email )
            .then( customer => createPlan( customer,amount,plan_type ) )
            .then( plan => {
                //Log the plan has been created and is ready to be used
                resolve();
            })
            .catch( error => {
                //Log the error
                reject();
            });
    });
}

function getAllDonations() {

    return new Promise( ( resolve, reject ) => {

        Donation.model
            .find()
            .exec()
            .then( donations => {
                // if no donations could be found
                if( donations.length === 0 ) {
                    // log an error for debugging purposes
                    console.error( `no donations could be found` );
                }
                // resolve the promise with the donations
                resolve( donations );
            // if there was an error fetching from the database
            }, err => {
                // log an error for debugging purposes
                console.error( `error fetching donations - ${ err }` );
                // and reject the promise
                reject();
            });
    });
}
/* revealing module pattern to expose public methods */
exports = module.exports = {

    oneTimeCharge: oneTimeCharge,
    recurringCharge: recurringCharge,
    getAllDonations: getAllDonations
}<commit_msg>#25 | update reference in donation service to point to the correct location<commit_after>const stripe = require( 'stripe' ),
      moment = require( 'moment' ),
      Donation = require( '../../models/Donation' );

/* define subscription plan types as per stripe API: https://stripe.com/docs/api#create_plan */
const plan_types = {

    monthly: {
        id: 'monthly',
        interval: 'month'
    },

    annual: {
        id: 'annual',
        interval: 'year'
    },

    semiannual: {
        id: 'semiannual',
        interval: 'month',
        interval_count: '6'  /* interval_count: The number of intervals between each subscription billing.
                                                For example, interval = month and interval_count = 3 bills every 3 months.
                                                Maximum of one year interval allowed (1 year, 12 months, or 52 weeks).*/
    }
};

// some helper functions
function createStripeCustomer( stripeToken, email ) {

    // create stripe customer
    return stripe.customers.create({
            email: email,
            source: stripeToken
    });
}

function createCharge( customer, amount ) {

    return stripe.charges.create({
        amount: amount,
        currency: 'usd',
        customer: customer.id
    });
}

function createPlan( customer, amount, plan_type ) {

    return stripe.plans.create({
        amount: amount,
        name: plan_type.id,
        id: plan_type.id,
        currency: 'usd',
        interval: plan_type.interval,
        interval_count: plan_type.interval_count ? plan_type.interval_count : 1
    });
}

function oneTimeCharge( stripeToken, email, amount ) {

    return new Promise( ( resolve, reject ) => {

            createStripeCustomer( stripeToken, email )
            .then( customer => createCharge( customer,amount ) )
            .then( charge => {
                // log the customer has been charged x
                resolve();
            })
            .catch( error => {
                // log the error
                reject();
            });
    });
}

function recurringCharge( stripeToken, email, amount, plan_type ) {

    return new Promise( ( resolve,reject ) => {

            createStripeCustomer( stripeToken, email )
            .then( customer => createPlan( customer,amount,plan_type ) )
            .then( plan => {
                //Log the plan has been created and is ready to be used
                resolve();
            })
            .catch( error => {
                //Log the error
                reject();
            });
    });
}

function getAllDonations() {

    return new Promise( ( resolve, reject ) => {

        Donation.model
            .find()
            .exec()
            .then( donations => {
                // if no donations could be found
                if( donations.length === 0 ) {
                    // log an error for debugging purposes
                    console.error( `no donations could be found` );
                }
                // resolve the promise with the donations
                resolve( donations );
            // if there was an error fetching from the database
            }, err => {
                // log an error for debugging purposes
                console.error( `error fetching donations - ${ err }` );
                // and reject the promise
                reject();
            });
    });
}
/* revealing module pattern to expose public methods */
exports = module.exports = {

    oneTimeCharge: oneTimeCharge,
    recurringCharge: recurringCharge,
    getAllDonations: getAllDonations
}<|endoftext|>


<commit_before>"use strict";
var subscription_1 = require('./subscription');
var Message = (function () {
    function Message(message) {
        this.message = message;
        this._subscriptions = [];
        this._nextId = 0;
    }
    Message.prototype.subscribe = function (callback) {
        var subscription = new subscription_1.Subscription(this._nextId++, callback);
        this._subscriptions[subscription.id] = subscription;
        return subscription.id;
    };
    Message.prototype.unsubscribe = function (id) {
        this._subscriptions[id] = undefined;
    };
    Message.prototype.notify = function (payload) {
        for (var index = 0; index < this._subscriptions.length; index++) {
            if (this._subscriptions[index]) {
                this._subscriptions[index].callback(payload);
            }
        }
    };
    return Message;
}());
exports.Message = Message;
//# sourceMappingURL=message.js.map<commit_msg>Delete message.js<commit_after><|endoftext|>


<commit_before>const DESCRIPTION = "The awesome power of command line is finally releaved.";
const COPYRIGHT = "Developed with JavaScript and ♥ by Ionică Bizău";

var ImageToAscii = require("image-to-ascii")
  , Overlap = require("overlap")
  , myImage = new ImageToAscii ({
        resize: {
            width:  "100%"
          , height: "90%"
        }
      , multiplyWidth: 1
      , colored: true
    })
  ;

myImage.convert(__dirname + "/../resources/splash/tmuxos.png", function(err, converted) {
    if (err) { throw err; }
    console.log(Overlap({
        who: Overlap({
            who: converted.trim()
          , with: DESCRIPTION
          , where: {
                x: process.stdout.columns / 2 - DESCRIPTION.length / 2
              , y: converted.split("\n").length - 1
            }
        })
      , with: COPYRIGHT
      , where: {
            x: process.stdout.columns / 2 - COPYRIGHT.length / 2
          , y: converted.split("\n").length
        }
    }));
});
<commit_msg>Removed resources from tmuxos.png path<commit_after>const DESCRIPTION = "The awesome power of command line is finally releaved.";
const COPYRIGHT = "Developed with JavaScript and ♥ by Ionică Bizău";

var ImageToAscii = require("image-to-ascii")
  , Overlap = require("overlap")
  , myImage = new ImageToAscii ({
        resize: {
            width:  "100%"
          , height: "90%"
        }
      , multiplyWidth: 1
      , colored: true
    })
  ;

myImage.convert(__dirname + "/tmuxos.png", function(err, converted) {
    if (err) { throw err; }
    console.log(Overlap({
        who: Overlap({
            who: converted.trim()
          , with: DESCRIPTION
          , where: {
                x: process.stdout.columns / 2 - DESCRIPTION.length / 2
              , y: converted.split("\n").length - 1
            }
        })
      , with: COPYRIGHT
      , where: {
            x: process.stdout.columns / 2 - COPYRIGHT.length / 2
          , y: converted.split("\n").length
        }
    }));
});
<|endoftext|>