1// Copyright 2019 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
18	"fmt"
19	"strings"
20)
21
22const targetFilesPattern = "*-target_files-*.zip"
23
24var targetZipPartitions = []string{
25	"BOOT/RAMDISK/",
26	"BOOT/",
27	"DATA/",
28	"ODM/",
29	"OEM/",
30	"PRODUCT/",
31	"SYSTEM_EXT/",
32	"ROOT/",
33	"SYSTEM/",
34	"SYSTEM_OTHER/",
35	"VENDOR/",
36}
37
38var targetZipFilter = []string{
39	"IMAGES/",
40	"OTA/",
41	"META/",
42	"PREBUILT_IMAGES/",
43	"RADIO/",
44}
45
46func filterTargetZipFiles(files []*ZipArtifactFile, artifact string, patterns []string) ([]*ZipArtifactFile, error) {
47	var ret []*ZipArtifactFile
48outer:
49	for _, f := range files {
50		if f.FileInfo().IsDir() {
51			continue
52		}
53
54		if artifact == targetFilesPattern {
55			found := false
56			for _, p := range targetZipPartitions {
57				if strings.HasPrefix(f.Name, p) {
58					f.Name = strings.ToLower(p) + strings.TrimPrefix(f.Name, p)
59					found = true
60				}
61			}
62			for _, filter := range targetZipFilter {
63				if strings.HasPrefix(f.Name, filter) {
64					continue outer
65				}
66			}
67
68			if !found {
69				return nil, fmt.Errorf("unmatched prefix for %s", f.Name)
70			}
71		}
72
73		if patterns != nil {
74			for _, pattern := range patterns {
75				match, _ := Match(pattern, f.Name)
76				if match {
77					ret = append(ret, f)
78				}
79			}
80		} else {
81			ret = append(ret, f)
82		}
83	}
84
85	return ret, nil
86}
87