-
Notifications
You must be signed in to change notification settings - Fork 568
Expand file tree
/
Copy pathProgram.cs
More file actions
447 lines (374 loc) · 12.4 KB
/
Program.cs
File metadata and controls
447 lines (374 loc) · 12.4 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
using System.Diagnostics;
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;
try {
return await RunAsync (args);
} 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 },
{ "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 },
};
try {
var remaining = options.Parse (args);
if (remaining.Count > 0) {
Console.Error.WriteLine ($"Error: Unexpected argument(s): {string.Join (" ", remaining)}");
Console.Error.WriteLine ($"Try '{Name} --help' for more information.");
return 1;
}
} catch (OptionException e) {
Console.Error.WriteLine ($"Error: {e.Message}");
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} --adb /path/to/adb -p com.example.myapp -c com.example.myapp.MainActivity");
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)) {
Console.Error.WriteLine ("Error: --activity or --instrument is required.");
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}");
}
// Set up Ctrl+C handler
Console.CancelKeyPress += OnCancelKeyPress;
try {
if (isInstrumentMode)
return await RunInstrumentationAsync ();
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 ()
{
// Build the am instrument command
var userArg = string.IsNullOrEmpty (deviceUserId) ? "" : $" --user {deviceUserId}";
var cmdArgs = $"shell am instrument -w{userArg} {package}/{instrumentation}";
if (verbose)
Console.WriteLine ($"Running instrumentation: adb {cmdArgs}");
// Run instrumentation with streaming output
var psi = AdbHelper.CreateStartInfo (adbPath, adbTarget, cmdArgs);
using var instrumentProcess = new Process { StartInfo = psi };
var locker = new Lock ();
instrumentProcess.OutputDataReceived += (s, e) => {
if (e.Data != null)
lock (locker)
Console.WriteLine (e.Data);
};
instrumentProcess.ErrorDataReceived += (s, e) => {
if (e.Data != null)
lock (locker)
Console.Error.WriteLine (e.Data);
};
instrumentProcess.Start ();
instrumentProcess.BeginOutputReadLine ();
instrumentProcess.BeginErrorReadLine ();
// Also start logcat in the background for additional debug output
logcatPid = await GetAppPidAsync ();
if (logcatPid != null)
StartLogcat ();
// Wait for instrumentation to complete or Ctrl+C
try {
while (!instrumentProcess.HasExited && !cts.Token.IsCancellationRequested)
await Task.Delay (250, cts.Token).ConfigureAwait (ConfigureAwaitOptions.SuppressThrowing);
if (cts.Token.IsCancellationRequested) {
try { instrumentProcess.Kill (); } catch { }
return 1;
}
instrumentProcess.WaitForExit ();
} finally {
// Clean up logcat
try {
if (logcatProcess != null && !logcatProcess.HasExited) {
logcatProcess.Kill ();
logcatProcess.WaitForExit (1000);
}
} catch { }
}
// Check exit status
if (instrumentProcess.ExitCode != 0) {
Console.Error.WriteLine ($"Error: adb instrument exited with code {instrumentProcess.ExitCode}");
return 1;
}
return 0;
}
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);
}
}