Skip to content

Commit

Permalink
Use new and more elegant AppTools.RunProcessCommand.
Browse files Browse the repository at this point in the history
  • Loading branch information
CartBlanche committed Jun 19, 2024
1 parent 2d35c0e commit 037190a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 33 deletions.
36 changes: 23 additions & 13 deletions Source/v2/Meadow.CLI/Commands/Current/App/AppTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,31 +138,41 @@ internal static string SanitizeMeadowFilename(string fileName)
return meadowFileName!.Replace(Path.DirectorySeparatorChar, '/');
}

// Method to run a command and return the output as a list of strings
public async static Task<List<string>> RunDotNetCommand(string command, string arguments, CancellationToken cancellationToken)
internal static async Task<int> RunProcessCommand(string command, string args, Action<string>? handleOutput = null, Action<string>? handleError = null, CancellationToken cancellationToken = default)
{

var processStartInfo = new ProcessStartInfo
{
FileName = command,
Arguments = arguments,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};

var output = new List<string>();
using var process = new Process { StartInfo = processStartInfo };
using (var process = new Process { StartInfo = processStartInfo })
{
process.Start();

process.Start();
var outputCompletion = ReadLinesAsync(process.StandardOutput, handleOutput, cancellationToken);
var errorCompletion = ReadLinesAsync(process.StandardError, handleError, cancellationToken);

while (!process.StandardOutput.EndOfStream)
{
output.Add(await process.StandardOutput.ReadLineAsync(cancellationToken) ?? string.Empty);
}
await Task.WhenAll(outputCompletion, errorCompletion, process.WaitForExitAsync());

await process.WaitForExitAsync();
return process.ExitCode;
}
}

return output;
private static async Task ReadLinesAsync(StreamReader reader, Action<string>? handleLine, CancellationToken cancellationToken)
{
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(line)
&& handleLine != null)
{
handleLine(line);
}
}
}
}
51 changes: 31 additions & 20 deletions Source/v2/Meadow.CLI/Commands/Current/Project/ProjectNewCommand.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using CliFx.Attributes;
using Meadow.CLI.Commands.DeviceManagement;
Expand Down Expand Up @@ -102,7 +100,7 @@ private async Task GenerateProjectsAndSolutionsFromSelectedTemplates(string proj
outputPathArgument = "--output " + outputPath;
generatedProjectName = $"{projectName}.{selectedTemplate.ShortName}";

_ = await AppTools.RunDotNetCommand("dotnet", $"new {selectedTemplate.ShortName} --name {generatedProjectName} {outputPathArgument} --language {Language} --force", CancellationToken);
_ = await AppTools.RunProcessCommand("dotnet", $"new {selectedTemplate.ShortName} --name {generatedProjectName} {outputPathArgument} --language {Language} --force", cancellationToken: CancellationToken);
}

if (generateSln)
Expand All @@ -118,7 +116,7 @@ private async Task GenerateSolution(string projectName)
AnsiConsole.MarkupLine($"[green]{Strings.ProjectTemplates.CreatingSln}[/]");

// Create the sln
_ = await AppTools.RunDotNetCommand("dotnet", $"new sln -n {projectName} -o {OutputPath} --force", CancellationToken);
_ = await AppTools.RunProcessCommand("dotnet", $"new sln -n {projectName} -o {OutputPath} --force", cancellationToken: CancellationToken);

//Now add to the new sln
var slnFilePath = Path.Combine(OutputPath!, projectName + ".sln");
Expand All @@ -144,10 +142,10 @@ private async Task GenerateSolution(string projectName)
var projectFiles = Directory.EnumerateFiles(OutputPath!, searchWildCard, SearchOption.AllDirectories);
foreach (var projectFile in projectFiles)
{
_ = await AppTools.RunDotNetCommand("dotnet", $"sln {slnFilePath} add {projectFile}", CancellationToken);
_ = await AppTools.RunProcessCommand("dotnet", $"sln {slnFilePath} add {projectFile}", cancellationToken: CancellationToken);
}

OpenSolution(slnFilePath);
await OpenSolution(slnFilePath);
}

private MeadowTemplate? PopulateTemplateNameList(List<string> templateList, List<MeadowTemplate> templateNameList, MeadowTemplate? startKitGroup, List<MeadowTemplate> startKitTemplates)
Expand Down Expand Up @@ -175,20 +173,38 @@ private async Task GenerateSolution(string projectName)

internal static async Task<List<string>?> GetInstalledTemplates(ILoggerFactory loggerFactory, CliFx.Infrastructure.IConsole console, CancellationToken cancellationToken)
{
var templateTable = new List<string>();

// Get the list of Meadow project templates
var templateTable = await AppTools.RunDotNetCommand("dotnet", "new list Meadow", cancellationToken);
var exitCode = await AppTools.RunProcessCommand("dotnet", "new list Meadow", handleOutput: outputLogLine =>
{
// Ignore empty output
if (!string.IsNullOrWhiteSpace(outputLogLine))
{
templateTable.Add(outputLogLine);
}
}, cancellationToken: cancellationToken);

// If no templates exists, then for now we automagically install them before proceeding
if (templateTable != null)

if (exitCode == 0)
{
if (templateTable.Count == 0)
{
AnsiConsole.MarkupLine($"[yellow]{Strings.ProjectTemplates.NoTemplatesFound}[/]");
var projectInstallCommand = new ProjectInstallCommand(loggerFactory);

// Let's install the templates then
var projectInstallCommand = new ProjectInstallCommand(loggerFactory);
await projectInstallCommand.ExecuteAsync(console);

templateTable = await AppTools.RunDotNetCommand("dotnet", "new list Meadow", cancellationToken);
// Try to populate the templateTable again, after installing the templates
exitCode = await AppTools.RunProcessCommand("dotnet", "new list Meadow", handleOutput: outputLogLine =>
{
// Ignore empty output
if (!string.IsNullOrWhiteSpace(outputLogLine))
{
templateTable.Add(outputLogLine);
}
}, cancellationToken: cancellationToken);
}

// Extract template names from the output
Expand All @@ -204,21 +220,16 @@ private async Task GenerateSolution(string projectName)
return null;
}

private void OpenSolution(string solutionPath)
private async Task OpenSolution(string solutionPath)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo
{
FileName = "cmd",
Arguments = $"/c start {solutionPath}",
UseShellExecute = false
});
var exitCode = await AppTools.RunProcessCommand("cmd", $"/c start {solutionPath}");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
|| RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("open", solutionPath);
var exitCode = await AppTools.RunProcessCommand("code", Path.GetDirectoryName(solutionPath));
}
else
{
Expand Down

0 comments on commit 037190a

Please sign in to comment.