Coverage for src/shephex/executor/slurm/slurm_profile.py: 86%

44 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-06-20 14:58 +0200

1import json 

2import shutil 

3from pathlib import Path 

4 

5 

6class SlurmProfileManager: 

7 

8 def __init__(self) -> None: 

9 self.settings_directory = Path.home() / '.shephex/' 

10 self.settings_directory.mkdir(exist_ok=True) 

11 self.settings_path = self.settings_directory / 'slurm_profile_manager.json' 

12 

13 self.settings = self.load_settings() 

14 self.profile_directory = Path(self.settings['profile_directory']) 

15 self.profile_directory.mkdir(exist_ok=True) 

16 

17 def load_settings(self) -> dict: 

18 if self.settings_path.exists(): 

19 with open(self.settings_path) as f: 

20 settings = json.load(f) 

21 else: 

22 settings = {"profile_directory": str(self.settings_directory / 'slurm_profiles')} 

23 with open(self.settings_path, 'w') as f: 

24 json.dump(settings, f, indent=4) 

25 

26 return settings 

27 

28 def get_profile_directory(self) -> Path: 

29 return self.profile_directory 

30 

31 def get_all_profiles(self) -> list[Path]: 

32 return list(self.profile_directory.glob('*.json')) 

33 

34 def get_profile_path(self, name: str) -> Path: 

35 if not name.endswith('.json'): 

36 name = name + '.json' 

37 

38 path = self.profile_directory / name 

39 if not path.exists(): 

40 raise FileNotFoundError(f'Profile {name} not found in {self.profile_directory}') 

41 

42 return path 

43 

44 def get_profile(self, name: str) -> dict: 

45 path = self.get_profile_path(name) 

46 with open(path) as f: 

47 return json.load(f) 

48 

49 def add_profile(self, file: Path, name: str, overwrite: bool) -> None: 

50 directory = self.get_profile_directory() 

51 

52 if not file.suffix == '.json': 

53 raise ValueError('Profile file must be a json file.') 

54 

55 if name is None: 

56 name = Path(file).stem 

57 

58 new_path = (directory / name).with_suffix('.json') 

59 

60 if new_path.exists() and not overwrite: 

61 raise FileExistsError(f'Profile {name} already exists in {directory}') 

62 else: 

63 shutil.copy(file, new_path)