Allow non-ascii app names like 微信读书 (fix #1056) (#1207)

* Resolves #1056 Allow non-ascii app names like 微信读书

* Update src/utils/sanitizeFilename.ts

Co-authored-by: Ronan Jouchet <ronan@jouchet.fr>

* Fix prettier

Co-authored-by: Ronan Jouchet <ronan@jouchet.fr>
This commit is contained in:
Adam Weeden 2021-05-31 23:27:32 -04:00 committed by GitHub
parent 6c55e1a9a1
commit 86a27d4f39
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 16 deletions

View File

@ -1,17 +1,25 @@
import { sanitizeFilename } from './sanitizeFilename';
import { DEFAULT_APP_NAME } from '../constants';
describe('replacing non ascii characters', () => {
const nonAscii = '<27>';
test('it should return a result without non ascii characters', () => {
const param = `${nonAscii}abc`;
describe('replacing reserved characters', () => {
const reserved = '\\/?*<>:|';
test('it should return a result without reserved characters', () => {
const expectedResult = 'abc';
const param = `${reserved}${expectedResult}`;
const result = sanitizeFilename('', param);
expect(result).toBe(expectedResult);
});
describe('when the result of replacing these characters is empty', () => {
const result = sanitizeFilename('', nonAscii);
test('it should allow non-ascii characters', () => {
const expectedResult = '微信读书';
const param = `${reserved}${expectedResult}`;
const result = sanitizeFilename('', param);
expect(result).toBe(expectedResult);
});
test('when the result of replacing these characters is empty, use default', () => {
const result = sanitizeFilename('', reserved);
expect(result).toBe(DEFAULT_APP_NAME);
});
});

View File

@ -1,27 +1,25 @@
import * as log from 'loglevel';
import sanitize = require('sanitize-filename');
import { DEFAULT_APP_NAME } from '../constants';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const sanitize = require('sanitize-filename');
export function sanitizeFilename(
platform: string,
filenameToSanitize: string,
): string {
let result: string = sanitize(filenameToSanitize);
// remove all non ascii / file-problematic chars, or use default app name
/* eslint-disable no-control-regex */
result =
result.replace(/[^\x00-\x7F]/g, '').replace(/[/,;.\\]/g, '') ||
DEFAULT_APP_NAME;
/* eslint-enable no-control-regex */
// spaces will cause problems with Ubuntu when pinned to the dock
if (platform === 'linux') {
result = result.replace(/\s/g, '');
}
if (!result || result === '') {
result = DEFAULT_APP_NAME;
log.warn(
'Falling back to default app name as result of filename sanitization. Use flag "--name" to set a name',
);
}
log.debug(`Sanitized filename for ${filenameToSanitize} : ${result}`);
return result;
}