示例#1
0
        // Compile a setting file, return a hash for template
        public TableCompileResult Compile(string path, string compileToFilePath, string compileBaseDir = null, bool doRealCompile = true)
        {
            // 确保目录存在
            compileToFilePath = Path.GetFullPath(compileToFilePath);
            string compileToFileDirPath = Path.GetDirectoryName(compileToFilePath);

            if (!Directory.Exists(compileToFileDirPath))
            {
                Directory.CreateDirectory(compileToFileDirPath);
            }

            string ext = Path.GetExtension(path);

            ITableSourceFile sourceFile;

            if (ext == ".tsv")
            {
                sourceFile = new SimpleTSVFile(path);
            }
            else
            {
                sourceFile = new SimpleExcelFile(path);
            }

            TableCompileResult hash = DoCompilerExcelReader(path, sourceFile, compileToFilePath, compileBaseDir, doRealCompile);

            return(hash);
        }
示例#2
0
        }                                                            // column + Default Values

        public TableTemplateVars(TableCompileResult compileResult, string extraString)
            : base()
        {
            var tabFileRelativePath = compileResult.TabFileRelativePath;

            RelativePaths.Add(compileResult.TabFileRelativePath);

            ClassName = DefaultClassNameParse(tabFileRelativePath);
            // 可自定义Class Name
            if (CustomClassNameFunc != null)
            {
                ClassName = CustomClassNameFunc(ClassName, tabFileRelativePath);
            }

            FieldsInternal       = compileResult.FieldsInternal;
            PrimaryKey           = compileResult.PrimaryKey;
            Columns2DefaultValus = new List <Hash>();

            Extra = extraString;
        }
示例#3
0
        /// <summary>
        /// 生成tml文件内容
        /// </summary>
        /// <param name="path">源excel的相对路径</param>
        /// <param name="excelFile"></param>
        /// <param name="compileToFilePath">编译后的tml文件路径</param>
        /// <param name="compileBaseDir"></param>
        /// <param name="doCompile"></param>
        /// <returns></returns>
        private TableCompileResult DoCompilerExcelReader(string path, ITableSourceFile excelFile, string compileToFilePath = null, string compileBaseDir = null, bool doCompile = true)
        {
            var renderVars = new TableCompileResult();

            renderVars.ExcelFile      = excelFile;
            renderVars.FieldsInternal = new List <TableColumnVars>();

            var tableBuilder  = new StringBuilder();
            var rowBuilder    = new StringBuilder();
            var ignoreColumns = new HashSet <int>();

            // Header Column
            foreach (var colNameStr in excelFile.ColName2Index.Keys)
            {
                var colIndex = excelFile.ColName2Index[colNameStr];
                if (!string.IsNullOrEmpty(colNameStr))
                {
                    var isCommentColumn = CheckCellType(colNameStr) == CellType.Comment;
                    if (isCommentColumn)
                    {
                        ignoreColumns.Add(colIndex);
                    }
                    else
                    {
                        //NOTE by qingqing-zhao 加入\t,从指定的列开始读取,但是dict的索引是从0开始
                        if (colIndex > 0)
                        {
                            tableBuilder.Append("\t");
                        }
                        tableBuilder.Append(colNameStr);

                        string typeName   = "string";
                        string defaultVal = "";

                        var attrs = excelFile.ColName2Statement[colNameStr].Split(new char[] { '|', '/' }, StringSplitOptions.RemoveEmptyEntries);
                        // Type
                        if (attrs.Length > 0)
                        {
                            typeName = attrs[0];
                        }
                        // Default Value
                        if (attrs.Length > 1)
                        {
                            defaultVal = attrs[1];
                        }
                        if (attrs.Length > 2)
                        {
                            if (attrs[2] == "pk")
                            {
                                renderVars.PrimaryKey = colNameStr;
                            }
                        }

                        renderVars.FieldsInternal.Add(new TableColumnVars
                        {
                            Index        = colIndex - ignoreColumns.Count, // count the comment columns
                            Type         = typeName,
                            Name         = colNameStr,
                            DefaultValue = defaultVal,
                            Comment      = excelFile.ColName2Comment[colNameStr],
                        });
                    }
                }
            }
            tableBuilder.Append("\n");

            // Statements rows, keeps
            foreach (var kv in excelFile.ColName2Statement)
            {
                var colName      = kv.Key;
                var statementStr = kv.Value;
                var colIndex     = excelFile.ColName2Index[colName];

                if (ignoreColumns.Contains(colIndex)) // comment column, ignore
                {
                    continue;
                }
                //NOTE by qingqing-zhao 加入\t,从指定的列开始读取,但是dict的索引是从0开始
                if (colIndex > 0)
                {
                    tableBuilder.Append("\t");
                }
                tableBuilder.Append(statementStr);
            }
            tableBuilder.Append("\n");
            //以上是tml写入的第一行


            // #if check, 是否正在if false模式, if false时,行被忽略
            var ifCondtioning = true;

            if (doCompile)
            {
                // 如果不需要真编译,获取头部信息就够了
                // Data Rows
                for (var startRow = 0; startRow < excelFile.GetRowsCount(); startRow++)
                {
                    rowBuilder.Length   = 0;
                    rowBuilder.Capacity = 0;
                    var columnCount = excelFile.GetColumnCount();
                    for (var loopColumn = 0; loopColumn < columnCount; loopColumn++)
                    {
                        if (!ignoreColumns.Contains(loopColumn)) // comment column, ignore 注释列忽略
                        {
                            var columnName = excelFile.Index2ColName[loopColumn];
                            var cellStr    = excelFile.GetString(columnName, startRow);

                            if (loopColumn == 0)
                            {
                                var cellType = CheckCellType(cellStr);
                                if (cellType == CellType.Comment) // 如果行首为#注释字符,忽略这一行)
                                {
                                    break;
                                }

                                // 进入#if模式
                                if (cellType == CellType.If)
                                {
                                    var ifVars     = GetIfVars(cellStr);
                                    var hasAllVars = true;
                                    foreach (var var in ifVars)
                                    {
                                        if (_config.ConditionVars == null ||
                                            !_config.ConditionVars.Contains(var)) // 定义的变量,需要全部配置妥当,否则if失败
                                        {
                                            hasAllVars = false;
                                            break;
                                        }
                                    }
                                    ifCondtioning = hasAllVars;
                                    break;
                                }
                                if (cellType == CellType.Endif)
                                {
                                    ifCondtioning = true;
                                    break;
                                }

                                if (!ifCondtioning) // 这一行被#if 忽略掉了
                                {
                                    break;
                                }


                                if (startRow != 0) // 不是第一行,往添加换行,首列
                                {
                                    rowBuilder.Append("\n");
                                }
                            }

                            /*
                             *  NOTE by qingqing-zhao 因为是从指定的列开始读取,所以>有效列 才加入\t
                             *  如果这列是空白的也不需要加入
                             */
                            if (!string.IsNullOrEmpty(columnName) &&
                                loopColumn > 0 &&
                                loopColumn < columnCount)   // 最后一列不需加tab
                            {
                                rowBuilder.Append("\t");
                            }

                            // 如果单元格是字符串,换行符改成\\n
                            cellStr = cellStr.Replace("\n", "\\n");
                            rowBuilder.Append(cellStr);
                        }
                    }

                    // 如果这行,之后\t或换行符,无其它内容,认为是可以省略的
                    if (!string.IsNullOrEmpty(rowBuilder.ToString().Trim()))
                    {
                        tableBuilder.Append(rowBuilder);
                    }
                }
            }
            //以上是tml写入其它行


            var    fileName = Path.GetFileNameWithoutExtension(path);
            string exportPath;

            if (!string.IsNullOrEmpty(compileToFilePath))
            {
                exportPath = compileToFilePath;
            }
            else
            {
                // use default
                exportPath = fileName + _config.ExportTabExt;
            }

            var exportDirPath = Path.GetDirectoryName(exportPath);

            if (!Directory.Exists(exportDirPath))
            {
                Directory.CreateDirectory(exportDirPath);
            }

            // 是否写入文件
            if (doCompile)
            {
                File.WriteAllText(exportPath, tableBuilder.ToString());
            }


            // 基于base dir路径
            var tabFilePath     = exportPath; // without extension
            var fullTabFilePath = Path.GetFullPath(tabFilePath).Replace("\\", "/");;

            if (!string.IsNullOrEmpty(compileBaseDir))
            {
                var fullCompileBaseDir = Path.GetFullPath(compileBaseDir).Replace("\\", "/");;
                tabFilePath = fullTabFilePath.Replace(fullCompileBaseDir, ""); // 保留后戳
            }
            if (tabFilePath.StartsWith("/"))
            {
                tabFilePath = tabFilePath.Substring(1);
            }

            renderVars.TabFileFullPath     = fullTabFilePath;
            renderVars.TabFileRelativePath = tabFilePath;

            return(renderVars);
        }
        /// <summary>
        /// 生成代码文件
        /// </summary>
        /// <param name="results"></param>
        /// <param name="settingCodeIgnorePattern"></param>
        /// <param name="forceAll"></param>
        /// <param name="genManagerClass"></param>
        /// <param name="templateVars">如果是生成Manager Class 一定要在外部初始化此字段</param>
        public void GenCodeFile(TableCompileResult compileResult, string genCodeTemplateString, string genCodeFilePath,
                                string nameSpace = "AppSettings", string changeExtension = ".tml", string settingCodeIgnorePattern = null, bool forceAll = false, bool genManagerClass = false, Dictionary <string, TableTemplateVars> templateVars = null)
        {
            // 根据编译结果,构建vars,同class名字的,进行合并
            if (!genManagerClass)
            {
                templateVars = new Dictionary <string, TableTemplateVars>();
            }
            if (!string.IsNullOrEmpty(settingCodeIgnorePattern))
            {
                var ignoreRegex = new Regex(settingCodeIgnorePattern);
                if (ignoreRegex.IsMatch(compileResult.TabFileRelativePath))
                {
                    return; // ignore this
                }
            }

            var customExtraStr = CustomExtraString != null?CustomExtraString(compileResult) : null;

            var templateVar = new TableTemplateVars(compileResult, customExtraStr);

            // 尝试类过滤
            var ignoreThisClassName = false;

            if (GenerateCodeFilesFilter != null)
            {
                for (var i = 0; i < GenerateCodeFilesFilter.Length; i++)
                {
                    var filterClass = GenerateCodeFilesFilter[i];
                    if (templateVar.ClassName.Contains(filterClass))
                    {
                        ignoreThisClassName = true;
                        break;
                    }
                }
            }
            if (!ignoreThisClassName)
            {
                if (!templateVars.ContainsKey(templateVar.ClassName))
                {
                    templateVars.Add(templateVar.ClassName, templateVar);
                }
                else
                {
                    templateVars[templateVar.ClassName].RelativePaths.Add(compileResult.TabFileRelativePath);
                }
                //templateVars[templateVar.ClassName].TabFileNames = compileResult.TabFileNames;
            }

            if (!genManagerClass)
            {
                //首字母大写,符合微软命名规范
                var newFileName = string.Concat(DefaultClassNameParse(compileResult.TabFileRelativePath), FileNameSuffix, ".cs");
                if (string.IsNullOrEmpty(genCodeFilePath))
                {
                    genCodeFilePath += string.Concat(DefaultGenCodeDir, newFileName);
                }
                else
                {
                    genCodeFilePath += newFileName;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(genCodeFilePath))
                {
                    genCodeFilePath += string.Concat(DefaultGenCodeDir, ManagerClassName);
                }
                else
                {
                    genCodeFilePath += ManagerClassName;
                }
            }


            // 整合成字符串模版使用的List
            var templateHashes = new List <Hash>();

            foreach (var kv in templateVars)
            {
                //TODO render 加多一项TabFilName
                var templateVar2       = kv.Value;
                var renderTemplateHash = Hash.FromAnonymousObject(templateVar2);
                templateHashes.Add(renderTemplateHash);
            }

            if (forceAll)
            {
                // force 才进行代码编译
                GenerateCode(genCodeTemplateString, genCodeFilePath, nameSpace, templateHashes);
            }
        }