Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 59b9348

Browse files
CommanderRooterezrokah
andauthoredMar 28, 2022
chore: replace deprecated String.prototype.substr() (decaporg#6333)
* chore: replace deprecated String.prototype.substr() .substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated Signed-off-by: Tobias Speicher <[email protected]> * refactor: add prefer slice lint rule and fix errors Co-authored-by: erezrokah <[email protected]>
1 parent de624a9 commit 59b9348

File tree

20 files changed

+157
-106
lines changed

20 files changed

+157
-106
lines changed
 

‎.eslintrc.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,9 @@ module.exports = {
5151
destructuring: 'all',
5252
},
5353
],
54+
'unicorn/prefer-string-slice': 'error',
5455
},
55-
plugins: ['babel', '@emotion', 'cypress'],
56+
plugins: ['babel', '@emotion', 'cypress', 'unicorn'],
5657
settings: {
5758
react: {
5859
version: 'detect',

‎dev-test/backends/test/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@
183183
h('h2', {}, 'Related Post'),
184184
h('h3', {}, post.get('title')),
185185
h('img', { src: post.get('image') }),
186-
h('p', {}, post.get('body', '').substr(0, 100) + '...'),
186+
h('p', {}, post.get('body', '').slice(0, 100) + '...'),
187187
) : null;
188188
}
189189
});

‎dev-test/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@
183183
h('h2', {}, 'Related Post'),
184184
h('h3', {}, post.get('title')),
185185
h('img', { src: post.get('image') }),
186-
h('p', {}, post.get('body', '').substr(0, 100) + '...'),
186+
h('p', {}, post.get('body', '').slice(0, 100) + '...'),
187187
) : null;
188188
}
189189
});

‎package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,11 +128,12 @@
128128
"cypress-jest-adapter": "^0.1.1",
129129
"cypress-plugin-tab": "^1.0.0",
130130
"dotenv": "^10.0.0",
131-
"eslint": "^7.0.0",
131+
"eslint": "^8.12.0",
132132
"eslint-plugin-cypress": "^2.6.0",
133133
"eslint-plugin-import": "^2.18.2",
134134
"eslint-plugin-prettier": "^4.0.0",
135135
"eslint-plugin-react": "^7.17.0",
136+
"eslint-plugin-unicorn": "^41.0.1",
136137
"execa": "^5.0.0",
137138
"friendly-errors-webpack-plugin": "^1.7.0",
138139
"fs-extra": "^10.0.0",

‎packages/netlify-cms-backend-azure/src/API.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ export default class API {
293293
fromBase64 = (str: string) => Base64.decode(str);
294294

295295
branchToRef = (branch: string): string => `refs/heads/${branch}`;
296-
refToBranch = (ref: string): string => ref.substr('refs/heads/'.length);
296+
refToBranch = (ref: string): string => ref.slice('refs/heads/'.length);
297297

298298
user = async () => {
299299
const result = await this.requestJSON<AzureUser>({

‎packages/netlify-cms-backend-github/src/API.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ export default class API {
361361
return parseContentKey(contentKey);
362362
}
363363

364-
return parseContentKey(contentKey.substring(this.repo.length + 1));
364+
return parseContentKey(contentKey.slice(this.repo.length + 1));
365365
}
366366

367367
checkMetadataRef() {
@@ -728,7 +728,7 @@ export default class API {
728728

729729
async migrateToVersion1(pullRequest: GitHubPull, metadata: Metadata) {
730730
// hard code key/branch generation logic to ignore future changes
731-
const oldContentKey = pullRequest.head.ref.substring(`cms/`.length);
731+
const oldContentKey = pullRequest.head.ref.slice(`cms/`.length);
732732
const newContentKey = `${metadata.collection}/${oldContentKey}`;
733733
const newBranchName = `cms/${newContentKey}`;
734734

@@ -765,7 +765,7 @@ export default class API {
765765
async migrateToPullRequestLabels(pullRequest: GitHubPull, metadata: Metadata) {
766766
await this.setPullRequestStatus(pullRequest, metadata.status);
767767

768-
const contentKey = pullRequest.head.ref.substring(`cms/`.length);
768+
const contentKey = pullRequest.head.ref.slice(`cms/`.length);
769769
await this.deleteMetadata(contentKey);
770770
}
771771

@@ -829,7 +829,7 @@ export default class API {
829829
// open authoring branches can exist without a pr
830830
const cmsBranches: Octokit.GitListMatchingRefsResponse =
831831
await this.getOpenAuthoringBranches();
832-
branches = cmsBranches.map(b => b.ref.substring('refs/heads/'.length));
832+
branches = cmsBranches.map(b => b.ref.slice('refs/heads/'.length));
833833
// filter irrelevant branches
834834
const branchesWithFilter = await Promise.all(
835835
branches.map(b => this.filterOpenAuthoringBranches(b)),

‎packages/netlify-cms-backend-github/src/__tests__/API.spec.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ describe('github API', () => {
1111

1212
function mockAPI(api, responses) {
1313
api.request = jest.fn().mockImplementation((path, options = {}) => {
14-
const normalizedPath = path.indexOf('?') !== -1 ? path.substr(0, path.indexOf('?')) : path;
14+
const normalizedPath = path.indexOf('?') !== -1 ? path.slice(0, path.indexOf('?')) : path;
1515
const response = responses[normalizedPath];
1616
return typeof response === 'function'
1717
? Promise.resolve(response(options))

‎packages/netlify-cms-core/src/backend.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ function prepareMetaPath(path: string, collection: Collection) {
292292
return path;
293293
}
294294
const dir = dirname(path);
295-
return dir.substr(collection.get('folder')!.length + 1) || '/';
295+
return dir.slice(collection.get('folder')!.length + 1) || '/';
296296
}
297297

298298
function collectionDepth(collection: Collection) {

‎packages/netlify-cms-core/src/components/Collection/Entries/EntriesCollection.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,15 +117,15 @@ export class EntriesCollection extends React.Component {
117117

118118
export function filterNestedEntries(path, collectionFolder, entries) {
119119
const filtered = entries.filter(e => {
120-
const entryPath = e.get('path').substring(collectionFolder.length + 1);
120+
const entryPath = e.get('path').slice(collectionFolder.length + 1);
121121
if (!entryPath.startsWith(path)) {
122122
return false;
123123
}
124124

125125
// only show immediate children
126126
if (path) {
127127
// non root path
128-
const trimmed = entryPath.substring(path.length + 1);
128+
const trimmed = entryPath.slice(path.length + 1);
129129
return trimmed.split('/').length === 2;
130130
} else {
131131
// root path

‎packages/netlify-cms-core/src/components/Collection/NestedCollection.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ export function getTreeData(collection, entries) {
144144
const rootFolder = '/';
145145
const entriesObj = entries
146146
.toJS()
147-
.map(e => ({ ...e, path: e.path.substring(collectionFolder.length) }));
147+
.map(e => ({ ...e, path: e.path.slice(collectionFolder.length) }));
148148

149149
const dirs = entriesObj.reduce((acc, entry) => {
150150
let dir = dirname(entry.path);

‎packages/netlify-cms-core/src/formats/frontmatter.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,16 @@ const parsers = {
2727
parse: (input: string) => {
2828
let JSONinput = input.trim();
2929
// Fix JSON if leading and trailing brackets were trimmed.
30-
if (JSONinput.substr(0, 1) !== '{') {
30+
if (JSONinput.slice(0, 1) !== '{') {
3131
JSONinput = '{' + JSONinput + '}';
3232
}
3333
return jsonFormatter.fromFile(JSONinput);
3434
},
3535
stringify: (metadata: object) => {
3636
let JSONoutput = jsonFormatter.toFile(metadata).trim();
3737
// Trim leading and trailing brackets.
38-
if (JSONoutput.substr(0, 1) === '{' && JSONoutput.substr(-1) === '}') {
38+
if (JSONoutput.slice(0, 1) === '{' && JSONoutput.slice(-1) === '}') {
39+
// eslint-disable-next-line unicorn/prefer-string-slice
3940
JSONoutput = JSONoutput.substring(1, JSONoutput.length - 1);
4041
}
4142
return JSONoutput;
@@ -54,8 +55,9 @@ const parsers = {
5455
};
5556

5657
function inferFrontmatterFormat(str: string) {
57-
const firstLine = str.substr(0, str.indexOf('\n')).trim();
58-
if (firstLine.length > 3 && firstLine.substr(0, 3) === '---') {
58+
// eslint-disable-next-line unicorn/prefer-string-slice
59+
const firstLine = str.substring(0, str.indexOf('\n')).trim();
60+
if (firstLine.length > 3 && firstLine.slice(0, 3) === '---') {
5961
// No need to infer, `gray-matter` will handle things like `---toml` for us.
6062
return;
6163
}
@@ -130,6 +132,7 @@ export class FrontmatterFormatter {
130132
comments,
131133
...format,
132134
});
135+
// eslint-disable-next-line unicorn/prefer-string-slice
133136
return trimLastLineBreak && file.slice(-1) === '\n' ? file.substring(0, file.length - 1) : file;
134137
}
135138
}

‎packages/netlify-cms-core/src/lib/textHelper.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@ export function stringToRGB(str) {
77

88
const c = (hash & 0x00ffffff).toString(16).toUpperCase();
99

10+
// eslint-disable-next-line unicorn/prefer-string-slice
1011
return '00000'.substring(0, 6 - c.length) + c;
1112
}

‎packages/netlify-cms-lib-util/src/APIUtils.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export function isCMSLabel(label: string, labelPrefix: string) {
1313
}
1414

1515
export function labelToStatus(label: string, labelPrefix: string) {
16-
return label.substr(getLabelPrefix(labelPrefix).length);
16+
return label.slice(getLabelPrefix(labelPrefix).length);
1717
}
1818

1919
export function statusToLabel(status: string, labelPrefix: string) {
@@ -26,11 +26,11 @@ export function generateContentKey(collectionName: string, slug: string) {
2626

2727
export function parseContentKey(contentKey: string) {
2828
const index = contentKey.indexOf('/');
29-
return { collection: contentKey.substr(0, index), slug: contentKey.substr(index + 1) };
29+
return { collection: contentKey.slice(0, index), slug: contentKey.slice(index + 1) };
3030
}
3131

3232
export function contentKeyFromBranch(branch: string) {
33-
return branch.substring(`${CMS_BRANCH_PREFIX}/`.length);
33+
return branch.slice(`${CMS_BRANCH_PREFIX}/`.length);
3434
}
3535

3636
export function branchFromContentKey(contentKey: string) {

‎packages/netlify-cms-lib-util/src/path.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ export function basename(p: string, ext = '') {
3636
}
3737
// Remove the extension, if need be.
3838
if (ext.length > 0) {
39-
const lastPartExt = lastPart.substr(lastPart.length - ext.length);
39+
const lastPartExt = lastPart.slice(-ext.length);
4040
if (lastPartExt === ext) {
41-
return lastPart.substr(0, lastPart.length - ext.length);
41+
return lastPart.slice(0, -ext.length);
4242
}
4343
}
4444
return lastPart;
@@ -68,7 +68,7 @@ export function fileExtensionWithSeparator(p: string) {
6868
if (i === -1 || i === 0) {
6969
return '';
7070
}
71-
return p.substr(i);
71+
return p.slice(i);
7272
}
7373

7474
/**
@@ -82,5 +82,5 @@ export function fileExtensionWithSeparator(p: string) {
8282
*/
8383
export function fileExtension(p: string) {
8484
const ext = fileExtensionWithSeparator(p);
85-
return ext === '' ? ext : ext.substr(1);
85+
return ext === '' ? ext : ext.slice(1);
8686
}

‎packages/netlify-cms-lib-widgets/src/stringTemplate.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ function getExplicitFieldReplacement(key: string, data: Map<string, unknown>) {
135135
if (!key.startsWith(FIELD_PREFIX)) {
136136
return;
137137
}
138-
const fieldName = key.substring(FIELD_PREFIX.length);
138+
const fieldName = key.slice(FIELD_PREFIX.length);
139139
const value = data.getIn(keyToPathArray(fieldName));
140140
if (typeof value === 'object' && value !== null) {
141141
return JSON.stringify(value);
@@ -241,7 +241,7 @@ export function addFileTemplateFields(entryPath: string, fields: Map<string, str
241241
fields = fields.withMutations(map => {
242242
map.set('dirname', dirnameExcludingFolder);
243243
map.set('filename', filename);
244-
map.set('extension', extension === '' ? extension : extension.substr(1));
244+
map.set('extension', extension === '' ? extension : extension.slice(1));
245245
});
246246

247247
return fields;

‎packages/netlify-cms-proxy-server/src/middlewares/utils/fs.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export async function listRepoFiles(
2929
depth: number,
3030
) {
3131
const files = await listFiles(path.join(repoPath, folder), extension, depth);
32-
return files.map(f => f.substr(repoPath.length + 1));
32+
return files.map(f => f.slice(repoPath.length + 1));
3333
}
3434

3535
export async function writeFile(filePath: string, content: Buffer | string) {

‎packages/netlify-cms-widget-file/src/withFileControl.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,7 @@ export default function withFileControl({ forImage } = {}) {
319319
if (!value || value.length <= size) {
320320
return value;
321321
}
322+
// eslint-disable-next-line unicorn/prefer-string-slice
322323
const text = `${value.substring(0, size / 2)}\u2026${value.substring(
323324
value.length - size / 2 + 1,
324325
value.length,

‎packages/netlify-cms-widget-markdown/src/serializers/slateRemark.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,9 @@ export default function slateToRemark(raw, { voidCodeBlock }) {
177177
const index = node.text.search(exp);
178178
if (index > -1) {
179179
const substringIndex = trailing ? index : index + 1;
180+
// eslint-disable-next-line unicorn/prefer-string-slice
180181
const firstSplit = node.text.substring(0, substringIndex);
182+
// eslint-disable-next-line unicorn/prefer-string-slice
181183
const secondSplit = node.text.substring(substringIndex);
182184
const whitespace = trailing ? secondSplit : firstSplit;
183185
const text = trailing ? firstSplit : secondSplit;

‎scripts/webpack.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ function baseConfig({ target = isProduction ? 'umd' : 'umddir' } = {}) {
138138
* Exclude peer dependencies from package bundles.
139139
*/
140140
externals:
141-
target.substr(0, 3) === 'umd'
141+
target.slice(0, 3) === 'umd'
142142
? umdExternals
143143
: (context, request, cb) => {
144144
const externals = Object.keys(pkg.peerDependencies || {});

‎yarn.lock

Lines changed: 119 additions & 77 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)
Please sign in to comment.