Example #1
0
 /// <summary>
 /// 根据类型名称获取子段模板
 /// </summary>
 /// <param name="typeName">类型名称</param>
 /// <param name="name">子段模板名称</param>
 /// <returns>子段模板</returns>
 protected override TreeBuilder.Node fromNameNode(string typeName, ref SubString name)
 {
     TreeBuilder.Node node = GetNode(typeName);
     if (node != null)
     {
         node = node.GetFirstNodeByTag(Command.NAME, ref name);
         if (node == null)
         {
             Messages.Error("模板文件 " + getTemplateFileName(typeName) + " 未找到NAME " + name.ToString());
         }
     }
     return(node);
 }
Example #2
0
 /// <summary>
 /// 安装入口
 /// </summary>
 /// <param name="parameter">安装参数</param>
 /// <returns>是否安装成功</returns>
 public bool Run(ProjectParameter parameter)
 {
     if (parameter != null)
     {
         HashSet <string> codeFileNames = new HashSet <string>();
         foreach (Type type in parameter.Types ?? EmptyArray <Type> .Array)
         {
             if (!type.IsAbstract && typeof(CombinationTemplateConfig).IsAssignableFrom(type) && type != typeof(CombinationTemplateConfig))
             {
                 CombinationTemplateConfig config = (CombinationTemplateConfig)Activator.CreateInstance(type);
                 string codeFileName = config.GetCodeFileName(parameter.DefaultNamespace);
                 if (!codeFileNames.Add(codeFileName))
                 {
                     Messages.Error("自定义简单组合模板目标文件名称冲突 " + codeFileName);
                     return(false);
                 }
                 LeftArray <string> codes = new LeftArray <string>(0);
                 foreach (string templatePath in config.TemplatePath)
                 {
                     DirectoryInfo directory = new DirectoryInfo(Path.Combine(parameter.ProjectPath, templatePath));
                     if (directory.Exists)
                     {
                         foreach (FileInfo file in directory.GetFiles("*.cs"))
                         {
                             LeftArray <string> newCodes = getCode(file.FullName);
                             if (newCodes.Length == 0)
                             {
                                 return(false);
                             }
                             codes.Add(ref newCodes);
                         }
                     }
                     else
                     {
                         Messages.Error("没有找到自定义模板相对项目路径" + config.TemplatePath);
                         return(false);
                     }
                 }
                 string fileName = Path.Combine(parameter.ProjectPath, @"{" + codeFileName + "}.CombinationTemplate.cs");
                 if (Coder.WriteFile(fileName, Coder.WarningCode + string.Concat(codes.ToArray()) + Coder.FileEndCode))
                 {
                     Messages.Message(fileName + " 被修改");
                 }
             }
         }
         return(true);
     }
     return(false);
 }
Example #3
0
 /// <summary>
 /// 根据类型名称获取CSharp代码树节点
 /// </summary>
 /// <param name="fileName"></param>
 /// <returns>CSharp代码树节点</returns>
 internal TreeBuilder.Node GetNode(string fileName)
 {
     TreeBuilder.Node node;
     if (!nodeCache.TryGetValue(fileName + extensionName, out node))
     {
         fileName = getTemplateFileName(fileName);
         if (File.Exists(fileName))
         {
             nodeCache.Add(fileName, node = new TreeBuilder().Create(File.ReadAllText(fileName)));
         }
         else
         {
             Messages.Error("未找到模板文件 " + fileName);
         }
     }
     return(node);
 }
Example #4
0
        /// <summary>
        /// 复制脚本文件
        /// </summary>
        private void copyScript()
        {
            string        scriptPath   = Parameter.ProjectPath + @"Js\";
            DirectoryInfo AutoCSerPath = new DirectoryInfo(AutoCSerScriptPath);

            copyJs(AutoCSerPath, scriptPath);
            foreach (DirectoryInfo directory in AutoCSerPath.GetDirectories())
            {
                switch (directory.Name)
                {
                case "ace": copyJs(directory, scriptPath + directory.Name + @"\", new string[] { "load.js", "ace.js" }); break;

                case "mathJax": copyJs(directory, scriptPath + directory.Name + @"\", new string[] { "load.js", "MathJax.js" }); break;

                case "highcharts": copyJs(directory, scriptPath + directory.Name + @"\"); break;

                default: Messages.Error("未知的js文件夹 " + directory.fullName()); break;
                }
            }
        }
Example #5
0
        /// <summary>
        /// 安装入口
        /// </summary>
        /// <param name="parameter">安装参数</param>
        /// <returns>是否安装成功</returns>
        public bool Run(ProjectParameter parameter)
        {
            if (parameter != null)
            {
                if (parameter.IsAutoCSerCodeGenerator || parameter.IsCustomCodeGenerator)
                {
                    LeftArray <Definition> definitions = (parameter.IsCustomCodeGenerator ? parameter.Assembly : ProjectParameter.CurrentAssembly).GetTypes().getArray(type => new Definition {
                        Type = type, Auto = type.customAttribute <GeneratorAttribute>(), Parameter = parameter
                    })
                                                         .getFind(type => type.Auto != null && type.Auto.IsTemplate)// && type.Auto.DependType == typeof(cSharper)
                                                         .Sort((left, right) => string.CompareOrdinal(left.Type.FullName, right.Type.FullName));
                    LeftArray <string> codes = new LeftArray <string>(definitions.Length);
                    foreach (Definition definition in definitions)
                    {
                        codes.Add(definition.ToString());
                        if (Messages.IsError)
                        {
                            return(false);
                        }
                    }
#if DotNetStandard
                    string path = new System.IO.FileInfo(parameter.AssemblyPath).Directory.fullName();
                    copyDotNetCoreJson(path, "AutoCSer.CodeGenerator.deps.json");
                    copyDotNetCoreJson(path, "AutoCSer.CodeGenerator.runtimeconfig.dev.json");
                    copyDotNetCoreJson(path, "AutoCSer.CodeGenerator.runtimeconfig.json");
#endif
                    string fileName = parameter.ProjectPath + @"{AutoCSer}.CSharper.cs";
                    if (Coder.WriteFile(fileName, Coder.WarningCode + string.Concat(codes.ToArray()) + Coder.FileEndCode))
                    {
                        Messages.Error(fileName + " 被修改");
                        return(false);
                    }
                }
                return(true);
            }
            return(false);
        }
Example #6
0
 /// <summary>
 /// 启动代码生成
 /// </summary>
 public void Start()
 {
     if (string.IsNullOrEmpty(ProjectPath) || !Directory.Exists(ProjectPath))
     {
         Messages.Error("项目路径不存在 : " + ProjectPath);
     }
     else
     {
         try
         {
             if (IsAutoCSerCodeGenerator || IsCustomCodeGenerator)
             {
                 run(new CSharper());
             }
             else
             {
                 KeyValue <Type, GeneratorAttribute>[] generators = (CustomConfig.Default.IsAutoCSer ? CurrentAssembly.GetTypes() : EmptyArray <Type> .Array)
                                                                    .concat(CustomConfig.Assembly == null ? EmptyArray <Type> .Array : CustomConfig.Assembly.GetTypes())
                                                                    .getFind(type => !type.IsInterface && !type.IsAbstract && typeof(IGenerator).IsAssignableFrom(type))
                                                                    .GetArray(type => new KeyValue <Type, GeneratorAttribute>(type, type.customAttribute <GeneratorAttribute>()))
                                                                    .getFind(value => value.Value != null && value.Value.IsAuto).ToArray();
                 if (generators.Length != 0)
                 {
                     generators = generators.sort((left, right) => string.CompareOrdinal(left.Key.FullName, right.Key.FullName));
                     HashSet <HashType> types = generators.getHash(value => (HashType)value.Key);
                     KeyValue <HashType, HashType>[] depends = generators
                                                               .getFind(value => value.Value.DependType != null && types.Contains(value.Value.DependType))
                                                               .GetArray(value => new KeyValue <HashType, HashType>((HashType)value.Key, (HashType)value.Value.DependType));
                     foreach (Type type in AutoCSer.Algorithm.TopologySort.Sort(depends, types, true))
                     {
                         run(type.Assembly.CreateInstance(type.FullName) as IGenerator);
                     }
                 }
                 if (CustomConfig.Default.IsAutoCSer)
                 {
                     foreach (Type type in Types)
                     {
                         if (!type.IsGenericType && !type.IsInterface && !type.IsEnum)
                         {
                             foreach (Metadata.MethodIndex methodInfo in Metadata.MethodIndex.GetMethods <TestMethodAttribute>(type, MemberFilters.Static, false, true, false))
                             {
                                 MethodInfo method = methodInfo.Method;
                                 if (method.IsGenericMethod)
                                 {
                                     //isTest = false;
                                     Messages.Message("测试用例不能是泛型函数 " + method.fullName());
                                 }
                                 else
                                 {
                                     Type returnType = method.ReturnType;
                                     if ((returnType == typeof(bool) || returnType == typeof(void)) && method.GetParameters().Length == 0)
                                     {
                                         try
                                         {
                                             object returnValue = method.Invoke(null, null);
                                             if (method.ReturnType == typeof(bool) && !(bool)returnValue)
                                             {
                                                 //isTest = false;
                                                 Messages.Message("测试用例调用失败 " + method.fullName());
                                             }
                                         }
                                         catch (Exception error)
                                         {
                                             Messages.Message(error.ToString());
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         catch (Exception error)
         {
             if (CustomConfig.Assembly == null)
             {
                 Messages.Exception(error);
             }
             else
             {
                 Messages.Error(CustomConfig.Assembly.FullName + "\r\n" + error.ToString());
             }
         }
         finally { Coder.Output(this); }
     }
 }
Example #7
0
        ///// <summary>
        ///// 添加没有依赖的记忆代码
        ///// </summary>
        ///// <param name="code">没有依赖的记忆代码</param>
        //[MethodImpl(AutoCSer.MethodImpl.AggressiveInlining)]
        //public static void AddRemember(string code)
        //{
        //    rememberCodes.Add(code);
        //}
        /// <summary>
        /// 输出代码
        /// </summary>
        public static void Output(ProjectParameter parameter)
        {
            StringArray[] builders = new StringArray[codes.Length];
            for (int index = codes.Length; index != 0;)
            {
                StringArray builder = codes[--index];
                if (builder.Length != 0)
                {
                    builders[index] = builder;
                    codes[index]    = new StringArray();
                }
                CodeLanguage language = (CodeLanguage)(byte)index;
                switch (language)
                {
                case CodeLanguage.JavaScript:
                case CodeLanguage.TypeScript:
                    if (builders[index] != null)
                    {
                        Messages.Error("生成了未知的 " + language + " 代码。");
                    }
                    break;
                }
            }
            //StringArray rememberCodeBuilder = null;
            //if (rememberCodes.Length != 0)
            //{
            //    rememberCodeBuilder = rememberCodes;
            //    rememberCodes = new StringArray();
            //}
            codeTypes.Clear();
            if (Messages.IsError)
            {
                return;
            }
            //string message = string.Empty;
            for (int index = builders.Length; index != 0;)
            {
                StringArray builder = builders[--index];
                if (builder != null)
                {
                    switch (index)
                    {
                    case (int)CodeLanguage.CSharp:
                        string code = builder.ToString(), AutoCSerFileName = null;
#if !DotNetStandard
                        bool isAutoCSer = false;
#endif
                        if (!string.IsNullOrEmpty(code))
                        {
                            string fileName = parameter.ProjectPath + (AutoCSerFileName = "{" + parameter.DefaultNamespace + "}.AutoCSer.cs");
                            if (WriteFile(fileName, WarningCode + code + FileEndCode))
                            {
#if !DotNetStandard
                                isAutoCSer = true;
#endif
                                Messages.Message(fileName + " 被修改");
                                //message = fileName + " 被修改";
                            }
                        }
#if !DotNetStandard
                        if (parameter.IsProjectFile && isAutoCSer)
                        {
                            string projectFile = parameter.AssemblyPath + parameter.ProjectName + ".csproj";
                            if (File.Exists(projectFile))
                            {
                                string projectXml = File.ReadAllText(projectFile, System.Text.Encoding.UTF8);
                                if (isAutoCSer)
                                {
                                    AutoCSerFileName = @"<Compile Include=""" + AutoCSerFileName + @""" />";
                                }
                                int fileIndex;
                                if (isAutoCSer && (fileIndex = projectXml.IndexOf(AutoCSerFileName)) != -1)
                                {
                                    break;
                                }
                                string csFileName = @".cs"" />
";
                                if ((fileIndex = projectXml.IndexOf(csFileName)) != -1)
                                {
                                    if (isAutoCSer)
                                    {
                                        AutoCSerFileName += @"
    ";
                                    }
                                    projectXml = projectXml.Insert(fileIndex + csFileName.Length, AutoCSerFileName);
                                    MoveFile(projectFile, projectXml);
                                }
                            }
                        }
#endif
                        break;
                    }
                }
            }
            //if (message.Length != 0) AutoCSer.LogHelper.waitThrow(AutoCSer.LogLevel.All, message);
        }
Example #8
0
        /// <summary>
        /// 生成代码
        /// </summary>
        /// <param name="fileName">模板文件名</param>
        /// <returns>代码</returns>
        private static LeftArray <string> getCode(string fileName)
        {
            string code = File.ReadAllText(fileName, System.Text.Encoding.UTF8);
            int    startIndex = code.IndexOf("/*", StringComparison.Ordinal), endIndex = code.IndexOf(@"*/

", startIndex + 2, StringComparison.Ordinal);

            if (endIndex > 0 && startIndex > 0)
            {
                LeftArray <string[][]> headerArray = new LeftArray <string[][]>(0);
                foreach (SubString line in new SubString(startIndex += 2, endIndex - startIndex, code).Trim().Split('\n'))
                {
                    SubString headerLine = line.Trim();
                    if (headerLine.Length != 0)
                    {
                        headerArray.Add(headerLine.Split(';').GetArray(p => p.Split(',').GetArray(v => (string)v)));
                    }
                }
                if (headerArray.Length != 0)
                {
                    CombinationTemplateLink header = new CombinationTemplateLink(code = code.Substring(endIndex + 4));
                    int row = 0;
                    foreach (string[][] line in headerArray)
                    {
                        int col = 0;
                        foreach (string value in line[0])
                        {
                            bool isSplit = false;
                            CombinationTemplateLink link = header;
                            do
                            {
                                link = link.Split(value, row, col, ref isSplit);
                            }while (link != null);
                            if (!isSplit)
                            {
                                Messages.Error("自定义简单组合模板文件内容没有找到匹配替换标记 " + value + " : " + fileName);
                                return(new LeftArray <string>(0));
                            }
                            ++col;
                        }
                        ++row;
                    }
                    LeftArray <CombinationTemplateLink> linkArray = new LeftArray <CombinationTemplateLink>(0);
                    LeftArray <string> codeArray = new LeftArray <string>(0);
                    do
                    {
                        if (header.Row >= 0)
                        {
                            linkArray.Add(header);
                            header.Index = codeArray.Length;
                            codeArray.Add(string.Empty);
                        }
                        else
                        {
                            codeArray.Add(header.Code);
                        }
                    }while ((header = header.Next) != null);
                    CombinationTemplateHeaderEnumerable headerEnumerable = new CombinationTemplateHeaderEnumerable(ref headerArray, codeArray.ToArray(), linkArray.ToArray());
                    codeArray.Length = 0;
                    foreach (string enumerableCode in headerEnumerable.GetCode())
                    {
                        codeArray.Add(enumerableCode);
                    }
                    return(codeArray);
                }
                else
                {
                    Messages.Error("自定义简单组合模板文件缺少头部信息解析失败 : " + fileName);
                }
            }
            else
            {
                Messages.Error("自定义简单组合模板文件缺少头部注释信息 : " + fileName);
            }
            return(new LeftArray <string>(0));
        }