1#!/usr/bin/env python3 2# 3# Copyright (C) 2022 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License.""" 16 17import difflib 18import pathlib 19from diffs.diff import Diff, ExtractInfo 20 21 22class ContextDiff(Diff): 23 def __init__(self, tool: ExtractInfo, tool_name: str): 24 self.tool = tool 25 self.tool_name = tool_name 26 27 def diff(self, left_path: pathlib.Path, right_path: pathlib.Path) -> list[str]: 28 errors = [] 29 30 left = self.tool(left_path) 31 right = self.tool(right_path) 32 comparator = difflib.context_diff(left, right) 33 difflines = list(comparator) 34 if difflines: 35 err = "\n".join(difflines) 36 errors.append( 37 f"{left_path}\ndiffers from\n{right_path}\nper {self.tool_name}:\n{err}") 38 return errors 39