chore: reformat code with Prettier

This commit is contained in:
Julien Fontanet 2020-06-03 11:02:14 +02:00
parent 3524886d5d
commit f18e98a63e
95 changed files with 283 additions and 350 deletions

View File

@ -51,7 +51,7 @@ const pluginsOrder = [
'@babel/plugin-proposal-class-properties', '@babel/plugin-proposal-class-properties',
] ]
module.exports = function(pkg, plugins, presets) { module.exports = function (pkg, plugins, presets) {
plugins === undefined && (plugins = {}) plugins === undefined && (plugins = {})
presets === undefined && (presets = {}) presets === undefined && (presets = {})

View File

@ -3,7 +3,7 @@ const getopts = require('getopts')
const { version } = require('./package.json') const { version } = require('./package.json')
module.exports = commands => module.exports = commands =>
async function(args, prefix) { async function (args, prefix) {
const opts = getopts(args, { const opts = getopts(args, {
alias: { alias: {
help: 'h', help: 'h',

View File

@ -5,7 +5,7 @@ const { NULL_REF, Xapi } = require('xen-api')
const pkg = require('./package.json') const pkg = require('./package.json')
Xapi.prototype.getVmDisks = async function(vm) { Xapi.prototype.getVmDisks = async function (vm) {
const disks = { __proto__: null } const disks = { __proto__: null }
await Promise.all([ await Promise.all([
...vm.VBDs.map(async vbdRef => { ...vm.VBDs.map(async vbdRef => {

View File

@ -21,7 +21,7 @@ import emitAsync from '@xen-orchestra/emit-async'
const ee = new EE() const ee = new EE()
ee.emitAsync = emitAsync ee.emitAsync = emitAsync
ee.on('start', async function() { ee.on('start', async function () {
// whatever // whatever
}) })

View File

@ -5,7 +5,7 @@ import emitAsync from '@xen-orchestra/emit-async'
const ee = new EE() const ee = new EE()
ee.emitAsync = emitAsync ee.emitAsync = emitAsync
ee.on('start', async function() { ee.on('start', async function () {
// whatever // whatever
}) })

View File

@ -31,10 +31,7 @@ export default class MountHandler extends LocalHandler {
} }
this._realPath = join( this._realPath = join(
mountsDir, mountsDir,
remote.id || remote.id || Math.random().toString(36).slice(2)
Math.random()
.toString(36)
.slice(2)
) )
} }

View File

@ -648,7 +648,7 @@ function createPrefixWrapperMethods() {
return return
} }
descriptor.value = function() { descriptor.value = function () {
let path let path
if (arguments.length !== 0 && typeof (path = arguments[0]) === 'string') { if (arguments.length !== 0 && typeof (path = arguments[0]) === 'string') {
arguments[0] = this._resolve(path) arguments[0] = this._resolve(path)

View File

@ -28,7 +28,7 @@ const unsecureRandomBytes = n => {
const TEST_DATA_LEN = 1024 const TEST_DATA_LEN = 1024
const TEST_DATA = unsecureRandomBytes(TEST_DATA_LEN) const TEST_DATA = unsecureRandomBytes(TEST_DATA_LEN)
const createTestDataStream = asyncIteratorToStream(function*() { const createTestDataStream = asyncIteratorToStream(function* () {
yield TEST_DATA yield TEST_DATA
}) })

View File

@ -12,7 +12,7 @@ const createTransport = config => {
if (Array.isArray(config)) { if (Array.isArray(config)) {
const transports = config.map(createTransport) const transports = config.map(createTransport)
const { length } = transports const { length } = transports
return function() { return function () {
for (let i = 0; i < length; ++i) { for (let i = 0; i < length; ++i) {
transports[i].apply(this, arguments) transports[i].apply(this, arguments)
} }
@ -30,14 +30,14 @@ const createTransport = config => {
} }
const orig = transport const orig = transport
transport = function(log) { transport = function (log) {
if ((level !== undefined && log.level >= level) || filter(log)) { if ((level !== undefined && log.level >= level) || filter(log)) {
return orig.apply(this, arguments) return orig.apply(this, arguments)
} }
} }
} else if (level !== undefined) { } else if (level !== undefined) {
const orig = transport const orig = transport
transport = function(log) { transport = function (log) {
if (log.level >= level) { if (log.level >= level) {
return orig.apply(this, arguments) return orig.apply(this, arguments)
} }

View File

@ -38,7 +38,7 @@ const { prototype } = Logger
for (const name in LEVELS) { for (const name in LEVELS) {
const level = LEVELS[name] const level = LEVELS[name]
prototype[name.toLowerCase()] = function(message, data) { prototype[name.toLowerCase()] = function (message, data) {
if (typeof message !== 'string') { if (typeof message !== 'string') {
if (message instanceof Error) { if (message instanceof Error) {
data = { error: message } data = { error: message }
@ -54,13 +54,13 @@ for (const name in LEVELS) {
} }
} }
prototype.wrap = function(message, fn) { prototype.wrap = function (message, fn) {
const logger = this const logger = this
const warnAndRethrow = error => { const warnAndRethrow = error => {
logger.warn(message, { error }) logger.warn(message, { error })
throw error throw error
} }
return function() { return function () {
try { try {
const result = fn.apply(this, arguments) const result = fn.apply(this, arguments)
const then = result != null && result.then const then = result != null && result.then

View File

@ -13,10 +13,7 @@ export const evalTemplate = (tpl, data) => {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
const compileGlobPatternFragment = pattern => const compileGlobPatternFragment = pattern =>
pattern pattern.split('*').map(escapeRegExp).join('.*')
.split('*')
.map(escapeRegExp)
.join('.*')
export const compileGlobPattern = pattern => { export const compileGlobPattern = pattern => {
const no = [] const no = []

View File

@ -37,7 +37,7 @@ export async function set(data) {
export async function unset(paths) { export async function unset(paths) {
const config = await load() const config = await load()
const l33tConfig = l33t(config) const l33tConfig = l33t(config)
;[].concat(paths).forEach(function(path) { ;[].concat(paths).forEach(function (path) {
l33tConfig.purge(path, true) l33tConfig.purge(path, true)
}) })
return save(config) return save(config)

View File

@ -55,7 +55,7 @@ function help() {
$name v$version $name v$version
` `
).replace(/<([^>]+)>|\$(\w+)/g, function(_, arg, key) { ).replace(/<([^>]+)>|\$(\w+)/g, function (_, arg, key) {
if (arg) { if (arg) {
return '<' + chalk.yellow(arg) + '>' return '<' + chalk.yellow(arg) + '>'
} }

View File

@ -173,9 +173,9 @@ const handleHook = data => {
// Log it // Log it
console.log( console.log(
`${new Date( `${new Date(timestamp).toISOString()} [${method}|${type}] ${params} → ${
timestamp result || error
).toISOString()} [${method}|${type}] ${params} → ${result || error}` }`
) )
// Run scripts // Run scripts

View File

@ -221,13 +221,7 @@ export class GlobPattern extends Node {
Object.defineProperty(this, 'match', { Object.defineProperty(this, 'match', {
value: this.match.bind( value: this.match.bind(
this, this,
new RegExp( new RegExp(value.split('*').map(escapeRegExp).join('.*'), 'i')
value
.split('*')
.map(escapeRegExp)
.join('.*'),
'i'
)
), ),
}) })
} }

View File

@ -16,6 +16,7 @@ Installation of the [npm package](https://npmjs.org/package/value-matcher):
```js ```js
import { createPredicate } from 'value-matcher' import { createPredicate } from 'value-matcher'
;[ ;[
{ user: 'sam', age: 65, active: false }, { user: 'sam', age: 65, active: false },
{ user: 'barney', age: 36, active: true }, { user: 'barney', age: 36, active: true },

View File

@ -11,10 +11,10 @@ export default async function main(args) {
const handler = getHandler({ url: 'file:///' }) const handler = getHandler({ url: 'file:///' })
const stream = await createSyntheticStream(handler, path.resolve(args[0])) const stream = await createSyntheticStream(handler, path.resolve(args[0]))
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
stream.on('error', reject).pipe( stream
createWriteStream(args[1]) .on('error', reject)
.on('error', reject) .pipe(
.on('finish', resolve) createWriteStream(args[1]).on('error', reject).on('finish', resolve)
) )
}) })
} }

View File

@ -28,7 +28,7 @@ afterEach(async () => {
}) })
async function createRandomFile(name, sizeMB) { async function createRandomFile(name, sizeMB) {
const createRandomStream = asyncIteratorToStream(function*(size) { const createRandomStream = asyncIteratorToStream(function* (size) {
while (size-- > 0) { while (size-- > 0) {
yield Buffer.from([Math.floor(Math.random() * 256)]) yield Buffer.from([Math.floor(Math.random() * 256)])
} }

View File

@ -2,7 +2,7 @@ import asyncIteratorToStream from 'async-iterator-to-stream'
import Vhd from './vhd' import Vhd from './vhd'
export default asyncIteratorToStream(async function*(handler, path) { export default asyncIteratorToStream(async function* (handler, path) {
const fd = await handler.openFile(path, 'r') const fd = await handler.openFile(path, 'r')
try { try {
const vhd = new Vhd(handler, fd) const vhd = new Vhd(handler, fd)

View File

@ -3,7 +3,7 @@ import asyncIteratorToStream from 'async-iterator-to-stream'
import computeGeometryForSize from './_computeGeometryForSize' import computeGeometryForSize from './_computeGeometryForSize'
import { createFooter } from './_createFooterHeader' import { createFooter } from './_createFooterHeader'
export default asyncIteratorToStream(async function*(size, blockParser) { export default asyncIteratorToStream(async function* (size, blockParser) {
const geometry = computeGeometryForSize(size) const geometry = computeGeometryForSize(size)
const actualSize = geometry.actualSize const actualSize = geometry.actualSize
const footer = createFooter( const footer = createFooter(

View File

@ -96,7 +96,7 @@ export default async function createSyntheticStream(handler, paths) {
} }
const fileSize = blockOffset * SECTOR_SIZE + FOOTER_SIZE const fileSize = blockOffset * SECTOR_SIZE + FOOTER_SIZE
const iterator = function*() { const iterator = function* () {
try { try {
footer = fuFooter.pack(footer) footer = fuFooter.pack(footer)
checksumStruct(footer, fuFooter) checksumStruct(footer, fuFooter)
@ -119,7 +119,7 @@ export default async function createSyntheticStream(handler, paths) {
yield bitmap yield bitmap
const blocksByVhd = new Map() const blocksByVhd = new Map()
const emitBlockSectors = function*(iVhd, i, n) { const emitBlockSectors = function* (iVhd, i, n) {
const vhd = vhds[iVhd] const vhd = vhds[iVhd]
const isRootVhd = vhd === rootVhd const isRootVhd = vhd === rootVhd
if (!vhd.containsBlock(iBlock)) { if (!vhd.containsBlock(iBlock)) {

View File

@ -36,7 +36,7 @@ const convert = (inputFormat, inputFile, outputFormat, outputFile) =>
outputFile, outputFile,
]) ])
const createRandomStream = asyncIteratorToStream(function*(size) { const createRandomStream = asyncIteratorToStream(function* (size) {
let requested = Math.min(size, yield) let requested = Math.min(size, yield)
while (size > 0) { while (size > 0) {
const buf = Buffer.allocUnsafe(requested) const buf = Buffer.allocUnsafe(requested)

View File

@ -49,7 +49,7 @@ const getStyle = vdi => {
} }
const mapFilter = (collection, iteratee, results = []) => { const mapFilter = (collection, iteratee, results = []) => {
forEach(collection, function() { forEach(collection, function () {
const result = iteratee.apply(this, arguments) const result = iteratee.apply(this, arguments)
if (result !== undefined) { if (result !== undefined) {
results.push(result) results.push(result)

View File

@ -4,7 +4,7 @@ export default function coalesceCalls(fn) {
const clean = () => { const clean = () => {
promise = undefined promise = undefined
} }
return function() { return function () {
if (promise !== undefined) { if (promise !== undefined) {
return promise return promise
} }

View File

@ -517,9 +517,7 @@ export class Xapi extends EventEmitter {
throw new Error('Xapi#barrier() requires events watching') throw new Error('Xapi#barrier() requires events watching')
} }
const key = `xo:barrier:${Math.random() const key = `xo:barrier:${Math.random().toString(36).slice(2)}`
.toString(36)
.slice(2)}`
const poolRef = this._pool.$ref const poolRef = this._pool.$ref
const { promise, resolve } = defer() const { promise, resolve } = defer()
@ -1079,7 +1077,7 @@ export class Xapi extends EventEmitter {
const getObjectByRef = ref => this._objectsByRef[ref] const getObjectByRef = ref => this._objectsByRef[ref]
Record = defineProperty( Record = defineProperty(
function(ref, data) { function (ref, data) {
defineProperties(this, { defineProperties(this, {
$id: { value: data.uuid ?? ref }, $id: { value: data.uuid ?? ref },
$ref: { value: ref }, $ref: { value: ref },
@ -1098,10 +1096,10 @@ export class Xapi extends EventEmitter {
const getters = { $pool: getPool } const getters = { $pool: getPool }
const props = { const props = {
$call: function(method, ...args) { $call: function (method, ...args) {
return xapi.call(`${type}.${method}`, this.$ref, ...args) return xapi.call(`${type}.${method}`, this.$ref, ...args)
}, },
$callAsync: function(method, ...args) { $callAsync: function (method, ...args) {
return xapi.callAsync(`${type}.${method}`, this.$ref, ...args) return xapi.callAsync(`${type}.${method}`, this.$ref, ...args)
}, },
$type: type, $type: type,
@ -1113,7 +1111,7 @@ export class Xapi extends EventEmitter {
if (typeof fn === 'function' && name.startsWith(type + '_')) { if (typeof fn === 'function' && name.startsWith(type + '_')) {
const key = '$' + name.slice(type.length + 1) const key = '$' + name.slice(type.length + 1)
assert.strictEqual(props[key], undefined) assert.strictEqual(props[key], undefined)
props[key] = function(...args) { props[key] = function (...args) {
return xapi[name](this.$ref, ...args) return xapi[name](this.$ref, ...args)
} }
} }
@ -1124,7 +1122,7 @@ export class Xapi extends EventEmitter {
} }
})(xapi) })(xapi)
fields.forEach(field => { fields.forEach(field => {
props[`set_${field}`] = function(value) { props[`set_${field}`] = function (value) {
return xapi.setField(this.$type, this.$ref, field, value) return xapi.setField(this.$type, this.$ref, field, value)
} }
@ -1133,24 +1131,24 @@ export class Xapi extends EventEmitter {
const value = data[field] const value = data[field]
if (Array.isArray(value)) { if (Array.isArray(value)) {
if (value.length === 0 || isOpaqueRef(value[0])) { if (value.length === 0 || isOpaqueRef(value[0])) {
getters[$field] = function() { getters[$field] = function () {
const value = this[field] const value = this[field]
return value.length === 0 ? value : value.map(getObjectByRef) return value.length === 0 ? value : value.map(getObjectByRef)
} }
} }
props[`add_${field}`] = function(value) { props[`add_${field}`] = function (value) {
return xapi return xapi
.call(`${type}.add_${field}`, this.$ref, value) .call(`${type}.add_${field}`, this.$ref, value)
.then(noop) .then(noop)
} }
props[`remove_${field}`] = function(value) { props[`remove_${field}`] = function (value) {
return xapi return xapi
.call(`${type}.remove_${field}`, this.$ref, value) .call(`${type}.remove_${field}`, this.$ref, value)
.then(noop) .then(noop)
} }
} else if (value !== null && typeof value === 'object') { } else if (value !== null && typeof value === 'object') {
getters[$field] = function() { getters[$field] = function () {
const value = this[field] const value = this[field]
const result = {} const result = {}
getKeys(value).forEach(key => { getKeys(value).forEach(key => {
@ -1158,7 +1156,7 @@ export class Xapi extends EventEmitter {
}) })
return result return result
} }
props[`update_${field}`] = function(entries, value) { props[`update_${field}`] = function (entries, value) {
return typeof entries === 'string' return typeof entries === 'string'
? xapi.setFieldEntry(this.$type, this.$ref, field, entries, value) ? xapi.setFieldEntry(this.$type, this.$ref, field, entries, value)
: xapi.setFieldEntries(this.$type, this.$ref, field, entries) : xapi.setFieldEntries(this.$type, this.$ref, field, entries)
@ -1167,7 +1165,7 @@ export class Xapi extends EventEmitter {
// 2019-02-07 - JFT: even if `value` should not be an empty string for // 2019-02-07 - JFT: even if `value` should not be an empty string for
// a ref property, an user had the case on XenServer 7.0 on the CD VBD // a ref property, an user had the case on XenServer 7.0 on the CD VBD
// of a VM created by XenCenter // of a VM created by XenCenter
getters[$field] = function() { getters[$field] = function () {
return xapi._objectsByRef[this[field]] return xapi._objectsByRef[this[field]]
} }
} }

View File

@ -22,9 +22,7 @@ async function main([url]) {
while (loop) { while (loop) {
await pool.update_other_config( await pool.update_other_config(
'xo:injectEvents', 'xo:injectEvents',
Math.random() Math.random().toString(36).slice(2)
.toString(36)
.slice(2)
) )
await pDelay(1e2) await pDelay(1e2)
} }

View File

@ -18,36 +18,36 @@ const configFile = configPath + '/config.json'
// =================================================================== // ===================================================================
const load = (exports.load = function() { const load = (exports.load = function () {
return readFile(configFile) return readFile(configFile)
.then(JSON.parse) .then(JSON.parse)
.catch(function() { .catch(function () {
return {} return {}
}) })
}) })
exports.get = function(path) { exports.get = function (path) {
return load().then(function(config) { return load().then(function (config) {
return l33t(config).tap(path) return l33t(config).tap(path)
}) })
} }
const save = (exports.save = function(config) { const save = (exports.save = function (config) {
return mkdirp(configPath).then(function() { return mkdirp(configPath).then(function () {
return writeFile(configFile, JSON.stringify(config)) return writeFile(configFile, JSON.stringify(config))
}) })
}) })
exports.set = function(data) { exports.set = function (data) {
return load().then(function(config) { return load().then(function (config) {
return save(Object.assign(config, data)) return save(Object.assign(config, data))
}) })
} }
exports.unset = function(paths) { exports.unset = function (paths) {
return load().then(function(config) { return load().then(function (config) {
const l33tConfig = l33t(config) const l33tConfig = l33t(config)
;[].concat(paths).forEach(function(path) { ;[].concat(paths).forEach(function (path) {
l33tConfig.purge(path, true) l33tConfig.purge(path, true)
}) })
return save(config) return save(config)

View File

@ -71,7 +71,7 @@ function extractFlags(args) {
const PARAM_RE = /^([^=]+)=([^]*)$/ const PARAM_RE = /^([^=]+)=([^]*)$/
function parseParameters(args) { function parseParameters(args) {
const params = {} const params = {}
forEach(args, function(arg) { forEach(args, function (arg) {
let matches let matches
if (!(matches = arg.match(PARAM_RE))) { if (!(matches = arg.match(PARAM_RE))) {
throw new Error('invalid arg: ' + arg) throw new Error('invalid arg: ' + arg)
@ -132,7 +132,7 @@ function wrap(val) {
// =================================================================== // ===================================================================
const help = wrap( const help = wrap(
(function(pkg) { (function (pkg) {
return require('strip-indent')( return require('strip-indent')(
` `
Usage: Usage:
@ -166,7 +166,7 @@ const help = wrap(
$name v$version $name v$version
` `
).replace(/<([^>]+)>|\$(\w+)/g, function(_, arg, key) { ).replace(/<([^>]+)>|\$(\w+)/g, function (_, arg, key) {
if (arg) { if (arg) {
return '<' + chalk.yellow(arg) + '>' return '<' + chalk.yellow(arg) + '>'
} }
@ -187,7 +187,7 @@ function main(args) {
return help() return help()
} }
const fnName = args[0].replace(/^--|-\w/g, function(match) { const fnName = args[0].replace(/^--|-\w/g, function (match) {
if (match === '--') { if (match === '--') {
return '' return ''
} }
@ -227,7 +227,7 @@ async function register(args) {
const [ const [
url, url,
email, email,
password = await new Promise(function(resolve) { password = await new Promise(function (resolve) {
process.stdout.write('Password: ') process.stdout.write('Password: ')
pw(resolve) pw(resolve)
}), }),
@ -256,7 +256,7 @@ async function listCommands(args) {
let json = false let json = false
const patterns = [] const patterns = []
forEach(args, function(arg) { forEach(args, function (arg) {
if (arg === '--json') { if (arg === '--json') {
json = true json = true
} else { } else {
@ -273,7 +273,7 @@ async function listCommands(args) {
} }
methods = pairs(methods) methods = pairs(methods)
methods.sort(function(a, b) { methods.sort(function (a, b) {
a = a[0] a = a[0]
b = b[0] b = b[0]
if (a < b) { if (a < b) {
@ -283,11 +283,11 @@ async function listCommands(args) {
}) })
const str = [] const str = []
forEach(methods, function(method) { forEach(methods, function (method) {
const name = method[0] const name = method[0]
const info = method[1] const info = method[1]
str.push(chalk.bold.blue(name)) str.push(chalk.bold.blue(name))
forEach(info.params || [], function(info, name) { forEach(info.params || [], function (info, name) {
str.push(' ') str.push(' ')
if (info.optional) { if (info.optional) {
str.push('[') str.push('[')
@ -321,7 +321,7 @@ exports.listCommands = listCommands
async function listObjects(args) { async function listObjects(args) {
const properties = getKeys(extractFlags(args)) const properties = getKeys(extractFlags(args))
const filterProperties = properties.length const filterProperties = properties.length
? function(object) { ? function (object) {
return pick(object, properties) return pick(object, properties)
} }
: identity : identity

View File

@ -132,7 +132,7 @@ var bar = col.get('bar', 6.28)
var _ = require('lodash') var _ = require('lodash')
// Prints all the items. // Prints all the items.
_.forEach(col.all, function(value, key) { _.forEach(col.all, function (value, key) {
console.log('- %s: %j', key, value) console.log('- %s: %j', key, value)
}) })

View File

@ -114,7 +114,7 @@ var bar = col.get('bar', 6.28)
var _ = require('lodash') var _ = require('lodash')
// Prints all the items. // Prints all the items.
_.forEach(col.all, function(value, key) { _.forEach(col.all, function (value, key) {
console.log('- %s: %j', key, value) console.log('- %s: %j', key, value)
}) })

View File

@ -10,7 +10,7 @@ import Collection, { DuplicateItem, NoSuchItem } from './collection'
function waitTicks(n = 2) { function waitTicks(n = 2) {
const { nextTick } = process const { nextTick } = process
return new Promise(function(resolve) { return new Promise(function (resolve) {
;(function waitNextTick() { ;(function waitNextTick() {
// The first tick is handled by Promise#then() // The first tick is handled by Promise#then()
if (--n) { if (--n) {
@ -22,24 +22,24 @@ function waitTicks(n = 2) {
}) })
} }
describe('Collection', function() { describe('Collection', function () {
let col let col
beforeEach(function() { beforeEach(function () {
col = new Collection() col = new Collection()
col.add('bar', 0) col.add('bar', 0)
return waitTicks() return waitTicks()
}) })
it('is iterable', function() { it('is iterable', function () {
const iterator = col[Symbol.iterator]() const iterator = col[Symbol.iterator]()
expect(iterator.next()).toEqual({ done: false, value: ['bar', 0] }) expect(iterator.next()).toEqual({ done: false, value: ['bar', 0] })
expect(iterator.next()).toEqual({ done: true, value: undefined }) expect(iterator.next()).toEqual({ done: true, value: undefined })
}) })
describe('#keys()', function() { describe('#keys()', function () {
it('returns an iterator over the keys', function() { it('returns an iterator over the keys', function () {
const iterator = col.keys() const iterator = col.keys()
expect(iterator.next()).toEqual({ done: false, value: 'bar' }) expect(iterator.next()).toEqual({ done: false, value: 'bar' })
@ -47,8 +47,8 @@ describe('Collection', function() {
}) })
}) })
describe('#values()', function() { describe('#values()', function () {
it('returns an iterator over the values', function() { it('returns an iterator over the values', function () {
const iterator = col.values() const iterator = col.values()
expect(iterator.next()).toEqual({ done: false, value: 0 }) expect(iterator.next()).toEqual({ done: false, value: 0 })
@ -56,8 +56,8 @@ describe('Collection', function() {
}) })
}) })
describe('#add()', function() { describe('#add()', function () {
it('adds item to the collection', function() { it('adds item to the collection', function () {
const spy = jest.fn() const spy = jest.fn()
col.on('add', spy) col.on('add', spy)
@ -69,17 +69,17 @@ describe('Collection', function() {
expect(spy).not.toHaveBeenCalled() expect(spy).not.toHaveBeenCalled()
// Async event. // Async event.
return eventToPromise(col, 'add').then(function(added) { return eventToPromise(col, 'add').then(function (added) {
expect(Object.keys(added)).toEqual(['foo']) expect(Object.keys(added)).toEqual(['foo'])
expect(added.foo).toBe(true) expect(added.foo).toBe(true)
}) })
}) })
it('throws an exception if the item already exists', function() { it('throws an exception if the item already exists', function () {
expect(() => col.add('bar', true)).toThrowError(DuplicateItem) expect(() => col.add('bar', true)).toThrowError(DuplicateItem)
}) })
it('accepts an object with an id property', function() { it('accepts an object with an id property', function () {
const foo = { id: 'foo' } const foo = { id: 'foo' }
col.add(foo) col.add(foo)
@ -88,8 +88,8 @@ describe('Collection', function() {
}) })
}) })
describe('#update()', function() { describe('#update()', function () {
it('updates an item of the collection', function() { it('updates an item of the collection', function () {
const spy = jest.fn() const spy = jest.fn()
col.on('update', spy) col.on('update', spy)
@ -102,17 +102,17 @@ describe('Collection', function() {
expect(spy).not.toHaveBeenCalled() expect(spy).not.toHaveBeenCalled()
// Async event. // Async event.
return eventToPromise(col, 'update').then(function(updated) { return eventToPromise(col, 'update').then(function (updated) {
expect(Object.keys(updated)).toEqual(['bar']) expect(Object.keys(updated)).toEqual(['bar'])
expect(updated.bar).toBe(2) expect(updated.bar).toBe(2)
}) })
}) })
it('throws an exception if the item does not exist', function() { it('throws an exception if the item does not exist', function () {
expect(() => col.update('baz', true)).toThrowError(NoSuchItem) expect(() => col.update('baz', true)).toThrowError(NoSuchItem)
}) })
it('accepts an object with an id property', function() { it('accepts an object with an id property', function () {
const bar = { id: 'bar' } const bar = { id: 'bar' }
col.update(bar) col.update(bar)
@ -121,8 +121,8 @@ describe('Collection', function() {
}) })
}) })
describe('#remove()', function() { describe('#remove()', function () {
it('removes an item of the collection', function() { it('removes an item of the collection', function () {
const spy = jest.fn() const spy = jest.fn()
col.on('remove', spy) col.on('remove', spy)
@ -134,17 +134,17 @@ describe('Collection', function() {
expect(spy).not.toHaveBeenCalled() expect(spy).not.toHaveBeenCalled()
// Async event. // Async event.
return eventToPromise(col, 'remove').then(function(removed) { return eventToPromise(col, 'remove').then(function (removed) {
expect(Object.keys(removed)).toEqual(['bar']) expect(Object.keys(removed)).toEqual(['bar'])
expect(removed.bar).toBeUndefined() expect(removed.bar).toBeUndefined()
}) })
}) })
it('throws an exception if the item does not exist', function() { it('throws an exception if the item does not exist', function () {
expect(() => col.remove('baz', true)).toThrowError(NoSuchItem) expect(() => col.remove('baz', true)).toThrowError(NoSuchItem)
}) })
it('accepts an object with an id property', function() { it('accepts an object with an id property', function () {
const bar = { id: 'bar' } const bar = { id: 'bar' }
col.remove(bar) col.remove(bar)
@ -153,8 +153,8 @@ describe('Collection', function() {
}) })
}) })
describe('#set()', function() { describe('#set()', function () {
it('adds item if collection has not key', function() { it('adds item if collection has not key', function () {
const spy = jest.fn() const spy = jest.fn()
col.on('add', spy) col.on('add', spy)
@ -166,13 +166,13 @@ describe('Collection', function() {
expect(spy).not.toHaveBeenCalled() expect(spy).not.toHaveBeenCalled()
// Async events. // Async events.
return eventToPromise(col, 'add').then(function(added) { return eventToPromise(col, 'add').then(function (added) {
expect(Object.keys(added)).toEqual(['foo']) expect(Object.keys(added)).toEqual(['foo'])
expect(added.foo).toBe(true) expect(added.foo).toBe(true)
}) })
}) })
it('updates item if collection has key', function() { it('updates item if collection has key', function () {
const spy = jest.fn() const spy = jest.fn()
col.on('udpate', spy) col.on('udpate', spy)
@ -184,13 +184,13 @@ describe('Collection', function() {
expect(spy).not.toHaveBeenCalled() expect(spy).not.toHaveBeenCalled()
// Async events. // Async events.
return eventToPromise(col, 'update').then(function(updated) { return eventToPromise(col, 'update').then(function (updated) {
expect(Object.keys(updated)).toEqual(['bar']) expect(Object.keys(updated)).toEqual(['bar'])
expect(updated.bar).toBe(1) expect(updated.bar).toBe(1)
}) })
}) })
it('accepts an object with an id property', function() { it('accepts an object with an id property', function () {
const foo = { id: 'foo' } const foo = { id: 'foo' }
col.set(foo) col.set(foo)
@ -199,36 +199,36 @@ describe('Collection', function() {
}) })
}) })
describe('#unset()', function() { describe('#unset()', function () {
it('removes an existing item', function() { it('removes an existing item', function () {
col.unset('bar') col.unset('bar')
expect(col.has('bar')).toBe(false) expect(col.has('bar')).toBe(false)
return eventToPromise(col, 'remove').then(function(removed) { return eventToPromise(col, 'remove').then(function (removed) {
expect(Object.keys(removed)).toEqual(['bar']) expect(Object.keys(removed)).toEqual(['bar'])
expect(removed.bar).toBeUndefined() expect(removed.bar).toBeUndefined()
}) })
}) })
it('does not throw if the item does not exists', function() { it('does not throw if the item does not exists', function () {
col.unset('foo') col.unset('foo')
}) })
it('accepts an object with an id property', function() { it('accepts an object with an id property', function () {
col.unset({ id: 'bar' }) col.unset({ id: 'bar' })
expect(col.has('bar')).toBe(false) expect(col.has('bar')).toBe(false)
return eventToPromise(col, 'remove').then(function(removed) { return eventToPromise(col, 'remove').then(function (removed) {
expect(Object.keys(removed)).toEqual(['bar']) expect(Object.keys(removed)).toEqual(['bar'])
expect(removed.bar).toBeUndefined() expect(removed.bar).toBeUndefined()
}) })
}) })
}) })
describe('touch()', function() { describe('touch()', function () {
it('can be used to signal an indirect update', function() { it('can be used to signal an indirect update', function () {
const foo = { id: 'foo' } const foo = { id: 'foo' }
col.add(foo) col.add(foo)
@ -243,8 +243,8 @@ describe('Collection', function() {
}) })
}) })
describe('clear()', function() { describe('clear()', function () {
it('removes all items from the collection', function() { it('removes all items from the collection', function () {
col.clear() col.clear()
expect(col.size).toBe(0) expect(col.size).toBe(0)
@ -256,7 +256,7 @@ describe('Collection', function() {
}) })
}) })
describe('deduplicates events', function() { describe('deduplicates events', function () {
forEach( forEach(
{ {
'add & update → add': [ 'add & update → add': [
@ -316,7 +316,7 @@ describe('Collection', function() {
], ],
}, },
([operations, results], label) => { ([operations, results], label) => {
it(label, function() { it(label, function () {
forEach(operations, ([method, ...args]) => { forEach(operations, ([method, ...args]) => {
col[method](...args) col[method](...args)
}) })

View File

@ -25,7 +25,7 @@ const waitTicks = (n = 2) => {
// =================================================================== // ===================================================================
describe('Index', function() { describe('Index', function () {
let col, byGroup let col, byGroup
const item1 = { const item1 = {
id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba', id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba',
@ -43,7 +43,7 @@ describe('Index', function() {
id: 'd90b7335-e540-4a44-ad22-c4baae9cd0a9', id: 'd90b7335-e540-4a44-ad22-c4baae9cd0a9',
} }
beforeEach(function() { beforeEach(function () {
col = new Collection() col = new Collection()
forEach([item1, item2, item3, item4], item => { forEach([item1, item2, item3, item4], item => {
col.add(item) col.add(item)
@ -56,7 +56,7 @@ describe('Index', function() {
return waitTicks() return waitTicks()
}) })
it('works with existing items', function() { it('works with existing items', function () {
expect(col.indexes).toEqual({ expect(col.indexes).toEqual({
byGroup: { byGroup: {
foo: { foo: {
@ -70,7 +70,7 @@ describe('Index', function() {
}) })
}) })
it('works with added items', function() { it('works with added items', function () {
const item5 = { const item5 = {
id: '823b56c4-4b96-4f3a-9533-5d08177167ac', id: '823b56c4-4b96-4f3a-9533-5d08177167ac',
group: 'baz', group: 'baz',
@ -96,7 +96,7 @@ describe('Index', function() {
}) })
}) })
it('works with updated items', function() { it('works with updated items', function () {
const item1bis = { const item1bis = {
id: item1.id, id: item1.id,
group: 'bar', group: 'bar',
@ -119,7 +119,7 @@ describe('Index', function() {
}) })
}) })
it('works with removed items', function() { it('works with removed items', function () {
col.remove(item2) col.remove(item2)
return waitTicks().then(() => { return waitTicks().then(() => {
@ -135,7 +135,7 @@ describe('Index', function() {
}) })
}) })
it('correctly updates the value even the same object has the same hash', function() { it('correctly updates the value even the same object has the same hash', function () {
const item1bis = { const item1bis = {
id: item1.id, id: item1.id,
group: item1.group, group: item1.group,
@ -159,8 +159,8 @@ describe('Index', function() {
}) })
}) })
describe('#sweep()', function() { describe('#sweep()', function () {
it('removes empty items lists', function() { it('removes empty items lists', function () {
col.remove(item2) col.remove(item2)
return waitTicks().then(() => { return waitTicks().then(() => {

View File

@ -25,7 +25,7 @@ const waitTicks = (n = 2) => {
// =================================================================== // ===================================================================
describe('UniqueIndex', function() { describe('UniqueIndex', function () {
let col, byKey let col, byKey
const item1 = { const item1 = {
id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba', id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba',
@ -39,7 +39,7 @@ describe('UniqueIndex', function() {
id: '668c1274-4442-44a6-b99a-512188e0bb09', id: '668c1274-4442-44a6-b99a-512188e0bb09',
} }
beforeEach(function() { beforeEach(function () {
col = new Collection() col = new Collection()
forEach([item1, item2, item3], item => { forEach([item1, item2, item3], item => {
col.add(item) col.add(item)
@ -52,7 +52,7 @@ describe('UniqueIndex', function() {
return waitTicks() return waitTicks()
}) })
it('works with existing items', function() { it('works with existing items', function () {
expect(col.indexes).toEqual({ expect(col.indexes).toEqual({
byKey: { byKey: {
[item1.key]: item1, [item1.key]: item1,
@ -61,7 +61,7 @@ describe('UniqueIndex', function() {
}) })
}) })
it('works with added items', function() { it('works with added items', function () {
const item4 = { const item4 = {
id: '823b56c4-4b96-4f3a-9533-5d08177167ac', id: '823b56c4-4b96-4f3a-9533-5d08177167ac',
key: '1437af14-429a-40db-8a51-8a2f5ed03201', key: '1437af14-429a-40db-8a51-8a2f5ed03201',
@ -80,7 +80,7 @@ describe('UniqueIndex', function() {
}) })
}) })
it('works with updated items', function() { it('works with updated items', function () {
const item1bis = { const item1bis = {
id: item1.id, id: item1.id,
key: 'e03d4a3a-0331-4aca-97a2-016bbd43a29b', key: 'e03d4a3a-0331-4aca-97a2-016bbd43a29b',
@ -98,7 +98,7 @@ describe('UniqueIndex', function() {
}) })
}) })
it('works with removed items', function() { it('works with removed items', function () {
col.remove(item2) col.remove(item2)
return waitTicks().then(() => { return waitTicks().then(() => {
@ -110,7 +110,7 @@ describe('UniqueIndex', function() {
}) })
}) })
it('correctly updates the value even the same object has the same hash', function() { it('correctly updates the value even the same object has the same hash', function () {
const item1bis = { const item1bis = {
id: item1.id, id: item1.id,
key: item1.key, key: item1.key,

View File

@ -43,7 +43,7 @@ activeUsers.on('remove', users => {
}) })
// Make some changes in the future. // Make some changes in the future.
setTimeout(function() { setTimeout(function () {
console.log('-----') console.log('-----')
users.set({ users.set({

View File

@ -118,7 +118,7 @@ xo.on('closed', () => {
``` ```
```javascript ```javascript
xo.on('notification', function(notif) { xo.on('notification', function (notif) {
console.log('notification:', notif.method, notif.params) console.log('notification:', notif.method, notif.params)
}) })
``` ```

View File

@ -100,7 +100,7 @@ xo.on('closed', () => {
``` ```
```javascript ```javascript
xo.on('notification', function(notif) { xo.on('notification', function (notif) {
console.log('notification:', notif.method, notif.params) console.log('notification:', notif.method, notif.params)
}) })
``` ```

View File

@ -1,6 +1,6 @@
'use strict' 'use strict'
process.on('unhandledRejection', function(error) { process.on('unhandledRejection', function (error) {
console.log(error) console.log(error)
}) })
@ -11,51 +11,51 @@ const xo = new Xo({
}) })
xo.open() xo.open()
.then(function() { .then(function () {
return xo return xo
.call('acl.get', {}) .call('acl.get', {})
.then(function(result) { .then(function (result) {
console.log('success:', result) console.log('success:', result)
}) })
.catch(function(error) { .catch(function (error) {
console.log('failure:', error) console.log('failure:', error)
}) })
}) })
.then(function() { .then(function () {
return xo return xo
.signIn({ .signIn({
email: 'admin@admin.net', email: 'admin@admin.net',
password: 'admin', password: 'admin',
}) })
.then(function() { .then(function () {
console.log('connected as ', xo.user) console.log('connected as ', xo.user)
}) })
.catch(function(error) { .catch(function (error) {
console.log('failure:', error) console.log('failure:', error)
}) })
}) })
.then(function() { .then(function () {
return xo return xo
.signIn({ .signIn({
email: 'tom', email: 'tom',
password: 'tom', password: 'tom',
}) })
.then(function() { .then(function () {
console.log('connected as', xo.user) console.log('connected as', xo.user)
return xo return xo
.call('acl.get', {}) .call('acl.get', {})
.then(function(result) { .then(function (result) {
console.log('success:', result) console.log('success:', result)
}) })
.catch(function(error) { .catch(function (error) {
console.log('failure:', error) console.log('failure:', error)
}) })
}) })
.catch(function(error) { .catch(function (error) {
console.log('failure', error) console.log('failure', error)
}) })
}) })
.then(function() { .then(function () {
return xo.close() return xo.close()
}) })

View File

@ -266,7 +266,7 @@ class AuditXoPlugin {
} }
AuditXoPlugin.prototype._getRecordsStream = asyncIteratorToStream( AuditXoPlugin.prototype._getRecordsStream = asyncIteratorToStream(
async function*(id) { async function* (id) {
for await (const record of this._auditCore.getFrom(id)) { for await (const record of this._auditCore.getFrom(id)) {
yield JSON.stringify(record) yield JSON.stringify(record)
yield '\n' yield '\n'

View File

@ -69,10 +69,7 @@ const STATUS_ICON = {
const DATE_FORMAT = 'dddd, MMMM Do YYYY, h:mm:ss a' const DATE_FORMAT = 'dddd, MMMM Do YYYY, h:mm:ss a'
const createDateFormatter = timezone => const createDateFormatter = timezone =>
timezone !== undefined timezone !== undefined
? timestamp => ? timestamp => moment(timestamp).tz(timezone).format(DATE_FORMAT)
moment(timestamp)
.tz(timezone)
.format(DATE_FORMAT)
: timestamp => moment(timestamp).format(DATE_FORMAT) : timestamp => moment(timestamp).format(DATE_FORMAT)
const formatDuration = milliseconds => moment.duration(milliseconds).humanize() const formatDuration = milliseconds => moment.duration(milliseconds).humanize()

View File

@ -704,7 +704,7 @@ ${entry.listItem}
} }
} }
exports.default = function({ xo }) { exports.default = function ({ xo }) {
return new PerfAlertXoPlugin(xo) return new PerfAlertXoPlugin(xo)
} }

View File

@ -33,7 +33,7 @@ exports.testSchema = {
// //
// Its only parameter is an object which currently only contains a // Its only parameter is an object which currently only contains a
// `xo` property: the instance of the currently running xo-server. // `xo` property: the instance of the currently running xo-server.
exports.default = function(opts) { exports.default = function (opts) {
// For simplicity's sake, this plugin returns a plain object, but // For simplicity's sake, this plugin returns a plain object, but
// usually it returns a new instance of an existing class. // usually it returns a new instance of an existing class.
return { return {
@ -42,7 +42,7 @@ exports.default = function(opts) {
// //
// Note: before being called, the configuration is validated // Note: before being called, the configuration is validated
// against the provided configuration schema. // against the provided configuration schema.
configure: function(configuration, state) { configure: function (configuration, state) {
console.log('stub configured', configuration) console.log('stub configured', configuration)
console.log('sub is currently', state.loaded ? 'loaded' : 'unloaded') console.log('sub is currently', state.loaded ? 'loaded' : 'unloaded')
}, },
@ -54,14 +54,14 @@ exports.default = function(opts) {
// //
// Note 2: if the plugin is configurable, will only be called if // Note 2: if the plugin is configurable, will only be called if
// the plugin has been successfully configured. // the plugin has been successfully configured.
load: function() { load: function () {
console.log('stub loaded') console.log('stub loaded')
}, },
// This (optional) method is called to unload the plugin. // This (optional) method is called to unload the plugin.
// //
// Note: will only be called if the plugin is currently loaded. // Note: will only be called if the plugin is currently loaded.
unload: function() { unload: function () {
console.log('stub unloaded') console.log('stub unloaded')
}, },
@ -70,7 +70,7 @@ exports.default = function(opts) {
// Note 2: before being called, the test configuration is validated // Note 2: before being called, the test configuration is validated
// against the provided test data. // against the provided test data.
// Note 3: will only be called if the test option is activated. // Note 3: will only be called if the test option is activated.
test: function(data) { test: function (data) {
console.log('the configuration is about to be tested') console.log('the configuration is about to be tested')
// TODO: test the configuration, i.e, use the main feature of the plugin and throws any errors. // TODO: test the configuration, i.e, use the main feature of the plugin and throws any errors.
}, },

View File

@ -1,6 +1,3 @@
const randomId = () => const randomId = () => Math.random().toString(36).slice(2)
Math.random()
.toString(36)
.slice(2)
export { randomId as default } export { randomId as default }

View File

@ -77,7 +77,7 @@ describe('group', () => {
() => { () => {
throw new Error('createGroup() should have thrown') throw new Error('createGroup() should have thrown')
}, },
function(error) { function (error) {
expect(error.message).to.match(/duplicate group/i) expect(error.message).to.match(/duplicate group/i)
} }
) )

View File

@ -231,7 +231,7 @@ describe('host', () => {
}) })
expect(stats).to.be.an.object() expect(stats).to.be.an.object()
forEach(stats, function(array, key) { forEach(stats, function (array, key) {
expect(array).to.be.an.array() expect(array).to.be.an.array()
}) })
}) })

View File

@ -139,7 +139,7 @@ describe('schedule', () => {
() => { () => {
throw new Error('getSchedule() should have thrown') throw new Error('getSchedule() should have thrown')
}, },
function(error) { function (error) {
expect(error.message).to.match(/no such object/) expect(error.message).to.match(/no such object/)
} }
) )

View File

@ -108,7 +108,7 @@ describe('vbd', () => {
() => { () => {
throw new Error('vbd.delete() should have thrown') throw new Error('vbd.delete() should have thrown')
}, },
function(error) { function (error) {
// TODO: check with Julien if it is ok // TODO: check with Julien if it is ok
expect(error.message).to.match('unknown error from the peer') expect(error.message).to.match('unknown error from the peer')
} }

View File

@ -95,7 +95,7 @@ describe('vif', () => {
() => { () => {
throw new Error('vif.delete() should have thrown') throw new Error('vif.delete() should have thrown')
}, },
function(error) { function (error) {
expect(error.message).to.be.equal('unknown error from the peer') expect(error.message).to.be.equal('unknown error from the peer')
} }
) )

View File

@ -629,7 +629,7 @@ describe('vm', () => {
() => { () => {
throw new Error('createInterface() sould have trown') throw new Error('createInterface() sould have trown')
}, },
function(error) { function (error) {
expect(error.message).to.be.equal('unknown error from the peer') expect(error.message).to.be.equal('unknown error from the peer')
} }
) )

View File

@ -110,7 +110,7 @@ const normaliseValue = value => (isFinite(value) ? round(value, 2) : '-')
// =================================================================== // ===================================================================
Handlebars.registerHelper('compare', function( Handlebars.registerHelper('compare', function (
lvalue, lvalue,
operator, operator,
rvalue, rvalue,
@ -131,7 +131,7 @@ Handlebars.registerHelper('compare', function(
: options.inverse(this) : options.inverse(this)
}) })
Handlebars.registerHelper('math', function(lvalue, operator, rvalue, options) { Handlebars.registerHelper('math', function (lvalue, operator, rvalue, options) {
if (arguments.length < 3) { if (arguments.length < 3) {
throw new Error('Handlebars Helper "math" needs 2 parameters') throw new Error('Handlebars Helper "math" needs 2 parameters')
} }

View File

@ -12,7 +12,7 @@ function* values(object) {
* *
* @param {(Array|Object)} collection * @param {(Array|Object)} collection
*/ */
module.exports = asyncIteratorToStream(function*(collection) { module.exports = asyncIteratorToStream(function* (collection) {
for (const value of Array.isArray(collection) for (const value of Array.isArray(collection)
? collection ? collection
: values(collection)) { : values(collection)) {

View File

@ -11,7 +11,7 @@ function State() {
export const dedupeUnmount = (fn, keyFn) => { export const dedupeUnmount = (fn, keyFn) => {
const states = new MultiKeyMap() const states = new MultiKeyMap()
return function() { return function () {
const keys = ensureArray(keyFn.apply(this, arguments)) const keys = ensureArray(keyFn.apply(this, arguments))
let state = states.get(keys) let state = states.get(keys)
if (state === undefined) { if (state === undefined) {

View File

@ -2,18 +2,18 @@
import ensureArray from './_ensureArray' import ensureArray from './_ensureArray'
describe('ensureArray()', function() { describe('ensureArray()', function () {
it('wrap the value in an array', function() { it('wrap the value in an array', function () {
const value = 'foo' const value = 'foo'
expect(ensureArray(value)).toEqual([value]) expect(ensureArray(value)).toEqual([value])
}) })
it('returns an empty array for undefined', function() { it('returns an empty array for undefined', function () {
expect(ensureArray(undefined)).toEqual([]) expect(ensureArray(undefined)).toEqual([])
}) })
it('returns the object itself if is already an array', function() { it('returns the object itself if is already an array', function () {
const array = ['foo', 'bar', 'baz'] const array = ['foo', 'bar', 'baz']
expect(ensureArray(array)).toBe(array) expect(ensureArray(array)).toBe(array)

View File

@ -30,7 +30,7 @@ export const REMOVE_CACHE_ENTRY = {}
export const debounceWithKey = (fn, delay, keyFn = defaultKeyFn) => { export const debounceWithKey = (fn, delay, keyFn = defaultKeyFn) => {
const cache = new MultiKeyMap() const cache = new MultiKeyMap()
const delayFn = typeof delay === 'number' ? () => delay : delay const delayFn = typeof delay === 'number' ? () => delay : delay
return function(arg) { return function (arg) {
if (arg === REMOVE_CACHE_ENTRY) { if (arg === REMOVE_CACHE_ENTRY) {
return removeCacheEntry( return removeCacheEntry(
cache, cache,

View File

@ -6,7 +6,7 @@ describe('REMOVE_CACHE_ENTRY', () => {
it('clears the cache', async () => { it('clears the cache', async () => {
let i = 0 let i = 0
const debouncedFn = debounceWithKey( const debouncedFn = debounceWithKey(
function() { function () {
return Promise.resolve(++i) return Promise.resolve(++i)
}, },
Infinity, Infinity,

View File

@ -12,7 +12,7 @@ const log = createLogger('xo:disk')
// =================================================================== // ===================================================================
export const create = defer(async function( export const create = defer(async function (
$defer, $defer,
{ name, size, sr, vm, bootable, position, mode } { name, size, sr, vm, bootable, position, mode }
) { ) {

View File

@ -36,7 +36,7 @@ export { delete_ as delete }
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// FIXME: human readable strings should be handled. // FIXME: human readable strings should be handled.
export const set = defer(async function($defer, params) { export const set = defer(async function ($defer, params) {
const { vdi } = params const { vdi } = params
const xapi = this.getXapi(vdi) const xapi = this.getXapi(vdi)
const ref = vdi._xapiRef const ref = vdi._xapiRef

View File

@ -49,7 +49,7 @@ const extract = (obj, prop) => {
} }
// TODO: Implement ACLs // TODO: Implement ACLs
export const create = defer(async function($defer, params) { export const create = defer(async function ($defer, params) {
const { user } = this const { user } = this
const resourceSet = extract(params, 'resourceSet') const resourceSet = extract(params, 'resourceSet')
const template = extract(params, 'template') const template = extract(params, 'template')
@ -345,7 +345,7 @@ create.resolve = {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
const delete_ = defer(async function( const delete_ = defer(async function (
$defer, $defer,
{ {
delete_disks, // eslint-disable-line camelcase delete_disks, // eslint-disable-line camelcase
@ -553,7 +553,7 @@ migrate.resolve = {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
export const set = defer(async function($defer, params) { export const set = defer(async function ($defer, params) {
const VM = extract(params, 'VM') const VM = extract(params, 'VM')
const xapi = this.getXapi(VM) const xapi = this.getXapi(VM)
const vmId = VM._xapiId const vmId = VM._xapiId
@ -691,7 +691,7 @@ restart.resolve = {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
export const clone = defer(async function( export const clone = defer(async function (
$defer, $defer,
{ vm, name, full_copy: fullCopy } { vm, name, full_copy: fullCopy }
) { ) {
@ -794,7 +794,7 @@ export { convertToTemplate as convert }
// ------------------------------------------------------------------- // -------------------------------------------------------------------
export const snapshot = defer(async function( export const snapshot = defer(async function (
$defer, $defer,
{ {
vm, vm,
@ -1197,7 +1197,7 @@ resume.resolve = {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
export const revert = defer(async function($defer, { snapshot }) { export const revert = defer(async function ($defer, { snapshot }) {
await this.checkPermissions(this.user.id, [ await this.checkPermissions(this.user.id, [
[snapshot.$snapshot_of, 'operate'], [snapshot.$snapshot_of, 'operate'],
]) ])

View File

@ -114,7 +114,7 @@ function createVolumeInfoTypes() {
} }
const sshInfoType = (command, handler) => { const sshInfoType = (command, handler) => {
return async function(sr) { return async function (sr) {
const glusterEndpoint = this::_getGlusterEndpoint(sr) const glusterEndpoint = this::_getGlusterEndpoint(sr)
const cmdShouldRetry = result => const cmdShouldRetry = result =>
!result.commandStatus && !result.commandStatus &&
@ -412,7 +412,7 @@ async function glusterCmd(glusterEndpoint, cmd, ignoreError = false) {
return result return result
} }
const createNetworkAndInsertHosts = defer(async function( const createNetworkAndInsertHosts = defer(async function (
$defer, $defer,
xapi, xapi,
pif, pif,
@ -483,7 +483,7 @@ async function getOrCreateSshKey(xapi) {
return sshKey return sshKey
} }
const _probePoolAndWaitForPresence = defer(async function( const _probePoolAndWaitForPresence = defer(async function (
$defer, $defer,
glusterEndpoint, glusterEndpoint,
addresses addresses
@ -618,7 +618,7 @@ async function _removeQuota(glusterEndpoint) {
await glusterCmd(glusterEndpoint, 'volume quota xosan disable', true) await glusterCmd(glusterEndpoint, 'volume quota xosan disable', true)
} }
export const createSR = defer(async function( export const createSR = defer(async function (
$defer, $defer,
{ {
template, template,
@ -669,11 +669,7 @@ export const createSR = defer(async function(
$defer.onFailure(() => this.unbindXosanLicense({ srId: tmpBoundObjectId })) $defer.onFailure(() => this.unbindXosanLicense({ srId: tmpBoundObjectId }))
// '172.31.100.0' -> '172.31.100.' // '172.31.100.0' -> '172.31.100.'
const networkPrefix = const networkPrefix = ipRange.split('.').slice(0, 3).join('.') + '.'
ipRange
.split('.')
.slice(0, 3)
.join('.') + '.'
let vmIpLastNumber = VM_FIRST_NUMBER let vmIpLastNumber = VM_FIRST_NUMBER
try { try {
@ -1199,7 +1195,7 @@ const _median = arr => {
return arr[Math.floor(arr.length / 2)] return arr[Math.floor(arr.length / 2)]
} }
const insertNewGlusterVm = defer(async function( const insertNewGlusterVm = defer(async function (
$defer, $defer,
xapi, xapi,
xosansr, xosansr,
@ -1249,7 +1245,7 @@ const insertNewGlusterVm = defer(async function(
return { data, newVM, addressAndHost, glusterEndpoint } return { data, newVM, addressAndHost, glusterEndpoint }
}) })
export const addBricks = defer(async function( export const addBricks = defer(async function (
$defer, $defer,
{ xosansr, lvmsrs, brickSize } { xosansr, lvmsrs, brickSize }
) { ) {
@ -1345,7 +1341,7 @@ addBricks.resolve = {
lvmsrs: ['sr', 'SR', 'administrate'], lvmsrs: ['sr', 'SR', 'administrate'],
} }
export const removeBricks = defer(async function($defer, { xosansr, bricks }) { export const removeBricks = defer(async function ($defer, { xosansr, bricks }) {
await this.checkXosanLicense({ srId: xosansr.uuid }) await this.checkXosanLicense({ srId: xosansr.uuid })
const xapi = this.getXapi(xosansr) const xapi = this.getXapi(xosansr)

View File

@ -6,7 +6,7 @@ module.exports = function globMatcher(patterns, opts) {
if (!Array.isArray(patterns)) { if (!Array.isArray(patterns)) {
if (patterns[0] === '!') { if (patterns[0] === '!') {
const m = matcher(patterns.slice(1), opts) const m = matcher(patterns.slice(1), opts)
return function(string) { return function (string) {
return !m(string) return !m(string)
} }
} else { } else {
@ -30,7 +30,7 @@ module.exports = function globMatcher(patterns, opts) {
const nNone = noneMustMatch.length const nNone = noneMustMatch.length
const nAny = anyMustMatch.length const nAny = anyMustMatch.length
return function(string) { return function (string) {
let i let i
for (i = 0; i < nNone; ++i) { for (i = 0; i < nNone; ++i) {

View File

@ -4,7 +4,7 @@ import { forEach } from 'lodash'
import { thunkToArray } from './utils' import { thunkToArray } from './utils'
import { crossProduct, mergeObjects } from './math' import { crossProduct, mergeObjects } from './math'
describe('mergeObjects', function() { describe('mergeObjects', function () {
forEach( forEach(
{ {
'Two sets of one': [{ a: 1, b: 2 }, { a: 1 }, { b: 2 }], 'Two sets of one': [{ a: 1, b: 2 }, { a: 1 }, { b: 2 }],
@ -29,7 +29,7 @@ describe('mergeObjects', function() {
}, },
([resultSet, ...sets], name) => { ([resultSet, ...sets], name) => {
describe(`with ${name}`, () => { describe(`with ${name}`, () => {
it('Assembles all given param sets in on set', function() { it('Assembles all given param sets in on set', function () {
expect(mergeObjects(sets)).toEqual(resultSet) expect(mergeObjects(sets)).toEqual(resultSet)
}) })
}) })
@ -37,7 +37,7 @@ describe('mergeObjects', function() {
) )
}) })
describe('crossProduct', function() { describe('crossProduct', function () {
// Gives the sum of all args // Gives the sum of all args
const addTest = args => args.reduce((prev, curr) => prev + curr, 0) const addTest = args => args.reduce((prev, curr) => prev + curr, 0)
// Gives the product of all args // Gives the product of all args
@ -98,7 +98,7 @@ describe('crossProduct', function() {
}, },
([product, items, cb], name) => { ([product, items, cb], name) => {
describe(`with ${name}`, () => { describe(`with ${name}`, () => {
it('Crosses sets of values with a crossProduct callback', function() { it('Crosses sets of values with a crossProduct callback', function () {
expect(thunkToArray(crossProduct(items, cb)).sort()).toEqual( expect(thunkToArray(crossProduct(items, cb)).sort()).toEqual(
product.sort() product.sort()
) )

View File

@ -57,7 +57,7 @@ export function extractProperty(obj, prop) {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// Returns the first defined (non-undefined) value. // Returns the first defined (non-undefined) value.
export const firstDefined = function() { export const firstDefined = function () {
const n = arguments.length const n = arguments.length
for (let i = 0; i < n; ++i) { for (let i = 0; i < n; ++i) {
const arg = arguments[i] const arg = arguments[i]
@ -107,7 +107,7 @@ export const generateToken = (randomBytes => {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
export const formatXml = (function() { export const formatXml = (function () {
const builder = new xml2js.Builder({ const builder = new xml2js.Builder({
headless: true, headless: true,
}) })
@ -115,7 +115,7 @@ export const formatXml = (function() {
return (...args) => builder.buildObject(...args) return (...args) => builder.buildObject(...args)
})() })()
export const parseXml = (function() { export const parseXml = (function () {
const opts = { const opts = {
mergeAttrs: true, mergeAttrs: true,
explicitArray: false, explicitArray: false,

View File

@ -12,18 +12,18 @@ import {
// =================================================================== // ===================================================================
describe('camelToSnakeCase()', function() { describe('camelToSnakeCase()', function () {
it('converts a string from camelCase to snake_case', function() { it('converts a string from camelCase to snake_case', function () {
expect(camelToSnakeCase('fooBar')).toBe('foo_bar') expect(camelToSnakeCase('fooBar')).toBe('foo_bar')
expect(camelToSnakeCase('ipv4Allowed')).toBe('ipv4_allowed') expect(camelToSnakeCase('ipv4Allowed')).toBe('ipv4_allowed')
}) })
it('does not alter snake_case strings', function() { it('does not alter snake_case strings', function () {
expect(camelToSnakeCase('foo_bar')).toBe('foo_bar') expect(camelToSnakeCase('foo_bar')).toBe('foo_bar')
expect(camelToSnakeCase('ipv4_allowed')).toBe('ipv4_allowed') expect(camelToSnakeCase('ipv4_allowed')).toBe('ipv4_allowed')
}) })
it('does not alter upper case letters expect those from the camelCase', function() { it('does not alter upper case letters expect those from the camelCase', function () {
expect(camelToSnakeCase('fooBar_BAZ')).toBe('foo_bar_BAZ') expect(camelToSnakeCase('fooBar_BAZ')).toBe('foo_bar_BAZ')
}) })
}) })
@ -41,15 +41,15 @@ describe('diffItems', () => {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
describe('extractProperty()', function() { describe('extractProperty()', function () {
it('returns the value of the property', function() { it('returns the value of the property', function () {
const value = {} const value = {}
const obj = { prop: value } const obj = { prop: value }
expect(extractProperty(obj, 'prop')).toBe(value) expect(extractProperty(obj, 'prop')).toBe(value)
}) })
it('removes the property from the object', function() { it('removes the property from the object', function () {
const value = {} const value = {}
const obj = { prop: value } const obj = { prop: value }
@ -60,8 +60,8 @@ describe('extractProperty()', function() {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
describe('formatXml()', function() { describe('formatXml()', function () {
it('formats a JS object to an XML string', function() { it('formats a JS object to an XML string', function () {
expect( expect(
formatXml({ formatXml({
foo: { foo: {
@ -85,22 +85,22 @@ describe('generateToken()', () => {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
describe('parseSize()', function() { describe('parseSize()', function () {
it('parses a human size', function() { it('parses a human size', function () {
expect(parseSize('1G')).toBe(1e9) expect(parseSize('1G')).toBe(1e9)
}) })
it('returns the parameter if already a number', function() { it('returns the parameter if already a number', function () {
expect(parseSize(1e6)).toBe(1e6) expect(parseSize(1e6)).toBe(1e6)
}) })
it('throws if the string cannot be parsed', function() { it('throws if the string cannot be parsed', function () {
expect(function() { expect(function () {
parseSize('foo') parseSize('foo')
}).toThrow() }).toThrow()
}) })
it('supports the B unit as suffix', function() { it('supports the B unit as suffix', function () {
expect(parseSize('3MB')).toBe(3e6) expect(parseSize('3MB')).toBe(3e6)
}) })
}) })

View File

@ -151,7 +151,7 @@ const TRANSFORMS = {
logging: obj.logging, logging: obj.logging,
name_description: obj.name_description, name_description: obj.name_description,
name_label: obj.name_label, name_label: obj.name_label,
memory: (function() { memory: (function () {
if (metrics) { if (metrics) {
const free = +metrics.memory_free const free = +metrics.memory_free
const total = +metrics.memory_total const total = +metrics.memory_total
@ -298,7 +298,7 @@ const TRANSFORMS = {
: +obj.VCPUs_at_startup, : +obj.VCPUs_at_startup,
}, },
current_operations: currentOperations, current_operations: currentOperations,
docker: (function() { docker: (function () {
const monitor = otherConfig['xscontainer-monitor'] const monitor = otherConfig['xscontainer-monitor']
if (!monitor) { if (!monitor) {
return return
@ -328,7 +328,7 @@ const TRANSFORMS = {
mainIpAddress: extractIpFromVmNetworks(guestMetrics?.networks), mainIpAddress: extractIpFromVmNetworks(guestMetrics?.networks),
high_availability: obj.ha_restart_priority, high_availability: obj.ha_restart_priority,
memory: (function() { memory: (function () {
const dynamicMin = +obj.memory_dynamic_min const dynamicMin = +obj.memory_dynamic_min
const dynamicMax = +obj.memory_dynamic_max const dynamicMax = +obj.memory_dynamic_max
const staticMin = +obj.memory_static_min const staticMin = +obj.memory_static_min
@ -413,7 +413,7 @@ const TRANSFORMS = {
vm.CPUs.number = +obj.VCPUs_at_startup vm.CPUs.number = +obj.VCPUs_at_startup
vm.template_info = { vm.template_info = {
arch: otherConfig['install-arch'], arch: otherConfig['install-arch'],
disks: (function() { disks: (function () {
const { disks: xml } = otherConfig const { disks: xml } = otherConfig
let data let data
if (!xml || !(data = parseXml(xml)).provision) { if (!xml || !(data = parseXml(xml)).provision) {
@ -429,7 +429,7 @@ const TRANSFORMS = {
return disks return disks
})(), })(),
install_methods: (function() { install_methods: (function () {
const methods = otherConfig['install-methods'] const methods = otherConfig['install-methods']
return methods ? methods.split(',') : [] return methods ? methods.split(',') : []

View File

@ -30,7 +30,7 @@ export default {
get: true, get: true,
set: [ set: [
'ipv4Allowed', 'ipv4Allowed',
function(value, vif) { function (value, vif) {
const lockingMode = const lockingMode =
isEmpty(value) && isEmpty(vif.ipv6_allowed) isEmpty(value) && isEmpty(vif.ipv6_allowed)
? 'network_default' ? 'network_default'
@ -46,7 +46,7 @@ export default {
get: true, get: true,
set: [ set: [
'ipv6Allowed', 'ipv6Allowed',
function(value, vif) { function (value, vif) {
const lockingMode = const lockingMode =
isEmpty(value) && isEmpty(vif.ipv4_allowed) isEmpty(value) && isEmpty(vif.ipv4_allowed)
? 'network_default' ? 'network_default'

View File

@ -56,7 +56,7 @@ const listMissingPatches = debounceWithKey(
export default { export default {
// raw { uuid: patch } map translated from updates.xensource.com/XenServer/updates.xml // raw { uuid: patch } map translated from updates.xensource.com/XenServer/updates.xml
// FIXME: should be static // FIXME: should be static
@decorateWith(debounceWithKey, 24 * 60 * 60 * 1000, function() { @decorateWith(debounceWithKey, 24 * 60 * 60 * 1000, function () {
return this return this
}) })
async _getXenUpdates() { async _getXenUpdates() {
@ -102,7 +102,7 @@ export default {
} }
}) })
const resolveVersionPatches = function(uuids) { const resolveVersionPatches = function (uuids) {
const versionPatches = { __proto__: null } const versionPatches = { __proto__: null }
forEach(ensureArray(uuids), ({ uuid }) => { forEach(ensureArray(uuids), ({ uuid }) => {
@ -444,7 +444,7 @@ export default {
return vdi return vdi
}, },
_poolWideInstall: deferrable(async function($defer, patches) { _poolWideInstall: deferrable(async function ($defer, patches) {
// Legacy XS patches // Legacy XS patches
if (!useUpdateSystem(this.pool.$master)) { if (!useUpdateSystem(this.pool.$master)) {
// for each patch: pool_patch.pool_apply // for each patch: pool_patch.pool_apply

View File

@ -155,7 +155,7 @@ export const makeEditObject = specs => {
if (set === true) { if (set === true) {
const prop = camelToSnakeCase(name) const prop = camelToSnakeCase(name)
return function(value, obj) { return function (value, obj) {
return this.setField(obj.$type, obj.$ref, prop, value) return this.setField(obj.$type, obj.$ref, prop, value)
} }
} }
@ -164,7 +164,7 @@ export const makeEditObject = specs => {
const index = set.indexOf('.') const index = set.indexOf('.')
if (index === -1) { if (index === -1) {
const prop = camelToSnakeCase(set) const prop = camelToSnakeCase(set)
return function(value, obj) { return function (value, obj) {
return this.setField(obj.$type, obj.$ref, prop, value) return this.setField(obj.$type, obj.$ref, prop, value)
} }
} }
@ -172,7 +172,7 @@ export const makeEditObject = specs => {
const field = set.slice(0, index) const field = set.slice(0, index)
const entry = set.slice(index + 1) const entry = set.slice(index + 1)
return function(value, object) { return function (value, object) {
return this.setFieldEntry( return this.setFieldEntry(
object.$type, object.$type,
object.$ref, object.$ref,
@ -198,7 +198,7 @@ export const makeEditObject = specs => {
return set[0] return set[0]
} }
return function(value, object) { return function (value, object) {
return Promise.all(mapToArray(set, set => set.call(this, value, object))) return Promise.all(mapToArray(set, set => set.call(this, value, object)))
} }
} }

View File

@ -250,9 +250,7 @@ export default class Api {
const userName = context.user ? context.user.email : '(unknown user)' const userName = context.user ? context.user.email : '(unknown user)'
const data = { const data = {
callId: Math.random() callId: Math.random().toString(36).slice(2),
.toString(36)
.slice(2),
userId, userId,
userName, userName,
userIp: session.get('user_ip', undefined), userIp: session.get('user_ip', undefined),

View File

@ -386,7 +386,7 @@ const wrapTaskFn = <T>(
opts: any, opts: any,
task: (...any) => Promise<T> task: (...any) => Promise<T>
): ((taskId: string, ...any) => Promise<T>) => ): ((taskId: string, ...any) => Promise<T>) =>
async function() { async function () {
const { data, logger, message, parentId, result } = const { data, logger, message, parentId, result } =
typeof opts === 'function' ? opts.apply(this, arguments) : opts typeof opts === 'function' ? opts.apply(this, arguments) : opts
@ -936,7 +936,7 @@ export default class BackupNg {
@decorateWith( @decorateWith(
debounceWithKey, debounceWithKey,
function() { function () {
return parseDuration(this._backupOptions.listingDebounce) return parseDuration(this._backupOptions.listingDebounce)
}, },
function keyFn(remoteId) { function keyFn(remoteId) {

View File

@ -5,7 +5,7 @@ const log = createLogger('xo:xo-mixins:hooks')
const makeSingletonHook = (hook, postEvent) => { const makeSingletonHook = (hook, postEvent) => {
let promise let promise
return function() { return function () {
if (promise === undefined) { if (promise === undefined) {
promise = runHook(this, hook) promise = runHook(this, hook)
promise.then(() => { promise.then(() => {

View File

@ -3,7 +3,7 @@
import { forEach } from 'lodash' import { forEach } from 'lodash'
import { resolveParamsVector } from './execute-call' import { resolveParamsVector } from './execute-call'
describe('resolveParamsVector', function() { describe('resolveParamsVector', function () {
forEach( forEach(
{ {
'cross product with three sets': [ 'cross product with three sets': [
@ -71,7 +71,7 @@ describe('resolveParamsVector', function() {
// Context. // Context.
{ {
getObjects: function() { getObjects: function () {
return [ return [
{ {
id: 'vm:1', id: 'vm:1',

View File

@ -139,10 +139,7 @@ export default class Proxy {
) )
patch(proxy, { address, authenticationToken, name, vmUuid }) patch(proxy, { address, authenticationToken, name, vmUuid })
return this._db return this._db.update(proxy).then(extractProperties).then(omitToken)
.update(proxy)
.then(extractProperties)
.then(omitToken)
} }
async upgradeProxyAppliance(id) { async upgradeProxyAppliance(id) {

View File

@ -13,7 +13,7 @@ global.Promise = require('bluebird')
// $FlowFixMe // $FlowFixMe
const config: Object = JSON.parse(process.env.XO_CONFIG) const config: Object = JSON.parse(process.env.XO_CONFIG)
export const mergeVhd = defer(async function( export const mergeVhd = defer(async function (
$defer: any, $defer: any,
parentRemote: Remote, parentRemote: Remote,
parentPath: string, parentPath: string,

View File

@ -214,7 +214,7 @@ export default class Xo extends EventEmitter {
// For security, prevent from accessing `this`. // For security, prevent from accessing `this`.
if (typeof value === 'function') { if (typeof value === 'function') {
value = (value => value = (value =>
function() { function () {
return value.apply(thisArg, arguments) return value.apply(thisArg, arguments)
})(value) })(value)
} }

View File

@ -35,7 +35,7 @@ var vmdkToVhd = require('xo-vmdk-to-vhd').vmdkToVhd
var createReadStream = require('fs').createReadStream var createReadStream = require('fs').createReadStream
var createWriteStream = require('fs').createWriteStream var createWriteStream = require('fs').createWriteStream
vmdkToVhd(fs.createReadStream(vmdkFileName)).then(function(stream) { vmdkToVhd(fs.createReadStream(vmdkFileName)).then(function (stream) {
stream.pipe(fs.createWriteStream(vhdFileName)) stream.pipe(fs.createWriteStream(vhdFileName))
}) })
``` ```

View File

@ -17,7 +17,7 @@ var vmdkToVhd = require('xo-vmdk-to-vhd').vmdkToVhd
var createReadStream = require('fs').createReadStream var createReadStream = require('fs').createReadStream
var createWriteStream = require('fs').createWriteStream var createWriteStream = require('fs').createWriteStream
vmdkToVhd(fs.createReadStream(vmdkFileName)).then(function(stream) { vmdkToVhd(fs.createReadStream(vmdkFileName)).then(function (stream) {
stream.pipe(fs.createWriteStream(vhdFileName)) stream.pipe(fs.createWriteStream(vhdFileName))
}) })
``` ```

View File

@ -25,19 +25,19 @@ const gulp = require('gulp')
// =================================================================== // ===================================================================
function lazyFn(factory) { function lazyFn(factory) {
let fn = function() { let fn = function () {
fn = factory() fn = factory()
return fn.apply(this, arguments) return fn.apply(this, arguments)
} }
return function() { return function () {
return fn.apply(this, arguments) return fn.apply(this, arguments)
} }
} }
// ------------------------------------------------------------------- // -------------------------------------------------------------------
const livereload = lazyFn(function() { const livereload = lazyFn(function () {
const livereload = require('gulp-refresh') const livereload = require('gulp-refresh')
livereload.listen({ livereload.listen({
port: LIVERELOAD_PORT, port: LIVERELOAD_PORT,
@ -46,7 +46,7 @@ const livereload = lazyFn(function() {
return livereload return livereload
}) })
const pipe = lazyFn(function() { const pipe = lazyFn(function () {
let current let current
function pipeCore(streams) { function pipeCore(streams) {
let i, n, stream let i, n, stream
@ -63,7 +63,7 @@ const pipe = lazyFn(function() {
} }
const push = Array.prototype.push const push = Array.prototype.push
return function(streams) { return function (streams) {
try { try {
if (!(streams instanceof Array)) { if (!(streams instanceof Array)) {
streams = [] streams = []
@ -79,7 +79,7 @@ const pipe = lazyFn(function() {
} }
}) })
const resolvePath = lazyFn(function() { const resolvePath = lazyFn(function () {
return require('path').resolve return require('path').resolve
}) })
@ -87,7 +87,7 @@ const resolvePath = lazyFn(function() {
// Similar to `gulp.src()` but the pattern is relative to `SRC_DIR` // Similar to `gulp.src()` but the pattern is relative to `SRC_DIR`
// and files are automatically watched when not in production mode. // and files are automatically watched when not in production mode.
const src = lazyFn(function() { const src = lazyFn(function () {
function resolve(path) { function resolve(path) {
return path ? resolvePath(SRC_DIR, path) : SRC_DIR return path ? resolvePath(SRC_DIR, path) : SRC_DIR
} }
@ -125,7 +125,7 @@ const src = lazyFn(function() {
// Similar to `gulp.dest()` but the output directory is relative to // Similar to `gulp.dest()` but the output directory is relative to
// `DIST_DIR` and default to `./`, and files are automatically live- // `DIST_DIR` and default to `./`, and files are automatically live-
// reloaded when not in production mode. // reloaded when not in production mode.
const dest = lazyFn(function() { const dest = lazyFn(function () {
function resolve(path) { function resolve(path) {
return path ? resolvePath(DIST_DIR, path) : DIST_DIR return path ? resolvePath(DIST_DIR, path) : DIST_DIR
} }
@ -211,21 +211,21 @@ function browserify(path, opts) {
} }
if (PRODUCTION) { if (PRODUCTION) {
write = function(data) { write = function (data) {
stream.push(data) stream.push(data)
stream.push(null) stream.push(null)
} }
} else { } else {
stream = require('gulp-plumber')().pipe(stream) stream = require('gulp-plumber')().pipe(stream)
write = function(data) { write = function (data) {
stream.push(data) stream.push(data)
} }
bundler.on('update', bundle) bundler.on('update', bundle)
} }
stream._read = function() { stream._read = function () {
this._read = function() {} this._read = function () {}
bundle() bundle()
} }

View File

@ -111,7 +111,7 @@ if (VERBOSE) {
} }
} }
BaseComponent.prototype.componentDidUpdate = function(oldProps, oldState) { BaseComponent.prototype.componentDidUpdate = function (oldProps, oldState) {
const prefix = `${this.constructor.name} updated because of its` const prefix = `${this.constructor.name} updated because of its`
diff(`${prefix} props:`, oldProps, this.props) diff(`${prefix} props:`, oldProps, this.props)
diff(`${prefix} state:`, oldState, this.state) diff(`${prefix} state:`, oldState, this.state)

View File

@ -93,11 +93,7 @@ export class FormattedDuration extends Component {
_humanizeDuration = createSelector( _humanizeDuration = createSelector(
() => this.props.duration, () => this.props.duration,
() => this.props.lang, () => this.props.lang,
(duration, lang) => (duration, lang) => moment.duration(duration).locale(lang).humanize()
moment
.duration(duration)
.locale(lang)
.humanize()
) )
render() { render() {

View File

@ -2364,7 +2364,7 @@ const messages = {
durationFormat: durationFormat:
'{days, plural, =0 {} one {# day } other {# days }}{hours, plural, =0 {} one {# hour } other {# hours }}{minutes, plural, =0 {} one {# minute } other {# minutes }}{seconds, plural, =0 {} one {# second} other {# seconds}}', '{days, plural, =0 {} one {# day } other {# days }}{hours, plural, =0 {} one {# hour } other {# hours }}{minutes, plural, =0 {} one {# minute } other {# minutes }}{seconds, plural, =0 {} one {# second} other {# seconds}}',
} }
forEach(messages, function(message, id) { forEach(messages, function (message, id) {
if (typeof message === 'string') { if (typeof message === 'string') {
messages[id] = { messages[id] = {
id, id,

View File

@ -43,8 +43,9 @@ function* range(ip1, ip2) {
} }
for (let i = hex; i <= hex2; i++) { for (let i = hex; i <= hex2; i++) {
yield `${(i >> 24) & 0xff}.${(i >> 16) & 0xff}.${(i >> 8) & 0xff}.${i & yield `${(i >> 24) & 0xff}.${(i >> 16) & 0xff}.${(i >> 8) & 0xff}.${
0xff}` i & 0xff
}`
} }
} }

View File

@ -1,9 +1,6 @@
// this computed can be used to generate a random id for the lifetime of the // this computed can be used to generate a random id for the lifetime of the
// component // component
export const generateId = () => export const generateId = () => `i${Math.random().toString(36).slice(2)}`
`i${Math.random()
.toString(36)
.slice(2)}`
// TODO: remove these functions once the PR: https://github.com/JsCommunity/reaclette/pull/5 has been merged // TODO: remove these functions once the PR: https://github.com/JsCommunity/reaclette/pull/5 has been merged
// It only supports native inputs // It only supports native inputs

View File

@ -413,9 +413,7 @@ export const SelectHost = makeStoreSelect(
export const SelectPool = makeStoreSelect( export const SelectPool = makeStoreSelect(
() => ({ () => ({
xoObjects: createGetObjectsOfType('pool') xoObjects: createGetObjectsOfType('pool').filter(getPredicate).sort(),
.filter(getPredicate)
.sort(),
}), }),
{ placeholder: _('selectPools') } { placeholder: _('selectPools') }
) )
@ -463,12 +461,8 @@ export const SelectVm = makeStoreSelect(
keys(vmsByContainer) keys(vmsByContainer)
) )
const getPools = createGetObjectsOfType('pool') const getPools = createGetObjectsOfType('pool').pick(getContainerIds).sort()
.pick(getContainerIds) const getHosts = createGetObjectsOfType('host').pick(getContainerIds).sort()
.sort()
const getHosts = createGetObjectsOfType('host')
.pick(getContainerIds)
.sort()
const getContainers = createSelector(getPools, getHosts, (pools, hosts) => const getContainers = createSelector(getPools, getHosts, (pools, hosts) =>
pools.concat(hosts) pools.concat(hosts)
@ -507,12 +501,8 @@ export const SelectVmSnapshot = makeStoreSelect(
export const SelectHostVm = makeStoreSelect( export const SelectHostVm = makeStoreSelect(
() => { () => {
const getHosts = createGetObjectsOfType('host') const getHosts = createGetObjectsOfType('host').filter(getPredicate).sort()
.filter(getPredicate) const getVms = createGetObjectsOfType('VM').filter(getPredicate).sort()
.sort()
const getVms = createGetObjectsOfType('VM')
.filter(getPredicate)
.sort()
const getObjects = createSelector(getHosts, getVms, (hosts, vms) => const getObjects = createSelector(getHosts, getVms, (hosts, vms) =>
hosts.concat(vms) hosts.concat(vms)

View File

@ -91,7 +91,7 @@ const _create2 = (...inputs) => {
throw new Error('no input selectors') throw new Error('no input selectors')
} }
return create(inputSelectors, function() { return create(inputSelectors, function () {
const args = new Array(n) const args = new Array(n)
for (let i = 0, j = 0; i < n; ++i) { for (let i = 0, j = 0; i < n; ++i) {
const input = inputs[i] const input = inputs[i]

View File

@ -599,9 +599,9 @@ class SortedTable extends Component {
selectedItemsIds.delete(item.id) selectedItemsIds.delete(item.id)
}) })
} else { } else {
const method = (selected === undefined const method = (
? !selectedItemsIds.has(item.id) selected === undefined ? !selectedItemsIds.has(item.id) : selected
: selected) )
? 'add' ? 'add'
: 'delete' : 'delete'

View File

@ -9,7 +9,7 @@ const createAction = (() => {
payload: payloadCreator(...args), payload: payloadCreator(...args),
}) })
: (action => : (action =>
function() { function () {
if (arguments.length) { if (arguments.length) {
throw new Error('this action expects no payload!') throw new Error('this action expects no payload!')
} }

View File

@ -16,7 +16,7 @@
* - `newState` {Object} * - `newState` {Object}
* - `position` {OBject} {left: {Number}, top: {Number}} * - `position` {OBject} {left: {Number}, top: {Number}}
*/ */
export default function(e, target, node, place, effect, offset) { export default function (e, target, node, place, effect, offset) {
const tipWidth = node.clientWidth const tipWidth = node.clientWidth
const tipHeight = node.clientHeight const tipHeight = node.clientHeight
const { mouseX, mouseY } = getCurrentOffset(e, target, effect) const { mouseX, mouseY } = getCurrentOffset(e, target, effect)

View File

@ -382,7 +382,7 @@ export const htmlFileToStream = file => {
stream.emit('error', error) stream.emit('error', error)
} }
stream._read = function(size) { stream._read = function (size) {
if (offset >= file.size) { if (offset >= file.size) {
stream.push(null) stream.push(null)
} else { } else {
@ -420,7 +420,7 @@ const OPs = {
} }
const makeNiceCompare = compare => const makeNiceCompare = compare =>
function() { function () {
const { length } = arguments const { length } = arguments
if (length === 2) { if (length === 2) {
return compare(arguments[0], arguments[1]) return compare(arguments[0], arguments[1])
@ -547,10 +547,7 @@ export const getMemoryUsedMetric = ({ memory, memoryFree = memory }) =>
// =================================================================== // ===================================================================
export const generateRandomId = () => export const generateRandomId = () => Math.random().toString(36).slice(2)
Math.random()
.toString(36)
.slice(2)
// =================================================================== // ===================================================================

View File

@ -210,10 +210,7 @@ export default class XoParallelChart extends Component {
forEach(columnsIds, (columnId, index) => { forEach(columnsIds, (columnId, index) => {
const max = d3.max(dataSet, elem => elem.data[columnId]) const max = d3.max(dataSet, elem => elem.data[columnId])
y[columnId] = d3 y[columnId] = d3.scaleLinear().domain([0, max]).range([CHART_HEIGHT, 0])
.scaleLinear()
.domain([0, max])
.range([CHART_HEIGHT, 0])
}) })
// 3. Build columns. // 3. Build columns.

View File

@ -144,10 +144,7 @@ class XoWeekChart extends Component {
const svg = this._svg const svg = this._svg
svg svg.select('.horizon-area').selectAll('path').remove()
.select('.horizon-area')
.selectAll('path')
.remove()
forEach(splittedData, data => { forEach(splittedData, data => {
svg svg
.select('.horizon-area') .select('.horizon-area')
@ -195,11 +192,7 @@ class XoWeekChart extends Component {
::setStyles(X_AXIS_TEXT_STYLE) ::setStyles(X_AXIS_TEXT_STYLE)
// 4. Update label. // 4. Update label.
svg svg.select('.label').attr('dx', 5).attr('dy', 20).text(props.label)
.select('.label')
.attr('dx', 5)
.attr('dy', 20)
.text(props.label)
} }
_handleMouseMove = () => { _handleMouseMove = () => {
@ -228,10 +221,7 @@ class XoWeekChart extends Component {
const { props } = this const { props } = this
const hover = this._svg.select('.hover-container') const hover = this._svg.select('.hover-container')
hover hover.select('.hover-line').attr('x1', x).attr('x2', x)
.select('.hover-line')
.attr('x1', x)
.attr('x2', x)
hover hover
.select('.hover-text') .select('.hover-text')
@ -247,16 +237,10 @@ class XoWeekChart extends Component {
.select(this.refs.chart) .select(this.refs.chart)
.append('svg') .append('svg')
.attr('transform', `translate(${HORIZON_AREA_MARGIN}, 0)`)) .attr('transform', `translate(${HORIZON_AREA_MARGIN}, 0)`))
svg svg.append('g').attr('class', 'x-axis')::setStyles(X_AXIS_STYLE)
.append('g')
.attr('class', 'x-axis')
::setStyles(X_AXIS_STYLE)
svg.append('g').attr('class', 'horizon-area') svg.append('g').attr('class', 'horizon-area')
svg svg.append('text').attr('class', 'label')::setStyles(LABEL_STYLE)
.append('text')
.attr('class', 'label')
::setStyles(LABEL_STYLE)
// Tooltip --------------------------------------------- // Tooltip ---------------------------------------------
svg svg

View File

@ -30,7 +30,7 @@ React.createElement = (createElement => {
return patchedRender return patchedRender
} }
return function(Component) { return function (Component) {
if (typeof Component === 'function') { if (typeof Component === 'function') {
const patched = Component._patched const patched = Component._patched
if (patched) { if (patched) {

View File

@ -30,7 +30,7 @@ const DiskImport = decorate([
provideState({ provideState({
initialState: getInitialState, initialState: getInitialState,
effects: { effects: {
handleDrop: async function(_, files) { handleDrop: async function (_, files) {
this.state.loadingDisks = true this.state.loadingDisks = true
const disks = await Promise.all( const disks = await Promise.all(
map(files, async file => { map(files, async file => {

View File

@ -76,7 +76,7 @@ const ACTIONS = [
}, },
] ]
const getType = function(param) { const getType = function (param) {
if (!param) { if (!param) {
return return
} }
@ -101,7 +101,7 @@ const reduceObject = (value, propertyName = 'id') =>
/** /**
* Adapts all data "arrayed" by UI-multiple-selectors to job's cross-product trick * Adapts all data "arrayed" by UI-multiple-selectors to job's cross-product trick
*/ */
const dataToParamVectorItems = function(params, data) { const dataToParamVectorItems = function (params, data) {
const items = [] const items = []
forEach(params, (param, name) => { forEach(params, (param, name) => {
if (Array.isArray(data[name]) && param.items) { if (Array.isArray(data[name]) && param.items) {

View File

@ -62,9 +62,7 @@ import TabXosan from './tab-xosan'
const getVdiIds = (state, props) => getSr(state, props).VDIs const getVdiIds = (state, props) => getSr(state, props).VDIs
const getVdis = createGetObjectsOfType('VDI') const getVdis = createGetObjectsOfType('VDI').pick(getVdiIds).sort()
.pick(getVdiIds)
.sort()
const getVdiSnapshots = createGetObjectsOfType('VDI-snapshot') const getVdiSnapshots = createGetObjectsOfType('VDI-snapshot')
.pick(getVdiIds) .pick(getVdiIds)
.sort() .sort()

View File

@ -268,7 +268,10 @@ const SshKeys = addSubscriptions({
})(({ user }) => { })(({ user }) => {
const sshKeys = user && user.preferences && user.preferences.sshKeys const sshKeys = user && user.preferences && user.preferences.sshKeys
const sshKeysWithIds = map(sshKeys, sshKey => ({ ...sshKey, id: sshKey.key })) const sshKeysWithIds = map(sshKeys, sshKey => ({
...sshKey,
id: sshKey.key,
}))
return ( return (
<div> <div>

View File

@ -223,7 +223,7 @@ const Updates = decorate([
defined(channel, xoaConfiguration.channel), defined(channel, xoaConfiguration.channel),
installedPackages: COMMUNITY installedPackages: COMMUNITY
? () => ({ 'xen-orchestra': 'sources' }) ? () => ({ 'xen-orchestra': 'sources' })
: async function() { : async function () {
const { const {
engine, engine,
installer, installer,