Importing string methods directly from @ember/string (#12499)

* Capitalize methods

* Let ESLint yell at us again

* Dasherize
This commit is contained in:
Phil Renaud 2022-04-07 15:51:41 -04:00 committed by GitHub
parent 09b5e8d388
commit 311a6d82c9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 113 additions and 75 deletions

View file

@ -1,5 +1,6 @@
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { camelize } from '@ember/string';
import RESTAdapter from '@ember-data/adapter/rest';
import codesForError from '../utils/codes-for-error';
import removeRecord from '../utils/remove-record';
@ -96,8 +97,7 @@ export default class ApplicationAdapter extends RESTAdapter {
let prefix = this.urlPrefix();
if (modelName) {
/* eslint-disable-next-line ember/no-string-prototype-extensions */
path = modelName.camelize();
path = camelize(modelName);
if (path) {
url.push(path);
}

View file

@ -1,6 +1,7 @@
import Component from '@ember/component';
import { action, computed } from '@ember/object';
import { inject as service } from '@ember/service';
import { camelize } from '@ember/string';
import { classNames } from '@ember-decorators/component';
import classic from 'ember-classic-decorator';
import jobClientStatus from 'nomad-ui/utils/properties/job-client-status';
@ -36,8 +37,7 @@ export default class JobClientStatusSummary extends Component {
@action
onSliceClick(ev, slice) {
/* eslint-disable-next-line ember/no-string-prototype-extensions */
this.gotoClients([slice.className.camelize()]);
this.gotoClients([camelize(slice.className)]);
}
persist(item, isOpen) {

View file

@ -3,7 +3,7 @@ import { action, computed } from '@ember/object';
import { inject as service } from '@ember/service';
import { classNames } from '@ember-decorators/component';
import classic from 'ember-classic-decorator';
import { camelize } from '@ember/string';
@classic
@classNames('boxed-section')
export default class Summary extends Component {
@ -24,8 +24,7 @@ export default class Summary extends Component {
@action
onSliceClick(ev, slice) {
/* eslint-disable-next-line ember/no-string-prototype-extensions */
this.gotoAllocations([slice.label.camelize()]);
this.gotoAllocations([camelize(slice.label)]);
}
@computed('forceCollapsed')

View file

@ -1,5 +1,5 @@
import { helper } from '@ember/component/helper';
import { dasherize } from '@ember/string';
/**
* CSS Class
*
@ -9,8 +9,7 @@ import { helper } from '@ember/component/helper';
* Differs from dasherize by handling slashes.
*/
export function cssClass([updateType]) {
/* eslint-disable-next-line ember/no-string-prototype-extensions */
return updateType.replace(/\//g, '-').dasherize();
return dasherize(updateType.replace(/\//g, '-'));
}
export default helper(cssClass);

View file

@ -1,4 +1,3 @@
/* eslint-disable ember/no-string-prototype-extensions */
import { copy } from 'ember-copy';
import { get } from '@ember/object';
import { makeArray } from '@ember/array';
@ -7,7 +6,7 @@ import { pluralize, singularize } from 'ember-inflector';
import removeRecord from '../utils/remove-record';
import { assign } from '@ember/polyfills';
import classic from 'ember-classic-decorator';
import { camelize, capitalize, dasherize } from '@ember/string';
@classic
export default class Application extends JSONSerializer {
primaryKey = 'ID';
@ -61,11 +60,11 @@ export default class Application extends JSONSerializer {
separateNanos = null;
keyForAttribute(attr) {
return attr.camelize().capitalize();
return capitalize(camelize(attr));
}
keyForRelationship(attr, relationshipType) {
const key = `${singularize(attr).camelize().capitalize()}ID`;
const key = `${capitalize(camelize(singularize(attr)))}ID`;
return relationshipType === 'hasMany' ? pluralize(key) : key;
}
@ -176,6 +175,6 @@ export default class Application extends JSONSerializer {
}
modelNameFromPayloadKey(key) {
return singularize(key.dasherize());
return singularize(dasherize(key));
}
}

View file

@ -1,7 +1,7 @@
import { set, get } from '@ember/object';
import ApplicationSerializer from './application';
import classic from 'ember-classic-decorator';
import { capitalize } from '@ember/string';
@classic
export default class VolumeSerializer extends ApplicationSerializer {
attrs = {
@ -56,8 +56,7 @@ export default class VolumeSerializer extends ApplicationSerializer {
keyForRelationship(attr, relationshipType) {
//Embedded relationship attributes don't end in IDs
/* eslint-disable-next-line ember/no-string-prototype-extensions */
if (this.embeddedRelationships.includes(attr)) return attr.capitalize();
if (this.embeddedRelationships.includes(attr)) return capitalize(attr);
return super.keyForRelationship(attr, relationshipType);
}

View file

@ -1,4 +1,5 @@
import { Factory, trait } from 'ember-cli-mirage';
import { dasherize } from '@ember/string';
import faker from 'nomad-ui/mirage/faker';
import { pickOne } from '../utils';
@ -6,10 +7,7 @@ const REF_TIME = new Date();
const TROUBLESOME_CHARACTERS = '🏆 💃 🤩 🙌🏿 🖨 ? ; %'.split(' ');
const makeWord = () => (faker.random.number(10000000) + 50000).toString(36);
const makeSentence = (count = 10) =>
new Array(count)
.fill(null)
.map(makeWord)
.join(' ');
new Array(count).fill(null).map(makeWord).join(' ');
const fileTypeMapping = {
svg: 'image/svg',
@ -36,7 +34,9 @@ const fileBodyMapping = {
.map((_, i) => {
const date = new Date(2019, 6, 23);
date.setSeconds(i * 5);
return `${date.toISOString()} ${makeSentence(faker.random.number({ max: 5 }) + 7)}`;
return `${date.toISOString()} ${makeSentence(
faker.random.number({ max: 5 }) + 7
)}`;
})
.join('\n'),
json: () =>
@ -52,7 +52,7 @@ const fileBodyMapping = {
};
export default Factory.extend({
id: i => i,
id: (i) => i,
isDir: faker.random.boolean,
@ -78,9 +78,9 @@ export default Factory.extend({
},
name() {
return `${faker.hacker.noun().dasherize()}-${pickOne(TROUBLESOME_CHARACTERS)}${
this.isDir ? '' : `.${this.fileType}`
}`;
return `${dasherize(faker.hacker.noun())}-${pickOne(
TROUBLESOME_CHARACTERS
)}${this.isDir ? '' : `.${this.fileType}`}`;
},
body() {
@ -99,12 +99,20 @@ export default Factory.extend({
afterCreate(allocFile, server) {
// create files for the directory
if (allocFile.depth > 0) {
server.create('allocFile', 'dir', { parent: allocFile, depth: allocFile.depth - 1 });
server.create('allocFile', 'dir', {
parent: allocFile,
depth: allocFile.depth - 1,
});
}
server.createList('allocFile', faker.random.number({ min: 1, max: 3 }), 'file', {
parent: allocFile,
});
server.createList(
'allocFile',
faker.random.number({ min: 1, max: 3 }),
'file',
{
parent: allocFile,
}
);
},
}),

View file

@ -2,12 +2,13 @@ import { Factory } from 'ember-cli-mirage';
import faker from 'nomad-ui/mirage/faker';
import { pickOne } from '../utils';
import { STORAGE_PROVIDERS } from '../common';
import { dasherize } from '@ember/string';
const ACCESS_MODES = ['multi-node-single-writer'];
const ATTACHMENT_MODES = ['file-system'];
export default Factory.extend({
id: i => `${faker.hacker.noun().dasherize()}-${i}`.toLowerCase(),
id: (i) => `${dasherize(faker.hacker.noun())}-${i}`.toLowerCase(),
name() {
return this.id;
},
@ -36,7 +37,9 @@ export default Factory.extend({
afterCreate(volume, server) {
if (!volume.namespaceId) {
const namespace = server.db.namespaces.length ? pickOne(server.db.namespaces).id : null;
const namespace = server.db.namespaces.length
? pickOne(server.db.namespaces).id
: null;
volume.update({
namespace,
namespaceId: namespace,
@ -48,7 +51,9 @@ export default Factory.extend({
}
if (!volume.plugin) {
const plugin = server.db.csiPlugins.length ? pickOne(server.db.csiPlugins) : null;
const plugin = server.db.csiPlugins.length
? pickOne(server.db.csiPlugins)
: null;
volume.update({
PluginId: plugin && plugin.id,
});

View file

@ -3,6 +3,7 @@ import { Factory, trait } from 'ember-cli-mirage';
import faker from 'nomad-ui/mirage/faker';
import { provide, pickOne } from '../utils';
import { DATACENTERS } from '../common';
import { dasherize } from '@ember/string';
const REF_TIME = new Date();
const JOB_PREFIXES = provide(5, faker.hacker.abbreviation);
@ -17,9 +18,9 @@ export default Factory.extend({
return `${this.parentId}/${dispatchId}`;
}
return `${faker.helpers.randomize(
JOB_PREFIXES
)}-${faker.hacker.noun().dasherize()}-${i}`.toLowerCase();
return `${faker.helpers.randomize(JOB_PREFIXES)}-${dasherize(
faker.hacker.noun()
)}-${i}`.toLowerCase();
},
name() {
@ -40,7 +41,9 @@ export default Factory.extend({
resourceSpec: null,
groupsCount() {
return this.resourceSpec ? this.resourceSpec.length : faker.random.number({ min: 1, max: 2 });
return this.resourceSpec
? this.resourceSpec.length
: faker.random.number({ min: 1, max: 2 });
},
region: () => 'global',
@ -49,7 +52,9 @@ export default Factory.extend({
allAtOnce: faker.random.boolean,
status: () => faker.helpers.randomize(JOB_STATUSES),
datacenters: () =>
faker.helpers.shuffle(DATACENTERS).slice(0, faker.random.number({ min: 1, max: 4 })),
faker.helpers
.shuffle(DATACENTERS)
.slice(0, faker.random.number({ min: 1, max: 4 })),
childrenCount: () => faker.random.number({ min: 1, max: 2 }),
@ -148,7 +153,7 @@ export default Factory.extend({
}),
}),
createIndex: i => i,
createIndex: (i) => i,
modifyIndex: () => faker.random.number({ min: 10, max: 2000 }),
// Directive used to control sub-resources
@ -188,7 +193,9 @@ export default Factory.extend({
afterCreate(job, server) {
if (!job.namespaceId) {
const namespace = server.db.namespaces.length ? pickOne(server.db.namespaces).id : null;
const namespace = server.db.namespaces.length
? pickOne(server.db.namespaces).id
: null;
job.update({
namespace,
namespaceId: namespace,
@ -217,14 +224,20 @@ export default Factory.extend({
groups = provide(job.groupsCount, (_, idx) =>
server.create('task-group', 'noHostVolumes', {
...groupProps,
resourceSpec: job.resourceSpec && job.resourceSpec.length && job.resourceSpec[idx],
resourceSpec:
job.resourceSpec &&
job.resourceSpec.length &&
job.resourceSpec[idx],
})
);
} else {
groups = provide(job.groupsCount, (_, idx) =>
server.create('task-group', {
...groupProps,
resourceSpec: job.resourceSpec && job.resourceSpec.length && job.resourceSpec[idx],
resourceSpec:
job.resourceSpec &&
job.resourceSpec.length &&
job.resourceSpec[idx],
})
);
}
@ -234,11 +247,15 @@ export default Factory.extend({
});
const hasChildren = job.periodic || (job.parameterized && !job.parentId);
const jobSummary = server.create('job-summary', hasChildren ? 'withChildren' : 'withSummary', {
jobId: job.id,
groupNames: groups.mapBy('name'),
namespace: job.namespace,
});
const jobSummary = server.create(
'job-summary',
hasChildren ? 'withChildren' : 'withSummary',
{
jobId: job.id,
groupNames: groups.mapBy('name'),
namespace: job.namespace,
}
);
job.update({
jobSummaryId: jobSummary.id,

View file

@ -1,12 +1,13 @@
import { Factory } from 'ember-cli-mirage';
import faker from 'nomad-ui/mirage/faker';
import { provide } from '../utils';
import { dasherize } from '@ember/string';
const ON_UPDATE = ['default', 'ignore', 'ignore_warnings'];
export default Factory.extend({
name: id => `${faker.hacker.noun().dasherize()}-${id}-service`,
portLabel: () => faker.hacker.noun().dasherize(),
name: (id) => `${dasherize(faker.hacker.noun())}-${id}-service`,
portLabel: () => dasherize(faker.hacker.noun()),
onUpdate: faker.helpers.randomize(ON_UPDATE),
tags: () => {
if (!faker.random.boolean()) {
@ -23,7 +24,7 @@ export default Factory.extend({
Proxy: {
Upstreams: [
{
DestinationName: faker.hacker.noun().dasherize(),
DestinationName: dasherize(faker.hacker.noun()),
LocalBindPort: faker.random.number({ min: 5000, max: 60000 }),
},
],

View file

@ -2,11 +2,12 @@ import { Factory, trait } from 'ember-cli-mirage';
import faker from 'nomad-ui/mirage/faker';
import { provide } from '../utils';
import { generateResources } from '../common';
import { dasherize } from '@ember/string';
const DISK_RESERVATIONS = [200, 500, 1000, 2000, 5000, 10000, 100000];
export default Factory.extend({
name: id => `${faker.hacker.noun().dasherize()}-g-${id}`,
name: (id) => `${dasherize(faker.hacker.noun())}-g-${id}`,
count: () => faker.random.number({ min: 1, max: 2 }),
ephemeralDisk: () => ({
@ -75,7 +76,8 @@ export default Factory.extend({
if (!group.shallow) {
const resources =
group.resourceSpec && divide(group.count, parseResourceSpec(group.resourceSpec));
group.resourceSpec &&
divide(group.count, parseResourceSpec(group.resourceSpec));
const tasks = provide(group.count, (_, idx) => {
const mounts = faker.helpers
.shuffle(volumes)
@ -88,7 +90,7 @@ export default Factory.extend({
return server.create('task', {
taskGroup: group,
...maybeResources,
volumeMounts: mounts.map(mount => ({
volumeMounts: mounts.map((mount) => ({
Volume: mount,
Destination: `/${faker.internet.userName()}/${faker.internet.domainWord()}/${faker.internet.color()}`,
PropagationMode: '',
@ -113,7 +115,9 @@ export default Factory.extend({
namespace: group.job.namespace,
taskGroup: group.name,
name: `${group.name}.[${i}]`,
rescheduleSuccess: group.withRescheduling ? faker.random.boolean() : null,
rescheduleSuccess: group.withRescheduling
? faker.random.boolean()
: null,
rescheduleAttempts: group.withRescheduling
? faker.random.number({ min: 1, max: 5 })
: 0,
@ -162,11 +166,11 @@ function parseResourceSpec(spec) {
I: 'IOPS',
};
const terms = spec.split(',').map(t => {
const terms = spec.split(',').map((t) => {
const [k, v] = t
.trim()
.split(':')
.map(kv => kv.trim());
.map((kv) => kv.trim());
return [k, +v];
});
@ -201,12 +205,17 @@ function roulette(total, divisions, variance = 0.8) {
let roulette = new Array(divisions).fill(total / divisions);
roulette.forEach((v, i) => {
if (i === roulette.length - 1) return;
roulette.splice(i, 2, ...rngDistribute(roulette[i], roulette[i + 1], variance));
roulette.splice(
i,
2,
...rngDistribute(roulette[i], roulette[i + 1], variance)
);
});
return roulette;
}
function rngDistribute(a, b, variance = 0.8) {
const move = a * faker.random.number({ min: 0, max: variance, precision: 0.01 });
const move =
a * faker.random.number({ min: 0, max: variance, precision: 0.01 });
return [a - move, b + move];
}

View file

@ -1,6 +1,7 @@
import { Factory } from 'ember-cli-mirage';
import faker from 'nomad-ui/mirage/faker';
import { generateResources } from '../common';
import { dasherize } from '@ember/string';
const DRIVERS = ['docker', 'java', 'rkt', 'qemu', 'exec', 'raw_exec'];
@ -15,11 +16,11 @@ export default Factory.extend({
JobID: '',
name: id => `task-${faker.hacker.noun().dasherize()}-${id}`,
name: (id) => `task-${dasherize(faker.hacker.noun())}-${id}`,
driver: () => faker.helpers.randomize(DRIVERS),
originalResources: generateResources,
resources: function() {
resources: function () {
// Generate resources the usual way, but transform to the old
// shape because that's what the job spec uses.
const resources = this.originalResources;
@ -31,7 +32,7 @@ export default Factory.extend({
};
},
Lifecycle: i => {
Lifecycle: (i) => {
const cycle = i % 6;
if (cycle === 0) {
@ -54,11 +55,15 @@ export default Factory.extend({
const recommendations = [];
if (faker.random.number(10) >= 1) {
recommendations.push(server.create('recommendation', { task, resource: 'CPU' }));
recommendations.push(
server.create('recommendation', { task, resource: 'CPU' })
);
}
if (faker.random.number(10) >= 1) {
recommendations.push(server.create('recommendation', { task, resource: 'MemoryMB' }));
recommendations.push(
server.create('recommendation', { task, resource: 'MemoryMB' })
);
}
task.save({ recommendationIds: recommendations.mapBy('id') });

View file

@ -1,12 +1,8 @@
import { camelize, capitalize } from '@ember/string';
import { RestSerializer } from 'ember-cli-mirage';
const keyCase = str =>
str === 'id'
? 'ID'
: str
.camelize()
.capitalize()
.replace(/Id/g, 'ID');
const keyCase = (str) =>
str === 'id' ? 'ID' : capitalize(camelize(str)).replace(/Id/g, 'ID');
export default RestSerializer.extend({
serialize() {
@ -20,7 +16,7 @@ export default RestSerializer.extend({
},
keyForModel: keyCase,
keyForForeignKey: str => `${keyCase(str)}ID`,
keyForForeignKey: (str) => `${keyCase(str)}ID`,
keyForCollection: keyCase,
keyForAttribute: keyCase,
keyForRelationship: keyCase,

View file

@ -12,6 +12,7 @@ import {
selectOpenChoose,
} from '../../utils/ember-power-select-extensions';
import { componentA11yAudit } from 'nomad-ui/tests/helpers/a11y-audit';
import { capitalize } from '@ember/string';
module('Integration | Component | agent-monitor', function (hooks) {
setupRenderingTest(hooks);
@ -123,7 +124,7 @@ module('Integration | Component | agent-monitor', function (hooks) {
const contentId = await selectOpen('[data-test-level-switcher-parent]');
run.later(run, run.cancelTimers, INTERVAL);
await selectOpenChoose(contentId, newLevel.capitalize());
await selectOpenChoose(contentId, capitalize(newLevel));
await settled();
assert.ok(onLevelChange.calledOnce);
@ -154,7 +155,7 @@ module('Integration | Component | agent-monitor', function (hooks) {
const contentId = await selectOpen('[data-test-level-switcher-parent]');
run.later(run, run.cancelTimers, INTERVAL);
await selectOpenChoose(contentId, newLevel.capitalize());
await selectOpenChoose(contentId, capitalize(newLevel));
await settled();
assert.equal(
@ -197,7 +198,7 @@ module('Integration | Component | agent-monitor', function (hooks) {
const contentId = await selectOpen('[data-test-level-switcher-parent]');
run.later(run, run.cancelTimers, INTERVAL);
await selectOpenChoose(contentId, newLevel.capitalize());
await selectOpenChoose(contentId, capitalize(newLevel));
await settled();
assert.equal(