Add a method for getting the root of a rule workspace to the Label method

This method is exposed to Skylark and will enable correct handling of protobuf skylark files.
See #784

--
MOS_MIGRATED_REVID=112235357
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 70b4183..eb4ec81 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
@@ -250,6 +250,20 @@
   public String getPackageName() {
     return packageIdentifier.getPackageFragment().getPathString();
   }
+  
+  /**
+   * Returns the execution root for the workspace, relative to the execroot (e.g., for label
+   * {@code @repo//pkg:b}, it will returns {@code external/repo/pkg} and for label {@code //pkg:a},
+   * it will returns an empty string.
+   */
+  @SkylarkCallable(name = "workspace_root", structField = true,
+      doc = "Returns the execution root for the workspace of this label, relative to the execroot. "
+      + "For instance:<br>"
+      + "<pre class=language-python>Label(\"@repo//pkg/foo:abc\").workspace_root =="
+      + " \"external/repo\"</pre>")
+  public String getWorkspaceRoot() {
+    return packageIdentifier.getRepository().getPathFragment().toString();
+  }
 
   /**
    * Returns the path fragment of the package in which this rule was declared (e.g. {@code
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 ec10104..1f3ce8b 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
@@ -353,4 +353,12 @@
           "invalid repository name 'foo': workspace names must start with '@'");
     }
   }
+  
+  @Test
+  public void testGetWorkspaceRoot() throws Exception {
+    Label label = Label.parseAbsolute("//bar/baz");
+    assertThat(label.getWorkspaceRoot()).isEmpty();
+    label = Label.parseAbsolute("@repo//bar/baz");
+    assertThat(label.getWorkspaceRoot()).isEqualTo("external/repo");
+  }
 }