Example #1
0
        /// <summary>
        ///   加入腳本
        /// </summary>
        /// <param name="assembly">Assembly 組件資訊</param>
        public void AddScript(Assembly assembly)
        {
            Type[] cTypes = assembly.GetTypes();
            foreach (Type cType in cTypes)
            {
                ScriptPropertyAttribute[] cPropertys = cType.GetCustomAttributes(typeof(ScriptPropertyAttribute), false) as ScriptPropertyAttribute[];
                foreach (ScriptPropertyAttribute cProperty in cPropertys)
                {
                    int               iIndex        = 0;
                    string            sFullAssembly = cType.FullName;
                    ScriptInformation cScriptInfo   = new ScriptInformation(cType, cProperty);

                    lock (__cKeys) {
                        if (__cKeys.TryGetValue(sFullAssembly, out iIndex))
                        {
                            __cScripts[iIndex] = cScriptInfo;
                        }
                        else
                        {
                            iIndex = __cScripts.Count;
                            __cScripts.Add(cScriptInfo);
                            __cKeys.Add(sFullAssembly, iIndex);
                        }
                    }

                    if (onAdditionScript != null)
                    {
                        onAdditionScript(this, new AddationScriptEvent(assembly, cScriptInfo));
                    }
                }
            }
        }
Example #2
0
        private void frmScriptViewer_Load(object sender, EventArgs e)
        {
            List <ScriptInformation> cScripts = ScriptManager.Manager.Scripts;

            TreeNode cModuleItem = treeView.Nodes["treeItem_Module"];
            TreeNode cSignalItem = cModuleItem.Nodes["treeItem_Signal"];
            TreeNode cScriptItem = cModuleItem.Nodes["treeItem_Script"];

            int iCount = cScripts.Count;

            for (int i = 0; i < iCount; i++)
            {
                ScriptInformation cScriptInfo = cScripts[i];
                TreeNode          cNode       = new TreeNode();
                cNode.ImageIndex         = 1;
                cNode.SelectedImageIndex = 1;
                cNode.Tag  = cScriptInfo;
                cNode.Name = cScriptInfo.FullName;
                cNode.Text = cScriptInfo.Property.Comment;

                ScriptType cType = cScriptInfo.Property.ScriptType;
                switch (cType)
                {
                case ScriptType.Signal:
                    cSignalItem.Nodes.Add(cNode);
                    break;

                case ScriptType.Script:
                    cScriptItem.Nodes.Add(cNode);
                    break;
                }
            }

            cModuleItem.Expand();
        }
        public ScriptProcessorFixture()
        {
            Environment = FakeEnvironment.CreateUnixEnvironment();
            FileSystem  = new FakeFileSystem(Environment);

            Log             = Substitute.For <ICakeLog>();
            Installer       = Substitute.For <INuGetPackageInstaller>();
            ApplicationRoot = new DirectoryPath("/Working/Bin");

            AssembliesLocator = Substitute.For <INuGetPackageAssembliesLocator>();
            AssembliesLocator.FindAssemblies(Arg.Any <DirectoryPath>()).Returns(
                ci =>
            {
                var dir = FileSystem.GetDirectory(ci.Arg <DirectoryPath>());
                return(dir.GetFiles("*.dll", SearchScope.Recursive).ToArray());
            });

            // Create the script analyzer result.
            var script1 = new ScriptInformation("/Working/build.cake");

            script1.Addins.Add(new NuGetPackage("Addin")
            {
                Source = "http://example.com"
            });
            script1.Tools.Add(new NuGetPackage("Tool")
            {
                Source = "http://example.com"
            });
            Result = new ScriptAnalyzerResult(script1, new List <string>());
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var script = ScriptableObject.CreateInstance <ScriptAsset>();

            script.content = File.ReadAllBytes(ctx.assetPath);
            ctx.AddObjectToAsset($"VNBinary:{ctx.assetPath}", script, EditorGUIUtility.Load("File Icon/VNB Icon.png") as Texture2D);
            ctx.SetMainObject(script);
            ScriptInformation.CreateInformationFromAsset(ctx.assetPath);
        }
Example #5
0
 private static void ReloadDirectory(string root)
 {
     foreach (var directory in Directory.GetDirectories(root))
     {
         ReloadDirectory(directory);
     }
     foreach (var file in Directory.GetFiles(root).Where(e => e.EndsWith(".vns") || e.EndsWith(".vnb")))
     {
         RescanScriptInformation(ScriptInformation.CreateInformationFromAsset(file), false);
     }
 }
Example #6
0
        private void ApplyScriptsToDatabase(SchemaVersion currentVersion, ScriptInformation scriptInfo)
        {
            foreach (var location in scriptInfo.ScriptLocations.Where(sl => !sl.ContainsSchemaScripts))
            {
                TraceHelper.Info("Applying Change Scripts In '{0}'", location.Path);
                TraceHelper.Info("\tRunOnce: '{0}'", location.RunOnce);
                TraceHelper.Info("\tRecursive: '{0}'", location.Recursive);

                ApplyScriptsToDatabaseRecursiveDirectoryWalk(currentVersion, location, location.AbsolutePath);
            }
        }
Example #7
0
            public void Should_Set_Succeeded_To_True_If_Not_Any_Errors()
            {
                // Given
                var script = new ScriptInformation("./build.cake");

                // When
                var result = new ScriptAnalyzerResult(script, new List <string>(), new List <ScriptAnalyzerError>());

                // Then
                Assert.True(result.Succeeded);
            }
        internal frmScriptProperty(ScriptInformation scriptInformation)
        {
            InitializeComponent();

            ScriptPropertyAttribute cProperty = scriptInformation.Property;

            labVersion.Text    = cProperty.Version;
            labComment.Text    = cProperty.Comment;
            labCopyright.Text  = cProperty.Copyright;
            labName.Text       = scriptInformation.Name;
            labFullName.Text   = scriptInformation.FullName;
            labScriptType.Text = cProperty.ScriptType.ToString();
        }
Example #9
0
        /// <summary>
        ///   建立新的腳本執行個體
        /// </summary>
        /// <param name="scriptName">完整腳本名稱</param>
        /// <param name="args">腳本所需參數</param>
        /// <returns>返回值: CStudyAbstract 類別, null=無此腳本</returns>
        public CStudyAbstract CreateScript(string scriptName, object args)
        {
            int            iIndex  = 0;
            CStudyAbstract cScript = null;

            if (__cKeys.TryGetValue(scriptName, out iIndex))
            {
                ScriptInformation cScriptInfo = __cScripts[iIndex];
                cScript       = cScriptInfo.CreateScript(args);
                cScript.About = cScriptInfo.Property;
            }
            return(cScript);
        }
Example #10
0
            public void Should_Set_Succeeded_To_False_If_Any_Errors()
            {
                // Given
                var script = new ScriptInformation("./build.cake");
                var error  = new ScriptAnalyzerError("./build.cake", 1, "error message");

                // When
                var result = new ScriptAnalyzerResult(script, new List <string>(), new List <ScriptAnalyzerError> {
                    error
                });

                // Then
                Assert.False(result.Succeeded);
            }
Example #11
0
        private void treeView_DoubleClick(object sender, EventArgs e)
        {
            TreeNode cSelectedNode = treeView.SelectedNode;

            if (cSelectedNode != null)
            {
                ScriptInformation cInfo = cSelectedNode.Tag as ScriptInformation;
                if (cInfo != null)
                {
                    frmScriptProperty frmScriptProperty = new Forms.frmScriptProperty(cInfo);
                    frmScriptProperty.ShowDialog();
                }
            }
        }
Example #12
0
        public ScriptProcessorFixture()
        {
            Environment = FakeEnvironment.CreateUnixEnvironment();
            FileSystem  = new FakeFileSystem(Environment);
            Log         = Substitute.For <ICakeLog>();
            Installer   = Substitute.For <IPackageInstaller>();
            Installer.CanInstall(Arg.Any <PackageReference>(), Arg.Any <PackageType>()).Returns(true);
            InstallPath = new DirectoryPath("/Working/Bin");

            // Create the script analyzer result.
            var script = new ScriptInformation("/Working/build.cake");

            script.Addins.Add(new PackageReference("custom:?package=addin"));
            script.Tools.Add(new PackageReference("custom:?package=tool"));
            Result = new ScriptAnalyzerResult(script, new List <string>());
        }
Example #13
0
        private void SetScriptInformation(ScriptInformation scriptInformation)
        {
            __sScriptName = scriptInformation.FullName;
            __cScriptType = scriptInformation.Property.ScriptType;

            switch (__cScriptType)
            {
            case ScriptType.Script:
                break;

            case ScriptType.Signal:
                if (__cScriptSetting == null)
                {
                    __cScriptSetting = new SignalSetting();
                }
                break;
            }
        }
Example #14
0
            public void Should_Populate_Using_Static_From_Provided_Script()
            {
                // Given
                var script = new ScriptInformation("./build.cake");

                script.UsingStaticDirectives.Add("using static System.Math;");
                var other = new ScriptInformation("./other.cake");

                other.UsingStaticDirectives.Add("using static System.Console;");
                script.Includes.Add(other);

                // When
                var result = new ScriptAnalyzerResult(script, new List <string>());

                // Then
                Assert.Equal(2, result.UsingStaticDirectives.Count);
                Assert.Contains("using static System.Math;", result.UsingStaticDirectives);
                Assert.Contains("using static System.Console;", result.UsingStaticDirectives);
            }
Example #15
0
            public void Should_Populate_Tools_From_Provided_Script()
            {
                // Given
                var script = new ScriptInformation("./build.cake");

                script.Tools.Add(new NuGetPackage("First.Package"));
                var other = new ScriptInformation("./other.cake");

                other.Tools.Add(new NuGetPackage("Second.Package"));
                script.Includes.Add(other);

                // When
                var result = new ScriptAnalyzerResult(script, new List <string>());

                // Then
                Assert.Equal(2, result.Tools.Count);
                Assert.Contains(result.Tools, package => package.PackageId == "First.Package");
                Assert.Contains(result.Tools, package => package.PackageId == "Second.Package");
            }
Example #16
0
            public void Should_Populate_Addins_From_Provided_Script()
            {
                // Given
                var script = new ScriptInformation("./build.cake");

                script.Addins.Add(new PackageReference("nuget:?package=First.Package"));
                var other = new ScriptInformation("./other.cake");

                other.Addins.Add(new PackageReference("nuget:?package=Second.Package"));
                script.Includes.Add(other);

                // When
                var result = new ScriptAnalyzerResult(script, new List <string>());

                // Then
                Assert.Equal(2, result.Addins.Count);
                Assert.Contains(result.Addins, package => package.OriginalString == "nuget:?package=First.Package");
                Assert.Contains(result.Addins, package => package.OriginalString == "nuget:?package=Second.Package");
            }
Example #17
0
            public void Should_Populate_Using_Aliases_From_Provided_Script()
            {
                // Given
                var script = new ScriptInformation("./build.cake");

                script.UsingAliases.Add("using A = B;");
                var other = new ScriptInformation("./other.cake");

                other.UsingAliases.Add("using C = D;");
                script.Includes.Add(other);

                // When
                var result = new ScriptAnalyzerResult(script, new List <string>());

                // Then
                Assert.Equal(2, result.UsingAliases.Count);
                Assert.Contains("using A = B;", result.UsingAliases);
                Assert.Contains("using C = D;", result.UsingAliases);
            }
Example #18
0
            public void Should_Populate_Namespaces_From_Provided_Script()
            {
                // Given
                var script = new ScriptInformation("./build.cake");

                script.Namespaces.Add("A.B");
                var other = new ScriptInformation("./other.cake");

                other.Namespaces.Add("C.D");
                script.Includes.Add(other);

                // When
                var result = new ScriptAnalyzerResult(script, new List <string>());

                // Then
                Assert.Equal(2, result.Namespaces.Count);
                Assert.Contains("A.B", result.Namespaces);
                Assert.Contains("C.D", result.Namespaces);
            }
        /// <summary>
        /// Checks that the the <see cref="ScriptInformation"/> is valid.
        /// </summary>
        /// <param name="info">The info.</param>
        /// <exception cref="ParachuteException">Aborting. Incorrect Configuration.</exception>
        private void InformationChecks(ScriptInformation info)
        {
            if (info == null)
            {
                TraceHelper.Error("Configuration file '{0}' could not be parsed. See example files in GitHub Wiki.", FileName);
                throw new ParachuteException("Aborting. Incorrect Configuration.");
            }

            if (info.ScriptLocations.Count < 0)
            {
                TraceHelper.Error("Configuration file '{0}' contains no <scriptLocation> elements.", FileName);
                throw new ParachuteException("Aborting. Incorrect Configuration.");
            }

            if (info.ScriptLocations.Count(l => l.ContainsSchemaScripts) > 1)
            {
                TraceHelper.Error("Configuration file '{0}' contains more than one <scriptLocation> with containsSchemaScripts=\"true\".", FileName);
                throw new ParachuteException("Aborting. Incorrect Configuration.");
            }
        }
Example #20
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var text = new TextAsset(File.ReadAllText(ctx.assetPath, Encoding.UTF8));

            ctx.AddObjectToAsset($"VNScript:{ctx.assetPath}", text, EditorGUIUtility.Load("File Icon/VNS Icon.png") as Texture2D);
            ctx.SetMainObject(text);
            ScriptInformation.CreateInformationFromAsset(ctx.assetPath);
            if (!CompileConfiguration.Content.AutoCompile)
            {
                return;
            }
            try {
                CodeCompiler.CompileAsset(ctx.assetPath);
            } catch (CompileException compileException) {
                Debug.LogError($"Script {ctx.assetPath} contains error\n{compileException.Message}");
            } catch (Exception exception) {
                Debug.LogError($"Script {ctx.assetPath} compile failed\n{exception.Message}");
            }
            AssetDatabase.Refresh();
        }
        /// <summary>
        /// Loads this instance.
        /// </summary>
        /// <returns>The <see cref="ScriptInformation"/> object.</returns>
        public ScriptInformation Load()
        {
            ScriptInformation info = LoadFromFile();

            TraceHelper.Info("Validating Script Configuration File '{0}'", FileName);

            InformationChecks(info);

            foreach (var location in info.ScriptLocations)
            {
                LocationCheck(location);

                LocationCheckPath(location);

                LocationCheckPathContents(location);

                LocationCheckCustomScriptVariables(location);
            }

            return(info);
        }
Example #22
0
        public ScriptProcessorFixture()
        {
            Environment = FakeEnvironment.CreateUnixEnvironment();
            FileSystem  = new FakeFileSystem(Environment);

            Log             = Substitute.For <ICakeLog>();
            Installer       = Substitute.For <INuGetPackageInstaller>();
            ApplicationRoot = new DirectoryPath("/Working/Bin");

            // Create the script analyzer result.
            var script1 = new ScriptInformation("/Working/build.cake");

            script1.Addins.Add(new NuGetPackage("Addin")
            {
                Source = "http://example.com"
            });
            script1.Tools.Add(new NuGetPackage("Tool")
            {
                Source = "http://example.com"
            });
            Result = new ScriptAnalyzerResult(script1, new List <string>());
        }
        public void Can_Serialize_ScriptInformation()
        {
            var xns = new XmlSerializerNamespaces();

            xns.Add("", "");
            var v = new Variable {
                Key = "var1", DefaultValue = "somestring"
            };
            var s = new Script {
                ScriptName = "test"
            };

            s.Variables.Add(v);

            var sl = new ScriptLocation
            {
                Path                  = "..\\Some\\Path",
                Recursive             = false,
                RunOnce               = true,
                ContainsSchemaScripts = true
            };

            sl.Scripts.Add(s);

            var si = new ScriptInformation();

            si.ScriptLocations.Add(sl);
            si.ScriptLocations.Add(sl);
            si.ScriptLocations.Add(sl);

            var xs = new XmlSerializer(typeof(ScriptInformation));
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            xs.Serialize(sw, si, xns);

            Debug.WriteLine(sb.ToString());
            Assert.AreEqual(strScriptInformationXml, sb.ToString());
        }
Example #24
0
        public static void ShowPreviewSource(string[] lines, string[] pureLines, ScriptInformation[] infos, ref ScriptInformation[] selectedInfos)
        {
            if (lines == null || lines.Length == 0)
            {
                return;
            }
            if (pureLines == null || pureLines.Length != lines.Length)
            {
                pureLines = lines;
            }
            tabWidth   = RichLabel.CalcSize(new GUIContent("\t")).x;
            spaceWidth = RichLabel.CalcSize(new GUIContent(" ")).x;
            var  lineWidth = LinesStyle.CalcSize(new GUIContent(lines.Length.ToString())).x;
            Rect area      = EditorGUILayout.BeginVertical();
            ScriptInformation clickedInfo = null;

            for (int i = 0; i < lines.Length; i++)
            {
                Rect rect = uNodeGUIUtility.GetRect(new GUIContent(lines[i]), RichLabel);
                EditorGUI.LabelField(new Rect(rect.x, rect.y, lineWidth, rect.height), (i + 1).ToString(), LinesStyle);
                rect.x     += lineWidth + 6;
                rect.width -= lineWidth + 6;
                if (Event.current.type == EventType.Repaint)
                {
                    string label = lines[i].Replace("\t", "      ");
                    // string label = lines[i];
                    RichLabel.Draw(rect, label, false, false, false, false);
                    if (selectedInfos == null)
                    {
                        continue;
                    }
                    CalculatePosition(rect, pureLines[i], i, selectedInfos, (position, info) => {
                        GUI.DrawTexture(position, selectionTexture);
                    });
                }
                else if (Event.current.type == EventType.MouseDown)
                {
                    if (infos == null)
                    {
                        continue;
                    }
                    CalculatePosition(rect, pureLines[i], i, infos, (position, info) => {
                        if (position.Contains(Event.current.mousePosition))
                        {
                            if (clickedInfo != null)
                            {
                                if (clickedInfo.lineRange > info.lineRange || clickedInfo.lineRange == info.lineRange && clickedInfo.columnRange > info.columnRange)
                                {
                                    clickedInfo = info;
                                }
                            }
                            else
                            {
                                clickedInfo = info;
                            }
                        }
                    });
                }
            }
            if (clickedInfo != null)
            {
                selectedInfos = new ScriptInformation[] { clickedInfo };
                if (int.TryParse(clickedInfo.id, out var id))
                {
                    var obj = EditorUtility.InstanceIDToObject(id);
                    if (obj is NodeComponent)
                    {
                        uNodeEditor.HighlightNode(obj as NodeComponent);
                    }
                    else if (obj is RootObject)
                    {
                        var root = obj as RootObject;
                        if (root.startNode != null)
                        {
                            uNodeEditor.HighlightNode(root.startNode);
                        }
                        else
                        {
                            uNodeEditor.ChangeTarget(root);
                            uNodeEditor.window.Refresh();
                        }
                    }
                }
                else if (clickedInfo.id.StartsWith(CodeGenerator.KEY_INFORMATION_VARIABLE))
                {
                }
                window?.Repaint();
            }
            EditorGUILayout.EndVertical();
            GUI.Box(new Rect(area.x + lineWidth, area.y, 2, area.height), "");
        }
 internal AddationScriptEvent(Assembly assembly, ScriptInformation info)
 {
     this.Assembly          = assembly;
     this.ScriptInformation = info;
 }
Example #26
0
        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            // 重命名
            var movingFiles = movedFromAssetPaths
                              .WithIndex()
                              .Where(e => e.item.EndsWith(".vns") || e.item.EndsWith(".vnb") || e.item.EndsWith(".txt"))
                              .Select(e => (From: e.item, To: movedAssets[e.index]));

            foreach (var(movedFromAsset, moveToAsset) in movingFiles)
            {
                var origin = ScriptInformation.CreateInformationFromAsset(movedFromAsset);
                if (origin == null)
                {
                    continue;
                }
                var target = ScriptInformation.CreateInformationFromAsset(moveToAsset);
                if (target == null)
                {
                    CompileConfiguration.Content.Scripts.Remove(origin.Id);
                    continue;
                }
                if (movedFromAsset.EndsWith(".vns"))
                {
                    if (moveToAsset.EndsWith(".vns"))   // vns -> vns
                    // 同步Hash
                    {
                        target.Hash = target.Hash ?? origin.Hash;
                        // 移动翻译文件
                        foreach (var(language, path) in origin.Translations)
                        {
                            if (!target.Translations.ContainsKey(language))
                            {
                                target.Translations.Add(language, path);
                            }
                            var from = origin.LanguageAssetPath(language);
                            var to   = target.LanguageAssetPath(language);
                            if (from != to && File.Exists(from))
                            {
                                File.Move(from, to);
                            }
                        }
                        // 移动编译文件
                        target.RecordedHash = target.RecordedHash ?? origin.RecordedHash;
                        var binaryFile       = origin.BinaryAssetPath();
                        var targetBinaryFile = target.BinaryAssetPath();
                        if (binaryFile != targetBinaryFile && File.Exists(binaryFile))
                        {
                            File.Move(binaryFile, targetBinaryFile);
                        }
                    }
                    // 删除旧配置
                    CompileConfiguration.Content.Scripts.Remove(origin.Id);
                }
                else if (movedFromAsset.EndsWith(".vnb"))
                {
                    if (moveToAsset.EndsWith(".vnb"))   // vnb -> vnb
                    // 同步Hash
                    {
                        target.RecordedHash = target.RecordedHash ?? origin.RecordedHash;
                        // 移动翻译文件
                        foreach (var(language, path) in origin.Translations)
                        {
                            if (!target.Translations.ContainsKey(language))
                            {
                                target.Translations.Add(language, path);
                            }
                            var from = origin.LanguageAssetPath(language);
                            var to   = target.LanguageAssetPath(language);
                            if (from != to && File.Exists(from))
                            {
                                File.Move(from, to);
                            }
                        }
                        // 移动源文件
                        target.Hash = target.Hash ?? origin.Hash;
                        var sourceFile       = origin.SourceAssetPath();
                        var targetSourceFile = target.SourceAssetPath();
                        if (sourceFile != targetSourceFile && File.Exists(sourceFile))
                        {
                            File.Move(sourceFile, targetSourceFile);
                        }
                    }
                    // 删除旧配置
                    CompileConfiguration.Content.Scripts.Remove(origin.Id);
                }
            }
            // 处理删除
            foreach (var file in deletedAssets.Where(e => e.EndsWith(".vns") || e.EndsWith(".txt") || e.EndsWith(".vnb")))
            {
                var id = ScriptInformation.CreateIdFromAsset(file);
                if (id == null)
                {
                    continue;
                }
                if (CompileConfiguration.Content.Scripts.ContainsKey(id))
                {
                    CompileConfigurationWindow.RescanScriptInformation(CompileConfiguration.Content.Scripts[id]);
                }
            }
            AssetDatabase.Refresh();
        }
Example #27
0
        /// <summary>
        /// 重新扫描项目并更新目标脚本的信息
        /// </summary>
        /// <param name="option">目标脚本信息</param>
        /// <param name="save">是否扫描完成后自动保存</param>
        public static void RescanScriptInformation(ScriptInformation option, bool save = true)
        {
            var source = option.SourceAssetPath();

            if (!string.IsNullOrEmpty(source))
            {
                if (File.Exists(source))
                {
                    option.hash = Hasher.Crc32(Encoding.UTF8.GetBytes(File.ReadAllText(source, Encoding.UTF8).UnifyLineBreak()));
                }
                else
                {
                    option.hash = null;
                }
            }
            var binary = option.BinaryAssetPath();

            if (!string.IsNullOrEmpty(binary))
            {
                if (File.Exists(source))
                {
                    var stream = new FileStream(binary, FileMode.Open);
                    var hash   = ScriptInformation.ReadBinaryHash(stream);
                    stream.Close();
                    option.recordedHash = hash;
                }
                else
                {
                    option.recordedHash = null;
                }
            }
            var detectedLanguage = new List <string>();

            foreach (var language in Directory.GetDirectories($"Assets/{CompileConfiguration.Content.TranslationFolder}").Select(Path.GetFileName))
            {
                if (File.Exists($"Assets/{CompileConfiguration.Content.TranslationFolder}/{language}/{option.id}.txt"))
                {
                    if (!option.Translations.ContainsKey(language))
                    {
                        option.Translations.Add(language, null);
                    }
                    detectedLanguage.Add(language);
                }
                else
                {
                    if (option.Translations.ContainsKey(language))
                    {
                        option.Translations.Remove(language);
                    }
                }
            }
            var needRemove = new List <string>();

            foreach (var(key, _) in option.Translations)
            {
                if (!detectedLanguage.Contains(key))
                {
                    needRemove.Add(key);
                }
            }
            foreach (var key in needRemove)
            {
                option.Translations.Remove(key);
            }
            if (!option.HasSource() && !option.HasBinary())
            {
                CompileConfiguration.Content.Scripts.Remove(option.id);
            }
            if (save)
            {
                CompileConfiguration.Save();
            }
        }
Example #28
0
        /// <summary>
        /// 编译文件
        /// </summary>
        /// <param name="path">脚本ID</param>
        /// <param name="forceCompile">是否强制重新编译</param>
        /// <returns>发生变化的文件列表</returns>
        public static IEnumerable <string> CompileAsset(string path, bool forceCompile = false)
        {
            if (!Application.isEditor)
            {
                throw new NotSupportedException($"Cannot compile {path}: static file compiler can only run in editor mode");
            }
            if (!path.EndsWith(".vns"))
            {
                throw new NotSupportedException($"Cannot compile {path}: file name extension must be .vns");
            }
            var option = ScriptInformation.CreateInformationFromAsset(path);

            if (option == null)
            {
                throw new NullReferenceException($"Cannot compile {path}: target outside of source folder or target is not acceptable script/binary");
            }
            var changedFiles = new List <string>();
            var source       = File.ReadAllText(path, Encoding.UTF8).UnifyLineBreak();

            if (!option.hash.HasValue)
            {
                option.hash = Hasher.Crc32(Encoding.UTF8.GetBytes(source));
            }
            var identifier = new CodeIdentifier {
                Id = option.id, Hash = option.hash.Value
            };

            // 编译文件
            if (!forceCompile)
            {
                if (option.recordedHash.HasValue && option.recordedHash.Value == identifier.Hash)
                {
                    return(new string[] { }); // 如果源代码内容没有变化则直接跳过编译
                }
            }
            var(content, defaultTranslation) = CompileCode(source, identifier);
            var binaryFile = option.BinaryAssetPath();

            File.WriteAllBytes(binaryFile, content);
            option.recordedHash = option.hash = identifier.Hash;
            changedFiles.Add(binaryFile);
            // 处理其他翻译
            foreach (var(language, _) in option.Translations)
            {
                var languageFile = option.LanguageAssetPath(language);
                if (File.Exists(languageFile))
                {
                    var existedTranslation = new ScriptTranslation(File.ReadAllText(languageFile));
                    if (!existedTranslation.MergeWith(defaultTranslation))
                    {
                        continue;
                    }
                    existedTranslation.SaveToAsset(languageFile);
                    changedFiles.Add(languageFile);
                }
                else
                {
                    // 如果翻译不存在,以默认翻译为蓝本新建翻译文件
                    defaultTranslation.SaveToAsset(languageFile);
                    changedFiles.Add(languageFile);
                }
            }
            CompileConfiguration.Save();
            return(changedFiles);
        }
Example #29
0
        private void frmSignalViewer_DragDrop(object sender, DragEventArgs e)
        {
            ScriptInformation cInfo = e.Data.GetData("__script") as ScriptInformation;

            frmFormatObject.Create(this.DockPanel, cInfo);
        }
Example #30
0
        private void dockPanels_DragDrop(object sender, DragEventArgs e)
        {
            ScriptInformation cInfo = e.Data.GetData("__script") as ScriptInformation;

            frmFormatObject.Create(this.dockPanels, cInfo);
        }