123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- export function dedentBlockStringValue(rawString: string): string {
-
- const lines = rawString.split(/\r\n|[\n\r]/g);
-
- const commonIndent = getBlockStringIndentation(lines);
- if (commonIndent !== 0) {
- for (let i = 1; i < lines.length; i++) {
- lines[i] = lines[i].slice(commonIndent);
- }
- }
-
- while (lines.length > 0 && isBlank(lines[0])) {
- lines.shift();
- }
- while (lines.length > 0 && isBlank(lines[lines.length - 1])) {
- lines.pop();
- }
-
- return lines.join('\n');
- }
- export function getBlockStringIndentation(
- lines: $ReadOnlyArray<string>,
- ): number {
- let commonIndent = null;
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i];
- const indent = leadingWhitespace(line);
- if (indent === line.length) {
- continue;
- }
- if (commonIndent === null || indent < commonIndent) {
- commonIndent = indent;
- if (commonIndent === 0) {
- break;
- }
- }
- }
- return commonIndent === null ? 0 : commonIndent;
- }
- function leadingWhitespace(str) {
- let i = 0;
- while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {
- i++;
- }
- return i;
- }
- function isBlank(str) {
- return leadingWhitespace(str) === str.length;
- }
- export function printBlockString(
- value: string,
- indentation?: string = '',
- preferMultipleLines?: boolean = false,
- ): string {
- const isSingleLine = value.indexOf('\n') === -1;
- const hasLeadingSpace = value[0] === ' ' || value[0] === '\t';
- const hasTrailingQuote = value[value.length - 1] === '"';
- const hasTrailingSlash = value[value.length - 1] === '\\';
- const printAsMultipleLines =
- !isSingleLine ||
- hasTrailingQuote ||
- hasTrailingSlash ||
- preferMultipleLines;
- let result = '';
-
- if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {
- result += '\n' + indentation;
- }
- result += indentation ? value.replace(/\n/g, '\n' + indentation) : value;
- if (printAsMultipleLines) {
- result += '\n';
- }
- return '"""' + result.replace(/"""/g, '\\"""') + '"""';
- }
|