FOSSology  4.5.1
Open Source License Compliance by Open Source Software
Utils.py
1 #!/usr/bin/env python3
2 
3 # SPDX-FileCopyrightText: © 2024 Rajul Jha <rajuljha49@gmail.com>
4 
5 # SPDX-License-Identifier: GPL-2.0-only
6 
7 import logging
8 import os
9 import re
10 import shutil
11 
12 
13 def validate_keyword_conf_file(file_path: str) -> tuple[bool, str]:
14  """
15  Validate whether input file in keyword.conf format or not
16  :param file_path: File path to validate
17  :return: tuple (bool, str) - True if file in correct format,
18  False otherwise, and a message.
19  """
20  keyword_search_pattern = re.compile(r'keyword=')
21  keyword_format_pattern = re.compile(r'__\w+__')
22 
23  try:
24  with open(file_path, 'r', encoding='utf-8') as file:
25  lines = file.readlines()
26  if not lines:
27  return False, "File is empty"
28 
29  non_commented_lines = []
30  for line in lines:
31  stripped_line = line.strip()
32  # Consider lines that are not empty and do not start with '#' as
33  # non-commented
34  if stripped_line and not stripped_line.startswith('#'):
35  non_commented_lines.append(stripped_line)
36 
37  if not non_commented_lines:
38  return False, "File has no keyword to search for"
39 
40  keyword_found = False
41  for line in non_commented_lines:
42  if not keyword_search_pattern.search(line):
43  continue
44  keyword_found = True
45  matches = re.findall(r'__.*?__', line)
46  for match in matches:
47  if not keyword_format_pattern.fullmatch(match):
48  return False, f"Invalid '__keyword__' format in line: {line}"
49 
50  if not keyword_found:
51  return False, "File must contain at least one 'keyword=' line"
52 
53  return True, "Valid keyword.conf file"
54 
55  except FileNotFoundError:
56  return False, "File not found"
57  except UnicodeDecodeError:
58  return False, "Error decoding file. Please ensure it's UTF-8 compatible."
59  except IOError as e:
60  return False, f"An I/O error occurred: {e}"
61  except Exception as e:
62  return False, str(e)
63 
64 
65 def copy_keyword_file_to_destination(
66  source_path: str, destination_path: str
67 ) -> None:
68  """
69  Make destination path and copy keyword file to destination
70  :param source_path: Source file path
71  :param destination_path: Destination file path
72  :return: None
73  """
74  try:
75  destination_dir = os.path.dirname(destination_path)
76  if destination_dir:
77  os.makedirs(destination_dir, exist_ok=True)
78 
79  shutil.copyfile(source_path, destination_path)
80  logging.info(f"Keyword configuration file copied to {destination_path}")
81 
82  except FileNotFoundError:
83  logging.error(f"Source file not found at {source_path}")
84  except (OSError, shutil.Error) as e:
85  logging.error(f"Unable to copy the file to {destination_path}: {e}")
86  except Exception as e:
87  logging.error(f"An unexpected error occurred while copying file: {e}")