Coverage for ase/cli/main.py: 65.22%

69 statements  

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

1import argparse 

2import textwrap 

3from importlib import import_module 

4 

5from ase import __version__ 

6 

7 

8class CLIError(Exception): 

9 """Error for CLI commands. 

10 

11 A subcommand may raise this. The message will be forwarded to 

12 the error() method of the argument parser.""" 

13 

14 

15# Important: Following any change to command-line parameters, use 

16# python3 -m ase.cli.completion to update autocompletion. 

17commands = [ 

18 ('info', 'ase.cli.info'), 

19 # ('show', 'ase.cli.show'), 

20 ('test', 'ase.test'), 

21 ('gui', 'ase.gui.ag'), 

22 ('db', 'ase.cli.db'), 

23 ('run', 'ase.cli.run'), 

24 ('band-structure', 'ase.cli.band_structure'), 

25 ('build', 'ase.cli.build'), 

26 ('dimensionality', 'ase.cli.dimensionality'), 

27 ('eos', 'ase.eos'), 

28 ('ulm', 'ase.cli.ulm'), 

29 ('find', 'ase.cli.find'), 

30 ('nebplot', 'ase.cli.nebplot'), 

31 ('parallel', 'ase.cli.parallel'), 

32 ('convert', 'ase.cli.convert'), 

33 ('reciprocal', 'ase.cli.reciprocal'), 

34 ('completion', 'ase.cli.completion'), 

35 ('diff', 'ase.cli.diff'), 

36 ('exec', 'ase.cli.exec'), 

37] 

38 

39 

40def main( 

41 prog='ase', 

42 description='ASE command line tool.', 

43 version=__version__, 

44 commands=commands, 

45 hook=None, 

46 args=None, 

47): 

48 parser = argparse.ArgumentParser( 

49 prog=prog, description=description, formatter_class=Formatter 

50 ) 

51 parser.add_argument( 

52 '--version', action='version', version=f'%(prog)s-{version}' 

53 ) 

54 parser.add_argument('-T', '--traceback', action='store_true') 

55 subparsers = parser.add_subparsers(title='Sub-commands', dest='command') 

56 

57 subparser = subparsers.add_parser( 

58 'help', description='Help', help='Help for sub-command.' 

59 ) 

60 subparser.add_argument( 

61 'helpcommand', 

62 nargs='?', 

63 metavar='sub-command', 

64 help='Provide help for sub-command.', 

65 ) 

66 

67 functions = {} 

68 parsers = {} 

69 for command, module_name in commands: 

70 cmd = import_module(module_name).CLICommand 

71 docstring = cmd.__doc__ 

72 if docstring is None: 

73 # Backwards compatibility with GPAW 

74 short = cmd.short_description 

75 long = getattr(cmd, 'description', short) 

76 else: 

77 parts = docstring.split('\n', 1) 

78 if len(parts) == 1: 

79 short = docstring 

80 long = docstring 

81 else: 

82 short, body = parts 

83 long = short + '\n' + textwrap.dedent(body) 

84 subparser = subparsers.add_parser( 

85 command, formatter_class=Formatter, help=short, description=long 

86 ) 

87 cmd.add_arguments(subparser) 

88 functions[command] = cmd.run 

89 parsers[command] = subparser 

90 

91 if hook: 

92 args = hook(parser, args) 

93 else: 

94 args = parser.parse_args(args) 

95 

96 if args.command == 'help': 

97 if args.helpcommand is None: 

98 parser.print_help() 

99 else: 

100 parsers[args.helpcommand].print_help() 

101 elif args.command is None: 

102 parser.print_usage() 

103 else: 

104 f = functions[args.command] 

105 try: 

106 if f.__code__.co_argcount == 1: 

107 f(args) 

108 else: 

109 f(args, parsers[args.command]) 

110 except KeyboardInterrupt: 

111 pass 

112 except CLIError as x: 

113 parser.error(x) 

114 except Exception as x: 

115 if args.traceback: 

116 raise 

117 else: 

118 l1 = f'{x.__class__.__name__}: {x}\n' 

119 l2 = 'To get a full traceback, use: {} -T {} ...'.format( 

120 prog, args.command 

121 ) 

122 parser.error(l1 + l2) 

123 

124 

125class Formatter(argparse.HelpFormatter): 

126 """Improved help formatter.""" 

127 

128 def _fill_text(self, text, width, indent): 

129 assert indent == '' 

130 out = '' 

131 blocks = text.split('\n\n') 

132 for block in blocks: 

133 if block[0] == '*': 

134 # List items: 

135 for item in block[2:].split('\n* '): 

136 out += ( 

137 textwrap.fill( 

138 item, 

139 width=width - 2, 

140 initial_indent='* ', 

141 subsequent_indent=' ', 

142 ) 

143 + '\n' 

144 ) 

145 elif block[0] == ' ': 

146 # Indented literal block: 

147 out += block + '\n' 

148 else: 

149 # Block of text: 

150 out += textwrap.fill(block, width=width) + '\n' 

151 out += '\n' 

152 return out[:-1]