releasetools: common.UnzipTemp() filters out non-matching patterns.

common.UnzipTemp() calls `unzip` to do the unzipping, which will
complain if there's non-existent names in the given list. Prior to this
CL, callers had to do the work to remove non-existent entries. This CL
filters out the given patterns in common.UnzipTemp()/common.UnzipToDir()
to make callers' works easier.

Bug: 128848294
Test: `m dist` with aosp_taimen-userdebug (which calls
      ota_from_target_files.py on a target_files.zip that doesn't
      contain RADIO/*).
Test: `python -m unittest test_common.CommonZipTest`
Change-Id: I5e741c27ea8d0b8126c398a7e1b56a8deb4a3d7f
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 780b9c1..34c1359 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -17,6 +17,7 @@
 import collections
 import copy
 import errno
+import fnmatch
 import getopt
 import getpass
 import gzip
@@ -771,21 +772,29 @@
     shutil.copyfileobj(in_file, out_file)
 
 
-def UnzipToDir(filename, dirname, pattern=None):
+def UnzipToDir(filename, dirname, patterns=None):
   """Unzips the archive to the given directory.
 
   Args:
     filename: The name of the zip file to unzip.
-
     dirname: Where the unziped files will land.
-
-    pattern: Files to unzip from the archive. If omitted, will unzip the entire
-    archvie.
+    patterns: Files to unzip from the archive. If omitted, will unzip the entire
+        archvie. Non-matching patterns will be filtered out. If there's no match
+        after the filtering, no file will be unzipped.
   """
-
   cmd = ["unzip", "-o", "-q", filename, "-d", dirname]
-  if pattern is not None:
-    cmd.extend(pattern)
+  if patterns is not None:
+    # Filter out non-matching patterns. unzip will complain otherwise.
+    with zipfile.ZipFile(filename) as input_zip:
+      names = input_zip.namelist()
+    filtered = [
+        pattern for pattern in patterns if fnmatch.filter(names, pattern)]
+
+    # There isn't any matching files. Don't unzip anything.
+    if not filtered:
+      return
+    cmd.extend(filtered)
+
   RunAndCheckOutput(cmd)