chore: simpler string trimming (#14798)

This commit is contained in:
Simen Bekkhus 2023-12-28 19:22:15 +01:00 committed by GitHub
parent eef69ead9a
commit 14cfdae1e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 60 additions and 75 deletions

View File

@ -712,9 +712,6 @@ module.exports = {
'unicorn/prefer-set-has': 'off',
'unicorn/prefer-spread': 'off',
'unicorn/prefer-string-replace-all': 'off',
'unicorn/prefer-string-slice': 'off',
'unicorn/prefer-string-starts-ends-with': 'off',
'unicorn/prefer-string-trim-start-end': 'off',
'unicorn/prefer-type-error': 'off',
'unicorn/prevent-abbreviations': 'off',
'unicorn/text-encoding-identifier-case': 'off',

View File

@ -1642,7 +1642,7 @@ expect.extend({
toMatchTrimmedSnapshot(received, length) {
return toMatchSnapshot.call(
this,
received.substring(0, length),
received.slice(0, length),
'toMatchTrimmedSnapshot',
);
},
@ -1666,7 +1666,7 @@ const {toMatchInlineSnapshot} = require('jest-snapshot');
expect.extend({
toMatchTrimmedInlineSnapshot(received, ...rest) {
return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest);
return toMatchInlineSnapshot.call(this, received.slice(0, 10), ...rest);
},
});

View File

@ -46,7 +46,7 @@ const users = {
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
const userID = parseInt(url.slice('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])

View File

@ -273,7 +273,7 @@ const sortTests = (stdout: string) =>
}, [])
.sort(([a], [b]) => (a > b ? 1 : -1))
.map(strings =>
strings.length > 1 ? `${strings.join('\n').trimRight()}\n` : strings[0],
strings.length > 1 ? `${strings.join('\n').trimEnd()}\n` : strings[0],
)
.join('\n')
.trim();

View File

@ -28,7 +28,7 @@ test('shows the correct errors in stderr when failing tests', () => {
expect(result.exitCode).toBe(1);
const output = extractSummary(result.stderr)
.rest.split('\n')
.map(line => line.trimRight())
.map(line => line.trimEnd())
.join('\n');
expect(output).toMatchSnapshot();
});

View File

@ -78,9 +78,7 @@ test('works with snapshot failures', () => {
const result = normalizeDots(cleanStderr(stderr));
expect(
result.substring(0, result.indexOf('Snapshot Summary')),
).toMatchSnapshot();
expect(result.slice(0, result.indexOf('Snapshot Summary'))).toMatchSnapshot();
});
test('works with snapshot failures with hint', () => {
@ -88,9 +86,7 @@ test('works with snapshot failures with hint', () => {
const result = normalizeDots(cleanStderr(stderr));
expect(
result.substring(0, result.indexOf('Snapshot Summary')),
).toMatchSnapshot();
expect(result.slice(0, result.indexOf('Snapshot Summary'))).toMatchSnapshot();
});
test('works with error with cause', () => {
@ -113,7 +109,7 @@ test('works with error with cause thrown outside tests', () => {
expect(
// jasmine runner differ from circus one in this case, we just start
// the comparison when the stack starts to be reported
sanitizedSummary.substring(sanitizedSummary.indexOf('error during f')),
sanitizedSummary.slice(sanitizedSummary.indexOf('error during f')),
).toMatchSnapshot();
});

View File

@ -9,7 +9,7 @@ const users = {
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
const userID = parseInt(url.slice('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])

View File

@ -99,7 +99,7 @@ function getCacheKeyFromConfig(
.update('\0', 'utf8')
.update(process.version)
.digest('hex')
.substring(0, 32);
.slice(0, 32);
}
function loadBabelConfig(

View File

@ -205,7 +205,7 @@ describe('init', () => {
});
});
describe.each(JEST_CONFIG_EXT_ORDER.map(e => e.substring(1)))(
describe.each(JEST_CONFIG_EXT_ORDER.map(e => e.slice(1)))(
'has-jest-config-file-%s',
extension => {
describe('ask the user whether to override config or not', () => {

View File

@ -65,7 +65,7 @@ describe('check', () => {
expect(() => check(argv({maxWorkers: '50%'}))).not.toThrow();
});
test.each(constants.JEST_CONFIG_EXT_ORDER.map(e => e.substring(1)))(
test.each(constants.JEST_CONFIG_EXT_ORDER.map(e => e.slice(1)))(
'allows using "%s" file for --config option',
ext => {
expect(() => check(argv({config: `jest.config.${ext}`}))).not.toThrow();

View File

@ -79,7 +79,7 @@ export function check(argv: Config.Argv): true {
!isJSONString(argv.config) &&
!argv.config.match(
new RegExp(
`\\.(${constants.JEST_CONFIG_EXT_ORDER.map(e => e.substring(1)).join(
`\\.(${constants.JEST_CONFIG_EXT_ORDER.map(e => e.slice(1)).join(
'|',
)})$`,
'i',

View File

@ -76,7 +76,7 @@ it('picks an id based on the rootDir', async () => {
.update('/root/path/foo')
.update(String(Infinity))
.digest('hex')
.substring(0, 32);
.slice(0, 32);
const {options} = await normalize(
{
rootDir,

View File

@ -313,7 +313,7 @@ const normalizeMissingOptions = (
.update(configPath || '')
.update(String(projectIndex))
.digest('hex')
.substring(0, 32);
.slice(0, 32);
}
if (!options.setupFiles) {

View File

@ -58,13 +58,13 @@ export const replaceRootDirInPath = (
rootDir: string,
filePath: string,
): string => {
if (!/^<rootDir>/.test(filePath)) {
if (!filePath.startsWith('<rootDir>')) {
return filePath;
}
return path.resolve(
rootDir,
path.normalize(`./${filePath.substring('<rootDir>'.length)}`),
path.normalize(`./${filePath.slice('<rootDir>'.length)}`),
);
};

View File

@ -54,10 +54,8 @@ export default function getConsoleOutput(
return `${
output + TITLE_INDENT + chalk.dim(typeMessage)
}\n${message.trimRight()}\n${chalk.dim(
formattedStackTrace.trimRight(),
)}\n\n`;
}\n${message.trimEnd()}\n${chalk.dim(formattedStackTrace.trimEnd())}\n\n`;
}, '');
return `${logEntries.trimRight()}\n`;
return `${logEntries.trimEnd()}\n`;
}

View File

@ -58,7 +58,7 @@ function getGlobalCacheKey(
createHash('sha1'),
)
.digest('hex')
.substring(0, length);
.slice(0, length);
}
function getCacheKeyFunction(
@ -80,7 +80,7 @@ function getCacheKeyFunction(
.update('\0', 'utf8')
.update(instrument ? 'instrument' : '')
.digest('hex')
.substring(0, length);
.slice(0, length);
};
}

View File

@ -23,12 +23,12 @@ const STRING_ARRAY: ReadonlyArray<string> = [];
export function extract(contents: string): string {
const match = contents.match(docblockRe);
return match ? match[0].trimLeft() : '';
return match ? match[0].trimStart() : '';
}
export function strip(contents: string): string {
const match = contents.match(docblockRe);
return match && match[0] ? contents.substring(match[0].length) : contents;
return match && match[0] ? contents.slice(match[0].length) : contents;
}
export function parse(docblock: string): Pragmas {
@ -52,13 +52,13 @@ export function parseWithComments(docblock: string): {
prev = docblock;
docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
}
docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
docblock = docblock.replace(ltrimNewlineRe, '').trimEnd();
const result = Object.create(null) as Pragmas;
const comments = docblock
.replace(propertyRe, '')
.replace(ltrimNewlineRe, '')
.trimRight();
.trimEnd();
let match;
while ((match = propertyRe.exec(docblock))) {

View File

@ -25,7 +25,7 @@ module.exports = {
}
return filename
.substr(filename.lastIndexOf(path.sep) + 1)
.slice(filename.lastIndexOf(path.sep) + 1)
.replace(/(\.(android|ios|native))?\.js$/, '');
},

View File

@ -104,7 +104,7 @@ function find(
if (stat.isDirectory()) {
search(file);
} else {
const ext = path.extname(file).substr(1);
const ext = path.extname(file).slice(1);
if (extensions.includes(ext)) {
result.push([file, stat.mtime.getTime(), stat.size]);
}

View File

@ -12,7 +12,7 @@ const MOCKS_PATTERN = `${path.sep}__mocks__${path.sep}`;
const getMockName = (filePath: string): string => {
const mockPath = filePath.split(MOCKS_PATTERN)[1];
return mockPath
.substring(0, mockPath.lastIndexOf(path.extname(mockPath)))
.slice(0, mockPath.lastIndexOf(path.extname(mockPath)))
.replace(/\\/g, '/');
};

View File

@ -295,7 +295,7 @@ class HasteMap extends EventEmitter implements IHasteMap {
const rootDirHash = createHash('sha1')
.update(options.rootDir)
.digest('hex')
.substring(0, 32);
.slice(0, 32);
let hasteImplHash = '';
let dependencyExtractorHash = '';
@ -344,7 +344,7 @@ class HasteMap extends EventEmitter implements IHasteMap {
const hash = createHash('sha1').update(extra.join(''));
return path.join(
tmpdir,
`${id.replace(/\W/g, '-')}-${hash.digest('hex').substring(0, 32)}`,
`${id.replace(/\W/g, '-')}-${hash.digest('hex').slice(0, 32)}`,
);
}

View File

@ -10,7 +10,7 @@ import * as path from 'path';
// rootDir and filename must be absolute paths (resolved)
export function relative(rootDir: string, filename: string): string {
return filename.indexOf(rootDir + path.sep) === 0
? filename.substring(rootDir.length + 1)
? filename.slice(rootDir.length + 1)
: path.relative(rootDir, filename);
}

View File

@ -17,7 +17,7 @@ export default function getPlatformExtension(
if (secondToLast === -1) {
return null;
}
const platform = file.substring(secondToLast + 1, last);
const platform = file.slice(secondToLast + 1, last);
// If an overriding platform array is passed, check that first
if (platforms && platforms.includes(platform)) {

View File

@ -69,7 +69,7 @@ export async function worker(data: WorkerMessage): Promise<WorkerMetadata> {
} catch (err: any) {
throw new Error(`Cannot parse ${filePath} as JSON: ${err.message}`);
}
} else if (!blacklist.has(filePath.substring(filePath.lastIndexOf('.')))) {
} else if (!blacklist.has(filePath.slice(filePath.lastIndexOf('.')))) {
// Process a random file that is returned as a MODULE.
if (hasteImpl) {
id = hasteImpl.getHasteName(filePath);

View File

@ -53,7 +53,7 @@ function stackFormatter(
}
if (initError) {
return `${errorMessage.trimRight()}\n\n${initError.stack}`;
return `${errorMessage.trimEnd()}\n\n${initError.stack}`;
}
return new Error(errorMessage).stack;

View File

@ -312,5 +312,5 @@ const extractCustomPendingMessage = function (e: Error) {
const boilerplateEnd =
boilerplateStart + Spec.pendingSpecExceptionMessage.length;
return fullMessage.substr(boilerplateEnd);
return fullMessage.slice(boilerplateEnd);
};

View File

@ -511,7 +511,7 @@ const removeBlankErrorLine = (str: string) =>
// Lines saying just `Error:` are useless
.filter(line => !errorRegexp.test(line))
.join('\n')
.trimRight();
.trimEnd();
// jasmine and worker farm sometimes don't give us access to the actual
// Error object, so we have to regexp out the message from the stack string

View File

@ -885,7 +885,7 @@ export class ModuleMocker {
// if-do-while for perf reasons. The common case is for the if to fail.
if (name.startsWith(boundFunctionPrefix)) {
do {
name = name.substring(boundFunctionPrefix.length);
name = name.slice(boundFunctionPrefix.length);
// Call bind() just to alter the function name.
bindCall = '.bind(null)';
} while (name && name.startsWith(boundFunctionPrefix));

View File

@ -19,13 +19,13 @@ const createValidationError = (message: string) =>
new ValidationError(`${BULLET}Validation Error`, message, DOCUMENTATION_NOTE);
const replaceRootDirInPath = (rootDir: string, filePath: string): string => {
if (!/^<rootDir>/.test(filePath)) {
if (!filePath.startsWith('<rootDir>')) {
return filePath;
}
return path.resolve(
rootDir,
path.normalize(`./${filePath.substr('<rootDir>'.length)}`),
path.normalize(`./${filePath.slice('<rootDir>'.length)}`),
);
};

View File

@ -56,7 +56,7 @@ describe('Runtime', () => {
});
it('does not find modules if NODE_PATH is relative', async () => {
const nodePath = `${cwd.substr(
const nodePath = `${cwd.slice(
path.sep.length,
)}src/Runtime/__tests__/NODE_PATH_dir`;
const runtime = await createLocalRuntime(nodePath);

View File

@ -97,7 +97,7 @@ function stripAddedIndentation(inlineSnapshot: string) {
return inlineSnapshot;
}
lines[i] = lines[i].substring(indentation.length);
lines[i] = lines[i].slice(indentation.length);
}
}

View File

@ -122,7 +122,7 @@ class ScriptTransformer {
.update(transformerCacheKey)
.update(CACHE_VERSION)
.digest('hex')
.substring(0, 32);
.slice(0, 32);
}
return createHash('sha1')
@ -132,7 +132,7 @@ class ScriptTransformer {
.update(filename)
.update(CACHE_VERSION)
.digest('hex')
.substring(0, 32);
.slice(0, 32);
}
private _buildTransformCacheKey(pattern: string, filepath: string) {
@ -901,10 +901,7 @@ const stripShebang = (content: string) => {
* could get corrupted, out-of-sync, etc.
*/
function writeCodeCacheFile(cachePath: string, code: string) {
const checksum = createHash('sha1')
.update(code)
.digest('hex')
.substring(0, 32);
const checksum = createHash('sha1').update(code).digest('hex').slice(0, 32);
writeCacheFile(cachePath, `${checksum}\n${code}`);
}
@ -919,12 +916,9 @@ function readCodeCacheFile(cachePath: string): string | null {
if (content == null) {
return null;
}
const code = content.substring(33);
const checksum = createHash('sha1')
.update(code)
.digest('hex')
.substring(0, 32);
if (checksum === content.substring(0, 32)) {
const code = content.slice(33);
const checksum = createHash('sha1').update(code).digest('hex').slice(0, 32);
if (checksum === content.slice(0, 32)) {
return code;
}
return null;

View File

@ -64,7 +64,7 @@ ${chalk.cyan('https://jestjs.io/docs/code-transformation')}
${chalk.bold.red('Details:')}
${e.stack ?? ''}`.trimRight();
${e.stack ?? ''}`.trimEnd();
return e;
}

View File

@ -1664,7 +1664,7 @@ expect.extend({
toMatchTrimmedSnapshot(received, length) {
return toMatchSnapshot.call(
this,
received.substring(0, length),
received.slice(0, length),
'toMatchTrimmedSnapshot',
);
},
@ -1688,7 +1688,7 @@ const {toMatchInlineSnapshot} = require('jest-snapshot');
expect.extend({
toMatchTrimmedInlineSnapshot(received, ...rest) {
return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest);
return toMatchInlineSnapshot.call(this, received.slice(0, 10), ...rest);
},
});

View File

@ -46,7 +46,7 @@ const users = {
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
const userID = parseInt(url.slice('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])

View File

@ -1664,7 +1664,7 @@ expect.extend({
toMatchTrimmedSnapshot(received, length) {
return toMatchSnapshot.call(
this,
received.substring(0, length),
received.slice(0, length),
'toMatchTrimmedSnapshot',
);
},
@ -1688,7 +1688,7 @@ const {toMatchInlineSnapshot} = require('jest-snapshot');
expect.extend({
toMatchTrimmedInlineSnapshot(received, ...rest) {
return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest);
return toMatchInlineSnapshot.call(this, received.slice(0, 10), ...rest);
},
});

View File

@ -46,7 +46,7 @@ const users = {
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
const userID = parseInt(url.slice('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])

View File

@ -1664,7 +1664,7 @@ expect.extend({
toMatchTrimmedSnapshot(received, length) {
return toMatchSnapshot.call(
this,
received.substring(0, length),
received.slice(0, length),
'toMatchTrimmedSnapshot',
);
},
@ -1688,7 +1688,7 @@ const {toMatchInlineSnapshot} = require('jest-snapshot');
expect.extend({
toMatchTrimmedInlineSnapshot(received, ...rest) {
return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest);
return toMatchInlineSnapshot.call(this, received.slice(0, 10), ...rest);
},
});

View File

@ -46,7 +46,7 @@ const users = {
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
const userID = parseInt(url.slice('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])

View File

@ -1664,7 +1664,7 @@ expect.extend({
toMatchTrimmedSnapshot(received, length) {
return toMatchSnapshot.call(
this,
received.substring(0, length),
received.slice(0, length),
'toMatchTrimmedSnapshot',
);
},
@ -1688,7 +1688,7 @@ const {toMatchInlineSnapshot} = require('jest-snapshot');
expect.extend({
toMatchTrimmedInlineSnapshot(received, ...rest) {
return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest);
return toMatchInlineSnapshot.call(this, received.slice(0, 10), ...rest);
},
});

View File

@ -46,7 +46,7 @@ const users = {
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
const userID = parseInt(url.slice('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])