122 lines
4.7 KiB
C#
122 lines
4.7 KiB
C#
using System.Diagnostics;
|
||
using System.Text.Json;
|
||
|
||
internal sealed record EmulatorInstance(string Name, string Type, string Version, string Running)
|
||
{
|
||
public override string ToString() => $"{Name} | {Type} | {Version} | {Running}";
|
||
}
|
||
|
||
internal sealed record EmulatorImage(string Type, string Version, string Downloaded)
|
||
{
|
||
public override string ToString() => $"{Type} | {Version} | {Downloaded}";
|
||
}
|
||
|
||
internal static class EmulatorCli
|
||
{
|
||
internal static string DefaultPath()
|
||
{
|
||
var name = OperatingSystem.IsWindows() ? "Emulator.exe" : "Emulator";
|
||
var configured = Environment.GetEnvironmentVariable("HARMONY_EMULATOR");
|
||
if (!string.IsNullOrWhiteSpace(configured))
|
||
return configured;
|
||
|
||
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||
string?[] candidates =
|
||
[
|
||
Environment.GetEnvironmentVariable("DEVECO_CLI_CLT_PATH"),
|
||
Path.Combine(home, "harmonyos", "command-line-tools"),
|
||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Huawei", "DevEco Studio", "tools"),
|
||
"/Applications/DevEco-Studio.app/Contents/tools"
|
||
];
|
||
return candidates.Where(path => !string.IsNullOrWhiteSpace(path))
|
||
.Select(path => Path.Combine(path!, "emulator", name))
|
||
.FirstOrDefault(path => Path.IsPathFullyQualified(path) && File.Exists(path)) ?? name;
|
||
}
|
||
|
||
internal static async Task<string> RunAsync(
|
||
string executable, string[] args, Action<string> log, CancellationToken cancellation)
|
||
{
|
||
var info = new ProcessStartInfo(executable)
|
||
{
|
||
UseShellExecute = false,
|
||
RedirectStandardOutput = true,
|
||
RedirectStandardError = true,
|
||
RedirectStandardInput = true,
|
||
CreateNoWindow = true
|
||
};
|
||
foreach (var argument in args)
|
||
info.ArgumentList.Add(argument);
|
||
|
||
log($"› Emulator {string.Join(" ", args.Select(arg => JsonSerializer.Serialize(arg)))}");
|
||
using var process = Process.Start(info) ?? throw new InvalidOperationException("无法启动 Emulator。");
|
||
process.StandardInput.Close();
|
||
var capture = args[0] is "-list" or "-imageList";
|
||
var stdout = ReadAsync(process.StandardOutput, capture ? null : log, capture, cancellation);
|
||
var stderr = ReadAsync(process.StandardError, log, false, cancellation);
|
||
try
|
||
{
|
||
await Task.WhenAll(process.WaitForExitAsync(cancellation), stdout, stderr);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
if (!process.HasExited)
|
||
process.Kill(entireProcessTree: true);
|
||
await process.WaitForExitAsync();
|
||
throw;
|
||
}
|
||
|
||
if (process.ExitCode != 0)
|
||
{
|
||
if (capture)
|
||
log(await stdout);
|
||
throw new InvalidOperationException($"Emulator 退出码 {process.ExitCode}。请查看命令输出。");
|
||
}
|
||
return await stdout;
|
||
}
|
||
|
||
private static async Task<string> ReadAsync(
|
||
StreamReader reader, Action<string>? log, bool capture, CancellationToken cancellation)
|
||
{
|
||
var output = new System.Text.StringBuilder();
|
||
while (await reader.ReadLineAsync(cancellation) is { } line)
|
||
{
|
||
log?.Invoke(line);
|
||
if (capture)
|
||
output.AppendLine(line);
|
||
}
|
||
return output.ToString();
|
||
}
|
||
|
||
internal static EmulatorInstance[] Instances(string output) => Parse(output, row => new EmulatorInstance(
|
||
Field(row, "name"), Field(row, "deviceType"), Field(row, "os.osVersion"),
|
||
Field(row, "isRunning").ToLowerInvariant() switch
|
||
{
|
||
"true" => "运行中",
|
||
"false" => "已停止",
|
||
_ => "未知"
|
||
}));
|
||
|
||
internal static EmulatorImage[] Images(string output) => Parse(output, row => new EmulatorImage(
|
||
Field(row, "deviceType"), Field(row, "osVersion"),
|
||
Field(row, "downloaded").ToLowerInvariant() switch
|
||
{
|
||
"true" => "已下载",
|
||
"false" => "未下载",
|
||
_ => "未知"
|
||
}));
|
||
|
||
private static T[] Parse<T>(string output, Func<JsonElement, T> convert)
|
||
{
|
||
var first = output.IndexOf('[');
|
||
var last = output.LastIndexOf(']');
|
||
if (first < 0 || last <= first)
|
||
throw new InvalidOperationException("未收到 Emulator 的 JSON 列表。请查看命令输出。");
|
||
|
||
using var document = JsonDocument.Parse(output[first..(last + 1)]);
|
||
return document.RootElement.EnumerateArray().Select(convert).ToArray();
|
||
}
|
||
|
||
private static string Field(JsonElement row, string name) =>
|
||
row.TryGetProperty(name, out var value) ? value.ToString() : "";
|
||
}
|