MCPcopy
hub / github.com/huggingface/transformers / check_codes_match

Function check_codes_match

utils/check_copies.py:594–642  ·  view source on GitHub ↗

Checks if two version of a code match with the exception of the class/function name. Args: observed_code (`str`): The code found. theoretical_code (`str`): The code to match. Returns: `Optional[int]`: The index of the first line where there is a difference (if

(observed_code: str, theoretical_code: str)

Source from the content-addressed store, hash-verified

592
593
594def check_codes_match(observed_code: str, theoretical_code: str) -> int | None:
595 """
596 Checks if two version of a code match with the exception of the class/function name.
597
598 Args:
599 observed_code (`str`): The code found.
600 theoretical_code (`str`): The code to match.
601
602 Returns:
603 `Optional[int]`: The index of the first line where there is a difference (if any) and `None` if the codes
604 match.
605 """
606 observed_code_header = observed_code.split("\n")[0]
607 theoretical_code_header = theoretical_code.split("\n")[0]
608
609 # Catch the function/class name: it is expected that those do not match.
610 _re_class_match = re.compile(r"class\s+([^\(:]+)(?:\(|:)")
611 _re_func_match = re.compile(r"def\s+([^\(]+)\(")
612 for re_pattern in [_re_class_match, _re_func_match]:
613 if re_pattern.match(observed_code_header) is not None:
614 try:
615 observed_obj_name = re_pattern.search(observed_code_header).groups()[0]
616 except Exception:
617 raise ValueError(
618 "Tried to split a class or function. It did not work. Error comes from: \n```\n"
619 + observed_code_header
620 + "\n```\n"
621 )
622
623 try:
624 theoretical_name = re_pattern.search(theoretical_code_header).groups()[0]
625 except Exception:
626 raise ValueError(
627 "Tried to split a class or function. It did not work. Error comes from: \n```\n"
628 + theoretical_code_header
629 + "\n```\n"
630 )
631 theoretical_code_header = theoretical_code_header.replace(theoretical_name, observed_obj_name)
632
633 # Find the first diff. Line 0 is special since we need to compare with the function/class names ignored.
634 diff_index = 0
635 if theoretical_code_header != observed_code_header:
636 return 0
637
638 diff_index = 1
639 for observed_line, theoretical_line in zip(observed_code.split("\n")[1:], theoretical_code.split("\n")[1:]):
640 if observed_line != theoretical_line:
641 return diff_index
642 diff_index += 1
643
644
645def is_copy_consistent(

Callers 1

is_copy_consistentFunction · 0.85

Calls 1

splitMethod · 0.80

Tested by

no test coverage detected