OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GHA] Copyright checker improvements (#34150)
Vladislav Golubevb4e48c80ae9e
diff --git a/.github/scripts/check_copyright.py b/.github/scripts/check_copyright.pyindex cdc78947512..dd9b6501f99 100644--- a/.github/scripts/check_copyright.py+++ b/.github/scripts/check_copyright.py@@ -7,7 +7,9 @@ Checks that source files have the correct copyright header.Handles C++ files (.cpp, .hpp, .h) and Python files (.py)."""+import difflibimport os+import reimport sysfrom datetime import datetimefrom pathlib import Path@@ -34,6 +36,31 @@ def is_supported_file_type(file_path: str) -> bool:return get_file_type_info(file_path) is not None+def get_encoding_line_number(file_path: str) -> int:+ """+ Detect encoding declaration in Python files.+ Returns the line number (0-indexed) if found, -1 otherwise.+ Encoding must be in the first or second line per PEP 263.+ """+ if not file_path.endswith('.py'):+ return -1++ encoding_pattern = r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)'++ try:+ with open(file_path, 'r', encoding='utf-8-sig', errors='ignore') as f:+ for i in range(2): # Check first two lines per PEP 263+ line = f.readline()+ if not line:+ break+ if re.match(encoding_pattern, line):+ return i+ except Exception:+ pass++ return -1++def get_expected_header(file_path: str) -> str:"""Get the expected copyright header for a file."""info = get_file_type_info(file_path)@@ -55,10 +82,18 @@ def should_check_file(file_path: str) -> bool:def get_file_header(file_path: str, num_lines: int = 3) -> str:- """Read the first few lines of a file, handling BOM if present."""+ """Read the first few lines of a file, handling BOM and encoding declaration if present."""try:with open(file_path, 'r', encoding='utf-8-sig', errors='ignore') as f:- return ''.join(f.readline() for _ in range(num_lines))+ all_lines = [f.readline() for _ in range(num_lines + 2)] # Read extra lines to account for encoding++ # For Python files, skip the encoding line when checking copyright+ encoding_line = get_encoding_line_number(file_path)+ if encoding_line >= 0:+ # Skip encoding line and return the copyright-relevant lines+ return ''.join(all_lines[encoding_line + 1:encoding_line + 1 + num_lines])++ return ''.join(all_lines[:num_lines])except Exception as e:print(f"Warning: Could not read {file_path}: {e}")return ""@@ -82,39 +117,54 @@ def generate_diff(file_path: str) -> str:"""Generate a unified diff for fixing the copyright header."""try:with open(file_path, 'r', encoding='utf-8-sig', errors='ignore') as f:- lines = f.read().split('\n')+ original_lines = f.readlines()except Exception as e:raise IOError(f"Could not read {file_path}: {e}")-+info = get_file_type_info(file_path)if not info:return ""-+comment_style, has_extra_line = infocurrent_year = datetime.now().year- has_copyright = any('Copyright' in line or 'SPDX-License-Identifier' in line- for line in lines[:5])-- diff_lines = [f"--- a/{file_path}", f"+++ b/{file_path}"]-++ encoding_line = get_encoding_line_number(file_path)+ header_start = encoding_line + 1 if encoding_line >= 0 else 0++ has_copyright = any('Copyright' in line or 'SPDX-License-Identifier' in line+ for line in original_lines[header_start:header_start + 5])++ correct_header = [+ f"{comment_style} Copyright (C) 2018-{current_year} Intel Corporation\n",+ f"{comment_style} SPDX-License-Identifier: Apache-2.0\n",+ ]+ if has_extra_line:+ correct_header.append(f"{comment_style}\n")+ correct_header.append("\n")++ corrected_lines = list(original_lines)if has_copyright:- # Wrong year - replace first line only- diff_lines.extend([- "@@ -1 +1 @@",- f"-{lines[0]}",- f"+{comment_style} Copyright (C) 2018-{current_year} Intel Corporation"- ])+ # Walk the actual contiguous comment block so we never overwrite lines beyond it.+ block_end = header_start+ while block_end < len(original_lines) and original_lines[block_end].startswith(comment_style):+ block_end += 1+ # Include the single trailing blank line that separates the header from code+ if block_end < len(original_lines) and original_lines[block_end].strip() == '':+ block_end += 1+ corrected_lines[header_start:block_end] = correct_headerelse:- # Missing copyright - insert at beginning- num_lines = 4 if has_extra_line else 3- diff_lines.append(f"@@ -0,0 +1,{num_lines} @@")- diff_lines.append(f"+{comment_style} Copyright (C) 2018-{current_year} Intel Corporation")- diff_lines.append(f"+{comment_style} SPDX-License-Identifier: Apache-2.0")- if has_extra_line:- diff_lines.append(f"+{comment_style}")- diff_lines.append("+")-- return '\n'.join(diff_lines) + '\n'+ # Insert the header at the right position (after encoding line if present)+ corrected_lines[header_start:header_start] = correct_header++ normalized_path = file_path.lstrip('/')+ diff = difflib.unified_diff(+ [l.rstrip('\n') for l in original_lines],+ [l.rstrip('\n') for l in corrected_lines],+ fromfile=f"a/{normalized_path}",+ tofile=f"b/{normalized_path}",+ lineterm='',+ )+ return '\n'.join(diff) + '\n'def main():diff --git a/.github/workflows/copyright_check.yml b/.github/workflows/copyright_check.ymlindex da419e44f56..47695e99f98 100644--- a/.github/workflows/copyright_check.yml+++ b/.github/workflows/copyright_check.yml@@ -48,9 +48,9 @@ jobs:echo "Found issues in the following files:"cat copyright_issues.txtecho ""- echo "### How to fix:"+ echo "### How to fix"echo ""- echo "**Option 1: Download and apply the patch**"+ echo "**Option 1: Download and apply the auto-generated patch**"echo "1. Go to the 'Summary' page of this workflow run"echo "2. Scroll down to the 'Artifacts' section"echo "3. Download the 'copyright-fixes' artifact"@@ -58,7 +58,30 @@ jobs:echo "5. Apply it: patch -p1 < copyright_fixes.diff"echo "6. Commit and push the changes"echo ""- echo "**Option 2: Review the diff below and apply manually**"+ echo "> **Note:** the patch is generated automatically and may be incorrect in"+ echo "> edge cases (e.g. when the file has an unusual structure at the top)."+ echo "> If the patch does not apply cleanly or produces unexpected results,"+ echo "> please proceed with Option 2."+ echo ""+ echo "**Option 2: Fix manually using the reference headers**"+ echo ""+ echo "Align the top of each affected file with the reference header below."+ echo ""+ echo "**Python (.py):**"+ echo "\`\`\`"+ echo "# Copyright (C) 2018-$(date +%Y) Intel Corporation"+ echo "# SPDX-License-Identifier: Apache-2.0"+ echo ""+ echo "\`\`\`"+ echo "**C++ (.cpp / .hpp / .h):**"+ echo "\`\`\`"+ echo "// Copyright (C) 2018-$(date +%Y) Intel Corporation"+ echo "// SPDX-License-Identifier: Apache-2.0"+ echo "//"+ echo ""+ echo "\`\`\`"+ echo ""+ echo "**Diff for reference:**"echo ""cat copyright_fixes.diffecho ""