Remove most usages of PackageIdentifier#parse(String)

This parse method doesn't use repo mapping and can thus be potentially problematic. We should replace it with one that does respect repo mapping; that CL will follow this one.

The usages replaced in this CL are mostly :
1. Test usages, with something to the effect of `PackageIdentifier.parse("@//foo")`. These can simply be replaced with `PackageIdentifier.createInMainRepo("foo")`.
2. Certain prod usages where we construct a package identifier string from a RepositoryName object and a path segment. This can be done directly with `PackageIdentifier.create(repo, pkg)`, instead of `PackageIdentifier.parse(repo.toString() + "//" + pkg)`.
  - Most notably, this includes some changes in the TargetPattern / query logic that were using a similar idiom for labels (constructing a string and re-parsing it, instead of simply constructing from parts).

PiperOrigin-RevId: 446162604
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java b/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java
index 950f325..581a655 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/BuildView.java
@@ -198,7 +198,7 @@
       TargetPatternPhaseValue loadingResult,
       BuildOptions targetOptions,
       Set<String> multiCpu,
-      ImmutableSet<String> explicitTargetPatterns,
+      ImmutableSet<Label> explicitTargetPatterns,
       List<String> aspects,
       ImmutableMap<String, String> aspectsParameters,
       AnalysisOptions viewOptions,
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/constraints/TopLevelConstraintSemantics.java b/src/main/java/com/google/devtools/build/lib/analysis/constraints/TopLevelConstraintSemantics.java
index efdff8c..a28948c 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/constraints/TopLevelConstraintSemantics.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/constraints/TopLevelConstraintSemantics.java
@@ -123,7 +123,7 @@
    */
   public PlatformRestrictionsResult checkPlatformRestrictions(
       ImmutableSet<ConfiguredTarget> topLevelTargets,
-      ImmutableSet<String> explicitTargetPatterns,
+      ImmutableSet<Label> explicitTargetPatterns,
       boolean keepGoing)
       throws ViewCreationFailedException {
     ImmutableSet.Builder<ConfiguredTarget> incompatibleTargets = ImmutableSet.builder();
@@ -141,15 +141,14 @@
       // We need the label in unambiguous form here. I.e. with the "@" prefix for targets in the
       // main repository. explicitTargetPatterns is also already in the unambiguous form to make
       // comparison succeed regardless of the provided form.
-      String labelString = target.getLabel().getUnambiguousCanonicalForm();
-      if (explicitTargetPatterns.contains(labelString)) {
+      if (explicitTargetPatterns.contains(target.getLabel())) {
         if (!keepGoing) {
           // Use the slightly simpler form for printing error messages. I.e. no "@" prefix for
           // targets in the main repository.
           String targetIncompatibleMessage =
               String.format(
                   TARGET_INCOMPATIBLE_ERROR_TEMPLATE,
-                  target.getLabel().toString(),
+                  target.getLabel(),
                   // We need access to the provider so we pass in the underlying target here that is
                   // responsible for the incompatibility.
                   reportOnIncompatibility(result.underlyingTarget()));
@@ -161,7 +160,7 @@
                   .build());
         }
         this.eventHandler.handle(
-            Event.warn(String.format(TARGET_INCOMPATIBLE_ERROR_TEMPLATE, labelString, "")));
+            Event.warn(String.format(TARGET_INCOMPATIBLE_ERROR_TEMPLATE, target.getLabel(), "")));
         incompatibleButRequestedTargets.add(target);
       } else {
         // If this is not an explicitly requested target we can safely skip it.
diff --git a/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisAndExecutionPhaseRunner.java b/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisAndExecutionPhaseRunner.java
index ae4c415..5309790 100644
--- a/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisAndExecutionPhaseRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisAndExecutionPhaseRunner.java
@@ -25,6 +25,7 @@
 import com.google.devtools.build.lib.analysis.config.CoreOptions;
 import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
 import com.google.devtools.build.lib.buildtool.buildevent.NoAnalyzeEvent;
+import com.google.devtools.build.lib.cmdline.Label;
 import com.google.devtools.build.lib.cmdline.TargetParsingException;
 import com.google.devtools.build.lib.cmdline.TargetPattern;
 import com.google.devtools.build.lib.events.Event;
@@ -174,7 +175,7 @@
           BuildFailedException, TestExecException {
     env.getReporter().handle(Event.progress("Loading complete.  Analyzing..."));
 
-    ImmutableSet<String> explicitTargetPatterns =
+    ImmutableSet<Label> explicitTargetPatterns =
         getExplicitTargetPatterns(env, request.getTargets());
 
     BuildView view =
@@ -216,10 +217,10 @@
    *     stringified labels are in the "unambiguous canonical form".
    * @throws ViewCreationFailedException if a pattern fails to parse for some reason.
    */
-  private static ImmutableSet<String> getExplicitTargetPatterns(
+  private static ImmutableSet<Label> getExplicitTargetPatterns(
       CommandEnvironment env, List<String> requestedTargetPatterns)
       throws ViewCreationFailedException {
-    ImmutableSet.Builder<String> explicitTargetPatterns = ImmutableSet.builder();
+    ImmutableSet.Builder<Label> explicitTargetPatterns = ImmutableSet.builder();
     TargetPattern.Parser parser = TargetPattern.mainRepoParser(env.getRelativeWorkingDirectory());
 
     for (String requestedTargetPattern : requestedTargetPatterns) {
@@ -243,7 +244,7 @@
       }
 
       if (parsedPattern.getType() == TargetPattern.Type.SINGLE_TARGET) {
-        explicitTargetPatterns.add(parsedPattern.getSingleTargetPath());
+        explicitTargetPatterns.add(parsedPattern.getSingleTargetLabel());
       }
     }
 
diff --git a/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisPhaseRunner.java b/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisPhaseRunner.java
index f64c397..b74834c 100644
--- a/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisPhaseRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/buildtool/AnalysisPhaseRunner.java
@@ -205,7 +205,7 @@
     Stopwatch timer = Stopwatch.createStarted();
     env.getReporter().handle(Event.progress("Loading complete.  Analyzing..."));
 
-    ImmutableSet<String> explicitTargetPatterns =
+    ImmutableSet<Label> explicitTargetPatterns =
         getExplicitTargetPatterns(env, request.getTargets());
 
     BuildView view =
@@ -317,10 +317,10 @@
    *     stringified labels are in the "unambiguous canonical form".
    * @throws ViewCreationFailedException if a pattern fails to parse for some reason.
    */
-  private static ImmutableSet<String> getExplicitTargetPatterns(
+  private static ImmutableSet<Label> getExplicitTargetPatterns(
       CommandEnvironment env, List<String> requestedTargetPatterns)
       throws ViewCreationFailedException {
-    ImmutableSet.Builder<String> explicitTargetPatterns = ImmutableSet.builder();
+    ImmutableSet.Builder<Label> explicitTargetPatterns = ImmutableSet.builder();
     TargetPattern.Parser parser = TargetPattern.mainRepoParser(env.getRelativeWorkingDirectory());
 
     for (String requestedTargetPattern : requestedTargetPatterns) {
@@ -344,7 +344,7 @@
       }
 
       if (parsedPattern.getType() == TargetPattern.Type.SINGLE_TARGET) {
-        explicitTargetPatterns.add(parsedPattern.getSingleTargetPath());
+        explicitTargetPatterns.add(parsedPattern.getSingleTargetLabel());
       }
     }
 
diff --git a/src/main/java/com/google/devtools/build/lib/cmdline/Label.java b/src/main/java/com/google/devtools/build/lib/cmdline/Label.java
index b4d670c..6171b13 100644
--- a/src/main/java/com/google/devtools/build/lib/cmdline/Label.java
+++ b/src/main/java/com/google/devtools/build/lib/cmdline/Label.java
@@ -85,7 +85,7 @@
    * {@code [@repo]//foo/bar[:quux]}. If the {@code @repo} part is present, it must be a canonical
    * repo name, otherwise the label will be assumed to be in the main repo.
    */
-  private static Label parseCanonical(String raw) throws LabelSyntaxException {
+  static Label parseCanonical(String raw) throws LabelSyntaxException {
     Parts parts = Parts.parse(raw);
     parts.checkPkgIsAbsolute();
     RepositoryName repoName =
@@ -112,7 +112,7 @@
    * [@repo]//foo/bar[:quux]}. If the {@code @repo} part is present, it will undergo {@code
    * repoMapping}, otherwise the label will be assumed to be in {@code currentRepo}.
    */
-  private static Label parseWithRepoContext(
+  static Label parseWithRepoContext(
       String raw, RepositoryName currentRepo, RepositoryMapping repoMapping)
       throws LabelSyntaxException {
     Parts parts = Parts.parse(raw);
@@ -130,7 +130,7 @@
    * repoMapping}, otherwise the label will be assumed to be in the repo of {@code
    * packageIdentifier}.
    */
-  private static Label parseWithPackageContext(
+  static Label parseWithPackageContext(
       String raw, PackageIdentifier packageIdentifier, RepositoryMapping repoMapping)
       throws LabelSyntaxException {
     Parts parts = Parts.parse(raw);
diff --git a/src/main/java/com/google/devtools/build/lib/cmdline/TargetPattern.java b/src/main/java/com/google/devtools/build/lib/cmdline/TargetPattern.java
index e02aeee..e9a77a6 100644
--- a/src/main/java/com/google/devtools/build/lib/cmdline/TargetPattern.java
+++ b/src/main/java/com/google/devtools/build/lib/cmdline/TargetPattern.java
@@ -22,13 +22,10 @@
 import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.devtools.build.lib.cmdline.LabelValidator.BadLabelException;
-import com.google.devtools.build.lib.cmdline.LabelValidator.PackageAndTarget;
 import com.google.devtools.build.lib.io.InconsistentFilesystemException;
 import com.google.devtools.build.lib.io.ProcessPackageDirectoryException;
 import com.google.devtools.build.lib.server.FailureDetails.TargetPatterns;
@@ -226,8 +223,8 @@
     throw new IllegalStateException();
   }
 
-  /** For patterns of type {@link Type#SINGLE_TARGET}, returns the target path. */
-  public String getSingleTargetPath() {
+  /** For patterns of type {@link Type#SINGLE_TARGET}, returns the label to the target. */
+  public Label getSingleTargetLabel() {
     throw new IllegalStateException();
   }
 
@@ -261,13 +258,11 @@
 
   private static final class SingleTarget extends TargetPattern {
 
-    private final String targetName;
-    private final PackageIdentifier directory;
+    private final Label target;
 
-    private SingleTarget(String targetName, PackageIdentifier directory, String originalPattern) {
+    private SingleTarget(Label target, String originalPattern) {
       super(originalPattern);
-      this.targetName = Preconditions.checkNotNull(targetName);
-      this.directory = Preconditions.checkNotNull(directory);
+      this.target = Preconditions.checkNotNull(target);
     }
 
     @Override
@@ -278,17 +273,17 @@
         BatchCallback<T, E> callback,
         Class<E> exceptionClass)
         throws TargetParsingException, E, InterruptedException {
-      callback.process(resolver.getExplicitTarget(label(targetName)).getTargets());
+      callback.process(resolver.getExplicitTarget(target).getTargets());
     }
 
     @Override
     public PackageIdentifier getDirectory() {
-      return directory;
+      return target.getPackageIdentifier();
     }
 
     @Override
     public RepositoryName getRepository() {
-      return directory.getRepository();
+      return target.getRepository();
     }
 
     @Override
@@ -297,8 +292,8 @@
     }
 
     @Override
-    public String getSingleTargetPath() {
-      return targetName;
+    public Label getSingleTargetLabel() {
+      return target;
     }
 
     @Override
@@ -315,12 +310,12 @@
         return false;
       }
       SingleTarget that = (SingleTarget) o;
-      return targetName.equals(that.targetName) && directory.equals(that.directory);
+      return target.equals(that.target);
     }
 
     @Override
     public int hashCode() {
-      return Objects.hash(getType(), targetName, directory);
+      return Objects.hash(getType(), target);
     }
   }
 
@@ -340,22 +335,25 @@
         BatchCallback<T, E> callback,
         Class<E> exceptionClass)
         throws TargetParsingException, E, InterruptedException, InconsistentFilesystemException {
-      if (resolver.isPackage(PackageIdentifier.createInMainRepo(path))) {
+      PackageIdentifier pathAsPackage = PackageIdentifier.createInMainRepo(path);
+      if (resolver.isPackage(pathAsPackage)) {
         // User has specified a package name. lookout for default target.
-        callback.process(resolver.getExplicitTarget(label("//" + path)).getTargets());
+        callback.process(
+            resolver
+                .getExplicitTarget(
+                    label(pathAsPackage, pathAsPackage.getPackageFragment().getBaseName()))
+                .getTargets());
       } else {
         List<String> pieces = SLASH_SPLITTER.splitToList(path);
 
         // Interprets the label as a file target.  This loop stops as soon as the
         // first BUILD file is found (i.e. longest prefix match).
         for (int i = pieces.size() - 1; i >= 0; i--) {
-          String packageName = SLASH_JOINER.join(pieces.subList(0, i));
-          if (resolver.isPackage(PackageIdentifier.createInMainRepo(packageName))) {
+          PackageIdentifier pkg =
+              PackageIdentifier.createInMainRepo(SLASH_JOINER.join(pieces.subList(0, i)));
+          if (resolver.isPackage(pkg)) {
             String targetName = SLASH_JOINER.join(pieces.subList(i, pieces.size()));
-            callback.process(
-                resolver
-                    .getExplicitTarget(label("//" + packageName + ":" + targetName))
-                    .getTargets());
+            callback.process(resolver.getExplicitTarget(label(pkg, targetName)).getTargets());
             return;
           }
         }
@@ -962,15 +960,7 @@
 
       if (packagePart.endsWith("/...")) {
         String realPackagePart = packagePart.substring(0, packagePart.length() - "/...".length());
-        PackageIdentifier packageIdentifier;
-        try {
-          packageIdentifier =
-              PackageIdentifier.parse(repository.getNameWithAt() + "//" + realPackagePart);
-        } catch (LabelSyntaxException e) {
-          throw new TargetParsingException(
-              "Invalid package name '" + realPackagePart + "': " + e.getMessage(),
-              TargetPatterns.Code.LABEL_SYNTAX_ERROR);
-        }
+        PackageIdentifier packageIdentifier = createPackageIdentifier(repository, realPackagePart);
         if (targetPart.isEmpty() || ALL_RULES_IN_SUFFIXES.contains(targetPart)) {
           return new TargetsBelowDirectory(originalPattern, packageIdentifier, true);
         } else if (ALL_TARGETS_IN_SUFFIXES.contains(targetPart)) {
@@ -979,46 +969,35 @@
       }
 
       if (ALL_RULES_IN_SUFFIXES.contains(targetPart)) {
-        PackageIdentifier packageIdentifier;
-        try {
-          packageIdentifier =
-              PackageIdentifier.parse(repository.getNameWithAt() + "//" + packagePart);
-        } catch (LabelSyntaxException e) {
-          throw new TargetParsingException(
-              "Invalid package name '" + packagePart + "': " + e.getMessage(),
-              TargetPatterns.Code.LABEL_SYNTAX_ERROR);
-        }
         return new TargetsInPackage(
-            originalPattern, packageIdentifier, targetPart, wasOriginallyAbsolute, true, true);
+            originalPattern,
+            createPackageIdentifier(repository, packagePart),
+            targetPart,
+            wasOriginallyAbsolute,
+            true,
+            true);
       }
 
       if (ALL_TARGETS_IN_SUFFIXES.contains(targetPart)) {
-        PackageIdentifier packageIdentifier;
-        try {
-          packageIdentifier =
-              PackageIdentifier.parse(repository.getNameWithAt() + "//" + packagePart);
-        } catch (LabelSyntaxException e) {
-          throw new TargetParsingException(
-              "Invalid package name '" + packagePart + "': " + e.getMessage(),
-              TargetPatterns.Code.LABEL_SYNTAX_ERROR);
-        }
         return new TargetsInPackage(
-            originalPattern, packageIdentifier, targetPart, wasOriginallyAbsolute, false, true);
+            originalPattern,
+            createPackageIdentifier(repository, packagePart),
+            targetPart,
+            wasOriginallyAbsolute,
+            false,
+            true);
       }
 
       if (includesRepo || wasOriginallyAbsolute || pattern.contains(":")) {
-        PackageIdentifier packageIdentifier;
-        String fullLabel = repository.getNameWithAt() + "//" + pattern;
+        Label label;
         try {
-          PackageAndTarget packageAndTarget = LabelValidator.validateAbsoluteLabel(fullLabel);
-          packageIdentifier =
-              PackageIdentifier.create(
-                  repository, PathFragment.create(packageAndTarget.getPackageName()));
-        } catch (BadLabelException e) {
-          String error = "invalid target format '" + originalPattern + "': " + e.getMessage();
-          throw new TargetParsingException(error, TargetPatterns.Code.TARGET_FORMAT_INVALID);
+          label = Label.parseCanonical(repository.getNameWithAt() + "//" + pattern);
+        } catch (LabelSyntaxException e) {
+          throw new TargetParsingException(
+              "invalid target format '" + originalPattern + "': " + e.getMessage(),
+              TargetPatterns.Code.TARGET_FORMAT_INVALID);
         }
-        return new SingleTarget(fullLabel, packageIdentifier, originalPattern);
+        return new SingleTarget(label, originalPattern);
       }
 
       // This is a stripped-down version of interpretPathAsTarget that does no I/O.  We have a basic
@@ -1031,16 +1010,25 @@
       if (slashIndex > 0) {
         packageName = pattern.substring(0, slashIndex);
       }
-      try {
-        PackageIdentifier.parse("//" + packageName);
-      } catch (LabelSyntaxException e) {
+      String pkgError = LabelValidator.validatePackageName(packageName);
+      if (pkgError != null) {
         throw new TargetParsingException(
-            "Bad target pattern '" + originalPattern + "': " + e.getMessage(),
+            "Bad target pattern '" + originalPattern + "': " + pkgError,
             TargetPatterns.Code.LABEL_SYNTAX_ERROR);
       }
       return new InterpretPathAsTarget(pattern, originalPattern);
     }
 
+    private PackageIdentifier createPackageIdentifier(RepositoryName repoName, String pkg)
+        throws TargetParsingException {
+      String pkgError = LabelValidator.validatePackageName(pkg);
+      if (pkgError != null) {
+        throw new TargetParsingException(
+            "Invalid package name '" + pkg + "': " + pkgError, Code.LABEL_SYNTAX_ERROR);
+      }
+      return PackageIdentifier.create(repoName, PathFragment.create(pkg));
+    }
+
     /**
      * Parses a constant string TargetPattern, throwing IllegalStateException on invalid pattern.
      */
@@ -1077,15 +1065,15 @@
     }
   }
 
-  // Parse 'label' as a Label, mapping LabelSyntaxException into
-  // TargetParsingException.
-  private static Label label(String label) throws TargetParsingException {
+  // Creates a label from parts, mapping LabelSyntaxException into TargetParsingException.
+  private static Label label(PackageIdentifier pkg, String targetName)
+      throws TargetParsingException {
     try {
-      return Label.parseAbsolute(label, ImmutableMap.of());
+      return Label.create(pkg, targetName);
     } catch (LabelSyntaxException e) {
       throw new TargetParsingException(
-          "invalid target format: '"
-              + StringUtilities.sanitizeControlChars(label)
+          "invalid target name: '"
+              + StringUtilities.sanitizeControlChars(targetName)
               + "'; "
               + StringUtilities.sanitizeControlChars(e.getMessage()),
           TargetPatterns.Code.TARGET_FORMAT_INVALID);
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternValue.java b/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternValue.java
index eef2535..1ef1321 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternValue.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/TargetPatternValue.java
@@ -17,10 +17,8 @@
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.devtools.build.lib.cmdline.Label;
-import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
 import com.google.devtools.build.lib.cmdline.ResolvedTargets;
 import com.google.devtools.build.lib.cmdline.SignedTargetPattern;
 import com.google.devtools.build.lib.cmdline.SignedTargetPattern.Sign;
@@ -171,15 +169,7 @@
           }
         }
       } else if (excludeSingleTargets && laterParsedPattern.getType() == Type.SINGLE_TARGET) {
-        try {
-          Label label =
-              Label.parseAbsolute(
-                  laterParsedPattern.getSingleTargetPath(),
-                  /*repositoryMapping=*/ ImmutableMap.of());
-          excludedSingleTargetsBuilder.add(label);
-        } catch (LabelSyntaxException e) {
-          indicesOfNegativePatternsThatNeedToBeIncludedBuilder.add(j);
-        }
+        excludedSingleTargetsBuilder.add(laterParsedPattern.getSingleTargetLabel());
       } else {
         indicesOfNegativePatternsThatNeedToBeIncludedBuilder.add(j);
       }
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestCase.java b/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestCase.java
index 7b39dfb..31766a2 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/util/AnalysisTestCase.java
@@ -343,7 +343,7 @@
   protected AnalysisResult update(
       EventBus eventBus,
       FlagBuilder config,
-      ImmutableSet<String> explicitTargetPatterns,
+      ImmutableSet<Label> explicitTargetPatterns,
       ImmutableList<String> aspects,
       ImmutableMap<String, String> aspectsParameters,
       String... labels)
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java
index 34df45d..c3dd1c7 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/util/BuildViewForTesting.java
@@ -192,7 +192,7 @@
       TargetPatternPhaseValue loadingResult,
       BuildOptions targetOptions,
       Set<String> multiCpu,
-      ImmutableSet<String> explicitTargetPatterns,
+      ImmutableSet<Label> explicitTargetPatterns,
       List<String> aspects,
       ImmutableMap<String, String> aspectsParameters,
       AnalysisOptions viewOptions,
diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java
index 38a060c..c3568ba 100644
--- a/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/pkgcache/LoadingPhaseRunnerTest.java
@@ -1172,8 +1172,7 @@
   public void testPatternStartingWithDotDotSlash() {
     expectError(
         "../foo",
-        "Bad target pattern '../foo': invalid package name '..': package name component contains"
-            + " only '.' characters");
+        "Bad target pattern '../foo': package name component contains only '.' characters");
   }
 
   private void runTestPackageLoadingError(boolean keepGoing, String... patterns) throws Exception {
diff --git a/src/test/java/com/google/devtools/build/lib/query2/testutil/AbstractQueryTest.java b/src/test/java/com/google/devtools/build/lib/query2/testutil/AbstractQueryTest.java
index 6fcfefb..874b4e7 100644
--- a/src/test/java/com/google/devtools/build/lib/query2/testutil/AbstractQueryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/query2/testutil/AbstractQueryTest.java
@@ -79,6 +79,11 @@
 
   private static final String DEFAULT_UNIVERSE = "//...:*";
 
+  protected static final String BAD_PACKAGE_NAME =
+      "package names may contain "
+          + "A-Z, a-z, 0-9, or any of ' !\"#$%&'()*+,-./;<=>?[]^_`{|}~' "
+          + "(most 7-bit ascii characters except 0-31, 127, ':', or '\\')";
+
   protected MockToolsConfig mockToolsConfig;
   protected QueryHelper<T> helper;
   protected AnalysisMock analysisMock;
@@ -315,11 +320,7 @@
   protected final void checkResultofBadTargetLiterals(String message, FailureDetail failureDetail) {
     assertThat(failureDetail.getTargetPatterns().getCode())
         .isEqualTo(TargetPatterns.Code.LABEL_SYNTAX_ERROR);
-    // TODO(bazel-team): This error message could use some improvement. It's verbose (duplicate
-    //   message) and shows an extra "@" that wasn't in the input.
-    assertThat(message)
-        .isEqualTo(
-            "Invalid package name 'bad:*': invalid package identifier '@//bad:*': contains ':'");
+    assertThat(message).isEqualTo("Invalid package name 'bad:*': " + BAD_PACKAGE_NAME);
   }
 
   @Test
@@ -1358,7 +1359,7 @@
     writeFile("y/BUILD");
 
     eval("//x:*");
-    helper.assertPackageNotLoaded("@//y");
+    helper.assertPackageNotLoaded("y");
   }
 
   // #1352570, "NPE crash in deps(x, n)".
diff --git a/src/test/java/com/google/devtools/build/lib/query2/testutil/SkyframeQueryHelper.java b/src/test/java/com/google/devtools/build/lib/query2/testutil/SkyframeQueryHelper.java
index cfd4b76..df6b0fe 100644
--- a/src/test/java/com/google/devtools/build/lib/query2/testutil/SkyframeQueryHelper.java
+++ b/src/test/java/com/google/devtools/build/lib/query2/testutil/SkyframeQueryHelper.java
@@ -363,7 +363,7 @@
   @Override
   public void assertPackageNotLoaded(String packageName) throws Exception {
     MemoizingEvaluator evaluator = skyframeExecutor.getEvaluator();
-    SkyKey key = PackageValue.key(PackageIdentifier.parse(packageName));
+    SkyKey key = PackageValue.key(PackageIdentifier.createInMainRepo(packageName));
     if (evaluator.getExistingValue(key) != null
         || evaluator.getExistingErrorForTesting(key) != null) {
       throw new IllegalStateException("Package was loaded: " + packageName);
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/BzlCompileFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/BzlCompileFunctionTest.java
index 295ccc7..54ce1a8 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/BzlCompileFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/BzlCompileFunctionTest.java
@@ -88,7 +88,7 @@
     mockFS.throwIOExceptionFor = PathFragment.create("/workspace/foo/BUILD");
     invalidatePackages(/*alsoConfigs=*/ false); // We don't want to fail early on config creation.
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     EvaluationResult<PackageValue> result =
         SkyframeExecutorTestUtils.evaluate(
             getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter);
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java
index cc0741b..14e77c7 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java
@@ -195,7 +195,7 @@
   private Exception evaluatePackageToException(String pkg, boolean keepGoing) throws Exception {
     reporter.removeHandler(failFastHandler);
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse(pkg));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo(pkg));
     EvaluationResult<PackageValue> result =
         SkyframeExecutorTestUtils.evaluate(getSkyframeExecutor(), skyKey, keepGoing, reporter);
     assertThat(result.hasError()).isTrue();
@@ -205,7 +205,7 @@
   @Test
   public void testValidPackage() throws Exception {
     scratch.file("pkg/BUILD");
-    validPackageWithoutErrors(PackageValue.key(PackageIdentifier.parse("@//pkg")));
+    validPackageWithoutErrors(PackageValue.key(PackageIdentifier.createInMainRepo("pkg")));
   }
 
   @Test
@@ -227,7 +227,7 @@
 
     invalidatePackages();
 
-    Exception ex = evaluatePackageToException("@//pkg");
+    Exception ex = evaluatePackageToException("pkg");
     assertThat(ex).isInstanceOf(InvalidPackageException.class);
     assertThat(ex).hasMessageThat().contains("no such package 'pkg': no good");
     assertContainsEvent("warning event");
@@ -244,7 +244,7 @@
 
     SkyframeExecutorTestUtils.evaluate(
         getSkyframeExecutor(),
-        PackageValue.key(PackageIdentifier.parse("@//pkg")),
+        PackageValue.key(PackageIdentifier.createInMainRepo("pkg")),
         /*keepGoing=*/ false,
         reporter);
 
@@ -271,7 +271,7 @@
         .when(mockPackageValidator)
         .validate(any(Package.class), any(OptionalLong.class), any(ExtendedEventHandler.class));
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     EvaluationResult<PackageValue> result1 =
         SkyframeExecutorTestUtils.evaluate(
             getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter);
@@ -343,7 +343,7 @@
     SkyValue fooDirValue = FileStateValue.create(pkgRootedPath, SyscallCache.NO_CACHE, tsgm);
     differencer.inject(ImmutableMap.of(FileStateValue.key(pkgRootedPath), fooDirValue));
 
-    Exception ex = evaluatePackageToException("@//foo");
+    Exception ex = evaluatePackageToException("foo");
     String msg = ex.getMessage();
     assertThat(msg).contains("Inconsistent filesystem operations");
     assertThat(msg)
@@ -379,7 +379,7 @@
             DirectoryListingStateValue.create(
                 ImmutableList.of(new Dirent("baz", Dirent.Type.DIRECTORY)))));
 
-    Exception ex = evaluatePackageToException("@//foo");
+    Exception ex = evaluatePackageToException("foo");
     String msg = ex.getMessage();
     assertThat(msg).contains("Inconsistent filesystem operations");
     assertThat(msg).contains("/workspace/foo/bar/baz is no longer an existing directory");
@@ -401,7 +401,7 @@
 
     Exception ex =
         evaluatePackageToException(
-            "@//foo",
+            "foo",
             // Use --keep_going, not --nokeep_going, semantics so as to exercise the situation we
             // want to exercise.
             //
@@ -427,7 +427,7 @@
     scratch.file("foo/b.txt");
     scratch.file("foo/c/c.txt");
     preparePackageLoading(rootDirectory);
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     Package pkg = validPackageWithoutErrors(skyKey);
     assertThat((Iterable<Label>) pkg.getTarget("foo").getAssociatedRule().getAttr("srcs"))
         .containsExactly(
@@ -455,7 +455,7 @@
     scratch.file("foo/b.txt");
     scratch.file("foo/a.config");
     preparePackageLoading(rootDirectory);
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:b.txt");
     scratch.overwriteFile(
         "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.txt', '*.config']))");
@@ -498,7 +498,7 @@
     scratch.file("foo/BUILD", "filegroup(name = 'foo', srcs = glob(['*.txt']))");
     scratch.file("foo/@f.txt");
     preparePackageLoading(rootDirectory);
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:@f.txt");
 
     scratch.overwriteFile("foo/BUILD", "filegroup(name = 'foo', srcs = glob(['*.txt'])) # comment");
@@ -531,7 +531,7 @@
     FileSystemUtils.ensureSymbolicLink(
         scratch.resolve("foo/subdir_link"), externalTarget.getParentDirectory());
     preparePackageLoading(rootDirectory);
-    SkyKey fooKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey fooKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     Package fooPkg = validPackageWithoutErrors(fooKey);
     assertSrcs(fooPkg, "foo", "//foo:link.sh", "//foo:ordinary.sh");
     assertSrcs(fooPkg, "bar", "//foo:link.sh");
@@ -575,7 +575,7 @@
         "sh_library(name = 'foo', srcs = glob(['*.sh']))",
         "sh_library(name = 'bar', srcs = glob(['*.sh', '*.txt']))");
     preparePackageLoading(rootDirectory);
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     Package pkg = validPackageWithoutErrors(skyKey);
     scratch.file("foo/irrelevant");
     getSkyframeExecutor()
@@ -593,7 +593,7 @@
         "sh_library(name = 'foo', srcs = glob(['*.sh', '*.txt']))",
         "sh_library(name = 'bar', srcs = glob(['*.sh', '*.txt']))");
     preparePackageLoading(rootDirectory);
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     Package pkg = validPackageWithoutErrors(skyKey);
     scratch.file("foo/irrelevant");
     getSkyframeExecutor()
@@ -616,7 +616,7 @@
 
     preparePackageLoading(rootDirectory);
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     Package pkg = validPackageWithoutErrors(skyKey);
     assertThat(pkg.getStarlarkFileDependencies())
         .containsExactly(
@@ -642,7 +642,7 @@
     scratch.file("test/starlark/BUILD", "load('//test/starlark:bad_extension.bzl', 'some_symbol')");
     invalidatePackages();
 
-    Exception ex = evaluatePackageToException("@//test/starlark");
+    Exception ex = evaluatePackageToException("test/starlark");
     assertThat(ex)
         .hasMessageThat()
         .isEqualTo(
@@ -661,7 +661,7 @@
     scratch.file("test/starlark/BUILD", "load('//test/starlark:extension.bzl', 'a')");
     invalidatePackages();
 
-    Exception ex = evaluatePackageToException("@//test/starlark");
+    Exception ex = evaluatePackageToException("test/starlark");
     assertThat(ex)
         .hasMessageThat()
         .isEqualTo(
@@ -683,7 +683,7 @@
         "exported_to_java = {}");
     scratch.file("pkg/BUILD");
 
-    Exception ex = evaluatePackageToException("@//pkg");
+    Exception ex = evaluatePackageToException("pkg");
     assertThat(ex)
         .hasMessageThat()
         .isEqualTo(
@@ -701,7 +701,7 @@
     scratch.file("test/starlark/BUILD", "load('//test/starlark:extension.bzl', 'a')");
     invalidatePackages();
 
-    Exception ex = evaluatePackageToException("@//test/starlark");
+    Exception ex = evaluatePackageToException("test/starlark");
     assertThat(ex)
         .hasMessageThat()
         .isEqualTo(
@@ -719,7 +719,7 @@
     Path barBuildFile = scratch.file("foo/bar/BUILD");
     fs.stubStatError(barBuildFile, new IOException("nope"));
 
-    evaluatePackageToException("@//foo");
+    evaluatePackageToException("foo");
     assertContainsEvent("nope");
   }
 
@@ -735,7 +735,7 @@
         "load('subdir/a.bzl', 'c')",
         "load('//p:a.bzl', 'd')",
         "load('//p:subdir/a.bzl', 'e')");
-    validPackageWithoutErrors(PackageValue.key(PackageIdentifier.parse("@//p")));
+    validPackageWithoutErrors(PackageValue.key(PackageIdentifier.createInMainRepo("p")));
   }
 
   // See WorkspaceFileFunctionTest for tests that exercise load('@repo...').
@@ -744,7 +744,7 @@
   public void testLoadBadLabel() throws Exception {
     scratch.file("p/BUILD", "load('this\tis not a label', 'a')");
     reporter.removeHandler(failFastHandler);
-    SkyKey key = PackageValue.key(PackageIdentifier.parse("@//p"));
+    SkyKey key = PackageValue.key(PackageIdentifier.createInMainRepo("p"));
     SkyframeExecutorTestUtils.evaluate(skyframeExecutor, key, /*keepGoing=*/ false, reporter);
     assertContainsEvent(
         "in load statement: invalid target name 'this<?>is not a label': target names may not"
@@ -755,7 +755,7 @@
   public void testLoadFromExternalPackage() throws Exception {
     scratch.file("p/BUILD", "load('//external:file.bzl', 'a')");
     reporter.removeHandler(failFastHandler);
-    SkyKey key = PackageValue.key(PackageIdentifier.parse("@//p"));
+    SkyKey key = PackageValue.key(PackageIdentifier.createInMainRepo("p"));
     SkyframeExecutorTestUtils.evaluate(skyframeExecutor, key, /*keepGoing=*/ false, reporter);
     assertContainsEvent("Starlark files may not be loaded from the //external package");
   }
@@ -764,7 +764,7 @@
   public void testLoadWithoutBzlSuffix() throws Exception {
     scratch.file("p/BUILD", "load('//p:file.starlark', 'a')");
     reporter.removeHandler(failFastHandler);
-    SkyKey key = PackageValue.key(PackageIdentifier.parse("@//p"));
+    SkyKey key = PackageValue.key(PackageIdentifier.createInMainRepo("p"));
     SkyframeExecutorTestUtils.evaluate(skyframeExecutor, key, /*keepGoing=*/ false, reporter);
     assertContainsEvent("The label must reference a file with extension '.bzl'");
   }
@@ -800,7 +800,7 @@
 
     preparePackageLoading(rootDirectory);
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     Package pkg = validPackageWithoutErrors(skyKey);
     assertThat(pkg.containsErrors()).isFalse();
     assertThat(pkg.getTarget("existing.txt").getName()).isEqualTo("existing.txt");
@@ -851,7 +851,7 @@
 
     preparePackageLoading(rootDirectory);
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     Package pkg = validPackageWithoutErrors(skyKey);
     assertThat(pkg.containsErrors()).isFalse();
     assertThat(pkg.getTarget("bar-matched").getName()).isEqualTo("bar-matched");
@@ -879,7 +879,7 @@
     IOException exn = new IOException("nope");
     fs.throwExceptionOnGetInputStream(fooBuildFilePath, exn);
 
-    Exception ex = evaluatePackageToException("@//foo");
+    Exception ex = evaluatePackageToException("foo");
     assertThat(ex).hasMessageThat().contains("nope");
     assertThat(ex).isInstanceOf(NoSuchPackageException.class);
     assertThat(ex).hasCauseThat().isInstanceOf(IOException.class);
@@ -893,7 +893,7 @@
     IOException exn = new IOException("nope");
     fs.throwExceptionOnGetInputStream(fooBzlFilePath, exn);
 
-    Exception ex = evaluatePackageToException("@//foo");
+    Exception ex = evaluatePackageToException("foo");
     assertThat(ex).hasMessageThat().contains("nope");
     assertThat(ex).isInstanceOf(NoSuchPackageException.class);
     assertThat(ex).hasCauseThat().isInstanceOf(IOException.class);
@@ -909,7 +909,7 @@
     scratch.file("pkg/sub/BUILD");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     EvaluationResult<PackageValue> result =
         SkyframeExecutorTestUtils.evaluate(
             getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter);
@@ -926,7 +926,7 @@
     FileSystemUtils.ensureSymbolicLink(subBuildFilePath, subBuildFilePath);
     invalidatePackages();
 
-    Exception ex = evaluatePackageToException("@//pkg");
+    Exception ex = evaluatePackageToException("pkg");
     assertThat(ex).isInstanceOf(BuildFileNotFoundException.class);
     assertThat(ex)
         .hasMessageThat()
@@ -960,7 +960,7 @@
     // the non-Skyframe globbing error, but for the label crossing event to *not* get added (because
     // the globbing IOException would put Package.Builder in a state on which we cannot run
     // handleLabelsCrossingSubpackagesAndPropagateInconsistentFilesystemExceptions).
-    SkyKey pkgKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey pkgKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     EvaluationResult<PackageValue> result =
         SkyframeExecutorTestUtils.evaluate(
             getSkyframeExecutor(), pkgKey, /*keepGoing=*/ true, reporter);
@@ -984,7 +984,7 @@
     scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty = 5)");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     validPackage(skyKey);
 
     assertContainsEvent("expected boolean for argument `allow_empty`, got `5`");
@@ -995,7 +995,7 @@
     scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=True)");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     Package pkg = validPackage(skyKey);
     assertThat(pkg.containsErrors()).isFalse();
     assertNoEvents();
@@ -1011,7 +1011,7 @@
     scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'])");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     Package pkg = validPackage(skyKey);
     assertThat(pkg.containsErrors()).isFalse();
     assertNoEvents();
@@ -1023,7 +1023,7 @@
     scratch.file("pkg/blah.foo");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
 
     Package pkg = validPackage(skyKey);
     assertThat(pkg.containsErrors()).isFalse();
@@ -1055,7 +1055,7 @@
     scratch.file("pkg/blah.foo");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
 
     Package pkg = validPackage(skyKey);
     assertThat(pkg.containsErrors()).isFalse();
@@ -1081,7 +1081,7 @@
     scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=False)");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     reporter.removeHandler(failFastHandler);
 
     Package pkg = validPackage(skyKey);
@@ -1113,7 +1113,7 @@
     scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'])");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     reporter.removeHandler(failFastHandler);
 
     Package pkg = validPackage(skyKey);
@@ -1142,7 +1142,7 @@
     scratch.file("pkg/blah.foo");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     reporter.removeHandler(failFastHandler);
 
     Package pkg = validPackage(skyKey);
@@ -1178,7 +1178,7 @@
     scratch.file("pkg/blah.foo");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     reporter.removeHandler(failFastHandler);
 
     Package pkg = validPackage(skyKey);
@@ -1205,7 +1205,7 @@
     scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=False)");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
 
     reporter.removeHandler(failFastHandler);
     Package pkg = validPackage(skyKey);
@@ -1238,7 +1238,7 @@
     scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'])");
     invalidatePackages();
 
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
 
     reporter.removeHandler(failFastHandler);
     Package pkg = validPackage(skyKey);
@@ -1271,7 +1271,7 @@
 
     // load p
     preparePackageLoading(rootDirectory);
-    SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//p"));
+    SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("p"));
     Package p = validPackageWithoutErrors(skyKey);
 
     // Keys are load strings as they appear in the source (notice ":" in one of them).
@@ -1303,7 +1303,7 @@
 
     // Note: syntax error (recovered), non-existent .bzl file.
     scratch.file("pkg/BUILD", "load('//does_not:exist.bzl', 'broken'");
-    SkyKey key = PackageValue.key(PackageIdentifier.parse("@//pkg"));
+    SkyKey key = PackageValue.key(PackageIdentifier.createInMainRepo("pkg"));
     EvaluationResult<PackageValue> result =
         SkyframeExecutorTestUtils.evaluate(getSkyframeExecutor(), key, false, reporter);
     assertThatEvaluationResult(result).hasErrorEntryForKeyThat(key);
@@ -1328,7 +1328,7 @@
     assertThat(ioExnFromFS).hasMessageThat().contains("Too many levels of symbolic links");
 
     // Then, when we evaluate the PackageValue node for the Package in keepGoing mode,
-    SkyKey pkgKey = PackageValue.key(PackageIdentifier.parse("@//foo"));
+    SkyKey pkgKey = PackageValue.key(PackageIdentifier.createInMainRepo("foo"));
     EvaluationResult<PackageValue> result =
         SkyframeExecutorTestUtils.evaluate(
             getSkyframeExecutor(), pkgKey, /*keepGoing=*/ true, reporter);
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java
index 1feedf4..6c5a14e 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PrepareDepsOfPatternsFunctionSmartNegationTest.java
@@ -134,8 +134,10 @@
     WalkableGraph walkableGraph = getGraphFromPatternsEvaluation(patternSequence);
 
     // Then the graph contains package values for "@//foo" and "@//foo/foo",
-    assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo")), walkableGraph)).isTrue();
-    assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo/foo")), walkableGraph))
+    assertThat(exists(PackageValue.key(PackageIdentifier.createInMainRepo("foo")), walkableGraph))
+        .isTrue();
+    assertThat(
+            exists(PackageValue.key(PackageIdentifier.createInMainRepo("foo/foo")), walkableGraph))
         .isTrue();
 
     // But the graph does not contain a value for the target "@//foo/foo:foofoo".
@@ -175,10 +177,12 @@
     WalkableGraph walkableGraph = getGraphFromPatternsEvaluation(patternSequence);
 
     // Then the graph contains a package value for "@//foo",
-    assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo")), walkableGraph)).isTrue();
+    assertThat(exists(PackageValue.key(PackageIdentifier.createInMainRepo("foo")), walkableGraph))
+        .isTrue();
 
     // But no package value for "@//foo/foo",
-    assertThat(exists(PackageValue.key(PackageIdentifier.parse("@//foo/foo")), walkableGraph))
+    assertThat(
+            exists(PackageValue.key(PackageIdentifier.createInMainRepo("foo/foo")), walkableGraph))
         .isFalse();
 
     // And the graph does not contain a value for the target "@//foo/foo:foofoo".
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/StarlarkFileContentHashTests.java b/src/test/java/com/google/devtools/build/lib/skyframe/StarlarkFileContentHashTests.java
index 2d872f3..a842410 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/StarlarkFileContentHashTests.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/StarlarkFileContentHashTests.java
@@ -175,7 +175,7 @@
             ImmutableMap.<String, String>of(),
             new TimestampGranularityMonitor(BlazeClock.instance()));
     skyframeExecutor.setActionEnv(ImmutableMap.<String, String>of());
-    SkyKey pkgLookupKey = PackageValue.key(PackageIdentifier.parse("@//" + pkg));
+    SkyKey pkgLookupKey = PackageValue.key(PackageIdentifier.createInMainRepo(pkg));
     EvaluationResult<PackageValue> result =
         SkyframeExecutorTestUtils.evaluate(
             getSkyframeExecutor(), pkgLookupKey, /*keepGoing=*/ false, reporter);