protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context)
        {
            var    model             = context.GetVariable <object>("Model");
            var    entityUsingText   = context.GetVariable <string>("EntityUsingText");
            string templateDir       = context.GetVariable <string>("TemplateDirectory");
            var    modelingUsingText = TextGenerator.GenerateByTemplateName(templateDir, "DbContextModelCreatingExtensions_Using", model);
            var    entityConfigText  = TextGenerator.GenerateByTemplateName(templateDir, "DbContextModelCreatingExtensions_EntityConfig", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => 1,
                    entityUsingText,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityUsingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    modelingUsingText,
                    InsertPosition.After,
                    root => root.DescendantsNotContain <UsingDirectiveSyntax>(modelingUsingText)),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <MethodDeclarationSyntax>().First().GetEndLine(),
                    entityConfigText,
                    modifyCondition: root => root.Descendants <MethodDeclarationSyntax>().First().NotContains(entityConfigText)
                    )
            });
        }
Exemplo n.º 2
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context, CompilationUnitSyntax rootUnit)
        {
            var    model                 = context.GetVariable <object>("Model");
            string entityUsingText       = context.GetVariable <string>("EntityUsingText");
            string templateDir           = context.GetVariable <string>(VariableNames.TemplateDirectory);
            string dbContextUsingText    = TextGenerator.GenerateByTemplateName(templateDir, "DbContextInterface_Using", model);
            string dbContextPropertyText = TextGenerator.GenerateByTemplateName(templateDir, "DbContextInterface_Property", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => 1,
                    dbContextUsingText,
                    InsertPosition.Before,
                    root => root.DescendantsNotContain <UsingDirectiveSyntax>(dbContextUsingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    entityUsingText,
                    InsertPosition.After,
                    root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityUsingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <InterfaceDeclarationSyntax>().Single().GetEndLine(),
                    dbContextPropertyText,
                    modifyCondition: root => root.DescendantsNotContain <PropertyDeclarationSyntax>(dbContextPropertyText)
                    )
            });
        }
Exemplo n.º 3
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context)
        {
            var    model              = context.GetVariable <object>("Model");
            string entityUsingText    = context.GetVariable <string>("EntityUsingText");
            string entityDtoUsingText = context.GetVariable <string>("EntityDtoUsingText");
            string templateDir        = context.GetVariable <string>("TemplateDirectory");
            string contents           = TextGenerator.GenerateByTemplateName(templateDir, "ApplicationAutoMapperProfile_CreateMap", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    entityUsingText,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityUsingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    entityDtoUsingText,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityDtoUsingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ConstructorDeclarationSyntax>().Single().GetEndLine(),
                    contents,
                    modifyCondition: root => root.Descendants <ConstructorDeclarationSyntax>().Single().NotContains(contents)
                    )
            });
        }
Exemplo n.º 4
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context, CompilationUnitSyntax rootUnit)
        {
            var    serviceInterfaceInfo = context.GetVariable <TypeInfo>("InterfaceInfo");
            var    serviceClassInfo     = context.GetVariable <TypeInfo>("ClassInfo");
            var    controllerInfo       = context.GetVariable <TypeInfo>("ControllerInfo");
            string templateDir          = context.GetVariable <string>("TemplateDirectory");

            // Generate added methods
            var modifications = new List <ModificationBuilder <CSharpSyntaxNode> >();
            var addedMethods  = serviceClassInfo.Methods
                                .Except(controllerInfo.Methods)          // Except the existing controller methods
                                .Intersect(serviceInterfaceInfo.Methods) // Only methods defined in the interface need to generate
                                                                         // Why not just use the `serviceInterfaceInfo.Methods`? Because we need use attributes info
                                                                         // which only defined in the service class
            ;

            foreach (var method in addedMethods)
            {
                var    model      = new { method };
                string methodText = TextGenerator.GenerateByTemplateName(templateDir, "ControllerMethod", model);
                modifications.Add(
                    new InsertionBuilder <CSharpSyntaxNode>(
                        root => root.Descendants <ClassDeclarationSyntax>().First().GetEndLine(),
                        methodText
                        ));
            }

            return(modifications);
        }
Exemplo n.º 5
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context)
        {
            var    projectInfo = context.GetVariable <ProjectInfo>("ProjectInfo");
            var    model       = context.GetVariable <object>("Model");
            string templateDir = context.GetVariable <string>("TemplateDirectory");
            string permissionDefinitionsText = TextGenerator.GenerateByTemplateName(templateDir, "Permissions_Definitions", model);

            var builders = new List <ModificationBuilder <CSharpSyntaxNode> >();

            builders.Add(new InsertionBuilder <CSharpSyntaxNode>(
                             root => root.Descendants <MethodDeclarationSyntax>().First().GetEndLine(),
                             permissionDefinitionsText,
                             InsertPosition.Before,
                             root => root.DescendantsNotContain <ClassDeclarationSyntax>(permissionDefinitionsText)
                             ));

            if (projectInfo.TemplateType == TemplateType.Application)
            {
                // Noting special to do
            }
            else if (projectInfo.TemplateType == TemplateType.Module)
            {
                string addGroupText = TextGenerator.GenerateByTemplateName(templateDir, "Permissions_AddGroup", model);

                // Uncomment the add group statement
                builders.Add(new ReplacementBuilder <CSharpSyntaxNode>(
                                 root => root.Descendants <MethodDeclarationSyntax>().First().GetStartLine() + 2,
                                 root => root.Descendants <MethodDeclarationSyntax>().First().GetStartLine() + 2,
                                 addGroupText,
                                 modifyCondition: root => !root.DescendantsNotContain <MethodDeclarationSyntax>($"//" + addGroupText)
                                 ));
            }

            return(builders);
        }
Exemplo n.º 6
0
        protected override IList <ModificationBuilder <IEnumerable <LineNode> > > CreateModifications(
            WorkflowExecutionContext context)
        {
            var    model          = context.GetVariable <object>("Model");
            string templateDir    = context.GetVariable <string>("TemplateDirectory");
            string importContents = TextGenerator.GenerateByTemplateName(templateDir, "RoutingModule_ImportList", model);
            string moduleContents = TextGenerator.GenerateByTemplateName(templateDir, "RoutingModule_Routes", model);

            int LineExpression(IEnumerable <LineNode> lines) => lines.Last(l => l.IsMath($"const routes")).LineNumber;

            return(new List <ModificationBuilder <IEnumerable <LineNode> > >
            {
                new InsertionBuilder <IEnumerable <LineNode> >(
                    lines => lines.Last(l => l.IsMath("^import")).LineNumber,
                    importContents,
                    InsertPosition.After,
                    lines => lines.Where(l => l.IsMath("^import")).All(l => !l.LineContent.Contains(importContents))
                    ),
                new ReplacementBuilder <IEnumerable <LineNode> >(
                    LineExpression,
                    LineExpression,
                    moduleContents
                    )
            });
        }
Exemplo n.º 7
0
        protected override IList <ModificationBuilder <IEnumerable <LineNode> > > CreateModifications(
            WorkflowExecutionContext context)
        {
            var    model                = context.GetVariable <object>("Model");
            var    entityInfo           = context.GetVariable <EntityInfo>("EntityInfo");
            string templateDir          = context.GetVariable <string>(VariableNames.TemplateDirectory);
            string importContents       = TextGenerator.GenerateByTemplateName(templateDir, "Module_ImportSharedModule", model);
            string sharedModuleContents = TextGenerator.GenerateByTemplateName(templateDir, "Module_SharedModule", model);

            int LineExpression(IEnumerable <LineNode> lines) => lines.Last(l => l.IsMath($"{entityInfo.NamespaceLastPart}RoutingModule")).LineNumber;

            return(new List <ModificationBuilder <IEnumerable <LineNode> > >
            {
                new InsertionBuilder <IEnumerable <LineNode> >(
                    lines => lines.Last(l => l.IsMath("^import")).LineNumber,
                    importContents,
                    InsertPosition.After,
                    lines => lines.Where(l => l.IsMath("^import")).All(l => !l.LineContent.Contains(importContents))
                    ),
                new InsertionBuilder <IEnumerable <LineNode> >(
                    LineExpression,
                    sharedModuleContents,
                    InsertPosition.After,
                    lines => lines.All(l => !l.LineContent.Contains(sharedModuleContents))
                    )
            });
        }
Exemplo n.º 8
0
        protected override Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context, CancellationToken cancellationToken)
        {
            var projectInfo   = context.GetVariable <ProjectInfo>("ProjectInfo");
            var option        = context.GetVariable <object>("Option");
            var entityInfo    = context.GetVariable <EntityInfo>("EntityInfo");
            var interfaceInfo = context.GetVariable <TypeInfo>("InterfaceInfo");
            var classInfo     = context.GetVariable <TypeInfo>("ClassInfo");
            var variables     = context.GetVariables().Where(v => v.Key.StartsWith("Bag."));
            var bag           = new ExpandoObject();

            foreach (var variable in variables)
            {
                ((IDictionary <string, object>)bag)[variable.Key.RemovePreFix("Bag.")] = variable.Value.Value;
            }

            context.SetVariable("Model", new
            {
                ProjectInfo   = projectInfo,
                Option        = option,
                EntityInfo    = entityInfo,
                InterfaceInfo = interfaceInfo,
                ClassInfo     = classInfo,
                Bag           = bag,
            });
            return(Task.FromResult(Done()));
        }
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context)
        {
            var    model             = context.GetVariable <object>("Model");
            string templateDir       = context.GetVariable <string>("TemplateDirectory");
            string usingTaskContents = TextGenerator.GenerateByTemplateName(templateDir, "AppService_UsingTask", model);
            string usingDtoContents  = TextGenerator.GenerateByTemplateName(templateDir, "AppService_UsingDto", model);
            string classContents     = TextGenerator.GenerateByTemplateName(templateDir, "AppServiceClass", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => 1,
                    usingTaskContents,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(usingTaskContents)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => 1,
                    usingDtoContents,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(usingDtoContents)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ClassDeclarationSyntax>().Single().GetEndLine(),
                    classContents
                    ),
            });
        }
Exemplo n.º 10
0
        protected override async Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context,
                                                                               CancellationToken cancellationToken)
        {
            Logger.LogInformation("生成一个空的模块。");
            var modelInfo         = context.GetVariable <ModuleInfo>("ModuleInfo");
            var permissionControl = context.GetVariable <bool>("PermissionControl");

            var appDir  = AppDomain.CurrentDomain.BaseDirectory;
            var tempDir = Path.Combine(appDir, context.GetVariable <string>("TemplateDirectory"), "Generate", "src");

            if (!Directory.Exists(tempDir))
            {
                throw new DirectoryNotFoundException($"模板目录 {tempDir} 不存在。");
            }

            string targetDirectory = Path.Combine(context.GetVariable <string>("ProjectDirectory"), "src");
            var    overwrite       = context.GetVariable <bool>("Overwrite");

            var model = new GenerateEmptyModel
            {
                Name              = modelInfo.Name,
                ModuleInfo        = modelInfo,
                GenerateCreate    = true,
                GenerateEdit      = true,
                PermissionControl = permissionControl
            };

            await GenerateFiles(tempDir, targetDirectory, model, overwrite);

            return(Done());
        }
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context)
        {
            var    model           = context.GetVariable <object>("Model");
            string entityUsingText = context.GetVariable <string>("EntityUsingText");
            string templateDir     = context.GetVariable <string>("TemplateDirectory");
            string contents        = TextGenerator.GenerateByTemplateName(templateDir, "EntityFrameworkCoreModule_AddRepository", model);

            CSharpSyntaxNode Func(CSharpSyntaxNode root) => root
            .Descendants <ExpressionStatementSyntax>()
            .Single(node => node.ToString().Contains("AddAbpDbContext"))
            ;

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => 1,
                    entityUsingText,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityUsingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => Func(root).GetEndLine(),
                    contents,
                    modifyCondition: root => Func(root).NotContains(contents)
                    ),
            });
        }
Exemplo n.º 12
0
        protected override async Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context, CancellationToken cancellationToken)
        {
            var moduleInfo = context.GetVariable <ModuleInfo>("ModuleInfo");

            var appDir  = AppDomain.CurrentDomain.BaseDirectory;
            var tempDir = Path.Combine(appDir, context.GetVariable <string>("TemplateDirectory"), "Generate", "src", "views");

            if (!Directory.Exists(tempDir))
            {
                throw new DirectoryNotFoundException($"模板目录 {tempDir} 不存在。");
            }

            string targetDirectory = moduleInfo.Option.OutputFolder.IsNullOrWhiteSpace()
                ? Path.Combine(context.GetVariable <string>("ProjectDirectory"), "src", "views")
                : Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, moduleInfo.Option.OutputFolder));

            ModuleApiOperation postApi = context.GetVariable <ModuleApiOperation>("PostModuleApi");
            var apiSchema = postApi.Operation.RequestBody.Content.First().Value.Schema;

            var model = new GenerateModelModel
            {
                Name              = moduleInfo.Name,
                ModuleInfo        = moduleInfo,
                RequestBodySchema = apiSchema
            };

            var overwrite = context.GetVariable <bool>("Overwrite");

            await GenerateFiles(tempDir, targetDirectory, model, overwrite);

            return(Done());
        }
Exemplo n.º 13
0
        protected override Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context, CancellationToken cancellationToken)
        {
            var entityInfo  = context.GetVariable <EntityInfo>("EntityInfo");
            var projectInfo = context.GetVariable <ProjectInfo>("ProjectInfo");

            context.SetVariable("Model", new { EntityInfo = entityInfo, ProjectInfo = projectInfo });
            return(Task.FromResult(Done()));
        }
Exemplo n.º 14
0
        protected override ActivityExecutionResult OnExecute(WorkflowExecutionContext context)
        {
            var entityInfo = context.GetVariable <EntityInfo>("EntityInfo");
            var option     = context.GetVariable <object>("Option") as CrudCommandOption;

            try
            {
                string[] actionNames = { string.Empty, string.Empty, string.Empty };

                if (option != null && option.SeparateDto)
                {
                    actionNames[1] = "Create";
                    actionNames[2] = "Update";
                }
                else
                {
                    actionNames[1] = "CreateUpdate";
                    actionNames[2] = actionNames[1];
                }

                string[] typeNames = new string[actionNames.Length];

                var useEntityPrefix = option != null && option.EntityPrefixDto;
                var dtoSubfix       = option?.DtoSuffix ?? "Dto";

                for (int i = 0; i < typeNames.Length; i++)
                {
                    typeNames[i] = useEntityPrefix
                        ? $"{entityInfo.Name}{actionNames[i]}{dtoSubfix}"
                        : $"{actionNames[i]}{entityInfo.Name}{dtoSubfix}";
                }

                DtoInfo dtoInfo = new DtoInfo(typeNames[0], typeNames[1], typeNames[2]);

                context.SetLastResult(dtoInfo);
                context.SetVariable("DtoInfo", dtoInfo);
                LogOutput(() => dtoInfo);

                return(Done());
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Building DTO info failed.");
                if (e is ParseException pe)
                {
                    foreach (var error in pe.Errors)
                    {
                        Logger.LogError(error);
                    }
                }
                throw;
            }
        }
Exemplo n.º 15
0
        protected override async Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context,
                                                                               CancellationToken cancellationToken)
        {
            var option     = context.GetVariable <InitCommandOption>("Option");
            var projectDir = context.GetVariable <string>("ProjectDirectory");

            var haveAbpVueJsonFile =
                Directory.EnumerateFiles(projectDir, "abpvue.json", SearchOption.TopDirectoryOnly).Any();

            if (haveAbpVueJsonFile && !option.Overwrite)
            {
                Logger.LogWarning("项目已经初始化,请勿重复执行。");
                return(Done());
            }

            var tempDir = Path.Combine(context.GetVariable <string>("TemplateDirectory"), "Init");

            if (!Directory.Exists(tempDir))
            {
                throw new DirectoryNotFoundException($"模板目录 {tempDir} 不存在。");
            }


            string templatePath = null;

            if (!option.SaveTemplates.IsNullOrWhiteSpace())
            {
                // 保存模板到指定文件夹。
                templatePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, option.SaveTemplates, "Templates"));
                if (!Directory.Exists(templatePath))
                {
                    var dirInfo = Directory.CreateDirectory(templatePath);
                    templatePath = dirInfo.FullName;
                }

                // 将所有模板文件copy到指定目录。
                await CopyFilesAsync(context.GetVariable <string>("TemplateDirectory"), templatePath, option.Overwrite);
            }

            await GenerateFiles(tempDir, projectDir, new
            {
                Option = option,
                TemplateFileDirectory = templatePath
            }, option.Overwrite);

            await ImportCss(projectDir);

            return(Done());
        }
Exemplo n.º 16
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context, CompilationUnitSyntax rootUnit)
        {
            var    model           = context.GetVariable <object>("Model");
            string templateDir     = context.GetVariable <string>("TemplateDirectory");
            string addMenuNameText = TextGenerator.GenerateByTemplateName(templateDir, "Menus_AddMenuName", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ClassDeclarationSyntax>().Single().GetEndLine(),
                    addMenuNameText,
                    modifyCondition: root => root.DescendantsNotContain <ClassDeclarationSyntax>(addMenuNameText)
                    ),
            });
        }
Exemplo n.º 17
0
        protected override async Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context,
                                                                               CancellationToken cancellationToken)
        {
            var projectDir = context.GetVariable <string>("ProjectDirectory");

            var configFilePath = Path.Combine(projectDir, "abpvue.json");

            if (!File.Exists(configFilePath))
            {
                throw new FileNotFoundException("abpvue.json 文件没有找到。你可以使用 “abpvue init” 初始化项目 ");
            }

            var configText = await File.ReadAllTextAsync(configFilePath, cancellationToken);

            var projectInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <ProjectInfo>(configText);

            if (string.IsNullOrWhiteSpace(projectInfo.OpenApiAddr))
            {
                throw new ArgumentNullException(nameof(projectInfo.OpenApiAddr), "请提供 OpenApi 地址。");
            }

            if (!projectInfo.TemplateFileDirectory.IsNullOrWhiteSpace())
            {
                context.SetVariable("TemplateDirectory", projectInfo.TemplateFileDirectory);
            }

            context.SetVariable("ProjectInfo", projectInfo);

            return(Done());
        }
Exemplo n.º 18
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context, CompilationUnitSyntax rootUnit)
        {
            var    model               = context.GetVariable <object>("Model");
            string templateDir         = context.GetVariable <string>("TemplateDirectory");
            string permissionNamesText = TextGenerator.GenerateByTemplateName(templateDir, "Permissions_Names", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ClassDeclarationSyntax>().First().GetEndLine(),
                    permissionNamesText,
                    InsertPosition.Before,
                    root => root.DescendantsNotContain <ClassDeclarationSyntax>(permissionNamesText)
                    ),
            });
        }
Exemplo n.º 19
0
        protected override Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context, CancellationToken cancellationToken)
        {
            var startupDirectory = context.GetVariable <string>("StartupDirectory");

            Logger.LogInformation("启动目录:{dir}", startupDirectory);

            var isValidProject = CheckIsValidProject(startupDirectory);

            if (!isValidProject)
            {
                var srcPath      = @"\src\";
                var srcPathIndex = startupDirectory.LastIndexOf(srcPath, StringComparison.Ordinal);
                if (srcPathIndex == -1)
                {
                    throw new DirectoryNotFoundException($"未存在 “src” 目录,目录: {Environment.CurrentDirectory}");
                }

                startupDirectory = startupDirectory.Substring(0, srcPathIndex);

                isValidProject = CheckIsValidProject(startupDirectory);
            }

            if (!isValidProject)
            {
                throw new NotSupportedException($"未知的项目结构,目录: {startupDirectory}");
            }

            Logger.LogInformation("项目根目录:{dir}", startupDirectory);
            context.SetVariable("ProjectDirectory", startupDirectory);

            return(Task.FromResult(Done()));
        }
Exemplo n.º 20
0
        protected override IList <ModificationBuilder> CreateModifications(WorkflowExecutionContext context)
        {
            var entityInfo         = context.GetVariable <EntityInfo>("EntityInfo");
            var entityDtoUsingText = context.GetVariable <string>("EntityDtoUsingText");

            return(new List <ModificationBuilder>
            {
                new InsertionBuilder(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    entityDtoUsingText,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityDtoUsingText)
                    ),
                new InsertionBuilder(
                    root => root.Descendants <ConstructorDeclarationSyntax>().Single().GetEndLine(),
                    TextGenerator.GenerateByTemplateName("WebAutoMapperProfile_CreateMap", new { EntityInfo = entityInfo })
                    )
            });
        }
Exemplo n.º 21
0
        private void EnsureSlnFileExists(WorkflowExecutionContext context, string projectName)
        {
            string aspNetCoreDir = context.GetVariable <string>(VariableNames.AspNetCoreDir);
            string slnFile       = Path.Combine(aspNetCoreDir, $"{projectName}.sln");

            if (!File.Exists(slnFile))
            {
                throw new FileNotFoundException($"The solution file '{projectName}.sln' is not found in '{aspNetCoreDir}'. Make sure you specific the right folder.");
            }
        }
Exemplo n.º 22
0
        protected override IList <ModificationBuilder> CreateModifications(WorkflowExecutionContext context)
        {
            var entityUsingText       = context.GetVariable <string>("EntityUsingText");
            var dbContextPropertyText = context.GetVariable <string>(TextGenerationStep.DefaultGeneratedTextParameterName);

            return(new List <ModificationBuilder>
            {
                new InsertionBuilder(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    entityUsingText,
                    InsertPosition.After,
                    root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityUsingText)
                    ),
                new InsertionBuilder(
                    root => root.Descendants <ConstructorDeclarationSyntax>().Single().Identifier.GetStartLine() - 1,
                    dbContextPropertyText
                    )
            });
        }
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context, CompilationUnitSyntax rootUnit)
        {
            var    projectInfo = context.GetVariable <ProjectInfo>("ProjectInfo");
            string templateDir = context.GetVariable <string>(VariableNames.TemplateDirectory);
            string groupName   = rootUnit.Descendants <LocalDeclarationStatementSyntax>()
                                 .Single(stat => stat.ToFullString().Contains("context.AddGroup"))
                                 .Descendants <VariableDeclarationSyntax>().Single()
                                 .Variables[0].Identifier.Text;
            var model = context.GetVariable <dynamic>("Model");

            model.Bag.GroupName = groupName;
            string permissionDefinitionsText = TextGenerator.GenerateByTemplateName(templateDir, "Permissions_Definitions", model);

            var builders = new List <ModificationBuilder <CSharpSyntaxNode> >();

            builders.Add(new InsertionBuilder <CSharpSyntaxNode>(
                             root => root.Descendants <MethodDeclarationSyntax>().First().GetEndLine(),
                             permissionDefinitionsText,
                             InsertPosition.Before,
                             root => root.DescendantsNotContain <ClassDeclarationSyntax>(permissionDefinitionsText)
                             ));

            if (projectInfo.TemplateType == TemplateType.Application)
            {
                // Noting special to do
            }
            else if (projectInfo.TemplateType == TemplateType.Module)
            {
                string addGroupText = TextGenerator.GenerateByTemplateName(templateDir, "Permissions_AddGroup", model);

                // Uncomment the add group statement
                builders.Add(new ReplacementBuilder <CSharpSyntaxNode>(
                                 root => root.Descendants <MethodDeclarationSyntax>().First().GetStartLine() + 2,
                                 root => root.Descendants <MethodDeclarationSyntax>().First().GetStartLine() + 2,
                                 addGroupText,
                                 modifyCondition: root => !root.DescendantsNotContain <MethodDeclarationSyntax>($"//" + addGroupText)
                                 ));
            }

            return(builders);
        }
Exemplo n.º 24
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context)
        {
            var    model                 = context.GetVariable <object>("Model");
            string entityUsingText       = context.GetVariable <string>("EntityUsingText");
            string templateDir           = context.GetVariable <string>("TemplateDirectory");
            string dbContextPropertyText = TextGenerator.GenerateByTemplateName(templateDir, "DbContextClass_Property", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    entityUsingText,
                    InsertPosition.After,
                    root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityUsingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ConstructorDeclarationSyntax>().Single().Identifier.GetStartLine() - 1,
                    dbContextPropertyText,
                    modifyCondition: root => root.DescendantsNotContain <PropertyDeclarationSyntax>(dbContextPropertyText)
                    )
            });
        }
Exemplo n.º 25
0
        protected override async Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context,
                                                                               CancellationToken cancellationToken)
        {
            var openApiDocument = context.GetVariable <OpenApiDocument>("OpenApiDocument");
            var options         = context.GetVariable <GenerateCommandOptionBasic>("Option");

            var moduleApiPathItems =
                (from item in openApiDocument.Paths
                 let haveTag = item.Value.Operations.Any(x => x.Value.Tags
                                                         .Any(y => y.Name.Equals(options.Module, StringComparison.OrdinalIgnoreCase)))
                               where haveTag
                               select item).ToList();

            //var moduleApiPathItems =
            //    (from item in openApiDocument.Paths
            //        let match = item.Key.StartsWith(options.ModulePrefix)
            //        where match
            //        select item).ToList();

            var emptyModule = "empty".Equals(options.ModulePrefix, StringComparison.OrdinalIgnoreCase);

            context.SetVariable("EmptyModule", emptyModule);

            if (moduleApiPathItems.Count == 0 && !emptyModule)
            {
                Logger.LogWarning("找不到模块:{module} 的任何接口。", options.Module);
                return(base.Fault(""));
            }

            var projectInfo = context.GetVariable <ProjectInfo>("ProjectInfo");
            var modelInfo   = new ModuleInfo(moduleApiPathItems)
            {
                Option      = options,
                ProjectInfo = projectInfo
            };

            context.SetVariable("ModuleInfo", modelInfo);
            return(Done());
        }
Exemplo n.º 26
0
        protected override IList <ModificationBuilder> CreateModifications(WorkflowExecutionContext context)
        {
            var entityInfo = context.GetVariable <EntityInfo>("EntityInfo");

            return(new List <ModificationBuilder>
            {
                new InsertionBuilder(root => root.Descendants <MethodDeclarationSyntax>()
                                     .Single(n => n.Identifier.ToString() == "ConfigureMainMenuAsync")
                                     .GetEndLine(),
                                     TextGenerator.GenerateByTemplateName("MenuContributor_AddMenuItem", new { EntityInfo = entityInfo })
                                     )
            });
        }
Exemplo n.º 27
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context, CompilationUnitSyntax rootUnit)
        {
            var    model             = context.GetVariable <object>("Model");
            string templateDir       = context.GetVariable <string>(VariableNames.TemplateDirectory);
            string protectedCtorText = TextGenerator.GenerateByTemplateName(templateDir, "Entity_ProtectedConstructor", model);
            string publicCtorText    = TextGenerator.GenerateByTemplateName(templateDir, "Entity_PublicConstructor", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ClassDeclarationSyntax>().Single().GetEndLine(),
                    protectedCtorText,
                    InsertPosition.Before,
                    root => root.DescendantsNotContain <ClassDeclarationSyntax>(protectedCtorText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ClassDeclarationSyntax>().Single().GetEndLine(),
                    publicCtorText,
                    InsertPosition.Before,
                    modifyCondition: root => root.DescendantsNotContain <ClassDeclarationSyntax>(publicCtorText)
                    )
            });
        }
        protected override IList <ModificationBuilder> CreateModifications(WorkflowExecutionContext context)
        {
            var entityUsingText   = context.GetVariable <string>("EntityUsingText");
            var modelingUsingText = context.GetVariable <string>("ModelingUsingText");
            var entityConfigText  = context.GetVariable <string>("EntityConfigText");

            return(new List <ModificationBuilder>
            {
                new InsertionBuilder(
                    root => 1,
                    entityUsingText,
                    modifyCondition: root => root.DescendantsNotContain <UsingDirectiveSyntax>(entityUsingText)
                    ),
                new InsertionBuilder(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    modelingUsingText,
                    InsertPosition.After,
                    root => root.DescendantsNotContain <UsingDirectiveSyntax>(modelingUsingText)),
                new InsertionBuilder(
                    root => root.Descendants <MethodDeclarationSyntax>().First().GetEndLine(),
                    entityConfigText
                    )
            });
        }
Exemplo n.º 29
0
        protected override ActivityExecutionResult OnExecute(WorkflowExecutionContext context)
        {
            var modelInfo          = context.GetVariable <ModuleInfo>("ModuleInfo");
            ModuleApiOperation api = modelInfo.ModuleApis.FirstOrDefault(api =>
                                                                         api.Url.Equals(modelInfo.Option.ModulePrefix, StringComparison.OrdinalIgnoreCase) &&
                                                                         api.Method.Equals("get", StringComparison.OrdinalIgnoreCase));

            if (api == null)
            {
                Logger.LogError("找不到 GET LIST API");
                return(Fault("找不到 GET LIST API"));
            }

            Logger.LogInformation("GET LIST API:{api}", modelInfo.Option.ModulePrefix);

            context.SetVariable("GetListModuleApi", api);

            return(Done());
        }
        protected override async Task <ActivityExecutionResult> OnExecuteAsync(WorkflowExecutionContext context,
                                                                               CancellationToken cancellationToken)
        {
            using var httpClient = new HttpClient();

            var projectInfo = context.GetVariable <ProjectInfo>("ProjectInfo");

            Logger.LogInformation("正在获取 OpenApi 文档,url:{url}。", projectInfo.OpenApiAddr);
            var responseStream = await httpClient.GetStreamAsync(projectInfo.OpenApiAddr);

            var openApiDocument = new OpenApiStreamReader().Read(responseStream, out OpenApiDiagnostic diagnostic);

            //if (diagnostic.Errors.Count > 0)
            //{
            //    throw new InvalidOperationException();
            //}

            Logger.LogInformation("读取 OpenApi 文档成功。");
            context.SetVariable("OpenApiDocument", openApiDocument);
            return(Done());
        }