Skip to content

Commit

Permalink
feat: allow truncate with ellipsis
Browse files Browse the repository at this point in the history
  • Loading branch information
alextekartik committed Feb 3, 2025
1 parent 1467343 commit ab177ee
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 5 deletions.
6 changes: 3 additions & 3 deletions lib/src/log_format_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ class LogFormatOptions {
}

/// Truncate a string
String logTruncateString(String value, {int? length}) {
String logTruncateString(String value, {int? length, bool? ellipsis}) {
length ??= logBasicTypeTruncateLength;
if (length != null) {
return value.truncate(length);
return value.truncate(length, ellipsis: ellipsis);
}
return value;
}
Expand Down Expand Up @@ -165,7 +165,7 @@ String logFormat(Object? value, {LogFormatOptions? options}) {
}
options ??= globalLogFormatOptions;
if (options.finalTypeTruncateLength != null) {
return text.truncate(options.finalTypeTruncateLength!);
return text.truncate(options.finalTypeTruncateLength!, ellipsis: true);
}
return text;
}
3 changes: 2 additions & 1 deletion lib/src/string_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ extension TekartikCommonStringExtension on String {
}

/// Truncate at max element.
String truncate(int len) => stringTruncate(this, len)!;
String truncate(int len, {bool? ellipsis}) =>
stringTruncate(this, len, ellipsis: ellipsis)!;

/// Obfuscate a string by replacing all but the first and last 4 characters with '*'.
/// at least half of the characters are obfuscated.
Expand Down
10 changes: 9 additions & 1 deletion lib/string_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,15 @@ String? stringSubString(String? text, int start, [int? end]) {
}

/// Truncate at max element.
String? stringTruncate(String? text, int len) => stringSubString(text, 0, len);
String? stringTruncate(String? text, int len, {bool? ellipsis}) {
if (text != null) {
var existingLen = text.length;
if (existingLen > len) {
return '${text.substring(0, len)}${(ellipsis ?? false) ? '…' : ''}';
}
}
return text;
}

/// Returns an empty string in the worst case
String stringNonNull(String? value, [String? defaultValue = '']) =>
Expand Down
2 changes: 2 additions & 0 deletions test/string_utils_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ void main() {
expect(''.nonEmpty(), isNull);
expect('456'.nonEmpty(), '456');
expect('123'.truncate(2), '12');
expect('123'.truncate(2, ellipsis: true), '12…');
expect('123'.truncate(3, ellipsis: true), '123');
expect('123'.truncate(4), '123');
});
test('stringsCompareWithLastInt', () {
Expand Down

0 comments on commit ab177ee

Please sign in to comment.