1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4#
5# Copyright (c) 2024 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19# Preprocess the input file, removing extraneous information, and generate an intermediate file
20import os
21import stat
22
23from src.keywords import keywords_dict, get_dict_value
24from src.utils.log_wrapper import log_info
25
26
27def handle_file_preprocess(input_file, output_file):
28    # Check if the file at the output file path exists, and if it does, delete it first.
29    if os.path.exists(output_file):
30        try:
31            os.remove(output_file)
32        except Exception as e:
33            print(f"delete {output_file} failed:{e}")
34
35    with open(input_file, 'r', encoding='utf-8') as infile:
36        flags = os.O_WRONLY | os.O_CREAT
37        mode = stat.S_IWUSR | stat.S_IRUSR
38        with os.fdopen(os.open(output_file, flags, mode), 'w') as outfile:
39            event_tree_dump_info_key = get_dict_value(keywords_dict, 'EventTreeDumpInfo')
40            for line in infile:
41                # find the EventTreeDumpInfo section position
42                index = line.find(event_tree_dump_info_key)
43                if index != -1:
44                    new_index = index + len(event_tree_dump_info_key)
45                    newline = line[new_index:]
46                    outfile.write(newline)
47                else:
48                    outfile.write(line)
49    log_info("preprocess done: " + input_file + "->" + output_file)
50