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',
]
module.exports = function(pkg, plugins, presets) {
module.exports = function (pkg, plugins, presets) {
plugins === undefined && (plugins = {})
presets === undefined && (presets = {})

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -28,7 +28,7 @@ afterEach(async () => {
})
async function createRandomFile(name, sizeMB) {
const createRandomStream = asyncIteratorToStream(function*(size) {
const createRandomStream = asyncIteratorToStream(function* (size) {
while (size-- > 0) {
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'
export default asyncIteratorToStream(async function*(handler, path) {
export default asyncIteratorToStream(async function* (handler, path) {
const fd = await handler.openFile(path, 'r')
try {
const vhd = new Vhd(handler, fd)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -22,9 +22,7 @@ async function main([url]) {
while (loop) {
await pool.update_other_config(
'xo:injectEvents',
Math.random()
.toString(36)
.slice(2)
Math.random().toString(36).slice(2)
)
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)
.then(JSON.parse)
.catch(function() {
.catch(function () {
return {}
})
})
exports.get = function(path) {
return load().then(function(config) {
exports.get = function (path) {
return load().then(function (config) {
return l33t(config).tap(path)
})
}
const save = (exports.save = function(config) {
return mkdirp(configPath).then(function() {
const save = (exports.save = function (config) {
return mkdirp(configPath).then(function () {
return writeFile(configFile, JSON.stringify(config))
})
})
exports.set = function(data) {
return load().then(function(config) {
exports.set = function (data) {
return load().then(function (config) {
return save(Object.assign(config, data))
})
}
exports.unset = function(paths) {
return load().then(function(config) {
exports.unset = function (paths) {
return load().then(function (config) {
const l33tConfig = l33t(config)
;[].concat(paths).forEach(function(path) {
;[].concat(paths).forEach(function (path) {
l33tConfig.purge(path, true)
})
return save(config)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -25,7 +25,7 @@ const waitTicks = (n = 2) => {
// ===================================================================
describe('UniqueIndex', function() {
describe('UniqueIndex', function () {
let col, byKey
const item1 = {
id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba',
@ -39,7 +39,7 @@ describe('UniqueIndex', function() {
id: '668c1274-4442-44a6-b99a-512188e0bb09',
}
beforeEach(function() {
beforeEach(function () {
col = new Collection()
forEach([item1, item2, item3], item => {
col.add(item)
@ -52,7 +52,7 @@ describe('UniqueIndex', function() {
return waitTicks()
})
it('works with existing items', function() {
it('works with existing items', function () {
expect(col.indexes).toEqual({
byKey: {
[item1.key]: item1,
@ -61,7 +61,7 @@ describe('UniqueIndex', function() {
})
})
it('works with added items', function() {
it('works with added items', function () {
const item4 = {
id: '823b56c4-4b96-4f3a-9533-5d08177167ac',
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 = {
id: item1.id,
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)
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 = {
id: item1.id,
key: item1.key,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -69,10 +69,7 @@ const STATUS_ICON = {
const DATE_FORMAT = 'dddd, MMMM Do YYYY, h:mm:ss a'
const createDateFormatter = timezone =>
timezone !== undefined
? timestamp =>
moment(timestamp)
.tz(timezone)
.format(DATE_FORMAT)
? timestamp => moment(timestamp).tz(timezone).format(DATE_FORMAT)
: timestamp => moment(timestamp).format(DATE_FORMAT)
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)
}

View File

@ -33,7 +33,7 @@ exports.testSchema = {
//
// Its only parameter is an object which currently only contains a
// `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
// usually it returns a new instance of an existing class.
return {
@ -42,7 +42,7 @@ exports.default = function(opts) {
//
// Note: before being called, the configuration is validated
// against the provided configuration schema.
configure: function(configuration, state) {
configure: function (configuration, state) {
console.log('stub configured', configuration)
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
// the plugin has been successfully configured.
load: function() {
load: function () {
console.log('stub loaded')
},
// This (optional) method is called to unload the plugin.
//
// Note: will only be called if the plugin is currently loaded.
unload: function() {
unload: function () {
console.log('stub unloaded')
},
@ -70,7 +70,7 @@ exports.default = function(opts) {
// Note 2: before being called, the test configuration is validated
// against the provided test data.
// 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')
// 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 = () =>
Math.random()
.toString(36)
.slice(2)
const randomId = () => Math.random().toString(36).slice(2)
export { randomId as default }

View File

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

View File

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

View File

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

View File

@ -108,7 +108,7 @@ describe('vbd', () => {
() => {
throw new Error('vbd.delete() should have thrown')
},
function(error) {
function (error) {
// TODO: check with Julien if it is ok
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')
},
function(error) {
function (error) {
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')
},
function(error) {
function (error) {
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,
operator,
rvalue,
@ -131,7 +131,7 @@ Handlebars.registerHelper('compare', function(
: options.inverse(this)
})
Handlebars.registerHelper('math', function(lvalue, operator, rvalue, options) {
Handlebars.registerHelper('math', function (lvalue, operator, rvalue, options) {
if (arguments.length < 3) {
throw new Error('Handlebars Helper "math" needs 2 parameters')
}

View File

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

View File

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

View File

@ -2,18 +2,18 @@
import ensureArray from './_ensureArray'
describe('ensureArray()', function() {
it('wrap the value in an array', function() {
describe('ensureArray()', function () {
it('wrap the value in an array', function () {
const value = 'foo'
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([])
})
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']
expect(ensureArray(array)).toBe(array)

View File

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

View File

@ -6,7 +6,7 @@ describe('REMOVE_CACHE_ENTRY', () => {
it('clears the cache', async () => {
let i = 0
const debouncedFn = debounceWithKey(
function() {
function () {
return Promise.resolve(++i)
},
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,
{ name, size, sr, vm, bootable, position, mode }
) {

View File

@ -36,7 +36,7 @@ export { delete_ as delete }
// -------------------------------------------------------------------
// 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 xapi = this.getXapi(vdi)
const ref = vdi._xapiRef

View File

@ -49,7 +49,7 @@ const extract = (obj, prop) => {
}
// TODO: Implement ACLs
export const create = defer(async function($defer, params) {
export const create = defer(async function ($defer, params) {
const { user } = this
const resourceSet = extract(params, 'resourceSet')
const template = extract(params, 'template')
@ -345,7 +345,7 @@ create.resolve = {
// -------------------------------------------------------------------
const delete_ = defer(async function(
const delete_ = defer(async function (
$defer,
{
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 xapi = this.getXapi(VM)
const vmId = VM._xapiId
@ -691,7 +691,7 @@ restart.resolve = {
// -------------------------------------------------------------------
export const clone = defer(async function(
export const clone = defer(async function (
$defer,
{ 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,
{
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, [
[snapshot.$snapshot_of, 'operate'],
])

View File

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

View File

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

View File

@ -4,7 +4,7 @@ import { forEach } from 'lodash'
import { thunkToArray } from './utils'
import { crossProduct, mergeObjects } from './math'
describe('mergeObjects', function() {
describe('mergeObjects', function () {
forEach(
{
'Two sets of one': [{ a: 1, b: 2 }, { a: 1 }, { b: 2 }],
@ -29,7 +29,7 @@ describe('mergeObjects', function() {
},
([resultSet, ...sets], 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)
})
})
@ -37,7 +37,7 @@ describe('mergeObjects', function() {
)
})
describe('crossProduct', function() {
describe('crossProduct', function () {
// Gives the sum of all args
const addTest = args => args.reduce((prev, curr) => prev + curr, 0)
// Gives the product of all args
@ -98,7 +98,7 @@ describe('crossProduct', function() {
},
([product, items, cb], 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(
product.sort()
)

View File

@ -57,7 +57,7 @@ export function extractProperty(obj, prop) {
// -------------------------------------------------------------------
// Returns the first defined (non-undefined) value.
export const firstDefined = function() {
export const firstDefined = function () {
const n = arguments.length
for (let i = 0; i < n; ++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({
headless: true,
})
@ -115,7 +115,7 @@ export const formatXml = (function() {
return (...args) => builder.buildObject(...args)
})()
export const parseXml = (function() {
export const parseXml = (function () {
const opts = {
mergeAttrs: true,
explicitArray: false,

View File

@ -12,18 +12,18 @@ import {
// ===================================================================
describe('camelToSnakeCase()', function() {
it('converts a string from camelCase to snake_case', function() {
describe('camelToSnakeCase()', function () {
it('converts a string from camelCase to snake_case', function () {
expect(camelToSnakeCase('fooBar')).toBe('foo_bar')
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('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')
})
})
@ -41,15 +41,15 @@ describe('diffItems', () => {
// -------------------------------------------------------------------
describe('extractProperty()', function() {
it('returns the value of the property', function() {
describe('extractProperty()', function () {
it('returns the value of the property', function () {
const value = {}
const obj = { prop: 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 obj = { prop: value }
@ -60,8 +60,8 @@ describe('extractProperty()', function() {
// -------------------------------------------------------------------
describe('formatXml()', function() {
it('formats a JS object to an XML string', function() {
describe('formatXml()', function () {
it('formats a JS object to an XML string', function () {
expect(
formatXml({
foo: {
@ -85,22 +85,22 @@ describe('generateToken()', () => {
// -------------------------------------------------------------------
describe('parseSize()', function() {
it('parses a human size', function() {
describe('parseSize()', function () {
it('parses a human size', function () {
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)
})
it('throws if the string cannot be parsed', function() {
expect(function() {
it('throws if the string cannot be parsed', function () {
expect(function () {
parseSize('foo')
}).toThrow()
})
it('supports the B unit as suffix', function() {
it('supports the B unit as suffix', function () {
expect(parseSize('3MB')).toBe(3e6)
})
})

View File

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

View File

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

View File

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

View File

@ -155,7 +155,7 @@ export const makeEditObject = specs => {
if (set === true) {
const prop = camelToSnakeCase(name)
return function(value, obj) {
return function (value, obj) {
return this.setField(obj.$type, obj.$ref, prop, value)
}
}
@ -164,7 +164,7 @@ export const makeEditObject = specs => {
const index = set.indexOf('.')
if (index === -1) {
const prop = camelToSnakeCase(set)
return function(value, obj) {
return function (value, obj) {
return this.setField(obj.$type, obj.$ref, prop, value)
}
}
@ -172,7 +172,7 @@ export const makeEditObject = specs => {
const field = set.slice(0, index)
const entry = set.slice(index + 1)
return function(value, object) {
return function (value, object) {
return this.setFieldEntry(
object.$type,
object.$ref,
@ -198,7 +198,7 @@ export const makeEditObject = specs => {
return set[0]
}
return function(value, object) {
return function (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 data = {
callId: Math.random()
.toString(36)
.slice(2),
callId: Math.random().toString(36).slice(2),
userId,
userName,
userIp: session.get('user_ip', undefined),

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2364,7 +2364,7 @@ const messages = {
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}}',
}
forEach(messages, function(message, id) {
forEach(messages, function (message, id) {
if (typeof message === 'string') {
messages[id] = {
id,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,7 +16,7 @@
* - `newState` {Object}
* - `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 tipHeight = node.clientHeight
const { mouseX, mouseY } = getCurrentOffset(e, target, effect)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -76,7 +76,7 @@ const ACTIONS = [
},
]
const getType = function(param) {
const getType = function (param) {
if (!param) {
return
}
@ -101,7 +101,7 @@ const reduceObject = (value, propertyName = 'id') =>
/**
* 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 = []
forEach(params, (param, name) => {
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 getVdis = createGetObjectsOfType('VDI')
.pick(getVdiIds)
.sort()
const getVdis = createGetObjectsOfType('VDI').pick(getVdiIds).sort()
const getVdiSnapshots = createGetObjectsOfType('VDI-snapshot')
.pick(getVdiIds)
.sort()

View File

@ -268,7 +268,10 @@ const SshKeys = addSubscriptions({
})(({ user }) => {
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 (
<div>

View File

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