Skip to content

Commit 13d1293

Browse files
committed
ruff format
1 parent fd6ed57 commit 13d1293

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+2068
-1008
lines changed

SECI_Config_Analyser/Directory_Operations.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def __init__(self, search_path):
1717
"""
1818
create lists for filenames and initialise to empty lists
1919
call methods for reading directory contents and searching for config filenames
20-
:param search_path: the search path for files
20+
:param search_path: the search path for files
2121
"""
2222

2323
self.full_path = search_path
@@ -34,19 +34,16 @@ def _extract_config_filenames(self):
3434
"""
3535

3636
for filename in self.directory_contents:
37-
38-
if fnmatch(filename, '*.conf'):
39-
37+
if fnmatch(filename, "*.conf"):
4038
self.config_filenames.append(filename)
4139

42-
elif fnmatch(filename, '*.comp'):
43-
40+
elif fnmatch(filename, "*.comp"):
4441
self.comp_filenames.append(filename)
4542

4643
def _parse_vis_from_files(self, filenames):
4744
"""
4845
extracts VI names and paths from config files
49-
:param filenames: list of filenames to process
46+
:param filenames: list of filenames to process
5047
:return: vis_in_files: list of VIs with fullpaths
5148
"""
5249

@@ -70,7 +67,7 @@ def _parse_file(filename_and_path):
7067
vis_in_file = []
7168
tree = ET.parse(filename_and_path)
7269
root = tree.getroot()
73-
for child in root.iter('FilePath'):
70+
for child in root.iter("FilePath"):
7471
vi_path = ET.tostring(child, encoding=None, method="text")
7572
vis_in_file.append(vi_path.strip())
7673

@@ -91,8 +88,7 @@ def _remove_duplicates(input_list):
9188
encountered = set()
9289

9390
for item in input_list:
94-
95-
item = str(item, 'UTF-8')
91+
item = str(item, "UTF-8")
9692
if item not in encountered:
9793
output_list.append(item)
9894
encountered.add(item)

SECI_Config_Analyser/SECI_Config_Analyser.py

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -7,65 +7,67 @@
77

88
from Directory_Operations import ReadConfigFiles
99

10-
if __name__ == '__main__':
11-
10+
if __name__ == "__main__":
1211
parser = argparse.ArgumentParser(
13-
description='Analyse the SECI configuration files of specified instrument and output results to file')
12+
description="Analyse the SECI configuration files of specified instrument and output results to file"
13+
)
1414

15-
parser.add_argument('--instrument', '-i',
16-
type=str,
17-
default=None,
18-
help='instrument to be analysed')
15+
parser.add_argument(
16+
"--instrument", "-i", type=str, default=None, help="instrument to be analysed"
17+
)
1918

20-
parser.add_argument('--output_file', '-o',
21-
type=str,
22-
default=None,
23-
help='file to write the results to')
19+
parser.add_argument(
20+
"--output_file", "-o", type=str, default=None, help="file to write the results to"
21+
)
2422

25-
parser.add_argument('--adminaccount', '-a',
26-
type=str,
27-
default=None,
28-
help=r'admin account name (without host i.e. NOT \\NDXxxx\xxx, just xxx')
23+
parser.add_argument(
24+
"--adminaccount",
25+
"-a",
26+
type=str,
27+
default=None,
28+
help=r"admin account name (without host i.e. NOT \\NDXxxx\xxx, just xxx",
29+
)
2930

30-
parser.add_argument('--adminpassword', '-p',
31-
type=str,
32-
default=None,
33-
help='admin account password')
31+
parser.add_argument(
32+
"--adminpassword", "-p", type=str, default=None, help="admin account password"
33+
)
3434

3535
args = parser.parse_args()
3636

3737
if args.instrument is None:
3838
parser.print_help()
3939

4040
if args.output_file is None:
41-
args.output_file = f'{args.instrument.upper()}_-_VIs_from_SECI_configs.txt'
41+
args.output_file = f"{args.instrument.upper()}_-_VIs_from_SECI_configs.txt"
4242

4343
# open reference to appropriate network drive with supplied credentials
4444

45-
print('Connecting to remote directory...')
46-
system(f"net use \\\\ndx{args.instrument}\\c$ /user:ndx{args.instrument}\\{args.adminaccount} {args.adminpassword}")
45+
print("Connecting to remote directory...")
46+
system(
47+
f"net use \\\\ndx{args.instrument}\\c$ /user:ndx{args.instrument}\\{args.adminaccount} {args.adminpassword}"
48+
)
4749

4850
# create instance of 'ReadConfigFiles' as 'filelist' and supply directory to be read
4951

50-
print('Reading configuration files...')
51-
filelist = ReadConfigFiles(f"//ndx{args.instrument}/c$/Program Files (x86)/STFC ISIS Facility/SECI/Configurations/")
52+
print("Reading configuration files...")
53+
filelist = ReadConfigFiles(
54+
f"//ndx{args.instrument}/c$/Program Files (x86)/STFC ISIS Facility/SECI/Configurations/"
55+
)
5256

53-
print('Analysing files...')
57+
print("Analysing files...")
5458
xml_data = filelist.analyse_config_files()
5559

5660
# delete reference to network drive
5761

58-
print('Removing network connection...')
62+
print("Removing network connection...")
5963
system(f"net use \\\\ndx{args.instrument}\\c$ /delete")
6064

6165
# concatenate each element in list with newline character, then print whole string
6266

63-
print('Writing output file...')
64-
with open(args.output_file, 'w') as outputfile:
65-
67+
print("Writing output file...")
68+
with open(args.output_file, "w") as outputfile:
6669
outputfile.write(f"SECI configuration analysis for {args.instrument.upper()}:\n\n")
6770

6871
for item in xml_data:
69-
70-
outputfile.write('\n'.join(x for x in item))
72+
outputfile.write("\n".join(x for x in item))
7173
outputfile.write(f"\nNumber of VIs in configuration/component: {str(len(item))}\n\n")

build_tools/check_builds_are_recent.py

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,40 +6,53 @@
66

77
kits_root = r"\\isis\inst$\kits$\CompGroup\ICP"
88

9+
910
def format_build_num_with_dash(build_num):
1011
return f"BUILD-{build_num}"
1112

13+
1214
def get_latest_build(dir, directory_formatter) -> Union[None, str]:
1315
latest_build = None
1416
with open(os.path.join(dir, "LATEST_BUILD.txt")) as latest_build_file:
1517
latest_build = latest_build_file.readline().strip()
16-
latest_build_dir = os.path.join(dir, directory_formatter(latest_build)) if latest_build is not None else None
18+
latest_build_dir = (
19+
os.path.join(dir, directory_formatter(latest_build)) if latest_build is not None else None
20+
)
1721
return latest_build_dir
1822

23+
1924
def get_last_modified_datetime(dir):
2025
time_in_seconds_of_last_modification = os.path.getmtime(dir)
2126
datetime_of_last_modification = datetime.fromtimestamp(time_in_seconds_of_last_modification)
2227
return datetime_of_last_modification
2328

29+
2430
def get_formatted_last_modified_datetime(dir):
2531
last_modified_date = get_last_modified_datetime(dir)
2632
return last_modified_date.strftime("%d/%m/%Y, %H:%M:%S")
2733

34+
2835
def modified_in_last_x_days(dir, x_days):
2936
datetime_of_last_modification = get_last_modified_datetime(dir)
3037
datetime_now = datetime.now()
3138
timedelta_since_last_modification = datetime_now - datetime_of_last_modification
3239
return timedelta_since_last_modification.days < x_days
3340

41+
3442
def was_modified_recently(latest_build, num_days):
3543
last_modified_datetime = get_formatted_last_modified_datetime(latest_build)
3644
modified_recently = modified_in_last_x_days(latest_build, num_days)
3745
if modified_recently:
38-
print(f"SUCCESS: {latest_build} has been modified in the last {num_days} days. Last modified: {last_modified_datetime}")
46+
print(
47+
f"SUCCESS: {latest_build} has been modified in the last {num_days} days. Last modified: {last_modified_datetime}"
48+
)
3949
else:
40-
print(f"WARNING: {latest_build} modified longer than {num_days} ago. Last modified: {last_modified_datetime}")
50+
print(
51+
f"WARNING: {latest_build} modified longer than {num_days} ago. Last modified: {last_modified_datetime}"
52+
)
4153
return modified_recently
4254

55+
4356
def check_build_dir(build_dir, num_days, directory_formatter):
4457
latest_build = get_latest_build(build_dir, directory_formatter)
4558
modified_recently = False
@@ -49,33 +62,39 @@ def check_build_dir(build_dir, num_days, directory_formatter):
4962
modified_recently = was_modified_recently(latest_build, num_days)
5063
return modified_recently
5164

65+
5266
def check_build_dirs(build_dirs):
5367
build_dirs_not_modified_recently = []
5468
for build_dir in build_dirs:
5569
directory = build_dir[0]
5670
stale_days_limit = int(build_dir[1])
5771
directory_formatter = build_dir[2]
5872
build_dir_full_path = os.path.join(kits_root, directory)
59-
modified_recently = check_build_dir(build_dir_full_path, stale_days_limit, directory_formatter)
73+
modified_recently = check_build_dir(
74+
build_dir_full_path, stale_days_limit, directory_formatter
75+
)
6076
if not modified_recently:
6177
build_dirs_not_modified_recently.append(build_dir_full_path)
6278
return build_dirs_not_modified_recently
6379

80+
6481
if __name__ == "__main__":
6582
builds_to_check = os.getenv("BUILDS_TO_CHECK")
6683
if builds_to_check is None:
67-
print ("ERROR: BUILDS_TO_CHECK enviroment variable not set")
84+
print("ERROR: BUILDS_TO_CHECK enviroment variable not set")
6885
sys.exit(1)
6986
try:
7087
builds_by_stale_times = json.loads(builds_to_check)
7188
except ValueError as e:
72-
print(f"ERROR: parameter is not valid JSON.\nParameter:{builds_to_check}\nSpecific Error: {e.args}")
89+
print(
90+
f"ERROR: parameter is not valid JSON.\nParameter:{builds_to_check}\nSpecific Error: {e.args}"
91+
)
7392
sys.exit(1)
7493
build_dirs = []
7594
for time, builds_by_stale_time in builds_by_stale_times.items():
7695
for build in builds_by_stale_time:
7796
directory_formatter = format_build_num_with_dash
78-
build_dirs.append((build,time,directory_formatter))
97+
build_dirs.append((build, time, directory_formatter))
7998
build_dirs_not_modified_recently = check_build_dirs(build_dirs)
8099
if build_dirs_not_modified_recently:
81100
sys.exit(1)

build_tools/purge_archive.py

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ def delete_dir(directory):
3737
except Exception as e:
3838
print(f"Unable to delete directory {directory}: {e}")
3939

40+
4041
def delete_file(file):
4142
print(f"Deleting file: {file}")
4243
try:
@@ -46,7 +47,9 @@ def delete_file(file):
4647

4748

4849
def old_enough_to_delete(f):
49-
return datetime.now() - datetime.fromtimestamp(os.path.getmtime(f)) > timedelta(days=max_build_age_in_days)
50+
return datetime.now() - datetime.fromtimestamp(os.path.getmtime(f)) > timedelta(
51+
days=max_build_age_in_days
52+
)
5053

5154

5255
def is_build_dir(d):
@@ -57,35 +60,57 @@ def deletion_directories(project_areas):
5760
dirs = []
5861
for project_area in project_areas:
5962
project_dirs = [os.path.join(project_area, sub_dir) for sub_dir in os.listdir(project_area)]
60-
build_dirs_by_age = sorted(filter(is_build_dir, project_dirs), key=os.path.getmtime, reverse=True)
63+
build_dirs_by_age = sorted(
64+
filter(is_build_dir, project_dirs), key=os.path.getmtime, reverse=True
65+
)
6166
build_dirs_we_could_delete = build_dirs_by_age[minimum_number_of_builds_to_keep:]
6267
build_dirs_we_will_delete = filter(old_enough_to_delete, build_dirs_we_could_delete)
6368
dirs_to_add = list(build_dirs_we_will_delete)
6469
dirs += dirs_to_add
6570
print(f"Identifying {len(dirs_to_add)} old builds for deletion in: {project_area}")
6671
return dirs
6772

73+
6874
def deletion_files(project_areas, pattern):
6975
files = []
7076
for project_area in project_areas:
71-
files_by_age = sorted(glob.glob(os.path.join(project_area, pattern)), key=os.path.getmtime, reverse=True)
77+
files_by_age = sorted(
78+
glob.glob(os.path.join(project_area, pattern)), key=os.path.getmtime, reverse=True
79+
)
7280
files_we_could_delete = files_by_age[minimum_number_of_builds_to_keep:]
7381
files_we_will_delete = filter(old_enough_to_delete, files_we_could_delete)
7482
files_to_add = list(files_we_will_delete)
7583
files += files_to_add
76-
print(f"Identifying {len(files_to_add)} old {pattern} files for deletion in: {project_area}")
84+
print(
85+
f"Identifying {len(files_to_add)} old {pattern} files for deletion in: {project_area}"
86+
)
7787
return files
7888

7989

8090
def purge(dry_run=False):
8191
print("Beginning archive purge...")
82-
project_areas = [os.path.join(build_area, proj) for proj in ("Client_E4", "script_generator", "genie_python_3", "VHDS")] + \
83-
[os.path.join(build_area, "EPICS", proj) for proj in os.listdir(os.path.join(build_area, "EPICS"))
84-
if proj.startswith("EPICS")]
85-
project_areas.extend([os.path.join(build_area, "developer", "EPICS", proj) for proj in os.listdir(os.path.join(build_area, "developer", "EPICS"))
86-
if proj.startswith("windows")])
87-
project_areas.extend([os.path.join(build_area, "developer", "EPICS32", proj) for proj in os.listdir(os.path.join(build_area, "developer", "EPICS32"))
88-
if proj.startswith("win32")])
92+
project_areas = [
93+
os.path.join(build_area, proj)
94+
for proj in ("Client_E4", "script_generator", "genie_python_3", "VHDS")
95+
] + [
96+
os.path.join(build_area, "EPICS", proj)
97+
for proj in os.listdir(os.path.join(build_area, "EPICS"))
98+
if proj.startswith("EPICS")
99+
]
100+
project_areas.extend(
101+
[
102+
os.path.join(build_area, "developer", "EPICS", proj)
103+
for proj in os.listdir(os.path.join(build_area, "developer", "EPICS"))
104+
if proj.startswith("windows")
105+
]
106+
)
107+
project_areas.extend(
108+
[
109+
os.path.join(build_area, "developer", "EPICS32", proj)
110+
for proj in os.listdir(os.path.join(build_area, "developer", "EPICS32"))
111+
if proj.startswith("win32")
112+
]
113+
)
89114
for d in deletion_directories(project_areas):
90115
try:
91116
if dry_run:
@@ -97,7 +122,7 @@ def purge(dry_run=False):
97122
except BaseException as be:
98123
print(f"BaseException - unable to delete directory {d}: {be}")
99124
break
100-
for f in deletion_files(project_areas, 'ZBUILD-*.7z'):
125+
for f in deletion_files(project_areas, "ZBUILD-*.7z"):
101126
try:
102127
if dry_run:
103128
print(f"{f}")
@@ -110,4 +135,5 @@ def purge(dry_run=False):
110135
break
111136
print("Archive purge complete.")
112137

138+
113139
purge()

0 commit comments

Comments
 (0)