Unsparse images before generating OTA

Test: th
Bug: 283172692
Change-Id: Ie6d3dc704fd9a8c107e2888222e4c2bf804dad3e
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 06de622..7adc9fa 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -2782,6 +2782,8 @@
 
 def Cleanup():
   for i in OPTIONS.tempfiles:
+    if not os.path.exists(i):
+      continue
     if os.path.isdir(i):
       shutil.rmtree(i, ignore_errors=True)
     else:
@@ -4117,6 +4119,17 @@
     return fp.read(4) == b'\x3A\xFF\x26\xED'
 
 
+def UnsparseImage(filepath, target_path=None):
+  if not IsSparseImage(filepath):
+    return
+  if target_path is None:
+    tmp_img = MakeTempFile(suffix=".img")
+    RunAndCheckOutput(["simg2img", filepath, tmp_img])
+    os.rename(tmp_img, filepath)
+  else:
+    RunAndCheckOutput(["simg2img", filepath, target_path])
+
+
 def ParseUpdateEngineConfig(path: str):
   """Parse the update_engine config stored in file `path`
   Args