public int SolutionPart1(params string[] input) { var totalLiterals = input.Sum(x => x.Length); var totalInMemory = new StringEscaper().GetInMemoryCharacters(input).Sum(x => x.Length); return totalLiterals - totalInMemory; }
public int SolutionPart2(params string[] input) { var totalLiterals = input.Sum(x => x.Length); var totalEncoded = new StringEscaper().GetEncodedCharacters(input).Sum(x => x.Length); return totalEncoded - totalLiterals; }
public void ExpandSectionParams_2() { EngineState s = EngineTests.CreateEngineState(); Variables.SetVariable(s, "#1", "World"); const string src = "%A% ##2 #1"; string dest = StringEscaper.ExpandSectionParams(s, src); const string comp = "%A% ##2 World"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public void ExpandSectionParams_7() { EngineState s = EngineTests.CreateEngineState(); s.SectionReturnValue = "TEST"; const string src = "##1 ##a ##r #r"; string dest = StringEscaper.ExpandSectionParams(s, src); const string comp = "##1 ##a ##r TEST"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public void PathSecurityCheck() { void Template(string path, bool expected) { bool result = StringEscaper.PathSecurityCheck(path, out _); Assert.AreEqual(expected, result); } string normalDir = FileHelper.GetTempDir(); try { // Valid paths Template(Path.Combine(normalDir, "PEBakery.exe"), true); Template(Path.Combine(normalDir, "Wildcard.*"), true); Template(Path.Combine(normalDir, "Wild*.???"), true); Template("C:\\", true); Template(string.Empty, true); } finally { if (Directory.Exists(normalDir)) { Directory.Delete(normalDir, true); } } // %WinDir% string winDir = Environment.GetEnvironmentVariable("WinDir"); Assert.IsNotNull(winDir); Template(Path.Combine(winDir, "System32", "notepad.exe"), false); // %ProgramFiles% string programFiles = Environment.GetEnvironmentVariable("ProgramFiles"); Assert.IsNotNull(programFiles); Template(Path.Combine(programFiles, "PEBakery", "PEBakery.ini"), false); // %ProgramFiles(x86)% switch (RuntimeInformation.ProcessArchitecture) { // Not sure about ARM64, please submit an issue/PR if anyone have ARM64 Windows device! case Architecture.Arm64: case Architecture.X64: // Only in 64bit process string programFiles86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); Assert.IsNotNull(programFiles86); Template(Path.Combine(programFiles86, "PEBakery", "PEBakery.ini"), false); break; } }
public void Preprocess_3() { EngineState s = EngineTests.CreateEngineState(); s.Variables.SetValue(VarsType.Local, "A", "Hello"); const string src = "%A% #1"; string dest = StringEscaper.Preprocess(s, src); const string comp = "Hello #1"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public static void ExpandVariables_2() { EngineState s = EngineTests.CreateEngineState(); s.CurSectionInParams[1] = "World"; const string src = "%A% #1"; string dest = StringEscaper.ExpandVariables(s, src); const string comp = "#$pA#$p World"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public static void Preprocess_2() { EngineState s = EngineTests.CreateEngineState(); Variables.SetVariable(s, "#1", "World"); const string src = "%A% #1"; string dest = StringEscaper.Preprocess(s, src); const string comp = "%A% World"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
private void FileCopy_SingleTemplate( EngineState s, string rawCode, string srcFileName, string destFileName, ErrorCheck check = ErrorCheck.Success, bool preserve = false, bool ignoreCompare = false) { if (destFileName == null) { destFileName = srcFileName; } string dirPath = StringEscaper.Preprocess(s, Path.Combine("%TestBench%", "CommandFile")); string srcDir = Path.Combine(dirPath, SrcDir_File); string destDir = Path.Combine(dirPath, DestDir_FileCopy); string srcFullPath = Path.Combine(srcDir, srcFileName); string destFullPath = Path.Combine(destDir, destFileName); if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } Directory.CreateDirectory(destDir); try { if (preserve) { File.Create(destFullPath).Close(); } EngineTests.Eval(s, rawCode, CodeType.FileCopy, check); if (check == ErrorCheck.Success && ignoreCompare == false) { Assert.IsTrue(File.Exists(destFullPath)); using (FileStream srcStream = new FileStream(srcFullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream destStream = new FileStream(destFullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { byte[] srcDigest = HashHelper.CalcHash(HashType.SHA256, srcStream); byte[] destDigest = HashHelper.CalcHash(HashType.SHA256, destStream); Assert.IsTrue(srcDigest.SequenceEqual(destDigest)); } } } finally { Directory.Delete(destDir, true); } }
public void ExpandSectionParams_3() { EngineState s = EngineTests.CreateEngineState(); s.Variables.SetValue(VarsType.Local, "A", "Hello"); string src = "%A% #1"; string dest = StringEscaper.ExpandSectionParams(s, src); string comp = "%A% ##1"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public void RenameFile() { EngineState s = EngineTests.CreateEngineState(); string originScriptPath = Path.Combine(StringEscaper.Preprocess(s, "%TestBench%"), "EncodedFile", "ExtractFileTests.script"); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(string folderName, string oldFileName, string newFileName, bool result) { string destDir = FileHelper.GetTempDir(); string destScript = Path.Combine(destDir, "RenameFileTest.script"); try { File.Copy(originScriptPath, destScript, true); Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions()); string errMsg; (sc, errMsg) = EncodedFile.RenameFile(sc, folderName, oldFileName, newFileName); if (errMsg != null) { Assert.IsFalse(result); return; } Assert.IsTrue(result); Assert.IsFalse(sc.Sections.ContainsKey(GetSectionName(folderName, oldFileName))); Assert.IsTrue(sc.Sections.ContainsKey(GetSectionName(folderName, newFileName))); Dictionary <string, string> fileDict = sc.Sections[folderName].IniDict; Assert.IsFalse(fileDict.ContainsKey(oldFileName)); Assert.IsTrue(fileDict.ContainsKey(newFileName)); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } } Template("FolderExample", "Type1.jpg", "JPEG.jpg", true); Template("FolderExample", "Type2.7z", "LZMA2.7z", true); Template("FolderExample", "Type3.pdf", "Postscript.pdf", true); Template(AuthorEncoded, "Logo.jpg", "L.jpg", true); Template(InterfaceEncoded, "PEBakeryAlphaMemory.jpg", "P.jpg", true); Template("BannerImage", "Should.fail", "Should.fail.2", false); Template("ShouldFail", "Should.fail", "Should.fail.2", false); }
public static List <LogInfo> IniAddSection(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_IniAddSection info = cmd.Info.Cast <CodeInfo_IniAddSection>(); string fileName = StringEscaper.Preprocess(s, info.FileName); string section = StringEscaper.Preprocess(s, info.Section); Debug.Assert(fileName != null, $"{nameof(fileName)} != null"); Debug.Assert(section != null, $"{nameof(section)} != null"); if (section.Length == 0) { return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty")); } if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string dirPath = Path.GetDirectoryName(fileName); if (dirPath == null) { throw new InternalException("Internal Logic Error at IniAddSection"); } if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } // If a dest file does not exist, create an empty file to force ANSI encoding as default in IniReadWriter. if (!File.Exists(fileName)) { File.Create(fileName).Dispose(); } bool result = IniReadWriter.AddSection(fileName, section); if (result) { logs.Add(new LogInfo(LogState.Success, $"Section [{section}] added to [{fileName}]", cmd)); } else { logs.Add(new LogInfo(LogState.Error, $"Could not add section [{section}] to [{fileName}]", cmd)); } return(logs); }
public static List <LogInfo> PathMove(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_PathMove)); CodeInfo_PathMove info = cmd.Info as CodeInfo_PathMove; string srcPath = StringEscaper.Preprocess(s, info.SrcPath); string destPath = StringEscaper.Preprocess(s, info.DestPath); // Path Security Check if (StringEscaper.PathSecurityCheck(destPath, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } // SrcPath must be directory if (File.Exists(srcPath)) { File.SetAttributes(srcPath, FileAttributes.Normal); File.Move(srcPath, destPath); logs.Add(new LogInfo(LogState.Success, $"File [{srcPath}] moved to [{destPath}]")); } else if (Directory.Exists(srcPath)) { // DestPath must be directory if (File.Exists(destPath)) { logs.Add(new LogInfo(LogState.Error, $"[{destPath}] is a file, not a directory")); return(logs); } if (Directory.Exists(destPath)) { string destFullPath = Path.Combine(destPath, Path.GetFileName(srcPath)); Directory.Move(srcPath, destFullPath); logs.Add(new LogInfo(LogState.Success, $"Directory [{srcPath}] moved to [{destFullPath}]")); } else { Directory.Move(srcPath, destPath); logs.Add(new LogInfo(LogState.Success, $"Directory [{srcPath}] moved to [{destPath}]")); } } else { logs.Add(new LogInfo(LogState.Success, $"Path [{srcPath}] does not exist")); } return(logs); }
public static List <LogInfo> TXTReplaceOp(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_TXTReplaceOp)); CodeInfo_TXTReplaceOp infoOp = cmd.Info as CodeInfo_TXTReplaceOp; string fileName = StringEscaper.Preprocess(s, infoOp.InfoList[0].FileName); if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } if (File.Exists(fileName) == false) { logs.Add(new LogInfo(LogState.Error, $"File [{fileName}] not exists")); return(logs); } List <Tuple <string, string> > prepReplace = new List <Tuple <string, string> >(); foreach (CodeInfo_TXTReplace info in infoOp.InfoList) { string oldStr = StringEscaper.Preprocess(s, info.OldStr); string newStr = StringEscaper.Preprocess(s, info.NewStr); prepReplace.Add(new Tuple <string, string>(oldStr, newStr)); } Encoding encoding = FileHelper.DetectTextEncoding(fileName); string tempPath = Path.GetTempFileName(); using (StreamReader reader = new StreamReader(fileName, encoding)) using (StreamWriter writer = new StreamWriter(tempPath, false, encoding)) { string str = reader.ReadToEnd(); foreach (var tup in prepReplace) { string oldStr = tup.Item1; string newStr = tup.Item2; str = StringHelper.ReplaceEx(str, oldStr, newStr, StringComparison.OrdinalIgnoreCase); logs.Add(new LogInfo(LogState.Success, $"Replaced [{oldStr}] with [{newStr}]")); } writer.Write(str); } FileHelper.FileReplaceEx(tempPath, fileName); return(logs); }
public void FileRename() { EngineState s = EngineTests.CreateEngineState(); string destDir = FileHelper.GetTempDir(); void Template(string rawCode, string srcFileName, string destFileName, ErrorCheck check = ErrorCheck.Success) { string dirPath = StringEscaper.Preprocess(s, Path.Combine("%TestBench%", "CommandFile")); string srcDir = Path.Combine(dirPath, SrcDirFile); string srcFullPath = Path.Combine(destDir, srcFileName); string destFullPath = Path.Combine(destDir, destFileName); if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } FileHelper.DirCopy(srcDir, destDir, new DirCopyOptions { CopySubDirs = true, Overwrite = true, }); try { if (rawCode.StartsWith("FileRename", StringComparison.OrdinalIgnoreCase)) { EngineTests.Eval(s, rawCode, CodeType.FileRename, check); } else { EngineTests.Eval(s, rawCode, CodeType.FileMove, check); } if (check == ErrorCheck.Success) { Assert.IsFalse(File.Exists(srcFullPath)); Assert.IsTrue(File.Exists(destFullPath)); } } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } } Template($@"FileRename,{destDir}\A.txt,{destDir}\R.txt", "A.txt", "R.txt"); Template($@"FileRename,{destDir}\A.txt,{destDir}\B.txt", "A.txt", "B.txt", ErrorCheck.RuntimeError); Template($@"FileRename,{destDir}\R.txt,{destDir}\S.txt", "R.txt", "S.txt", ErrorCheck.RuntimeError); Template($@"FileMove,{destDir}\A.txt,{destDir}\R.txt", "A.txt", "R.txt"); }
public static void ExpandVariables_1() { EngineState s = EngineTests.CreateEngineState(); s.Variables.SetValue(VarsType.Local, "A", "Hello"); s.CurSectionInParams[1] = "World"; const string src = "%A% #1"; string dest = StringEscaper.ExpandVariables(s, src); const string comp = "Hello World"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
private void UnescapeButton_Click(object sender, RoutedEventArgs e) { string str = StringEscaper.QuoteUnescape(m.Escaper_StringToConvert); if (m.Escaper_EscapePercent) { m.Escaper_ConvertedString = StringEscaper.UnescapePercent(str); } else { m.Escaper_ConvertedString = str; } }
public void PackRegMultiBinary_1() { string[] src = new string[] { "C:\\", "Hello", "World", }; string dest = StringEscaper.PackRegMultiBinary(src); string comp = "43,00,3A,00,5C,00,00,00,48,00,65,00,6C,00,6C,00,6F,00,00,00,57,00,6F,00,72,00,6C,00,64,00"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public void PackRegMultiString() { string[] src = { "C:\\", "Hello", "World", }; string dest = StringEscaper.PackRegMultiString(src); const string comp = "C:\\#$zHello#$zWorld"; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public static List<LogInfo> SetMacro(EngineState s, CodeCommand cmd) { // SetMacro,<MacroName>,<MacroCommand>,[GLOBAL|PERMANENT] CodeInfo_SetMacro info = cmd.Info.Cast<CodeInfo_SetMacro>(); string macroCommand = StringEscaper.Preprocess(s, info.MacroCommand); if (macroCommand.Equals("NIL", StringComparison.OrdinalIgnoreCase)) macroCommand = null; LogInfo log = s.Macro.SetMacro(info.MacroName, macroCommand, cmd.Section, info.Global, info.Permanent); return new List<LogInfo>(1) { log }; }
public void ExtractAllFiles() { EngineState s = EngineTests.CreateEngineState(); string srcDir = StringEscaper.Preprocess(s, Path.Combine("%TestBench%", "EncodedFile")); string scPath = Path.Combine(srcDir, "ExtractFileTests.script"); string destDir = Path.GetTempFileName(); try { File.Delete(destDir); Directory.CreateDirectory(destDir); void SingleTemplate(string rawCode, string[] srcFileNames, ErrorCheck check = ErrorCheck.Success) { EngineTests.Eval(s, rawCode, CodeType.ExtractAllFiles, check); if (check == ErrorCheck.Success || check == ErrorCheck.Warning) { foreach (string srcFileName in srcFileNames) { string srcFile = Path.Combine(srcDir, srcFileName); string destFile = Path.Combine(destDir, srcFileName); byte[] originDigest; byte[] extractDigest; using (FileStream fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { originDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, fs); } using (FileStream fs = new FileStream(destFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { extractDigest = HashHelper.GetHash(HashHelper.HashType.SHA256, fs); } Assert.IsTrue(originDigest.SequenceEqual(extractDigest)); } } } SingleTemplate($@"ExtractAllFiles,{scPath},FolderExample,{destDir}", new string[] { "Type1.jpg", "Type2.7z", "Type3.pdf" }); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } }
public static List <LogInfo> Hash(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_Hash)); CodeInfo_Hash info = cmd.Info as CodeInfo_Hash; string hashTypeStr = StringEscaper.Preprocess(s, info.HashType); string filePath = StringEscaper.Preprocess(s, info.FilePath); HashType hashType; if (hashTypeStr.Equals("MD5", StringComparison.OrdinalIgnoreCase)) { hashType = HashType.MD5; } else if (hashTypeStr.Equals("SHA1", StringComparison.OrdinalIgnoreCase)) { hashType = HashType.SHA1; } else if (hashTypeStr.Equals("SHA256", StringComparison.OrdinalIgnoreCase)) { hashType = HashType.SHA256; } else if (hashTypeStr.Equals("SHA384", StringComparison.OrdinalIgnoreCase)) { hashType = HashType.SHA384; } else if (hashTypeStr.Equals("SHA512", StringComparison.OrdinalIgnoreCase)) { hashType = HashType.SHA512; } else { throw new ExecuteException($"Invalid hash type [{hashTypeStr}]"); } string digest; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { digest = HashHelper.CalcHashString(hashType, fs); } logs.Add(new LogInfo(LogState.Success, $"Hash [{hashType}] digest of [{filePath}] is [{digest}]")); List <LogInfo> varLogs = Variables.SetVariable(s, info.DestVar, digest.ToString()); logs.AddRange(varLogs); return(logs); }
public static List <LogInfo> DirMove(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_DirMove info = cmd.Info.Cast <CodeInfo_DirMove>(); string srcDir = StringEscaper.Preprocess(s, info.SrcDir); string destPath = StringEscaper.Preprocess(s, info.DestPath); // Path Security Check if (!StringEscaper.PathSecurityCheck(destPath, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } // SrcPath must be directory // WB082 does not check this, so file can be moved with DirMove if (File.Exists(srcDir)) { return(LogInfo.LogErrorMessage(logs, $"[{srcDir}] is a file, not a directory")); } // DestPath must be directory if (File.Exists(destPath)) { return(LogInfo.LogErrorMessage(logs, $"[{destPath}] is a file, not a directory")); } if (Directory.Exists(destPath)) { string srcDirName = Path.GetFileName(srcDir); if (srcDirName == null) { throw new InternalException("Internal Logic Error at DirMove"); } string destFullPath = Path.Combine(destPath, srcDirName); Directory.Move(srcDir, destFullPath); logs.Add(new LogInfo(LogState.Success, $"Directory [{srcDir}] moved to [{destFullPath}]")); } else { Directory.Move(srcDir, destPath); logs.Add(new LogInfo(LogState.Success, $"Directory [{srcDir}] moved to [{destPath}]")); } return(logs); }
public static List <LogInfo> IniDelete(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_IniDelete info = cmd.Info.Cast <CodeInfo_IniDelete>(); string fileName = StringEscaper.Preprocess(s, info.FileName); string sectionName = StringEscaper.Preprocess(s, info.Section); string key = StringEscaper.Preprocess(s, info.Key); Debug.Assert(fileName != null, $"{nameof(fileName)} != null"); Debug.Assert(sectionName != null, $"{nameof(sectionName)} != null"); Debug.Assert(key != null, $"{nameof(key)} != null"); if (sectionName.Length == 0) { return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty")); } if (key.Length == 0) { return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty")); } if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } bool result; if (s.CompatAutoCompactIniWriteCommand) { result = IniReadWriter.DeleteCompactKey(fileName, sectionName, key); } else { result = IniReadWriter.DeleteKey(fileName, sectionName, key); } if (result) { logs.Add(new LogInfo(LogState.Success, $"Key [{key}] deleted from [{fileName}]", cmd)); } else { logs.Add(new LogInfo(LogState.Ignore, $"Could not delete key [{key}] from [{fileName}]", cmd)); } return(logs); }
public static List <LogInfo> IniReadSection(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_IniReadSection info = cmd.Info.Cast <CodeInfo_IniReadSection>(); string fileName = StringEscaper.Preprocess(s, info.FileName); string section = StringEscaper.Preprocess(s, info.Section); string delim = "|"; if (info.Delim != null) { delim = StringEscaper.Preprocess(s, info.Delim); } Debug.Assert(fileName != null, $"{nameof(fileName)} != null"); Debug.Assert(section != null, $"{nameof(section)} != null"); if (section.Length == 0) { return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty")); } IniKey[] keys = IniReadWriter.ReadSection(fileName, section); if (keys != null) { List <string> kvList = new List <string>(keys.Length * 2); foreach (IniKey k in keys) { kvList.Add(k.Key); kvList.Add(k.Value); } string destStr = StringEscaper.PackListStr(kvList, delim); logs.Add(new LogInfo(LogState.Success, $"Section [{section}] read from [{fileName}]")); string escapedValue = StringEscaper.Escape(destStr, false, true); List <LogInfo> varLogs = Variables.SetVariable(s, info.DestVar, escapedValue, false, false, false); logs.AddRange(varLogs); } else { logs.Add(new LogInfo(LogState.Ignore, $"Section [{section}] does not exist in [{fileName}]")); List <LogInfo> varLogs = Variables.SetVariable(s, info.DestVar, string.Empty, false, false, false); logs.AddRange(varLogs); } return(logs); }
public static void ExpandVariables_4() { EngineState s = EngineTests.CreateEngineState(); EngineTests.PushDepthInfo(s, 2); s.Variables.SetValue(VarsType.Local, "A", "Hello"); const string src = "%A% #1"; string dest = StringEscaper.ExpandVariables(s, src); const string comp = "Hello "; Assert.IsTrue(dest.Equals(comp, StringComparison.Ordinal)); }
public static void Macro(EngineState s, CodeCommand cmd) { CodeInfo_Macro info = cmd.Info.Cast <CodeInfo_Macro>(); bool isGlobal; CodeCommand macroCmd; if (s.Macro.GlobalDict.ContainsKey(info.MacroType)) { macroCmd = s.Macro.GlobalDict[info.MacroType]; macroCmd.RawCode = cmd.RawCode; isGlobal = true; } else if (s.Macro.LocalDict.ContainsKey(info.MacroType)) { macroCmd = s.Macro.LocalDict[info.MacroType]; macroCmd.RawCode = cmd.RawCode; isGlobal = false; } else { s.Logger.BuildWrite(s, new LogInfo(LogState.Error, $"Invalid Command [{info.MacroType}]", cmd, s.CurDepth)); return; } Dictionary <int, string> paramDict = new Dictionary <int, string>(); for (int i = 0; i < info.Args.Count; i++) { paramDict[i + 1] = StringEscaper.ExpandSectionParams(s, info.Args[i]); } s.CurSectionInParams = paramDict; s.Logger.BuildWrite(s, new LogInfo(LogState.Info, $"Executing Command [{info.MacroType}]", cmd, s.CurDepth)); // Backup and set EngineState values int realScriptIdBackup = s.RefScriptId; if (isGlobal) { s.RefScriptId = s.Logger.BuildRefScriptWrite(s, macroCmd.Section.Script); } s.InMacro = true; CommandBranch.RunExec(s, macroCmd, true); // Restore and reset EngineState values s.RefScriptId = realScriptIdBackup; s.InMacro = false; }
public static List <LogInfo> Exit(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_Exit info = cmd.Info.Cast <CodeInfo_Exit>(); string message = StringEscaper.Preprocess(s, info.Message); s.PassCurrentScriptFlag = true; logs.Add(new LogInfo(info.NoWarn ? LogState.Ignore : LogState.Warning, message, cmd)); return(logs); }
public static List <LogInfo> IniDeleteSectionOp(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_IniDeleteSectionOp)); CodeInfo_IniDeleteSectionOp infoOp = cmd.Info as CodeInfo_IniDeleteSectionOp; string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName); if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } string[] sections = new string[infoOp.Cmds.Count]; for (int i = 0; i < sections.Length; i++) { CodeInfo_IniDeleteSection info = infoOp.Infos[i]; string sectionName = StringEscaper.Preprocess(s, info.Section); // WB082 : 여기 값은 변수 Expand 안한다. if (sectionName.Equals(string.Empty, StringComparison.Ordinal)) { throw new InvalidCodeCommandException("Section name cannot be empty", cmd); } sections[i] = sectionName; } bool result = Ini.DeleteSections(fileName, sections); if (result) { for (int i = 0; i < sections.Length; i++) { logs.Add(new LogInfo(LogState.Success, $"Section [{sections[i]}] deleted", infoOp.Cmds[i])); } logs.Add(new LogInfo(LogState.Success, $"Deleted [{sections.Length}] sections from [{fileName}]", cmd)); } else { for (int i = 0; i < sections.Length; i++) { logs.Add(new LogInfo(LogState.Error, $"Could not delete section [{sections[i]}]", infoOp.Cmds[i])); } logs.Add(new LogInfo(LogState.Error, $"Could not delete [{sections.Length}] sections from [{fileName}]", cmd)); } return(logs); }
public static List <LogInfo> IniDeleteSectionOp(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_IniDeleteSectionOp infoOp = cmd.Info.Cast <CodeInfo_IniDeleteSectionOp>(); string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName); Debug.Assert(fileName != null, $"{nameof(fileName)} != null"); if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg)) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string[] sections = new string[infoOp.Cmds.Count]; for (int i = 0; i < sections.Length; i++) { CodeInfo_IniDeleteSection info = infoOp.Infos[i]; string sectionName = StringEscaper.Preprocess(s, info.Section); // WB082 : 여기 값은 변수 Expand 안한다. if (sectionName.Length == 0) { return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty")); } sections[i] = sectionName; } bool result = IniReadWriter.DeleteSections(fileName, sections); if (result) { for (int i = 0; i < sections.Length; i++) { logs.Add(new LogInfo(LogState.Success, $"Section [{sections[i]}] deleted", infoOp.Cmds[i])); } logs.Add(new LogInfo(LogState.Success, $"Deleted [{sections.Length}] sections from [{fileName}]", cmd)); } else { for (int i = 0; i < sections.Length; i++) { logs.Add(new LogInfo(LogState.Error, $"Could not delete section [{sections[i]}]", infoOp.Cmds[i])); } logs.Add(new LogInfo(LogState.Error, $"Could not delete [{sections.Length}] sections from [{fileName}]", cmd)); } return(logs); }
public static List <LogInfo> PackParam(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(4); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_PackParam)); CodeInfo_PackParam info = cmd.Info as CodeInfo_PackParam; string startIndexStr = StringEscaper.Preprocess(s, info.StartIndex); if (!NumberHelper.ParseInt32(startIndexStr, out int startIndex)) { logs.Add(new LogInfo(LogState.Error, $"[{startIndexStr}] is not a valid integer")); return(logs); } int varCount = s.CurSectionParamsCount; if (startIndex <= varCount) { StringBuilder b = new StringBuilder(); for (int i = 1; i <= varCount; i++) { b.Append('"'); if (s.CurSectionParams.ContainsKey(i)) { b.Append(StringEscaper.Escape(s.CurSectionParams[i], true, false)); } b.Append('"'); if (i + 1 <= varCount) { b.Append(','); } } logs.AddRange(Variables.SetVariable(s, info.DestVar, b.ToString(), false, false)); } else { logs.Add(new LogInfo(LogState.Ignore, $"StartIndex [#{startIndex}] is invalid, [{varCount}] section parameters provided.")); logs.AddRange(Variables.SetVariable(s, info.DestVar, string.Empty, false, false)); } if (info.VarCount != null) { logs.AddRange(Variables.SetVariable(s, info.VarCount, varCount.ToString(), false, false)); } return(logs); }
public static List <LogInfo> TXTDelSpaces(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_TXTDelSpaces)); CodeInfo_TXTDelSpaces info = cmd.Info as CodeInfo_TXTDelSpaces; string fileName = StringEscaper.Preprocess(s, info.FileName); if (StringEscaper.PathSecurityCheck(fileName, out string errorMsg) == false) { logs.Add(new LogInfo(LogState.Error, errorMsg)); return(logs); } if (File.Exists(fileName) == false) { logs.Add(new LogInfo(LogState.Error, $"File [{fileName}] not exists")); return(logs); } Encoding encoding = FileHelper.DetectTextEncoding(fileName); int i = 0; string tempPath = Path.GetTempFileName(); using (StreamReader reader = new StreamReader(fileName, encoding)) using (StreamWriter writer = new StreamWriter(tempPath, false, encoding)) { string srcLine; while ((srcLine = reader.ReadLine()) != null) { // WB082 delete spaces only if spaces are placed in front of line. // Same with C#'s string.TrimStart(). int count = StringHelper.CountOccurrences(srcLine, " "); if (0 < count) { i++; srcLine = srcLine.TrimStart(); } writer.WriteLine(srcLine); } } FileHelper.FileReplaceEx(tempPath, fileName); logs.Add(new LogInfo(LogState.Success, $"Deleted [{i}] spaces")); return(logs); }