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 os
8 import re
9 import shutil
10 
11 def validate_keyword_conf_file(file_path:str):
12  """
13  Validate whether input file in keyword.conf format or not
14  :param: file_path : str File path to validate
15  :return: bool True if file in correct format. Else False
16  :return: str Validation message(True)/Error message(False)
17  """
18  try:
19  with open(file_path, 'r') as file:
20  lines = file.readlines()
21  if not lines:
22  return False, "File is empty"
23  commented_lines = []
24  non_commented_lines = []
25  for line in lines:
26  stripped_line = line.strip()
27  if stripped_line.startswith('#') or not stripped_line:
28  commented_lines.append(stripped_line)
29  else:
30  non_commented_lines.append(stripped_line)
31 
32  if not non_commented_lines:
33  return False, "File has no keyword to search for"
34 
35  keyword_found = False
36  for line in non_commented_lines:
37  if not re.search(r'keyword=',line):
38  continue
39  keyword_found = True
40  matches = re.findall(r'__.*?__', line)
41  for match in matches:
42  if not re.match(r'__\w+__', match):
43  return False, f"Invalid '__keyword__' format in line: {line}"
44 
45  if not keyword_found:
46  return False, "File must contain at least one 'keyword=' line"
47 
48  return True, "Valid keyword.conf file"
49 
50  except FileNotFoundError:
51  return False, "File not found"
52  except Exception as e:
53  return False, str(e)
54 
55 def copy_keyword_file_to_destination(source_path:str, destination_path:str) -> None:
56  """
57  Make destination path and copy keyword file to destination
58  :param: source_path:str Source file path
59  :param: destination_path:str Destination file path
60  :return: None
61  """
62  try:
63  os.makedirs(os.path.dirname(destination_path),exist_ok=True)
64  shutil.copyfile(source_path,destination_path)
65  print(f"Keyword configuration file copied to {destination_path}")
66 
67  except Exception as e:
68  print(f"Unable to copy the file to {destination_path}: {e}")