idf-build-apps 2.4.3__py3-none-any.whl → 2.5.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
idf_build_apps/main.py CHANGED
@@ -7,11 +7,10 @@ import argparse
7
7
  import json
8
8
  import logging
9
9
  import os
10
- import re
11
10
  import sys
12
11
  import textwrap
13
12
  import typing as t
14
- from copy import deepcopy
13
+ from dataclasses import asdict
15
14
 
16
15
  import argcomplete
17
16
  from pydantic import (
@@ -19,9 +18,8 @@ from pydantic import (
19
18
  create_model,
20
19
  )
21
20
 
22
- from . import (
23
- SESSION_ARGS,
24
- )
21
+ from idf_build_apps.args import BuildArguments, DumpManifestShaArguments, FindArguments, add_arguments_to_parser
22
+
25
23
  from .app import (
26
24
  App,
27
25
  AppDeserializer,
@@ -29,12 +27,6 @@ from .app import (
29
27
  MakeApp,
30
28
  )
31
29
  from .autocompletions import activate_completions
32
- from .build_apps_args import (
33
- BuildAppsArgs,
34
- )
35
- from .config import (
36
- get_valid_config,
37
- )
38
30
  from .constants import ALL_TARGETS, BuildStatus, completion_instructions
39
31
  from .finder import (
40
32
  _find_apps,
@@ -44,189 +36,65 @@ from .junit import (
44
36
  TestReport,
45
37
  TestSuite,
46
38
  )
47
- from .log import (
48
- setup_logging,
49
- )
50
39
  from .manifest.manifest import (
51
- FolderRule,
52
40
  Manifest,
53
41
  )
54
42
  from .utils import (
55
43
  AutocompleteActivationError,
56
44
  InvalidCommand,
57
- files_matches_patterns,
45
+ drop_none_kwargs,
58
46
  get_parallel_start_stop,
59
- semicolon_separated_str_to_list,
60
- to_absolute_path,
61
47
  to_list,
62
48
  )
63
49
 
64
50
  LOGGER = logging.getLogger(__name__)
65
51
 
66
52
 
67
- def _check_app_dependency(
68
- manifest_rootpath: t.Optional[str] = None,
69
- modified_components: t.Optional[t.List[str]] = None,
70
- modified_files: t.Optional[t.List[str]] = None,
71
- ignore_app_dependencies_components: t.Optional[t.List[str]] = None,
72
- ignore_app_dependencies_filepatterns: t.Optional[t.List[str]] = None,
73
- ) -> bool:
74
- # not check since modified_components and modified_files are not passed
75
- if modified_components is None and modified_files is None:
76
- return False
77
-
78
- # not check since ignore_app_dependencies_components is passed and matched
79
- if (
80
- ignore_app_dependencies_components
81
- and modified_components is not None
82
- and set(modified_components).intersection(ignore_app_dependencies_components)
83
- ):
84
- LOGGER.info(
85
- 'Build all apps since modified components %s matches ignored components %s',
86
- ', '.join(modified_components),
87
- ', '.join(ignore_app_dependencies_components),
88
- )
89
- return False
90
-
91
- # not check since ignore_app_dependencies_filepatterns is passed and matched
92
- if (
93
- ignore_app_dependencies_filepatterns
94
- and modified_files is not None
95
- and files_matches_patterns(modified_files, ignore_app_dependencies_filepatterns, manifest_rootpath)
96
- ):
97
- LOGGER.info(
98
- 'Build all apps since modified files %s matches ignored file patterns %s',
99
- ', '.join(modified_files),
100
- ', '.join(ignore_app_dependencies_filepatterns),
101
- )
102
- return False
103
-
104
- return True
105
-
106
-
107
53
  def find_apps(
108
- paths: t.Union[t.List[str], str],
109
- target: str,
54
+ paths: t.Union[t.List[str], str, None] = None,
55
+ target: t.Optional[str] = None,
110
56
  *,
111
- build_system: t.Union[t.Type[App], str] = CMakeApp,
112
- recursive: bool = False,
113
- exclude_list: t.Optional[t.List[str]] = None,
114
- work_dir: t.Optional[str] = None,
115
- build_dir: str = 'build',
116
- config_rules_str: t.Optional[t.Union[t.List[str], str]] = None,
117
- build_log_filename: t.Optional[str] = None,
118
- size_json_filename: t.Optional[str] = None,
119
- check_warnings: bool = False,
120
- preserve: bool = True,
121
- manifest_rootpath: t.Optional[str] = None,
122
- manifest_files: t.Optional[t.Union[t.List[str], str]] = None,
123
- check_manifest_rules: bool = False,
124
- default_build_targets: t.Optional[t.Union[t.List[str], str]] = None,
125
- modified_components: t.Optional[t.Union[t.List[str], str]] = None,
126
- modified_files: t.Optional[t.Union[t.List[str], str]] = None,
127
- ignore_app_dependencies_components: t.Optional[t.Union[t.List[str], str]] = None,
128
- ignore_app_dependencies_filepatterns: t.Optional[t.Union[t.List[str], str]] = None,
129
- sdkconfig_defaults: t.Optional[str] = None,
130
- include_skipped_apps: bool = False,
131
- include_disabled_apps: bool = False,
57
+ find_arguments: t.Optional[FindArguments] = None,
58
+ **kwargs,
132
59
  ) -> t.List[App]:
133
60
  """
134
- Find app directories in paths (possibly recursively), which contain apps for the given build system, compatible
135
- with the given target
136
-
137
- :param paths: list of app directories (can be / usually will be a relative path)
138
- :param target: desired value of IDF_TARGET; apps incompatible with the given target are skipped.
139
- :param build_system: class of the build system, default CMakeApp
140
- :param recursive: Recursively search into the nested sub-folders if no app is found or not
141
- :param exclude_list: list of paths to be excluded from the recursive search
142
- :param work_dir: directory where the app should be copied before building. Support placeholders
143
- :param build_dir: directory where the build will be done. Support placeholders.
144
- :param config_rules_str: mapping of sdkconfig file name patterns to configuration names
145
- :param build_log_filename: filename of the build log. Will be placed under the app.build_path.
146
- Support placeholders. The logs will go to stdout/stderr if not specified
147
- :param size_json_filename: filename to collect the app's size information. Will be placed under the app.build_path.
148
- Support placeholders. The app's size information won't be collected if not specified
149
- :param check_warnings: Check for warnings in the build log or not
150
- :param preserve: Preserve the built binaries or not
151
- :param manifest_rootpath: The root path of the manifest files. Usually the folders specified in the manifest files
152
- are relative paths. Use the current directory if not specified
153
- :param manifest_files: paths of the manifest files
154
- :param check_manifest_rules: check the manifest rules or not
155
- :param default_build_targets: default build targets used in manifest files
156
- :param modified_components: modified components
157
- :param modified_files: modified files
158
- :param ignore_app_dependencies_components: components used for ignoring checking the app dependencies
159
- :param ignore_app_dependencies_filepatterns: file patterns used for ignoring checking the app dependencies
160
- :param sdkconfig_defaults: semicolon-separated string, pass to idf.py -DSDKCONFIG_DEFAULTS if specified,
161
- also could be set via environment variables "SDKCONFIG_DEFAULTS"
162
- :param include_skipped_apps: include skipped apps or not
163
- :param include_disabled_apps: include disabled apps or not
61
+ Find apps in the given paths for the specified target. For all kwargs, please refer to `FindArguments`
62
+
164
63
  :return: list of found apps
165
64
  """
166
- if default_build_targets:
167
- default_build_targets = to_list(default_build_targets)
168
- LOGGER.info('Overriding default build targets to %s', default_build_targets)
169
- FolderRule.DEFAULT_BUILD_TARGETS = default_build_targets
65
+ if find_arguments is None:
66
+ find_arguments = FindArguments(
67
+ paths=to_list(paths), # type: ignore
68
+ target=target, # type: ignore
69
+ **kwargs,
70
+ )
170
71
 
171
- if isinstance(build_system, str):
72
+ app_cls: t.Type[App]
73
+ if isinstance(find_arguments.build_system, str):
172
74
  # backwards compatible
173
- if build_system == 'cmake':
174
- build_system = CMakeApp
175
- elif build_system == 'make':
176
- build_system = MakeApp
75
+ if find_arguments.build_system == 'cmake':
76
+ app_cls = CMakeApp
77
+ elif find_arguments.build_system == 'make':
78
+ app_cls = MakeApp
177
79
  else:
178
80
  raise ValueError('Only Support "make" and "cmake"')
179
- app_cls = build_system
180
-
181
- # always set the manifest rootpath at the very beginning of find_apps in case ESP-IDF switches the branch.
182
- Manifest.ROOTPATH = to_absolute_path(manifest_rootpath or os.curdir)
183
- Manifest.CHECK_MANIFEST_RULES = check_manifest_rules
184
-
185
- if manifest_files:
186
- App.MANIFEST = Manifest.from_files(to_list(manifest_files))
187
-
188
- modified_components = to_list(modified_components)
189
- modified_files = to_list(modified_files)
190
- ignore_app_dependencies_components = to_list(ignore_app_dependencies_components)
191
- ignore_app_dependencies_filepatterns = to_list(ignore_app_dependencies_filepatterns)
192
- config_rules_str = to_list(config_rules_str)
81
+ else:
82
+ app_cls = find_arguments.build_system
193
83
 
194
84
  apps = []
195
- if target == 'all':
85
+ if find_arguments.target == 'all':
196
86
  targets = ALL_TARGETS
197
87
  else:
198
- targets = [target]
88
+ targets = [find_arguments.target]
199
89
 
200
- for target in targets:
201
- for path in to_list(paths):
202
- path = path.strip()
90
+ for _t in targets:
91
+ for _p in find_arguments.paths:
203
92
  apps.extend(
204
93
  _find_apps(
205
- path,
206
- target,
207
- app_cls,
208
- recursive,
209
- exclude_list or [],
210
- work_dir=work_dir,
211
- build_dir=build_dir or 'build',
212
- config_rules_str=config_rules_str,
213
- build_log_filename=build_log_filename,
214
- size_json_filename=size_json_filename,
215
- check_warnings=check_warnings,
216
- preserve=preserve,
217
- manifest_rootpath=manifest_rootpath,
218
- check_app_dependencies=_check_app_dependency(
219
- manifest_rootpath=manifest_rootpath,
220
- modified_components=modified_components,
221
- modified_files=modified_files,
222
- ignore_app_dependencies_components=ignore_app_dependencies_components,
223
- ignore_app_dependencies_filepatterns=ignore_app_dependencies_filepatterns,
224
- ),
225
- modified_components=modified_components,
226
- modified_files=modified_files,
227
- sdkconfig_defaults_str=sdkconfig_defaults,
228
- include_skipped_apps=include_skipped_apps,
229
- include_disabled_apps=include_disabled_apps,
94
+ _p,
95
+ _t,
96
+ app_cls=app_cls,
97
+ args=find_arguments,
230
98
  )
231
99
  )
232
100
 
@@ -236,85 +104,29 @@ def find_apps(
236
104
 
237
105
 
238
106
  def build_apps(
239
- apps: t.Union[t.List[App], App],
240
- *,
241
- build_verbose: bool = False,
242
- dry_run: bool = False,
243
- keep_going: bool = False,
244
- ignore_warning_strs: t.Optional[t.List[str]] = None,
245
- ignore_warning_file: t.Optional[t.TextIO] = None,
246
- copy_sdkconfig: bool = False,
247
- manifest_rootpath: t.Optional[str] = None,
248
- modified_components: t.Optional[t.Union[t.List[str], str]] = None,
249
- modified_files: t.Optional[t.Union[t.List[str], str]] = None,
250
- ignore_app_dependencies_components: t.Optional[t.Union[t.List[str], str]] = None,
251
- ignore_app_dependencies_filepatterns: t.Optional[t.Union[t.List[str], str]] = None,
252
- check_app_dependencies: t.Optional[bool] = None,
253
- # BuildAppsArgs
254
- parallel_count: int = 1,
255
- parallel_index: int = 1,
256
- collect_size_info: t.Optional[str] = None,
257
- collect_app_info: t.Optional[str] = None,
258
- junitxml: t.Optional[str] = None,
107
+ apps: t.Union[t.List[App], App, None] = None, *, build_arguments: t.Optional[BuildArguments] = None, **kwargs
259
108
  ) -> int:
260
109
  """
261
- Build all the specified apps
262
-
263
- :param apps: list of apps to be built
264
- :param build_verbose: call ``--verbose`` in ``idf.py build`` or not
265
- :param dry_run: simulate this run or not
266
- :param keep_going: keep building or not if one app's build failed
267
- :param ignore_warning_strs: ignore build warnings that matches any of the specified regex patterns
268
- :param ignore_warning_file: ignore build warnings that matches any of the lines of the regex patterns in the
269
- specified file
270
- :param copy_sdkconfig: copy the sdkconfig file to the build directory or not
271
- :param manifest_rootpath: The root path of the manifest files. Usually the folders specified in the manifest files
272
- are relative paths. Use the current directory if not specified
273
- :param modified_components: modified components
274
- :param modified_files: modified files
275
- :param ignore_app_dependencies_components: components used for ignoring checking the app dependencies
276
- :param ignore_app_dependencies_filepatterns: file patterns used for ignoring checking the app dependencies
277
- :param check_app_dependencies: check app dependencies or not. if not set, will be calculated by modified_components,
278
- modified_files, and ignore_app_dependencies_filepatterns
279
- :param parallel_count: number of parallel tasks to run
280
- :param parallel_index: index of the parallel task to run
281
- :param collect_size_info: file path to record all generated size files' paths if specified
282
- :param collect_app_info: file path to record all the built apps' info if specified
283
- :param junitxml: path of the junitxml file
110
+ Build all the specified apps. For all kwargs, please refer to `BuildArguments`
111
+
284
112
  :return: exit code
285
113
  """
286
114
  apps = to_list(apps)
287
- modified_components = to_list(modified_components)
288
- modified_files = to_list(modified_files)
289
- ignore_app_dependencies_components = to_list(ignore_app_dependencies_components)
290
- ignore_app_dependencies_filepatterns = to_list(ignore_app_dependencies_filepatterns)
115
+ if build_arguments is None:
116
+ build_arguments = BuildArguments(
117
+ **kwargs,
118
+ )
291
119
 
292
- test_suite = TestSuite('build_apps')
120
+ if apps is None:
121
+ apps = find_apps(find_arguments=FindArguments.from_dict(asdict(build_arguments)))
293
122
 
294
- ignore_warnings_regexes = []
295
- if ignore_warning_strs:
296
- for s in ignore_warning_strs:
297
- ignore_warnings_regexes.append(re.compile(s))
298
- if ignore_warning_file:
299
- for s in ignore_warning_file:
300
- ignore_warnings_regexes.append(re.compile(s.strip()))
301
- App.IGNORE_WARNS_REGEXES = ignore_warnings_regexes
123
+ test_suite = TestSuite('build_apps')
302
124
 
303
- start, stop = get_parallel_start_stop(len(apps), parallel_count, parallel_index)
125
+ start, stop = get_parallel_start_stop(len(apps), build_arguments.parallel_count, build_arguments.parallel_index)
304
126
  LOGGER.info('Total %s apps. running build for app %s-%s', len(apps), start, stop)
305
127
 
306
- build_apps_args = BuildAppsArgs(
307
- parallel_count=parallel_count,
308
- parallel_index=parallel_index,
309
- collect_size_info=collect_size_info,
310
- collect_app_info=collect_app_info,
311
- junitxml=junitxml,
312
- )
313
- for app in apps[start - 1 : stop]: # we use 1-based
314
- app.build_apps_args = build_apps_args
315
-
316
128
  # cleanup collect files if exists at this early-stage
317
- for f in (build_apps_args.collect_app_info, build_apps_args.collect_size_info, build_apps_args.junitxml):
129
+ for f in (build_arguments.collect_app_info, build_arguments.collect_size_info, build_arguments.junitxml):
318
130
  if f and os.path.isfile(f):
319
131
  os.remove(f)
320
132
  LOGGER.debug('Remove existing collect file %s', f)
@@ -326,26 +138,18 @@ def build_apps(
326
138
  continue
327
139
 
328
140
  # attrs
329
- app.dry_run = dry_run
141
+ app.dry_run = build_arguments.dry_run
330
142
  app.index = index
331
- app.verbose = build_verbose
332
- app.copy_sdkconfig = copy_sdkconfig
143
+ app.verbose = build_arguments.build_verbose
144
+ app.copy_sdkconfig = build_arguments.copy_sdkconfig
333
145
 
334
146
  LOGGER.info('(%s/%s) Building app: %s', index, len(apps), app)
335
147
 
336
148
  app.build(
337
- manifest_rootpath=manifest_rootpath,
338
- modified_components=modified_components,
339
- modified_files=modified_files,
340
- check_app_dependencies=_check_app_dependency(
341
- manifest_rootpath=manifest_rootpath,
342
- modified_components=modified_components,
343
- modified_files=modified_files,
344
- ignore_app_dependencies_components=ignore_app_dependencies_components,
345
- ignore_app_dependencies_filepatterns=ignore_app_dependencies_filepatterns,
346
- )
347
- if check_app_dependencies is None
348
- else check_app_dependencies,
149
+ manifest_rootpath=build_arguments.manifest_rootpath,
150
+ modified_components=build_arguments.modified_components,
151
+ modified_files=build_arguments.modified_files,
152
+ check_app_dependencies=build_arguments.dependency_driven_build_enabled,
349
153
  )
350
154
  test_suite.add_test_case(TestCase.from_app(app))
351
155
 
@@ -354,20 +158,20 @@ def build_apps(
354
158
  else:
355
159
  LOGGER.info('%s', app.build_status.value)
356
160
 
357
- if build_apps_args.collect_app_info:
358
- with open(build_apps_args.collect_app_info, 'a') as fw:
161
+ if build_arguments.collect_app_info:
162
+ with open(build_arguments.collect_app_info, 'a') as fw:
359
163
  fw.write(app.to_json() + '\n')
360
- LOGGER.debug('Recorded app info in %s', build_apps_args.collect_app_info)
164
+ LOGGER.debug('Recorded app info in %s', build_arguments.collect_app_info)
361
165
 
362
166
  if app.build_status == BuildStatus.FAILED:
363
- if not keep_going:
167
+ if not build_arguments.keep_going:
364
168
  return 1
365
169
  else:
366
170
  exit_code = 1
367
171
  elif app.build_status == BuildStatus.SUCCESS:
368
- if build_apps_args.collect_size_info and app.size_json_path:
172
+ if build_arguments.collect_size_info and app.size_json_path:
369
173
  if os.path.isfile(app.size_json_path):
370
- with open(build_apps_args.collect_size_info, 'a') as fw:
174
+ with open(build_arguments.collect_size_info, 'a') as fw:
371
175
  fw.write(
372
176
  json.dumps(
373
177
  {
@@ -379,13 +183,13 @@ def build_apps(
379
183
  )
380
184
  + '\n'
381
185
  )
382
- LOGGER.debug('Recorded size info file path in %s', build_apps_args.collect_size_info)
186
+ LOGGER.debug('Recorded size info file path in %s', build_arguments.collect_size_info)
383
187
 
384
188
  LOGGER.info('') # add one empty line for separating different builds
385
189
 
386
- if build_apps_args.junitxml:
387
- TestReport([test_suite], build_apps_args.junitxml).create_test_report()
388
- LOGGER.info('Generated junit report for build apps: %s', build_apps_args.junitxml)
190
+ if build_arguments.junitxml:
191
+ TestReport([test_suite], build_arguments.junitxml).create_test_report()
192
+ LOGGER.info('Generated junit report for build apps: %s', build_arguments.junitxml)
389
193
 
390
194
  return exit_code
391
195
 
@@ -438,7 +242,7 @@ class IdfBuildAppsCliFormatter(argparse.HelpFormatter):
438
242
 
439
243
  def get_parser() -> argparse.ArgumentParser:
440
244
  parser = argparse.ArgumentParser(
441
- description='Tools for building ESP-IDF related apps.'
245
+ description='Tools for building ESP-IDF related apps. '
442
246
  'Some CLI options can be expanded by the following placeholders, like "--work-dir", "--build-dir", etc.:\n'
443
247
  '- @t: would be replaced by the target chip type\n'
444
248
  '- @w: would be replaced by the wildcard, usually the sdkconfig\n'
@@ -449,180 +253,11 @@ def get_parser() -> argparse.ArgumentParser:
449
253
  '- @p: would be replaced by the parallel index (only available in `build` command)',
450
254
  formatter_class=argparse.RawDescriptionHelpFormatter,
451
255
  )
452
- actions = parser.add_subparsers(dest='action')
453
-
454
- common_args = argparse.ArgumentParser(add_help=False)
455
- common_args.add_argument(
456
- '-c',
457
- '--config-file',
458
- help='Path to the default configuration file, toml file',
459
- )
460
-
461
- common_args.add_argument(
462
- '-p', '--paths', nargs='*', help='One or more paths to look for apps. By default build the current directory.'
463
- )
464
- common_args.add_argument(
465
- '-t', '--target', default='all', help='filter apps by given target. By default build all supported targets.'
466
- )
467
- common_args.add_argument(
468
- '--build-system', default='cmake', choices=['cmake', 'make'], help='filter apps by given build system'
469
- )
470
- common_args.add_argument(
471
- '--recursive',
472
- action='store_true',
473
- help='Look for apps in the specified paths recursively',
474
- )
475
- common_args.add_argument('--exclude', nargs='+', help='Ignore specified path (if --recursive is given)')
476
- common_args.add_argument(
477
- '--work-dir',
478
- help='If set, the app is first copied into the specified directory, and then built. '
479
- 'If not set, the work directory is the directory of the app. Can expand placeholders',
480
- )
481
- common_args.add_argument(
482
- '--build-dir',
483
- default='build',
484
- help='If set, specifies the build directory name. Can be either a name relative to the work directory, '
485
- 'or an absolute path. Can expand placeholders',
486
- )
487
- common_args.add_argument(
488
- '--build-log',
489
- help='Relative to build dir. The build log will be written to this file instead of sys.stdout if specified. '
490
- 'Can expand placeholders',
491
- )
492
- common_args.add_argument(
493
- '--size-file',
494
- help='Relative to build dir. The size json will be written to this file if specified. Can expand placeholders',
495
- )
496
- common_args.add_argument(
497
- '--config',
498
- nargs='+',
499
- help='Adds configurations (sdkconfig file names) to build. '
500
- 'This can either be FILENAME[=NAME] or FILEPATTERN. FILENAME is the name of the sdkconfig file, '
501
- 'relative to the project directory, to be used. Optional NAME can be specified, '
502
- 'which can be used as a name of this configuration. FILEPATTERN is the name of '
503
- 'the sdkconfig file, relative to the project directory, with at most one wildcard. '
504
- 'The part captured by the wildcard is used as the name of the configuration',
505
- )
506
-
507
- common_args.add_argument(
508
- '--override-sdkconfig-items',
509
- nargs='?',
510
- type=str,
511
- help='The --override-sdkconfig-items option is a comma-separated list '
512
- 'that permits the overriding of specific configuration items defined '
513
- "in the SDK's sdkconfig file and Kconfig using a command-line argument. "
514
- 'The sdkconfig items specified here override the same sdkconfig '
515
- 'item defined in the --override-sdkconfig-files, if exists.',
516
- )
517
- common_args.add_argument(
518
- '--override-sdkconfig-files',
519
- nargs='?',
520
- type=str,
521
- help='"The --override-sdkconfig-files option is a comma-separated list, '
522
- 'which provides an alternative (alt: --override-sdkconfig-items) '
523
- 'approach for overriding SDK configuration items. '
524
- 'The filepath may be global or relative to the root.',
525
- )
526
- common_args.add_argument(
527
- '--sdkconfig-defaults',
528
- help='semicolon-separated string, pass to idf.py -DSDKCONFIG_DEFAULTS if specified, also could be set via '
529
- 'environment variables "SDKCONFIG_DEFAULTS"',
530
- )
531
- common_args.add_argument(
532
- '-v',
533
- '--verbose',
534
- default=0,
535
- action='count',
536
- help='Increase the logging level of the whole process. Can be specified multiple times. '
537
- 'By default set to WARNING level. '
538
- 'Specify once to set to INFO level. '
539
- 'Specify twice or more to set to DEBUG level',
540
- )
541
- common_args.add_argument(
542
- '--log-file',
543
- help='Write the log to the specified file, instead of stderr',
544
- )
545
- common_args.add_argument(
546
- '--check-warnings', action='store_true', help='If set, fail the build if warnings are found'
547
- )
548
-
549
- common_args.add_argument(
550
- '--manifest-file',
551
- nargs='+',
552
- help='Manifest files which specify the build test rules of the apps',
553
- )
554
- common_args.add_argument(
555
- '--manifest-rootpath',
556
- help='Root directory for calculating the realpath of the relative path defined in the manifest files. '
557
- 'Would use the current directory if not set',
558
- )
559
- common_args.add_argument(
560
- '--check-manifest-rules',
561
- action='store_true',
562
- help='Exit with error if any of the manifest rules does not exist on your filesystem',
563
- )
564
- common_args.add_argument(
565
- '--enable-preview-targets',
566
- action='store_true',
567
- help='Build the apps with all targets in the current ESP-IDF branch, '
568
- 'including preview targets, when the app supports the target.',
569
- )
570
- common_args.add_argument(
571
- '--default-build-targets',
572
- nargs='+',
573
- help='space-separated list of string which specifies the targets for building the apps. '
574
- 'If provided, the apps will be built only with the specified targets '
575
- 'when the app supports the target.',
576
- )
577
- common_args.add_argument(
578
- '--modified-components',
579
- type=semicolon_separated_str_to_list,
580
- help='semicolon-separated string which specifies the modified components. '
581
- 'app with `depends_components` set in the corresponding manifest files would only be built '
582
- 'if depends on any of the specified components. '
583
- 'If set to "", the value would be considered as None. '
584
- 'If set to ";", the value would be considered as an empty list',
585
- )
586
- common_args.add_argument(
587
- '--modified-files',
588
- type=semicolon_separated_str_to_list,
589
- help='semicolon-separated string which specifies the modified files. '
590
- 'app with `depends_filepatterns` set in the corresponding manifest files would only be built '
591
- 'if any of the specified file pattern matches any of the specified modified files. '
592
- 'If set to "", the value would be considered as None. '
593
- 'If set to ";", the value would be considered as an empty list',
594
- )
595
- common_args.add_argument(
596
- '-ic',
597
- '--ignore-app-dependencies-components',
598
- type=semicolon_separated_str_to_list,
599
- help='semicolon-separated string which specifies the modified components used for '
600
- 'ignoring checking the app dependencies. '
601
- 'The `depends_components` and `depends_filepatterns` set in the manifest files will be ignored when any of the '
602
- 'specified components matches any of the modified components. '
603
- 'Must be used together with --modified-components. '
604
- 'If set to "", the value would be considered as None. '
605
- 'If set to ";", the value would be considered as an empty list',
606
- )
607
- common_args.add_argument(
608
- '-if',
609
- '--ignore-app-dependencies-filepatterns',
610
- type=semicolon_separated_str_to_list,
611
- help='semicolon-separated string which specifies the file patterns used for '
612
- 'ignoring checking the app dependencies. '
613
- 'The `depends_components` and `depends_filepatterns` set in the manifest files will be ignored when any of the '
614
- 'specified file patterns matches any of the modified files. '
615
- 'Must be used together with --modified-files. '
616
- 'If set to "", the value would be considered as None. '
617
- 'If set to ";", the value would be considered as an empty list',
618
- )
619
-
620
- common_args.add_argument(
621
- '--no-color',
622
- action='store_true',
623
- help='enable colored output by default on UNIX-like systems. enable this flag to make the logs uncolored.',
624
- )
256
+ actions = parser.add_subparsers(dest='action', required=True)
625
257
 
258
+ ########
259
+ # Find #
260
+ ########
626
261
  find_parser = actions.add_parser(
627
262
  'find',
628
263
  help='Find the buildable applications. Run `idf-build-apps find --help` for more information on a command.',
@@ -630,95 +265,25 @@ def get_parser() -> argparse.ArgumentParser:
630
265
  '`--path` and `--target` options must be provided. '
631
266
  'By default, print the found apps in stdout. '
632
267
  'To find apps for all chips use the `--target` option with the `all` argument.',
633
- parents=[common_args],
634
268
  formatter_class=IdfBuildAppsCliFormatter,
635
269
  )
636
- find_parser.add_argument('-o', '--output', help='Print the found apps to the specified file instead of stdout')
637
- find_parser.add_argument(
638
- '--output-format',
639
- choices=['raw', 'json'],
640
- default='raw',
641
- help='Output format. In "raw" format, each line is a valid json that represents the app. '
642
- 'In "json" format, the whole file is a JSON file of a list of apps.',
643
- )
644
- find_parser.add_argument(
645
- '--include-all-apps',
646
- action='store_true',
647
- help='Include skipped and disabled apps. By default only apps that should be built.',
648
- )
270
+ add_arguments_to_parser(FindArguments, find_parser)
649
271
 
272
+ #########
273
+ # Build #
274
+ #########
650
275
  build_parser = actions.add_parser(
651
276
  'build',
652
277
  help='Build the found applications. Run `idf-build-apps build --help` for more information on a command.',
653
278
  description='Build the application in the given path or paths for specified chips. '
654
279
  '`--path` and `--target` options must be provided.',
655
- parents=[common_args],
656
280
  formatter_class=IdfBuildAppsCliFormatter,
657
281
  )
658
- build_parser.add_argument(
659
- '--build-verbose',
660
- action='store_true',
661
- help='Enable verbose output of the build system',
662
- )
663
- build_parser.add_argument(
664
- '--parallel-count',
665
- default=1,
666
- type=int,
667
- help="Number of parallel build jobs. Note that this script doesn't start all jobs simultaneously. "
668
- 'It needs to be executed multiple times with same value of --parallel-count and '
669
- 'different values of --parallel-index',
670
- )
671
- build_parser.add_argument(
672
- '--parallel-index',
673
- default=1,
674
- type=int,
675
- help='Index (1-based) of the job, out of the number specified by --parallel-count',
676
- )
677
- build_parser.add_argument(
678
- '--dry-run',
679
- action='store_true',
680
- help="Don't actually build, only print the build commands",
681
- )
682
- build_parser.add_argument(
683
- '--keep-going',
684
- action='store_true',
685
- help="Don't exit immediately when a build fails",
686
- )
687
- build_parser.add_argument(
688
- '--no-preserve',
689
- action='store_true',
690
- help="Don't preserve the build directory after a successful build",
691
- )
692
- build_parser.add_argument(
693
- '--collect-size-info',
694
- help='write size info json file while building into the specified file. each line is a json object. '
695
- 'Can expand placeholder @p',
696
- )
697
- build_parser.add_argument(
698
- '--collect-app-info',
699
- help='write app info json file while building into the specified file. each line is a json object. '
700
- 'Can expand placeholder @p',
701
- )
702
- build_parser.add_argument(
703
- '--ignore-warning-str',
704
- nargs='+',
705
- help='Ignore the warning string that match the specified regex in the build output',
706
- )
707
- build_parser.add_argument(
708
- '--ignore-warning-file',
709
- type=argparse.FileType('r'),
710
- help='Ignore the warning strings in the specified file. Each line should be a regex string',
711
- )
712
- build_parser.add_argument(
713
- '--copy-sdkconfig',
714
- action='store_true',
715
- help='Copy the sdkconfig file to the build directory',
716
- )
717
- build_parser.add_argument(
718
- '--junitxml',
719
- help='Path to the junitxml file. If specified, the junitxml file will be generated. Can expand placeholder @p',
720
- )
282
+ add_arguments_to_parser(BuildArguments, build_parser)
721
283
 
284
+ ###############
285
+ # Completions #
286
+ ###############
722
287
  completions_parser = actions.add_parser(
723
288
  'completions',
724
289
  help='Add the autocompletion activation script to the shell rc file. '
@@ -739,9 +304,19 @@ def get_parser() -> argparse.ArgumentParser:
739
304
  '-s',
740
305
  '--shell',
741
306
  choices=['bash', 'zsh', 'fish'],
742
- help='Specify the shell type for the autocomplite activation script. ',
307
+ help='Specify the shell type for the autocomplete activation script.',
743
308
  )
744
309
 
310
+ ############################
311
+ # Dump Manifest SHA Values #
312
+ ############################
313
+ dump_manifest_parser = actions.add_parser(
314
+ 'dump-manifest-sha',
315
+ help='Dump the manifest files SHA values. '
316
+ 'This could be useful in CI to check if the manifest files are changed.',
317
+ )
318
+ add_arguments_to_parser(DumpManifestShaArguments, dump_manifest_parser)
319
+
745
320
  return parser
746
321
 
747
322
 
@@ -756,54 +331,6 @@ def handle_completions(args: argparse.Namespace) -> None:
756
331
  print(completion_instructions)
757
332
 
758
333
 
759
- def validate_args(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
760
- # validate cli subcommands
761
- if args.action not in ['find', 'build', 'completions']:
762
- parser.print_help()
763
- raise InvalidCommand('subcommand is required. {find, build, completions}')
764
-
765
- if not args.paths:
766
- cur_dir = os.getcwd()
767
- LOGGER.debug(f'--paths is missing. Set --path as current directory "{cur_dir}".')
768
- args.paths = [cur_dir]
769
-
770
- if not args.target:
771
- LOGGER.debug('--target is missing. Set --target as "all".')
772
- args.target = 'all'
773
-
774
- default_build_targets = []
775
- if args.default_build_targets:
776
- for target in args.default_build_targets:
777
- if target not in ALL_TARGETS:
778
- LOGGER.warning(
779
- f'Ignoring... Unrecognizable target {target} specified with "--default-build-targets". '
780
- f'Current ESP-IDF available targets: {ALL_TARGETS}'
781
- )
782
- elif target not in default_build_targets:
783
- default_build_targets.append(target)
784
- args.default_build_targets = default_build_targets
785
- elif args.enable_preview_targets:
786
- args.default_build_targets = deepcopy(ALL_TARGETS)
787
-
788
- if args.ignore_app_dependencies_components is not None:
789
- if args.modified_components is None:
790
- raise InvalidCommand('Must specify "--ignore-app-dependencies-components" with "--modified-components", ')
791
-
792
- if args.ignore_app_dependencies_filepatterns is not None:
793
- if args.modified_files is None:
794
- raise InvalidCommand('Must specify "--ignore-app-dependencies-filepatterns" with "--modified-files", ')
795
-
796
-
797
- def apply_config_args(args: argparse.Namespace) -> None:
798
- # support toml config file
799
- config_dict = get_valid_config(custom_path=args.config_file)
800
- if config_dict:
801
- for k, v in config_dict.items():
802
- setattr(args, k, v)
803
-
804
- setup_logging(args.verbose, args.log_file, not args.no_color)
805
-
806
-
807
334
  def main():
808
335
  parser = get_parser()
809
336
  argcomplete.autocomplete(parser)
@@ -813,86 +340,42 @@ def main():
813
340
  handle_completions(args)
814
341
  sys.exit(0)
815
342
 
816
- apply_config_args(args)
817
- validate_args(parser, args)
818
-
819
- SESSION_ARGS.set(args)
820
-
821
- if args.action == 'build':
822
- args.output = None # build action doesn't support output option
823
-
824
- kwargs = {
825
- 'build_system': args.build_system,
826
- 'recursive': args.recursive,
827
- 'exclude_list': args.exclude or [],
828
- 'work_dir': args.work_dir,
829
- 'build_dir': args.build_dir or 'build',
830
- 'config_rules_str': args.config,
831
- 'build_log_filename': args.build_log,
832
- 'size_json_filename': args.size_file,
833
- 'check_warnings': args.check_warnings,
834
- 'manifest_rootpath': args.manifest_rootpath,
835
- 'manifest_files': args.manifest_file,
836
- 'check_manifest_rules': args.check_manifest_rules,
837
- 'default_build_targets': args.default_build_targets,
838
- 'modified_components': args.modified_components,
839
- 'modified_files': args.modified_files,
840
- 'ignore_app_dependencies_components': args.ignore_app_dependencies_components,
841
- 'ignore_app_dependencies_filepatterns': args.ignore_app_dependencies_filepatterns,
842
- 'sdkconfig_defaults': args.sdkconfig_defaults,
843
- }
844
- # only useful in find
845
- if args.action == 'find' and args.include_all_apps:
846
- kwargs['include_skipped_apps'] = True
847
- kwargs['include_disabled_apps'] = True
848
-
849
- # real call starts here
850
- apps = find_apps(args.paths, args.target, **kwargs)
343
+ if args.action == 'dump-manifest-sha':
344
+ arguments = DumpManifestShaArguments.from_dict(drop_none_kwargs(vars(args)))
345
+ Manifest.from_files(arguments.manifest_files).dump_sha_values(arguments.output)
346
+ sys.exit(0)
851
347
 
852
348
  if args.action == 'find':
853
- if args.output:
854
- os.makedirs(os.path.dirname(os.path.realpath(args.output)), exist_ok=True)
855
- if args.output.endswith('.json'):
856
- LOGGER.info('Detecting output file ends with ".json", writing json file.')
857
- args.output_format = 'json'
858
-
859
- with open(args.output, 'w') as fw:
860
- if args.output_format == 'raw':
349
+ arguments = FindArguments.from_dict(drop_none_kwargs(vars(args)))
350
+ else:
351
+ arguments = BuildArguments.from_dict(drop_none_kwargs(vars(args)))
352
+
353
+ # real call starts here
354
+ # build also needs to find first
355
+ apps = find_apps(args.paths, args.target, find_arguments=arguments)
356
+ if isinstance(arguments, FindArguments): # find only
357
+ if arguments.output:
358
+ os.makedirs(os.path.dirname(os.path.realpath(arguments.output)), exist_ok=True)
359
+ with open(arguments.output, 'w') as fw:
360
+ if arguments.output_format == 'raw':
861
361
  for app in apps:
862
362
  fw.write(app.to_json() + '\n')
863
- elif args.output_format == 'json':
363
+ elif arguments.output_format == 'json':
864
364
  fw.write(json.dumps([app.model_dump() for app in apps], indent=2))
865
365
  else:
866
- raise ValueError(f'Output format {args.output_format} is not supported.')
366
+ raise InvalidCommand(f'Output format {arguments.output_format} is not supported.')
867
367
  else:
868
368
  for app in apps:
869
369
  print(app)
870
370
 
871
371
  sys.exit(0)
872
372
 
873
- if args.no_preserve:
373
+ # build
374
+ if arguments.no_preserve:
874
375
  for app in apps:
875
376
  app.preserve = False
876
377
 
877
- res = build_apps(
878
- apps,
879
- build_verbose=args.build_verbose,
880
- parallel_count=args.parallel_count,
881
- parallel_index=args.parallel_index,
882
- dry_run=args.dry_run,
883
- keep_going=args.keep_going,
884
- collect_size_info=args.collect_size_info,
885
- collect_app_info=args.collect_app_info,
886
- ignore_warning_strs=args.ignore_warning_str,
887
- ignore_warning_file=args.ignore_warning_file,
888
- copy_sdkconfig=args.copy_sdkconfig,
889
- manifest_rootpath=args.manifest_rootpath,
890
- modified_components=args.modified_components,
891
- modified_files=args.modified_files,
892
- ignore_app_dependencies_components=args.ignore_app_dependencies_components,
893
- ignore_app_dependencies_filepatterns=args.ignore_app_dependencies_filepatterns,
894
- junitxml=args.junitxml,
895
- )
378
+ ret_code = build_apps(apps, build_arguments=arguments)
896
379
 
897
380
  built_apps = [app for app in apps if app.build_status == BuildStatus.SUCCESS]
898
381
  if built_apps:
@@ -912,7 +395,7 @@ def main():
912
395
  for app in failed_apps:
913
396
  print(f' {app}')
914
397
 
915
- sys.exit(res)
398
+ sys.exit(ret_code)
916
399
 
917
400
 
918
401
  def json_to_app(json_str: str, extra_classes: t.Optional[t.List[t.Type[App]]] = None) -> App:
@@ -924,13 +407,17 @@ def json_to_app(json_str: str, extra_classes: t.Optional[t.List[t.Type[App]]] =
924
407
  You can pass extra_cls to support custom App class. A custom App class must be a subclass of App, and have a
925
408
  different value of `build_system`. For example, a custom CMake app
926
409
 
927
- >>> class CustomApp(CMakeApp):
928
- >>> build_system: Literal['custom_cmake'] = 'custom_cmake'
410
+ .. code:: python
411
+
412
+ class CustomApp(CMakeApp):
413
+ build_system: Literal['custom_cmake'] = 'custom_cmake'
414
+
415
+ Then you can pass the :class:`CustomApp` class to the :attr:`extra_cls` argument
929
416
 
930
- Then you can pass the CustomApp class to the `extra_cls` argument
417
+ .. code:: python
931
418
 
932
- >>> json_str = CustomApp('.', 'esp32').to_json()
933
- >>> json_to_app(json_str, extra_classes=[CustomApp])
419
+ json_str = CustomApp('.', 'esp32').to_json()
420
+ json_to_app(json_str, extra_classes=[CustomApp])
934
421
 
935
422
  :param json_str: json string
936
423
  :param extra_classes: extra App class