Coverage for apio/commands/apio_format.py: 77%

56 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-11-06 10:20 +0000

1# -*- coding: utf-8 -*- 

2# -- This file is part of the Apio project 

3# -- (C) 2016-2024 FPGAwars 

4# -- Authors 

5# -- * Jesús Arroyo (2016-2019) 

6# -- * Juan Gonzalez (obijuan) (2019-2024) 

7# -- License GPLv2 

8"""Implementation of 'apio format' command""" 

9 

10import sys 

11import os 

12from pathlib import Path 

13from glob import glob 

14from typing import Tuple, List, Optional 

15import click 

16from apio.common.apio_console import cout, cerror, cstyle 

17from apio.common.apio_styles import EMPH3, SUCCESS, INFO 

18from apio.common.common_util import PROJECT_BUILD_PATH, sort_files 

19from apio.apio_context import ( 

20 ApioContext, 

21 PackagesPolicy, 

22 ProjectPolicy, 

23 RemoteConfigPolicy, 

24) 

25from apio.commands import options 

26from apio.utils import util, cmd_util 

27 

28 

29# -------------- apio format 

30 

31# -- Text in the rich-text format of the python rich library. 

32APIO_FORMAT_HELP = """ 

33The command 'apio format' formats the project's source files to ensure \ 

34consistency and style without altering their semantics. The command accepts \ 

35the names of specific source files to format or formats all project source \ 

36files by default. 

37 

38Examples:[code] 

39 apio format # Format all source files. 

40 apio format -v # Same but with verbose output. 

41 apio format main.v main_tb.v # Format the two files.[/code] 

42 

43[NOTE] The file arguments are relative to the project directory, even if \ 

44the --project-dir option is used. 

45 

46The format command utilizes the format tool from the Verible project, which \ 

47can be configured by setting its flags in the apio.ini project file \ 

48For example: 

49 

50 

51[code]format-verible-options = 

52 --column_limit=80 

53 --indentation_spaces=4[/code] 

54 

55If needed, sections of source code can be protected from formatting using \ 

56Verible formatter directives: 

57 

58[code]// verilog_format: off 

59... untouched code ... 

60// verilog_format: on[/code] 

61 

62For a full list of Verible formatter flags, refer to the documentation page \ 

63online or use the command 'apio raw -- verible-verilog-format --helpfull'. 

64""" 

65 

66# -- File types that the format support. 'sv' indicates System Verilog 

67# -- and 'h' indicates an includes file. 

68_FILE_TYPES = [".v", ".sv", ".vh", ".svh"] 

69 

70 

71@click.command( 

72 name="format", 

73 cls=cmd_util.ApioCommand, 

74 short_help="Format verilog source files.", 

75 help=APIO_FORMAT_HELP, 

76) 

77@click.argument("files", nargs=-1, required=False) 

78@options.env_option_gen() 

79@options.project_dir_option 

80@options.verbose_option 

81def cli( 

82 # Arguments 

83 files: Tuple[str], 

84 env: Optional[str], 

85 project_dir: Optional[Path], 

86 verbose: bool, 

87): 

88 """Implements the format command which formats given or all source 

89 files to format. 

90 """ 

91 

92 # -- Create an apio context with a project object. 

93 apio_ctx = ApioContext( 

94 project_policy=ProjectPolicy.PROJECT_REQUIRED, 

95 remote_config_policy=RemoteConfigPolicy.CACHED_OK, 

96 packages_policy=PackagesPolicy.ENSURE_PACKAGES, 

97 project_dir_arg=project_dir, 

98 env_arg=env, 

99 ) 

100 

101 # -- Get the optional formatter options from apio.ini 

102 cmd_options = apio_ctx.project.get_list_option( 

103 "format-verible-options", default=[] 

104 ) 

105 

106 # -- Add verbose option if needed. 

107 if verbose and "--verbose" not in cmd_options: 107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true

108 cmd_options.append("--verbose") 

109 

110 # -- Prepare the packages for use. 

111 apio_ctx.set_env_for_packages(quiet=not verbose) 

112 

113 # -- Convert the tuple with file names into a list. 

114 files: List[str] = list(files) 

115 

116 # -- Change to the project's folder. 

117 os.chdir(apio_ctx.project_dir) 

118 

119 # -- If user didn't specify files to format, all all source files to 

120 # -- the list. 

121 if not files: 

122 for ext in _FILE_TYPES: 

123 files.extend(glob("**/*" + ext, recursive=True)) 

124 

125 # -- Filter out files that are under the _build directory. 

126 files = [f for f in files if PROJECT_BUILD_PATH not in Path(f).parents] 

127 

128 # -- Error if no file to format. 

129 if not files: 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true

130 cerror(f"No files of types {_FILE_TYPES}") 

131 sys.exit(1) 

132 

133 # -- Sort files, case insensitive. 

134 files = sort_files(files) 

135 

136 # -- Iterate the files and format one at a time. We could format 

137 # -- all of them at once but this way we can make the output more 

138 # -- user friendly. 

139 for f in files: 

140 # -- Convert to a Path object. 

141 path = Path(f) 

142 

143 # -- Check the file extension. 

144 _, ext = os.path.splitext(path) 

145 if ext not in _FILE_TYPES: 145 ↛ 146line 145 didn't jump to line 146 because the condition on line 145 was never true

146 cerror(f"'{f}' has an unexpected extension.") 

147 cout(f"Should be one of {_FILE_TYPES}", style=INFO) 

148 sys.exit(1) 

149 

150 # -- Check that the file exists and is a file. 

151 if not path.is_file(): 151 ↛ 152line 151 didn't jump to line 152 because the condition on line 151 was never true

152 cerror(f"'{f}' is not a file.") 

153 sys.exit(1) 

154 

155 # -- Print file name. 

156 styled_f = cstyle(f, style=EMPH3) 

157 cout(f"Formatting {styled_f}") 

158 

159 # -- Construct the formatter command line. 

160 command = ( 

161 "verible-verilog-format --nofailsafe_success --inplace " 

162 f' {" ".join(cmd_options)} "{f}"' 

163 ) 

164 if verbose: 164 ↛ 165line 164 didn't jump to line 165 because the condition on line 164 was never true

165 cout(command) 

166 

167 # -- Execute the formatter command line. 

168 exit_code = os.system(command) 

169 if exit_code != 0: 169 ↛ 170line 169 didn't jump to line 170 because the condition on line 169 was never true

170 cerror(f"Formatting of '{f}' failed") 

171 return exit_code 

172 

173 # -- All done ok. 

174 cout(f"Processed {util.plurality(files, 'file')}.", style=SUCCESS) 

175 sys.exit(0)