Analyzer: Look for bazel BUILD file before .packages files

Also move local function packageRootedHere outside of a while loop.

Change-Id: Ie900a36507934038a7bace23e6241a9c91080943
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/178640
Commit-Queue: Samuel Rawlins <srawlins@google.com>
Reviewed-by: Konstantin Shcheglov <scheglov@google.com>
diff --git a/pkg/analyzer/lib/src/workspace/bazel.dart b/pkg/analyzer/lib/src/workspace/bazel.dart
index cb5b7cc..bb6aaed 100644
--- a/pkg/analyzer/lib/src/workspace/bazel.dart
+++ b/pkg/analyzer/lib/src/workspace/bazel.dart
@@ -467,6 +467,21 @@
       }
     }
 
+    // Return a Package rooted at [folder].
+    BazelWorkspacePackage packageRootedHere() {
+      List<String> uriParts = (packageUriResolver as BazelPackageUriResolver)
+          ._restoreUriParts(root, '${folder.path}/lib/__fake__.dart');
+      String packageName;
+      if (uriParts != null && uriParts.isNotEmpty) {
+        packageName = uriParts[0];
+      }
+      // TODO(srawlins): If [packageName] could not be derived from [uriParts],
+      //  I imagine this should throw.
+      var package = BazelWorkspacePackage(packageName, folder.path, this);
+      _directoryToPackage[directoryPath] = package;
+      return package;
+    }
+
     while (true) {
       Folder parent = folder.parent;
       if (parent == null) {
@@ -478,17 +493,9 @@
         return null;
       }
 
-      // Return a Package rooted at [folder].
-      BazelWorkspacePackage packageRootedHere() {
-        List<String> uriParts = (packageUriResolver as BazelPackageUriResolver)
-            ._restoreUriParts(root, '${folder.path}/lib/__fake__.dart');
-        String packageName;
-        if (uriParts != null && uriParts.isNotEmpty) {
-          packageName = uriParts[0];
-        }
-        var package = BazelWorkspacePackage(packageName, folder.path, this);
-        _directoryToPackage[directoryPath] = package;
-        return package;
+      if (folder.getChildAssumingFile(_buildFileName).exists) {
+        // Found the BUILD file, denoting a Dart package.
+        return packageRootedHere();
       }
 
       // In some distributed build environments, BUILD files are not preserved.
@@ -517,11 +524,6 @@
         }
       }
 
-      if (folder.getChildAssumingFile(_buildFileName).exists) {
-        // Found the BUILD file, denoting a Dart package.
-        return packageRootedHere();
-      }
-
       // Go up a folder.
       folder = parent;
     }