Esempio n. 1
0
        public static List <LogInfo> IniRead(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

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

            string fileName     = StringEscaper.Preprocess(s, info.FileName);
            string sectionName  = StringEscaper.Preprocess(s, info.Section);
            string key          = StringEscaper.Preprocess(s, info.Key);
            string defaultValue = null;

            if (info.DefaultValue != null)
            {
                defaultValue = StringEscaper.Preprocess(s, info.DefaultValue);
            }

            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"));
            }

            string value = IniReadWriter.ReadKey(fileName, sectionName, key);

            if (value != null)
            {
                logs.Add(new LogInfo(LogState.Success, $"Key [{key}] and it's value [{value}] read from [{fileName}]"));

                string         escapedValue = StringEscaper.Escape(value, false, true);
                List <LogInfo> varLogs      = Variables.SetVariable(s, info.DestVar, escapedValue, false, false, false);
                logs.AddRange(varLogs);
            }
            else
            {
                if (defaultValue != null)
                {
                    logs.Add(new LogInfo(LogState.Ignore, $"Key [{key}] does not exist in [{fileName}]. Assigning default value [{defaultValue}]"));

                    List <LogInfo> varLogs = Variables.SetVariable(s, info.DestVar, defaultValue, false, false, false);
                    logs.AddRange(varLogs);
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Ignore, $"Key [{key}] does not exist in [{fileName}]"));

                    List <LogInfo> varLogs = Variables.SetVariable(s, info.DestVar, string.Empty, false, false, false);
                    logs.AddRange(varLogs);
                }
            }

            return(logs);
        }
Esempio n. 2
0
        public void Visible()
        {
            string srcFile    = Path.Combine(EngineTests.Project.ProjectDir, TestSuiteInterface, "ReadInterface.script");
            string scriptFile = Path.GetTempFileName();


            try
            {
                void SingleTemplate(string rawCode, string key, string compStr, ErrorCheck check = ErrorCheck.Success)
                {
                    File.Copy(srcFile, scriptFile, true);

                    EngineState s  = EngineTests.CreateEngineState();
                    Script      sc = s.Project.LoadScriptRuntime(scriptFile, new LoadScriptRuntimeOptions());
                    // ScriptSection ifaceSection = sc.GetInterfaceSection(out _);
                    ScriptSection section = sc.Sections["Process"];

                    // Enable Visible command
                    CodeParser.Options opts = CodeParser.Options.CreateOptions(Global.Setting, EngineTests.Project.Compat);
                    opts.AllowLegacyInterfaceCommand = true;
                    CodeParser parser = new CodeParser(section, opts);

                    try
                    {
                        EngineTests.Eval(s, parser, rawCode, CodeType.Visible, check);
                        if (check == ErrorCheck.Success)
                        {
                            string dest = IniReadWriter.ReadKey(scriptFile, "Interface", key);
                            Assert.IsTrue(dest.Equals(compStr, StringComparison.Ordinal));
                        }
                    }
                    finally
                    {
                        if (File.Exists(scriptFile))
                        {
                            File.Delete(scriptFile);
                        }
                    }
                }
                void OptTemplate(List <string> rawCodes, (string key, string value)[] compTuples, bool optSuccess, ErrorCheck check = ErrorCheck.Success)
Esempio n. 3
0
        public static void SetDelPermanent(EngineState s)
        {
            string scPath = s.Project.MainScript.RealPath;

            IniReadWriter.DeleteKey(scPath, "Variables", "%PermDest%");
            try
            {
                // Set
                EngineTests.Eval(s, "Set,%PermDest%,PEBakery,PERMANENT", CodeType.Set, ErrorCheck.Success);

                string dest = s.Variables.GetValue(VarsType.Global, "PermDest");
                Assert.IsTrue(dest.Equals("PEBakery", StringComparison.Ordinal));

                // Check memory-cached script section
                ScriptSection varSect = s.Project.MainScript.Sections["Variables"];
                int           idx     = Array.FindIndex(varSect.Lines, x => x.StartsWith("%PermDest%="));
                Assert.AreNotEqual(-1, idx);

                // Check script file
                string permanent = IniReadWriter.ReadKey(scPath, "Variables", "%PermDest%");
                Assert.IsTrue(dest.Equals(permanent, StringComparison.Ordinal));

                // Delete
                EngineTests.Eval(s, "Set,%PermDest%,NIL,PERMANENT", CodeType.Set, ErrorCheck.Success);

                // Check memory-cached script section
                idx = Array.FindIndex(varSect.Lines, x => x.StartsWith("%PermDest%="));
                Assert.AreEqual(-1, idx);

                // Check script file
                permanent = IniReadWriter.ReadKey(scPath, "Variables", "%PermDest%");
                Assert.IsNull(permanent);
            }
            finally
            {
                IniReadWriter.DeleteKey(scPath, "Variables", "%PermDest%");
            }
        }
Esempio n. 4
0
        private ResultReport <Script> InternalUpdateOneScript(Script sc, ScriptStateBackup stateBackup)
        {
            // Never should be triggered, because Script class constructor check it
            Debug.Assert(sc.ParsedVersion != null, $"Local script [{sc.Title}] does not provide proper version information");

            string updateUrl      = sc.UpdateUrl;
            string metaJsonUrl    = Path.ChangeExtension(updateUrl, ".meta.json");
            string metaJsonFile   = FileHelper.GetTempFile(".meta.json");
            string tempScriptFile = FileHelper.GetTempFile(".script");

            try
            {
                // Download .meta.json
                HttpFileDownloader.Report httpReport = DownloadFile(metaJsonUrl, metaJsonFile);
                if (!httpReport.Result)
                {
                    // Failed to send a request, such as network not available
                    if (httpReport.StatusCode == 0)
                    {
                        return(new ResultReport <Script>(false, null, $"Unable to connect to the server"));
                    }

                    // Try downloading .deleted to check if a script is deleted
                    string errorMsg;
                    string deletedUrl  = Path.ChangeExtension(updateUrl, ".deleted");
                    string deletedFile = Path.ChangeExtension(metaJsonFile, ".deleted");
                    try
                    {
                        httpReport = DownloadFile(deletedUrl, deletedFile);
                        if (httpReport.Result)
                        {                                     // Successfully received response
                            if (httpReport.StatusCode == 200) // .deleted file exists in the server
                            {
                                errorMsg = $"[{sc.Title}] was deleted from the server";
                            }
                            else // There is no .deleted file in the server
                            {
                                errorMsg = $"Update is not available for [{sc.Title}]";
                            }
                        }
                        else
                        {
                            if (httpReport.StatusCode == 0) // Failed to send a request, such as network not available
                            {
                                errorMsg = $"Unable to connect to the server";
                            }
                            else
                            {
                                errorMsg = $"Update is not available for [{sc.Title}]";
                            }
                        }
                    }
                    finally
                    {
                        if (File.Exists(deletedFile))
                        {
                            File.Delete(deletedFile);
                        }
                    }

                    return(new ResultReport <Script>(false, null, errorMsg));
                }

                // Check and read .meta.json
                ResultReport <UpdateJson.Root> jsonReport = UpdateJson.ReadUpdateJson(metaJsonFile);
                if (!jsonReport.Success)
                {
                    return(new ResultReport <Script>(false, null, jsonReport.Message));
                }

                UpdateJson.Root      metaJson = jsonReport.Result;
                UpdateJson.FileIndex index    = metaJson.Index;
                if (index.Kind != UpdateJson.IndexEntryKind.Script)
                {
                    return(new ResultReport <Script>(false, null, "Update json is not of a script file"));
                }
                UpdateJson.ScriptInfo scInfo = index.ScriptInfo;
                if (scInfo.Format != UpdateJson.ScriptFormat.IniBased)
                {
                    return(new ResultReport <Script>(false, null, $"Format [{scInfo.Format}] of remote script [{sc.Title}] is not supported"));
                }
                UpdateJson.IniBasedScript iniScInfo = scInfo.IniBased;
                if (iniScInfo.Version <= sc.ParsedVersion)
                {
                    return(new ResultReport <Script>(false, null, $"You are using the lastest version of script [{sc.Title}]"));
                }

                // Download .script file
                httpReport = DownloadFile(updateUrl, tempScriptFile);
                if (!httpReport.Result)
                {
                    return(new ResultReport <Script>(false, null, httpReport.ErrorMsg));
                }

                // Verify downloaded .script file with FileMetadata
                ResultReport verifyReport = index.FileMetadata.VerifyFile(tempScriptFile);
                if (!verifyReport.Success)
                {
                    return(new ResultReport <Script>(false, null, $"Remote script [{sc.Title}] is corrupted"));
                }

                // Check downloaded script's version and check
                // Must have been checked with the UpdateJson
                string    remoteVerStr = IniReadWriter.ReadKey(tempScriptFile, "Main", "Version");
                VersionEx remoteVer    = VersionEx.Parse(remoteVerStr);
                if (remoteVer == null)
                {
                    return(new ResultReport <Script>(false, null, $"Version of remote script [{sc.Title}] is corrupted"));
                }
                if (!remoteVer.Equals(iniScInfo.Version))
                {
                    return(new ResultReport <Script>(false, null, $"Version of remote script [{sc.Title}] is corrupted"));
                }
                if (remoteVer <= sc.ParsedVersion)
                {
                    return(new ResultReport <Script>(false, null, $"Version of remote script [{sc.Title}] is corrupted"));
                }

                // Check if remote script is valid
                Script remoteScript = _p.LoadScriptRuntime(tempScriptFile, new LoadScriptRuntimeOptions
                {
                    IgnoreMain             = false,
                    AddToProjectTree       = false,
                    OverwriteToProjectTree = false,
                });
                if (remoteScript == null)
                {
                    return(new ResultReport <Script>(false, null, $"Remote script [{sc.Title}] is corrupted"));
                }

                // Overwrite backup state to new script
                if (stateBackup != null)
                {
                    RestoreScriptState(remoteScript, stateBackup);

                    // Let's be extra careful
                    remoteScript = _p.RefreshScript(remoteScript);
                    if (remoteScript == null)
                    {
                        return(new ResultReport <Script>(false, null, $"Internal error at {nameof(FileUpdater)}.{nameof(RestoreScriptState)}"));
                    }
                }

                // Copy downloaded remote script into new script
                File.Copy(tempScriptFile, sc.DirectRealPath, true);
                Script newScript = _p.RefreshScript(sc);

                // Return updated script instance
                return(new ResultReport <Script>(true, newScript, $"Updated script [{sc.Title}] to [v{sc.RawVersion}] from [v{newScript.RawVersion}]"));
            }
            finally
            {
                if (File.Exists(metaJsonFile))
                {
                    File.Delete(metaJsonFile);
                }
                if (File.Exists(tempScriptFile))
                {
                    File.Delete(tempScriptFile);
                }
            }
        }