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
« 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.
3Run this when ever options are changed::
5 python3 -m ase.cli.completion
6"""
8import sys
9from pathlib import Path
11# Path of the complete.py script:
12path = Path(__file__).with_name('complete.py')
15class CLICommand:
16 """Add tab-completion for Bash.
18 Will show the command that needs to be added to your '~/.bashrc file.
19 """
21 cmd = f'complete -o default -C "{sys.executable} {path}" ase'
23 @staticmethod
24 def add_arguments(parser):
25 pass
27 @staticmethod
28 def run(args):
29 cmd = CLICommand.cmd
30 print(cmd)
33def update(
34 path: Path, subcommands: list[tuple[str, str]], test: bool = False
35) -> None:
36 """Update commands dict in complete.py.
38 Use test=True to test that no changes are needed.
40 Refactor with care! This function is also used by GPAW.
41 """
43 from importlib import import_module
45 dct: dict[str, list[str]] = {}
47 class Subparser:
48 def __init__(self, command):
49 self.command = command
50 dct[command] = []
52 def add_argument(self, *args, **kwargs):
53 dct[command].extend(arg for arg in args if arg.startswith('-'))
55 def add_argument_group(self, name):
56 return self
58 def add_mutually_exclusive_group(self, required=False):
59 return self
61 for command, module_name in subcommands:
62 module = import_module(module_name)
63 module.CLICommand.add_arguments(Subparser(command))
65 tokens = ['commands = {\n']
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')
76 tokens.append('}\n')
78 txt = ''.join(tokens)
80 with path.open() as fd:
81 lines = fd.readlines()
83 a = lines.index('# Beginning of computer generated data:\n')
84 b = lines.index('# End of computer generated data\n')
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}')
102if __name__ == '__main__':
103 from ase.cli.main import commands
105 update(path, commands)