filter_process.py 4.9 KB
Newer Older
W
wenjun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys
import os
import shutil
from utils import read_json_file
from xml.etree.ElementTree import parse
from utils import remove_path


def is_opensource(bundle):
    """Get opensource infomation from bundle.json."""
    bundle_data = read_json_file(bundle)
    bundle_publish = bundle_data.get('publishAs')
    if not bundle_publish:
        raise Exception('Could not find "publishAs" in {}'.format(bundle))

    if bundle_publish == 'source':
        return True

    return False


def filter_out_code(code_path):
    if not os.path.exists(code_path):
        raise Exception('Could not find code path: {}'.format(code_path))
    shutil.rmtree(code_path)


def get_source_list(tag):
    if tag is None:
        return None

    source_list = []
    for source in tag.iterfind('project'):
        path = source.attrib['path']
        source_list.append(path)

    return source_list


def get_filter_list(xml):
    """Parse the config xml and get selected code path."""
    filter_xml = parse(xml)
    opensource_tag = filter_xml.find('opensource')
    non_opensource_tag = filter_xml.find('non_opensource')

    opensource_list = get_source_list(opensource_tag)
    non_opensource_list = get_source_list(non_opensource_tag)

    return opensource_list, non_opensource_list


def check_ignore(no_commit_msg):
    if no_commit_msg:
        ignore = shutil.ignore_patterns('.git', '.repo')
    else:
        ignore = None

    return ignore


def filter_by_bundle(config, path, no_commit_msg):
    """Filter out code by bundle.json in every code repository."""
    cwd_path = os.getcwd()
    ignore = check_ignore(no_commit_msg)
    shutil.copytree(cwd_path, path, symlinks=False, ignore=ignore)

    for relpath, dirs, files in os.walk(path):
        if config in files:
            full_path = os.path.join(path, relpath, config)
            bundle_path = os.path.normpath(os.path.abspath(full_path))
            if not is_opensource(bundle_path):
                code_path = os.path.join(path, relpath)
                filter_out_code(code_path)


def filter_by_path(config, path, no_commit_msg):
    """Filter out code by the config."""
    if not os.path.exists(config):
        raise Exception("Could not find config: {}".format(config))
    opensouce_list, non_opensource_list = get_filter_list(config)

    # remove target path if exsits
    remove_path(path)
    cwd_path = os.getcwd()
    ignore = check_ignore(no_commit_msg)

    # copy opensource code directly
    if opensouce_list:
        for each in opensouce_list:
            source_path = os.path.join(cwd_path, each)
            dst_path = os.path.join(path, each)
            if os.path.isfile(source_path):
                shutil.copy(source_path, dst_path)
            else:
                try:
                    shutil.copytree(source_path, dst_path, symlinks=False,
                                    ignore=ignore)
                except Exception as e:
                    print(e.args[0])

        if non_opensource_list:
            for source_code in non_opensource_list:
                source_path = os.path.join(path, source_code)
                if os.path.exists(source_path):
                    shutil.rmtree(source_path)
    # copy whole source code to target path and remove selected code in config
    elif non_opensource_list:
        shutil.copytree(cwd_path, path, symlinks=False, ignore=ignore)
        for source_code in non_opensource_list:
            source_path = os.path.join(path, source_code)
            if os.path.exists(source_path):
                shutil.rmtree(source_path)


def code_filter(**kwargs):
    """
    description: Filter out code by config or bundle.json
    param:
        callback_dict: building class, contains the path of config
        or bundle.json
        no_commit_msg: true if remove git message, like .git and .repo
        target_path: target code path after filtering out
    return: NA
    """
    callback_dict = kwargs['callback_dict']
    no_commit_msg = kwargs['no_commit_msg']
    target_path = kwargs['target_path']

    if callback_dict.config is None:
        target_config = 'bundle.json'
        filter_by_bundle(target_config, target_path, no_commit_msg)
    else:
        target_config = callback_dict.config
        filter_by_path(target_config, target_path, no_commit_msg)


if __name__ == "__main__":
    sys.exit(0)