public void BuildBox(string content, string LeftButtonKey, string RightButtonKey, UnityAction leftButtonClickEvent, UnityAction rightButtonClickEvent, string TitleKey = "") { Title.enabled = false; Content.enabled = false; Title.LocalizedText.Key = TitleKey; Content.text = content; TextReplacer tmp1 = Selectables[0].GetComponentInChildren <TextReplacer>(); tmp1.LocalizedText.Key = LeftButtonKey; tmp1.enabled = false; Selectables[0].onClick.AddListener(leftButtonClickEvent); TextReplacer tmp2 = Selectables[1].GetComponentInChildren <TextReplacer>(); tmp2.LocalizedText.Key = RightButtonKey; tmp2.enabled = false; Selectables[1].onClick.AddListener(rightButtonClickEvent); Title.enabled = true; Content.enabled = true; tmp1.enabled = true; tmp2.enabled = true; }
static void Main(string[] args) { var n = DateTime.Now; var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second)); tempDi.Create(); File.Copy("../../Test01.pptx", Path.Combine(tempDi.FullName, "Test01out.pptx")); using (PresentationDocument pDoc = PresentationDocument.Open(Path.Combine(tempDi.FullName, "Test01out.pptx"), true)) { TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", true); } File.Copy("../../Test02.pptx", Path.Combine(tempDi.FullName, "Test02out.pptx")); using (PresentationDocument pDoc = PresentationDocument.Open(Path.Combine(tempDi.FullName, "Test02out.pptx"), true)) { TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", true); } File.Copy("../../Test03.pptx", Path.Combine(tempDi.FullName, "Test03out.pptx")); using (PresentationDocument pDoc = PresentationDocument.Open(Path.Combine(tempDi.FullName, "Test03out.pptx"), true)) { TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", false); } }
protected override void ProcessRecord() { foreach (var document in AllDocuments("Set-OpenXmlString")) { try { if (!(document is WmlDocument) && !(document is PmlDocument)) { throw new PowerToolsDocumentException("Not a supported document."); } if (document is WmlDocument) { OutputDocument(TextReplacer.SearchAndReplace((WmlDocument)document, Pattern, Replace, CaseSensitive)); } if (document is PmlDocument) { OutputDocument(TextReplacer.SearchAndReplace((PmlDocument)document, Pattern, Replace, CaseSensitive)); } } catch (Exception e) { WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, document)); } } }
public void ShouldReturnOriginalTextIfNoVariables() { var replacer = new TextReplacer(); var variables = new Mock<ITextVariables>(); variables.Setup(v => v["host"]).Returns("example.com"); Assert.That(replacer.ReplaceVariables("http://example.com/blah/blah", variables.Object), Is.EqualTo("http://example.com/blah/blah")); }
public void ReplaceIn_DontCommit() { // Copy binary files over to test that they're skipped new FileCopier( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), WorkingDirectory ).Copy("*.dll"); var testFileName = Path.Combine(CurrentDirectory, "TestFolder/HelloWorld/TestFile.txt"); var testFileContent = "Hello World"; var searchText = "World"; var replacementText = "Universe"; DirectoryChecker.EnsureDirectoryExists(Path.GetDirectoryName(testFileName)); File.WriteAllText(testFileName, testFileContent); var replacer = new TextReplacer(); replacer.ReplaceIn(Path.Combine(CurrentDirectory, "TestFolder"), "**", searchText, replacementText, false); var newText = File.ReadAllText(testFileName); Assert.IsTrue(File.Exists(testFileName), "File name must have been changed when it shouldn't have."); Assert.IsFalse( newText.Contains(replacementText), "The replacement text was found when it shouldn't have been." ); }
public override bool Run(string[] args) { Console.WriteLine(""); Console.WriteLine("Replacing text in files..."); Console.WriteLine(""); var replacer = new TextReplacer(); var commit = Arguments.ContainsAny("c", "commit"); var text = args[0]; var replacementText = args[1]; var patterns = new string[] { "*" }; // TODO: Should this be "**" to search sub directories? if (Arguments.ContainsAny("f", "files")) { patterns = Arguments["f", "files"].Split(';'); } replacer.ReplaceIn(CurrentDirectory, patterns, text, replacementText, commit); return(!IsError); }
public static void WordTextReplacer(string filePath, string key, string value, bool b) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { TextReplacer.SearchAndReplace(doc, key, value, b); } }
public void PowerPoint(string filePath) { var outFile = Path.Combine(TempDir, Path.GetFileName(filePath).Replace(".pptx", "out.pptx")); File.Copy(GetFilePath(filePath), outFile); using var pDoc = PresentationDocument.Open(outFile, true); TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", true); }
/// <summary> /// Support UTF8 /// Create list files /// </summary> /// <param name="zip">Zip.</param> /// <param name="zipPath">Zip path.</param> /// <param name="srcDir">Source dir.</param> /// <param name="srcFiles">Source files.</param> /// <param name="deleteSrcFiles">If set to <c>true</c> delete source files.</param> /// <param name="removedFiles">remove files are added to the list file</param> public static void CreateZipAndList(this FastZip zip, string zipPath, string srcDir, IEnumerable <FileInfo> srcFiles, bool deleteSrcFiles, IEnumerable <string> removedFiles = null) { string zipName = PathUtil.GetFileNameWithoutExt(zipPath) + ".zip"; // Compress List <string> paths = new List <string>(); foreach (FileInfo f in srcFiles) { paths.Add(f.FullName); } // Generate MD5 digest for assets StringBuilder zipFilter = new StringBuilder(); StringBuilder fileListStr = new StringBuilder(); fileListStr.Append(DownloadList.ZIP_HEADER).Append(zipName).Append("\n"); // create zip filter and file list foreach (FileInfo f in srcFiles) { string fullPath = f.FullName; string relativePath = PathUtil.GetRelativePath(fullPath, srcDir); zipFilter.Append(relativePath).Append("$;"); fileListStr.Append(DownloadList.ZIP_ENTRY_HEADER); AddDigest(fileListStr, relativePath, fullPath); } // add remove list foreach (string r in removedFiles) { fileListStr.Append(DownloadList.DELETE_HEADER).Append(r).Append("\n"); } zipFilter.Replace(@"\", @"\\"); // Zipping TextReplacer replace = new TextReplacer(); replace.AddReplaceToken(@"\(", @"\("); replace.AddReplaceToken(@"\)", @"\)"); replace.AddReplaceToken(@"\+", @"\+"); replace.AddReplaceToken(@"\.", @"\."); ZipEntryFactory ef = zip.EntryFactory as ZipEntryFactory; ef.IsUnicodeText = true; string filter = replace.Replace(zipFilter.ToString()); UnityEngine.Debug.Log("srcdir:" + srcDir); UnityEngine.Debug.Log("filter:" + filter); zip.CreateZip(zipPath, srcDir, true, filter); if (deleteSrcFiles) { foreach (string deletePath in paths) { File.Delete(PathUtil.Combine(PathUtil.Combine(srcDir, deletePath))); } } File.WriteAllText(PathUtil.ReplaceExtension(zipPath, ".bytes"), fileListStr.ToString()); }
private void ExecuteReplacedMode() { Viewer displayer = new Viewer(string.Format("Count of" + " replaced string \n<{0}>", _args[0])); //todo Replacer stringReplacer = new TextReplacer(_args[0], 1000); //todo const stringReplacer.ReplaceString(_args[1], _args[2]); displayer.ShowMessage(stringReplacer.ReplacementsCount); }
string CheckReplaceTargetText(string displayText, string targetText) { int nowCharCount = displayText.Length; string check = TextReplacer.CheckReplace_reading(targetText.Substring(nowCharCount)); if (!string.IsNullOrEmpty(check)) { _textCommandList[check]?.Invoke(); targetText = TextReplacer.ReplaceText_reading(targetText); } return(targetText); }
public void ShouldEscapeDoubleBraces() { var replacer = new TextReplacer(); var variables = new Mock<ITextVariables>(); variables.Setup(v => v["host"]).Returns("example.com"); Assert.That(replacer.ReplaceVariables("http://{{host}}/blah/blah", variables.Object), Is.EqualTo("http://{host}/blah/blah")); Assert.That(replacer.ReplaceVariables("http://{{host}", variables.Object), Is.EqualTo("http://{host}")); Assert.That(replacer.ReplaceVariables("http://{", variables.Object), Is.EqualTo("http://{")); Assert.That(replacer.ReplaceVariables("http://}}", variables.Object), Is.EqualTo("http://}")); Assert.That(replacer.ReplaceVariables("http://{{", variables.Object), Is.EqualTo("http://{")); Assert.That(replacer.ReplaceVariables("http://{{{host}}}/blah/blah", variables.Object), Is.EqualTo("http://{example.com}/blah/blah")); Assert.That(replacer.ReplaceVariables("{{http://host/blah/blah", variables.Object), Is.EqualTo("{http://host/blah/blah")); }
string RepalceData(string text) { var tempText = text; string check = TextReplacer.CheckReplace_before(tempText); while (!string.IsNullOrEmpty(check)) { var replace = TextReplacer.GetReplaceContent_before(check); tempText = TextReplacer.ReplaceText_before(tempText, replace); check = TextReplacer.CheckReplace_before(tempText); } return(tempText); }
static void Main() { var sw = new Stopwatch(); sw.Restart(); var txt = new TextFile(@"C:\Temp\B1.html"); var str = txt.ReadText(); Console.WriteLine("new txt, read" + sw.ElapsedTicks); sw.Restart(); var s = new TextReplacer(str); Console.WriteLine("new TextReplacer" + sw.ElapsedTicks); sw.Restart(); var pat = "<span(.+?)</span>"; //"#bookmark(\\d+?\")(.+?)bookmark\\1";//"<span(.+?)</span>"; var regex = new RegexProcessor(pat); var rep = new Replacement(@"\1"); //(@"#b\1\2b\1");//(@"12345\1=234567"); Console.WriteLine("new regex/repl" + sw.ElapsedTicks); sw.Restart(); var matches = regex.RelatedMatches(str, s); Console.WriteLine("matches" + sw.ElapsedTicks + " in ms:" + sw.Elapsed); sw.Reset(); var sw1 = new Stopwatch(); foreach (var match in matches) { sw.Start(); var repls = rep.CreateCopyWithGroups(match); sw.Stop(); sw1.Start(); s.Replace(match, repls); sw1.Stop(); } Console.WriteLine("replacement build " + sw.ElapsedTicks); Console.WriteLine("text replace" + sw1.ElapsedTicks); sw.Restart(); var res = s.BuildResult(); sw.Stop(); Console.WriteLine("сборка" + sw.ElapsedTicks); Console.ReadLine(); }
public void TestReplace_ByContext() { var replacer = new TextReplacer(); var context = new DataContext(); context.DataDictionary.AddValue("key", "dictionary"); var source = "Text line with key.\r\nAnother key line.\r\n"; var expected = "Text line with dictionary.\r\nAnother dictionary line.\r\n"; source = replacer.Replace(source, context); Assert.Equal(expected, source); }
public void UpdateSourceFiles(string id, string fromVersion, string toVersion) { var fromText = id + "." + fromVersion; var toText = id + "." + toVersion; var replacer = new TextReplacer(); replacer.ReplaceIn( Path.GetFullPath("src"), "**.cs", fromText, toText, true ); }
public void SearchAndReplaceTags(IDictionary <string, string> tagNamesToReplace) { if (tagNamesToReplace == null || !tagNamesToReplace.Any()) { return; } using (var wordDoc = WordprocessingDocument.Open(stream, true)) { var tagNamesWithMarkupToReplace = MapDictionnaryWithMarkupOnKey(tagNamesToReplace); foreach (var(tag, text) in tagNamesWithMarkupToReplace) { TextReplacer.SearchAndReplace(wordDoc, tag, text, false); } } }
public static void Substituir(string arquivoOrigem, string arquivoDestino, IEnumerable <Substituicao> substituicoes) { UtilitarioArquivo.ClonarArquivo(arquivoOrigem, arquivoDestino); using (WordprocessingDocument document = WordprocessingDocument.Open(arquivoDestino, isEditable: true)) { foreach (Substituicao substituicao in substituicoes) { TextReplacer.SearchAndReplace( document, substituicao.Chave, substituicao.Valor, substituicao.MatchCase); } } }
public void TestReplace_ByParameters() { var replacer = new TextReplacer(); replacer.ReplaceKeys.Add(new ReplaceParameter("key", "val")); var context = new DataContext(); context.DataDictionary.AddValue("key", "dictionary"); var source = "Text line with key.\r\nAnother key line.\r\n"; var expected = "Text line with val.\r\nAnother val line.\r\n"; source = replacer.Replace(source, context); Assert.Equal(expected, source); }
static void Main(string[] args) { //try //{ // ConsoleController application = new ConsoleController(args); // application.Run(); //} //catch (Exception) //{ // Console.WriteLine("Instruction");// todo //} using (TextReplacer rep = new TextReplacer(".\\Instruction.txt", "a")) { rep.ReplaceString("77"); } Console.ReadKey(); }
public void Word() { var di2 = new DirectoryInfo(GetFilePath("Word")); foreach (var file in di2.GetFiles("*.docx")) { file.CopyTo(Path.Combine(TempDir, file.Name)); } using (var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test01.docx"), true)) TextReplacer.SearchAndReplace(doc, "the", "this", false); try { using var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test02.docx"), true); TextReplacer.SearchAndReplace(doc, "the", "this", false); } catch (Exception) { } try { using var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test03.docx"), true); TextReplacer.SearchAndReplace(doc, "the", "this", false); } catch (Exception) { } using (var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test04.docx"), true)) TextReplacer.SearchAndReplace(doc, "the", "this", true); using (var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test05.docx"), true)) TextReplacer.SearchAndReplace(doc, "is on", "is above", true); using (var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test06.docx"), true)) TextReplacer.SearchAndReplace(doc, "the", "this", false); using (var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test07.docx"), true)) TextReplacer.SearchAndReplace(doc, "the", "this", true); using (var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test08.docx"), true)) TextReplacer.SearchAndReplace(doc, "the", "this", true); using (var doc = WordprocessingDocument.Open(Path.Combine(TempDir, "Test09.docx"), true)) TextReplacer.SearchAndReplace(doc, "===== Replace this text =====", "***zzz***", true); }
private void OnReplace(object sender, EventArgs e) { if (_procOpt == null) { _procOpt = new ReplaceOption(); _optDlg = new OptionsDlg(); _optDlg.AddOption(_procOpt); } if (_optDlg.ShowDialog() != DialogResult.OK) { return; } StrStreamProvider provider = new StrStreamProvider(_textBoxInput.Text); MemoryStream memstrm = new MemoryStream(); TextReplacer processor = new TextReplacer((new StreamWriter(memstrm)), _procOpt); TextDispatcher dispatcher = new TextDispatcher(provider, processor); dispatcher.Run(); UpdateOutputTextBox(Encoding.Default.GetString(memstrm.GetBuffer())); }
static void Main(string[] args) { File.Delete("../../Test01out.pptx"); File.Copy("../../Test01.pptx", "../../Test01out.pptx"); using (PresentationDocument pDoc = PresentationDocument.Open("../../Test01out.pptx", true)) { TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", true); } File.Delete("../../Test02out.pptx"); File.Copy("../../Test02.pptx", "../../Test02out.pptx"); using (PresentationDocument pDoc = PresentationDocument.Open("../../Test02out.pptx", true)) { TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", true); } File.Delete("../../Test03out.pptx"); File.Copy("../../Test03.pptx", "../../Test03out.pptx"); using (PresentationDocument pDoc = PresentationDocument.Open("../../Test03out.pptx", true)) { TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", false); } }
async Task TranslateSourceFiles( IEnumerable <FSTextFile> files, Action entryPoint ) { var textReplacer = new TextReplacer(); var generator = new IntegrationGenerator(); var firmwareTemplates = IntegrationTemplatesLoader.FirmwareTemplates; var hardwareTemplates = IntegrationTemplatesLoader.HardwareTemplates; var tx = new CSharp2CPPTranslator(); var source = new FSSnapshot(); source.Files.AddRange(files); tx.Run(source); var firmwareSource = tx.Result; var socGenerator = new SOCGenerator(); var socRecords = new List <SOCRecord>(); var socRecordsBuilder = new SOCRecordsBuilder(); // default code block socRecords.Add(new SOCRecord() { DataType = typeof(uint), SegmentBits = 12, HardwareName = "firmware", SoftwareName = "firmware", Segment = 0, Depth = 512, Template = "memory32" }); socRecords.AddRange(socRecordsBuilder.ToSOCRecords(0x800, tx.SOCResources)); firmwareSource.Add(socGenerator.SOCImport(socRecords)); var generatedSourceFiles = firmwareSource.Files.Where(f => Path.GetExtension(f.Name).ToLower() == ".cpp").ToList(); var generatedHeaderFiles = firmwareSource.Files.Where(f => Path.GetExtension(f.Name).ToLower() == ".h").ToList(); firmwareSource.Merge(firmwareTemplates, f => !f.Name.Contains("template")); var firmwareTemplate = firmwareTemplates.Get <FSTextFile>("firmware.template.cpp"); var firmwareMap = new Dictionary <string, string>() { { "FIRMWARE_INCLUDES", string.Join(Environment.NewLine, generatedHeaderFiles.Select(f => $"#include \"{f.Name}\"")) }, { "FIRMWARE_CODE", $"{entryPoint.Method.DeclaringType.Namespace}::{entryPoint.Method.DeclaringType.Name}::{entryPoint.Method.Name}();" }, }; firmwareSource.Add("firmware.cpp", textReplacer.ReplaceToken(firmwareTemplate.Content, firmwareMap)); var makefileTemplate = firmwareTemplates.Get <FSTextFile>("Makefile.template"); var makefileMap = new Dictionary <string, string>() { { "SOURCES_LIST", string.Join(" ", generatedSourceFiles.Select(f => f.Name)) } }; firmwareSource.Add("Makefile", textReplacer.ReplaceToken(makefileTemplate.Content, makefileMap)); IntermediateData.SaveFirmwareSource(firmwareSource); var firmwareOutput = await CompileFromIntermediate(); IntermediateData.SaveFirmwareOutput(firmwareOutput); // generat verilog var hardwareTemplate = hardwareTemplates.Get <FSTextFile>("hardware.template.v").Content; var replacers = new Dictionary <string, string>(); // memory init file replacers["MEM_INIT"] = ""; foreach (var dma in socRecords) { var binFile = firmwareOutput.Get <FSBinaryFile>($"{dma.HardwareName}.bin"); if (binFile != null) { var words = TestTools.ReadWords(binFile.Content).ToList(); var memInit = generator.MemInit(words, dma.HardwareName, (int)dma.Depth, SizeOfType(dma.DataType)); replacers["MEM_INIT"] += memInit; } else { var memInit = generator.MemInit(Enumerable.Range(0, (int)dma.Depth).Select(idx => 0UL).ToList(), dma.HardwareName, (int)dma.Depth, SizeOfType(dma.DataType)); replacers["MEM_INIT"] += memInit; } } // data declarations replacers["DATA_DECL"] = generator.DataDeclaration(socRecords); // data control signals var templates = new IntegrationTemplates(); foreach (var t in hardwareTemplates.Files.OfType <FSTextFile>()) { templates.Templates[t.Name] = t.Content; } replacers["DATA_CTRL"] = generator.DataControl(socRecords, templates); replacers["MEM_READY"] = generator.MemReady(socRecords); replacers["MEM_RDATA"] = generator.MemRData(socRecords); hardwareTemplate = textReplacer.ReplaceToken(hardwareTemplate, replacers); var hardwareSource = new FSSnapshot(); hardwareSource.Add("hardware.v", hardwareTemplate); IntermediateData.SaveHardwareSource(hardwareSource); }
public void ShouldThrowExceptionIfVariableNotComplete() { var replacer = new TextReplacer(); var variables = new Mock<ITextVariables>(); Assert.That(() => replacer.ReplaceVariables("http://{host", variables.Object), Throws.InstanceOf(typeof (ParseException))); }
public void HandleText(ITextElement text) { // Scan the characters for (int i = 0; i < text.Value.Length; i++) { char c = text.Value[i]; switch (State) { case 0: if (c == '$') { State = 1; Position = i; Add(text); } break; case 1: if (c == '{') { State = 2; Add(text); } else { Reset(); } break; case 2: if (c == '}') { Add(text); Console.WriteLine("Found: " + Buffer); // We are on the final State // I will use the first text in the stack and discard the others // Here I am going to distinguish between whether I have only one item or more if (TextsList.Count == 1) { // Happy path - we have only one item - set the replacement value and then continue scanning string prefix = TextsList[0].Value.Substring(0, Position) + TextReplacer.ReplaceValue(Buffer.ToString()); // Set the current index to point to the end of the prefix.The program will continue to with the next items TextsList[0].Value = prefix + TextsList[0].Value.Substring(i + 1); i = prefix.Length - 1; Reset(); } else { // We have more than one item - discard the inbetweeners for (int j = 1; j < TextsList.Count - 1; j++) { TextsList[j].RemoveFromParent(); } // I will set the value under the first Text item where the $ was found TextsList[0].Value = TextsList[0].Value.Substring(0, Position) + TextReplacer.ReplaceValue(Buffer.ToString()); // Set the text for the current item to the remaining chars text.Value = text.Value.Substring(i + 1); i = -1; Reset(); } } else { Buffer.Append(c); Add(text); } break; } } }
public void Run(CancellationToken cancellationToken) { lock (_busy) { if (Immutable) { return; } if (_state != MicroTaskStates.None) { _log.Error("_state != MicroTaskStates.None"); } if (cancellationToken.IsCancellationRequested) { return; } State = MicroTaskStates.Reading; var text = _file.ReadText(); var replacer = new TextReplacer(text); if (cancellationToken.IsCancellationRequested) { return; } State = MicroTaskStates.Searching; var matches = new List <RelatedMatch>(); var m = _regex.RelatedMatch(text, 0, replacer); while (m.Success) { CurrentStagePercentage = (double)(m.StartIndex + m.Length) / text.Length; matches.Add(m); if (cancellationToken.IsCancellationRequested) { return; } m = _regex.RelatedMatch(text, m.StartIndex + m.Length, replacer); } if (matches.Count == 0) { matches.Add(m); } if (!matches[0].Success) { Immutable = true; State = MicroTaskStates.Complete; return; } if (cancellationToken.IsCancellationRequested) { return; } State = MicroTaskStates.Replacing; foreach (var relatedMatch in matches) { replacer.Replace(relatedMatch, _replacement.CreateCopyWithGroups(relatedMatch)); } State = MicroTaskStates.BuildingResult; var result = replacer.BuildResult(); ReplacesCount += matches.Count; if (cancellationToken.IsCancellationRequested) { return; } State = MicroTaskStates.SavingResult; _file.WriteText(result); State = MicroTaskStates.Complete; } }
async Task RunWithData( List <SOCRecord> externalData, string mainCode) { var textReplacer = new TextReplacer(); var templateRoot = TemplatesPath(Path.GetDirectoryName(Directory.GetCurrentDirectory())); var sourceRoot = @"C:\code\Quokka.RISCV.Docker.Server\Quokka.RISCV.Integration.Tests\Client\Blinker\Source"; var context = new RISCVIntegrationContext() .WithExtensionClasses( new ExtensionClasses() .Text("") .Text("lds") .Text("s") .Text("c") .Text("cpp") .Text("h") .Binary("bin") .Binary("elf") .Text("map") ) .WithRootFolder(sourceRoot) .WithAllRegisteredFiles() .WithOperations( new BashInvocation("make firmware.bin") ) .TakeModifiedFiles() ; var firmwareTemplatePath = File.ReadAllText(Path.Combine(templateRoot, "firmware.template.cpp")); var firmwareMap = new Dictionary <string, string>() { { "MAIN_CODE", mainCode } }; firmwareTemplatePath = textReplacer.ReplaceToken(firmwareTemplatePath, firmwareMap); var dmaGenerator = new SOCGenerator(); context.SourceSnapshot.Files.Add(dmaGenerator.SOCImport(externalData)); var generator = new IntegrationGenerator(); context.SourceSnapshot.Files.Add(generator.Firmware(firmwareTemplatePath)); new FSManager(sourceRoot).SaveSnapshot(context.SourceSnapshot); var result = await RISCVIntegrationClient.Run(context); Assert.IsNotNull(result); var hardwareTemplatePath = Path.Combine(templateRoot, "hardware.template.v"); var hardwareTemplate = File.ReadAllText(hardwareTemplatePath); // memory init file var binFile = (FSBinaryFile)result.ResultSnapshot.Files.Find(f => f.Name == "firmware.bin"); Assert.IsNotNull(binFile); var replacers = new Dictionary <string, string>(); var words = TestTools.ReadWords(binFile.Content).ToList(); var memInit = generator.MemInit(words, "l_mem", 512, 4); replacers["MEM_INIT"] = memInit; // data declarations replacers["DATA_DECL"] = generator.DataDeclaration(externalData); // data control signals var templates = new IntegrationTemplates(); foreach (var templatePath in Directory.EnumerateFiles(templateRoot, "*.*", SearchOption.AllDirectories)) { var name = Path.GetFileName(templatePath).Split('.')[0]; templates.Templates[name] = File.ReadAllText(templatePath); } replacers["DATA_CTRL"] = generator.DataControl(externalData, templates); replacers["MEM_READY"] = generator.MemReady(externalData); replacers["MEM_RDATA"] = generator.MemRData(externalData); hardwareTemplate = textReplacer.ReplaceToken(hardwareTemplate, replacers); File.WriteAllText(@"C:\code\picorv32\quartus\RVTest.v", hardwareTemplate); }
private static void TestText() { var tr = new TextReplacer(); tr.SetContext(null, new Log(), "", "D:\\Program Files\\Winning.FrameWork.Config __HRP_PATH__>D:\\Program Files".Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); }
public PhpArrayReplacer() { _strRegex = new Regex(@"s:\d+:\\""(.*?)\\""(;?)"); _replacer = new TextReplacer(false); }
private static void Main(string[] args) { using (WordprocessingDocument doc = WordprocessingDocument.Open("Test01.docx", true)) TextReplacer.SearchAndReplace(wordDoc: doc, search: "the", replace: "this", matchCase: false); }
private static void Main() { var n = DateTime.Now; var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second)); tempDi.Create(); var di2 = new DirectoryInfo("../../"); foreach (var file in di2.GetFiles("*.docx")) { file.CopyTo(Path.Combine(tempDi.FullName, file.Name)); } using (var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test01.docx"), true)) { TextReplacer.SearchAndReplace(doc, "the", "this", false); } try { using var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test02.docx"), true); TextReplacer.SearchAndReplace(doc, "the", "this", false); } catch (Exception) { } try { using var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test03.docx"), true); TextReplacer.SearchAndReplace(doc, "the", "this", false); } catch (Exception) { } using (var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test04.docx"), true)) { TextReplacer.SearchAndReplace(doc, "the", "this", true); } using (var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test05.docx"), true)) { TextReplacer.SearchAndReplace(doc, "is on", "is above", true); } using (var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test06.docx"), true)) { TextReplacer.SearchAndReplace(doc, "the", "this", false); } using (var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test07.docx"), true)) { TextReplacer.SearchAndReplace(doc, "the", "this", true); } using (var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test08.docx"), true)) { TextReplacer.SearchAndReplace(doc, "the", "this", true); } using (var doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test09.docx"), true)) { TextReplacer.SearchAndReplace(doc, "===== Replace this text =====", "***zzz***", true); } }
public void Run(CancellationToken cancellationToken) { lock (_busy) { if (Immutable) return; if (_state != MicroTaskStates.None) _log.Error("_state != MicroTaskStates.None"); if (cancellationToken.IsCancellationRequested) return; State = MicroTaskStates.Reading; var text = _file.ReadText(); var replacer = new TextReplacer(text); if (cancellationToken.IsCancellationRequested) return; State = MicroTaskStates.Searching; var matches = new List<RelatedMatch>(); var m = _regex.RelatedMatch(text, 0, replacer); while (m.Success) { CurrentStagePercentage = (double)(m.StartIndex + m.Length) / text.Length; matches.Add(m); if (cancellationToken.IsCancellationRequested) return; m = _regex.RelatedMatch(text, m.StartIndex + m.Length, replacer); } if (matches.Count == 0) matches.Add(m); if (!matches[0].Success) { Immutable = true; State = MicroTaskStates.Complete; return; } if (cancellationToken.IsCancellationRequested) return; State = MicroTaskStates.Replacing; foreach (var relatedMatch in matches) replacer.Replace(relatedMatch, _replacement.CreateCopyWithGroups(relatedMatch)); State = MicroTaskStates.BuildingResult; var result = replacer.BuildResult(); ReplacesCount += matches.Count; if (cancellationToken.IsCancellationRequested) return; State = MicroTaskStates.SavingResult; _file.WriteText(result); State = MicroTaskStates.Complete; } }
public void WordTextReplacer(string key, string value) { TextReplacer.SearchAndReplace(objWordDocument, key, value, true); }