Exemple #1
0
        /// <summary>
        /// 生成Config
        /// </summary>
        public static void Generate(List <Source> sources, string outputFolder)
        {
            foreach (Source src in sources)
            {
                string content    = templete;
                string outputPath = outputFolder + "/" + src.configName + ".cs";

                string idType  = ConfigTools.SourceType2CSharpType(src.matrix[1, 0]);
                string idField = src.matrix[2, 0];

                //属性声明
                string declareProperties = "";
                for (int x = 0; x < src.column; x++)
                {
                    string comment = src.matrix[0, x];
                    string csType  = ConfigTools.SourceType2CSharpType(src.matrix[1, x]);
                    string field   = src.matrix[2, x];
                    string declare = string.Format(templete2, comment, csType, field);
                    declareProperties += declare;
                }

                //替换
                content = content.Replace("/*ClassName*/", src.configName);
                content = content.Replace("/*DeclareProperties*/", declareProperties);
                content = content.Replace("/*IDType*/", idType);
                content = content.Replace("/*IDField*/", idField);

                //写入
                ConfigTools.WriteFile(outputPath, content);
            }
        }
Exemple #2
0
        /// <summary>
        /// 获取所有源
        /// </summary>
        /// <returns></returns>
        private List <Source> GetSources()
        {
            //获取所有配置文件
            DirectoryInfo directory = new DirectoryInfo(cache.sourceFolder);

            FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);

            //可选选项


            string sv;
            string lf;

            //源
            List <Source> sources = new List <Source>();

            for (int i = 0, l = files.Length; i < l; i++)
            {
                FileInfo file = files[i];
                if (file.Extension != ".txt" && file.Extension != ".csv")
                {
                    continue;
                }

                Source source = new Source();

                string content;
                byte[] bytes;
                ConfigTools.ReadFile(file.FullName, out bytes);
                ConfigTools.DetectTextEncoding(bytes, out content);//转换不同的编码格式

                //判断换行符
                if (content.IndexOf("\r\n") != -1)
                {
                    lf = "\r\n";
                }
                else
                {
                    lf = "\n";
                }

                //判断分割符
                if (content.IndexOf("\t") != -1)
                {
                    sv = "\t";
                }
                else
                {
                    sv = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";//Fork:https://stackoverflow.com/questions/6542996/how-to-split-csv-whose-columns-may-contain
                }
                //写入源
                source.content    = content;
                source.sourceName = file.Name.Replace(file.Extension, ""); //文件名
                source.configName = source.sourceName + "Config";          //类名
                source.matrix     = ConfigTools.Content2Matrix(source.content, sv, lf, out source.row, out source.column);

                sources.Add(source);
            }
            return(sources);
        }
Exemple #3
0
        public static void Generate(List <SheetSource> sheets, List <StructSource> jsons, string outputFolder)
        {
            string outputPath = outputFolder + "/SerializableSet.cs";
            string content    = template;

            //Sheet声明
            string configDeclarations = "";

            foreach (SheetSource sheet in sheets)
            {
                string declaration = template2;
                declaration         = declaration.Replace("/*ConfigName*/", sheet.className);
                declaration         = declaration.Replace("/*SourceName*/", sheet.originalName);
                configDeclarations += declaration;
            }
            content = content.Replace("/*ConfigDeclarations*/", configDeclarations);

            //Json声明
            string jsonDeclarations = "";

            foreach (StructSource json in jsons)
            {
                string declaration = template3;
                declaration       = declaration.Replace("/*JsonName*/", json.className);
                declaration       = declaration.Replace("/*SourceName*/", json.originalName);
                jsonDeclarations += declaration;
            }
            content = content.Replace("/*JsonDeclarations*/", jsonDeclarations);

            ConfigTools.WriteFile(outputPath, content);
        }
        /// <summary>
        /// 从源数据反射为对应的配置数组
        /// </summary>
        /// <returns></returns>
        private static Array Source2Configs(Source source)
        {
            Type configType = FindType(source.configName);

            int   count   = source.row - 3;
            Array configs = Array.CreateInstance(configType, count);

            for (int y = 3, i = 0; i < count; y++, i++)
            {
                object config = Activator.CreateInstance(configType);
                for (int x = 0; x < source.column; x++)
                {
                    string    valueType   = source.matrix[1, x];
                    string    valueField  = source.matrix[2, x];
                    string    valueString = source.matrix[y, x];
                    FieldInfo field       = configType.GetField(valueField);

                    try
                    {
                        object value = ConfigTools.SourceValue2Object(valueType, valueString);
                        field.SetValue(config, value);
                    }
                    catch
                    {
                        UnityEngine.Debug.LogError(string.Format("SourceValue2Object Error!valueType={0},valueString={1}", valueType, valueString));
                    }
                }
                configs.SetValue(config, i);
            }
            return(configs);
        }
Exemple #5
0
        /// <summary>
        /// 转换原始配置配型 -> CShartType
        /// </summary>
        private static void ConvertOriginalType(string[,] matrix)
        {
            int column = matrix.GetLength(1);

            for (int x = 0; x < column; x++)
            {
                matrix[1, x] = ConfigTools.SourceType2CSharpType(x, matrix);
            }
        }
Exemple #6
0
        private static object ParseNode(XmlNode node)
        {
            //判断是否是对象或数组
            if (IsObject(node))
            {
                Dictionary <string, object> result = new Dictionary <string, object>();
                //添加属性字段
                if (node.Attributes != null)
                {
                    foreach (XmlAttribute attribute in node.Attributes)
                    {
                        result.Add(attribute.Name, ConfigTools.ConvertBaseObject(attribute.Value));
                    }
                }

                List <string> addedNodeNames = new List <string>();
                //添加子节点(如果多个同名子节点则是数组)
                foreach (XmlNode childNode in node.ChildNodes)
                {
                    if (childNode.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }

                    string childName = childNode.Name;
                    if (addedNodeNames.Contains(childName))
                    {
                        continue;
                    }

                    XmlNodeList sameNameNodes = node.SelectNodes(childName);//相同名字的

                    //数组
                    if (sameNameNodes.Count > 1)
                    {
                        object[] objects = new object[sameNameNodes.Count];
                        for (int i = 0, l = sameNameNodes.Count; i < l; i++)
                        {
                            XmlNode sameNameChild = sameNameNodes[i];
                            objects[i] = ParseNode(sameNameChild);
                        }
                        result.Add(childName, objects);
                    }
                    //对象
                    else
                    {
                        result.Add(childName, ParseNode(childNode));
                    }

                    addedNodeNames.Add(childName);
                }

                return(result);
            }
            return(ConfigTools.ConvertBaseObject(node.InnerText.Trim()));
        }
        /// <summary>
        /// 解析成员为键值对数组
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private static Pair[] ParseMembers(ref string content)
        {
            List <Pair> membersList = new List <Pair>();

            string original = content.ToString();

            //判断Object类型
            Pair[] pairsOfObject = ParsePairs(ref content, regexPairOfObject);
            foreach (Pair pair in pairsOfObject)
            {
                pair.index = original.IndexOf(pair.content);
                pair.value = ParseObject(ref pair.content);
            }
            membersList.AddRange(pairsOfObject);

            //判断Array类型
            Pair[] pairsOfArray = ParsePairs(ref content, regexPairOfArray);
            foreach (Pair pair in pairsOfArray)
            {
                pair.index = original.IndexOf(pair.content);
                pair.value = ParseArray(ref pair.content);
            }
            membersList.AddRange(pairsOfArray);

            //判断String类型
            Pair[] pairsOfString = ParsePairs(ref content, regexPairOfString);
            foreach (Pair pair in pairsOfString)
            {
                pair.index = original.IndexOf(pair.content);
                pair.value = pair.content;
            }
            membersList.AddRange(pairsOfString);

            //判断Number类型
            Pair[] pairsOfNumber = ParsePairs(ref content, regexPairOfNumber);
            foreach (Pair pair in pairsOfNumber)
            {
                pair.index = original.IndexOf(pair.content);
                pair.value = ConfigTools.ConvertNumber(pair.content);
            }
            membersList.AddRange(pairsOfNumber);

            //判断Bool类型
            Pair[] pairsOfBool = ParsePairs(ref content, regexPairOfBool);
            foreach (Pair pair in pairsOfBool)
            {
                pair.index = original.IndexOf(pair.content);
                pair.value = ConfigTools.ConvertBool(pair.content);
            }
            membersList.AddRange(pairsOfBool);

            //排序
            membersList.Sort(Pair.Compare);

            return(membersList.ToArray());
        }
Exemple #8
0
        public static void Generate(List <StructSource> structs, string outputFolder)
        {
            subObjects = new List <StructSubObject>();
            subID      = 0;

            //创建各个Json
            foreach (StructSource src in structs)
            {
                string content    = templateRoot;
                string outputPath = outputFolder + "/" + src.className + ".cs";

                //Decalre
                List <Declaration> declarations = DeclareObject(src.obj);


                string declarationStr = CombineDeclarations(declarations);

                //替换
                content = content.Replace("/*ClassName*/", src.className);
                content = content.Replace("/*Declarations*/", declarationStr);

                //写入
                ConfigTools.WriteFile(outputPath, content);
            }

            //创建JsonObject子类
            string allSubClasses = "";

            foreach (StructSubObject subObj in subObjects)
            {
                string declarations = CombineDeclarations(subObj.declarations);
                string subClass     = templateSubObject;
                subClass = subClass.Replace("/*ClassName*/", subObj.name);
                subClass = subClass.Replace("/*Declarations*/", declarations);

                allSubClasses += subClass;
            }

            //写入
            ConfigTools.WriteFile(outputFolder + "/" + "StructObjects.cs", allSubClasses);

            subObjects = null;
        }
        public static void Generate(List <Source> sources, string outputFolder)
        {
            string outputPath = outputFolder + "/SerializableSet.cs";
            string content    = templete;

            string declareConfigs = "";

            foreach (Source src in sources)
            {
                string declare = templete2;
                declare         = declare.Replace("/*ConfigName*/", src.configName);
                declare         = declare.Replace("/*SourceName*/", src.sourceName);
                declareConfigs += declare;
            }

            content = content.Replace("/*DeclareConfigs*/", declareConfigs);

            ConfigTools.WriteFile(outputPath, content);
        }
Exemple #10
0
        public static void Generate(List <SheetSource> sheets, List <StructSource> jsons, string outputFolder)
        {
            string outputPath = outputFolder + "/Deserializer.cs";
            string content    = template;

            //sheets
            string setDictionaries = "";

            foreach (SheetSource sheet in sheets)
            {
                string idField   = sheet.matrix[2, 0];
                string setScript = template2;

                setScript = setScript.Replace("/*ConfigName*/", sheet.className);
                setScript = setScript.Replace("/*SourceName*/", sheet.originalName);
                setScript = setScript.Replace("/*IDField*/", idField);

                setDictionaries += setScript;
            }

            //jsons
            string setJsons = "";

            foreach (StructSource json in jsons)
            {
                string setScript = template3;
                setScript = setScript.Replace("/*ClassName*/", json.className);
                setScript = setScript.Replace("/*SourceName*/", json.originalName);

                setJsons += setScript;
            }


            content = content.Replace("/*SetDictionaries*/", setDictionaries);
            content = content.Replace("/*SetJsons*/", setJsons);

            ConfigTools.WriteFile(outputPath, content);
        }
        public static void Generate(List <Source> sources, string outputFolder)
        {
            string outputPath = outputFolder + "/Deserializer.cs";
            string content    = templete;


            string setDictionaries = "";

            foreach (Source src in sources)
            {
                string idField   = src.matrix[2, 0];
                string setScript = templete2;

                setScript = setScript.Replace("/*ConfigName*/", src.configName);
                setScript = setScript.Replace("/*SourceName*/", src.sourceName);
                setScript = setScript.Replace("/*IDField*/", idField);

                setDictionaries += setScript;
            }

            content = content.Replace("/*SetDictionaries*/", setDictionaries);
            ConfigTools.WriteFile(outputPath, content);
        }
        private static object ParseBaseValue(string contentOfValue)
        {
            Match result;

            result = Regex.Match(contentOfValue, regexString);
            if (result.Success)
            {
                return(result.Groups[1].Value);
            }

            result = Regex.Match(contentOfValue, regexNumber);
            if (result.Success)
            {
                return(ConfigTools.ConvertNumber(result.Groups[1].Value));
            }

            result = Regex.Match(contentOfValue, regexBool);
            if (result.Success)
            {
                return(ConfigTools.ConvertBool(result.Groups[1].Value));
            }

            return(null);
        }
Exemple #13
0
        /// <summary>
        /// 检测数组中是否含有子对象
        /// </summary>
        /// <param name="array"></param>
        private static string DeclareArray(object[] array)
        {
            //判断是否需要创建Array类
            bool   arrayClass = false;
            Type   lt         = null;
            object li         = null;

            foreach (object item in array)
            {
                Type t = item.GetType();
                if (t.IsArray)
                {
                    arrayClass = true;
                    break;
                }
                if (lt != null)
                {
                    //类型不同
                    if (lt != t)
                    {
                        //数字类型不同不算
                        if (!ConfigTools.IsNumber(lt) || !ConfigTools.IsNumber(t))
                        {
                            arrayClass = true;
                            break;
                        }
                    }
                    //类型相同 && 都是Dictionary<string, object>
                    else if (t == ConfigConstants.OBJECT_DICTIONARY_TYPE)
                    {
                        if (!ConfigTools.IsSameObjectDictionary((Dictionary <string, object>)li, (Dictionary <string, object>)item))
                        {
                            arrayClass = true;
                            break;
                        }
                    }
                }
                lt = t;
                li = item;
            }

            //普通数组
            if (!arrayClass)
            {
                Type firstType = array[0].GetType();
                if (firstType == typeof(Dictionary <string, object>))
                {
                    return(GetSubObject((Dictionary <string, object>)array[0]) + "[]");
                }
                if (ConfigTools.IsNumber(firstType))//数字
                {
                    return(ConfigTools.FindMinimalNumberType(array).ToString() + "[]");
                }
                else
                {
                    //string bool
                    return(firstType.ToString() + "[]");
                }
            }
            else//创建数组对象
            {
                List <Declaration> declarations = new List <Declaration>();
                int i = 0;
                foreach (object item in array)
                {
                    Declaration declaration = new Declaration();
                    declaration.field = "arg" + i++;
                    declaration.type  = GetDeclarationType(item);
                    declarations.Add(declaration);
                }
                return(GetSubObject(declarations));
            }

            /*
             * //获取所有项的类型名称
             * Type type = array[0].GetType();
             * //对象
             * if (type == typeof(Dictionary<string, object>))
             * {
             *  return GetSubObject((Dictionary<string, object>)array[0]) + "[]";
             * }
             * //数组
             * else if (type.IsArray)
             * {
             *  Debug.LogError("不支持嵌套数组!");
             *  return "string";
             * }
             * else
             * {
             *  return type.ToString() + "[]";
             * }
             */
        }
Exemple #14
0
        /// <summary>
        /// 获取所有源
        /// </summary>
        /// <returns></returns>
        private void GetSources(out List <SheetSource> sheets, out List <StructSource> structs)
        {
            //获取所有配置文件
            DirectoryInfo directory = new DirectoryInfo(cache.sourceFolder);

            FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);

            //源
            sheets  = new List <SheetSource>();
            structs = new List <StructSource>();

            for (int i = 0, l = files.Length; i < l; i++)
            {
                FileInfo file = files[i];
                if (IsTemporaryFile(file.Name))//临时文件
                {
                    continue;
                }

                OriginalType type;
                if (!TypeEnabled(file.Extension, out type))
                {
                    continue;
                }

                //可以同时读流
                FileStream fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                ExcelWorksheet excelData = null;
                string         content   = "";

                //读取Excel
                if (type == OriginalType.Xlsx)
                {
                    ExcelPackage package = new ExcelPackage(fileStream);
                    excelData = package.Workbook.Worksheets[1];

                    fileStream.Close();
                }
                //其他
                else
                {
                    //读Byte
                    byte[]       bytes;
                    BinaryReader br = new BinaryReader(fileStream);
                    bytes = br.ReadBytes((int)fileStream.Length);
                    StreamReader renderer = new StreamReader(fileStream);
                    content = renderer.ReadToEnd();

                    ConfigTools.DetectTextEncoding(bytes, out content);//转换不同的编码格式

                    if (string.IsNullOrEmpty(content))
                    {
                        Debug.LogWarning(file.Name + "内容为空!");
                        continue;
                    }
                }

                switch (type)
                {
                case OriginalType.Txt:
                case OriginalType.Csv:
                    try
                    {
                        SheetSource source = SheetParser.Parse(content, file.Name);
                        sheets.Add(source);
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogError(file.Name + "解析失败!请检查格式是否正确,如果格式正确请联系作者:https://github.com/RickJiangShu/ConfigManager/issues" + "\n" + e);
                    }
                    break;

                case OriginalType.Json:
                    try
                    {
                        StructSource st = JsonParser.Parse(content, file.Name);
                        structs.Add(st);
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogError(file.Name + "解析失败!请检查格式是否正确,如果格式正确请联系作者:https://github.com/RickJiangShu/ConfigManager/issues" + "\n" + e);
                    }
                    break;

                case OriginalType.Xml:
                    try
                    {
                        StructSource st = XmlParser.Parse(content, file.Name);
                        structs.Add(st);
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogError(file.Name + "解析失败!请检查格式是否正确,如果格式正确请联系作者:https://github.com/RickJiangShu/ConfigManager/issues" + "\n" + e);
                    }
                    break;

                case OriginalType.Xlsx:
                    try
                    {
                        SheetSource st = SheetParser.Parse(excelData, file.Name);
                        sheets.Add(st);
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogError(file.Name + "解析失败!请检查格式是否正确,如果格式正确请联系作者:https://github.com/RickJiangShu/ConfigManager/issues" + "\n" + e);
                    }
                    break;
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// 保存缓存
        /// </summary>
        public void SaveCache()
        {
            string json = JsonUtility.ToJson(cache, true);

            ConfigTools.WriteFile(cacheDiskPath, json);
        }
        /// <summary>
        /// 解析数组
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private static object[] ParseArray(ref string content)
        {
            List <object> array = new List <object>();

            //排序
            string      original = content.ToString();
            List <Sort> sorts    = new List <Sort>();

            //Object
            MatchCollection matchObjects = MatchesAndRemove(ref content, regexObject);

            foreach (Match match in matchObjects)
            {
                string s = match.Groups[1].Value;
                sorts.Add(new Sort(original.IndexOf(s), ParseObject(ref s)));
            }

            //数组
            MatchCollection matchArraies = MatchesAndRemove(ref content, regexArray);

            foreach (Match match in matchArraies)
            {
                string s = match.Groups[1].Value;
                sorts.Add(new Sort(original.IndexOf(s), ParseArray(ref s)));
            }

            //String
            MatchCollection matchStrings = MatchesAndRemove(ref content, regexString);

            foreach (Match match in matchStrings)
            {
                string s = match.Groups[1].Value;
                sorts.Add(new Sort(original.IndexOf(s), s));
            }

            //Number
            MatchCollection matchNumbers = MatchesAndRemove(ref content, regexNumber);

            foreach (Match match in matchNumbers)
            {
                string s = match.Groups[1].Value;
                sorts.Add(new Sort(original.IndexOf(s), ConfigTools.ConvertNumber(s)));
            }

            //Bool
            MatchCollection matchBools = MatchesAndRemove(ref content, regexBool);

            foreach (Match match in matchBools)
            {
                string s = match.Groups[1].Value;
                sorts.Add(new Sort(original.IndexOf(s), ConfigTools.ConvertBool(s)));
            }

            //进行排序
            sorts.Sort(Sort.Compare);
            foreach (Sort s in sorts)
            {
                array.Add(s.data);
            }

            return(array.ToArray());
        }