<commit_before>/**
 * i18n handling
 */
define(['jquery', 'i18next', 'moment'], function($, i18next, moment) {
    // Fetch the language once from the html lang attribute
    var lang = $('html').attr('lang');

    // Initialize required modules
    moment.locale(lang);
    i18next.init({
        lng: lang,
        ns: 'udata',
        fallbackLng: 'en',
        getAsync: false,
        nsseparator: '::', // Allow to use real sentences as keys
        keyseparator: '$$', // Allow to use real sentences as keys
        resGetPath: require.toUrl('../locales/__ns__.__lng__.json')
    });

    return {
        lang: lang,
        t: i18next.t,
        _: i18next.t
    }
});
<commit_msg>Disable language fallback<commit_after>/**
 * i18n handling
 */
define(['jquery', 'i18next', 'moment'], function($, i18next, moment) {
    // Fetch the language once from the html lang attribute
    var lang = $('html').attr('lang');

    // Initialize required modules
    moment.locale(lang);
    i18next.init({
        lng: lang,
        ns: 'udata',
        fallbackLng: false,
        getAsync: false,
        nsseparator: '::', // Allow to use real sentences as keys
        keyseparator: '$$', // Allow to use real sentences as keys
        resGetPath: require.toUrl('../locales/__ns__.__lng__.json')
    });

    return {
        lang: lang,
        t: i18next.t,
        _: i18next.t
    }
});
<|endoftext|>


<commit_before>const
  fs = require('fs'),
  path = require('path')

const
  { logError, writeFile } = require('./build.utils'),
  typeRoot = path.resolve(__dirname, '../types'),
  distRoot = path.resolve(__dirname, '../dist/types'),
  resolvePath = file => path.resolve(distRoot, file),
  extraInterfaces = {},
  // eslint-disable-next-line no-useless-escape
  toCamelCase = s => s.replace(/(\-\w)/g, m => { return m[1].toUpperCase() })

function writeLine (fileContent, line = '', indent = 0) {
  fileContent.push(`${line.padStart(line.length + (indent * 4), ' ')}\n`)
}

function write (fileContent, text = '') {
  fileContent.push(`${text}`)
}

const typeMap = new Map([
  ['Array', 'any[]'],
  ['Any', 'any'],
  ['Component', 'Vue'],
  ['String', 'string'],
  ['Boolean', 'boolean'],
  ['Number', 'number']
])

function convertTypeVal (type, def, required) {
  if (def.tsType !== void 0) {
    return def.tsType
  }

  const t = type.trim()

  if (typeMap.has(t)) {
    return typeMap.get(t)
  }

  if (t === 'Object') {
    if (def.definition) {
      const defs = getPropDefinitions(def.definition, required)
      return defs && defs.length > 0 ? `{\n        ${getPropDefinitions(def.definition, required).join('\n        ')} }` : 'any'
    }

    return 'any'
  }

  return t
}

function getTypeVal (def, required) {
  return Array.isArray(def.type)
    ? def.type.map(type => convertTypeVal(type, def, required)).join(' | ')
    : convertTypeVal(def.type, def, required)
}

function getPropDefinition (key, propDef, required) {
  const propName = toCamelCase(key)

  if (!propName.startsWith('...')) {
    const propType = getTypeVal(propDef, required)
    addToExtraInterfaces(propDef)
    return `${propName}${!propDef.required && !required ? '?' : ''} : ${propType}`
  }
}

function getPropDefinitions (propDefs, required) {
  const defs = []

  for (const key in propDefs) {
    const def = getPropDefinition(key, propDefs[key], required)
    def && defs.push(def)
  }

  return defs
}

function getMethodDefinition (key, methodDef, required) {
  let def = ''
  def += `${key} (`
  if (methodDef.params) {
    // TODO: Verify if this should be optional even for plugins
    const params = getPropDefinitions(methodDef.params)
    def += params.join(', ')
  }
  const returns = methodDef.returns
  def += `): ${returns ? getTypeVal(returns, required) : 'void'}`

  return def
}

function getObjectParamDefinition (def, required) {
  let res = []

  Object.keys(def).forEach(propName => {
    const propDef = def[propName]
    if (propDef.type && propDef.type === 'Function') {
      res.push(
        getMethodDefinition(propName, propDef, required)
      )
    }
    else {
      res.push(
        getPropDefinition(propName, propDef, required)
      )
    }
  })

  return res
}

function getInjectionDefinition (injectionName, typeDef) {
  // Get property injection point
  for (var propKey in typeDef.props) {
    const propDef = typeDef.props[propKey]
    if (propDef.tsInjectionPoint) {
      return getPropDefinition(injectionName, propDef, true)
    }
  }

  // Get method injection point
  for (var methodKey in typeDef.methods) {
    const methodDef = typeDef.methods[methodKey]
    if (methodDef.tsInjectionPoint) {
      return getMethodDefinition(injectionName, methodDef, true)
    }
  }
}

function copyPredefinedTypes (dir, parentDir) {
  fs.readdirSync(dir).forEach(file => {
    const fullPath = path.resolve(dir, file)
    const stats = fs.lstatSync(fullPath)
    if (stats.isFile()) {
      writeFile(
        resolvePath(parentDir ? parentDir + file : file),
        fs.readFileSync(fullPath)
      )
    }
    else if (stats.isDirectory()) {
      const p = resolvePath(parentDir ? parentDir + file : file)
      if (!fs.existsSync(p)) {
        fs.mkdirSync(p)
      }
      copyPredefinedTypes(fullPath, parentDir ? parentDir + file : file + '/')
    }
  })
}

function addToExtraInterfaces (def, required) {
  if (
    def !== void 0 &&
    def.tsType !== void 0 &&
    extraInterfaces[def.tsType] === void 0 &&
    def.definition !== void 0
  ) {
    extraInterfaces[def.tsType] = getObjectParamDefinition(
      def.definition, required
    )
  }
}

function writeIndexDTS (apis) {
  var contents = []
  var quasarTypeContents = []

  writeLine(contents, `import Vue, { VueConstructor } from 'vue'`)
  writeLine(contents)
  writeLine(quasarTypeContents, 'export as namespace quasar')
  writeLine(quasarTypeContents, `export * from './utils'`)

  const injections = {}

  apis.forEach(data => {
    const content = data.api
    const typeName = data.name

    // Declare class
    const extendsVue = (content.type === 'component' || content.type === 'mixin')
    writeLine(quasarTypeContents, `export const ${typeName}: ${extendsVue ? `VueConstructor<${typeName}>` : typeName}`)
    writeLine(contents, `export interface ${typeName} ${extendsVue ? 'extends Vue ' : ''}{`)

    // Write Props
    const props = getPropDefinitions(content.props, content.type === 'plugin')
    props.forEach(prop => writeLine(contents, prop, 1))

    // Write Methods
    for (const methodKey in content.methods) {
      write(contents, `    ${methodKey}(`)
      const method = content.methods[methodKey]
      if (method.params) {
        const params = getPropDefinitions(method.params)
        write(contents, params.join(', '))
      }
      const returns = method.returns
      writeLine(contents, `): ${returns ? getTypeVal(returns, content.type === 'plugin') : 'void'}`)

      addToExtraInterfaces(returns, true)
    }

    // Close class declaration
    writeLine(contents, `}`)
    writeLine(contents)

    // Copy Injections for type declaration
    if (content.type === 'plugin') {
      if (content.injection) {
        const injectionParts = content.injection.split('.')
        if (!injections[injectionParts[0]]) {
          injections[injectionParts[0]] = []
        }
        let def = getInjectionDefinition(injectionParts[1], content)
        if (!def) {
          def = `${injectionParts[1]}: ${typeName}`
        }
        injections[injectionParts[0]].push(def)
      }
    }
  })

  Object.keys(extraInterfaces).forEach(name => {
    writeLine(contents, `export interface ${name} {`)
    extraInterfaces[name].forEach(def => {
      writeLine(contents, def, 1)
    })
    writeLine(contents, `}\n`)
  })

  // Write injection types
  for (const key in injections) {
    const injectionDefs = injections[key]
    if (injectionDefs) {
      writeLine(contents, `export interface ${key.toUpperCase().replace('$', '')}VueGlobals {`)
      for (const defKey in injectionDefs) {
        writeLine(contents, injectionDefs[defKey], 1)
      }
      writeLine(contents, '}')
    }
  }

  writeLine(contents)

  // Extend Vue instance with injections
  if (injections) {
    writeLine(contents, `declare module 'vue/types/vue' {`)
    writeLine(contents, 'interface Vue {', 1)

    for (const key3 in injections) {
      writeLine(contents, `${key3}: ${key3.toUpperCase().replace('$', '')}VueGlobals`, 2)
    }
    writeLine(contents, '}', 1)
    writeLine(contents, '}')
  }

  quasarTypeContents.forEach(line => write(contents, line))

  writeLine(contents, `import './vue'`)

  writeFile(resolvePath('index.d.ts'), contents.join(''))
}

module.exports.generate = function (data) {
  const apis = data.plugins
    .concat(data.directives)
    .concat(data.components)

  try {
    copyPredefinedTypes(typeRoot)
    writeIndexDTS(apis)
  }
  catch (err) {
    logError(`build.types.js: something went wrong...`)
    console.log()
    console.error(err)
    console.log()
    process.exit(1)
  }
}
<commit_msg>Add Quasar Plugin Type for use with Quasar Testing extension. (#4634)<commit_after>const
  fs = require('fs'),
  path = require('path')

const
  { logError, writeFile } = require('./build.utils'),
  typeRoot = path.resolve(__dirname, '../types'),
  distRoot = path.resolve(__dirname, '../dist/types'),
  resolvePath = file => path.resolve(distRoot, file),
  extraInterfaces = {},
  // eslint-disable-next-line no-useless-escape
  toCamelCase = s => s.replace(/(\-\w)/g, m => { return m[1].toUpperCase() })

function writeLine (fileContent, line = '', indent = 0) {
  fileContent.push(`${line.padStart(line.length + (indent * 4), ' ')}\n`)
}

function write (fileContent, text = '') {
  fileContent.push(`${text}`)
}

const typeMap = new Map([
  ['Array', 'any[]'],
  ['Any', 'any'],
  ['Component', 'Vue'],
  ['String', 'string'],
  ['Boolean', 'boolean'],
  ['Number', 'number']
])

function convertTypeVal (type, def, required) {
  if (def.tsType !== void 0) {
    return def.tsType
  }

  const t = type.trim()

  if (typeMap.has(t)) {
    return typeMap.get(t)
  }

  if (t === 'Object') {
    if (def.definition) {
      const defs = getPropDefinitions(def.definition, required)
      return defs && defs.length > 0 ? `{\n        ${getPropDefinitions(def.definition, required).join('\n        ')} }` : 'any'
    }

    return 'any'
  }

  return t
}

function getTypeVal (def, required) {
  return Array.isArray(def.type)
    ? def.type.map(type => convertTypeVal(type, def, required)).join(' | ')
    : convertTypeVal(def.type, def, required)
}

function getPropDefinition (key, propDef, required) {
  const propName = toCamelCase(key)

  if (!propName.startsWith('...')) {
    const propType = getTypeVal(propDef, required)
    addToExtraInterfaces(propDef)
    return `${propName}${!propDef.required && !required ? '?' : ''} : ${propType}`
  }
}

function getPropDefinitions (propDefs, required) {
  const defs = []

  for (const key in propDefs) {
    const def = getPropDefinition(key, propDefs[key], required)
    def && defs.push(def)
  }

  return defs
}

function getMethodDefinition (key, methodDef, required) {
  let def = ''
  def += `${key} (`
  if (methodDef.params) {
    // TODO: Verify if this should be optional even for plugins
    const params = getPropDefinitions(methodDef.params)
    def += params.join(', ')
  }
  const returns = methodDef.returns
  def += `): ${returns ? getTypeVal(returns, required) : 'void'}`

  return def
}

function getObjectParamDefinition (def, required) {
  let res = []

  Object.keys(def).forEach(propName => {
    const propDef = def[propName]
    if (propDef.type && propDef.type === 'Function') {
      res.push(
        getMethodDefinition(propName, propDef, required)
      )
    }
    else {
      res.push(
        getPropDefinition(propName, propDef, required)
      )
    }
  })

  return res
}

function getInjectionDefinition (injectionName, typeDef) {
  // Get property injection point
  for (var propKey in typeDef.props) {
    const propDef = typeDef.props[propKey]
    if (propDef.tsInjectionPoint) {
      return getPropDefinition(injectionName, propDef, true)
    }
  }

  // Get method injection point
  for (var methodKey in typeDef.methods) {
    const methodDef = typeDef.methods[methodKey]
    if (methodDef.tsInjectionPoint) {
      return getMethodDefinition(injectionName, methodDef, true)
    }
  }
}

function copyPredefinedTypes (dir, parentDir) {
  fs.readdirSync(dir).forEach(file => {
    const fullPath = path.resolve(dir, file)
    const stats = fs.lstatSync(fullPath)
    if (stats.isFile()) {
      writeFile(
        resolvePath(parentDir ? parentDir + file : file),
        fs.readFileSync(fullPath)
      )
    }
    else if (stats.isDirectory()) {
      const p = resolvePath(parentDir ? parentDir + file : file)
      if (!fs.existsSync(p)) {
        fs.mkdirSync(p)
      }
      copyPredefinedTypes(fullPath, parentDir ? parentDir + file : file + '/')
    }
  })
}

function addToExtraInterfaces (def, required) {
  if (
    def !== void 0 &&
    def.tsType !== void 0 &&
    extraInterfaces[def.tsType] === void 0 &&
    def.definition !== void 0
  ) {
    extraInterfaces[def.tsType] = getObjectParamDefinition(
      def.definition, required
    )
  }
}

function writeQuasarPluginProps (contents, nameName, props, isLast) {
  writeLine(contents, `${nameName}: {`, 1)
  props.forEach(prop => writeLine(contents, prop, 2))
  writeLine(contents, `}${isLast ? '' : ','}`, 1)
}

function addQuasarPluginOptions (contents, components, directives, plugins) {
  writeLine(contents, `export interface QuasarPluginOptions {`)
  writeLine(contents, `lang: any,`, 1)
  writeLine(contents, `config: any,`, 1)
  writeLine(contents, `iconSet: any,`, 1)
  writeQuasarPluginProps(contents, 'components', components)
  writeQuasarPluginProps(contents, 'directives', directives)
  writeQuasarPluginProps(contents, 'plugins', plugins, true)
  writeLine(contents, `}`)
  writeLine(contents)
}

function writeIndexDTS (apis) {
  var contents = []
  var quasarTypeContents = []
  var components = []
  var directives = []
  var plugins = []

  writeLine(contents, `import Vue, { VueConstructor, PluginObject } from 'vue'`)
  writeLine(contents)
  writeLine(quasarTypeContents, 'export as namespace quasar')
  writeLine(quasarTypeContents, `export * from './utils'`)

  const injections = {}

  apis.forEach(data => {
    const content = data.api
    const typeName = data.name

    const extendsVue = (content.type === 'component' || content.type === 'mixin')
    const typeValue = `${extendsVue ? `VueConstructor<${typeName}>` : typeName}`
    // Add Type to the appropriate section of types
    const propTypeDef = `${typeName}: ${typeValue}`
    if (content.type === 'component') {
      write(components, propTypeDef)
    }
    else if (content.type === 'directive') {
      write(directives, propTypeDef)
    }
    else if (content.type === 'plugin') {
      write(plugins, propTypeDef)
    }

    // Declare class
    writeLine(quasarTypeContents, `export const ${typeName}: ${extendsVue ? `VueConstructor<${typeName}>` : typeName}`)
    writeLine(contents, `export interface ${typeName} ${extendsVue ? 'extends Vue ' : ''}{`)

    // Write Props
    const props = getPropDefinitions(content.props, content.type === 'plugin')
    props.forEach(prop => writeLine(contents, prop, 1))

    // Write Methods
    for (const methodKey in content.methods) {
      write(contents, `    ${methodKey}(`)
      const method = content.methods[methodKey]
      if (method.params) {
        const params = getPropDefinitions(method.params)
        write(contents, params.join(', '))
      }
      const returns = method.returns
      writeLine(contents, `): ${returns ? getTypeVal(returns, content.type === 'plugin') : 'void'}`)

      addToExtraInterfaces(returns, true)
    }

    // Close class declaration
    writeLine(contents, `}`)
    writeLine(contents)

    // Copy Injections for type declaration
    if (content.type === 'plugin') {
      if (content.injection) {
        const injectionParts = content.injection.split('.')
        if (!injections[injectionParts[0]]) {
          injections[injectionParts[0]] = []
        }
        let def = getInjectionDefinition(injectionParts[1], content)
        if (!def) {
          def = `${injectionParts[1]}: ${typeName}`
        }
        injections[injectionParts[0]].push(def)
      }
    }
  })

  Object.keys(extraInterfaces).forEach(name => {
    writeLine(contents, `export interface ${name} {`)
    extraInterfaces[name].forEach(def => {
      writeLine(contents, def, 1)
    })
    writeLine(contents, `}\n`)
  })

  // Write injection types
  for (const key in injections) {
    const injectionDefs = injections[key]
    if (injectionDefs) {
      writeLine(contents, `export interface ${key.toUpperCase().replace('$', '')}VueGlobals {`)
      for (const defKey in injectionDefs) {
        writeLine(contents, injectionDefs[defKey], 1)
      }
      writeLine(contents, '}')
    }
  }

  writeLine(contents)

  // Extend Vue instance with injections
  if (injections) {
    writeLine(contents, `declare module 'vue/types/vue' {`)
    writeLine(contents, 'interface Vue {', 1)

    for (const key3 in injections) {
      writeLine(contents, `${key3}: ${key3.toUpperCase().replace('$', '')}VueGlobals`, 2)
    }
    writeLine(contents, '}', 1)
    writeLine(contents, '}')
  }

  addQuasarPluginOptions(contents, components, directives, plugins)

  quasarTypeContents.forEach(line => write(contents, line))

  writeLine(contents, `export const Quasar: PluginObject<QuasarPluginOptions>`)
  writeLine(contents)

  writeLine(contents, `import './vue'`)

  writeFile(resolvePath('index.d.ts'), contents.join(''))
}

module.exports.generate = function (data) {
  const apis = data.plugins
    .concat(data.directives)
    .concat(data.components)

  try {
    copyPredefinedTypes(typeRoot)
    writeIndexDTS(apis)
  }
  catch (err) {
    logError(`build.types.js: something went wrong...`)
    console.log()
    console.error(err)
    console.log()
    process.exit(1)
  }
}
<|endoftext|>


<commit_before>// @datatype_void

var helpers = require('./helpers');
// Webpack Plugins
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
var DefinePlugin  = require('webpack/lib/DefinePlugin');
var ENV = process.env.ENV = process.env.NODE_ENV = 'test';

/*
 * Config
 */
module.exports = {
  devtool: 'inline-source-map',
  resolve: {
    extensions: ['', '.ts', '.js', '.scss']
  },
  module: {
    preLoaders: [
      {
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [
          helpers.root('node_modules')
        ]
      },
      {
        test: /\.js$/,
        loader: "source-map-loader",
        exclude: [
          helpers.root('node_modules/rxjs')
        ]
      }
    ],
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        query: {
          "compilerOptions": {
            "removeComments": true,
          }
        },
        exclude: [ /\.e2e\.ts$/, helpers.root('node_modules') ]
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
        exclude: [ helpers.root('src/index.html'), helpers.root('node_modules') ] },
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [ helpers.root('src/index.html'), helpers.root('node_modules') ] },
      {
        test: /\.css$/,
        loader: 'raw-loader',
        exclude: [ helpers.root('src/index.html'), helpers.root('node_modules') ] },
      {
        test: /\.scss$/,
        loader: 'style!css!autoprefixer-loader?browsers=last 2 versions!sass',
        exclude: [ helpers.root('node_modules') ]
      }
    ],
    postLoaders: [
      // instrument only testing sources with Istanbul
      {
        test: /\.(js|ts)$/,
        include: helpers.root('src'),
        loader: 'istanbul-instrumenter-loader',
        exclude: [
          /\.(e2e|spec)\.ts$/,
          /node_modules/
        ]
      }
    ]
  },
  plugins: [
    new DefinePlugin({
      // Environment helpers
      'ENV': JSON.stringify(ENV),
      'HMR': false
    })
  ],
  node: {
    global: 'window',
    progress: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  },
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src',
  }
};
<commit_msg>chore(webpack.test): remove excludes<commit_after>// @datatype_void

var helpers = require('./helpers');
// Webpack Plugins
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
var DefinePlugin  = require('webpack/lib/DefinePlugin');
var ENV = process.env.ENV = process.env.NODE_ENV = 'test';

/*
 * Config
 */
module.exports = {
  devtool: 'inline-source-map',
  resolve: {
    extensions: ['', '.ts', '.js', '.scss']
  },
  module: {
    preLoaders: [
      {
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [
          helpers.root('node_modules')
        ]
      },
      {
        test: /\.js$/,
        loader: "source-map-loader",
        exclude: [
          helpers.root('node_modules/rxjs')
        ]
      }
    ],
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        query: {
          "compilerOptions": {
            "removeComments": true,
          }
        },
        exclude: [ /\.e2e\.ts$/ ]
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
        exclude: [ helpers.root('src/index.html') ] },
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [ helpers.root('src/index.html') ] },
      {
        test: /\.css$/,
        loader: 'raw-loader',
        exclude: [ helpers.root('src/index.html') ] },
      {
        test: /\.scss$/,
        loader: 'style!css!autoprefixer-loader?browsers=last 2 versions!sass',
        exclude: [ helpers.root('src/index.html') ] },
      }
    ],
    postLoaders: [
      // instrument only testing sources with Istanbul
      {
        test: /\.(js|ts)$/,
        include: helpers.root('src'),
        loader: 'istanbul-instrumenter-loader',
        exclude: [
          /\.(e2e|spec)\.ts$/,
          /node_modules/
        ]
      }
    ]
  },
  plugins: [
    new DefinePlugin({
      // Environment helpers
      'ENV': JSON.stringify(ENV),
      'HMR': false
    })
  ],
  node: {
    global: 'window',
    progress: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  },
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src',
  }
};
<|endoftext|>


<commit_before>/*
 * jQuery UI Spinner @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Spinner
 *
 * Depends:
 *  jquery.ui.core.js
 *  jquery.ui.widget.js
 */
(function( $ ) {

$.widget( "ui.spinner", {
	version: "@VERSION",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		incremental: true,
		max: null,
		min: null,
		numberFormat: null,
		page: 10,
		step: null,
		value: null
	},

	_create: function() {
		this._draw();
		this._markupOptions();
		this._mousewheel();
		this._aria();
	},

	_markupOptions: function() {
		var that = this;
		$.each({
			min: -Number.MAX_VALUE,
			max: Number.MAX_VALUE,
			step: 1
		}, function( attr, defaultValue ) {
			if ( that.options[ attr ] === null ) {
				var value = that.element.attr( attr );
				that.options[ attr ] = typeof value === "string" && value.length > 0 ?
					that._parse( value ) :
					defaultValue;
			}
		});
		this.value( this.options.value !== null ? this.options.value : this.element.val() || 0 );
	},

	_draw: function() {
		var self = this,
			options = self.options;

		var uiSpinner = this.uiSpinner = self.element
			.addClass( "ui-spinner-input" )
			.attr( "autocomplete", "off" )
			.wrap( self._uiSpinnerHtml() )
			.parent()
				// add buttons
				.append( self._buttonHtml() )
				// add behaviours
				.disableSelection()
				// TODO: user ._hoverable
				.hover(function() {
					if ( !options.disabled ) {
						$( this ).addClass( "ui-state-hover" );
					}
					self.hovered = true;
				}, function() {
					$( this ).removeClass( "ui-state-hover" );
					self.hovered = false;
				});

		// TODO: use ._bind()
		this.element
			.attr( "role", "spinbutton" )
			.bind( "keydown.spinner", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self._start( event ) ) {
					return self._keydown( event );
				}
				return true;
			})
			.bind( "keyup.spinner", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			})
			.bind( "focus.spinner", function() {
				uiSpinner.addClass( "ui-state-active" );
				self.focused = true;
			})
			.bind( "blur.spinner", function( event ) {
				self.value( self.element.val() );
				if ( !self.hovered ) {
					uiSpinner.removeClass( "ui-state-active" );
				}
				self.focused = false;
			});

		// button bindings
		this.buttons = uiSpinner.find( ".ui-spinner-button" )
			.attr( "tabIndex", -1 )
			.button()
			.removeClass( "ui-corner-all" )
			.bind( "mousedown", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self._start( event ) === false ) {
					return false;
				}
				self._repeat( null, $( this ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
			})
			.bind( "mouseup", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			})
			.bind( "mouseenter", function() {
				if ( self.options.disabled ) {
					return;
				}
				// button will add ui-state-active if mouse was down while mouseleave and kept down
				if ( $( this ).hasClass( "ui-state-active" ) ) {
					if ( self._start( event ) === false ) {
						return false;
					}
					self._repeat( null, $( this ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
				}
			})
			.bind( "mouseleave", function() {
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			});

		// disable spinner if element was already disabled
		if ( options.disabled ) {
			this.disable();
		}
	},

	_keydown: function( event ) {
		var options = this.options,
			keyCode = $.ui.keyCode;

		switch ( event.keyCode ) {
		case keyCode.UP:
			this._repeat( null, 1, event );
			return false;
		case keyCode.DOWN:
			this._repeat( null, -1, event );
			return false;
		case keyCode.PAGE_UP:
			this._repeat( null, options.page, event );
			return false;
		case keyCode.PAGE_DOWN:
			this._repeat( null, -options.page, event );
			return false;
		case keyCode.ENTER:
			this.value( this.element.val() );
		}

		return true;
	},

	_mousewheel: function() {
		// need the delta normalization that mousewheel plugin provides
		if ( !$.fn.mousewheel ) {
			return;
		}
		var self = this;
		this.element.bind( "mousewheel.spinner", function( event, delta ) {
			if ( self.options.disabled || !delta ) {
				return;
			}
			if ( !self.spinning && !self._start( event ) ) {
				return false;
			}
			self._spin( (delta > 0 ? 1 : -1) * self.options.step, event );
			clearTimeout( self.timeout );
			self.timeout = setTimeout(function() {
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			}, 100);
			event.preventDefault();
		});
	},

	_uiSpinnerHtml: function() {
		return "";
	},

	_buttonHtml: function() {
		return "" +
			"" +
				"▲" +
			"" +
			"" +
				"▼" +
			"";
	},

	_start: function( event ) {
		if ( !this.spinning && this._trigger( "start", event ) === false ) {
			return false;
		}

		if ( !this.counter ) {
			this.counter = 1;
		}
		this.spinning = true;
		return true;
	},

	_repeat: function( i, steps, event ) {
		var self = this;
		i = i || 500;

		clearTimeout( this.timer );
		this.timer = setTimeout(function() {
			self._repeat( 40, steps, event );
		}, i );

		self._spin( steps * self.options.step, event );
	},

	_spin: function( step, event ) {
		if ( !this.counter ) {
			this.counter = 1;
		}

		// TODO refactor, maybe figure out some non-linear math
		var newVal = this.value() + step * (this.options.incremental &&
			this.counter > 20
				? this.counter > 100
					? this.counter > 200
						? 100
						: 10
					: 2
				: 1);

		if ( this._trigger( "spin", event, { value: newVal } ) !== false) {
			this.value( newVal );
			this.counter++;
		}
	},

	_stop: function( event ) {
		this.counter = 0;
		if ( this.timer ) {
			clearTimeout( this.timer );
		}
		this.element.focus();
		this.spinning = false;
		this._trigger( "stop", event );
	},

	_change: function( event ) {
		this._trigger( "change", event );
	},

	_setOption: function( key, value ) {
		if ( key === "value") {
			value = this._parse( value );
			if ( value < this.options.min ) {
				value = this.options.min;
			}
			if ( value > this.options.max ) {
				value = this.options.max;
			}
		}

		if ( key === "disabled" ) {
			if ( value ) {
				this.element.attr( "disabled", true );
				this.buttons.button( "disable" );
			} else {
				this.element.removeAttr( "disabled" );
				this.buttons.button( "enable" );
			}
		}

		this._super( "_setOption", key, value );
	},

	_setOptions: function( options ) {
		this._super( "_setOptions", options );
		if ( "value" in options ) {
			this._format( this.options.value );
		}
		this._aria();
	},

	_aria: function() {
		this.element.attr({
			"aria-valuemin": this.options.min,
			"aria-valuemax": this.options.max,
			"aria-valuenow": this.options.value
		});
	},

	_parse: function( val ) {
		if ( typeof val === "string" ) {
			val = $.global && this.options.numberFormat ? $.global.parseFloat( val ) : +val;
		}
		return isNaN( val ) ? null : val;
	},

	_format: function( num ) {
		this.element.val( $.global && this.options.numberFormat ? $.global.format( num, this.options.numberFormat ) : num );
	},

	destroy: function() {
		this.element
			.removeClass( "ui-spinner-input" )
			.removeAttr( "disabled" )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );
		this._super( "destroy" );
		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: function( steps ) {
		this._spin( (steps || 1) * this.options.step );
	},

	stepDown: function( steps ) {
		this._spin( (steps || 1) * -this.options.step );
	},

	pageUp: function( pages ) {
		this.stepUp( (pages || 1) * this.options.page );
	},

	pageDown: function( pages ) {
		this.stepDown( (pages || 1) * this.options.page );
	},

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		this.option( "value", newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
});

}( jQuery ) );
<commit_msg>Spinner: modified _spin and _setOption to call new method _trimValue to check for min/max values. Fixed #7264 - Spinner returns values beyond min and max, off by one<commit_after>/*
 * jQuery UI Spinner @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Spinner
 *
 * Depends:
 *  jquery.ui.core.js
 *  jquery.ui.widget.js
 */
(function( $ ) {

$.widget( "ui.spinner", {
	version: "@VERSION",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		incremental: true,
		max: null,
		min: null,
		numberFormat: null,
		page: 10,
		step: null,
		value: null
	},

	_create: function() {
		this._draw();
		this._markupOptions();
		this._mousewheel();
		this._aria();
	},

	_markupOptions: function() {
		var that = this;
		$.each({
			min: -Number.MAX_VALUE,
			max: Number.MAX_VALUE,
			step: 1
		}, function( attr, defaultValue ) {
			if ( that.options[ attr ] === null ) {
				var value = that.element.attr( attr );
				that.options[ attr ] = typeof value === "string" && value.length > 0 ?
					that._parse( value ) :
					defaultValue;
			}
		});
		this.value( this.options.value !== null ? this.options.value : this.element.val() || 0 );
	},

	_draw: function() {
		var self = this,
			options = self.options;

		var uiSpinner = this.uiSpinner = self.element
			.addClass( "ui-spinner-input" )
			.attr( "autocomplete", "off" )
			.wrap( self._uiSpinnerHtml() )
			.parent()
				// add buttons
				.append( self._buttonHtml() )
				// add behaviours
				.disableSelection()
				// TODO: user ._hoverable
				.hover(function() {
					if ( !options.disabled ) {
						$( this ).addClass( "ui-state-hover" );
					}
					self.hovered = true;
				}, function() {
					$( this ).removeClass( "ui-state-hover" );
					self.hovered = false;
				});

		// TODO: use ._bind()
		this.element
			.attr( "role", "spinbutton" )
			.bind( "keydown.spinner", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self._start( event ) ) {
					return self._keydown( event );
				}
				return true;
			})
			.bind( "keyup.spinner", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			})
			.bind( "focus.spinner", function() {
				uiSpinner.addClass( "ui-state-active" );
				self.focused = true;
			})
			.bind( "blur.spinner", function( event ) {
				self.value( self.element.val() );
				if ( !self.hovered ) {
					uiSpinner.removeClass( "ui-state-active" );
				}
				self.focused = false;
			});

		// button bindings
		this.buttons = uiSpinner.find( ".ui-spinner-button" )
			.attr( "tabIndex", -1 )
			.button()
			.removeClass( "ui-corner-all" )
			.bind( "mousedown", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self._start( event ) === false ) {
					return false;
				}
				self._repeat( null, $( this ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
			})
			.bind( "mouseup", function( event ) {
				if ( options.disabled ) {
					return;
				}
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			})
			.bind( "mouseenter", function() {
				if ( self.options.disabled ) {
					return;
				}
				// button will add ui-state-active if mouse was down while mouseleave and kept down
				if ( $( this ).hasClass( "ui-state-active" ) ) {
					if ( self._start( event ) === false ) {
						return false;
					}
					self._repeat( null, $( this ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
				}
			})
			.bind( "mouseleave", function() {
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			});

		// disable spinner if element was already disabled
		if ( options.disabled ) {
			this.disable();
		}
	},

	_keydown: function( event ) {
		var options = this.options,
			keyCode = $.ui.keyCode;

		switch ( event.keyCode ) {
		case keyCode.UP:
			this._repeat( null, 1, event );
			return false;
		case keyCode.DOWN:
			this._repeat( null, -1, event );
			return false;
		case keyCode.PAGE_UP:
			this._repeat( null, options.page, event );
			return false;
		case keyCode.PAGE_DOWN:
			this._repeat( null, -options.page, event );
			return false;
		case keyCode.ENTER:
			this.value( this.element.val() );
		}

		return true;
	},

	_mousewheel: function() {
		// need the delta normalization that mousewheel plugin provides
		if ( !$.fn.mousewheel ) {
			return;
		}
		var self = this;
		this.element.bind( "mousewheel.spinner", function( event, delta ) {
			if ( self.options.disabled || !delta ) {
				return;
			}
			if ( !self.spinning && !self._start( event ) ) {
				return false;
			}
			self._spin( (delta > 0 ? 1 : -1) * self.options.step, event );
			clearTimeout( self.timeout );
			self.timeout = setTimeout(function() {
				if ( self.spinning ) {
					self._stop( event );
					self._change( event );
				}
			}, 100);
			event.preventDefault();
		});
	},

	_uiSpinnerHtml: function() {
		return "";
	},

	_buttonHtml: function() {
		return "" +
			"" +
				"▲" +
			"" +
			"" +
				"▼" +
			"";
	},

	_start: function( event ) {
		if ( !this.spinning && this._trigger( "start", event ) === false ) {
			return false;
		}

		if ( !this.counter ) {
			this.counter = 1;
		}
		this.spinning = true;
		return true;
	},

	_repeat: function( i, steps, event ) {
		var self = this;
		i = i || 500;

		clearTimeout( this.timer );
		this.timer = setTimeout(function() {
			self._repeat( 40, steps, event );
		}, i );

		self._spin( steps * self.options.step, event );
	},

	_spin: function( step, event ) {
		if ( !this.counter ) {
			this.counter = 1;
		}

		// TODO refactor, maybe figure out some non-linear math
		var newVal = this.value() + step * (this.options.incremental &&
			this.counter > 20
				? this.counter > 100
					? this.counter > 200
						? 100
						: 10
					: 2
				: 1);

		// clamp the new value
		newVal = this._trimValue( newVal );

		if ( this._trigger( "spin", event, { value: newVal } ) !== false) {
			this.value( newVal );
			this.counter++;
		}
	},

	_trimValue: function( value ) {
		var options = this.options;

		if ( value > options.max) {
			return options.max;
		}

		if ( value < options.min ) {
			return options.min;
		}

		return value;
	},

	_stop: function( event ) {
		this.counter = 0;
		if ( this.timer ) {
			clearTimeout( this.timer );
		}
		this.element.focus();
		this.spinning = false;
		this._trigger( "stop", event );
	},

	_change: function( event ) {
		this._trigger( "change", event );
	},

	_setOption: function( key, value ) {
		if ( key === "value") {
			value = this._trimValue( this._parse(value) );
		}

		if ( key === "disabled" ) {
			if ( value ) {
				this.element.attr( "disabled", true );
				this.buttons.button( "disable" );
			} else {
				this.element.removeAttr( "disabled" );
				this.buttons.button( "enable" );
			}
		}

		this._super( "_setOption", key, value );
	},

	_setOptions: function( options ) {
		this._super( "_setOptions", options );
		if ( "value" in options ) {
			this._format( this.options.value );
		}
		this._aria();
	},

	_aria: function() {
		this.element.attr({
			"aria-valuemin": this.options.min,
			"aria-valuemax": this.options.max,
			"aria-valuenow": this.options.value
		});
	},

	_parse: function( val ) {
		if ( typeof val === "string" ) {
			val = $.global && this.options.numberFormat ? $.global.parseFloat( val ) : +val;
		}
		return isNaN( val ) ? null : val;
	},

	_format: function( num ) {
		this.element.val( $.global && this.options.numberFormat ? $.global.format( num, this.options.numberFormat ) : num );
	},

	destroy: function() {
		this.element
			.removeClass( "ui-spinner-input" )
			.removeAttr( "disabled" )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );
		this._super( "destroy" );
		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: function( steps ) {
		this._spin( (steps || 1) * this.options.step );
	},

	stepDown: function( steps ) {
		this._spin( (steps || 1) * -this.options.step );
	},

	pageUp: function( pages ) {
		this.stepUp( (pages || 1) * this.options.page );
	},

	pageDown: function( pages ) {
		this.stepDown( (pages || 1) * this.options.page );
	},

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		this.option( "value", newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
});

}( jQuery ) );
<|endoftext|>


<commit_before>'use strict';
var mkpath = require('mkpath');
var fs = require('fs');
var path = require('path');
var generate = require("./generate");
function checkDirectory(data, callback) {
    fs.stat(data, function (err, stats) {
        if (err && err.errno === -2) {
            console.log(err);
            callback(0);
        } else {
            callback(1)
        }
    });
}

function createFile(name, writeData) {
    fs.writeFile(name, writeData, function (err) {
        if (err) throw err;
    });
}

function createModel(model, data) {
    try {
        mkpath('public/' + process.argv[3], function (err) {
            if (err) throw err;
           // createFile('public/' + process.argv[3] + '/index.html', "");
            generate.htmlIndexGenerate(model,data);
            generate.generateController(process.argv[3]);
            generate.generateRoute(process.argv[3]);
        });
        let Mongodata = JSON.stringify(data);
        Mongodata = Mongodata.replace("\"Date\"", "Date").replace("\"Date.now\"", "Date.now");

        let writeData = "'use strict'\nlet mongoose = require('mongoose');";
        writeData += "\nlet Schema = new mongoose.Schema(" + Mongodata + ");";
        writeData += "\nmodule.exports = mongoose.model(\"" + model + "\", Schema);";
        createFile('app/database/mongo/models/' + model + '.js', writeData);
    }
    catch (e) {
        console.log(e);
    }
}

if (!process.argv[3] && process.argv[2] != "generate") {
    mkpath('app/database/' + process.argv[2] + '/models', function (err) {
        if (err) throw err;
    });

} else if (process.argv[2] == "generate") {
    let req = "'use strict';\n";
    let data = [];
    fs.readdirSync("app/route").filter((file) => {
        if (!fs.statSync(path.join("app/route", file)).isDirectory()) {
            req += "const " + path.basename(file, ".js") + " = require('./app/route/" + file + "')({devis: devis});\n";
            data.push(path.basename(file, ".js"));
        }

    });
    req += "const data=" + JSON.stringify(data) + ";\n";

    fs.writeFile('index.js', req, "UTF-8", "a+");
    fs.readFile('app/scripts/default/indexGenerator.js', function read(err, data) {
        fs.appendFile('./index.js', data, "UTF-8", "a+");
    });

} else {
    fs.readdirSync("app/database").filter((file) => {
        if (fs.statSync(path.join("app/database", file)).isDirectory()) {
            if (file == "mongo") {
                fs.readFile('app/database/data.json', function read(err, data) {
                    if (err) throw err;

                    let content = "";
                    content += data;
                    content = JSON.parse(content)[process.argv[3]];
                    createModel(process.argv[3], content);
                });

            }
            if (file == "mysql") {
                //will be implemented soon...
            }

        }
    });
}
<commit_msg>fix bugs<commit_after>'use strict';
var mkpath = require('mkpath');
var fs = require('fs');
var path = require('path');
var generate = require("./generate");
function checkDirectory(data, callback) {
    fs.stat(data, function (err, stats) {
        if (err && err.errno === -2) {
            console.log(err);
            callback(0);
        } else {
            callback(1)
        }
    });
}

function createFile(name, writeData) {
    fs.writeFile(name, writeData, function (err) {
        if (err) throw err;
    });
}

function createModel(model, data) {
    try {
        mkpath('public/' + process.argv[3], function (err) {
            if (err) throw err;
           // createFile('public/' + process.argv[3] + '/index.html', "");
            generate.htmlIndexGenerate(model,data);
            generate.generateController(process.argv[3]);
            generate.generateRoute(process.argv[3]);
        });
        let Mongodata = JSON.stringify(data);
        Mongodata = Mongodata.replace("\"Date\"", "Date").replace("\"Date.now\"", "Date.now");

        let writeData = "'use strict'\nlet mongoose = require('mongoose');";
        writeData += "\nlet Schema = new mongoose.Schema(" + Mongodata + ");";
        writeData += "\nmodule.exports = mongoose.model(\"" + model + "\", Schema);";
        createFile('app/database/mongo/models/' + model + '.js', writeData);
    }
    catch (e) {
        console.log(e);
    }
}

if (!process.argv[3] && process.argv[2] != "generate") {
    mkpath('app/database/' + process.argv[2] + '/models', function (err) {
        if (err) throw err;
    });

} else if (process.argv[2] == "generate") {
    let req = "'use strict';\nconst devis=require('devis');\n";
    let data = [];
    fs.readdirSync("app/route").filter((file) => {
        if (!fs.statSync(path.join("app/route", file)).isDirectory()) {
            req += "const " + path.basename(file, ".js") + " = require('./app/route/" + file + "')({devis: devis});\n";
            data.push(path.basename(file, ".js"));
        }

    });
    req += "const data=" + JSON.stringify(data) + ";\n";

    fs.writeFile('index.js', req, "UTF-8", "a+");
    fs.readFile('app/scripts/default/indexGenerator.js', function read(err, data) {
        fs.appendFile('./index.js', data, "UTF-8", "a+");
    });

} else {
    fs.readdirSync("app/database").filter((file) => {
        if (fs.statSync(path.join("app/database", file)).isDirectory()) {
            if (file == "mongo") {
                fs.readFile('app/database/data.json', function read(err, data) {
                    if (err) throw err;

                    let content = "";
                    content += data;
                    content = JSON.parse(content)[process.argv[3]];
                    createModel(process.argv[3], content);
                });

            }
            if (file == "mysql") {
                //will be implemented soon...
            }

        }
    });
}
<|endoftext|>


<commit_before>'use strict';

let fs = require('fs');
let path = require('path');
let fse = require('fs-extra');
let shell = require('shelljs');
let colors = require('colors');
let inquirer = require('inquirer');

const port = 8080;
const task = process.argv[2].substring(1);
const buildjs = process.argv[3] == 'js';
const sourcePath = path.join(__dirname, '../src');
const outputPath = path.join(__dirname, '../dist');

let start = () => {
    if (task == 'dev') {
        step3().then(() => {
            return `webpack-dev-server --inline --quiet --devtool eval --progress --colors --content-base ./src/ --hot --config ./webpack/webpack.dev.js --host 0.0.0.0 --port ${ port }`;
        }).then(step4).catch(( err ) => {
            if (/listen EADDRINUSE/.test(err.toString())) {
                console.log(`\n${ port } is aleary in use. Ctrl+C to leave or input a PID to kill：`.green);
                Promise.resolve(`lsof -i tcp:${ port }`).then(step4).then(step5).then(( pid ) => {
                    return `kill ${ pid }`;
                }).then(step4).catch(( err ) => {
                    console.log(err.toString().red);
                }).then(start);
            } else {
                console.log(err.toString().red);
            }
        });
    }
    if (task == 'build') {
        if (buildjs) {
            step3().then(step6).then(step7).then(( option ) => {
                return step1().then(() => {
                    return `webpack --progress --colors --config ./webpack/webpack.build.js${ option }`;
                });
            }).then(step4).then(( cmd ) => {
                return `${ cmd } --uglify`;
            }).then(step4).then(() => {
                console.log('build complete!'.green);
            }).catch((err) => {
                console.log(err.toString().red);
            });
        } else {
            step1().then(step2).then(step3).then(() => {
                return `webpack --progress --colors --config ./webpack/webpack.build.js`;
            }).then(step4).then(() => {
                console.log('build complete!'.green);
            }).catch(( err ) => {
                console.log(err.toString().red);
            });
        }
    }
};

/**
 * [step1] fse.remove -- Remove old files
 * @return {Promise} remove_success
 */
let step1 = () => new Promise(( resolve, reject ) => {
    fse.remove(path.join(outputPath, '*'), ( err ) => {
        if (err) {
            reject(err);
            return;
        }
        resolve();
    });
});

/**
 * [step2] fse.copySync -- Copy files like `html` or `images`
 * @return {Promise} copy_success
 */
let step2 = () => new Promise(( resolve, reject ) => {
    fs.readdir(sourcePath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        }
        files.forEach(( filename ) => {
            let file = path.join(sourcePath, filename);
            if (filename[0] === '.') {
                return;
            }
            if (fs.statSync(file).isDirectory() && filename == 'entry') {
                return;
            }
            if (fs.statSync(file).isFile()) {
                if (path.extname(file) == '.ejs') {
                    return;
                }
                if (path.extname(file) == '.html') {
                    return;
                }
                if (path.extname(file) == '.appcache') {
                    return;
                }
            }
            fse.copySync(file, path.join(outputPath, filename));
        });
        resolve();
    });
});

/**
 * [step3] fse.outputJson -- Create `webpack.entry.json` dynamically
 * @return {Promise} create_entry_success
 */
let step3 = () => new Promise(( resolve, reject ) => {
    let entry = {};
    let entryPath = path.join(sourcePath, 'entry');
    fs.readdir(entryPath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        }
        files.forEach(( filename ) => {
            let file = path.join(entryPath, filename);
            if (fs.statSync(file).isFile() && path.extname(file) == '.js') {
                entry[path.basename(filename, '.js')] = file;
            }
        });
        fse.outputJson(path.join(__dirname, 'webpack.entry.json'), entry, ( err ) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(entry);
        });
    });
});

/**
 * [step4] shell.exec -- Exec command
 * @return {Promise} exec_command_success
 */
let step4 = ( cmd ) => new Promise(( resolve, reject ) => {
    let result = shell.exec(cmd);
    if (result.code === 0) {
        resolve(cmd);
    } else {
        reject(result.stderr);
    }
});

/**
 * [step5] inquirer.prompt -- Get PID
 * @return {Promise} get_pid_success
 */
let step5 = () => new Promise(( resolve, reject ) => {
    inquirer.prompt([{
        type : 'input',
        name : 'pid',
        message : 'PID:',
    }]).then(( answers ) => {
        resolve(answers.pid);
    }).catch(( err ) => {
        reject(err);
    });
});

/**
 * [step6] inquirer.prompt -- Get js file
 * @return {Promise} get_js_success
 */
let step6 = ( entry ) => new Promise(( resolve, reject ) => {
    let choices = Object.keys(entry);
    if (choices.length) {
        choices.forEach(( file, index ) => {
            choices[index] = file + '.js';
        });
        inquirer.prompt([{
            type : 'list',
            name : 'file',
            message : 'Select a file to pack:',
            choices,
        }]).then(( answers ) => {
            let file = path.basename(answers.file, '.js');
            let js = {};
            js[file] = entry[file];
            fse.outputJson(path.join(__dirname, 'webpack.entry.json'), js, ( err ) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(js[file]);
            });
        }).catch(( err ) => {
            reject(err);
        });
    } else {
        reject('There is any js file in entry.');
    }
});

/**
 * [step7] fs.readFile -- Get js webpack config
 * @return {Promise} get_config_success
 */
let step7 = ( filepath ) => new Promise(( resolve, reject ) => {
    fs.readFile(filepath, (err, buffer) => {
        if (err) {
            reject(err);
            return;
        }
        let result = '';
        let match = buffer.toString().match(/\/\*(.|\n)*?\*\//);
        if (match) {
            let comments = match[0].match(/@.*/g);
            if (comments && comments[0].trim().substring('1') == 'webpack') {
                if (comments[1] && /^@library\b/.test(comments[1]) && !/^@library$/.test(comments[1].trim())) {
                    result += comments[1].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
                if (comments[2] && /^@libraryTarget\b/.test(comments[2]) && !/^@library$/.test(comments[2].trim())) {
                    result += comments[2].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
            }
        }
        resolve(result + ' --build=js');
    });
});

start();
<commit_msg>update node<commit_after>'use strict';

let fs = require('fs');
let path = require('path');
let fse = require('fs-extra');
let shell = require('shelljs');
let colors = require('colors');
let inquirer = require('inquirer');

const port = 8080;
const task = process.argv[2].substring(1);
const buildjs = process.argv[3] == 'js';
const sourcePath = path.join(__dirname, '../src');
const outputPath = path.join(__dirname, '../dist');

let start = () => {
    function reboot ( err ) {
        if (/listen EADDRINUSE/.test(err.toString())) {
            console.log(`\n${ port } is aleary in use. Ctrl+C to leave or input a PID to kill：`.green);
            Promise.resolve(`lsof -i tcp:${ port }`).then(step2).then(step3).then(( pid ) => {
                return `kill ${ pid }`;
            }).then(step2).catch(( err ) => {
                console.log(err.toString().red);
            }).then(start);
        } else {
            console.log(err.toString().red);
        }
    }
    if (task == 'dev') {
        step1().then(() => {
            return `webpack-dev-server --inline --quiet --devtool eval --progress --colors --content-base ./src/ --hot --config ./webpack/webpack.dev.js --host 0.0.0.0 --port ${ port }`;
        }).then(step2).catch(reboot);
    }
    if (task == 'build') {
        if (buildjs) {
            step1().then(step4).then(step5).then(( option ) => {
                return `webpack --progress --colors --config ./webpack/webpack.build.js${ option }`;
            }).then(step2).then(( cmd ) => {
                return `${ cmd } --uglify`;
            }).then(step2).then(() => {
                console.log('build complete!'.green);
            }).catch((err) => {
                console.log(err.toString().red);
            });
        } else {
            step1().then(() => {
                return `webpack --progress --colors --config ./webpack/webpack.build.js`;
            }).then(step2).then(() => {
                console.log('build complete!'.green);
            }).catch(( err ) => {
                console.log(err.toString().red);
            });
        }
    }
};

/**
 * [step1] fse.outputJson -- Create `webpack.entry.json` dynamically
 * @return {Promise} create_entry_success
 */
let step1 = () => new Promise(( resolve, reject ) => {
    let entry = {};
    let entryPath = path.join(sourcePath, 'entry');
    fs.readdir(entryPath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        }
        files.forEach(( filename ) => {
            let file = path.join(entryPath, filename);
            if (fs.statSync(file).isFile() && path.extname(file) == '.js') {
                entry[path.basename(filename, '.js')] = file;
            }
        });
        fse.outputJson(path.join(__dirname, 'webpack.entry.json'), entry, ( err ) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(entry);
        });
    });
});

/**
 * [step2] shell.exec -- Exec command
 * @param  {String} cmd command
 * @return {Promise} exec_command_success
 */
let step2 = ( cmd ) => new Promise(( resolve, reject ) => {
    let result = shell.exec(cmd);
    if (result.code === 0) {
        resolve(cmd);
    } else {
        reject(result.stderr);
    }
});

/**
 * [step3] inquirer.prompt -- Get PID
 * @return {Promise} get_pid_success
 */
let step3 = () => new Promise(( resolve, reject ) => {
    inquirer.prompt([{
        type : 'input',
        name : 'pid',
        message : 'PID:',
    }]).then(( answers ) => {
        resolve(answers.pid);
    }).catch(( err ) => {
        reject(err);
    });
});

/**
 * [step4] inquirer.prompt -- Get js file
 * @param  {JSON} entry entry
 * @return {Promise} get_js_success
 */
let step4 = ( entry ) => new Promise(( resolve, reject ) => {
    let choices = Object.keys(entry);
    if (choices.length) {
        choices.forEach(( file, index ) => {
            choices[index] = file + '.js';
        });
        inquirer.prompt([{
            type : 'list',
            name : 'file',
            message : 'Select a file to pack:',
            choices,
        }]).then(( answers ) => {
            let file = path.basename(answers.file, '.js');
            let js = {};
            js[file] = entry[file];
            fse.outputJson(path.join(__dirname, 'webpack.entry.json'), js, ( err ) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(js[file]);
            });
        }).catch(( err ) => {
            reject(err);
        });
    } else {
        reject('There is any js file in entry.');
    }
});

/**
 * [step5] fs.readFile -- Get js webpack config
 * @param  {String} filepath filepath
 * @return {Promise} get_config_success
 */
let step5 = ( filepath ) => new Promise(( resolve, reject ) => {
    fs.readFile(filepath, (err, buffer) => {
        if (err) {
            reject(err);
            return;
        }
        let result = '';
        let match = buffer.toString().match(/\/\*(.|\n)*?\*\//);
        if (match) {
            let comments = match[0].match(/@.*/g);
            if (comments && comments[0].trim().substring('1') == 'webpack') {
                if (comments[1] && /^@library\b/.test(comments[1]) && !/^@library$/.test(comments[1].trim())) {
                    result += comments[1].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
                if (comments[2] && /^@libraryTarget\b/.test(comments[2]) && !/^@library$/.test(comments[2].trim())) {
                    result += comments[2].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
            }
        }
        resolve(result + ' --build=js');
    });
});

start();
<|endoftext|>


<commit_before>/**
 * Created by Samuel Gratzl on 28.11.2016.
 */

const Promise = require('bluebird');
const path = require('path');
const fs = Promise.promisifyAll(require('fs-extra'));
const chalk = require('chalk');
const pkg = require('./package.json');
const argv = require('yargs-parser')(process.argv.slice(2));
const quiet = argv.quiet !== undefined;

const now = new Date();
const prefix = (n) => n < 10 ? ('0' + n) : n.toString();
const buildId = `${now.getUTCFullYear()}${prefix(now.getUTCMonth())}${prefix(now.getUTCDate())}-${prefix(now.getUTCHours())}${prefix(now.getUTCMinutes())}${prefix(now.getUTCSeconds())}`;
pkg.version = pkg.version.replace('SNAPSHOT', buildId);
const env = Object.assign({}, process.env);

function toRepoUrl(url) {
  return url.startsWith('https://github.com/') ? url : `https://github.com/${url}`;
}

function fromRepoUrl(url) {
  if (url.includes('.git')) {
    return url.match(/\/(.*)\.git/)[0]
  }
  return url.slice(url.lastIndexOf('/') + 1);
}

/**
 * spawns a child process
 * @param cmd command as array
 * @param args arguments
 * @param opts options
 */
function spawn(cmd, args, opts) {
  const spawn = require('child_process').spawn;
  return new Promise((resolve, reject) => {
    const p = spawn(cmd, args, opts);
    if (!quiet) {
      p.stdout.on('data', (data) => console.log(data.toString()));
      p.stderr.on('data', (data) => console.error(chalk.red(data.toString())));
    }
    p.on('close', (code) => code == 0 ? resolve() : reject(code));
  });
}

/**
 * run npm with the given args
 * @param cwd working directory
 * @param cmd the command to execute as a string
 * @return {*}
 */
function npm(cwd, cmd) {
  console.log(cwd, chalk.blue('running npm', cmd));
  const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
  return spawn(npm, (cmd || 'install').split(' '), {cwd, env});
}

/**
 * runs docker command
 * @param cwd
 * @param cmd
 * @return {*}
 */
function docker(cwd, cmd) {
  console.log(cwd, chalk.blue('running docker', cmd));
  return spawn('docker', (cmd || 'build .').split(' '), {cwd, env});
}

function dockerSave(image, target) {
  console.log(chalk.blue(`running docker save ${image} | gzip > ${target}`));
  const spawn = require('child_process').spawn;
  const opts = {env};
  return new Promise((resolve, reject) => {
    const p = spawn('docker', ['save', image], opts);
    const p2 = spawn('gzip', [], opts);
    p.stdout.pipe(p2.stdin);
    p2.stdout.pipe(fs.createWriteStream(target));
    if (!quiet) {
      p.stderr.on('data', (data) => console.error(chalk.red(data.toString())));
      p2.stderr.on('data', (data) => console.error(chalk.red(data.toString())));
    }
    p2.on('close', (code) => code == 0 ? resolve() : reject(code));
  });
}

function createQuietTerminalAdapter() {
  const TerminalAdapter = require('yeoman-environment/lib/adapter');
  const impl = new TerminalAdapter();
  impl.log.write = function () {
    return this;
  };
  return impl;
}

/**
 * runs yo internally
 * @param generator
 * @param options
 * @param cwd
 */
function yo(generator, options, cwd) {
  const yeoman = require('yeoman-environment');
  // call yo internally
  const yeomanEnv = yeoman.createEnv([], {cwd, env}, quiet ? createQuietTerminalAdapter() : undefined);
  yeomanEnv.register(require.resolve('generator-phovea/generators/' + generator), 'phovea:' + generator);
  const runYo = () => new Promise((resolve, reject) => {
    try {
      console.log(cwd, chalk.blue('running yo phovea:' + generator));
      yeomanEnv.run('phovea:' + generator, options, resolve);
    } catch (e) {
      console.error('error', e, e.stack);
      reject(e);
    }
  });
  // move my own .yo-rc.json to avoid a conflict
  return fs.renameAsync('.yo-rc.json', '.yo-rc_tmp.json')
    .then(runYo)
    .then(() => fs.renameAsync('.yo-rc_tmp.json', '.yo-rc.json'));
}

function cloneRepo(p, cwd) {
  // either of them has to be defined
  p.name = p.name || fromRepoUrl(p.repo);
  p.repo = p.repo || `phovea/${p.name}`;
  p.branch = p.branch || 'master';
  console.log(cwd, chalk.blue(`running git clone --depth 1 -b ${p.branch} ${toRepoUrl(p.repo)} ${p.name}`));
  return spawn('git', ['clone', '--depth', '1', '-b', p.branch, toRepoUrl(p.repo), p.name], {cwd});
}

function preBuild(p, dir) {
  const hasAdditional = p.additional.length > 0;
  let act = fs.emptyDir(dir)
    .then(() => cloneRepo(p, dir));
  if (hasAdditional) {
    act = act
      .then(() => Promise.all(p.additional.map((pi) => cloneRepo(pi, dir))));
  }
  return act;
}

function loadComposeFile(dir, p) {
  const composeFile = `${dir}/${p.name}/deploy/docker-compose.partial.yml`;
  if (fs.existsSync(composeFile)) {
    const yaml = require('yamljs');
    return fs.readFileAsync(composeFile).then((content) => yaml.parse(content.toString()));
  } else {
    return Promise.resolve({});
  }
}

function patchComposeFile(p, composeTemplate) {
  const service = {};
  if (composeTemplate && composeTemplate.services) {
    const firstService = Object.keys(composeTemplate.services)[0];
    //copy data from first service
    Object.assign(service, composeTemplate.services[firstService]);
    delete service.build;
  }
  service.image = p.image;
  if (p.type === 'web' || p.type === 'static') {
    service.ports = ['80:80'];
  }
  const r = {
    version: '2.0',
    services: {}
  };
  r.services[p.label] = service;
  return r;
}

function postBuild(p, dir, buildInSubDir) {
  return Promise.resolve(null)
    .then(() => docker(`${dir}${buildInSubDir ? '/' + p.name : ''}`, `build -t ${p.image} -f deploy/Dockerfile .`))
    .then(() => dockerSave(p.image, `build/${p.label}_image.tar.gz`))
    .then(() => Promise.all([loadComposeFile(dir, p).then(patchComposeFile.bind(null, p))].concat(p.additional.map((pi) => loadComposeFile(dir, pi)))))
    .then(mergeCompose);
}

function buildWebApp(p, dir) {
  console.log(dir, chalk.blue('building web application:'), p.label);
  const name = p.name;
  const hasAdditional = p.additional.length > 0;
  let act = preBuild(p, dir);
  //let act = Promise.resolve(null);
  if (hasAdditional) {
    act = act
      .then(() => yo('workspace', {noAdditionals: true}, dir))
      .then(() => npm(dir, 'install'));
    //test all modules
    if (hasAdditional && !argv.skipTests) {
      act = act.then(() => Promise.all(p.additional.map((pi) => npm(dir, `run test:${pi.name}`))));
    }
    act = act
      .then(() => npm(dir, `run dist:${p.name}`));
  } else {
    act = act
      .then(() => npm(dir + '/' + name, 'install'))
      .then(() => npm(dir + '/' + name, 'run dist'));
  }
  return act
    .then(() => fs.renameAsync(`${dir}/${p.name}/dist/${p.name}.tar.gz`, `./build/${p.label}.tar.gz`))
    .then(postBuild.bind(null, p, dir, true));
}

function buildServerApp(p, dir) {
  console.log(dir, chalk.blue('building service package:'), p.label);
  const name = p.name;

  let act = preBuild(p, dir);
  act = act
    .then(() => yo('workspace', {noAdditionals: true}, dir));

  act = act
    .then(() => console.log(chalk.yellow('create test environment')))
    .then(() => npm(dir + '/' + name, 'run build'))
    .then(() => Promise.all(p.additional.map((pi) => npm(dir + '/' + pi.name, `run build`))));

  //copy all together
  act = act
    .then(() => fs.ensureDirAsync(`${dir}/build`))
    .then(() => fs.copyAsync(`${dir}/${name}/build/source`, `${dir}/build/`))
    .then(() => Promise.all(p.additional.map((pi) => fs.copyAsync(`${dir}/${pi.name}/build/source/*`, `${dir}/build/source/`))));

  //let act = Promise.resolve([]);

  //copy main deploy thing and create a docker out of it
  return act
    .then(() => fs.copyAsync(`${dir}/${name}/deploy`, `${dir}/`))
    .then(postBuild.bind(null, p, dir, false));
}

function buildImpl(d, dir) {
  switch (d.type) {
    case 'static':
    case 'web':
      return buildWebApp(d, dir);
    case 'api':
      d.name = d.name || 'phovea_server';
      return buildServerApp(d, dir);
    case 'service':
      return buildServerApp(d, dir);
    default:
      console.error(chalk.red('unknown product type: ' + d.type));
      return Promise.resolve(null);
  }
}

function mergeCompose(composePartials) {
  let dockerCompose = {};
  const _ = require('lodash');
  const mergeArrayUnion = (a, b) => Array.isArray(a) ? _.union(a, b) : undefined;
  composePartials.forEach((c) => _.mergeWith(dockerCompose, c, mergeArrayUnion));
  return dockerCompose;
}

function buildCompose(descs, composePartials) {
  const dockerCompose = mergeCompose(composePartials);
  const services = dockerCompose.services;
  // link the api server types to the web types and server to the api
  const web = descs.filter((d) => d.type === 'web').map((d) => d.label);
  const api = descs.filter((d) => d.type === 'api').map((d) => d.label);
  api.forEach((s) => {
    web.forEach((w) => {
      services[w].links = services[w].links || [];
      services[w].links.push(`${s}:api`);
    });
  });
  descs.filter((d) => d.type === 'service').forEach((s) => {
    api.forEach((w) => {
      services[w].links = services[w].links || [];
      services[w].links.push(`${s.label}:${s.name}`);
    });
  });
  const yaml = require('yamljs');
  return fs.writeFileAsync('build/docker-compose.yml', yaml.stringify(dockerCompose, 100, 2));
}

if (require.main === module) {
  if (argv.skipTests) {
    // if skipTest option is set, skip tests
    console.log(chalk.blue('skipping tests'));
    env.PHOVEA_SKIP_TESTS = true;
  }
  if (argv.quiet) {
    // if skipTest option is set, skip tests
    console.log(chalk.blue('will try to keep my mouth shut...'));
  }
  const descs = require('./phovea_product.json');

  fs.emptyDirAsync('build')
    .then(() => Promise.all(descs.map((d, i) => {
      d.additional = d.additional || []; //default values
      d.name = d.name || fromRepoUrl(d.repo);
      d.label = d.label || d.name;
      d.image = `${d.label}:${pkg.version}`;
      let wait = buildImpl(d, './tmp' + i);
      wait.catch((error) => {
        d.error = error;
        console.error('ERROR building ', d, error);
      });
      return wait;
    })))
    .then((composeFiles) => buildCompose(descs, composeFiles.filter((d) => !!d)))
    .then(() => {
      console.log(chalk.bold('summary: '));
      const maxLength = Math.max(...descs.map((d) => d.name.length));
      descs.forEach((d) => console.log(` ${d.name}${'.'.repeat(3 + (maxLength - d.name.length))}` + (d.error ? chalk.red('ERROR') : chalk.green('SUCCESS'))));
    });
}
<commit_msg>add missing async for bluebird<commit_after>/**
 * Created by Samuel Gratzl on 28.11.2016.
 */

const Promise = require('bluebird');
const path = require('path');
const fs = Promise.promisifyAll(require('fs-extra'));
const chalk = require('chalk');
const pkg = require('./package.json');
const argv = require('yargs-parser')(process.argv.slice(2));
const quiet = argv.quiet !== undefined;

const now = new Date();
const prefix = (n) => n < 10 ? ('0' + n) : n.toString();
const buildId = `${now.getUTCFullYear()}${prefix(now.getUTCMonth())}${prefix(now.getUTCDate())}-${prefix(now.getUTCHours())}${prefix(now.getUTCMinutes())}${prefix(now.getUTCSeconds())}`;
pkg.version = pkg.version.replace('SNAPSHOT', buildId);
const env = Object.assign({}, process.env);

function toRepoUrl(url) {
  return url.startsWith('https://github.com/') ? url : `https://github.com/${url}`;
}

function fromRepoUrl(url) {
  if (url.includes('.git')) {
    return url.match(/\/(.*)\.git/)[0]
  }
  return url.slice(url.lastIndexOf('/') + 1);
}

/**
 * spawns a child process
 * @param cmd command as array
 * @param args arguments
 * @param opts options
 */
function spawn(cmd, args, opts) {
  const spawn = require('child_process').spawn;
  return new Promise((resolve, reject) => {
    const p = spawn(cmd, args, opts);
    if (!quiet) {
      p.stdout.on('data', (data) => console.log(data.toString()));
      p.stderr.on('data', (data) => console.error(chalk.red(data.toString())));
    }
    p.on('close', (code) => code == 0 ? resolve() : reject(code));
  });
}

/**
 * run npm with the given args
 * @param cwd working directory
 * @param cmd the command to execute as a string
 * @return {*}
 */
function npm(cwd, cmd) {
  console.log(cwd, chalk.blue('running npm', cmd));
  const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
  return spawn(npm, (cmd || 'install').split(' '), {cwd, env});
}

/**
 * runs docker command
 * @param cwd
 * @param cmd
 * @return {*}
 */
function docker(cwd, cmd) {
  console.log(cwd, chalk.blue('running docker', cmd));
  return spawn('docker', (cmd || 'build .').split(' '), {cwd, env});
}

function dockerSave(image, target) {
  console.log(chalk.blue(`running docker save ${image} | gzip > ${target}`));
  const spawn = require('child_process').spawn;
  const opts = {env};
  return new Promise((resolve, reject) => {
    const p = spawn('docker', ['save', image], opts);
    const p2 = spawn('gzip', [], opts);
    p.stdout.pipe(p2.stdin);
    p2.stdout.pipe(fs.createWriteStream(target));
    if (!quiet) {
      p.stderr.on('data', (data) => console.error(chalk.red(data.toString())));
      p2.stderr.on('data', (data) => console.error(chalk.red(data.toString())));
    }
    p2.on('close', (code) => code == 0 ? resolve() : reject(code));
  });
}

function createQuietTerminalAdapter() {
  const TerminalAdapter = require('yeoman-environment/lib/adapter');
  const impl = new TerminalAdapter();
  impl.log.write = function () {
    return this;
  };
  return impl;
}

/**
 * runs yo internally
 * @param generator
 * @param options
 * @param cwd
 */
function yo(generator, options, cwd) {
  const yeoman = require('yeoman-environment');
  // call yo internally
  const yeomanEnv = yeoman.createEnv([], {cwd, env}, quiet ? createQuietTerminalAdapter() : undefined);
  yeomanEnv.register(require.resolve('generator-phovea/generators/' + generator), 'phovea:' + generator);
  const runYo = () => new Promise((resolve, reject) => {
    try {
      console.log(cwd, chalk.blue('running yo phovea:' + generator));
      yeomanEnv.run('phovea:' + generator, options, resolve);
    } catch (e) {
      console.error('error', e, e.stack);
      reject(e);
    }
  });
  // move my own .yo-rc.json to avoid a conflict
  return fs.renameAsync('.yo-rc.json', '.yo-rc_tmp.json')
    .then(runYo)
    .then(() => fs.renameAsync('.yo-rc_tmp.json', '.yo-rc.json'));
}

function cloneRepo(p, cwd) {
  // either of them has to be defined
  p.name = p.name || fromRepoUrl(p.repo);
  p.repo = p.repo || `phovea/${p.name}`;
  p.branch = p.branch || 'master';
  console.log(cwd, chalk.blue(`running git clone --depth 1 -b ${p.branch} ${toRepoUrl(p.repo)} ${p.name}`));
  return spawn('git', ['clone', '--depth', '1', '-b', p.branch, toRepoUrl(p.repo), p.name], {cwd});
}

function preBuild(p, dir) {
  const hasAdditional = p.additional.length > 0;
  let act = fs.emptyDirAsync(dir)
    .then(() => cloneRepo(p, dir));
  if (hasAdditional) {
    act = act
      .then(() => Promise.all(p.additional.map((pi) => cloneRepo(pi, dir))));
  }
  return act;
}

function loadComposeFile(dir, p) {
  const composeFile = `${dir}/${p.name}/deploy/docker-compose.partial.yml`;
  if (fs.existsSync(composeFile)) {
    const yaml = require('yamljs');
    return fs.readFileAsync(composeFile).then((content) => yaml.parse(content.toString()));
  } else {
    return Promise.resolve({});
  }
}

function patchComposeFile(p, composeTemplate) {
  const service = {};
  if (composeTemplate && composeTemplate.services) {
    const firstService = Object.keys(composeTemplate.services)[0];
    //copy data from first service
    Object.assign(service, composeTemplate.services[firstService]);
    delete service.build;
  }
  service.image = p.image;
  if (p.type === 'web' || p.type === 'static') {
    service.ports = ['80:80'];
  }
  const r = {
    version: '2.0',
    services: {}
  };
  r.services[p.label] = service;
  return r;
}

function postBuild(p, dir, buildInSubDir) {
  return Promise.resolve(null)
    .then(() => docker(`${dir}${buildInSubDir ? '/' + p.name : ''}`, `build -t ${p.image} -f deploy/Dockerfile .`))
    .then(() => dockerSave(p.image, `build/${p.label}_image.tar.gz`))
    .then(() => Promise.all([loadComposeFile(dir, p).then(patchComposeFile.bind(null, p))].concat(p.additional.map((pi) => loadComposeFile(dir, pi)))))
    .then(mergeCompose);
}

function buildWebApp(p, dir) {
  console.log(dir, chalk.blue('building web application:'), p.label);
  const name = p.name;
  const hasAdditional = p.additional.length > 0;
  let act = preBuild(p, dir);
  //let act = Promise.resolve(null);
  if (hasAdditional) {
    act = act
      .then(() => yo('workspace', {noAdditionals: true}, dir))
      .then(() => npm(dir, 'install'));
    //test all modules
    if (hasAdditional && !argv.skipTests) {
      act = act.then(() => Promise.all(p.additional.map((pi) => npm(dir, `run test:${pi.name}`))));
    }
    act = act
      .then(() => npm(dir, `run dist:${p.name}`));
  } else {
    act = act
      .then(() => npm(dir + '/' + name, 'install'))
      .then(() => npm(dir + '/' + name, 'run dist'));
  }
  return act
    .then(() => fs.renameAsync(`${dir}/${p.name}/dist/${p.name}.tar.gz`, `./build/${p.label}.tar.gz`))
    .then(postBuild.bind(null, p, dir, true));
}

function buildServerApp(p, dir) {
  console.log(dir, chalk.blue('building service package:'), p.label);
  const name = p.name;

  let act = preBuild(p, dir);
  act = act
    .then(() => yo('workspace', {noAdditionals: true}, dir));

  act = act
    .then(() => console.log(chalk.yellow('create test environment')))
    .then(() => npm(dir + '/' + name, 'run build'))
    .then(() => Promise.all(p.additional.map((pi) => npm(dir + '/' + pi.name, `run build`))));

  //copy all together
  act = act
    .then(() => fs.ensureDirAsync(`${dir}/build`))
    .then(() => fs.copyAsync(`${dir}/${name}/build/source`, `${dir}/build/`))
    .then(() => Promise.all(p.additional.map((pi) => fs.copyAsync(`${dir}/${pi.name}/build/source/*`, `${dir}/build/source/`))));

  //let act = Promise.resolve([]);

  //copy main deploy thing and create a docker out of it
  return act
    .then(() => fs.copyAsync(`${dir}/${name}/deploy`, `${dir}/`))
    .then(postBuild.bind(null, p, dir, false));
}

function buildImpl(d, dir) {
  switch (d.type) {
    case 'static':
    case 'web':
      return buildWebApp(d, dir);
    case 'api':
      d.name = d.name || 'phovea_server';
      return buildServerApp(d, dir);
    case 'service':
      return buildServerApp(d, dir);
    default:
      console.error(chalk.red('unknown product type: ' + d.type));
      return Promise.resolve(null);
  }
}

function mergeCompose(composePartials) {
  let dockerCompose = {};
  const _ = require('lodash');
  const mergeArrayUnion = (a, b) => Array.isArray(a) ? _.union(a, b) : undefined;
  composePartials.forEach((c) => _.mergeWith(dockerCompose, c, mergeArrayUnion));
  return dockerCompose;
}

function buildCompose(descs, composePartials) {
  const dockerCompose = mergeCompose(composePartials);
  const services = dockerCompose.services;
  // link the api server types to the web types and server to the api
  const web = descs.filter((d) => d.type === 'web').map((d) => d.label);
  const api = descs.filter((d) => d.type === 'api').map((d) => d.label);
  api.forEach((s) => {
    web.forEach((w) => {
      services[w].links = services[w].links || [];
      services[w].links.push(`${s}:api`);
    });
  });
  descs.filter((d) => d.type === 'service').forEach((s) => {
    api.forEach((w) => {
      services[w].links = services[w].links || [];
      services[w].links.push(`${s.label}:${s.name}`);
    });
  });
  const yaml = require('yamljs');
  return fs.writeFileAsync('build/docker-compose.yml', yaml.stringify(dockerCompose, 100, 2));
}

if (require.main === module) {
  if (argv.skipTests) {
    // if skipTest option is set, skip tests
    console.log(chalk.blue('skipping tests'));
    env.PHOVEA_SKIP_TESTS = true;
  }
  if (argv.quiet) {
    // if skipTest option is set, skip tests
    console.log(chalk.blue('will try to keep my mouth shut...'));
  }
  const descs = require('./phovea_product.json');

  fs.emptyDirAsync('build')
    .then(() => Promise.all(descs.map((d, i) => {
      d.additional = d.additional || []; //default values
      d.name = d.name || fromRepoUrl(d.repo);
      d.label = d.label || d.name;
      d.image = `${d.label}:${pkg.version}`;
      let wait = buildImpl(d, './tmp' + i);
      wait.catch((error) => {
        d.error = error;
        console.error('ERROR building ', d, error);
      });
      return wait;
    })))
    .then((composeFiles) => buildCompose(descs, composeFiles.filter((d) => !!d)))
    .then(() => {
      console.log(chalk.bold('summary: '));
      const maxLength = Math.max(...descs.map((d) => d.name.length));
      descs.forEach((d) => console.log(` ${d.name}${'.'.repeat(3 + (maxLength - d.name.length))}` + (d.error ? chalk.red('ERROR') : chalk.green('SUCCESS'))));
    });
}
<|endoftext|>


<commit_before>/* Proximity listener - for the proximity device found on the Sony VAIO (and others).
 *
 * Copyright 2017 Raising the Floor - International
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The R&D leading to these results received funding from the
 * Department of Education - Grant H421A150005 (GPII-APCP). However,
 * these results do not necessarily represent the policy of the
 * Department of Education, and you should not assume endorsement by the
 * Federal Government.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */

"use strict";

var fluid = require("gpii-universal"),
    path = require("path"),
    edge = process.versions.electron ? require("electron-edge") : require("edge-js");

var gpii = fluid.registerNamespace("gpii");

// The proximity user listener
fluid.defaults("gpii.windows.userListeners.proximity", {
    gradeNames: ["fluid.component", "gpii.userListener"],
    members: {
        proximity: true,
        listenerName: "Proximity"
    },
    invokers: {
        startListener: {
            funcName: "gpii.windows.userListeners.startProximityListener",
            args: ["{that}"]
        },
        stopListener: {
            funcName: "gpii.windows.userListeners.stopProximityListener",
            args: ["{that}"]
        }
    }
});

/**
 * Calls the .NET proximity method to start/stop listening for NFC tags.
 *
 * See proximity.cs.
 *
 * @param options {object} Options object.
 * @param options.onTag {Function(tagBuffer)} [Optional] Call-back for when a tag has been presented.
 * @param options.stop {boolean} [Optional] true to stop listening for tags (onTag is ignored).
 * @return {Promise} Resolves with a value of true if successfully listening for tags, or false if there's no device.
 */
gpii.windows.userListeners.listenForTags = function (options) {
    var promise = fluid.promise();

    if (!options || (typeof(options.gotTag) !== "function" && !options.stop)) {
        fluid.fail("listenForTags() expects either options.gotTag or options.stop to be defined.");
    }

    options.stop = !!options.stop;

    if (!gpii.windows.userListeners.proximityFunction) {
        gpii.windows.userListeners.proximityFunction = edge.func({
            source: path.join(__dirname, "proximity.cs"),
            references: [
                path.join(process.env.SystemRoot, "System32\\WinMetadata\\Windows.Networking.winmd"),
                path.join(process.env.SystemRoot, "System32\\WinMetadata\\Windows.Storage.winmd"),
                "System.Runtime.dll",
                "System.Runtime.InteropServices.WindowsRuntime.dll"
            ]
        });
    }

    try {
        gpii.windows.userListeners.proximityFunction(options, function (err, result) {
            if (err) {
                promise.reject({
                    isError: true,
                    message: "Error calling .NET code for listenForTags.",
                    error: err
                });
            } else {
                promise.resolve(!!result);
            }
        });
    } catch (err) {
        promise.reject({
            isError: true,
            message: "Exception thrown from .NET listenForTags.",
            error: err
        });
    }
    return promise;
};

/**
 * Starts the proximity user listener.
 *
 * @param that {Component} The gpii.windows.userListeners.proximity instance.
 */
gpii.windows.userListeners.startProximityListener = function (that) {
    var promise = fluid.promise();

    gpii.windows.userListeners.listenForTags({
        gotTag: function (tagBuffer) {
            gpii.windows.userListeners.gotProximityTag(that, tagBuffer);
        }
    }).then(function (result) {
        if (result) {
            promise.resolve();
        } else {
            // No device.
            promise.reject({
                isError: true,
                noDevice: true,
                message: "No proximity device."
            });
        }
    });

    return promise;
};

/**
 * Callback for when the proximity receives a tag.
 *
 * @param that {Component} The gpii.windows.userListeners.proximity instance.
 * @param tagBuffer {Buffer} The NTAG message.
 */
gpii.windows.userListeners.gotProximityTag = function (that, tagBuffer) {
    var text = that.decodeNDEF(tagBuffer);
    if (text) {
        that.events.onTokenArrive.fire(that, text);
    }
};

/**
 * Stops the proximity user listener.
 *
 * @returns {Promise} Resolves when stopped (value true if there was a device).
 */
gpii.windows.userListeners.stopProximityListener = function () {
    return gpii.windows.userListeners.listenForTags({ stop: true });
};
<commit_msg>GPII-2294: Referring to "electron-edge-js" instead of "electron-edge"<commit_after>/* Proximity listener - for the proximity device found on the Sony VAIO (and others).
 *
 * Copyright 2017 Raising the Floor - International
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The R&D leading to these results received funding from the
 * Department of Education - Grant H421A150005 (GPII-APCP). However,
 * these results do not necessarily represent the policy of the
 * Department of Education, and you should not assume endorsement by the
 * Federal Government.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */

"use strict";

var fluid = require("gpii-universal"),
    path = require("path"),
    edge = process.versions.electron ? require("electron-edge-js") : require("edge-js");

var gpii = fluid.registerNamespace("gpii");

// The proximity user listener
fluid.defaults("gpii.windows.userListeners.proximity", {
    gradeNames: ["fluid.component", "gpii.userListener"],
    members: {
        proximity: true,
        listenerName: "Proximity"
    },
    invokers: {
        startListener: {
            funcName: "gpii.windows.userListeners.startProximityListener",
            args: ["{that}"]
        },
        stopListener: {
            funcName: "gpii.windows.userListeners.stopProximityListener",
            args: ["{that}"]
        }
    }
});

/**
 * Calls the .NET proximity method to start/stop listening for NFC tags.
 *
 * See proximity.cs.
 *
 * @param options {object} Options object.
 * @param options.onTag {Function(tagBuffer)} [Optional] Call-back for when a tag has been presented.
 * @param options.stop {boolean} [Optional] true to stop listening for tags (onTag is ignored).
 * @return {Promise} Resolves with a value of true if successfully listening for tags, or false if there's no device.
 */
gpii.windows.userListeners.listenForTags = function (options) {
    var promise = fluid.promise();

    if (!options || (typeof(options.gotTag) !== "function" && !options.stop)) {
        fluid.fail("listenForTags() expects either options.gotTag or options.stop to be defined.");
    }

    options.stop = !!options.stop;

    if (!gpii.windows.userListeners.proximityFunction) {
        gpii.windows.userListeners.proximityFunction = edge.func({
            source: path.join(__dirname, "proximity.cs"),
            references: [
                path.join(process.env.SystemRoot, "System32\\WinMetadata\\Windows.Networking.winmd"),
                path.join(process.env.SystemRoot, "System32\\WinMetadata\\Windows.Storage.winmd"),
                "System.Runtime.dll",
                "System.Runtime.InteropServices.WindowsRuntime.dll"
            ]
        });
    }

    try {
        gpii.windows.userListeners.proximityFunction(options, function (err, result) {
            if (err) {
                promise.reject({
                    isError: true,
                    message: "Error calling .NET code for listenForTags.",
                    error: err
                });
            } else {
                promise.resolve(!!result);
            }
        });
    } catch (err) {
        promise.reject({
            isError: true,
            message: "Exception thrown from .NET listenForTags.",
            error: err
        });
    }
    return promise;
};

/**
 * Starts the proximity user listener.
 *
 * @param that {Component} The gpii.windows.userListeners.proximity instance.
 */
gpii.windows.userListeners.startProximityListener = function (that) {
    var promise = fluid.promise();

    gpii.windows.userListeners.listenForTags({
        gotTag: function (tagBuffer) {
            gpii.windows.userListeners.gotProximityTag(that, tagBuffer);
        }
    }).then(function (result) {
        if (result) {
            promise.resolve();
        } else {
            // No device.
            promise.reject({
                isError: true,
                noDevice: true,
                message: "No proximity device."
            });
        }
    });

    return promise;
};

/**
 * Callback for when the proximity receives a tag.
 *
 * @param that {Component} The gpii.windows.userListeners.proximity instance.
 * @param tagBuffer {Buffer} The NTAG message.
 */
gpii.windows.userListeners.gotProximityTag = function (that, tagBuffer) {
    var text = that.decodeNDEF(tagBuffer);
    if (text) {
        that.events.onTokenArrive.fire(that, text);
    }
};

/**
 * Stops the proximity user listener.
 *
 * @returns {Promise} Resolves when stopped (value true if there was a device).
 */
gpii.windows.userListeners.stopProximityListener = function () {
    return gpii.windows.userListeners.listenForTags({ stop: true });
};
<|endoftext|>


<commit_before>// Copyright 2014 The Cayley Authors. All rights reserved.
//
// 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.

$(function() {

  $("#sbQuery").addClass("active");

  output_editor = CodeMirror.fromTextArea(document.getElementById("output"), {
    lineNumbers: true,
    matchBrackets: true,
  });

  $("#run_button").click(function() {
    var data = editor.getValue()
    $("#output").text(editor.getValue())
    animate();
    $.post("/api/v1/query/" + selectedQueryLanguage, data)
      .done(function(return_data) {
        if (typeof(Storage) !== "undefined") {
          localStorage.setItem("cayleySavedQueries" + selectedQueryLanguage, data)
        }
        output_editor.setValue(return_data)
        stopAndReset();
      })
      .fail(function(jqxhr, textStatus, errorThrown){
        output_editor.setValue(jqxhr.responseText)
        stopAndReset();
      })
  })
});
<commit_msg>ui: format json results; resolve #454<commit_after>// Copyright 2014 The Cayley Authors. All rights reserved.
//
// 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.

$(function() {

  $("#sbQuery").addClass("active");

  output_editor = CodeMirror.fromTextArea(document.getElementById("output"), {
    lineNumbers: true,
    matchBrackets: true,
  });

  $("#run_button").click(function() {
    var data = editor.getValue()
    $("#output").text(editor.getValue())
    animate();
    $.post("/api/v1/query/" + selectedQueryLanguage, data)
      .done(function(return_data) {
        if (typeof(Storage) !== "undefined") {
          localStorage.setItem("cayleySavedQueries" + selectedQueryLanguage, data)
        }
        output_editor.setValue(JSON.stringify(JSON.parse(return_data), null, '\t'))
        stopAndReset();
      })
      .fail(function(jqxhr, textStatus, errorThrown){
        output_editor.setValue(jqxhr.responseText)
        stopAndReset();
      })
  })
});
<|endoftext|>