<commit_before>module.exports = function(grunt) {

	grunt.initConfig({

		pkg: grunt.file.readJSON('package.json'),

		// Copy files that don't need compilation to dist/
		copy: {
			dist: {
				files: [
					// Copy all (non hidden) files (not directories) from src
					{dest: 'dist/', src: '*', filter: 'isFile', expand: true, cwd: 'src/'},

					// Copy the following hidden files
					{dest: 'dist/.htaccess', src: 'src/.htaccess'},

					// Copy any JavaScript libs
					{dest: 'dist/', src: 'js/vendor/*.min.js', expand: true, cwd: 'src/'},

					// Copy any CSS files (not LESS src)
					{dest: 'dist/', src: 'css/**/*.css', expand: true, cwd: 'src/'},

					// Copy other resources
					{dest: 'dist/', src: 'img/**', expand: true, cwd: 'src/'},
					{dest: 'dist/', src: 'font/**', expand: true, cwd: 'src/'}
				]
			}
		},

		includereplace: {
			dist: {
				options: {
					globals: {
						version: '<%= pkg.version %>',
						headHtml: ''
					}
				},
				files: [
					{src: '*.html', dest: 'dist/', expand: true, cwd: 'src/'},
					{src: 'inc/*.html', dest: 'dist/', expand: true, cwd: 'src/'}
				]
			}
		},

		// Compile the mobile first site stylesheet (and the no @media queries version for lt-ie8)
		less: {
			compile: {
				files: {
					'dist/css/main.css': 'src/css/main.less',
					'dist/css/ie.css': 'src/css/ie.less'
				}
			}
		},

		// Minify the site script
		uglify: {
			options: {
				/*compress: true,*/
				mangle: true,
				preserveComments: false,
				report: 'min'
			},
			compress: {
				src: [
					'src/js/plugins.js',
					'src/js/vendor/cycle.js',
					'src/js/vendor/d3.js',
					'src/js/vendor/handlebars.js',
					'src/js/vendor/jquery.ba-bbq.js',
					'src/js/vendor/jquery.ba-hashchange.js',
					'src/js/vendor/jquery.fancybox.js',
					'src/js/vendor/jquery.feed.js',
					'src/js/vendor/lodash.js',
					'src/js/vendor/moment.js',
					'src/js/vendor/stackable.js',
					'src/js/main.js',
					'src/js/homepage.js',
					'src/js/status.js',
					'src/js/search.js'
				],
				dest: 'dist/js/pack.js'
			}
		},

		// Minify the site CSS
		cssmin: {
			compress: {
				options: {
					keepSpecialComments: 0,
					report: 'min'
				},
				files: {
					'dist/css/main.css': 'dist/css/main.css',
					'dist/css/font-awesome-ie7.css': 'dist/css/font-awesome-ie7.css',
					'dist/css/ie.css': 'dist/css/ie.css'
				}
			}
		},

		// Lint the server JavaScript
		jshint: {
			files: ['*.js', 'src/js/*.js', 'test/*.js'],
			options: {
				'browser': false,
				'maxerr': 100,
				'node': true,
				/*'camelcase': true,*/
				'curly': true,
				'eqeqeq': true,
				'eqnull': true,
				'forin': true,
				'immed': true,
				'indent': 4,
				/*'latedef': true,*/
				'laxbreak': true,
				'laxcomma': true,
				'lastsemic': true,
				'loopfunc': true,
				'noarg': true,
				'newcap': true,
				'plusplus': false,
				'quotmark': 'single',
				'regexp': true,
				'shadow': true,
				'smarttabs': true,
				'strict': false,
				'sub': true,
				'trailing': true,
				'undef': true,
				'unused': true,
				ignores: ['.git', 'node_modules']
			}
		},

		// Test the things
		nodeunit: {
			all: ['test/**/*_test.js']
		},

		// Watch JS, LESS & HTML files for changes, copy & compile but not minify for easy debug during dev
		watch: {
			project: {
				options: {atBegin: true},
				files: ['src/js/**/*.js', 'src/css/**/*.less', 'src/**/*.html', 'src/img/**/*'],
				tasks: ['copy', 'includereplace', 'less', 'uglify']
			}
		},

		clean: {
			dist: 'dist/*'
		}
	});

	// Load the grunt-conrtib plugin so we can compile and compress CoffeeScript and LESS files
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-cssmin');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-include-replace');
	grunt.loadNpmTasks('grunt-contrib-nodeunit');
	grunt.loadNpmTasks('grunt-contrib-clean');

	grunt.registerTask('default', ['jshint', 'nodeunit', 'copy', 'includereplace', 'less', 'uglify', 'cssmin']);
};
<commit_msg>Gruntfile.js: remove unneeded jshint option.<commit_after>module.exports = function(grunt) {

	grunt.initConfig({

		pkg: grunt.file.readJSON('package.json'),

		// Copy files that don't need compilation to dist/
		copy: {
			dist: {
				files: [
					// Copy all (non hidden) files (not directories) from src
					{dest: 'dist/', src: '*', filter: 'isFile', expand: true, cwd: 'src/'},

					// Copy the following hidden files
					{dest: 'dist/.htaccess', src: 'src/.htaccess'},

					// Copy any JavaScript libs
					{dest: 'dist/', src: 'js/vendor/*.min.js', expand: true, cwd: 'src/'},

					// Copy any CSS files (not LESS src)
					{dest: 'dist/', src: 'css/**/*.css', expand: true, cwd: 'src/'},

					// Copy other resources
					{dest: 'dist/', src: 'img/**', expand: true, cwd: 'src/'},
					{dest: 'dist/', src: 'font/**', expand: true, cwd: 'src/'}
				]
			}
		},

		includereplace: {
			dist: {
				options: {
					globals: {
						version: '<%= pkg.version %>',
						headHtml: ''
					}
				},
				files: [
					{src: '*.html', dest: 'dist/', expand: true, cwd: 'src/'},
					{src: 'inc/*.html', dest: 'dist/', expand: true, cwd: 'src/'}
				]
			}
		},

		// Compile the mobile first site stylesheet (and the no @media queries version for lt-ie8)
		less: {
			compile: {
				files: {
					'dist/css/main.css': 'src/css/main.less',
					'dist/css/ie.css': 'src/css/ie.less'
				}
			}
		},

		// Minify the site script
		uglify: {
			options: {
				/*compress: true,*/
				mangle: true,
				preserveComments: false,
				report: 'min'
			},
			compress: {
				src: [
					'src/js/plugins.js',
					'src/js/vendor/cycle.js',
					'src/js/vendor/d3.js',
					'src/js/vendor/handlebars.js',
					'src/js/vendor/jquery.ba-bbq.js',
					'src/js/vendor/jquery.ba-hashchange.js',
					'src/js/vendor/jquery.fancybox.js',
					'src/js/vendor/jquery.feed.js',
					'src/js/vendor/lodash.js',
					'src/js/vendor/moment.js',
					'src/js/vendor/stackable.js',
					'src/js/main.js',
					'src/js/homepage.js',
					'src/js/status.js',
					'src/js/search.js'
				],
				dest: 'dist/js/pack.js'
			}
		},

		// Minify the site CSS
		cssmin: {
			compress: {
				options: {
					keepSpecialComments: 0,
					report: 'min'
				},
				files: {
					'dist/css/main.css': 'dist/css/main.css',
					'dist/css/font-awesome-ie7.css': 'dist/css/font-awesome-ie7.css',
					'dist/css/ie.css': 'dist/css/ie.css'
				}
			}
		},

		// Lint the server JavaScript
		jshint: {
			files: ['*.js', 'src/js/*.js', 'test/*.js'],
			options: {
				'browser': false,
				'maxerr': 100,
				'node': true,
				/*'camelcase': true,*/
				'curly': true,
				'eqeqeq': true,
				'eqnull': true,
				'forin': true,
				'immed': true,
				'indent': 4,
				/*'latedef': true,*/
				'laxbreak': true,
				'laxcomma': true,
				'lastsemic': true,
				'loopfunc': true,
				'noarg': true,
				'newcap': true,
				'plusplus': false,
				'quotmark': 'single',
				'regexp': true,
				'shadow': true,
				'smarttabs': true,
				'strict': false,
				'sub': true,
				'trailing': true,
				'undef': true,
				'unused': true
			}
		},

		// Test the things
		nodeunit: {
			all: ['test/**/*_test.js']
		},

		// Watch JS, LESS & HTML files for changes, copy & compile but not minify for easy debug during dev
		watch: {
			project: {
				options: {atBegin: true},
				files: ['src/js/**/*.js', 'src/css/**/*.less', 'src/**/*.html', 'src/img/**/*'],
				tasks: ['copy', 'includereplace', 'less', 'uglify']
			}
		},

		clean: {
			dist: 'dist/*'
		}
	});

	// Load the grunt-conrtib plugin so we can compile and compress CoffeeScript and LESS files
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-cssmin');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-include-replace');
	grunt.loadNpmTasks('grunt-contrib-nodeunit');
	grunt.loadNpmTasks('grunt-contrib-clean');

	grunt.registerTask('default', ['jshint', 'nodeunit', 'copy', 'includereplace', 'less', 'uglify', 'cssmin']);
};
<|endoftext|>


<commit_before>'use strict';

var paths = {
  js: ['*.js', 'test/**/*.js', '!test/coverage/**', '!bower_components/**', 'packages/**/*.js', '!packages/**/node_modules/**', '!packages/contrib/**/*.js', '!packages/contrib/**/node_modules/**'],
  html: ['packages/**/public/**/views/**', 'packages/**/server/views/**'],
  css: ['!bower_components/**', 'packages/**/public/**/css/*.css', '!packages/contrib/**/public/**/css/*.css']
};

module.exports = function(grunt) {

  if (process.env.NODE_ENV !== 'production') {
    require('time-grunt')(grunt);
  }

  // Project Configuration
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    assets: grunt.file.readJSON('config/assets.json'),
    clean: ['bower_components/build'],
    watch: {
      js: {
        files: paths.js,
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      },
      html: {
        files: paths.html,
        options: {
          livereload: true,
          interval: 500
        }
      },
      css: {
        files: paths.css,
        tasks: ['csslint'],
        options: {
          livereload: true
        }
      }
    },
    jshint: {
      all: {
        src: paths.js,
        options: {
          jshintrc: true
        }
      }
    },
    uglify: {
      core: {
        options: {
          mangle: false
        },
        files: '<%= assets.core.js %>'
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      src: paths.css
    },
    cssmin: {
      core: {
        files: '<%= assets.core.css %>'
      }
    },
    nodemon: {
      dev: {
        script: 'server.js',
        options: {
          args: [],
          ignore: ['node_modules/**'],
          ext: 'js,html',
          //nodeArgs: ['--debug'],
          delayTime: 1,
          cwd: __dirname
        }
      }
    },
    concurrent: {
      tasks: ['nodemon', 'watch'],
      options: {
        logConcurrentOutput: true
      }
    },
    mochaTest: {
      options: {
        reporter: 'spec',
        require: [
          'server.js',
          function() {
            require('meanio/lib/core_modules/module/util').preload(__dirname + '/packages/**/server', 'model');
          }
        ]
      },
      src: ['packages/**/server/tests/**/*.js']
    },
    env: {
      test: {
        NODE_ENV: 'test'
      }
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js'
      }
    },
    forever: {
      server: {
        options: {
          index: 'server.js',
          logDir: 'logs'
        }
      }
    }
  });

  //Load NPM tasks
  require('load-grunt-tasks')(grunt);
  grunt.loadNpmTasks('grunt-forever');

  /**
   * Default Task
   */
  grunt.hook.push('clean', -9999);
  grunt.hook.push('concurrent', 9999);
  if (process.env.NODE_ENV === 'production') {
    grunt.hook.push('cssmin', 100);
    grunt.hook.push('uglify', 200);
  } else {
    grunt.hook.push('jshint', -200);
    grunt.hook.push('csslint', 100);
  }

  //Default task.
  grunt.registerTask('default', ['hook']);

  //Test task.
  grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);

  // For Heroku users only.
  // Docs: https://github.com/linnovate/mean/wiki/Deploying-on-Heroku
  grunt.registerTask('heroku:production', ['cssmin', 'uglify']);
};
<commit_msg>Enable logging in daemon mode<commit_after>'use strict';

var paths = {
  js: ['*.js', 'test/**/*.js', '!test/coverage/**', '!bower_components/**', 'packages/**/*.js', '!packages/**/node_modules/**', '!packages/contrib/**/*.js', '!packages/contrib/**/node_modules/**'],
  html: ['packages/**/public/**/views/**', 'packages/**/server/views/**'],
  css: ['!bower_components/**', 'packages/**/public/**/css/*.css', '!packages/contrib/**/public/**/css/*.css']
};

module.exports = function(grunt) {

  if (process.env.NODE_ENV !== 'production') {
    require('time-grunt')(grunt);
  }

  // Project Configuration
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    assets: grunt.file.readJSON('config/assets.json'),
    clean: ['bower_components/build'],
    watch: {
      js: {
        files: paths.js,
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      },
      html: {
        files: paths.html,
        options: {
          livereload: true,
          interval: 500
        }
      },
      css: {
        files: paths.css,
        tasks: ['csslint'],
        options: {
          livereload: true
        }
      }
    },
    jshint: {
      all: {
        src: paths.js,
        options: {
          jshintrc: true
        }
      }
    },
    uglify: {
      core: {
        options: {
          mangle: false
        },
        files: '<%= assets.core.js %>'
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      src: paths.css
    },
    cssmin: {
      core: {
        files: '<%= assets.core.css %>'
      }
    },
    nodemon: {
      dev: {
        script: 'server.js',
        options: {
          args: [],
          ignore: ['node_modules/**'],
          ext: 'js,html',
          //nodeArgs: ['--debug'],
          delayTime: 1,
          cwd: __dirname
        }
      }
    },
    concurrent: {
      tasks: ['nodemon', 'watch'],
      options: {
        logConcurrentOutput: true
      }
    },
    mochaTest: {
      options: {
        reporter: 'spec',
        require: [
          'server.js',
          function() {
            require('meanio/lib/core_modules/module/util').preload(__dirname + '/packages/**/server', 'model');
          }
        ]
      },
      src: ['packages/**/server/tests/**/*.js']
    },
    env: {
      test: {
        NODE_ENV: 'test'
      }
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js'
      }
    },
    forever: {
      server: {
        options: {
          index: 'server.js',
          logDir: 'logs',
          errFile: 'err.log',
          outFile: 'out.log',
          logFile: 'log.log'
        }
      }
    }
  });

  //Load NPM tasks
  require('load-grunt-tasks')(grunt);
  grunt.loadNpmTasks('grunt-forever');

  /**
   * Default Task
   */
  grunt.hook.push('clean', -9999);
  grunt.hook.push('concurrent', 9999);
  if (process.env.NODE_ENV === 'production') {
    grunt.hook.push('cssmin', 100);
    grunt.hook.push('uglify', 200);
  } else {
    grunt.hook.push('jshint', -200);
    grunt.hook.push('csslint', 100);
  }

  //Default task.
  grunt.registerTask('default', ['hook']);

  //Test task.
  grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);

  // For Heroku users only.
  // Docs: https://github.com/linnovate/mean/wiki/Deploying-on-Heroku
  grunt.registerTask('heroku:production', ['cssmin', 'uglify']);
};
<|endoftext|>


<commit_before>
// LinkRegExp -- Regular

var LinkRegExp = RegExp(''
  // word boundaries
  + '\b('

    // protocol and domain
    + '(?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)'

    // TODO: ???
    + '(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+'

    // Filepath + Query String
    + '(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’])'

  + ')',
  'i'
);

// LinkValidationInterface -- for determining whether links match.
// ---------------------------------------------------------------

var LinkValidationInterface = {

  // **validRegexes** list of valid LinkRegexes
  validRegexes: [
    LinkRegExp
  ],

  // urlMatches: returns whether a given url matches this Shell.
  // determined by the validRegexes above.
  urlMatches: function(url) {
    return _(this.validRegexes).find(function(re) {
      return re.test(url);
    });
  },

  isValidLink: function(link) {
    return !!this.urlMatches(link);
  },

};

acorn.util.isValidLink =
  _.bind(LinkValidationInterface.isValidLink, LinkValidationInterface);

// **acorn.shellForLink** returns a shell to match given link
// ----------------------------------------------------------

acorn.shellForLink = function(link, options) {

  var location = parseUrl(link);

  // filter out shells that don't derive from LinkShell.
  var linkShells = _(acorn.shells).filter(function (shell) {
    return derives(shell, acorn.shells.LinkShell);
  });

  // filter out shells that don't match this link.
  var matchingShells = _(linkShells).filter(function (linkShell) {
    return linkShell.prototype.isValidLink(location);
  });

  // reduce to the most specific shell (in terms of inheritance).
  var bestShell = _(matchingShells).reduce(function(bestShell, shell) {
    return derives(bestShell, shell) ? bestShell : shell;
  }, acorn.shells.LinkShell);

  // if all else fails, use LinkShell.
  bestShell = bestShell || acorn.shells.LinkShell;

  // setup options
  options = _.extend({}, options);
  options.data = {'link': link};
  options.location = location;

  return new bestShell(options);
};

// LinkShellAPI -- interface for determining whether links match.
// -------------------------------------------------------------------

var LinkShellAPI = {

  shellid: 'acorn.LinkShell',

  // The cannonical type of this media. One of `acorn.types`.
  type: 'link',

  // **link** is the main data kept by LinkShells
  link: function(link) {
    if (link !== undefined)
      this.data.link = link;
    return this.data.link;
  },

  // **title** returns a simple title of the shell
  title: function() { return this.link(); },

  // **description** returns a simple description of the shell
  description: function() { return ''; },

  // **thumbnailLink** returns the link to the thumbnail image
  thumbnailLink: function(link) {
    if (link !== undefined)
      this.data.thumbnailLink = link;
    return this.data.thumbnailLink;
  },

  extraInfoLink: function() { return ''; },

  // Retrieve extra information. Nothing by default.
  retrieveExtraInfo: function(callback) {
    callback = callback || function() {};

    var extraInfoLink = this.extraInfoLink();
    if (!extraInfoLink || this.extraInfo) {
      return callback();
    }

    var self = this;
    $.getJSON(extraInfoLink, function(data) {
      self.extraInfo = data;
      callback();
    });
  },

};

_.extend(LinkShellAPI, LinkValidationInterface);

// acorn.shells.LinkShell -- a shell that links to media and embeds it.
// --------------------------------------------------------------------

var LinkShell = acorn.shells.LinkShell = Shell.extend(LinkShellAPI);

// ContentView -- Simply displays the link text for now.
// TODO: thumbnail the website? embed the webpage in iframe?
// ---------------------------------------------------------

LinkShell.ContentView = Shell.ContentView.extend({

  initialize: function() {
    Shell.ContentView.prototype.initialize.call(this);

    assert(this.shell.link, 'No link provided to LinkShell.');

    this.location = this.options.location || parseUrl(this.shell.link());

    assert(this.shell.isValidLink(this.location),
      'Link provided does not match ' + this.shell.type);

  },

  render: function() {
    var link = this.shell.link();
    this.$el.append(iframe(link, 'link-iframe'));
  },

});

// LinkShell.EditView -- a text field for the link.
// --------------------------------------------------

LinkShell.EditView = Shell.EditView.extend({

  template: _.template('\
    \

\

\

\
  '),

  initialize: function() {
    Shell.EditView.prototype.initialize.call(this);

    this.linkView = new Backbone.components.EditableTextCmp.View({
      textFn: this.link,
      placeholder: 'Enter Link',
      validate: _.bind(this.validateLink, this),
      addToggle: true,
      onSave: _.bind(this.onSave, this),
      onEdit: _.bind(this.onEdit, this),
    });

  },

  validateLink: function(link) {
    link = parseUrl(link).toString();
    if (acorn.util.isValidLink(link))
      return false;

    return "invalid link."
  },

  link: function(link) {
    if (link) {
      link = parseUrl(link).toString();
      this.shell.link(link);
      var s = acorn.shellForLink(link, {shell: this.shell});

      // if the shellid has changed, we need to swap shells entirely.
      if (s.shellid != this.shell.data.shell)
        this.trigger('swap:shell', s.data);

      // else, announce that the shell has changed.
      else
        this.trigger('change:shell', this.shell);
    }
    return this.shell.link();
  },

  render: function() {
    Shell.EditView.prototype.render.call(this);

    // set thumbnail src
    var tlink = this.shell.thumbnailLink();
    this.$el.find('#thumbnail').attr('src', tlink);

    this.linkView.setElement(this.$el.find('#link'));
    this.linkView.render();

    if (!this.link())
      this.linkView.edit();
  },

  onSave: function() {
    if (!this.shouldSave())
      return; // bail out if we shouldn't save

    var self = this;
    this.generateThumbnailLink(function(data) {
      self.shell.thumbnailLink(data);

      // call super class onSave
      Shell.EditView.prototype.onSave.call(self);
    });
  },

  generateThumbnailLink: function(callback) {
    var self = this;
    var bounds = '600x600';
    var req_url = '/url2png/' + bounds + '/' + this.shell.link();
    $.ajax(req_url, {
      success: function(data) {
        callback(data);
      },
      error: function() {
        acorn.alert('Error: failed to generate thumbnail for link.',
                    'alert-error');
      }
    });
  },

});

// Register the shell with the acorn object.
acorn.registerShell(LinkShell);
<commit_msg>temporary LinkRegExp (gruber's fails).<commit_after>
// LinkRegExp -- Regular

// var LinkRegExp = RegExp(''
//   + '\b'                      // words
//   + '('                       // Capture 1: entire matched URL
//   +   '(?:'
//   +     'https?://'                   // http or https protocol
//   +     '|'                           // or
//   +     'www\d{0,3}[.]'               // "www.", "www1.", "www2." … "www999."
//   +     '|'                           // or
//   +     '[a-z0-9.\-]+[.][a-z]{2,4}/'  // domain name followed by a slash
//   +   ')'
//   +   '(?:'                       // One or more:
//   +     '[^\s()<>]+'                  // Run of non-space, non-()<>
//   +     '|'                           // or
//   +     '\(([^\s()<>]+|(\([^\s()<>]+\)))*\)' // balanced parens, up to 2 levels
//   +   ')+'
//   +   '(?:'                       // End with:
//   +     '\(([^\s()<>]+|(\([^\s()<>]+\)))*\)'  // balanced parens, up to 2 levels
//   +     '|'                               //   or
//   +     '[^\s`!()\[\]{};:\'".,<>?«»“”‘’]'  // not these punct chars
//   +   ')'
//   + ')',
//   'i'
// );
//

var LinkRegExp =
  RegExp('http://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]', 'i');

// LinkValidationInterface -- for determining whether links match.
// ---------------------------------------------------------------

var LinkValidationInterface = {

  // **validRegexes** list of valid LinkRegexes
  validRegexes: [
    LinkRegExp
  ],

  // urlMatches: returns whether a given url matches this Shell.
  // determined by the validRegexes above.
  urlMatches: function(url) {
    return _(this.validRegexes).find(function(re) {
      return re.test(url);
    });
  },

  isValidLink: function(link) {
    return !!this.urlMatches(link);
  },

};

acorn.util.isValidLink =
  _.bind(LinkValidationInterface.isValidLink, LinkValidationInterface);

// **acorn.shellForLink** returns a shell to match given link
// ----------------------------------------------------------

acorn.shellForLink = function(link, options) {

  var location = parseUrl(link);

  // filter out shells that don't derive from LinkShell.
  var linkShells = _(acorn.shells).filter(function (shell) {
    return derives(shell, acorn.shells.LinkShell);
  });

  // filter out shells that don't match this link.
  var matchingShells = _(linkShells).filter(function (linkShell) {
    return linkShell.prototype.isValidLink(location);
  });

  // reduce to the most specific shell (in terms of inheritance).
  var bestShell = _(matchingShells).reduce(function(bestShell, shell) {
    return derives(bestShell, shell) ? bestShell : shell;
  }, acorn.shells.LinkShell);

  // if all else fails, use LinkShell.
  bestShell = bestShell || acorn.shells.LinkShell;

  // setup options
  options = _.extend({}, options);
  options.data = {'link': link};
  options.location = location;

  return new bestShell(options);
};

// LinkShellAPI -- interface for determining whether links match.
// -------------------------------------------------------------------

var LinkShellAPI = {

  shellid: 'acorn.LinkShell',

  // The cannonical type of this media. One of `acorn.types`.
  type: 'link',

  // **link** is the main data kept by LinkShells
  link: function(link) {
    if (link !== undefined)
      this.data.link = link;
    return this.data.link;
  },

  // **title** returns a simple title of the shell
  title: function() { return this.link(); },

  // **description** returns a simple description of the shell
  description: function() { return ''; },

  // **thumbnailLink** returns the link to the thumbnail image
  thumbnailLink: function(link) {
    if (link !== undefined)
      this.data.thumbnailLink = link;
    return this.data.thumbnailLink;
  },

  extraInfoLink: function() { return ''; },

  // Retrieve extra information. Nothing by default.
  retrieveExtraInfo: function(callback) {
    callback = callback || function() {};

    var extraInfoLink = this.extraInfoLink();
    if (!extraInfoLink || this.extraInfo) {
      return callback();
    }

    var self = this;
    $.getJSON(extraInfoLink, function(data) {
      self.extraInfo = data;
      callback();
    });
  },

};

_.extend(LinkShellAPI, LinkValidationInterface);

// acorn.shells.LinkShell -- a shell that links to media and embeds it.
// --------------------------------------------------------------------

var LinkShell = acorn.shells.LinkShell = Shell.extend(LinkShellAPI);

// ContentView -- Simply displays the link text for now.
// TODO: thumbnail the website? embed the webpage in iframe?
// ---------------------------------------------------------

LinkShell.ContentView = Shell.ContentView.extend({

  initialize: function() {
    Shell.ContentView.prototype.initialize.call(this);

    assert(this.shell.link, 'No link provided to LinkShell.');

    this.location = this.options.location || parseUrl(this.shell.link());

    assert(this.shell.isValidLink(this.location),
      'Link provided does not match ' + this.shell.type);

  },

  render: function() {
    var link = this.shell.link();
    this.$el.append(iframe(link, 'link-iframe'));
  },

});

// LinkShell.EditView -- a text field for the link.
// --------------------------------------------------

LinkShell.EditView = Shell.EditView.extend({

  template: _.template('\
    \

\

\

\
  '),

  initialize: function() {
    Shell.EditView.prototype.initialize.call(this);

    this.linkView = new Backbone.components.EditableTextCmp.View({
      textFn: this.link,
      placeholder: 'Enter Link',
      validate: _.bind(this.validateLink, this),
      addToggle: true,
      onSave: _.bind(this.onSave, this),
      onEdit: _.bind(this.onEdit, this),
    });

  },

  validateLink: function(link) {
    link = parseUrl(link).toString();
    if (acorn.util.isValidLink(link))
      return false;

    return "invalid link."
  },

  link: function(link) {
    if (link) {
      link = parseUrl(link).toString();
      this.shell.link(link);
      var s = acorn.shellForLink(link, {shell: this.shell});

      // if the shellid has changed, we need to swap shells entirely.
      if (s.shellid != this.shell.data.shell)
        this.trigger('swap:shell', s.data);

      // else, announce that the shell has changed.
      else
        this.trigger('change:shell', this.shell);
    }
    return this.shell.link();
  },

  render: function() {
    Shell.EditView.prototype.render.call(this);

    // set thumbnail src
    var tlink = this.shell.thumbnailLink();
    this.$el.find('#thumbnail').attr('src', tlink);

    this.linkView.setElement(this.$el.find('#link'));
    this.linkView.render();

    if (!this.link())
      this.linkView.edit();
  },

  onSave: function() {
    if (!this.shouldSave())
      return; // bail out if we shouldn't save

    var self = this;
    this.generateThumbnailLink(function(data) {
      self.shell.thumbnailLink(data);

      // call super class onSave
      Shell.EditView.prototype.onSave.call(self);
    });
  },

  generateThumbnailLink: function(callback) {
    var self = this;
    var bounds = '600x600';
    var req_url = '/url2png/' + bounds + '/' + this.shell.link();
    $.ajax(req_url, {
      success: function(data) {
        callback(data);
      },
      error: function() {
        acorn.alert('Error: failed to generate thumbnail for link.',
                    'alert-error');
      }
    });
  },

});

// Register the shell with the acorn object.
acorn.registerShell(LinkShell);
<|endoftext|>


<commit_before>$(function() {

    for (var y = 0; y < 14; y++) {
        var row = $('<div/>', {
                'class': 'row'
            }).appendTo('.map');
        for (var x = 0; x < 14; x++) {
            var field = $('<div/>', {
                'data-x': x,
                'data-y': y,
                'class': 'field'
            }).appendTo(row);
            $('<div/>', {
                'class': 'field_back'
            }).appendTo(field);
            $('<div/>', {
                'class': 'field_content'
            }).appendTo(field);
            $('<div/>', {
                'class': 'field_holder'
            }).appendTo(field);
        }
    };

    var Game = function (socket) {
        this.socket = socket;
        this.id = null;
        this.player = null;
        this.phase = null;
        this.units = null;
    };

    Game.prototype.send = function (t, params) {
        socket.emit("command", {
            type: t,
            params: params
        });
    };

    Game.prototype.skip = function () {
        socket.emit("command", {
            type: 'skip'
        });
    };

    Game.prototype.update = function (snapshot) {
        $('.field_content').html('').removeClass().addClass('field_content');
        $('.field').removeClass().addClass('field').unbind('click')
                .removeData('from').removeData('whereCouldAttack').removeData('whereCanMove');
        $('body').unbind('keypress');
        this.id = snapshot.myId;
        this.player = snapshot.players[this.id];
        this.phase = snapshot.world.phase;
        for (var i in snapshot.players) {
            for (var v in snapshot.players[i].units) {
                var unit = snapshot.players[i].units[v];
                $('.field[data-x="' + unit.location[0] + '"][data-y="' + unit.location[1] + '"] .field_content')
                    .addClass('unit')
                    .addClass(i == this.id ? unit.type : 'unknownUnit')
                    .parents('.field').addClass('with_unit');
            }
        }
        this[this.phase](snapshot);
    };

    Game.prototype.hasUnitHere = function (x, y) {
        for (var v in this.player.units) {
            var unit = this.player.units[v];
            if (unit.location[0] == x && unit.location[1] == y) {
                return true;
            }
        }
        return false;
    };

    Game.prototype.planning_phase = function (snapshot) {
        $('.field.with_unit').addClass('can_move');
        var unit = null;
        for (var v in this.player.unitsToPlace) {
            if (this.player.unitsToPlace[v] > 0) {
                unit = v;
                break;
            }
        }
        var voidFields = this.player.freeCells;
        if (unit) {
            var field = voidFields.splice(Math.floor(Math.random() * voidFields.length), 1)[0];
            this.placeUnit(unit, field);
        }
    };

    Game.prototype.move_phase = function (snapshot) {
        if (snapshot.world.currentPlayerId != this.id) {
            return;
        }
        var me = this;
        for (var v in this.player.units) {
            var unit = this.player.units[v];
            if (unit.whereCanMove.length) {
                $('.field[data-x="' + unit.location[0] + '"][data-y="' + unit.location[1] + '"]')
                    .addClass('can_move')
                    .data('whereCanMove', unit.whereCanMove)
                    .click(function () {
                        $('.field').removeClass('move_from').removeClass('move_to').removeData('from');
                        $(this).addClass('move_from');
                        var whereCanMove = $(this).data('whereCanMove');
                        for (var i = 0; i < whereCanMove.length; i++) {
                            var p = whereCanMove[i];
                            $('.field[data-x="' + p[0] + '"][data-y="' + p[1] + '"]').addClass('move_to')
                                .data('from', [$(this).data('x'), $(this).data('y')])
                                .click(function () {
                                    me.send('move', { 'from': $(this).data('from'), 'to': [$(this).data('x'), $(this).data('y')] });
                                    $('.field').unbind('click');
                                });
                        }
                    });
            }
        }
    };

    Game.prototype.attack_phase = function (snapshot) {
        if (snapshot.world.currentPlayerId != this.id) {
            return;
        }
        var me = this;
        var skip = true;
        for (var v in this.player.units) {
            var unit = this.player.units[v];
            if (unit.whereCanAttack.length) {
                skip = false;
                $('.field[data-x="' + unit.location[0] + '"][data-y="' + unit.location[1] + '"]')
                    .addClass('can_move')
                    .data('whereCanMove', unit.whereCanAttack)
                    .data('whereCouldAttack', unit.whereCouldAttack)
                    .click(function () {
                        $('.field').removeClass('move_from').removeClass('move_to').removeClass('could_attack').removeData('from');
                        var whereCouldAttack = $(this).data('whereCouldAttack');
                        for (var i = 0; i < whereCouldAttack.length; i++) {
                            var place = whereCouldAttack[i];
                            $('.field[data-x="' + place[0] + '"][data-y="' + place[1] + '"]')
                                .addClass('could_attack');
                        }
                        $(this).addClass('move_from');
                        var whereCanMove = $(this).data('whereCanMove');
                        for (var i = 0; i < whereCanMove.length; i++) {
                            var p = whereCanMove[i];
                            $('.field[data-x="' + p[0] + '"][data-y="' + p[1] + '"]').addClass('move_to')
                                .data('from', [$(this).data('x'), $(this).data('y')])
                                .click(function () {
                                    me.send('attack', { 'from': $(this).data('from'), 'to': [$(this).data('x'), $(this).data('y')] });
                                    $('.field').unbind('click');
                                    $('body').unbind('keypress');
                                });
                        }
                    });
            }
        }
        if (skip) {
            me.skip();
            $('.field').unbind('click');
            $('body').unbind('keypress');
        } else {
            $("body").keypress(function(event) {
                // w
                if (event.charCode == 119) {
                    me.skip();
                    $('.field').unbind('click');
                    $('body').unbind('keypress');
                }
            });
        }
    };

    Game.prototype.support_phase = function (snapshot) {
        if (snapshot.world.currentPlayerId != this.id) {
            return;
        }
        if (!this.player.supportCells || !this.player.supportCells.length) {
            me.skip();
            $('.field').unbind('click');
            $('body').unbind('keypress');
        } else {
            $("body").keypress(function(event) {
                // w
                if (event.charCode == 119) {
                    me.skip();
                    $('.field').unbind('click');
                    $('body').unbind('keypress');
                }
            });
        }
        var me = this;
        for (var v in this.player.supportCells) {
            var place = this.player.supportCells[v];
            $('.field[data-x="' + place[0] + '"][data-y="' + place[1] + '"]')
                .addClass('can_move')
                .click(function () {
                    me.send('support', { 'target': [$(this).data('x'), $(this).data('y')] });
                    $('.field').unbind('click');
                    $('body').unbind('keypress');
                });
        }
    };

    Game.prototype.battle_results_phase = function (snapshot) {
        this.skip();
    };

    Game.prototype.placeUnit = function (unit, place) {
        this.send('place', { 'location': place, 'type': unit });
    };

    var socket = io.connect(":" + LocalConfig.port);
    var game = new Game(socket);

    socket.on("update", function (snapshot) {
        console.log(snapshot);
        game.update(snapshot);
    });
});

<commit_msg>client results: waiting<commit_after>$(function() {

    for (var y = 0; y < 14; y++) {
        var row = $('<div/>', {
                'class': 'row'
            }).appendTo('.map');
        for (var x = 0; x < 14; x++) {
            var field = $('<div/>', {
                'data-x': x,
                'data-y': y,
                'class': 'field'
            }).appendTo(row);
            $('<div/>', {
                'class': 'field_back'
            }).appendTo(field);
            $('<div/>', {
                'class': 'field_content'
            }).appendTo(field);
            $('<div/>', {
                'class': 'field_holder'
            }).appendTo(field);
        }
    };

    var Game = function (socket) {
        this.socket = socket;
        this.id = null;
        this.player = null;
        this.phase = null;
        this.units = null;
    };

    Game.prototype.send = function (t, params) {
        socket.emit("command", {
            type: t,
            params: params
        });
    };

    Game.prototype.skip = function () {
        socket.emit("command", {
            type: 'skip'
        });
    };

    Game.prototype.update = function (snapshot) {
        $('.field_content').html('').removeClass().addClass('field_content');
        $('.field').removeClass().addClass('field').unbind('click')
                .removeData('from').removeData('whereCouldAttack').removeData('whereCanMove');
        $('body').unbind('keypress');
        this.id = snapshot.myId;
        this.player = snapshot.players[this.id];
        this.phase = snapshot.world.phase;
        for (var i in snapshot.players) {
            for (var v in snapshot.players[i].units) {
                var unit = snapshot.players[i].units[v];
                $('.field[data-x="' + unit.location[0] + '"][data-y="' + unit.location[1] + '"] .field_content')
                    .addClass('unit')
                    .addClass(i == this.id ? unit.type : 'unknownUnit')
                    .parents('.field').addClass('with_unit');
            }
        }
        this[this.phase](snapshot);
    };

    Game.prototype.hasUnitHere = function (x, y) {
        for (var v in this.player.units) {
            var unit = this.player.units[v];
            if (unit.location[0] == x && unit.location[1] == y) {
                return true;
            }
        }
        return false;
    };

    Game.prototype.planning_phase = function (snapshot) {
        $('.field.with_unit').addClass('can_move');
        var unit = null;
        for (var v in this.player.unitsToPlace) {
            if (this.player.unitsToPlace[v] > 0) {
                unit = v;
                break;
            }
        }
        var voidFields = this.player.freeCells;
        if (unit) {
            var field = voidFields.splice(Math.floor(Math.random() * voidFields.length), 1)[0];
            this.placeUnit(unit, field);
        }
    };

    Game.prototype.move_phase = function (snapshot) {
        if (snapshot.world.currentPlayerId != this.id) {
            return;
        }
        var me = this;
        for (var v in this.player.units) {
            var unit = this.player.units[v];
            if (unit.whereCanMove.length) {
                $('.field[data-x="' + unit.location[0] + '"][data-y="' + unit.location[1] + '"]')
                    .addClass('can_move')
                    .data('whereCanMove', unit.whereCanMove)
                    .click(function () {
                        $('.field').removeClass('move_from').removeClass('move_to').removeData('from');
                        $(this).addClass('move_from');
                        var whereCanMove = $(this).data('whereCanMove');
                        for (var i = 0; i < whereCanMove.length; i++) {
                            var p = whereCanMove[i];
                            $('.field[data-x="' + p[0] + '"][data-y="' + p[1] + '"]').addClass('move_to')
                                .data('from', [$(this).data('x'), $(this).data('y')])
                                .click(function () {
                                    me.send('move', { 'from': $(this).data('from'), 'to': [$(this).data('x'), $(this).data('y')] });
                                    $('.field').unbind('click');
                                });
                        }
                    });
            }
        }
    };

    Game.prototype.attack_phase = function (snapshot) {
        if (snapshot.world.currentPlayerId != this.id) {
            return;
        }
        var me = this;
        var skip = true;
        for (var v in this.player.units) {
            var unit = this.player.units[v];
            if (unit.whereCanAttack.length) {
                skip = false;
                $('.field[data-x="' + unit.location[0] + '"][data-y="' + unit.location[1] + '"]')
                    .addClass('can_move')
                    .data('whereCanMove', unit.whereCanAttack)
                    .data('whereCouldAttack', unit.whereCouldAttack)
                    .click(function () {
                        $('.field').removeClass('move_from').removeClass('move_to').removeClass('could_attack').removeData('from');
                        var whereCouldAttack = $(this).data('whereCouldAttack');
                        for (var i = 0; i < whereCouldAttack.length; i++) {
                            var place = whereCouldAttack[i];
                            $('.field[data-x="' + place[0] + '"][data-y="' + place[1] + '"]')
                                .addClass('could_attack');
                        }
                        $(this).addClass('move_from');
                        var whereCanMove = $(this).data('whereCanMove');
                        for (var i = 0; i < whereCanMove.length; i++) {
                            var p = whereCanMove[i];
                            $('.field[data-x="' + p[0] + '"][data-y="' + p[1] + '"]').addClass('move_to')
                                .data('from', [$(this).data('x'), $(this).data('y')])
                                .click(function () {
                                    me.send('attack', { 'from': $(this).data('from'), 'to': [$(this).data('x'), $(this).data('y')] });
                                    $('.field').unbind('click');
                                    $('body').unbind('keypress');
                                });
                        }
                    });
            }
        }
        if (skip) {
            me.skip();
            $('.field').unbind('click');
            $('body').unbind('keypress');
        } else {
            $("body").keypress(function(event) {
                // w
                if (event.charCode == 119) {
                    me.skip();
                    $('.field').unbind('click');
                    $('body').unbind('keypress');
                }
            });
        }
    };

    Game.prototype.support_phase = function (snapshot) {
        if (snapshot.world.currentPlayerId != this.id) {
            return;
        }
        if (!this.player.supportCells || !this.player.supportCells.length) {
            me.skip();
            $('.field').unbind('click');
            $('body').unbind('keypress');
        } else {
            $("body").keypress(function(event) {
                // w
                if (event.charCode == 119) {
                    me.skip();
                    $('.field').unbind('click');
                    $('body').unbind('keypress');
                }
            });
        }
        var me = this;
        for (var v in this.player.supportCells) {
            var place = this.player.supportCells[v];
            $('.field[data-x="' + place[0] + '"][data-y="' + place[1] + '"]')
                .addClass('can_move')
                .click(function () {
                    me.send('support', { 'target': [$(this).data('x'), $(this).data('y')] });
                    $('.field').unbind('click');
                    $('body').unbind('keypress');
                });
        }
    };

    Game.prototype.battle_results_phase = function (snapshot) {
        var me = this;
        var needToSkip = true;
        for (var i in snapshot.waitingForPlayerIds) {
            if (snapshot.waitingForPlayerIds[i] == this.id) {
                needToSkip = false;
                break;
            }
        }
        if (needToSkip) {
            $("body").keypress(function(event) {
                // w
                if (event.charCode == 119) {
                    me.skip();
                    $('body').unbind('keypress');
                }
            });
        }
    };

    Game.prototype.placeUnit = function (unit, place) {
        this.send('place', { 'location': place, 'type': unit });
    };

    var socket = io.connect(":" + LocalConfig.port);
    var game = new Game(socket);

    socket.on("update", function (snapshot) {
        console.log(snapshot);
        game.update(snapshot);
    });
});

<|endoftext|>


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

'use strict';

// Intrinsic modules.
var crypto = require('crypto');
var util = require('util');

// Npm modulez
var _ = require('lodash');
var Promise = require('bluebird');
Promise.longStackTraces();

/*
 * Constructor.
 */
function Client(image, kbox) {

  this.image = image;
  this.kbox = kbox;

}

/*
 * Return the metric record's ID, or create one if it doesn't have one.
 */
Client.prototype.__buildQuery = function(cmd, args, options) {

  cmd.unshift('terminus');
  return cmd.concat(args).concat(options);

};

/*
 * Send and handle a REST request.
 */
Client.prototype.__request = function(cmd, args, options) {

  // Save for later.
  var self = this;

  // Build create options.
  var hashMe = crypto.createHash('sha1').digest('hex');
  var createOpts = this.kbox.util.docker.CreateOpts(hashMe)
    .json();
  /* jshint ignore:start */
  //jscs:disable
  createOpts.Entrypoint = ["/bin/sh", "-c"];
  /* jshint ignore:end */

  // Get provider.
  return kbox.engine.provider()
  // Create app.
  .then(function(provider) {
    // Build start options
    var home = kbox.core.deps.lookup('globalConfig').home;
    var startOpts = this.kbox.util.docker.StartOpts()
      .bind(path.join(home, '.terminus'), '/root/.terminus')
      .json();

    var query = self.__buildQuery(cmd, args, options);
    return this.kbox.engine.use(this.image, createOpts, startOpts, function(container) {
      return self.kbox.engine.queryData(container.id, query);
    });
  }
};

/*
 * Get connection mode
 * terminus site connection-mode --site="$PANTHEON_SITE" --env="$PANTHEON_ENV")
 */
Client.prototype.getConnectionMode = function(site, env) {

  // @todo: can we use something like optimist to do better
  // options parsing?
  return this.__request(
    ['site'],
    ['connection-mode'],
    ['--json', '--site=' + site, '--env=' + env]
  );

};

// Return constructor as the module object.
module.exports = Client;
<commit_msg>#257: UWTF<commit_after>#!/usr/bin/env node

'use strict';

// Intrinsic modules.
var crypto = require('crypto');
var util = require('util');
var path = require('path');

// Npm modulez
var _ = require('lodash');
var Promise = require('bluebird');
Promise.longStackTraces();

/*
 * Constructor.
 */
function Client(image, kbox) {

  this.image = image;
  this.kbox = kbox;

}

/*
 * Return the metric record's ID, or create one if it doesn't have one.
 */
Client.prototype.__buildQuery = function(cmd, args, options) {

  cmd.unshift('terminus');
  return cmd.concat(args).concat(options);

};

/*
 * Send and handle a REST request.
 */
Client.prototype.__request = function(cmd, args, options) {

  // Save for later.
  var self = this;

  // Build create options.
  var hashMe = crypto.createHash('sha1').digest('hex');
  var createOpts = this.kbox.util.docker.CreateOpts(hashMe)
    .json();
  /* jshint ignore:start */
  //jscs:disable
  createOpts.Entrypoint = ["/bin/sh", "-c"];
  /* jshint ignore:end */

  // Get provider.
  return this.kbox.engine.provider()
  // Create app.
  .then(function(provider) {
    // Build start options
    var home = this.kbox.core.deps.lookup('globalConfig').home;
    var startOpts = this.kbox.util.docker.StartOpts()
      .bind(path.join(home, '.terminus'), '/root/.terminus')
      .json();

    var query = self.__buildQuery(cmd, args, options);
    return this.kbox.engine.use(this.image, createOpts, startOpts, function(container) {
      return self.kbox.engine.queryData(container.id, query);
    });
  });
};

/*
 * Get connection mode
 * terminus site connection-mode --site="$PANTHEON_SITE" --env="$PANTHEON_ENV")
 */
Client.prototype.getConnectionMode = function(site, env) {

  // @todo: can we use something like optimist to do better
  // options parsing?
  return this.__request(
    ['site'],
    ['connection-mode'],
    ['--json', '--site=' + site, '--env=' + env]
  );

};

// Return constructor as the module object.
module.exports = Client;
<|endoftext|>


<commit_before>const gulp = require('gulp');
const args = require('yargs').argv;
const colors = require('colors');
const fs = require('fs');
const util = require('util');
const path = require('path');
const execSync = require('child_process').execSync;

const mappings = {
  'analysisservices': {
    'dir': 'analysisServices/lib',
    'source': 'arm-analysisservices/2016-05-16/swagger/analysisservices.json',
  },
  'authorization': {
    'dir': 'authorizationManagement/lib',
    'source': 'arm-authorization/2015-07-01/swagger/authorization.json',
    'ft': 1
  },
  'batch.Management': {
    'dir': 'batchManagement/lib',
    'source': 'arm-batch/2017-01-01/swagger/BatchManagement.json',
    'ft': 1
  },
  'batch.Service': {
    'dir': 'batch/lib',
    'source': 'batch/2017-01-01.4.0/swagger/BatchService.json',
    'ft': 1
  },
  'cdn': {
    'dir': 'cdnManagement/lib',
    'source': 'arm-cdn/2016-10-02/swagger/cdn.json',
    'ft': 2
  },
  'compute': {
    'dir': 'computeManagement2/lib',
    'source': 'arm-compute/compositeComputeClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'datalake.analytics.account': {
    'dir': 'dataLake.Analytics/lib/account',
    'source': 'arm-datalake-analytics/account/2015-10-01-preview/swagger/account.json'
  },
  'datalake.analytics.job': {
    'dir': 'dataLake.Analytics/lib/job',
    'source': 'arm-datalake-analytics/job/2016-03-20-preview/swagger/job.json'
  },
  'datalake.analytics.catalog': {
    'dir': 'dataLake.Analytics/lib/catalog',
    'source': 'arm-datalake-analytics/catalog/2015-10-01-preview/swagger/catalog.json'
  },
  'datalake.store.account': {
    'dir': 'dataLake.Store/lib/account',
    'source': 'arm-datalake-store/account/2015-10-01-preview/swagger/account.json'
  },
  'datalake.store.filesystem': {
    'dir': 'dataLake.Store/lib/filesystem',
    'source': 'arm-datalake-store/filesystem/2015-10-01-preview/swagger/filesystem.json'
  },
  'devtestlabs': {
    'dir': 'devTestLabs/lib',
    'source': 'arm-devtestlabs/2016-05-15/swagger/DTL.json'
  },
  'dns': {
    'dir': 'dnsManagement/lib',
    'source': 'arm-dns/2016-04-01/swagger/dns.json'
  },
  'eventhub': {
    'dir': 'eventHubManagement/lib',
    'source': 'arm-eventhub/2015-08-01/swagger/EventHub.json'
  },
  'graph': {
    'dir': 'graphManagement/lib',
    'source': 'arm-graphrbac/compositeGraphRbacManagementClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'intune': {
    'dir': 'intune/lib',
    'source': 'arm-intune/2015-01-14-preview/swagger/intune.json',
  },
  'insights': {
    'dir': 'insights/lib',
    'source': 'insights/compositeInsightsClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'insights.management': {
    'dir': 'insightsManagement/lib',
    'source': 'arm-insights/compositeInsightsManagementClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'iothub': {
    'dir': 'iothub/lib',
    'source': 'arm-iothub/2016-02-03/swagger/iothub.json',
    'ft': 1
  },
  'keyvault': {
    'dir': 'keyvault/lib',
    'source': 'keyvault/2015-06-01/swagger/keyvault.json',
    'ft': 1
  },
  'keyvaultmanagement': {
    'dir': 'keyVaultManagement/lib',
    'source': 'arm-keyvault/2015-06-01/swagger/keyvault.json',
    'ft': 1
  },
  'network': {
    'dir': 'networkManagement2/lib',
    'source': 'arm-network/2016-09-01/swagger/network.json',
    'ft': 1
  },
  'notificationHubs': {
    'dir': 'notificationHubsManagement/lib',
    'source': 'arm-notificationhubs/2016-03-01/swagger/notificationhubs.json'
  },
  'powerbiembedded': {
    'dir': 'powerbiembedded/lib',
    'source': 'arm-powerbiembedded/2016-01-29/swagger/powerbiembedded.json'
  },
  'rediscache': {
    'dir': 'rediscachemanagement/lib',
    'source': 'arm-redis/2016-04-01/swagger/redis.json',
    'ft': 1
  },
  'resource': {
    'dir': 'resourceManagement/lib/resource',
    'source': 'arm-resources/resources/2016-09-01/swagger/resources.json'
  },
  'resource.subscription': {
    'dir': 'resourceManagement/lib/subscription',
    'source': 'arm-resources/subscriptions/2016-06-01/swagger/subscriptions.json'
  },
  'resource.lock': {
    'dir': 'resourceManagement/lib/lock',
    'source': 'arm-resources/locks/2015-01-01/swagger/locks.json'
  },
  'resource.link': {
    'dir': 'resourceManagement/lib/link',
    'source': 'arm-resources/links/2016-09-01/swagger/links.json'
  },
  'resource.feature': {
    'dir': 'resourceManagement/lib/feature',
    'source': 'arm-resources/features/2015-12-01/swagger/features.json'
  },
  'resource.policy': {
    'dir': 'resourceManagement/lib/policy',
    'source': 'arm-resources/policy/2016-04-01/swagger/policy.json'
  },
  'servermanagement': {
    'dir': 'servermanagement/lib',
    'source': 'arm-servermanagement/2015-07-01-preview/servermanagement.json'
  },
  'servicebus.management': {
    'dir': 'serviceBusManagement2/lib',
    'source': 'arm-servicebus/2015-08-01/swagger/servicebus.json'
  },
  'serviceFabric': {
    'dir': 'serviceFabric/lib',
    'source': 'servicefabric/2016-01-28/swagger/servicefabric.json',
    'language': 'NodeJS'
  },
  'storage': {
    'dir': 'storageManagement2/lib',
    'source': 'arm-storage/2016-12-01/swagger/storage.json',
    'ft': 2,
    'ClientName': 'StorageManagementClient'
  },
  'traffic': {
    'dir': 'trafficManagerManagement2/lib',
    'source': 'arm-trafficmanager/2015-11-01/swagger/trafficmanager.json',
    'ft': 1
  },
  'website': {
    'dir': 'websiteManagement2/lib',
    'source': 'arm-web/2015-08-01/swagger/service.json',
    'ft': 1
  }
};

const defaultAutoRestVersion = '1.0.1-20170317-2300-nightly';
var usingAutoRestVersion;
const specRoot = args['spec-root'] || "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master";
const project = args['project'];
const language = 'Azure.NodeJS';
const modeler = 'Swagger';

function getAutorestVersion(version) {
  if (!version) version = 'latest';
  let getVersion, execHelp;
  let result = true;
  try {
    let getVersionCmd = `autorest --version=${version}`;
    let execHelpCmd = `autorest --help`;
    console.log(getVersionCmd);
    getVersion = execSync(getVersionCmd, { encoding: 'utf8' });
    //console.debug(getVersion);
    console.log(execHelpCmd);
    execHelp = execSync(execHelpCmd, { encoding: 'utf8' });
    //console.debug(execHelp);
  } catch (err) {
    result = false;
    console.log(`An error occurred while getting the "${version}" of autorest and executing "autorest --help":\n ${util.inspect(err, { depth: null })}.`);
  }
  return result;
}

function generateProject(project, specRoot, autoRestVersion) {
  let currentModeler = modeler;
  let specPath = specRoot + '/' + mappings[project].source;
  let result;
  //servicefabric wants to generate using generic NodeJS.
  if (mappings[project].language && mappings[project].language.match(/^NodeJS$/ig) !== null) {
    language = mappings[project].language;
  }
  //default Modeler is Swagger. However, some services may want to use CompositeSwaggerModeler
  if (mappings[project].modeler && mappings[project].modeler.match(/^CompositeSwagger$/ig) !== null) {
    currentModeler = mappings[project].modeler;
  }
  console.log(`\n>>>>>>>>>>>>>>>>>>>Start: "${project}" >>>>>>>>>>>>>>>>>>>>>>>>>`);

  let cmd = util.format('autorest -Modeler %s -CodeGenerator %s -Input %s  -outputDirectory lib/services/%s -Header MICROSOFT_MIT_NO_VERSION --version=%s',
    currentModeler, language, specPath, mappings[project].dir, autoRestVersion);
  if (mappings[project].ft !== null && mappings[project].ft !== undefined) cmd += ' -FT ' + mappings[project].ft;
  if (mappings[project].ClientName !== null && mappings[project].ClientName !== undefined) cmd += ' -ClientName ' + mappings[project].ClientName;
  if (mappings[project].args !== undefined) {
    cmd = cmd + ' ' + args;
  }

  try {
    console.log('Executing command:');
    console.log('------------------------------------------------------------');
    console.log(cmd);
    console.log('------------------------------------------------------------');
    result = execSync(cmd, { encoding: 'utf8' });
    console.log('Output:');
    console.log(result);
  } catch (err) {
    console.log('Error:');
    console.log(`An error occurred while generating client for project: "${project}":\n ${util.inspect(err, { depth: null })}`);
  }
  console.log(`>>>>>>>>>>>>>>>>>>>>>End: "${project}" >>>>>>>>>>>>>>>>>>>>>>>>>\n`);
  return;
}

function installAutorest() {
  let installation;
  let isSuccessful = true;
  let autorestAlreadyInstalled = true;
  try {
    execSync(`autorest --help`);
  } catch (error) {
    autorestAlreadyInstalled = false;
  }
  try {
    if (!autorestAlreadyInstalled) {
      console.log('Looks like autorest is not installed on your machine. Installing autorest . . .');
      let installCmd = 'npm install -g autorest';
      console.log(installCmd);
      installation = execSync(installCmd, { encoding: 'utf8' });
      //console.debug('installation');
    }
    isSuccessful = getAutorestVersion();
  } catch (err) {
    isSuccessful = false;
    console.log(`An error occurred while installing autorest via npm:\n ${util.inspect(err, { depth: null })}.`);
  }
  return isSuccessful;
}

function codegen(project, index) {
  let versionSuccessfullyFound = false;
  if (mappings[project].autorestversion) {
    usingAutoRestVersion = mappings[project].autoRestVersion;
  } else {
    usingAutoRestVersion = defaultAutoRestVersion;
  }
  if (index === 0) {
    versionSuccessfullyFound = getAutorestVersion(usingAutoRestVersion);
    if (!versionSuccessfullyFound) {
      process.exit(1);
    }
  }
  return generateProject(project, specRoot, usingAutoRestVersion);
}

gulp.task('default', function () {
  console.log("Usage: gulp codegen [--spec-root <swagger specs root>] [--project <project name>]\n");
  console.log("--spec-root");
  console.log("\tRoot location of Swagger API specs, default value is \"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master\"");
  console.log("--project\n\tProject to regenerate, default is all. List of available project names:");
  Object.keys(mappings).forEach(function (i) {
    console.log('\t' + i.magenta);
  });
});

gulp.task('codegen', function (cb) {
  if (installAutorest()) {
    if (project === undefined) {
      let arr = Object.keys(mappings);
      for (let i = 0; i < arr.length; i++) {
        codegen(arr[i], i);
      }
    } else {
      if (mappings[project] === undefined) {
        console.error('Invalid project name "' + project + '"!');
        process.exit(1);
      }
      codegen(project, null);
    }
  } else {
    process.exit(1);
  }
});<commit_msg>updated mappings in gulpfile - (ml, monitor rename, mobileEngage)<commit_after>const gulp = require('gulp');
const args = require('yargs').argv;
const colors = require('colors');
const fs = require('fs');
const util = require('util');
const path = require('path');
const execSync = require('child_process').execSync;

const mappings = {
  'advisor': {
    'dir': 'advisorManagement/lib',
    'source': 'arm-advisor/2016-07-12-preview/swagger/advisor.json',
  },
  'analysisservices': {
    'dir': 'analysisServices/lib',
    'source': 'arm-analysisservices/2016-05-16/swagger/analysisservices.json',
  },
  'authorization': {
    'dir': 'authorizationManagement/lib',
    'source': 'arm-authorization/2015-07-01/swagger/authorization.json',
    'ft': 1
  },
  'automation': {
    'dir': 'automationManagement/lib',
    'source': 'arm-automation/compositeAutomation.json',
    'modeler': 'CompositeSwagger'
  },
  'batch.Management': {
    'dir': 'batchManagement/lib',
    'source': 'arm-batch/2017-01-01/swagger/BatchManagement.json',
    'ft': 1
  },
  'batch.Service': {
    'dir': 'batch/lib',
    'source': 'batch/2017-01-01.4.0/swagger/BatchService.json',
    'ft': 1
  },
  'billing': {
    'dir': 'billingManagement/lib',
    'source': 'arm-billing/2017-02-27-preview/swagger/billing.json',
    'ft': 1
  },
  'cdn': {
    'dir': 'cdnManagement/lib',
    'source': 'arm-cdn/2016-10-02/swagger/cdn.json',
    'ft': 2
  },
  'coginitiveServices': {
    'dir': 'coginitiveServicesManagement/lib',
    'source': 'arm-cognitiveservices/2016-02-01-preview/swagger/cognitiveservices.json'
  },
  'commerce': {
    'dir': 'commerce/lib',
    'source': 'arm-commerce/2015-06-01-preview/swagger/commerce.json',
    'ft': 2
  },
  'compute': {
    'dir': 'computeManagement2/lib',
    'source': 'arm-compute/compositeComputeClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'containerRegistry': {
    'dir': 'containerRegistryManagement/lib',
    'source': 'arm-containerregistry/2017-03-01/swagger/containerregistry.json'
  },
  'customerInsights': {
    'dir': 'customerInsightsManagement/lib',
    'source': 'arm-customer-insights/2017-01-01/swagger/customer-insights.json'
  },
  'datalake.analytics.account': {
    'dir': 'dataLake.Analytics/lib/account',
    'source': 'arm-datalake-analytics/account/2016-11-01/swagger/account.json'
  },
  'datalake.analytics.job': {
    'dir': 'dataLake.Analytics/lib/job',
    'source': 'arm-datalake-analytics/job/2016-11-01/swagger/job.json'
  },
  'datalake.analytics.catalog': {
    'dir': 'dataLake.Analytics/lib/catalog',
    'source': 'arm-datalake-analytics/catalog/2016-11-01/swagger/catalog.json'
  },
  'datalake.store.account': {
    'dir': 'dataLake.Store/lib/account',
    'source': 'arm-datalake-store/account/2016-11-01/swagger/account.json'
  },
  'datalake.store.filesystem': {
    'dir': 'dataLake.Store/lib/filesystem',
    'source': 'arm-datalake-store/filesystem/2016-11-01/swagger/filesystem.json'
  },
  'devtestlabs': {
    'dir': 'devTestLabs/lib',
    'source': 'arm-devtestlabs/2016-05-15/swagger/DTL.json'
  },
  'dns': {
    'dir': 'dnsManagement/lib',
    'source': 'arm-dns/2016-04-01/swagger/dns.json'
  },
  'documentdb': {
    'dir': 'documentdbManagement/lib',
    'source': 'arm-documentdb/2015-04-08/swagger/documentdb.json'
  },
  'eventhub': {
    'dir': 'eventHubManagement/lib',
    'source': 'arm-eventhub/2015-08-01/swagger/EventHub.json'
  },
  'graph': {
    'dir': 'graphManagement/lib',
    'source': 'arm-graphrbac/compositeGraphRbacManagementClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'intune': {
    'dir': 'intune/lib',
    'source': 'arm-intune/2015-01-14-preview/swagger/intune.json',
  },
  'insights': {
    'dir': 'insights/lib',
    'source': 'insights/compositeInsightsClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'insights.management': {
    'dir': 'insightsManagement/lib',
    'source': 'arm-insights/compositeInsightsManagementClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  },
  'iothub': {
    'dir': 'iothub/lib',
    'source': 'arm-iothub/2016-02-03/swagger/iothub.json',
    'ft': 1
  },
  'keyvault': {
    'dir': 'keyvault/lib',
    'source': 'keyvault/2016-10-01/swagger/keyvault.json',
    'ft': 1
  },
  'keyvaultmanagement': {
    'dir': 'keyVaultManagement/lib',
    'source': 'arm-keyvault/2015-06-01/swagger/keyvault.json',
    'ft': 1
  },
  'logic': {
    'dir': 'logicManagement/lib',
    'source': 'arm-logic/2016-06-01/swagger/logic.json',
  },
  'mediaServices': {
    'dir': 'mediaServicesManagement/lib',
    'source': 'arm-mediaservices/2015-10-01/swagger/media.json'
  },
  'network': {
    'dir': 'networkManagement2/lib',
    'source': 'arm-network/compositeNetworkClient.json',
    'modeler': 'CompositeSwagger'
  },
  'notificationHubs': {
    'dir': 'notificationHubsManagement/lib',
    'source': 'arm-notificationhubs/2016-03-01/swagger/notificationhubs.json'
  },
  'operationalInsights': {
    'dir': 'operationalInsightsManagement2/lib',
    'source': 'arm-operationalInsights/compositeOperationalInsights.json',
    'modeler': 'CompositeSwagger'
  },
  'powerbiembedded': {
    'dir': 'powerbiembedded/lib',
    'source': 'arm-powerbiembedded/2016-01-29/swagger/powerbiembedded.json'
  },
  'recoveryServices': {
    'dir': 'recoveryServicesManagement',
    'source': 'arm-recoveryservices/2016-06-01/swagger/recoveryservices.json'
  },
  'recoveryServicesBackup': {
    'dir': 'recoveryServicesBackupManagement',
    'source': 'arm-recoveryservicesbackup/compositeRecoveryServicesBackupClient.json',
    'modeler': 'CompositeSwagger'
  },
  'rediscache': {
    'dir': 'rediscachemanagement/lib',
    'source': 'arm-redis/2016-04-01/swagger/redis.json',
    'ft': 1
  },
  'relay': {
    'dir': 'relayManagement/lib',
    'source': 'arm-relay/2016-07-01/swagger/relay.json'
  },
  'resource': {
    'dir': 'resourceManagement/lib/resource',
    'source': 'arm-resources/resources/2016-09-01/swagger/resources.json'
  },
  'resource.subscription': {
    'dir': 'resourceManagement/lib/subscription',
    'source': 'arm-resources/subscriptions/2016-06-01/swagger/subscriptions.json'
  },
  'resource.lock': {
    'dir': 'resourceManagement/lib/lock',
    'source': 'arm-resources/locks/2016-09-01/swagger/locks.json'
  },
  'resource.link': {
    'dir': 'resourceManagement/lib/link',
    'source': 'arm-resources/links/2016-09-01/swagger/links.json'
  },
  'resource.feature': {
    'dir': 'resourceManagement/lib/feature',
    'source': 'arm-resources/features/2015-12-01/swagger/features.json'
  },
  'resource.policy': {
    'dir': 'resourceManagement/lib/policy',
    'source': 'arm-resources/policy/2016-12-01/swagger/policy.json'
  },
  'schedulerManagement': {
    'dir': 'schedulerManagement2/lib',
    'source': 'arm-scheduler/2016-03-01/swagger/scheduler.json'
  },
  'searchIndex': {
    'dir': 'searchIndex/lib',
    'source': 'search/2016-09-01/swagger/searchindex.json'
  },
  'searchService': {
    'dir': 'searchService/lib',
    'source': 'search/2016-09-01/swagger/searchservice.json'
  },
  'searchManagement': {
    'dir': 'searchManagement/lib',
    'source': 'arm-search/2015-08-19/swagger/search.json'
  },
  'servermanagement': {
    'dir': 'servermanagement/lib',
    'source': 'arm-servermanagement/2015-07-01-preview/servermanagement.json'
  },
  'servicebus.management': {
    'dir': 'serviceBusManagement2/lib',
    'source': 'arm-servicebus/2015-08-01/swagger/servicebus.json'
  },
  'serviceFabricManagement': {
    'dir': 'serviceFabricManagement/lib',
    'source': 'arm-servicefabric/2016-09-01/swagger/servicefabric.json'
  },
  'serviceFabric': {
    'dir': 'serviceFabric/lib',
    'source': 'servicefabric/2016-01-28/swagger/servicefabric.json',
    'language': 'NodeJS'
  },
  'serviceMap': {
    'dir': 'serviceMapManagement/lib',
    'source': 'arm-service-map/2015-11-01-preview/swagger/arm-service-map.json'
  },
  'sql': {
    'dir': 'sqlManagement2/lib',
    'source': 'arm-sql/compositeSql.json',
    'modeler': 'CompositeSwagger'
  },
  'storage': {
    'dir': 'storageManagement2/lib',
    'source': 'arm-storage/2016-12-01/swagger/storage.json',
    'ft': 2,
    'ClientName': 'StorageManagementClient'
  },
  'storageImportExport': {
    'dir': 'storageImportExportManagement/lib',
    'source': 'arm-storageimportexport/2016-11-01/swagger/storageimportexport.json'
  },
  'traffic': {
    'dir': 'trafficManagerManagement2/lib',
    'source': 'arm-trafficmanager/2017-03-01/swagger/trafficmanager.json',
    'ft': 1
  },
  'website': {
    'dir': 'websiteManagement2/lib',
    'source': 'arm-web/compositeWebAppClient.json',
    'ft': 1,
    'modeler': 'CompositeSwagger'
  }
};

const defaultAutoRestVersion = '1.0.1-20170317-2300-nightly';
var usingAutoRestVersion;
const specRoot = args['spec-root'] || "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master";
const project = args['project'];
const language = 'Azure.NodeJS';
const modeler = 'Swagger';

function getAutorestVersion(version) {
  if (!version) version = 'latest';
  let getVersion, execHelp;
  let result = true;
  try {
    let getVersionCmd = `autorest --version=${version}`;
    let execHelpCmd = `autorest --help`;
    console.log(getVersionCmd);
    getVersion = execSync(getVersionCmd, { encoding: 'utf8' });
    //console.debug(getVersion);
    console.log(execHelpCmd);
    execHelp = execSync(execHelpCmd, { encoding: 'utf8' });
    //console.debug(execHelp);
  } catch (err) {
    result = false;
    console.log(`An error occurred while getting the "${version}" of autorest and executing "autorest --help":\n ${util.inspect(err, { depth: null })}.`);
  }
  return result;
}

function generateProject(project, specRoot, autoRestVersion) {
  let currentModeler = modeler;
  let specPath = specRoot + '/' + mappings[project].source;
  let result;
  //servicefabric wants to generate using generic NodeJS.
  if (mappings[project].language && mappings[project].language.match(/^NodeJS$/ig) !== null) {
    language = mappings[project].language;
  }
  //default Modeler is Swagger. However, some services may want to use CompositeSwaggerModeler
  if (mappings[project].modeler && mappings[project].modeler.match(/^CompositeSwagger$/ig) !== null) {
    currentModeler = mappings[project].modeler;
  }
  console.log(`\n>>>>>>>>>>>>>>>>>>>Start: "${project}" >>>>>>>>>>>>>>>>>>>>>>>>>`);

  let cmd = util.format('autorest -Modeler %s -CodeGenerator %s -Input %s  -outputDirectory lib/services/%s -Header MICROSOFT_MIT_NO_VERSION --version=%s',
    currentModeler, language, specPath, mappings[project].dir, autoRestVersion);
  if (mappings[project].ft !== null && mappings[project].ft !== undefined) cmd += ' -FT ' + mappings[project].ft;
  if (mappings[project].ClientName !== null && mappings[project].ClientName !== undefined) cmd += ' -ClientName ' + mappings[project].ClientName;
  if (mappings[project].args !== undefined) {
    cmd = cmd + ' ' + args;
  }

  try {
    console.log('Executing command:');
    console.log('------------------------------------------------------------');
    console.log(cmd);
    console.log('------------------------------------------------------------');
    result = execSync(cmd, { encoding: 'utf8' });
    console.log('Output:');
    console.log(result);
  } catch (err) {
    console.log('Error:');
    console.log(`An error occurred while generating client for project: "${project}":\n ${util.inspect(err, { depth: null })}`);
  }
  console.log(`>>>>>>>>>>>>>>>>>>>>>End: "${project}" >>>>>>>>>>>>>>>>>>>>>>>>>\n`);
  return;
}

function installAutorest() {
  let installation;
  let isSuccessful = true;
  let autorestAlreadyInstalled = true;
  try {
    execSync(`autorest --help`);
  } catch (error) {
    autorestAlreadyInstalled = false;
  }
  try {
    if (!autorestAlreadyInstalled) {
      console.log('Looks like autorest is not installed on your machine. Installing autorest . . .');
      let installCmd = 'npm install -g autorest';
      console.log(installCmd);
      installation = execSync(installCmd, { encoding: 'utf8' });
      //console.debug('installation');
    }
    isSuccessful = getAutorestVersion();
  } catch (err) {
    isSuccessful = false;
    console.log(`An error occurred while installing autorest via npm:\n ${util.inspect(err, { depth: null })}.`);
  }
  return isSuccessful;
}

function codegen(project, index) {
  let versionSuccessfullyFound = false;
  if (mappings[project].autorestversion) {
    usingAutoRestVersion = mappings[project].autoRestVersion;
  } else {
    usingAutoRestVersion = defaultAutoRestVersion;
  }
  if (index === 0) {
    versionSuccessfullyFound = getAutorestVersion(usingAutoRestVersion);
    if (!versionSuccessfullyFound) {
      process.exit(1);
    }
  }
  return generateProject(project, specRoot, usingAutoRestVersion);
}

gulp.task('default', function () {
  console.log("Usage: gulp codegen [--spec-root <swagger specs root>] [--project <project name>]\n");
  console.log("--spec-root");
  console.log("\tRoot location of Swagger API specs, default value is \"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master\"");
  console.log("--project\n\tProject to regenerate, default is all. List of available project names:");
  Object.keys(mappings).forEach(function (i) {
    console.log('\t' + i.magenta);
  });
});

gulp.task('codegen', function (cb) {
  if (installAutorest()) {
    if (project === undefined) {
      let arr = Object.keys(mappings);
      for (let i = 0; i < arr.length; i++) {
        codegen(arr[i], i);
      }
    } else {
      if (mappings[project] === undefined) {
        console.error('Invalid project name "' + project + '"!');
        process.exit(1);
      }
      codegen(project, null);
    }
  } else {
    process.exit(1);
  }
});<|endoftext|>