Ejemplo n.º 1
0
        public OperationExecutor(
            [NotNull] CommonOptions options,
            [CanBeNull] string environment)
        {
            var projectFile = Path.Combine(Directory.GetCurrentDirectory(), Project.FileName);
            var project     = ProjectReader.GetProject(projectFile);

            var projectConfiguration = options.Configuration ?? Constants.DefaultConfiguration;
            var projectFramework     = options.Framework;

            var projectContext = ProjectContext.Create(project.ProjectFilePath,
                                                       projectFramework,
                                                       RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            var runtimeOutputPath = projectContext.GetOutputPaths(projectConfiguration)?.RuntimeOutputPath;

            if (!string.IsNullOrEmpty(runtimeOutputPath))
            {
                Reporter.Verbose.WriteLine(
                    ToolsCliStrings.LogDataDirectory(runtimeOutputPath));
                Environment.SetEnvironmentVariable(DataDirEnvName, runtimeOutputPath);
#if NET451
                AppDomain.CurrentDomain.SetData("DataDirectory", runtimeOutputPath);
#endif
            }

            var assemblyName  = project.GetCompilerOptions(projectFramework, projectConfiguration).OutputName;
            var projectDir    = project.ProjectDirectory;
            var rootNamespace = project.Name;

            var assemblyLoader  = new AssemblyLoader(Assembly.Load);
            var projectAssembly = assemblyLoader.Load(assemblyName);

            _contextOperations = new LazyRef <DbContextOperations>(
                () => new DbContextOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    projectAssembly,
                    environment,
                    projectDir));
            _databaseOperations = new LazyRef <DatabaseOperations>(
                () => new DatabaseOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
            _migrationsOperations = new LazyRef <MigrationsOperations>(
                () => new MigrationsOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
        }
Ejemplo n.º 2
0
        private void OnProjectChanged(object sender, FileSystemEventArgs e)
        {
            var project = ProjectReader.GetProject(this.projectFilePath);
            var json    = JsonConvert.SerializeObject(project, this.jsonSerializerSettings);

            File.WriteAllText(this.projectJsonFilePath, json);
        }
Ejemplo n.º 3
0
        public BuildCommand(
            string projectPath,
            string output           = "",
            string tempOutput       = "",
            string configuration    = "",
            bool noHost             = false,
            bool native             = false,
            string architecture     = "",
            string ilcArgs          = "",
            string ilcPath          = "",
            string appDepSDKPath    = "",
            bool nativeCppMode      = false,
            string cppCompilerFlags = ""
            )
            : base("dotnet")
        {
            _projectPath = projectPath;
            _project     = ProjectReader.GetProject(projectPath);

            _outputDirectory     = output;
            _tempOutputDirectory = tempOutput;
            _configuration       = configuration;
            _noHost           = noHost;
            _native           = native;
            _architecture     = architecture;
            _ilcArgs          = ilcArgs;
            _ilcPath          = ilcPath;
            _appDepSDKPath    = appDepSDKPath;
            _nativeCppMode    = nativeCppMode;
            _cppCompilerFlags = cppCompilerFlags;
        }
Ejemplo n.º 4
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication(false)
            {
                Name        = "dotnet restore",
                FullName    = ".NET project dependency restorer",
                Description = "Restores dependencies listed in project.json"
            };

            // Parse --quiet, because we have to handle that specially since NuGet3 has a different
            // "--verbosity" switch that goes BEFORE the command
            var quiet = args.Any(s => s.Equals("--quiet", StringComparison.OrdinalIgnoreCase));

            args = args.Where(s => !s.Equals("--quiet", StringComparison.OrdinalIgnoreCase)).ToArray();

            // Until NuGet/Home#1941 is fixed, if no RIDs are specified, add our own.
            if (!args.Any(s => s.Equals("--runtime", StringComparison.OrdinalIgnoreCase)))
            {
                args = Enumerable.Concat(
                    args,
                    PlatformServices.Default.Runtime.GetOverrideRestoreRuntimeIdentifiers().SelectMany(r => new [] { "--runtime", r })
                    ).ToArray();
            }

            app.OnExecute(() =>
            {
                try
                {
                    var projectRestoreResult = NuGet3.Restore(args, quiet);

                    var restoreTasks = GetRestoreTasks(args);

                    foreach (var restoreTask in restoreTasks)
                    {
                        var project = ProjectReader.GetProject(restoreTask.ProjectPath);

                        RestoreTools(project, restoreTask, quiet);
                    }

                    return(projectRestoreResult);
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);

                    return(-1);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                    return(-2);
                }
            });

            return(app.Execute(args));
        }
Ejemplo n.º 5
0
        private void OnProjectJsonChanged(object sender, FileSystemEventArgs e)
        {
            var project    = ProjectReader.GetProject(this.projectFilePath);
            var json       = File.ReadAllText(this.projectJsonFilePath);
            var newProject = JsonConvert.DeserializeObject <Project>(json);

            Mapper.Map(newProject, project);
        }
Ejemplo n.º 6
0
        private static ProjectContext GetProjectContext(string applicationBasePath, string framework)
        {
            var project = ProjectReader.GetProject(Path.Combine(applicationBasePath, "project.json"));

            return(new ProjectContextBuilder()
                   .WithProject(project)
                   .WithTargetFramework(framework)
                   .Build());
        }
Ejemplo n.º 7
0
 public PublishCommand(string projectPath, string framework = "", string runtime = "", string output = "", string config = "")
     : base("dotnet")
 {
     _path      = projectPath;
     _project   = ProjectReader.GetProject(projectPath);
     _framework = framework;
     _runtime   = runtime;
     _output    = output;
     _config    = config;
 }
        protected override int OnExecute()
        {
            var projectFile      = ProjectReader.GetProject(ProjectArgument.Value);
            var targetFrameworks = projectFile
                                   .GetTargetFrameworks()
                                   .Select(frameworkInformation => frameworkInformation.FrameworkName);

            NuGetFramework framework;

            if (!TryResolveFramework(targetFrameworks, out framework))
            {
                // Could not resolve framework for dispatch. Error was reported, exit early.
                return(0);
            }

            var dispatchArgs = new List <string>
            {
                CommandName,
                AssemblyNamesArgument.Value,
            };

            if (ProtocolOption.HasValue())
            {
                dispatchArgs.Add("--protocol");
                dispatchArgs.Add(ProtocolOption.Value());
            }

            var dispatchCommand = DotnetToolDispatcher.CreateDispatchCommand(
                dispatchArgs,
                framework,
                ConfigurationOption.Value(),
                outputPath: null,
                buildBasePath: BuildBasePathOption.Value(),
                projectDirectory: projectFile.ProjectDirectory);

            using (var errorWriter = new StringWriter())
            {
                var commandExitCode = dispatchCommand
                                      .ForwardStdErr(errorWriter)
                                      .ForwardStdOut()
                                      .Execute()
                                      .ExitCode;

                if (commandExitCode != 0)
                {
                    ReportError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.FailedToExecuteRazorTooling,
                            errorWriter.ToString()));
                }

                return(0);
            }
        }
Ejemplo n.º 9
0
 public PublishCommand(string projectPath, string framework = "", string runtime = "", string output = "", string config = "", bool forcePortable = false, bool noBuild = false)
     : base("dotnet")
 {
     _path      = projectPath;
     _project   = ProjectReader.GetProject(projectPath);
     _framework = framework;
     _runtime   = runtime;
     _output    = output;
     _config    = config;
     _noBuild   = noBuild;
 }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            var connectCentre = new ConnectionCentre();

            connectCentre.Connect("http://test0000003.atlassian.net", "admin", "11111111");

            var projectReader = new ProjectReader();
            var project       = projectReader.GetProject("PROJ");

            Console.WriteLine(project.Name);
            Console.WriteLine(project.Lead.Name);
            Console.ReadKey();
        }
Ejemplo n.º 11
0
        private void HoistFrameworkAssembliesForDesktopFrameworks(
            ProjectDependency projectDependency,
            ProjectRootElement outputMSBuildProject)
        {
            var targetFrameworks = ProjectReader
                                   .GetProject(projectDependency.ProjectFilePath)
                                   .GetTargetFrameworks().Where(p => !p.FrameworkName.IsPackageBased);

            foreach (var targetFramework in targetFrameworks)
            {
                HoistFrameworkAssemblies(targetFramework, outputMSBuildProject);
            }
        }
Ejemplo n.º 12
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication(false)
            {
                Name        = "dotnet restore",
                FullName    = ".NET project dependency restorer",
                Description = "Restores dependencies listed in project.json"
            };

            // Parse --quiet, because we have to handle that specially since NuGet3 has a different
            // "--verbosity" switch that goes BEFORE the command
            var quiet = args.Any(s => s.Equals("--quiet", StringComparison.OrdinalIgnoreCase));

            args = args.Where(s => !s.Equals("--quiet", StringComparison.OrdinalIgnoreCase)).ToArray();

            app.OnExecute(() =>
            {
                try
                {
                    var projectRestoreResult = NuGet3.Restore(args, quiet);

                    var restoreTasks = GetRestoreTasks(args);

                    foreach (var restoreTask in restoreTasks)
                    {
                        var project = ProjectReader.GetProject(restoreTask.ProjectPath);

                        RestoreTools(project, restoreTask, quiet);
                    }

                    return(projectRestoreResult);
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);

                    return(-1);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                    return(-2);
                }
            });

            return(app.Execute(args));
        }
Ejemplo n.º 13
0
        public BuildCommand(
            string projectPath,
            string output           = "",
            string buildBasePath    = "",
            string configuration    = "",
            string framework        = "",
            string runtime          = "",
            string versionSuffix    = "",
            bool noHost             = false,
            bool native             = false,
            string architecture     = "",
            string ilcArgs          = "",
            string ilcPath          = "",
            string appDepSDKPath    = "",
            bool nativeCppMode      = false,
            string cppCompilerFlags = "",
            bool buildProfile       = true,
            bool noIncremental      = false,
            bool noDependencies     = false,
            bool verbose            = true,
            bool skipLoadProject    = false)
            : base("dotnet")
        {
            _projectPath = projectPath;

            if (!skipLoadProject)
            {
                _project = ProjectReader.GetProject(projectPath);
            }

            _outputDirectory        = output;
            _buildBasePathDirectory = buildBasePath;
            _configuration          = configuration;
            _versionSuffix          = versionSuffix;
            _framework        = framework;
            _runtime          = runtime;
            _noHost           = noHost;
            _native           = native;
            _architecture     = architecture;
            _ilcArgs          = ilcArgs;
            _ilcPath          = ilcPath;
            _appDepSDKPath    = appDepSDKPath;
            _nativeCppMode    = nativeCppMode;
            _cppCompilerFlags = cppCompilerFlags;
            _buildProfile     = buildProfile;
            _noIncremental    = noIncremental;
            _noDependencies   = noDependencies;
            _verbose          = verbose;
        }
Ejemplo n.º 14
0
        private ProjectContext GetCompatibleStartupProjectContext(string startupProjectPath, NuGetFramework projectFramework)
        {
            var startupProject = ProjectReader.GetProject(startupProjectPath);
            var frameworks     = startupProject.GetTargetFrameworks()
                                 .Select(f => f.FrameworkName);

            var startupFramework = frameworks.FirstOrDefault(f => f.Equals(projectFramework));

            if (startupFramework == null)
            {
                if (projectFramework.IsDesktop())
                {
                    startupFramework = frameworks.FirstOrDefault(f => f.IsDesktop())
                                       ?? NuGetFrameworkUtility.GetNearest(
                        frameworks,
                        FrameworkConstants.CommonFrameworks.NetStandard15,
                        f => f);
                }
                else
                {
                    startupFramework = NuGetFrameworkUtility.GetNearest(
                        frameworks,
                        FrameworkConstants.CommonFrameworks.NetCoreApp10,
                        f => f)
                                       // TODO remove fallback to dnxcore50
                                       ?? NuGetFrameworkUtility.GetNearest(
                        frameworks,
                        FrameworkConstants.CommonFrameworks.DnxCore50,
                        f => f);
                }
            }

            if (startupFramework == null)
            {
                throw new OperationException(
                          ToolsCliStrings.IncompatibleStartupProject(startupProject.Name, projectFramework.GetShortFolderName()));
            }

            Reporter.Verbose.WriteLine(
                ToolsCliStrings.LogUsingFramework(startupFramework.GetShortFolderName(), startupProject.Name).Bold().Black());

            return(new ProjectContextBuilder()
                   .WithProject(startupProject)
                   .WithTargetFramework(startupFramework)
                   .WithRuntimeIdentifiers(PlatformServices.Default.Runtime.GetAllCandidateRuntimeIdentifiers())
                   .Build());
        }
Ejemplo n.º 15
0
 public PublishCommand(string projectPath,
                       string framework     = "",
                       string runtime       = "",
                       string output        = "",
                       string config        = "",
                       bool noBuild         = false,
                       string buildBasePath = "")
     : base("dotnet")
 {
     _path                  = projectPath;
     _project               = ProjectReader.GetProject(projectPath);
     _framework             = framework;
     _runtime               = runtime;
     _output                = output;
     _config                = config;
     _noBuild               = noBuild;
     _buidBasePathDirectory = buildBasePath;
 }
Ejemplo n.º 16
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication(false)
            {
                Name        = "dotnet restore",
                FullName    = ".NET project dependency restorer",
                Description = "Restores dependencies listed in project.json"
            };

            app.OnExecute(() =>
            {
                try
                {
                    var projectRestoreResult = Dnx.RunRestore(args);

                    var restoreTasks = GetRestoreTasks(args);

                    foreach (var restoreTask in restoreTasks)
                    {
                        var project = ProjectReader.GetProject(restoreTask.ProjectPath);

                        RestoreTools(project, restoreTask.Arguments);
                    }

                    return(projectRestoreResult);
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);

                    return(-1);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                    return(-2);
                }
            });

            return(app.Execute(args));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Main entry point.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            var resetmode = args.Contains("reset");

            // Find the project root where glbal.json lives
            var root = ProjectRootResolver.ResolveRootDirectory(".");

            // Lets find the repo
            var repo = new LibGit2Sharp.Repository(root);

            // Lets find all the project.json files in the src folder (don't care about versioning `tests`)
            var projectFiles = Directory.EnumerateFiles(Path.Combine(root, "src"), Project.FileName, SearchOption.AllDirectories);

            // Open them and convert them to source projects
            var projects = projectFiles.Select(x => ProjectReader.GetProject(x))
                           .Select(x => new SourceProject(x, repo.Info.WorkingDirectory))
                           .ToList();

            if (resetmode)
            {
                ResetProject(projects);
            }
            else
            {
                CaclulateProjectVersionNumber(projects, repo);

                UpdateVersionNumbers(projects);

                CreateBuildScript(projects);

                foreach (var p in projects)
                {
                    Console.WriteLine($"{p.Name} {p.FinalVersionNumber}");
                }
            }
        }
Ejemplo n.º 18
0
        /// <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();
                }
                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);
        }
Ejemplo n.º 19
0
        public static CommandLineApplication Create()
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name     = "dotnet ef",
                FullName = "Entity Framework .NET Core CLI Commands Dispatcher"
            };

            var noBuildOption = app.Option("--no-build", "Do not build before executing");

            var configurationOption = app.Option(
                "-c|--configuration <CONFIGURATION>",
                "Configuration under which to load");
            var frameworkOption = app.Option(
                "-f|--framework <FRAMEWORK>",
                "Target framework to load");
            var buildBasePathOption = app.Option(
                "-b|--build-base-path <OUTPUT_DIR>",
                "Directory in which to find temporary outputs");

            var outputOption = app.Option(
                "-o|--output <OUTPUT_DIR>",
                "Directory in which to find outputs");

            app.OnExecute(() =>
            {
                var project = Directory.GetCurrentDirectory();

                Reporter.Verbose.WriteLine(ToolsStrings.LogUsingProject(project));

                var projectFile = ProjectReader.GetProject(project);

                var framework = frameworkOption.HasValue()
                    ? NuGetFramework.Parse(frameworkOption.Value())
                    : null;

                if (framework == null)
                {
                    var frameworks = projectFile.GetTargetFrameworks().Select(i => i.FrameworkName);
                    framework      = NuGetFrameworkUtility.GetNearest(frameworks, FrameworkConstants.CommonFrameworks.NetCoreApp10, f => f)
                                     ?? frameworks.FirstOrDefault();

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingFramework(framework.GetShortFolderName()));
                }

                var configuration = configurationOption.Value();

                if (configuration == null)
                {
                    configuration = Constants.DefaultConfiguration;

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingConfiguration(configuration));
                }


                if (!noBuildOption.HasValue())
                {
                    var buildExitCode = BuildCommandFactory.Create(
                        projectFile.ProjectFilePath,
                        configuration,
                        framework,
                        buildBasePathOption.Value(),
                        outputOption.Value())
                                        .ForwardStdErr()
                                        .ForwardStdOut()
                                        .Execute()
                                        .ExitCode;
                    if (buildExitCode != 0)
                    {
                        throw new OperationException(ToolsStrings.BuildFailed(projectFile.Name));
                    }
                }

                Reporter.Verbose.WriteLine(ToolsStrings.LogBeginDispatch(ProjectDependencyToolName, projectFile.Name));

                try
                {
                    bool isVerbose;
                    bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out isVerbose);
                    var dispatchArgs = ExecuteCommand
                                       .CreateArgs(framework, configuration, buildBasePathOption.Value(), noBuildOption.HasValue(), isVerbose)
                                       .Concat(app.RemainingArguments);

                    return(DotnetToolDispatcher.CreateDispatchCommand(
                               dispatchArgs,
                               framework,
                               configuration,
                               outputPath: outputOption.Value(),
                               buildBasePath: buildBasePathOption.Value(),
                               projectDirectory: projectFile.ProjectDirectory,
                               toolName: ProjectDependencyToolName)
                           .ForwardStdErr()
                           .ForwardStdOut()
                           .Execute()
                           .ExitCode);
                }
                catch (CommandUnknownException ex)
                {
                    Reporter.Verbose.WriteLine(ex.Message);
                    // intentionally put DispatcherToolName in error because "Microsoft.EntityFrameworkCore.Tools.Cli" is
                    // brought in automatically as a dependency of "Microsoft.EntityFrameworkCore.Tools"
                    Reporter.Error.WriteLine(ToolsStrings.ProjectDependencyCommandNotFound(DispatcherToolName));
                    return(1);
                }
            });

            return(app);
        }
Ejemplo n.º 20
0
        public OperationExecutor(
            [NotNull] CommonOptions options,
            [CanBeNull] string startupProjectPath,
            [CanBeNull] string environment)
        {
            var projectFile = Path.Combine(Directory.GetCurrentDirectory(), Project.FileName);
            var project     = ProjectReader.GetProject(projectFile);

            startupProjectPath = startupProjectPath ?? projectFile;

            var projectConfiguration = options.Configuration ?? Constants.DefaultConfiguration;
            var projectFramework     = options.Framework;

            var startupConfiguration  = options.Configuration ?? Constants.DefaultConfiguration;
            var startupProjectContext = GetCompatibleStartupProjectContext(startupProjectPath, projectFramework);
            var startupFramework      = startupProjectContext.TargetFramework;

            var externalStartup = project.ProjectFilePath != startupProjectContext.ProjectFile.ProjectFilePath;

            if (externalStartup && !options.NoBuild)
            {
                Reporter.Verbose.WriteLine(ToolsCliStrings.LogBuildFailed.Bold().Black());

                var buildExitCode = BuildCommandFactory.Create(startupProjectPath,
                                                               startupConfiguration,
                                                               startupFramework,
                                                               options.BuildBasePath,
                                                               output: null)
                                    .ForwardStdOut()
                                    .ForwardStdErr()
                                    .Execute()
                                    .ExitCode;

                if (buildExitCode != 0)
                {
                    throw new OperationException(ToolsCliStrings.LogBuildFailed);
                }

                Reporter.Verbose.WriteLine(ToolsCliStrings.LogBuildSucceeded.Bold().Black());
            }

            var runtimeOutputPath = startupProjectContext.GetOutputPaths(startupConfiguration)?.RuntimeOutputPath;

            if (!string.IsNullOrEmpty(runtimeOutputPath))
            {
                Reporter.Verbose.WriteLine(
                    ToolsCliStrings.LogDataDirectory(runtimeOutputPath));
                Environment.SetEnvironmentVariable(DataDirEnvName, runtimeOutputPath);
#if NET451
                AppDomain.CurrentDomain.SetData("DataDirectory", runtimeOutputPath);
#endif
            }

            var startupAssemblyName = startupProjectContext.ProjectFile.GetCompilerOptions(startupFramework, startupConfiguration).OutputName;
            var assemblyName        = project.GetCompilerOptions(projectFramework, projectConfiguration).OutputName;
            var projectDir          = project.ProjectDirectory;
            var startupProjectDir   = startupProjectContext.ProjectFile.ProjectDirectory;
            var rootNamespace       = project.Name;

            var projectAssembly = Assembly.Load(new AssemblyName {
                Name = assemblyName
            });
#if NET451
            // TODO use app domains
            var startupAssemblyLoader = new AssemblyLoader(Assembly.Load);
#else
            AssemblyLoader startupAssemblyLoader;
            if (externalStartup)
            {
                var assemblyLoadContext = startupProjectContext.CreateLoadContext(
                    PlatformServices.Default.Runtime.GetRuntimeIdentifier(),
                    Constants.DefaultConfiguration);
                startupAssemblyLoader = new AssemblyLoader(assemblyLoadContext.LoadFromAssemblyName);
            }
            else
            {
                startupAssemblyLoader = new AssemblyLoader(Assembly.Load);
            }
#endif
            var startupAssembly = startupAssemblyLoader.Load(startupAssemblyName);

            _contextOperations = new LazyRef <DbContextOperations>(
                () => new DbContextOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    startupAssembly,
                    environment,
                    startupProjectDir));
            _databaseOperations = new LazyRef <DatabaseOperations>(
                () => new DatabaseOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    startupAssemblyLoader,
                    startupAssembly,
                    environment,
                    projectDir,
                    startupProjectDir,
                    rootNamespace));
            _migrationsOperations = new LazyRef <MigrationsOperations>(
                () => new MigrationsOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    startupAssemblyLoader,
                    startupAssembly,
                    environment,
                    projectDir,
                    startupProjectDir,
                    rootNamespace));
        }
Ejemplo n.º 21
0
        public static CommandLineApplication Create()
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name     = "dotnet ef",
                FullName = "Entity Framework .NET Core CLI Commands Dispatcher"
            };

            var noBuildOption = app.Option("--no-build", "Do not build before executing");

            var configurationOption = app.Option(
                "-c|--configuration <CONFIGURATION>",
                "Configuration under which to load");
            var frameworkOption = app.Option(
                "-f|--framework <FRAMEWORK>",
                "Target framework to load");
            var buildBasePathOption = app.Option(
                "-b|--build-base-path <OUTPUT_DIR>",
                "Directory in which to find temporary outputs");
            var outputOption = app.Option(
                "-o|--output <OUTPUT_DIR>",
                "Directory in which to find outputs");

            app.OnExecute(() =>
            {
                var project = Directory.GetCurrentDirectory();

                Reporter.Verbose.WriteLine(ToolsStrings.LogUsingProject(project));

                var projectFile = ProjectReader.GetProject(project);

                var framework = frameworkOption.HasValue()
                    ? NuGetFramework.Parse(frameworkOption.Value())
                    : null;

                if (framework == null)
                {
                    var frameworks = projectFile.GetTargetFrameworks().Select(i => i.FrameworkName);
                    framework      = NuGetFrameworkUtility.GetNearest(frameworks, FrameworkConstants.CommonFrameworks.NetCoreApp10, f => f)
                                     ?? frameworks.FirstOrDefault();

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingFramework(framework.GetShortFolderName()));
                }

                var configuration = configurationOption.Value();

                if (configuration == null)
                {
                    configuration = Constants.DefaultConfiguration;

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingConfiguration(configuration));
                }

                if (!noBuildOption.HasValue())
                {
                    var buildExitCode = BuildCommandFactory.Create(
                        projectFile.ProjectFilePath,
                        configuration,
                        framework,
                        buildBasePathOption.Value(),
                        outputOption.Value())
                                        .ForwardStdErr()
                                        .ForwardStdOut()
                                        .Execute()
                                        .ExitCode;
                    if (buildExitCode != 0)
                    {
                        throw new OperationException(ToolsStrings.BuildFailed(projectFile.Name));
                    }
                }

                // TODO remove when https://github.com/dotnet/cli/issues/2645 is resolved
                Func <bool> isClassLibrary = () =>
                {
                    var projectContext = ProjectContext.Create(
                        projectFile.ProjectFilePath,
                        framework,
                        RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

                    var runtimeFiles = projectContext
                                       .GetOutputPaths(configuration, buildBasePathOption.Value(), outputOption.Value())
                                       ?.RuntimeFiles;

                    return(runtimeFiles == null ||
                           (
                               framework.IsDesktop()
                                ? !Directory.Exists(runtimeFiles.BasePath)
                                : !File.Exists(runtimeFiles.RuntimeConfigJson) || !File.Exists(runtimeFiles.DepsJson)
                           ));
                };

                Reporter.Verbose.WriteLine(ToolsStrings.LogBeginDispatch(ProjectDependencyToolName, projectFile.Name));

                try
                {
                    bool isVerbose;
                    bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out isVerbose);
                    var dispatchArgs = ExecuteCommand
                                       .CreateArgs(framework, configuration, isVerbose)
                                       .Concat(app.RemainingArguments);

                    return(DotnetToolDispatcher.CreateDispatchCommand(
                               dispatchArgs,
                               framework,
                               configuration,
                               outputPath: outputOption.Value(),
                               buildBasePath: buildBasePathOption.Value(),
                               projectDirectory: projectFile.ProjectDirectory,
                               toolName: ProjectDependencyToolName)
                           .ForwardStdErr()
                           .ForwardStdOut()
                           .Execute()
                           .ExitCode);
                }
                catch (CommandUnknownException ex)
                {
                    Reporter.Verbose.WriteLine(ex.Message);

                    var fwlink = "http://go.microsoft.com/fwlink/?LinkId=798221";

                    if (isClassLibrary())
                    {
                        Reporter.Error.WriteLine(ToolsStrings.ClassLibrariesNotSupportedInCli(fwlink));
                    }
                    else
                    {
                        // intentionally put DispatcherToolName in error because "Microsoft.EntityFrameworkCore.Tools.Cli" is
                        // brought in automatically as a dependency of "Microsoft.EntityFrameworkCore.Tools"
                        Reporter.Error.WriteLine(ToolsStrings.ProjectDependencyCommandNotFound(DispatcherToolName, fwlink));
                    }

                    return(1);
                }
            });

            return(app);
        }