Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: replace deprecated String.substr() with String.slice() #19572

Merged
merged 2 commits into from
Apr 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/@aws-cdk/assertions/lib/private/cyclic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ function analyzeSubPattern(pattern: string): SubFragment[] {
}

if (start < pattern.length - 1) {
ret.push({ type: 'literal', content: pattern.substr(start) });
ret.push({ type: 'literal', content: pattern.slice(start) });
}

return ret;
Expand Down
6 changes: 3 additions & 3 deletions packages/@aws-cdk/aws-apigateway/lib/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ export abstract class ResourceBase extends ResourceConstruct implements IResourc
}

// trim trailing "/"
return this.resourceForPath(path.substr(1));
return this.resourceForPath(path.slice(1));
}

const parts = path.split('/');
Expand Down Expand Up @@ -544,11 +544,11 @@ export class ProxyResource extends Resource {
function validateResourcePathPart(part: string) {
// strip {} which indicate this is a parameter
if (part.startsWith('{') && part.endsWith('}')) {
part = part.substr(1, part.length - 2);
part = part.slice(1, -1);

// proxy resources are allowed to end with a '+'
if (part.endsWith('+')) {
part = part.substr(0, part.length - 1);
part = part.slice(0, -1);
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-apigateway/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function parseMethodOptionsPath(originalPath: string): { resourcePath: st
throw new Error(`Method options path must start with '/': ${originalPath}`);
}

const path = originalPath.substr(1); // trim trailing '/'
const path = originalPath.slice(1); // trim trailing '/'

const components = path.split('/');

Expand Down Expand Up @@ -60,7 +60,7 @@ export function parseAwsApiCall(path?: string, action?: string, actionParams?: {

if (action) {
if (actionParams) {
action += '&' + formatUrl({ query: actionParams }).substr(1);
action += '&' + formatUrl({ query: actionParams }).slice(1);
}

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ const requestCertificate = async function (requestId, domainName, subjectAlterna
const reqCertResponse = await acm.requestCertificate({
DomainName: domainName,
SubjectAlternativeNames: subjectAlternativeNames,
IdempotencyToken: crypto.createHash('sha256').update(requestId).digest('hex').substr(0, 32),
IdempotencyToken: crypto.createHash('sha256').update(requestId).digest('hex').slice(0, 32),
ValidationMethod: 'DNS'
}).promise();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export class OriginAccessIdentity extends OriginAccessIdentityBase implements IO
super(scope, id);

// Comment has a max length of 128.
const comment = (props?.comment ?? 'Allows CloudFront to reach the bucket').substr(0, 128);
const comment = (props?.comment ?? 'Allows CloudFront to reach the bucket').slice(0, 128);
this.resource = new CfnCloudFrontOriginAccessIdentity(this, 'Resource', {
cloudFrontOriginAccessIdentityConfig: { comment },
});
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-cloudfront/lib/origin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export abstract class OriginBase implements IOrigin {
if (originPath === undefined) { return undefined; }
let path = originPath;
if (!path.startsWith('/')) { path = '/' + path; }
if (path.endsWith('/')) { path = path.substr(0, path.length - 1); }
if (path.endsWith('/')) { path = path.slice(0, -1); }
return path;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-cloudfront/lib/web-distribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -815,7 +815,7 @@ export class CloudFrontWebDistribution extends cdk.Resource implements IDistribu
// Comments have an undocumented limit of 128 characters
const trimmedComment =
props.comment && props.comment.length > 128
? `${props.comment.substr(0, 128 - 3)}...`
? `${props.comment.slice(0, 128 - 3)}...`
: props.comment;

let distributionConfig: CfnDistribution.DistributionConfigProperty = {
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-codebuild/lib/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ export class Project extends ProjectBase {
// If the parameter name starts with / the resource name is not separated with a double '/'
// arn:aws:ssm:region:1111111111:parameter/PARAM_NAME
resourceName: envVariableValue.startsWith('/')
? envVariableValue.substr(1)
? envVariableValue.slice(1)
: envVariableValue,
}));
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-cognito/lib/user-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1055,7 +1055,7 @@ export class UserPool extends UserPoolBase {
return undefined;
}

const smsRoleExternalId = Names.uniqueId(this).substr(0, 1223); // sts:ExternalId max length of 1224
const smsRoleExternalId = Names.uniqueId(this).slice(0, 1223); // sts:ExternalId max length of 1224
const smsRole = props.smsRole ?? new Role(this, 'smsRole', {
assumedBy: new ServicePrincipal('cognito-idp.amazonaws.com', {
conditions: {
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-ec2/lib/cfn-init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export class CloudFormationInit {
// as well as include any asset hashes provided so the fingerprint is accurate.
const resolvedConfig = attachedResource.stack.resolve(bindResult.configData);
const fingerprintInput = { config: resolvedConfig, assetHash: bindResult.assetHash };
const fingerprint = contentHash(JSON.stringify(fingerprintInput)).substr(0, 16);
const fingerprint = contentHash(JSON.stringify(fingerprintInput)).slice(0, 16);

attachOptions.instanceRole.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['cloudformation:DescribeStackResource', 'cloudformation:SignalResource'],
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-ec2/lib/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ export class Instance extends Resource implements IInstance {
} finally {
recursing = false;
}
const digest = md5.digest('hex').substr(0, 16);
const digest = md5.digest('hex').slice(0, 16);
return `${originalLogicalId}${digest}`;
},
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ export class ClusterResourceHandler extends ResourceHandler {

private generateClusterName() {
const suffix = this.requestId.replace(/-/g, ''); // 32 chars
const prefix = this.logicalResourceId.substr(0, MAX_CLUSTER_NAME_LEN - suffix.length - 1);
const offset = MAX_CLUSTER_NAME_LEN - suffix.length - 1;
const prefix = this.logicalResourceId.slice(0, offset > 0 ? offset : 0);
return `${prefix}-${suffix}`;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ export class FargateProfileResourceHandler extends ResourceHandler {
*/
private generateProfileName() {
const suffix = this.requestId.replace(/-/g, ''); // 32 chars
const prefix = this.logicalResourceId.substr(0, MAX_NAME_LEN - suffix.length - 1);
const offset = MAX_NAME_LEN - suffix.length - 1;
const prefix = this.logicalResourceId.slice(0, offset > 0 ? offset : 0);
return `${prefix}-${suffix}`;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class HttpsRedirect extends CoreConstruct {
});

domainNames.forEach((domainName) => {
const hash = crypto.createHash('md5').update(domainName).digest('hex').substr(0, 6);
const hash = crypto.createHash('md5').update(domainName).digest('hex').slice(0, 6);
const aliasProps = {
recordName: domainName,
zone: props.zone,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ export class BucketDeployment extends CoreConstruct {
let prefix: string = props.destinationKeyPrefix ?
`:${props.destinationKeyPrefix}` :
'';
prefix += `:${this.cr.node.addr.substr(-8)}`;
prefix += `:${this.cr.node.addr.slice(-8)}`;
const tagKey = CUSTOM_RESOURCE_OWNER_TAG + prefix;

// destinationKeyPrefix can be 104 characters before we hit
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-secretsmanager/lib/secret.ts
Original file line number Diff line number Diff line change
Expand Up @@ -851,8 +851,8 @@ function parseSecretName(construct: IConstruct, secretArn: string) {
// Secret resource names are in the format `${secretName}-${6-character SecretsManager suffix}`
// If there is no hyphen (or 6-character suffix) assume no suffix was provided, and return the whole name.
const lastHyphenIndex = resourceName.lastIndexOf('-');
const hasSecretsSuffix = lastHyphenIndex !== -1 && resourceName.substr(lastHyphenIndex + 1).length === 6;
return hasSecretsSuffix ? resourceName.substr(0, lastHyphenIndex) : resourceName;
const hasSecretsSuffix = lastHyphenIndex !== -1 && resourceName.slice(lastHyphenIndex + 1).length === 6;
return hasSecretsSuffix ? resourceName.slice(0, lastHyphenIndex) : resourceName;
}
throw new Error('invalid ARN format; no secret name provided');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ export class EmrCreateCluster extends sfn.TaskStateBase {
throw new Error(`Step concurrency level must be in range [1, 256], but got ${this.props.stepConcurrencyLevel}.`);
}
if (this.props.releaseLabel && this.props.stepConcurrencyLevel !== 1) {
const [major, minor] = this.props.releaseLabel.substr(4).split('.');
const [major, minor] = this.props.releaseLabel.slice(4).split('.');
if (Number(major) < 5 || (Number(major) === 5 && Number(minor) < 28)) {
throw new Error(`Step concurrency is only supported in EMR release version 5.28.0 and above but got ${this.props.releaseLabel}.`);
}
Expand Down Expand Up @@ -391,8 +391,8 @@ export class EmrCreateCluster extends sfn.TaskStateBase {
* @see https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-release-components.html
*/
private validateReleaseLabel(releaseLabel: string): string {
const prefix = releaseLabel.substr(0, 4);
const versions = releaseLabel.substr(4).split('.');
const prefix = releaseLabel.slice(0, 4);
const versions = releaseLabel.slice(4).split('.');
if (prefix !== 'emr-' || versions.length !== 3 || versions.some((e) => isNotANumber(e))) {
throw new Error(`The release label must be in the format 'emr-x.x.x' but got ${releaseLabel}`);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/cfnspec/build-tools/patch-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ function findPatches(data: any, patchSource: any): Patch[] {
throw new Error(`adjustPath: expected string, got ${JSON.stringify(originalPath)}`);
}
if (originalPath.startsWith('$/')) {
return originalPath.substr(1);
return originalPath.slice(1);
}
return jsonPath.map(p => `/${p}`).join('') + originalPath;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/cfnspec/build-tools/spec-diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ async function main() {

function isSuffix(key: string, suffix: string) {
const index = key.indexOf(suffix);
return index === -1 ? undefined : key.substr(0, index);
return index === -1 ? undefined : key.slice(0, index);
}

function suffixKeys(suffix: string, xs: Record<string, any>): Record<string, any> {
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/cloudformation-diff/lib/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ class Formatter {
*/
function normalizePath(p: string) {
if (p.startsWith('/')) {
p = p.substr(1);
p = p.slice(1);
}

let parts = p.split('/');
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/cloudformation-diff/lib/iam/statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,5 +324,5 @@ export function renderCondition(condition: any): string {
// We can make it more compact without losing information by getting rid of the outermost braces
// and the indentation.
const lines = jsonRepresentation.split('\n');
return lines.slice(1, lines.length - 1).map(s => s.substr(2)).join('\n');
return lines.slice(1, lines.length - 1).map(s => s.slice(2)).join('\n');
}
2 changes: 1 addition & 1 deletion packages/@aws-cdk/core/lib/cfn-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export abstract class CfnRefElement extends CfnElement {

function notTooLong(x: string) {
if (x.length < 100) { return x; }
return x.substr(0, 47) + '...' + x.substr(x.length - 47);
return x.slice(0, 47) + '...' + x.slice(-47);
}

import { CfnReference } from './private/cfn-reference';
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/core/lib/cfn-parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -537,8 +537,8 @@ export class CfnParser {
if (dotIndex === -1) {
throw new Error(`Short-form Fn::GetAtt must contain a '.' in its string argument, got: '${value}'`);
}
logicalId = value.substr(0, dotIndex);
attributeName = value.substr(dotIndex + 1); // the +1 is to skip the actual '.'
logicalId = value.slice(0, dotIndex);
attributeName = value.slice(dotIndex + 1); // the +1 is to skip the actual '.'
stringForm = true;
} else {
// ...or a 2-element list
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/core/lib/cfn-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ export class CfnResource extends CfnRefElement {
const trace = this.creationStack;
if (trace) {
const creationStack = ['--- resource created at ---', ...trace].join('\n at ');
const problemTrace = e.stack.substr(e.stack.indexOf(e.message) + e.message.length);
const problemTrace = e.stack.slice(e.stack.indexOf(e.message) + e.message.length);
e.stack = `${e.message}\n ${creationStack}\n --- problem discovered at ---${problemTrace}`;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/core/lib/custom-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export class CustomResource extends Resource {
function uppercaseProperties(props: { [key: string]: any }) {
const ret: { [key: string]: any } = {};
Object.keys(props).forEach(key => {
const upper = key.substr(0, 1).toUpperCase() + key.substr(1);
const upper = key.slice(0, 1).toUpperCase() + key.slice(1);
ret[upper] = props[key];
});
return ret;
Expand All @@ -201,7 +201,7 @@ function renderResourceType(resourceType?: string) {
throw new Error(`Custom resource type must begin with "Custom::" (${resourceType})`);
}

const typeName = resourceType.substr(resourceType.indexOf('::') + 2);
const typeName = resourceType.slice(resourceType.indexOf('::') + 2);
if (typeName.length > 60) {
throw new Error(`Custom resource type length > 60 (${resourceType})`);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/core/lib/private/region-lookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function deployTimeLookup(stack: Stack, factName: string, lookupMap: Reco
}

function ucfirst(x: string) {
return `${x.substr(0, 1).toUpperCase()}${x.substr(1)}`;
return `${x.slice(0, 1).toUpperCase()}${x.slice(1)}`;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/core/lib/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export class ValidationResult {
if (!this.isSuccess) {
let message = this.errorTree();
// The first letter will be lowercase, so uppercase it for a nicer error message
message = message.substr(0, 1).toUpperCase() + message.substr(1);
message = message.slice(0, 1).toUpperCase() + message.slice(1);
throw new CfnSynthesisError(message);
}
}
Expand Down Expand Up @@ -382,7 +382,7 @@ function isCloudFormationIntrinsic(x: any) {
const keys = Object.keys(x);
if (keys.length !== 1) { return false; }

return keys[0] === 'Ref' || keys[0].substr(0, 4) === 'Fn::';
return keys[0] === 'Ref' || keys[0].slice(0, 4) === 'Fn::';
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/core/test/resource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -915,7 +915,7 @@ class Counter extends CfnResource {
}

function withoutHash(logId: string) {
return logId.substr(0, logId.length - 8);
return logId.slice(0, -8);
}

class CustomizableResource extends CfnResource {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export async function putObject(event: AWSCDKAsyncCustomResource.OnEventRequest)

// trim trailing `/`
if (objectKey.startsWith('/')) {
objectKey = objectKey.substr(1);
objectKey = objectKey.slice(1);
}

const publicRead = event.ResourceProperties[api.PROP_PUBLIC] || false;
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/pipelines/lib/codepipeline/artifact-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ function sanitizeArtifactName(x: string): string {
const maxLength = 100; // Max length of 100 is imposed by CodePipeline library

if (sani.length > maxLength) {
const fingerprint = crypto.createHash('sha256').update(sani).digest('hex').substr(0, 8);
sani = sani.substr(0, maxLength - fingerprint.length) + fingerprint;
const fingerprint = crypto.createHash('sha256').update(sani).digest('hex').slice(0, 8);
sani = sani.slice(0, maxLength - fingerprint.length) + fingerprint;
}

return sani;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ function filterBuildSpecCommands(buildSpec: codebuild.BuildSpec, osType: ec2.Ope
function extractTag(x: any): [string | undefined, any] {
if (typeof x !== 'string') { return [undefined, x]; }
for (const tag of [winTag, linuxTag]) {
if (x.startsWith(tag)) { return [tag, x.substr(tag.length)]; }
if (x.startsWith(tag)) { return [tag, x.slice(tag.length)]; }
}
return [undefined, x];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,5 +342,5 @@ export type AGraphNode = GraphNode<GraphAnnotation>;
export type AGraph = Graph<GraphAnnotation>;

function stripPrefix(s: string, prefix: string) {
return s.startsWith(prefix) ? s.substr(prefix.length) : s;
return s.startsWith(prefix) ? s.slice(prefix.length) : s;
}
2 changes: 1 addition & 1 deletion packages/@aws-cdk/pipelines/lib/legacy/stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ export class StackOutput {
}

function stripPrefix(s: string, prefix: string) {
return s.startsWith(prefix) ? s.substr(prefix.length) : s;
return s.startsWith(prefix) ? s.slice(prefix.length) : s;
}

function isAssetManifest(s: cxapi.CloudArtifact): s is cxapi.AssetManifestArtifact {
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/pipelines/lib/private/identifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ function sanitizeName(x: string): string {
*/
export function limitIdentifierLength(s: string, n: number): string {
if (s.length <= n) { return s; }
const h = hash(s).substr(0, 8);
const h = hash(s).slice(0, 8);
const mid = Math.floor((n - h.length) / 2);

return s.substr(0, mid) + h + s.substr(s.length - mid);
return s.slice(0, mid) + h + s.slice(-mid);
}
2 changes: 1 addition & 1 deletion packages/aws-cdk-migration/lib/rewrite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ function updatedExternalLocation(
return customModulePath;
}

if (options.rewriteCfnImports && modulePath.endsWith(`${options.packageUnscopedName?.substr('aws-'.length)}.generated`)) {
if (options.rewriteCfnImports && modulePath.endsWith(`${options.packageUnscopedName?.slice('aws-'.length)}.generated`)) {
return `${libName}/${options.packageUnscopedName}`;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ async function asyncGlobalReplace(str: string, regex: RegExp, cb: (x: string) =>

start = regex.lastIndex;
}
ret.push(str.substr(start));
ret.push(str.slice(start));

return ret.join('');
}
2 changes: 1 addition & 1 deletion packages/aws-cdk/lib/api/hotswap/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,5 +86,5 @@ export function transformObjectKeys(val: any, transform: (str: string) => string
* This function lower cases the first character of the string provided.
*/
export function lowerCaseFirstCharacter(str: string): string {
return str.length > 0 ? `${str[0].toLowerCase()}${str.substr(1)}` : str;
return str.length > 0 ? `${str[0].toLowerCase()}${str.slice(1)}` : str;
}
Loading