Allow pkg_tar's strip_prefix to work on directory output target names.

For build targets that yield a directory output, it is sometimes of
interest to turn them into tarballs, Docker images, etc., that contain
the directory output directly, without having any name prefix to it.

This currently breaks, because setting strip_prefix to the same name as
the directory itself causes build_tar.py to use an empty filename. There
is a check in the code to remove leading slashes, which breaks on empty
strings.

Closes #6980.

PiperOrigin-RevId: 228158067
diff --git a/src/test/shell/bazel/bazel_embedded_skylark_test.sh b/src/test/shell/bazel/bazel_embedded_skylark_test.sh
index 1e0733b..e7b9952 100755
--- a/src/test/shell/bazel/bazel_embedded_skylark_test.sh
+++ b/src/test/shell/bazel/bazel_embedded_skylark_test.sh
@@ -75,6 +75,53 @@
       || fail "symlink not packed"
 }
 
+test_pkg_tar_strip_directory() {
+  # Verify that pkg_tar's strip_prefix permits stripping off the name of
+  # directory output targets.
+  rm -rf main out
+  mkdir main
+  cd main
+  touch WORKSPACE
+  cat > BUILD <<'EOF'
+load(":apple.bzl", "create_banana_directory")
+
+create_banana_directory(
+    name = "banana_directory",
+)
+
+load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
+
+pkg_tar(
+    name = "banana_tarball",
+    srcs = [":banana_directory"],
+    strip_prefix = "banana",
+)
+EOF
+  cat > apple.bzl <<'EOF'
+def _create_banana_directory_impl(ctx):
+    out = ctx.actions.declare_directory("banana")
+    ctx.actions.run(
+        executable = "bash",
+        arguments = ["-c", "mkdir -p %s/pear && touch %s/pear/grape" % (out.path, out.path)],
+        outputs = [out],
+    )
+    return [
+        DefaultInfo(
+            files = depset([out]),
+        ),
+    ]
+
+create_banana_directory = rule(
+    implementation = _create_banana_directory_impl,
+)
+EOF
+  bazel build --all_incompatible_changes :banana_tarball || fail "Expected success"
+  mkdir ../out
+  tar -C ../out -x -v -f `bazel info bazel-bin`/banana_tarball.tar
+
+  test -f ../out/pear/grape || fail "expected file to be present"
+}
+
 test_http_archive() {
   mkdir ext
   cat > ext/foo.sh <<'EOF'
diff --git a/tools/build_defs/pkg/build_tar.py b/tools/build_defs/pkg/build_tar.py
index cba974c..d73087d 100644
--- a/tools/build_defs/pkg/build_tar.py
+++ b/tools/build_defs/pkg/build_tar.py
@@ -329,7 +329,7 @@
                FLAGS.root_directory) as output:
 
     def file_attributes(filename):
-      if filename[0] == '/':
+      if filename.startswith('/'):
         filename = filename[1:]
       return {
           'mode': mode_map.get(filename, default_mode),