/// <summary> /// Steps of execution /// 1. Try getting the projectContext for the project /// 2. Invoke project dependency command with the first compatible tfm found in the project /// </summary> internal int Execute(string[] args, bool isNoBuild) { var app = new ScaffoldingApp(false); bool isShowHelp = false; app.OnExecute(() => { try { string project = app.ProjectPath.Value(); if (string.IsNullOrEmpty(project)) { project = Directory.GetCurrentDirectory(); } project = Path.GetFullPath(project); var configuration = app.AppConfiguration.Value() ?? "Debug"; isShowHelp = ToolCommandLineHelper.IsHelpArgument(args) || app.GeneratorArgument == null || string.IsNullOrEmpty(app.GeneratorArgument.Value); ProjectFileFinder projectFileFinder = new ProjectFileFinder(project); if (isShowHelp) { app.ProjectContext = GetProjectInformation(projectFileFinder.ProjectFilePath, configuration); app.ShowHelp(); return(0); } // Invoke the tool from the project's build directory. return(BuildAndDispatchDependencyCommand( args, projectFileFinder.ProjectFilePath, app.BuildBasePath.Value(), configuration, isNoBuild, Logger)); } catch (Exception ex) { Logger.LogMessage(Resources.GenericErrorMessage, LogMessageLevel.Error); Logger.LogMessage(ex.Message, LogMessageLevel.Error); if (isShowHelp) { app.ShowHelp(); } Logger.LogMessage(ex.StackTrace, LogMessageLevel.Trace); if (Logger is ConsoleLogger consoleLogger && !consoleLogger.IsTracing) { Logger.LogMessage(Resources.EnableTracingMessage); } return(-1); } }); return(app.Execute(args)); }
public static int Main(string[] args) { int exitCode = -1; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); var instance = new Program(); instance.Logger.LogMessage($"Command Line: {string.Join(" ", args)}", LogMessageLevel.Trace); _isNoBuild = ToolCommandLineHelper.IsNoBuild(args); try { DotnetToolDispatcher.EnsureValidDispatchRecipient(ref args); instance.SkipImportTarget = false; exitCode = instance.Execute(args, _isNoBuild); } finally { stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); instance.Logger.LogMessage("RunTime " + elapsedTime, LogMessageLevel.Information); } return(exitCode); }
/// <summary> /// Steps of execution /// 1. Try getting the projectContext for the project /// 2. Invoke project dependency command with the first compatible tfm found in the project /// </summary> private static void Execute(string[] args, bool isNoBuild, ILogger logger) { var app = new ScaffoldingApp(false); app.OnExecute(() => { string project = app.ProjectPath.Value(); if (string.IsNullOrEmpty(project)) { project = Directory.GetCurrentDirectory(); } project = Path.GetFullPath(project); var configuration = app.AppConfiguration.Value() ?? "Debug"; var projectFileFinder = new ProjectFileFinder(project); if (ToolCommandLineHelper.IsHelpArgument(args)) { app.ProjectContext = GetProjectInformation(projectFileFinder.ProjectFilePath, configuration); app.ShowHelp(); return(0); } // Invoke the tool from the project's build directory. return(BuildAndDispatchDependencyCommand( args, projectFileFinder.ProjectFilePath, app.BuildBasePath.Value(), configuration, isNoBuild, logger)); }); app.Execute(args); }
public static void Main(string[] args) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); _logger = new ConsoleLogger(); _logger.LogMessage($"Command Line: {string.Join(" ", args)}", LogMessageLevel.Trace); _isNoBuild = ToolCommandLineHelper.IsNoBuild(args); try { DotnetToolDispatcher.EnsureValidDispatchRecipient(ref args); Execute(args, _isNoBuild, _logger); } finally { stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); _logger.LogMessage("RunTime " + elapsedTime, LogMessageLevel.Information); } }
// Creates a command to execute dotnet-aspnet-codegenerator-design private Command CreateDipatchCommand( IProjectContext context, string[] args, string buildBasePath, string configuration, NuGetFramework frameworkToUse, ScaffoldingServer server) { var projectDirectory = Directory.GetParent(context.ProjectFullPath).FullName; // Command Resolution Args // To invoke dotnet-aspnet-codegenerator-design with the user project's dependency graph, // we need to pass in the runtime config and deps file to dotnet for netcore app projects. // For projects that target net4x, since the dotnet-aspnet-codegenerator-design.exe is in the project's bin folder // and `dotnet build` generates a binding redirect file for it, we can directly invoke the exe from output location. var targetDir = Path.GetDirectoryName(context.AssemblyFullPath); var runtimeConfigPath = Path.Combine(targetDir, context.RuntimeConfig); var depsFile = Path.Combine(targetDir, context.DepsFile); string dotnetCodeGenInsideManPath = string.Empty; if (IsNetCoreAppFramework(frameworkToUse)) { dotnetCodeGenInsideManPath = context.CompilationAssemblies .Where(c => Path.GetFileNameWithoutExtension(c.Name) .Equals(DESIGN_TOOL_NAME, StringComparison.OrdinalIgnoreCase)) .Select(reference => reference.ResolvedPath) .FirstOrDefault(); if (string.IsNullOrEmpty(dotnetCodeGenInsideManPath)) { throw new InvalidOperationException(Resources.AddDesignPackage); } } else { dotnetCodeGenInsideManPath = Path.Combine(Path.GetDirectoryName(context.AssemblyFullPath), DESIGN_TOOL_NAME + ".exe"); if (!File.Exists(dotnetCodeGenInsideManPath)) { throw new InvalidOperationException(Resources.AddDesignPackage); } } var dependencyArgs = ToolCommandLineHelper.GetProjectDependencyCommandArgs( args, frameworkToUse.GetShortFolderName(), server.Port.ToString()); return(DotnetToolDispatcher.CreateDispatchCommand( runtimeConfigPath: runtimeConfigPath, depsFile: depsFile, dependencyToolPath: dotnetCodeGenInsideManPath, dispatchArgs: dependencyArgs, framework: frameworkToUse, configuration: configuration, projectDirectory: projectDirectory, assemblyFullPath: context.AssemblyFullPath) .InWorkingDirectory(projectDirectory)); }
private static int BuildAndDispatchDependencyCommand( string[] args, NuGetFramework frameworkToUse, string projectPath, string buildBasePath, string configuration) { if (frameworkToUse == null) { throw new ArgumentNullException(nameof(frameworkToUse)); } if (string.IsNullOrEmpty(projectPath)) { throw new ArgumentNullException(nameof(projectPath)); } var buildResult = DotNetBuildCommandHelper.Build( projectPath, configuration, frameworkToUse, buildBasePath); if (buildResult.Result.ExitCode != 0) { //Build failed. // Stop the process here. _logger.LogMessage("Build Failed"); _logger.LogMessage(string.Join(Environment.NewLine, buildResult.StdErr), LogMessageLevel.Error); return(buildResult.Result.ExitCode); } // Invoke the dependency command var projectFilePath = projectPath.EndsWith("project.json") ? projectPath : Path.Combine(projectPath, "project.json"); var projectDirectory = Directory.GetParent(projectFilePath).FullName; var dependencyArgs = ToolCommandLineHelper.GetProjectDependencyCommandArgs( args, frameworkToUse.GetShortFolderName()); var exitCode = DotnetToolDispatcher.CreateDispatchCommand( dependencyArgs, frameworkToUse, configuration, null, buildBasePath, projectDirectory) .ForwardStdErr() .ForwardStdOut() .Execute() .ExitCode; return(exitCode); }
/// <summary> /// The execution is done in 2 phases. /// Phase 1 :: /// 1. Determine if the tool is running as a project dependency or not. /// 2. Try getting the project context for the project (use netcoreapp1.0 as the tfm if not running as dependency command or else use the tfm passed in) /// 3. If not running as dependency command and project context cannot be built using netcoreapp1.0, invoke project dependency command with the first tfm found in the project.json /// /// Phase 2 :: /// 1. After successfully getting the Project context, invoke the CodeGenCommandExecutor. /// </summary> private static void Execute(string[] args) { var app = new CommandLineApplication(false) { Name = APPNAME, Description = APP_DESC }; // Define app Options; app.HelpOption("-h|--help"); var projectPath = app.Option("-p|--project", "Path to project.json", CommandOptionType.SingleValue); var packagesPath = app.Option("-n|--nuget-package-dir", "Path to check for Nuget packages", CommandOptionType.SingleValue); var appConfiguration = app.Option("-c|--configuration", "Configuration for the project (Possible values: Debug/ Release)", CommandOptionType.SingleValue); var framework = app.Option("-tfm|--target-framework", "Target Framework to use. (Short folder name of the tfm. eg. net451)", CommandOptionType.SingleValue); var buildBasePath = app.Option("-b|--build-base-path", "", CommandOptionType.SingleValue); var dependencyCommand = app.Option("--no-dispatch", "", CommandOptionType.NoValue); app.OnExecute(() => { string project = projectPath.Value(); if (string.IsNullOrEmpty(project)) { project = Directory.GetCurrentDirectory(); } project = Path.GetFullPath(project); var configuration = appConfiguration.Value() ?? Constants.DefaultConfiguration; var projectFile = ProjectReader.GetProject(project); var frameworksInProject = projectFile.GetTargetFrameworks().Select(f => f.FrameworkName); var nugetFramework = FrameworkConstants.CommonFrameworks.NetCoreApp10; if (_isDispatcher) { // Invoke the tool from the project's build directory. return(BuildAndDispatchDependencyCommand( args, frameworksInProject.FirstOrDefault(), project, buildBasePath.Value(), configuration)); } else { if (!TryGetNugetFramework(framework.Value(), out nugetFramework)) { throw new ArgumentException($"Could not understand the NuGetFramework information. Framework short folder name passed in was: {framework.Value()}"); } var nearestNugetFramework = NuGetFrameworkUtility.GetNearest( frameworksInProject, nugetFramework, f => new NuGetFramework(f)); if (nearestNugetFramework == null) { // This should never happen as long as we dispatch correctly. var msg = "Could not find a compatible framework to execute." + Environment.NewLine + $"Available frameworks in project:{string.Join($"{Environment.NewLine} -", frameworksInProject.Select(f => f.GetShortFolderName()))}"; throw new InvalidOperationException(msg); } ProjectContext context = new ProjectContextBuilder() .WithProject(projectFile) .WithTargetFramework(nearestNugetFramework) .Build(); Debug.Assert(context != null); var codeGenArgs = ToolCommandLineHelper.FilterExecutorArguments(args); CodeGenCommandExecutor executor = new CodeGenCommandExecutor( context, codeGenArgs, configuration, packagesPath.Value(), _logger); return(executor.Execute()); } }); app.Execute(args); }