Export the workspace name of a label to Starlark

In a world with external repositories, a label contains more information
that just "name" and "package", as the latter attribute only returns the
path to the corresponding package, relative to the root of the respective
repository. Therefore, also export the repository name to Starlark.

Fixes #6941.

Change-Id: I5cb39756673433f75838832799e1fc54b2041ade
PiperOrigin-RevId: 228309313
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 3f72641..454dfe8 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
@@ -447,6 +447,18 @@
         + name;
   }
 
+  /** Return the name of the repository label refers to without the leading `at` symbol. */
+  @SkylarkCallable(
+      name = "workspace_name",
+      structField = true,
+      doc =
+          "The repository part of this label. For isntance, "
+              + "<pre class=language-python>Label(\"@foo//bar:baz\").workspace_name"
+              + " == \"foo\"</pre>")
+  public String getWorkspaceName() {
+    return packageIdentifier.getRepository().strippedName();
+  }
+
   /**
    * Renders this label in canonical form, except with labels in the main and default repositories
    * conflated.
diff --git a/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java b/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java
index 6ea333f..ea74305 100644
--- a/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java
+++ b/src/test/java/com/google/devtools/build/lib/cmdline/LabelTest.java
@@ -481,4 +481,12 @@
     assertThat(Label.getContainingDirectory(Label.parseAbsoluteUnchecked("//a/b/c")))
         .isEqualTo(PathFragment.create("a/b/c"));
   }
+
+  @Test
+  public void testWorkspaceName() throws Exception {
+    assertThat(Label.parseAbsolute("@foo//bar:baz", ImmutableMap.of()).getWorkspaceName())
+        .isEqualTo("foo");
+    assertThat(Label.parseAbsolute("//bar:baz", ImmutableMap.of()).getWorkspaceName()).isEmpty();
+    assertThat(Label.parseAbsolute("@//bar:baz", ImmutableMap.of()).getWorkspaceName()).isEmpty();
+  }
 }