rokojori-godot/rokojori-cpp-generator/source/library/Texts.ts

154 lines
3.3 KiB
TypeScript

import path from "path";
import { text } from "stream/consumers";
import { MatchResult } from "./MatchResult";
export class Texts
{
static joinPaths( ...paths:string[] )
{
return path.join.apply( null, paths );
}
static makeSticky( regexp:RegExp )
{
if ( regexp.sticky )
{
return regexp;
}
var source = regexp.source;
var flags = regexp.flags;
if ( flags.indexOf( "y" ) === -1 )
{
flags += "y";
}
return new RegExp( source, flags );
}
static splitLines( text:string )
{
return text.split( /(?:\r\n)|\n|\r/g );
}
static fileName( fullPath:string )
{
return path.basename( fullPath );
}
static splitLinesCaptureBreaks( text:string )
{
return text.split( /((?:\r\n)|\n|\r)/g );
}
static makeGlobal( regexp:RegExp )
{
if ( regexp.global )
{
return regexp;
}
var source = regexp.source;
var flags = regexp.flags;
if ( flags.indexOf( "g" ) === -1 )
{
flags += "g";
}
return new RegExp( source, flags );
}
static replaceAllIn( texts:string[], replacements:Map<string,string> )
{
if ( texts === undefined || texts === null )
{
return texts;
}
let outputTexts = [];
for ( let i = 0; i < texts.length; i++ )
{
outputTexts.push( Texts.replaceAll( texts[ i ], replacements ) );
}
return outputTexts;
}
static replaceAll( text:string, replacements:Map<string,string> )
{
if ( text === undefined || text === null )
{
return text;
}
for ( let [ variable, replacement ] of replacements )
{
let replacementRegexSource = Texts.toRegexSource( variable );
let regex = new RegExp( replacementRegexSource, "g" );
text = text.replace( regex, replacement );
}
return text;
}
static toRegexSource( source:string )
{
source = source.replace( /\./g, "\\." );
source = source.replace( /\(/g, "\\(" );
source = source.replace( /\)/g, "\\)" );
source = source.replace( /\[/g, "\\[" );
source = source.replace( /\]/g, "\\]" );
source = source.replace( /\^/g, "\\^" );
source = source.replace( /\$/g, "\\$" );
source = source.replace( /\*/g, "\\*" );
source = source.replace( /\+/g, "\\+" );
source = source.replace( /\-/g, "\\-" );
source = source.replace( /\?/g, "\\?" );
source = source.replace( /\//g, "\\/" );
source = source.replace( /\|/g, "\\|" );
return source;
}
static getMatches( source:string, regex:RegExp, type:string = null )
{
regex = this.makeGlobal( regex );
let offset = 0;
let matches:MatchResult[] = [];
while ( offset < source.length )
{
regex.lastIndex = offset;
let result = regex.exec( source );
let match = result ? result[ 0 ] : null;
if ( result && result.index != offset && match.length > 0)
{
offset = result.index + match.length;
matches.push( { match:match, index: result.index, type:type } );
}
else
{
return matches;
}
}
return matches;
}
static insertText( sourceText:string, insertText:string, insertPosition:number )
{
let before = sourceText.substring( 0, insertPosition );
let after = sourceText.substring( insertPosition, sourceText.length );
return before + insertText + after;
}
}