File size: 31,737 Bytes
89995d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import tempfile
import subprocess
import shutil
import xml.etree.ElementTree as ET
from pathlib import Path
import shell
import eval_data_classes
import logging
from typing import Any, List
import os
import stat
import time
import re
from constants import CONFIG_PROPERTIES_FILE
import threading
import signal

TEMP_DIR = "/workspace/temp"


def get_android_home() -> str:
    """Returns the ANDROID_HOME environment variable or raises an error."""
    android_home = os.environ.get("ANDROID_HOME")
    if not android_home:
        raise EnvironmentError(
            "ANDROID_HOME environment variable not set. Please set it to your"
            " Android SDK path."
        )
    return android_home


def get_adb_path() -> str:
    """Returns the path to the adb executable."""
    return os.path.join(get_android_home(), "platform-tools", "adb")


def print_and_log(log_file: str, message: str) -> None:
    """Print and log the message."""

    logging.info(message)
    with open(log_file, "a") as log:
        log.write(f"{message}\n\n")


def git_clone(repo_full_name: str, cwd: str) -> None:
    """Clones a git repository."""
    repo_url = f"https://github.com/{repo_full_name}.git"
    # Git clone into cwd directly
    clone_command = f"git clone {repo_url} ."
    shell.run_command(clone_command, cwd=cwd)


def git_checkout(commit: str, cwd: str) -> None:
    """Checks out a specific commit."""
    # Git checkout sha
    checkout_command = f"git checkout {commit} -f"
    shell.run_command(checkout_command, cwd=cwd)
    shell.run_command("git submodule update --init --recursive", cwd=cwd)


def reset_to_commit(commit_sha: str, cwd: str) -> None:
    """Resets a git repository to a specific commit."""

    # Git checkout sha
    checkout_command = f"git reset --hard {commit_sha} --recurse-submodules"
    result = shell.run_command(checkout_command, cwd=cwd)
    logging.info(f"exit_code: {result.exit_code}")
    logging.info(f"stdout: {result.stdout}")
    logging.info(f"stderr: {result.stderr}")
    if result.exit_code != 0:
        logging.error(f"Error while resetting to a commit: {result.stderr}")
        return False
    return True


def reset_to_changeid(change_id: str, cwd: str) -> None:
    """Resets a git repository to a specific commit."""

    # Git checkout sha
    checkout_command = f"git reset --hard change-{change_id}"
    result = shell.run_command(checkout_command, cwd=cwd)
    logging.info(f"exit_code: {result.exit_code}")
    logging.info(f"stdout: {result.stdout}")
    logging.info(f"stderr: {result.stderr}")
    if result.exit_code != 0:
        logging.error(f"Error while resetting to a commit: {result.stderr}")
        return False
    return True


def _get_agp_version(project_dir: str) -> str | None:
    result = shell.run_command(
        "./gradlew buildEnvironment | grep com.android.tools.build:gradle:",
        cwd=project_dir,
    )
    lines = result.stdout.splitlines()
    if not lines:
        return None
    return lines[0].split("com.android.tools.build:gradle:")[-1]


def run_after_agent_commands(
    after_agent_commands: List[str],
    project_dir: str,
    timeout: int | None = None,
) -> bool:
    """Runs commands after the agent has run."""
    for command in after_agent_commands:
        result = shell.run_command(command, cwd=project_dir, timeout=timeout)
        logging.info(f"after_agent stdout: {result.stdout}")
        logging.info(f"after_agent stderr: {result.stderr}")
        if result.exit_code != 0:
            return False
    return True


def can_compile_successfully(
    build_commands: List[str],
    project_dir: str,
    timeout: int | None = None,
) -> bool:
    """Checks if a project can compile successfully."""
    for build_command in build_commands:
        build_command += " -Dorg.gradle.workers.max=8"
        result = shell.run_command(build_command, cwd=project_dir, timeout=timeout)
        logging.info(f"build stdout: {result.stdout}")
        logging.info(f"build stderr: {result.stderr}")
        if result.exit_code != 0:
            return False
    return True


def can_build_successfully(
    project_dir: str,
    log_file: str,
    pull_request_example: eval_data_classes.PullRequestExample,
    execution_config: eval_data_classes.RepoExecutionConfig,
    log_command_output: bool,
    timeout: int | None = None,
) -> bool:
    """Checks if a project can build successfully."""
    if execution_config and execution_config.assemble_command:
        build_command = execution_config.assemble_command
    else:
        build_command = "./gradlew assembleDebug"
    pull_request_example.build_command = build_command

    init_script = f"/tests/verifier/get-target-sdk-init-script.gradle"

    with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as tmp:
        build_command += f" -Pandroid.bench.targetSdk.path={tmp.name} --init-script={init_script} -Dorg.gradle.workers.max=8"
        result = shell.run_command(build_command, cwd=project_dir, timeout=timeout)
        logging.info(f"build stdout: {result.stdout}")
        logging.info(f"build stderr: {result.stderr}")

        _parse_android_test_target_sdk(tmp.name, execution_config)

    return result.exit_code == 0


def _parse_android_test_target_sdk(
    target_sdk_file_path: str, execution_config: eval_data_classes.RepoExecutionConfig
):

    max_target_sdk = 0
    with open(target_sdk_file_path, "r") as f:
        for line in f:
            if "uses Target SDK: " in line:
                max_target_sdk = max(
                    max_target_sdk, int(line.split("uses Target SDK: ")[-1].strip())
                )

    if max_target_sdk > 0:
        execution_config.fallback_target_sdk = str(max_target_sdk)


def _get_unit_test_command(execution_config: eval_data_classes.RepoExecutionConfig):
    if execution_config.unit_tests_command:
        return execution_config.unit_tests_command
    return r"./gradlew -q tasks --all | cut -d ' ' -f1 | grep -E '^\S*:test[^:]*DebugUnitTest' | xargs ./gradlew --no-configuration-cache --continue "


def _get_android_test_command(execution_config: eval_data_classes.RepoExecutionConfig):
    if execution_config.android_tests_command:
        return execution_config.android_tests_command
    return r"./gradlew -q tasks --all | cut -d ' ' -f1 | grep -E '^\S*:connected[^:]*DebugAndroidTest' | xargs ./gradlew --no-configuration-cache --continue "


def _parse_test_results(
    test_log_file_path: str,
    build_successful: bool = True,
    remove_task_names: bool = False,
):
    result = eval_data_classes.TestsExecutionResult(build_successful, set(), set())

    with open(test_log_file_path, "r") as f:
        for line in f:
            try:
                json_data = json.loads(line)
            except json.decoder.JSONDecodeError as e:
                logging.error(f"Failed to test results log: {e}, line: {line}")
                continue
            test = json_data["test"]
            if re.match(r"^\w+#Test", test) and remove_task_names:
                test = test.partition("#")[2]

            # Normalize composable lambda hash names in test results.
            test = re.sub(
                r"ComposableLambdaImpl@[a-zA-Z0-9]+(?=\))", "ComposableLambdaImpl", test
            )

            if json_data["status"] == "SUCCESS":
                result.passed_tests.add(test)
            else:
                result.failed_tests.add(test)

    return result


def clean_test_outputs(project_dir: str) -> None:
    """Cleans build output directories."""
    # Cleans the directories which we retrieve from copy_build_outputs function
    # because open-variants pollute these paths even before the run, which ends up
    # bringing stale artifacts from the container to the result folder.
    # We selectively delete test output paths instead of running `./gradlew clean` to preserve compilation build caches and avoid adding full recompilation overhead.
    try:
        shell.run_command(
            "find . -type d -path '*/build/test-results/dropshots' -exec rm -rf {} +",
            cwd=project_dir,
        )
        shell.run_command(
            "find . -type d -path '*/build/paparazzi' -exec rm -rf {} +",
            cwd=project_dir,
        )
        shell.run_command(
            "find . -type d -path '*/build/outputs/roborazzi' -exec rm -rf {} +",
            cwd=project_dir,
        )
        shell.run_command(
            "find . -type f -name 'logcat-*.txt' -exec rm -f {} +", cwd=project_dir
        )
    except Exception:
        pass


def run_tests(
    project_dir: str,
    run_tests_command: str,
    timeout: int | None = None,
    workers: int = 8,
    remove_task_names: bool = False,
) -> eval_data_classes.TestsExecutionResult:
    """Runs tests and returns the result."""

    TEMP_DIR = "/workspace/temp"
    os.makedirs(TEMP_DIR, exist_ok=True)
    _, path = tempfile.mkstemp(prefix="tmp-", suffix=".txt", dir=TEMP_DIR)

    init_script_path = f"/tests/verifier/test-dump-init-script.gradle"
    check_init_script_exists_command = f"ls {init_script_path}"
    init_exists_result = shell.run_command(check_init_script_exists_command)
    if init_exists_result.exit_code != 0:
        logging.error(
            f'mount_path contents: {shell.run_command("ls /tests/verifier").stdout}'
        )
        raise EnvironmentError("Gradle init script does not exist.")

    if "--continue" not in run_tests_command:
        run_tests_command += " --continue"
    run_tests_command += f" -Pandroid.bench.test.log.file.path={path} --init-script={init_script_path} --rerun-tasks -Dorg.gradle.workers.max={workers}"
    result = shell.run_command(run_tests_command, cwd=project_dir, timeout=timeout)
    logging.info(f"exit_code: {result.exit_code}")
    logging.info(
        f'is "BUILD SUCCESSFUL" in result.stdout: {"BUILD SUCCESSFUL" in result.stdout}'
    )
    logging.info(f"Gradle test stdout:\n {result.stdout}")
    logging.info(f"Gradle test stderr:\n {result.stderr}")
    # currently we check build status by checking if "BUILD SUCCESSFUL" is in the output
    # context: legit/258310/1/common/eval_data_classes.py#67
    build_successful = result.exit_code == 0

    test_results = _parse_test_results(path, build_successful, remove_task_names)
    os.remove(path)

    # Also parse XML results from androidTest-results directories
    for results_dir in Path(project_dir).glob("**/androidTest-results/connected"):
        if results_dir.is_dir():
            logging.info(f"Parsing XML test results from {results_dir}")
            _parse_xml_results(
                results_dir,
                test_results.passed_tests,
                test_results.failed_tests,
                remove_task_names,
            )

    return test_results


def _parse_xml_results(
    results_dir: Path,
    passed_tests: set[str],
    failed_tests: set[str],
    remove_task_names: bool = False,
):
    """Parses JUnit XML test results and adds them to the test sets."""
    for xml_file in results_dir.glob("**/*.xml"):
        logging.info(f"Parsing test results: {xml_file}")
        try:
            tree = ET.parse(xml_file)
            root = tree.getroot()
            flavor = _get_flavor_from_test_xml(root) or ""

            task_name = f"connected{flavor.capitalize()}DebugAndroidTest"
            for testcase in root.iter("testcase"):
                class_name = testcase.get("classname")
                test_name = testcase.get("name")

                if remove_task_names:
                    test = f"Test {test_name}({class_name})"
                else:
                    test = f"{task_name}#Test {test_name}({class_name})"

                # Escape control characters
                test = re.sub(
                    r"[\x00-\x1F]",
                    lambda m: f"\\u{ord(m.group(0)):04x}",
                    test.replace('"', '\\\\"'),
                )

                if testcase.find("failure") is not None:
                    failed_tests.add(test)
                elif testcase.find("skipped") is None:
                    passed_tests.add(test)

        except ET.ParseError as e:
            logging.warning(f"Warning: Failed to parse XML file: {xml_file.name} ({e})")
        except Exception as e:
            logging.error(
                f"An unexpected error occurred while processing {xml_file.name}: {e}"
            )


def _get_flavor_from_test_xml(root) -> str | None:
    """Parses flavor from test xml."""
    properties = root.find("properties")
    if properties is None:
        return None
    for prop in properties.findall("property"):
        if prop.get("name") == "flavor":
            return prop.get("value")
    return None


def can_run_unit_tests_successfully(
    project_dir: str,
    pull_request_example: eval_data_classes.PullRequestExample,
    execution_config: eval_data_classes.RepoExecutionConfig,
    timeout: int | None = None,
) -> eval_data_classes.TestsExecutionResult:
    """Extracts the unit test command and runs it."""
    run_unit_tests_command = _get_unit_test_command(execution_config)
    pull_request_example.unit_test_command = run_unit_tests_command
    return run_tests(project_dir, run_unit_tests_command, timeout)


def can_run_android_tests_successfully(
    project_dir: str,
    pull_request_example: eval_data_classes.PullRequestExample,
    execution_config: eval_data_classes.RepoExecutionConfig,
    timeout: int | None = None,
) -> eval_data_classes.TestsExecutionResult:
    """Extracts the Android test command and runs it."""
    run_android_tests_command = _get_android_test_command(execution_config)
    pull_request_example.android_test_commands = [run_android_tests_command]
    return run_tests(project_dir, run_android_tests_command, timeout, workers=4)


class EmulatorStartupTimeoutError(Exception):
    """Raised when the emulator fails to start within the timeout period."""

    timeout_seconds: int

    def __init__(self, timeout_seconds: int) -> None:
        self.timeout_seconds = timeout_seconds


class EmulatorFailedToStartError(Exception):
    """Raised when the emulator fails to start for any reason other than timeout."""

    pass


class EmulatorMissingError(Exception):
    """Raised when the requested emulator AVD is not installed."""

    def __init__(self, avd_name: str, available_avds: list[str]) -> None:
        self.avd_name = avd_name
        self.available_avds = available_avds
        super().__init__(
            f"Emulator AVD '{avd_name}' not found. "
            f"Available AVDs: {available_avds}. "
            "Please ensure the emulator is installed in the Docker image."
        )


class EmulatorHeartbeat(threading.Thread):
    """A thread that monitors the status of an Android emulator."""

    def __init__(
        self,
        emulator_process: subprocess.Popen,
        adb_path: str,
        log_file: str,
        interval_seconds: int = 15,
    ) -> None:
        super().__init__()
        self.emulator_process = emulator_process
        self.adb_path = adb_path
        self.log_file = log_file
        self.interval_seconds = interval_seconds
        self.daemon = True
        self._stop_event = threading.Event()
        self.failure: str | None = None

    def stop(self) -> None:
        """Stops the heartbeat thread."""
        self._stop_event.set()

    def run(self) -> None:
        """Periodically checks the emulator status."""
        while not self._stop_event.is_set():
            # Check if the emulator process is still running
            if self.emulator_process.poll() is not None:
                message = f"CRITICAL: Emulator process (PID {self.emulator_process.pid}) has exited unexpectedly with code {self.emulator_process.returncode}."
                print_and_log(self.log_file, message)
                self.failure = message
                os.kill(os.getpid(), signal.SIGINT)
                break

            # Check if adb can still see the emulator
            try:
                result = subprocess.run(
                    [self.adb_path, "devices"],
                    capture_output=True,
                    text=True,
                    timeout=10,
                )
                if "emulator" not in result.stdout.lower():
                    message = (
                        "CRITICAL: Emulator went offline or is not detected by ADB."
                    )
                    print_and_log(self.log_file, message)
                    self.failure = message
                    os.kill(os.getpid(), signal.SIGINT)
                    break
            except subprocess.TimeoutExpired:
                print_and_log(self.log_file, "WARNING: ADB devices command timed out.")
            except Exception as e:
                print_and_log(
                    self.log_file, f"WARNING: Error while checking emulator status: {e}"
                )

            # Wait for the next interval or until stopped
            self._stop_event.wait(self.interval_seconds)


def stop_active_emulators(
    log_file: str | None = None, target_avd_name: str | None = None
) -> None:
    """Shuts down active Android emulator instances.

    If target_avd_name is specified, shuts down only the matching emulator instance.
    Otherwise, shuts down all running emulators.

    Tries a graceful ADB shutdown first ('adb -s <serial> emu kill').
    Falls back to a force kill ('pkill -9 -f <pattern>') if instances remain.
    """
    msg = (
        f"Initiating shutdown of emulator ('{target_avd_name}')..."
        if target_avd_name
        else "Initiating shutdown of all active Android emulators..."
    )
    if log_file and os.path.exists(log_file):
        print_and_log(log_file, msg)
    else:
        logging.info(msg)

    adb_path = get_adb_path()
    try:
        # 1. Attempt graceful ADB shutdown
        result = subprocess.run(
            [adb_path, "devices"], capture_output=True, text=True, timeout=5
        )
        for line in result.stdout.splitlines():
            if "emulator-" in line and "device" in line:
                serial = line.split()[0]
                should_kill = True
                if target_avd_name:
                    # Query this specific emulator's AVD name
                    avd_query = subprocess.run(
                        [adb_path, "-s", serial, "emu", "avd", "name"],
                        capture_output=True,
                        text=True,
                        timeout=5,
                    )
                    running_avd = (
                        avd_query.stdout.splitlines()[0].strip()
                        if avd_query.stdout and avd_query.stdout.splitlines()
                        else ""
                    )
                    if running_avd != target_avd_name:
                        should_kill = False

                if should_kill:
                    logging.info(f"Sending graceful shutdown to {serial}...")
                    subprocess.run(
                        [adb_path, "-s", serial, "emu", "kill"],
                        capture_output=True,
                        timeout=5,
                    )
        # Give emulators a moment to save state and exit gracefully
        time.sleep(3)
    except Exception as e:
        logging.warning(f"Graceful ADB emulator shutdown met an error: {e}")

    # 2. Aggressive pkill fallback
    try:
        if target_avd_name:
            subprocess.run(
                ["pkill", "-9", "-f", f"-avd {target_avd_name}"],
                timeout=5,
                capture_output=True,
            )
        else:
            subprocess.run(
                ["pkill", "-9", "-f", "qemu"], timeout=5, capture_output=True
            )
            subprocess.run(
                ["pkill", "-9", "-f", "emulator"], timeout=5, capture_output=True
            )
            subprocess.run([adb_path, "kill-server"], timeout=5, capture_output=True)
    except Exception:
        pass


def start_and_wait_for_emulator(
    log_file: str,
    emulator_avd_name: str,
    timeout_seconds: int = 180,
    force_stop_existing: bool = True,
) -> subprocess.Popen[Any]:
    """Starts an Android emulator and waits for it to be fully booted.

    Args:
      emulator_avd_name: The name of the AVD to start.
      timeout_seconds: The maximum time to wait for the emulator to boot.
      force_stop_existing: If True, shuts down any already running emulators matching this AVD before starting.

    Returns:
      A subprocess.Popen object representing the running emulator process, or None
       if the emulator did not boot within the timeout period.

    Raises:
      EnvironmentError: If ANDROID_HOME environment variable is not set.
    """
    emulator_path = os.path.join(get_android_home(), "emulator", "emulator")

    # Check if emulator exists
    check_avd_command = f"{emulator_path} -list-avds"
    result = shell.run_command(check_avd_command)
    avd_list = result.stdout.splitlines() if result.stdout else []
    if emulator_avd_name not in avd_list:
        print_and_log(log_file, f"ERROR: Emulator AVD '{emulator_avd_name}' not found.")
        print_and_log(log_file, f"Available AVDs: {avd_list}")
        raise EmulatorMissingError(emulator_avd_name, avd_list)

    if force_stop_existing:
        stop_active_emulators(log_file, target_avd_name=emulator_avd_name)

    # -no-snapshot: start the emulator from scratch each time to prevent
    #   restarting the emulator from a bad state.
    # -wipe-data: completely perform a factory reset to obliterate any PINs, apps, or settings.
    # -no-window: don't start a window for the emulator; this means we can't see
    #   or interact with the emulator, but that's fine for this use case.
    emulator_command = (
        f"{emulator_path} -avd {emulator_avd_name} -no-snapshot -wipe-data -no-window"
    )
    check_boot_completed_command = f"{get_adb_path()} shell getprop sys.boot_completed"

    print_and_log(
        log_file, f"Starting emulator ('{emulator_avd_name}') with wiped data..."
    )
    start_time = time.time()
    try:
        emulator_process = shell.run_command_async(
            emulator_command,
            log_path=f"/logs/artifacts/emulator_process_{emulator_avd_name}.log",
        )
        # Give the emulator a moment to start its process
        time.sleep(5)

        print_and_log(log_file, "Waiting for emulator to boot...")
        while time.time() - start_time < timeout_seconds:
            result = shell.run_command(check_boot_completed_command, silent=True)
            if "1" in result.stdout.strip():
                print_and_log(log_file, "Emulator fully booted and ready!")
                break

            time.sleep(5)
        else:
            print_and_log(log_file, "Emulator did not boot within the timeout period.")
            # Capture emulator diagnostics (logcat & screenshot) before aborting on boot timeout
            os.makedirs("/logs/artifacts", exist_ok=True)
            # Dump system logcat buffer
            shell.run_command(
                f"{get_adb_path()} logcat -d > /logs/artifacts/boot_hang_logcat_{emulator_avd_name}.txt",
                silent=True,
            )
            # Capture AVD framebuffer screenshot
            shell.run_command(
                f"{get_adb_path()} exec-out screencap -p > /logs/artifacts/boot_hang_screen_{emulator_avd_name}.png",
                silent=True,
            )
            raise EmulatorStartupTimeoutError(timeout_seconds)
    except EmulatorStartupTimeoutError as e:
        raise e
    except Exception as e:
        print_and_log(log_file, f"An error occurred during emulator startup: {e}")
        raise EmulatorFailedToStartError()

    return emulator_process


def update_local_properties(repo_dir: str, java_home: str) -> None:
    """Updates local properties files to help Gradle sync succeed.

    Args:
      repo_dir: The directory containing the cloned repository.
      java_home: The path to the Java home directory.
    """
    # Write java.home to .gradle/config.properties
    if java_home:
        os.environ["JAVA_HOME"] = java_home
        gradle_dir = os.path.join(repo_dir, ".gradle")
        os.makedirs(gradle_dir, exist_ok=True)

        config_properties_path = os.path.join(gradle_dir, CONFIG_PROPERTIES_FILE)
        try:
            os.remove(config_properties_path)
        except OSError:
            pass
        with open(config_properties_path, "w+") as f:
            f.write(f"\njava.home={java_home}\n")


def clone_and_initialize_project(
    project_dir: str,
    pull_request_example: eval_data_classes.PullRequestExample,
    commit_sha: str,
    execution_config: eval_data_classes.RepoExecutionConfig,
    jdks_configs: dict[str, str],
) -> bool:
    """Clones a repository and initializes the project."""

    if not os.path.exists(project_dir):
        os.makedirs(project_dir, exist_ok=True)
    if not os.path.exists(os.path.join(project_dir, ".git")):
        helpers.git_clone(pull_request_example.repo, project_dir)
    if not helpers.reset_to_commit(commit_sha, project_dir):
        return False

    java_version = _extract_java_version(project_dir, execution_config)
    if not java_version or (java_version not in jdks_configs.keys()):
        logging.error(f"{java_version} is not in the list of available JDK version!")
        return False

    update_local_properties(project_dir, jdks_configs[java_version])
    if execution_config.init_command:
        shell.run_command(command=execution_config.init_command, cwd=project_dir)
        pull_request_example.init_command = execution_config.init_command
    return True


def is_test_file(file_name: str) -> bool:
    """Returns true if the file name is a test file."""
    # Normalize path separators
    file_name = file_name.replace("\\", "/")

    # Check for excluded directories
    # Patterns: **/build/*, **/androidTest/*, **/androidTests/*, **/testFixtures/*, **/[tT]est/*, **/[tT]ests/*
    path_parts = file_name.split("/")
    excluded_dirs = {
        "build",
        "androidTest",
        "androidTests",
        "testFixtures",
        "test",
        "Test",
        "tests",
        "Tests",
    }

    # Check directories
    if any(part in excluded_dirs for part in path_parts[:-1]):
        return True

    # Check for filename patterns
    basename = path_parts[-1]

    # If no extension, we probably don't match the .* patterns which imply an extension exists
    if "." not in basename:
        return False

    # Split name and extension. We handle multiple dots by splitting on the last dot.
    # Logic: validation patterns imply [Name].extension
    name_part, _ = os.path.splitext(basename)

    # **/*Test.*, **/*Tests.*, **/test.*, **/tests.*
    if name_part.endswith(("Test", "Tests")) or name_part in ("test", "tests"):
        return True

    return False


def filter_test_file_diffs(patch_content: str) -> str:
    """Removes diff sections for test files from a patch string."""
    if not patch_content:
        return ""

    sections = re.split(r"(?=^diff --git )", patch_content, flags=re.MULTILINE)
    filtered_sections = []

    for section in sections:
        if not section.startswith("diff --git "):
            filtered_sections.append(section)
            continue

        header_line = section.split("\n", 1)[0]
        match = re.search(
            r"diff --git\s+(?:a/|\"a/)(.+?)\"?\s+(?:b/|\"b/)(.+?)\"?\s*$",
            header_line,
        )
        if match:
            path = match.group(2)
        else:
            parts = header_line.strip().split()
            target = parts[-1] if len(parts) >= 3 else ""
            path = (
                target[2:]
                if (target.startswith("b/") or target.startswith("a/"))
                else target
            )

        if not is_test_file(path):
            filtered_sections.append(section)

    return "".join(filtered_sections)


def _remove_empty_dirs(path: Path) -> None:
    """Recursively removes empty directories within the given path."""
    if not path.is_dir():
        return
    for child in path.iterdir():
        if child.is_dir():
            _remove_empty_dirs(child)
    try:
        if not any(path.iterdir()):
            path.rmdir()
    except OSError:
        pass


def _copy_tree_writable(src: Path, dst: Path, ignore_func=None) -> None:
    """
    Recursively copies a directory tree without preserving permissions/metadata.
    This ensures the destination is writable by the current user even if the
    source (e.g., from a Docker volume) is read-only or owned by root.
    """
    if src.is_dir():
        dst.mkdir(parents=True, exist_ok=True)

        # Get list of items, respecting the ignore function
        names = [item.name for item in src.iterdir()]
        if ignore_func:
            ignored_names = ignore_func(str(src), names)
            names = [n for n in names if n not in ignored_names]

        for name in names:
            _copy_tree_writable(src / name, dst / name, ignore_func)
    else:
        # shutil.copyfile copies the file content but NOT permissions or metadata
        shutil.copyfile(src, dst)


def copy_build_outputs(work_dir: Path, output_dir: Path) -> None:
    """
    Finds 'build/test-results/dropshots', 'build/paparazzi/failures',
    'build/outputs/roborazzi', and 'logcat-*.txt' files/directories within
    work_dir and copies them preserving the directory structure relative to work_dir.
    Ignores empty folders by not copying output directories that contain no files,
    and cleaning up any copied empty directory structures.
    """
    logging.info(f"Scanning for build contents in: {work_dir}")

    found_outputs = []
    for pattern in [
        "build/test-results/dropshots",
        "build/paparazzi/",
        "build/outputs/roborazzi",
        "logcat-*.txt",
    ]:
        found_outputs.extend(
            [p for p in work_dir.rglob(pattern) if p.is_dir() or p.is_file()]
        )

    if not found_outputs:
        logging.info("No build output directories or files found.")
        return

    logging.info(f"Found {len(found_outputs)} items. Copying to {output_dir}...")

    ignore_func = shutil.ignore_patterns(
        "apk",
        "aar",
        "code_coverage",
        "unit_test_coverage",
        "mapping.txt",
        "res",
        "intermediates",
        "metadata",
        "bundle",
        "tmp",
    )

    for source_path in found_outputs:
        try:
            rel_path = source_path.relative_to(work_dir)
            dest_path = output_dir / rel_path

            # Ensure destination parent exists
            dest_path.parent.mkdir(parents=True, exist_ok=True)

            if dest_path.exists():
                shutil.rmtree(dest_path)

            logging.info(f"Copying {source_path} -> {dest_path}")
            _copy_tree_writable(source_path, dest_path, ignore_func)

        except Exception as e:
            logging.error(f"Failed to copy {source_path}: {e}")

    # Clean up any empty directories that might have been copied
    if output_dir.exists():
        _remove_empty_dirs(output_dir)