private static int Init() { Logger.Preparing("Initializing Electron..."); // TODO: Check if already installed DotNetHelper.RunDotNet("new -i BionicElectronTemplate"); // TODO: Check if platforms/electron already exists DotNetHelper.RunDotNet("new bionic.electron -o platforms"); var cd = Directory.GetCurrentDirectory(); int exitCode; try { Directory.SetCurrentDirectory(ToOSPath($"{cd}/platforms/electron")); exitCode = ProcessHelper.RunCmd("npm", "install"); } catch (Exception) { Logger.Error("Something went wrong during Electron install. Please check platforms/electron"); return(1); } finally { Directory.SetCurrentDirectory(cd); } if (exitCode == 0) { Logger.Success("Electron is ready to go! - try: bionic platform electron serve"); } return(exitCode); }
public async Task BuildPackageAsync( ILocalPackage package, IRemoteSourceControlRepository repository) { var nugetPackage = (IDotNetLocalPackage)package; foreach (var preprocessor in _dotNetLocalPackagePreprocessors) { await preprocessor.PreprocessPackageAsync(nugetPackage); } await UpdateProjectFileAsync( nugetPackage, repository); DotNetHelper.RestorePackages(nugetPackage.FolderPath); DotNetHelper.Build(nugetPackage.FolderPath); var folderDirectory = new DirectoryInfo(nugetPackage.FolderPath); var targetTestDirectoryPath = folderDirectory.Name + ".Tests"; var testDirectory = folderDirectory .Parent .GetDirectories() .SingleOrDefault(x => x.Name == targetTestDirectoryPath); if (testDirectory != null) { Console.WriteLine("Test directory for package " + nugetPackage.PublishName + " found at " + testDirectory.FullName + "."); DotNetHelper.Test(testDirectory.FullName); } else { Console.WriteLine("No test directory for package " + nugetPackage.PublishName + " found."); } }
public async Task InitializeAsync() { var logger = new TestLogger(); try { // Restore the Analyzer packages that have been added to `for_analyzer_formatter/analyzer_project/analyzer_project.csproj` var exitCode = await DotNetHelper.PerformRestore(s_analyzerProjectFilePath, TestOutputHelper); Assert.Equal(0, exitCode); // Load the analyzer_project into a MSBuildWorkspace. var workspacePath = Path.Combine(TestProjectsPathHelper.GetProjectsDirectory(), s_analyzerProjectFilePath); MSBuildRegistrar.RegisterInstance(); var analyzerWorkspace = await MSBuildWorkspaceLoader.LoadAsync(workspacePath, WorkspaceType.Project, binaryLogPath : null, logWorkspaceWarnings : true, logger, CancellationToken.None); TestOutputHelper.WriteLine(logger.GetLog()); // From this project we can get valid AnalyzerReferences to add to our test project. _analyzerReferencesProject = analyzerWorkspace.CurrentSolution.Projects.Single(); } catch { TestOutputHelper.WriteLine(logger.GetLog()); throw; } }
private static async Task <string> GenerateProjectFromTemplateAsync(string templateName, string languageName, ITestOutputHelper outputHelper) { var projectPath = GetProjectPath(templateName, languageName); var projectFilePath = GetProjectFilePath(projectPath, languageName); var exitCode = await DotNetHelper.NewProjectAsync(templateName, projectPath, languageName, outputHelper); Assert.Equal(0, exitCode); return(projectFilePath); }
public async Task TestOpenProject_NetCoreMultiTFM_ProjectReferenceWithReversedTFMs() { CreateFiles(GetNetCoreMultiTFMFiles_ProjectReferenceWithReversedTFMs()); // Restoring for Project.csproj should also restore Library.csproj DotNetHelper.Restore(@"Project\Project.csproj", workingDirectory: this.SolutionDirectory.Path); var projectFilePath = GetSolutionFileName(@"Project\Project.csproj"); await AssertNetCoreMultiTFMProject(projectFilePath); }
public void FormatProject() { string unformattedCsFilePath = Path.Combine(BaselineHelper.GetAssetsDirectory(), UnformattedFileName); string projectDirectory = DotNetHelper.ExecuteNew("console", nameof(FormatProject), "C#"); string projectFilePath = Path.Combine(projectDirectory, nameof(FormatProject) + ".csproj"); string testFilePath = Path.Combine(projectDirectory, TestFileName); File.Copy(unformattedCsFilePath, testFilePath); DotNetHelper.ExecuteCmd($"format {projectFilePath}"); BaselineHelper.CompareFiles(ExpectedFormattedFileName, testFilePath, OutputHelper); }
public async Task TestOpenProjectTwice_NetCoreApp2AndTwoLibraries() { CreateFiles(GetNetCoreApp2AndTwoLibrariesFiles()); var projectFilePath = GetSolutionFileName(@"Project\Project.csproj"); var library1FilePath = GetSolutionFileName(@"Library1\Library1.csproj"); var library2FilePath = GetSolutionFileName(@"Library2\Library2.csproj"); DotNetHelper.Restore(@"Project\Project.csproj", workingDirectory: this.SolutionDirectory.Path); DotNetHelper.Restore(@"Library2\Library2.csproj", workingDirectory: this.SolutionDirectory.Path); using (var workspace = CreateMSBuildWorkspace()) { var project = await workspace.OpenProjectAsync(projectFilePath); // Assert that there is are two projects loaded (Project.csproj references Library1.csproj). Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count); // Assert that the project does not have any diagnostics in Program.cs var document = project.Documents.First(d => d.Name == "Program.cs"); var semanticModel = await document.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); var library2 = await workspace.OpenProjectAsync(library2FilePath); // Assert that there are now three projects loaded (Library2.csproj also references Library1.csproj) Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count); // Assert that there is a project reference between Project.csproj and Library1.csproj AssertSingleProjectReference(project, library1FilePath); // Assert that there is a project reference between Library2.csproj and Library1.csproj AssertSingleProjectReference(library2, library1FilePath); } void AssertSingleProjectReference(Project project, string projectRefFilePath) { var projectReference = Assert.Single(project.ProjectReferences); var projectRefId = projectReference.ProjectId; Assert.Equal(projectRefFilePath, project.Solution.GetProject(projectRefId).FilePath); } }
public void WatchTests() { string projectDirectory = DotNetHelper.ExecuteNew(DotNetTemplate.Console.GetName(), nameof(DotNetWatchTests)); bool outputChanged = false; // We expect an exit code of 143 (128 + 15, i.e. SIGTERM) because we are killing the process manually DotNetHelper.ExecuteCmd( "watch run", workingDirectory: projectDirectory, additionalProcessConfigCallback: processConfigCallback, expectedExitCode: 143, millisecondTimeout: 30000); Assert.True(outputChanged); void processConfigCallback(Process process) { const string waitingString = "Waiting for a file to change before restarting dotnet..."; const string expectedString = "Hello from dotnet watch!"; bool fileChanged = false; process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { if (e.Data?.Contains(waitingString) ?? false) { if (!fileChanged) { OutputHelper.WriteLine("Program started, changing file on disk to trigger restart..."); File.WriteAllText( Path.Combine(projectDirectory, "Program.cs"), File.ReadAllText(Path.Combine(projectDirectory, "Program.cs")).Replace("Hello, World!", expectedString)); fileChanged = true; } } else if (e.Data?.Contains(expectedString) ?? false) { outputChanged = true; OutputHelper.WriteLine("Successfully re-ran program after code change."); ExecuteHelper.ExecuteProcessValidateExitCode("kill", $"-s TERM {process.Id}", OutputHelper); } }); } }
private static async Task <Workspace?> OpenMSBuildWorkspaceAsync( string solutionOrProjectPath, WorkspaceType workspaceType, bool noRestore, bool requiresSemantics, string?binaryLogPath, bool logWorkspaceWarnings, ILogger logger, CancellationToken cancellationToken) { if (requiresSemantics && !noRestore && await DotNetHelper.PerformRestoreAsync(solutionOrProjectPath, logger) != 0) { throw new Exception("Restore operation failed."); } return(await MSBuildWorkspaceLoader.LoadAsync(solutionOrProjectPath, workspaceType, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken)); }
internal void Execute(DotNetHelper dotNetHelper) { // Don't use the cli language name in the project name because it may contain '#': https://github.com/dotnet/roslyn/issues/51692 string projectName = $"{ScenarioName}_{Template}_{Language}"; string customNewArgs = Template.IsAspNetCore() && NoHttps ? "--no-https" : string.Empty; dotNetHelper.ExecuteNew(Template.GetName(), projectName, Language.ToCliName(), customArgs: customNewArgs); if (Commands.HasFlag(DotNetActions.Build)) { dotNetHelper.ExecuteBuild(projectName); } if (Commands.HasFlag(DotNetActions.Run)) { if (Template.IsAspNetCore()) { dotNetHelper.ExecuteRunWeb(projectName); } else { dotNetHelper.ExecuteRun(projectName); } } if (Commands.HasFlag(DotNetActions.Publish)) { dotNetHelper.ExecutePublish(projectName); } if (Commands.HasFlag(DotNetActions.PublishComplex)) { dotNetHelper.ExecutePublish(projectName, selfContained: false); dotNetHelper.ExecutePublish(projectName, selfContained: true, Config.TargetRid); dotNetHelper.ExecutePublish(projectName, selfContained: true, "linux-x64"); } if (Commands.HasFlag(DotNetActions.PublishR2R)) { dotNetHelper.ExecutePublish(projectName, selfContained: true, "linux-x64", trimmed: true, readyToRun: true); } if (Commands.HasFlag(DotNetActions.Test)) { dotNetHelper.ExecuteTest(projectName); } }
public async void VerifyScenario(DotNetTemplate template) { await InitializeOmniSharp(); string templateName = template.GetName(); string projectName = $"{nameof(OmniSharpTests)}_{templateName}"; string projectDirectory = DotNetHelper.ExecuteNew(templateName, projectName); (Process Process, string StdOut, string StdErr)executeResult = ExecuteHelper.ExecuteProcess( Path.Combine(OmniSharpDirectory, "run"), $"-s {projectDirectory}", OutputHelper, logOutput: true, millisecondTimeout: 5000, configure: (process) => DotNetHelper.ConfigureProcess(process, projectDirectory, setPath: true)); Assert.NotEqual(0, executeResult.Process.ExitCode); Assert.DoesNotContain("ERROR", executeResult.StdOut); Assert.DoesNotContain("ERROR", executeResult.StdErr); }
public async Task TestOpenProject_NetCoreMultiTFM() { CreateFiles(GetNetCoreMultiTFMFiles()); var projectFilePath = GetSolutionFileName("Project.csproj"); DotNetHelper.Restore("Project.csproj", workingDirectory: this.SolutionDirectory.Path); using (var workspace = CreateMSBuildWorkspace()) { await workspace.OpenProjectAsync(projectFilePath); // Assert that three projects have been loaded, one for each TFM. Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count); var projectPaths = new HashSet <string>(); var outputFilePaths = new HashSet <string>(); foreach (var project in workspace.CurrentSolution.Projects) { projectPaths.Add(project.FilePath); outputFilePaths.Add(project.OutputFilePath); } // Assert that the three projects share the same file path Assert.Single(projectPaths); // Assert that the three projects have different output file paths Assert.Equal(3, outputFilePaths.Count); // Assert that none of the projects have any diagnostics in Program.cs foreach (var project in workspace.CurrentSolution.Projects) { var document = project.Documents.First(d => d.Name == "Program.cs"); var semanticModel = await document.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); } } }
private static int Init() { while (_appName == null) { _appName = Prompt.GetString("App Name: ", promptColor: ConsoleColor.DarkGreen); } while (_package == null) { _package = Prompt.GetString("Package (Java like, e.g.: com.bionic.framework.myapp): ", promptColor: ConsoleColor.DarkGreen); } Logger.Preparing("Initializing Capacitor..."); // TODO: Check if required tools (npm/npx) are available // TODO: Check if already installed DotNetHelper.RunDotNet("new -i BionicCapacitorTemplate"); // TODO: Check if platforms/capacitor already exists DotNetHelper.RunDotNet("new bionic.capacitor -o platforms"); var cd = Directory.GetCurrentDirectory(); try { Directory.SetCurrentDirectory(ToOSPath($"{cd}/platforms/capacitor")); NpmInstall(); NpxCapInit(); } catch (Exception) { Logger.Error("Something went wrong during Capacitor install. Please check platforms/capacitor"); return(1); } finally { Directory.SetCurrentDirectory(cd); } Logger.Success("Capacitor is ready to go! - try: bionic platform capacitor"); return(0); }
public async Task TestOpenProject_NetCoreApp2() { CreateFiles(GetNetCoreApp2Files()); var projectFilePath = GetSolutionFileName("Project.csproj"); DotNetHelper.Restore("Project.csproj", workingDirectory: this.SolutionDirectory.Path); using (var workspace = CreateMSBuildWorkspace()) { var project = await workspace.OpenProjectAsync(projectFilePath); // Assert that there is a single project loaded. Assert.Single(workspace.CurrentSolution.ProjectIds); // Assert that the project does not have any diagnostics in Program.cs var document = project.Documents.First(d => d.Name == "Program.cs"); var semanticModel = await document.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); } }
public async Task TestOpenProjectTwice_NetCoreApp2AndLibrary() { CreateFiles(GetNetCoreApp2AndLibraryFiles()); var projectFilePath = GetSolutionFileName(@"Project\Project.csproj"); var libraryFilePath = GetSolutionFileName(@"Library\Library.csproj"); DotNetHelper.Restore(@"Project\Project.csproj", workingDirectory: this.SolutionDirectory.Path); using (var workspace = CreateMSBuildWorkspace()) { var libraryProject = await workspace.OpenProjectAsync(libraryFilePath); // Assert that there is a single project loaded. Assert.Single(workspace.CurrentSolution.ProjectIds); // Assert that the project does not have any diagnostics in Class1.cs var document = libraryProject.Documents.First(d => d.Name == "Class1.cs"); var semanticModel = await document.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); Assert.Empty(diagnostics); var project = await workspace.OpenProjectAsync(projectFilePath); // Assert that there are only two projects opened. Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count); // Assert that there is a project reference between Project.csproj and Library.csproj var projectReference = Assert.Single(project.ProjectReferences); var projectRefId = projectReference.ProjectId; Assert.Equal(libraryProject.Id, projectRefId); Assert.Equal(libraryProject.FilePath, workspace.CurrentSolution.GetProject(projectRefId).FilePath); } }
private static int InstallBionicTemplates() => DotNetHelper.RunDotNet("new -i BionicTemplates");
private static int InstallBionicCapacitorBridge() => DotNetHelper.RunDotNet("add package BionicBridgeCapacitor");
private static Tuple <string, List <ModuleDefinition> > GenerateProject(string msBuildPath, string workingDir, AssemblyDefinition definition, bool lib) { if (workingDir == null) { throw new ArgumentNullException(nameof(workingDir)); } if (definition == null) { throw new ArgumentNullException(nameof(definition)); } if (!Directory.Exists(workingDir)) { throw new DirectoryNotFoundException("Can not find the working directory: " + workingDir); } Logger.Log(LogType.Log, "Generating csproject File...", 1); if (lib) { DotNetHelper.NewLib(msBuildPath, workingDir, definition.AssemblyName); } else { DotNetHelper.NewCommandLine(msBuildPath, workingDir, definition.AssemblyName); } File.Delete(Path.Combine(workingDir, definition.AssemblyName, lib ? "Class1.cs" : "Program.cs")); //Delete Default Class string projectFile = Path.Combine(workingDir, definition.AssemblyName, definition.AssemblyName + ".csproj"); List <ModuleDefinition> modules = new List <ModuleDefinition>(); for (int i = 0; i < definition.IncludedModules.Count; i++) { if (modules.Count(x => x.Name == definition.IncludedModules[i].Name) == 0) { DiscoverModules(definition.IncludedModules[i], modules); } } Logger.Log(LogType.Log, $"Discovered {modules.Count} Modules.", 1); CSharpProject p = ProjectLoader.LoadProject(projectFile); foreach (ModuleDefinition defintionDefinition in modules) { for (int i = 0; i < defintionDefinition.Packages.Length; i++) { p.AddReference(defintionDefinition.Packages[i]); } for (int i = 0; i < defintionDefinition.EmbeddedFiles.Length; i++) { p.AddReference(defintionDefinition.EmbeddedFiles[i]); } } File.Delete(projectFile); p.Save(projectFile); return(new Tuple <string, List <ModuleDefinition> >(projectFile, modules)); }
protected SmokeTests(ITestOutputHelper outputHelper) { DotNetHelper = new DotNetHelper(outputHelper); OutputHelper = outputHelper; }
private static Tuple <string, List <ModuleDefinition> > GenerateProject(string msBuildPath, string workingDir, AssemblyDefinition definition, bool lib = true) { if (workingDir == null) { throw new ArgumentNullException(nameof(workingDir)); } if (definition == null) { throw new ArgumentNullException(nameof(definition)); } if (!Directory.Exists(workingDir)) { throw new DirectoryNotFoundException("Can not find the working directory: " + workingDir); } Logger.Log(LogType.Log, "Generating csproject File..."); DotNetHelper.New(msBuildPath, workingDir, definition.AssemblyName, lib); File.Delete(Path.Combine(workingDir, definition.AssemblyName, lib ? "Class1.cs" : "Program.cs")); //Delete Default Class string projectFile = Path.Combine(workingDir, definition.AssemblyName, definition.AssemblyName + ".csproj"); List <ModuleDefinition> modules = new List <ModuleDefinition>(); for (int i = 0; i < definition.IncludedModules.Count; i++) { if (modules.Count(x => x.Name == definition.IncludedModules[i].Name) == 0) { DiscoverModules(definition.IncludedModules[i], modules); } } Logger.Log(LogType.Log, $"Discovered {modules.Count} Modules."); CSharpProject p = ProjectLoader.LoadProject(projectFile); foreach (ModuleDefinition defintionDefinition in modules) { for (int i = 0; i < defintionDefinition.Packages.Length; i++) { p.AddReference(defintionDefinition.Packages[i]); } //for (int i = 0; i < defintionDefinition.Projects.Length; i++) //{ // CSharpReference r = PrepareForTransfer(defintionDefinition.Projects[i], // defintionDefinition); // string path = r.Attributes["Include"]; // if (modules.Count(x => path == Path.GetFullPath(Path.Combine(x.RootDirectory, x.Name + ".csproj"))) == 0) // { // p.AddReference(r); // } //} for (int i = 0; i < defintionDefinition.EmbeddedFiles.Length; i++) { p.AddReference(defintionDefinition.EmbeddedFiles[i]); } } File.Delete(projectFile); p.Save(projectFile); return(new Tuple <string, List <ModuleDefinition> >(projectFile, modules)); }
private static int Info() { new VersionCommand().Execute(); Logger.NewLine(); return(DotNetHelper.RunDotNet("--info")); }
public static void GenerateAssembly(string msBuildPath, AssemblyDefinition assemblyDefinitions, string outputFolder, AssemblyGeneratorBuildType buildType, bool lib) { if (msBuildPath == null) { throw new ArgumentNullException(nameof(msBuildPath)); } if (assemblyDefinitions == null) { throw new ArgumentNullException(nameof(assemblyDefinitions)); } if (outputFolder == null) { throw new ArgumentNullException(nameof(outputFolder)); } Logger.Log(LogType.Log, "Generating Assembly...", 1); string tempFolder = GetTempFolder(); Tuple <string, List <ModuleDefinition> > project = GenerateProject(msBuildPath, tempFolder, assemblyDefinitions, lib); string projectDir = Path.GetDirectoryName(project.Item1); Logger.Log(LogType.Log, $"Copying Files of {project.Item2.Count} Modules", 1); for (int i = 0; i < project.Item2.Count; i++) { string defDir = CreateDirectoryInFolderOrThrow(projectDir, project.Item2[i].Name); MoveFiles(defDir, project.Item2[i]); } string outDir = ""; if (buildType == AssemblyGeneratorBuildType.Build) { outDir = DotNetHelper.BuildProject(msBuildPath, project.Item1, assemblyDefinitions, lib); } else { outDir = DotNetHelper.PublishProject(msBuildPath, project.Item1, assemblyDefinitions, lib); } Logger.Log(LogType.Log, "Moving Files to output Directory...", 1); if (Directory.Exists(outputFolder)) { Directory.Delete(outputFolder, true); } Logger.Log(LogType.Log, "Cleaning Output Folder", 1); while (Directory.Exists(outputFolder)) { } Directory.Move(outDir, outputFolder); Logger.Log(LogType.Log, "Cleaning Temp Directory", 1); Directory.Delete(tempFolder, true); Logger.Log(LogType.Log, "Cleanup Finished.", 1); }
private static int UpdateBionic() => DotNetHelper.RunDotNet("tool update -g Bionic");
private static int InstallBionicExtensions() => DotNetHelper.RunDotNet("add package BionicExtensions");
private static int Info() { new VersionCommand().Execute(); Console.WriteLine(); return(DotNetHelper.RunDotNet("--info")); }
private static int ServeBlazor() => DotNetHelper.RunDotNet("watch run");
protected override string ProcessRemoteCommand(string name, string[] args) { var projectFullPath = Path.Combine(this.Context.SourceDirectory, this.ProjectPath); var buildProperties = string.Join(";", (this.MSBuildProperties ?? "").Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)); var config = "Configuration=" + this.ProjectBuildConfiguration; if (!string.IsNullOrEmpty(this.ProjectTargetPlatform)) { config += ";Platform=" + this.ProjectTargetPlatform; } if (!string.IsNullOrEmpty(buildProperties)) { config += ";" + buildProperties; } try { DotNetHelper.EnsureMsBuildWebTargets(); } catch { } this.LogDebug($"Building {projectFullPath}..."); int result = this.RunMSBuild( " \"{0}\" \"/p:{1}\"" + (this.IsWebProject || this.BuildToProjectConfigSubdirectories ? string.Empty : " \"/p:OutDir={2}\\\""), projectFullPath, config, this.Context.TargetDirectory.EndsWith("\\") ? this.Context.TargetDirectory : this.Context.TargetDirectory + '\\' ); if (result != 0) { this.LogError($"Build failed (msbuild returned {result})."); } else if (this.IsWebProject) { result = this.RunMSBuild( " \"{0}\" /target:_CopyWebApplication \"/p:OutDir={1}\\\" \"/p:WebProjectOutputDir={1}\\\" \"/p:{2}\"", projectFullPath, this.Context.TargetDirectory.EndsWith("\\") ? this.Context.TargetDirectory : this.Context.TargetDirectory + '\\', config ); if (result != 0) { this.LogError($"CopyWebApplication failed (msbuild returned {result})."); } else { result = this.RunMSBuild(" \"{0}\" /target:ResolveReferences \"/property:OutDir={1}\\\" \"/p:{2}\"", projectFullPath, Path.Combine(this.Context.TargetDirectory, "bin") + '\\', config ); if (result != 0) { this.LogError($"ResolveReferences failed (msbuild returned {result})."); } } } return(result.ToString()); }
private static int UninstallBionic() => DotNetHelper.RunDotNet("tool uninstall -g Bionic");