Esempio n. 1
0
        public void ExtractFolder()
        {
            EngineState s = EngineTests.CreateEngineState();

            void Template(string folderName)
            {
                string pbOriginScript = Path.Combine("%TestBench%", "EncodedFile", "ExtractFileTests.script");
                string originScript   = StringEscaper.Preprocess(s, pbOriginScript);

                string destDir = FileHelper.GetTempDir();

                try
                {
                    Script sc = s.Project.LoadScriptRuntime(originScript, new LoadScriptRuntimeOptions());

                    EncodedFile.ExtractFolder(sc, folderName, destDir);

                    string[] comps = IniReadWriter.ParseIniLinesIniStyle(sc.Sections[folderName].Lines).Keys.ToArray();
                    string[] dests = Directory.EnumerateFiles(destDir).Select(Path.GetFileName).ToArray();

                    Assert.IsTrue(comps.SequenceEqual(dests, StringComparer.OrdinalIgnoreCase));
                }
                finally
                {
                    if (Directory.Exists(destDir))
                    {
                        Directory.Delete(destDir, true);
                    }
                }
            }

            Template("FolderExample");
        }
Esempio n. 2
0
        public List <LogInfo> LoadMacroDict(MacroType type, Script sc, bool append, string sectionName = ScriptSection.Names.Variables)
        {
            if (!sc.Sections.ContainsKey(sectionName))
            {
                return(new List <LogInfo>());
            }

            ScriptSection section = sc.Sections[sectionName];

            // Pick key-value only if key is not wrapped by %
            Dictionary <string, string> dict = IniReadWriter.ParseIniLinesIniStyle(section.Lines);

            return(LoadMacroDict(type, section, dict, append));
        }
Esempio n. 3
0
        public List <LogInfo> LoadLocalMacroDict(Script sc, bool append, string sectionName = ScriptSection.Names.Variables)
        {
            if (sc.Sections.ContainsKey(sectionName))
            {
                ScriptSection section = sc.Sections[sectionName];

                // [Variables]'s type is SectionDataType.Lines
                // Pick key-value only if key is not wrapped by %
                Dictionary <string, string> dict = IniReadWriter.ParseIniLinesIniStyle(section.Lines);
                return(LoadLocalMacroDict(section, dict, append));
            }

            return(new List <LogInfo>());
        }
Esempio n. 4
0
        /// <summary>
        /// If _lines is not loaded from file, load it to memory.
        /// </summary>
        /// <returns>
        /// true if _lines is valid
        /// </returns>
        public bool LoadIniDict()
        {
            bool result = true;

            if (_lines == null)
            {
                result = LoadLines();
            }
            if (!result) // LoadLines failed
            {
                return(false);
            }

            if (_iniDict != null)
            {
                return(true);
            }

            _iniDict = IniReadWriter.ParseIniLinesIniStyle(_lines);
            return(true);
        }
Esempio n. 5
0
        public Macro(Project project, Variables variables, out List <LogInfo> logs)
        {
            logs = new List <LogInfo>();

            MacroEnabled = true;
            if (!project.MainScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            ScriptSection mainScriptVarSection = project.MainScript.Sections[ScriptSection.Names.Variables];

            Dictionary <string, string> varDict = IniReadWriter.ParseIniLinesVarStyle(mainScriptVarSection.Lines);

            if (!(varDict.ContainsKey(KnownVar.API) && varDict.ContainsKey(KnownVar.APIVAR)))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            // Get macroScript
            string rawScriptPath   = varDict[KnownVar.API];
            string macroScriptPath = variables.Expand(varDict[KnownVar.API]); // Need expansion

            MacroScript = project.AllScripts.Find(x => x.RealPath.Equals(macroScriptPath, StringComparison.OrdinalIgnoreCase));
            if (MacroScript == null)
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro script [{rawScriptPath}"));
                return;
            }

            // Get macroScript
            if (!MacroScript.Sections.ContainsKey(varDict[KnownVar.APIVAR]))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro section [{varDict[KnownVar.APIVAR]}"));
                return;
            }
            MacroSection = MacroScript.Sections[varDict[KnownVar.APIVAR]];
            variables.SetValue(VarsType.Global, KnownVar.API, macroScriptPath);
            if (MacroScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                logs.AddRange(variables.AddVariables(VarsType.Global, MacroScript.Sections[ScriptSection.Names.Variables]));
            }

            // Import Section [APIVAR]'s variables, such as '%Shc_Mode%=0'
            logs.AddRange(variables.AddVariables(VarsType.Global, MacroSection));

            // Parse Section [APIVAR] into MacroDict
            {
                ScriptSection section = MacroSection;
                Dictionary <string, string> rawDict = IniReadWriter.ParseIniLinesIniStyle(MacroSection.Lines);
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success)
                        { // Macro Name Validation
                            CodeParser parser = new CodeParser(section, Global.Setting, section.Project.Compat);
                            GlobalDict[kv.Key] = parser.ParseStatement(kv.Value);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }

            // Parse MainScript's section [Variables] into MacroDict
            // (Written by SetMacro, ... ,PERMANENT
            if (project.MainScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                ScriptSection permaSection          = project.MainScript.Sections[ScriptSection.Names.Variables];
                Dictionary <string, string> rawDict = IniReadWriter.ParseIniLinesIniStyle(permaSection.Lines);
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success)
                        { // Macro Name Validation
                            CodeParser parser = new CodeParser(permaSection, Global.Setting, permaSection.Project.Compat);
                            GlobalDict[kv.Key] = parser.ParseStatement(kv.Value);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }
        }
Esempio n. 6
0
        public List <LogInfo> LoadMacroDict(MacroType type, ScriptSection section, IEnumerable <string> lines, bool append)
        {
            Dictionary <string, string> dict = IniReadWriter.ParseIniLinesIniStyle(lines);

            return(LoadMacroDict(type, section, dict, append));
        }
Esempio n. 7
0
        public static List <LogInfo> ExtractAllFiles(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_ExtractAllFiles info = cmd.Info.Cast <CodeInfo_ExtractAllFiles>();

            string scriptFile = StringEscaper.Preprocess(s, info.ScriptFile);
            string dirName    = StringEscaper.Preprocess(s, info.DirName);
            string destDir    = StringEscaper.Preprocess(s, info.DestDir);

            Script sc = Engine.GetScriptInstance(s, s.CurrentScript.RealPath, scriptFile, out _);

            // Check if encoded file exist
            if (!EncodedFile.ContainsFolder(sc, dirName))
            {
                return(LogInfo.LogErrorMessage(logs, $"Encoded folder [{dirName}] not found in script [{sc.RealPath}]."));
            }

            // Filter dest path
            if (!StringEscaper.PathSecurityCheck(destDir, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string[] dirs = sc.Sections[ScriptSection.Names.EncodedFolders].Lines;
            if (!dirs.Any(d => d.Equals(dirName, StringComparison.OrdinalIgnoreCase)))
            {
                return(LogInfo.LogErrorMessage(logs, $"Directory [{dirName}] not exists in [{scriptFile}]"));
            }

            if (!Directory.Exists(destDir))
            {
                if (File.Exists(destDir))
                {
                    return(LogInfo.LogErrorMessage(logs, $"File [{destDir}] is not a directory"));
                }
                Directory.CreateDirectory(destDir);
            }

            string[] lines = sc.Sections[dirName].Lines;
            Dictionary <string, string> fileDict = IniReadWriter.ParseIniLinesIniStyle(lines);
            int fileCount = fileDict.Count;

            s.MainViewModel.SetBuildCommandProgress("ExtractAndRun Progress", fileCount);
            try
            {
                int i = 0;
                foreach (string file in fileDict.Keys)
                {
                    object             progressLock = new object();
                    IProgress <double> progress     = new Progress <double>(x =>
                    {
                        lock (progressLock)
                        {
                            s.MainViewModel.BuildCommandProgressText  = $"Decompressing \"{file}\"\r\n({(x + i) * 100 / fileCount:0.0}%)";
                            s.MainViewModel.BuildCommandProgressValue = x + i;
                        }
                    });

                    using (FileStream fs = new FileStream(Path.Combine(destDir, file), FileMode.Create, FileAccess.Write))
                    {
                        EncodedFile.ExtractFile(sc, dirName, file, fs, progress);
                    }

                    i += 1;
                }
            }
            finally
            {
                s.MainViewModel.ResetBuildCommandProgress();
            }

            logs.Add(new LogInfo(LogState.Success, $"Encoded folder [{dirName}] was extracted to [{destDir}]"));

            return(logs);
        }