blob: 21077be490ea55f2afb60b6327ac93b66757b2ed [file] [log] [blame]
Christoffer Quist Adamsen3f7e4282022-04-21 13:12:31 +02001#!/usr/bin/env python3
2# Copyright (c) 2022, the R8 project authors. Please see the AUTHORS file
3# for details. All rights reserved. Use of this source code is governed by a
4# BSD-style license that can be found in the LICENSE file.
5
Christoffer Quist Adamseneb29bfe2023-02-21 14:50:22 +01006import os
Christoffer Quist Adamsen0aaca162023-02-27 13:02:01 +01007import shutil
Christoffer Quist Adamseneb29bfe2023-02-21 14:50:22 +01008import subprocess
Christoffer Quist Adamsen3f7e4282022-04-21 13:12:31 +02009import zipfile
10
Christoffer Quist Adamsen0aaca162023-02-27 13:02:01 +010011import utils
12
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020013
Christoffer Quist Adamsen3f7e4282022-04-21 13:12:31 +020014def add_file_to_zip(file, destination, zip_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020015 with zipfile.ZipFile(zip_file, 'a') as zip:
16 zip.write(file, destination)
17
Christoffer Quist Adamsen4c6d15d2022-09-08 11:30:04 +020018
19def extract_all_that_matches(zip_file, destination, predicate):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020020 with zipfile.ZipFile(zip_file) as zip:
21 names_to_extract = [name for name in zip.namelist() if predicate(name)]
22 zip.extractall(path=destination, members=names_to_extract)
23 return names_to_extract
24
Christoffer Quist Adamsen4c6d15d2022-09-08 11:30:04 +020025
Christoffer Quist Adamsen0aaca162023-02-27 13:02:01 +010026def extract_member(zip_file, member, destination):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020027 with zipfile.ZipFile(zip_file) as zip:
28 with utils.TempDir() as temp:
29 zip.extract(member, path=temp)
30 shutil.move(os.path.join(temp, member), destination)
31
Christoffer Quist Adamsen0aaca162023-02-27 13:02:01 +010032
Christoffer Quist Adamsen4c6d15d2022-09-08 11:30:04 +020033def get_names_that_matches(zip_file, predicate):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020034 with zipfile.ZipFile(zip_file) as zip:
35 return [name for name in zip.namelist() if predicate(name)]
36
Christoffer Quist Adamseneb29bfe2023-02-21 14:50:22 +010037
38def remove_files_from_zip(files, zip_file):
Christoffer Quist Adamsen2434a4d2023-10-16 11:29:03 +020039 assert os.path.exists(zip_file)
40 cmd = ['zip', '-d', zip_file] + files
41 subprocess.run(cmd)