Coverage for ase/cli/completion.py: 78.85%

52 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""TAB-completion sub-command and update helper funtion. 

2 

3Run this when ever options are changed:: 

4 

5 python3 -m ase.cli.completion 

6""" 

7 

8import sys 

9from pathlib import Path 

10 

11# Path of the complete.py script: 

12path = Path(__file__).with_name('complete.py') 

13 

14 

15class CLICommand: 

16 """Add tab-completion for Bash. 

17 

18 Will show the command that needs to be added to your '~/.bashrc file. 

19 """ 

20 

21 cmd = f'complete -o default -C "{sys.executable} {path}" ase' 

22 

23 @staticmethod 

24 def add_arguments(parser): 

25 pass 

26 

27 @staticmethod 

28 def run(args): 

29 cmd = CLICommand.cmd 

30 print(cmd) 

31 

32 

33def update( 

34 path: Path, subcommands: list[tuple[str, str]], test: bool = False 

35) -> None: 

36 """Update commands dict in complete.py. 

37 

38 Use test=True to test that no changes are needed. 

39 

40 Refactor with care! This function is also used by GPAW. 

41 """ 

42 

43 from importlib import import_module 

44 

45 dct: dict[str, list[str]] = {} 

46 

47 class Subparser: 

48 def __init__(self, command): 

49 self.command = command 

50 dct[command] = [] 

51 

52 def add_argument(self, *args, **kwargs): 

53 dct[command].extend(arg for arg in args if arg.startswith('-')) 

54 

55 def add_argument_group(self, name): 

56 return self 

57 

58 def add_mutually_exclusive_group(self, required=False): 

59 return self 

60 

61 for command, module_name in subcommands: 

62 module = import_module(module_name) 

63 module.CLICommand.add_arguments(Subparser(command)) 

64 

65 tokens = ['commands = {\n'] 

66 

67 for command, opts in sorted(dct.items()): 

68 tokens.append(f" '{command}': [") 

69 if opts: 

70 tokens.append('\n') 

71 tokens += [f" '{opt}',\n" for opt in opts] 

72 tokens.append(' ],\n') 

73 else: 

74 tokens.append('],\n') 

75 

76 tokens.append('}\n') 

77 

78 txt = ''.join(tokens) 

79 

80 with path.open() as fd: 

81 lines = fd.readlines() 

82 

83 a = lines.index('# Beginning of computer generated data:\n') 

84 b = lines.index('# End of computer generated data\n') 

85 

86 if test: 

87 if ''.join(lines[a + 1 : b]) != txt: 

88 raise ValueError( 

89 'Please update ase/cli/complete.py using ' 

90 '"python3 -m ase.cli.completion".' 

91 ) 

92 else: 

93 lines[a + 1 : b] = [txt] 

94 new = path.with_name('complete.py.new') 

95 with new.open('w') as fd: 

96 print(''.join(lines), end='', file=fd) 

97 new.rename(path) 

98 path.chmod(0o775) 

99 print(f'Updated {path}') 

100 

101 

102if __name__ == '__main__': 

103 from ase.cli.main import commands 

104 

105 update(path, commands)