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

new feature: options.truncate length or cb fn #60

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,16 @@ Options:
a function, the function will be called with the invalid characters and it's
return value will be used as the replacement. See [`String.prototype.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
for more info.

* `options.truncateLength`: *optional, number, default: `255`*. Used in truncate call
to reduce string to the specified length. If <=0, returns ''.

* `options.preserveFileExt`: *optional, boolean, default: `false`*. By default,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could default to keeping the file extension and not make it configurable for now.. it's a breaking change either way and I'm not sure anyone will miss the old behaviour :)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @joelmukuthu.

I think preserveFileExt can be true by default and that we don't even need it to be an option. Are there use cases where you wouldn't want this behavior?

I think it's ok for the exact strings this module produces to change between minor versions. I would consider changing things like the 255 default max length a breaking change, but tweaks to the exact string produced can be a minor version change.

Open to other perspectives on this.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. As long as it produces 255-chatacter (max) filenames, it shouldn't be a breaking change. My only concern was for users who may use this in tests and have hard-coded some strings. All the same, truncating the file extension away is a bug so technically this is a bug fix.

string is trimmed to the `options.truncateLength` length. If true, file extension
is preserved within the `options.truncateLength` bounds, unless extension is
longer then `options.truncateLength` then the result is just the extension trimmed
to the `options.truncateLength` length. Note: extensions is parsed using
`path.extname` and as such the leading '.' in the extension name, unless it's a
'dot-file' in which case the extension is empty. Note that one exception is files
that end with a "." - such pattern is transformed away using `options.replacement`
(default: stripped away).
Comment on lines +108 to +116
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice thorough explanation of edge cases. Even if we remove this as an option, I think this information in the readme would be useful.

2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ declare function sanitize(
input: string,
options?: {
replacement?: string | ((substring: string) => string);
truncateLength?: number;
preserveFileExt?: boolean;
}
): string;

Expand Down
19 changes: 14 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
* Replaces characters in strings that are illegal/unsafe for filenames.
* Unsafe characters are either removed or replaced by a substitute set
* in the optional `options` object.
*
* Additionally, you can pass alternative truncation length (default: 255)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a little update :)

* or function (default: `require("truncate-utf8-bytes")`),
* via the `truncate` attribute of the optional `options` object.
*
* Illegal Characters on Various Operating Systems
* / ? < > \ : * | "
Expand All @@ -24,19 +28,20 @@
* http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs
*
* @param {String} input Original filename
* @param {Object} options {replacement: String | Function }
* @param {Object} options {replacement: String | Function, truncate: String | Function}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

truncateLength: Number

* @return {String} Sanitized filename
*/

var truncate = require("truncate-utf8-bytes");
var extname = require("path").extname;

var illegalRe = /[\/\?<>\\:\*\|"]/g;
var controlRe = /[\x00-\x1f\x80-\x9f]/g;
var reservedRe = /^\.+$/;
var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
var windowsTrailingRe = /[\. ]+$/;

function sanitize(input, replacement) {
function sanitize(input, replacement, truncateLength, preserveFileExt) {
if (typeof input !== 'string') {
throw new Error('Input must be string');
}
Expand All @@ -46,14 +51,18 @@ function sanitize(input, replacement) {
.replace(reservedRe, replacement)
.replace(windowsReservedRe, replacement)
.replace(windowsTrailingRe, replacement);
return truncate(sanitized, 255);
return preserveFileExt ?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm.. I think we shouldn't touch the extension while truncating. In my view, the algorithm here would be something like:

  • split out the extension, if any
  • subtract the length of the extension (including the dot) from truncateLength. If there's no extension, then truncate the entire string
  • if greater, truncate the filename (without the dot and extension) to the length calculated in the previous step
  • re-join the truncated filename with the extension

As a bonus, it would be nice to only truncate if the length of the filename exceeds truncaeLength in both cases

truncate(sanitized, Math.max(0, truncateLength - extname(sanitized).length)) + truncate(extname(sanitized), truncateLength)
: truncate(sanitized, truncateLength);
Comment on lines +54 to +56
Copy link
Owner

@parshap parshap Aug 2, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This ternary is a bit hairy. An if/else and some intermediate variables might make it more readable.

if (preserveFileExt) {
  var maxBaseLength = Math.max(0, truncateLength - extname(sanitized).length);
  var truncatedBase = truncate(sanitized, maxBaseLength);
  var truncatedExt = truncate(extname(sanitized), truncateLength);
  return truncatedBase + truncatedExt;
} else {
  return truncate(sanitized, truncateLength);
}

}

module.exports = function (input, options) {
var replacement = (options && options.replacement) || '';
var output = sanitize(input, replacement);
var preserveFileExt = (options && options.preserveFileExt) || false;
var truncateLength = (options && typeof options.truncateLength == typeof 0) ? options.truncateLength : 255;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

options.truncateLength === 'number' works better than options.truncateLength == typeof 0 here ;)

var output = sanitize(input, replacement, truncateLength, preserveFileExt);
if (replacement === '') {
return output;
}
return sanitize(output, '');
return sanitize(output, '', truncateLength, preserveFileExt);
};
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,21 @@ test("255 characters max", function(t) {
t.end();
});

test("variable length, include/exclude file extension", function(t) {
t.ok(sanitize("01234567.89A", { truncateLength: 8+1+3 }) == "01234567.89A");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: t.equal() produces better error messages and is how other tests are written.

t.ok(sanitize("0123456789ABC.DEF", { truncateLength: 8+1+3, preserveFileExt: true }) == "01234567.DEF");
t.ok(sanitize("\u000001234567.89ABCDEF", { truncateLength: 8+1+3, preserveFileExt: true }) == "012.89ABCDEF");
t.ok(sanitize("\u000001234567.89ABCDEF", { truncateLength: 8+1+3, preserveFileExt: false }) == "01234567.89A");
t.ok(sanitize("\u000001234567", { truncateLength: 4, preserveFileExt: true }) == "0123");
t.ok(sanitize("\u000001234567.", { truncateLength: 1, preserveFileExt: true }) == "0");
t.ok(sanitize("\u000001234567.", { replacement: "XYZ", truncateLength: 2, preserveFileExt: true }) == "XY");
t.ok(sanitize("\u000001234567.89ABCDEF", { truncateLength: 0, preserveFileExt: true }) == "");
t.ok(sanitize("\u0000", { truncateLength: 255, preserveFileExt: true }) == "");
t.ok(sanitize("\u00000123.ABCD", { truncateLength: 4, preserveFileExt: true }) == ".ABC");
t.ok(sanitize("01234567.89A", { truncateLength: -12 }) == "");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test case like the following? I believe there's a bug in the extension logic.

  t.ok(sanitize("01234567.89A", { preserveFileExt: true }) == "01234567.89A");

t.end();
});

// Test the handling of non-BMP chars in UTF-8
//

Expand Down