-
Notifications
You must be signed in to change notification settings - Fork 577
Expand file tree
/
Copy pathProgram.cs
More file actions
677 lines (574 loc) · 20.6 KB
/
Copy pathProgram.cs
File metadata and controls
677 lines (574 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
using System.Diagnostics;
using System.Text;
using Microsoft.Testing.Extensions;
using Mono.Options;
using Xamarin.Android.Tools;
const string Name = "Microsoft.Android.Run";
const string VersionsFileName = "Microsoft.Android.versions.txt";
string? adbPath = null;
string? adbTarget = null;
string? package = null;
string? activity = null;
string? deviceUserId = null;
string? instrumentation = null;
bool verbose = false;
int? logcatPid = null;
Process? logcatProcess = null;
CancellationTokenSource cts = new ();
string? logcatArgs = null;
bool isDotnetTestMode = false;
string? dotnetTestPipe = null;
try {
return await RunAsync (args);
} catch (OperationCanceledException) {
return 130; // 128 + SIGINT(2), standard Unix convention for Ctrl+C
} catch (Exception ex) {
Console.Error.WriteLine ($"Error: {ex.Message}");
if (verbose)
Console.Error.WriteLine (ex.ToString ());
return 1;
}
async Task<int> RunAsync (string[] args)
{
bool showHelp = false;
bool showVersion = false;
var options = new OptionSet {
$"Usage: {Name} [OPTIONS]",
"",
"Launches an Android application, streams its logcat output, and provides",
"proper Ctrl+C handling to stop the app gracefully.",
"Options:",
{ "a|adb=",
"Path to the {ADB} executable. If not specified, will attempt to locate " +
"the Android SDK automatically.",
v => adbPath = v },
{ "adb-target=",
"The {TARGET} device/emulator for adb commands (e.g., '-s emulator-5554').",
v => adbTarget = v },
{ "p|package=",
"The Android application {PACKAGE} name (e.g., com.example.myapp). Required.",
v => package = v },
{ "c|activity=",
"The {ACTIVITY} class name to launch. Required unless --instrument is used.",
v => activity = v },
{ "user=",
"The Android device {USER_ID} to launch the activity under (e.g., 10 for a work profile).",
v => deviceUserId = v },
{ "i|instrument=",
"The instrumentation {RUNNER} class name (e.g., com.example.myapp.TestInstrumentation). " +
"When specified, runs 'am instrument' instead of 'am start'.",
v => instrumentation = v },
{ "server=",
"The test {SERVER} protocol to use (e.g., 'dotnettestcli'). Used by 'dotnet test'.",
v => { if (v == "dotnettestcli") isDotnetTestMode = true; } },
{ "dotnet-test-pipe=",
"The {PIPE} name for dotnet test communication. Used by 'dotnet test'.",
v => dotnetTestPipe = v },
{ "v|verbose",
"Enable verbose output for debugging.",
v => verbose = v != null },
{ "logcat-args=",
"Extra {ARGUMENTS} to pass to 'adb logcat' (e.g., 'monodroid-assembly:S' to silence a tag).",
v => logcatArgs = v },
{ "version",
"Show version information and exit.",
v => showVersion = v != null },
{ "h|help|?",
"Show this help message and exit.",
v => showHelp = v != null },
};
List<string> remaining;
try {
remaining = options.Parse (args);
} catch (OptionException e) {
Console.Error.WriteLine ($"Error: {e.Message}");
Console.Error.WriteLine ($"Try '{Name} --help' for more information.");
return 1;
}
if (remaining.Count > 0 && !isDotnetTestMode && string.IsNullOrEmpty (instrumentation)) {
Console.Error.WriteLine ($"Error: Unexpected argument(s): {string.Join (" ", remaining)}");
Console.Error.WriteLine ($"Try '{Name} --help' for more information.");
return 1;
}
if (showVersion) {
var (version, commit) = GetVersionInfo ();
if (!string.IsNullOrEmpty (version)) {
Console.WriteLine ($"{Name} {version}");
if (!string.IsNullOrEmpty (commit))
Console.WriteLine ($"Commit: {commit}");
} else {
Console.WriteLine (Name);
}
return 0;
}
if (showHelp) {
options.WriteOptionDescriptions (Console.Out);
Console.WriteLine ();
Console.WriteLine ("Examples:");
Console.WriteLine ($" {Name} -p com.example.myapp -c com.example.myapp.MainActivity");
Console.WriteLine ($" {Name} -p com.example.myapp -i com.example.myapp.TestInstrumentation");
Console.WriteLine ($" {Name} -p com.example.myapp -i com.example.myapp.Benchmarks --filter *MyBench*");
Console.WriteLine ($" {Name} --adb /path/to/adb -p com.example.myapp -c com.example.myapp.MainActivity");
Console.WriteLine ();
Console.WriteLine ("When --instrument is used, any unrecognized arguments are forwarded to");
Console.WriteLine ("'am instrument' as extras: KEY=VALUE becomes '-e KEY VALUE', and everything");
Console.WriteLine ("else is joined into a single '-e args \"...\"' extra.");
Console.WriteLine ();
Console.WriteLine ("Press Ctrl+C while running to stop the Android application and exit.");
return 0;
}
if (string.IsNullOrEmpty (package)) {
Console.Error.WriteLine ("Error: --package is required.");
Console.Error.WriteLine ($"Try '{Name} --help' for more information.");
return 1;
}
bool isInstrumentMode = !string.IsNullOrEmpty (instrumentation);
if (!isInstrumentMode && string.IsNullOrEmpty (activity) && !isDotnetTestMode) {
Console.Error.WriteLine ("Error: --activity or --instrument is required.");
Console.Error.WriteLine ($"Try '{Name} --help' for more information.");
return 1;
}
if (isDotnetTestMode && !isInstrumentMode) {
Console.Error.WriteLine ("Error: --instrument is required when using dotnet test mode.");
Console.Error.WriteLine ($"Try '{Name} --help' for more information.");
return 1;
}
if (isInstrumentMode && !string.IsNullOrEmpty (activity)) {
Console.Error.WriteLine ("Error: --activity and --instrument cannot be used together.");
Console.Error.WriteLine ($"Try '{Name} --help' for more information.");
return 1;
}
// Resolve adb path if not specified
if (string.IsNullOrEmpty (adbPath)) {
adbPath = FindAdbPath ();
if (string.IsNullOrEmpty (adbPath)) {
Console.Error.WriteLine ("Error: Could not locate adb. Please specify --adb.");
return 1;
}
}
if (!File.Exists (adbPath)) {
Console.Error.WriteLine ($"Error: adb not found at '{adbPath}'.");
return 1;
}
Debug.Assert (adbPath != null, "adbPath should be non-null after validation");
if (verbose) {
Console.WriteLine ($"Using adb: {adbPath}");
if (!string.IsNullOrEmpty (adbTarget))
Console.WriteLine ($"Target: {adbTarget}");
Console.WriteLine ($"Package: {package}");
if (!string.IsNullOrEmpty (activity))
Console.WriteLine ($"Activity: {activity}");
if (isInstrumentMode)
Console.WriteLine ($"Instrumentation runner: {instrumentation}");
if (isDotnetTestMode)
Console.WriteLine ($"dotnet test mode (pipe: {dotnetTestPipe})");
}
// Set up Ctrl+C handler
Console.CancelKeyPress += OnCancelKeyPress;
try {
if (isDotnetTestMode)
return await RunDotnetTestAsync (remaining);
if (isInstrumentMode)
return await RunInstrumentationAsync (remaining);
return await RunAppAsync ();
} finally {
Console.CancelKeyPress -= OnCancelKeyPress;
cts.Dispose ();
}
}
void OnCancelKeyPress (object? sender, ConsoleCancelEventArgs e)
{
e.Cancel = true; // Prevent immediate exit
Console.WriteLine ();
Console.WriteLine ("Stopping application...");
cts.Cancel ();
// Force-stop the app (fire-and-forget in cancel handler)
_ = StopAppAsync ();
// Kill logcat process if running
try {
if (logcatProcess != null && !logcatProcess.HasExited) {
logcatProcess.Kill ();
}
} catch (Exception ex) {
if (verbose)
Console.Error.WriteLine ($"Error killing logcat process: {ex.Message}");
}
}
async Task<int> RunInstrumentationAsync (List<string> instrumentationArgs)
{
// '-w' waits for the run to complete; '-r' prints raw INSTRUMENTATION_STATUS
// blocks as they arrive instead of buffering everything until the end.
var cmdArgs = new List<string> { "shell", "am", "instrument", "-w", "-r" };
if (!string.IsNullOrEmpty (deviceUserId)) {
cmdArgs.Add ("--user");
cmdArgs.Add (deviceUserId);
}
cmdArgs.AddRange (BuildInstrumentationExtras (instrumentationArgs));
cmdArgs.Add ($"{package}/{instrumentation}");
if (verbose)
Console.WriteLine ($"Running instrumentation: adb {string.Join (" ", cmdArgs)}");
// Run instrumentation with streaming output
var psi = AdbHelper.CreateStartInfo (adbPath, adbTarget, cmdArgs);
using var instrumentProcess = new Process { StartInfo = psi };
var locker = new Lock ();
var output = new StringBuilder ();
instrumentProcess.OutputDataReceived += (s, e) => {
if (e.Data != null)
lock (locker) {
output.AppendLine (e.Data);
Console.WriteLine (e.Data);
}
};
instrumentProcess.ErrorDataReceived += (s, e) => {
if (e.Data != null)
lock (locker) {
output.AppendLine (e.Data);
Console.Error.WriteLine (e.Data);
}
};
instrumentProcess.Start ();
instrumentProcess.BeginOutputReadLine ();
instrumentProcess.BeginErrorReadLine ();
// Also stream logcat in the background, which is where Console output from the
// app ends up. The app process does not exist yet when `am instrument` starts,
// so poll for it rather than giving up after a single `pidof`.
var logcatTask = StartLogcatWhenAppStartsAsync ();
// Wait for instrumentation to complete or Ctrl+C
try {
try {
await instrumentProcess.WaitForExitAsync (cts.Token);
} catch (OperationCanceledException) {
try { instrumentProcess.Kill (); } catch (Exception ex) {
if (verbose)
Console.Error.WriteLine ($"Cleanup: {ex.Message}");
}
return 1;
}
} finally {
cts.Cancel ();
await logcatTask;
// Clean up logcat
try {
if (logcatProcess != null && !logcatProcess.HasExited) {
logcatProcess.Kill ();
logcatProcess.WaitForExit (1000);
}
} catch (Exception ex) {
if (verbose)
Console.Error.WriteLine ($"Logcat cleanup: {ex.Message}");
}
}
// Check exit status
if (instrumentProcess.ExitCode != 0) {
Console.Error.WriteLine ($"Error: adb instrument exited with code {instrumentProcess.ExitCode}");
return 1;
}
// `am instrument` exits 0 even when the instrumentation crashes or reports
// failure, so inspect what it printed to decide the exit code. `WaitForExitAsync`
// has already drained both readers, but read under the same lock for clarity.
string capturedOutput;
lock (locker)
capturedOutput = output.ToString ();
var failure = GetInstrumentationFailure (capturedOutput);
if (failure != null) {
Console.Error.WriteLine ($"Error: {failure}");
return 1;
}
return 0;
}
/// <summary>
/// Translates trailing `dotnet run -- ARGS` into `am instrument` extras.
/// `KEY=VALUE` arguments become `-e KEY VALUE`; everything else is joined and
/// passed as a single `-e args "..."` extra.
/// </summary>
List<string> BuildInstrumentationExtras (List<string> instrumentationArgs)
{
var result = new List<string> ();
if (instrumentationArgs.Count == 0)
return result;
var positional = new List<string> ();
foreach (var arg in instrumentationArgs) {
var eqIndex = arg.IndexOf ('=');
if (eqIndex > 0 && !arg.StartsWith ("-", StringComparison.Ordinal) && IsBundleKey (arg.AsSpan (0, eqIndex))) {
result.Add ("-e");
result.Add (arg.Substring (0, eqIndex));
result.Add (QuoteForDeviceShell (arg.Substring (eqIndex + 1)));
} else {
positional.Add (arg);
}
}
if (positional.Count > 0) {
result.Add ("-e");
result.Add ("args");
result.Add (QuoteForDeviceShell (string.Join (" ", positional)));
}
return result;
static bool IsBundleKey (ReadOnlySpan<char> key)
{
foreach (var c in key) {
if (!char.IsLetterOrDigit (c) && c != '_' && c != '.')
return false;
}
return key.Length > 0;
}
}
/// <summary>
/// Wraps a value in single quotes so the shell on the device treats it as a
/// single token. `adb shell` deliberately does not escape the arguments it
/// forwards, it just joins them with spaces (like `ssh`), so quoting for the
/// device shell is up to the caller. The surrounding quoting needed to survive
/// the *local* command line is handled by <see cref="ProcessStartInfo.ArgumentList"/>.
/// </summary>
static string QuoteForDeviceShell (string value) =>
"'" + value.Replace ("'", "'\\''") + "'";
/// <summary>
/// Inspects `am instrument` output for signs that the instrumentation crashed or
/// reported failure. Returns a human readable reason, or <c>null</c> on success.
/// </summary>
static string? GetInstrumentationFailure (string output)
{
if (output.Contains ("INSTRUMENTATION_FAILED", StringComparison.Ordinal))
return "The instrumentation failed to start. See the output above for details.";
string? shortMsg = null, longMsg = null;
int? code = null;
foreach (var rawLine in output.Split ('\n')) {
var line = rawLine.TrimEnd ('\r');
if (line.StartsWith ("INSTRUMENTATION_RESULT: shortMsg=", StringComparison.Ordinal))
shortMsg = line.Substring ("INSTRUMENTATION_RESULT: shortMsg=".Length).Trim ();
else if (line.StartsWith ("INSTRUMENTATION_RESULT: longMsg=", StringComparison.Ordinal))
longMsg = line.Substring ("INSTRUMENTATION_RESULT: longMsg=".Length).Trim ();
else if (line.StartsWith ("INSTRUMENTATION_CODE: ", StringComparison.Ordinal)) {
if (int.TryParse (line.Substring ("INSTRUMENTATION_CODE: ".Length).Trim (), out int parsed))
code = parsed;
}
}
if (longMsg != null || shortMsg != null)
return $"The application crashed: {longMsg ?? shortMsg}";
// Activity.RESULT_CANCELED (0) is what Instrumentation.Finish() reports on failure.
if (code == 0)
return "The instrumentation reported failure (INSTRUMENTATION_CODE: 0).";
if (code == null)
return "The instrumentation did not complete. It may have crashed before calling Finish().";
return null;
}
/// <summary>
/// Polls for the application process and starts streaming logcat once it appears.
/// </summary>
async Task StartLogcatWhenAppStartsAsync ()
{
try {
while (!cts.Token.IsCancellationRequested) {
var pid = await GetAppPidAsync ();
if (pid != null) {
logcatPid = pid;
StartLogcat ();
return;
}
await Task.Delay (250, cts.Token).ConfigureAwait (ConfigureAwaitOptions.SuppressThrowing);
}
} catch (OperationCanceledException) {
// The instrumentation finished (or was cancelled) before the app process was seen
} catch (Exception ex) {
if (verbose)
Console.Error.WriteLine ($"Error starting logcat: {ex.Message}");
}
}
async Task<int> RunDotnetTestAsync (List<string> mtpArgs)
{
if (verbose)
Console.WriteLine ("Running in dotnet test mode...");
if (string.IsNullOrEmpty (adbPath)) {
Console.Error.WriteLine ("Error: adb path must be specified in dotnet test mode.");
return 1;
}
if (string.IsNullOrEmpty (instrumentation)) {
Console.Error.WriteLine ("Error: Instrumentation must be specified in dotnet test mode.");
return 1;
}
if (string.IsNullOrEmpty (dotnetTestPipe)) {
Console.Error.WriteLine ("Error: --dotnet-test-pipe must be specified when using --server dotnettestcli.");
return 1;
}
if (string.IsNullOrEmpty (package)) {
Console.Error.WriteLine ("Error: Package must be specified in dotnet test mode.");
return 1;
}
var validatedAdbPath = adbPath;
var validatedInstrumentation = instrumentation;
var validatedDotnetTestPipe = dotnetTestPipe;
var validatedPackage = package;
// Re-add the MTP protocol args that Mono.Options consumed,
// since MTP needs them to set up the test communication channel.
mtpArgs.AddRange (["--server", "dotnettestcli", "--dotnet-test-pipe", validatedDotnetTestPipe]);
// MTP defaults its working directory to the DLL location (SDK tools directory),
// not Environment.CurrentDirectory. Pass --results-directory explicitly so TRX
// reports are written to the project directory, matching dotnet test conventions.
if (!mtpArgs.Contains ("--results-directory")) {
mtpArgs.AddRange (["--results-directory", Path.Combine (Environment.CurrentDirectory, "TestResults")]);
}
var testApplicationBuilder = await Microsoft.Testing.Platform.Builder.TestApplication.CreateBuilderAsync (mtpArgs.ToArray ());
var adapter = new AndroidTestAdapter (
validatedAdbPath,
adbTarget,
validatedPackage,
validatedInstrumentation,
verbose);
testApplicationBuilder.RegisterTestFramework (
_ => new AndroidTestCapabilities (),
(_, _) => adapter);
testApplicationBuilder.AddTrxReportProvider ();
using var testApplication = await testApplicationBuilder.BuildAsync ();
return await testApplication.RunAsync ();
}
async Task<int> RunAppAsync ()
{
// 1. Start the app
if (!await StartAppAsync ())
return 1;
// 2. Get the PID
logcatPid = await GetAppPidAsync ();
if (logcatPid == null) {
Console.Error.WriteLine ("Error: App started but could not retrieve PID. The app may have crashed.");
return 1;
}
if (verbose)
Console.WriteLine ($"App PID: {logcatPid}");
// 3. Stream logcat
StartLogcat ();
// 4. Wait for app to exit or Ctrl+C
await WaitForAppExitAsync ();
return 0;
}
async Task<bool> StartAppAsync ()
{
var userArg = string.IsNullOrEmpty (deviceUserId) ? "" : $" --user {deviceUserId}";
var cmdArgs = $"shell am start -S -W{userArg} -n \"{package}/{activity}\"";
var (exitCode, output, error) = await AdbHelper.RunAsync (adbPath, adbTarget, cmdArgs, cts.Token, verbose);
if (exitCode != 0) {
Console.Error.WriteLine ($"Error: Failed to start app: {error}");
return false;
}
if (verbose)
Console.WriteLine (output);
return true;
}
async Task<int?> GetAppPidAsync ()
{
var cmdArgs = $"shell pidof {package}";
var (exitCode, output, error) = await AdbHelper.RunAsync (adbPath, adbTarget, cmdArgs, cts.Token, verbose);
if (exitCode != 0 || string.IsNullOrWhiteSpace (output))
return null;
var pidStr = output.Trim ().Split (' ') [0]; // Take first PID if multiple
if (int.TryParse (pidStr, out int pid))
return pid;
return null;
}
void StartLogcat ()
{
if (logcatPid == null)
return;
var logcatArguments = $"logcat --pid={logcatPid}";
if (!string.IsNullOrEmpty (logcatArgs))
logcatArguments += $" {logcatArgs}";
var psi = AdbHelper.CreateStartInfo (adbPath, adbTarget, logcatArguments);
if (verbose)
Console.WriteLine ($"Running: adb {psi.Arguments}");
var locker = new Lock();
logcatProcess = new Process { StartInfo = psi };
logcatProcess.OutputDataReceived += (s, e) => {
if (e.Data != null)
lock (locker)
Console.WriteLine (e.Data);
};
logcatProcess.ErrorDataReceived += (s, e) => {
if (e.Data != null)
lock (locker)
Console.Error.WriteLine (e.Data);
};
logcatProcess.Start ();
logcatProcess.BeginOutputReadLine ();
logcatProcess.BeginErrorReadLine ();
}
async Task WaitForAppExitAsync ()
{
while (!cts.Token.IsCancellationRequested) {
// Check if app is still running
var pid = await GetAppPidAsync ();
if (pid == null || pid != logcatPid) {
if (verbose)
Console.WriteLine ("App has exited.");
break;
}
// Also check if logcat process exited unexpectedly
if (logcatProcess != null && logcatProcess.HasExited) {
if (verbose)
Console.WriteLine ("Logcat process exited.");
break;
}
await Task.Delay (1000, cts.Token).ConfigureAwait (ConfigureAwaitOptions.SuppressThrowing);
}
// Clean up logcat process
try {
if (logcatProcess != null && !logcatProcess.HasExited) {
logcatProcess.Kill ();
logcatProcess.WaitForExit (1000);
}
} catch (Exception ex) {
if (verbose)
Console.Error.WriteLine ($"Error cleaning up logcat process: {ex.Message}");
}
}
async Task StopAppAsync ()
{
if (string.IsNullOrEmpty (package) || string.IsNullOrEmpty (adbPath))
return;
var userArg = string.IsNullOrEmpty (deviceUserId) ? "" : $" --user {deviceUserId}";
await AdbHelper.RunAsync (adbPath, adbTarget, $"shell am force-stop{userArg} {package}", CancellationToken.None, verbose);
}
string? FindAdbPath ()
{
try {
// Use AndroidSdkInfo to locate the SDK
var sdk = new AndroidSdkInfo (
logger: verbose ? (level, msg) => Console.WriteLine ($"[{level}] {msg}") : null
);
if (!string.IsNullOrEmpty (sdk.AndroidSdkPath)) {
var adb = Path.Combine (sdk.AndroidSdkPath, "platform-tools", OperatingSystem.IsWindows () ? "adb.exe" : "adb");
if (File.Exists (adb))
return adb;
}
} catch (Exception ex) {
if (verbose)
Console.WriteLine ($"AndroidSdkInfo failed: {ex.Message}");
}
return null;
}
(string? Version, string? Commit) GetVersionInfo ()
{
try {
// The tool is in: <sdk>/tools/Microsoft.Android.Run.dll
// The versions file is in: <sdk>/Microsoft.Android.versions.txt
var toolPath = typeof (OptionSet).Assembly.Location;
if (string.IsNullOrEmpty (toolPath))
toolPath = Environment.ProcessPath;
if (string.IsNullOrEmpty (toolPath))
return (null, null);
var toolDir = Path.GetDirectoryName (toolPath);
if (string.IsNullOrEmpty (toolDir))
return (null, null);
var sdkDir = Path.GetDirectoryName (toolDir);
if (string.IsNullOrEmpty (sdkDir))
return (null, null);
var versionsFile = Path.Combine (sdkDir, VersionsFileName);
if (!File.Exists (versionsFile))
return (null, null);
var lines = File.ReadAllLines (versionsFile);
string? commit = lines.Length > 0 ? lines [0].Trim () : null;
string? version = lines.Length > 1 ? lines [1].Trim () : null;
return (version, commit);
} catch (Exception ex) {
if (verbose)
Console.Error.WriteLine ($"Error reading version info: {ex.Message}");
return (null, null);
}
}