• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nbiotcloud / ucdp / 14373374783

10 Apr 2025 05:58AM UTC coverage: 96.634% (-0.02%) from 96.653%
14373374783

push

github

web-flow
Merge pull request #93 from nbiotcloud/fix/aborted

Fix/aborted

2 of 3 new or added lines in 1 file covered. (66.67%)

4795 of 4962 relevant lines covered (96.63%)

7.73 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.18
/src/ucdp/cli.py
1
#
2
# MIT License
3
#
4
# Copyright (c) 2024-2025 nbiotcloud
5
#
6
# Permission is hereby granted, free of charge, to any person obtaining a copy
7
# of this software and associated documentation files (the "Software"), to deal
8
# in the Software without restriction, including without limitation the rights
9
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
# copies of the Software, and to permit persons to whom the Software is
11
# furnished to do so, subject to the following conditions:
12
#
13
# The above copyright notice and this permission notice shall be included in all
14
# copies or substantial portions of the Software.
15
#
16
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
# SOFTWARE.
23
#
24

25
"""Command Line Interface."""
26

27
import logging
8✔
28
import sys
8✔
29
from collections import defaultdict
8✔
30
from collections.abc import Iterable
8✔
31
from logging import StreamHandler
8✔
32
from pathlib import Path
8✔
33

34
import click
8✔
35
from click_bash42_completion import patch
8✔
36
from pydantic import BaseModel, ConfigDict
8✔
37
from rich.console import Console
8✔
38
from rich.logging import RichHandler
8✔
39
from rich.pretty import pprint
8✔
40
from rich.table import Table
8✔
41

42
from ._cligroup import MainGroup
8✔
43
from ._logging import HasErrorHandler
8✔
44
from .cache import CACHE
8✔
45
from .cliutil import (
8✔
46
    PathType,
47
    arg_template_filepaths,
48
    arg_top,
49
    arg_tops,
50
    auto_path,
51
    defines2data,
52
    opt_check,
53
    opt_create,
54
    opt_defines,
55
    opt_dry_run,
56
    opt_file,
57
    opt_filelist,
58
    opt_filepath,
59
    opt_local,
60
    opt_maxlevel,
61
    opt_maxworkers,
62
    opt_path,
63
    opt_show_diff,
64
    opt_tag,
65
    opt_target,
66
    opt_topsfile,
67
    read_file,
68
)
69
from .consts import PATH
8✔
70
from .fileset import FileSet
8✔
71
from .finder import find
8✔
72
from .generate import Generator, clean, get_makolator, render_generate, render_inplace
8✔
73
from .iterutil import namefilter
8✔
74
from .loader import load
8✔
75
from .modfilelist import iter_modfilelists
8✔
76
from .modtopref import PAT_TOPMODREF, TopModRef
8✔
77
from .pathutil import relative
8✔
78
from .top import Top
8✔
79
from .util import LOGGER, guess_path
8✔
80

81
patch()
8✔
82

83

84
_LOGLEVELMAP = {
8✔
85
    0: logging.WARNING,
86
    1: logging.INFO,
87
    2: logging.DEBUG,
88
}
89

90

91
class Ctx(BaseModel):
8✔
92
    """Command Line Context."""
93

94
    model_config = ConfigDict(
8✔
95
        arbitrary_types_allowed=True,
96
    )
97

98
    console: Console
8✔
99
    has_error_handler: HasErrorHandler | None = None
8✔
100

101
    verbose: int = 0
8✔
102
    no_cache: bool = False
8✔
103
    no_color: bool | None = None
8✔
104

105
    @staticmethod
8✔
106
    def create(no_color: bool | None = None, **kwargs) -> "Ctx":
8✔
107
        """Create."""
108
        console = Console(log_time=False, log_path=False, no_color=no_color)
8✔
109
        has_error_handler = HasErrorHandler()
8✔
110
        return Ctx(console=console, has_error_handler=has_error_handler, no_color=no_color, **kwargs)
8✔
111

112
    def __enter__(self):
8✔
113
        # Logging
114
        level = _LOGLEVELMAP.get(self.verbose, logging.DEBUG)
8✔
115
        if not self.no_color:
8✔
116
            handler = RichHandler(
×
117
                show_time=False,
118
                show_path=False,
119
                rich_tracebacks=True,
120
                console=Console(stderr=True, no_color=self.no_color),
121
            )
122
            format_ = "%(message)s"
×
123
        else:
124
            handler = StreamHandler(stream=sys.stderr)
8✔
125
            format_ = "%(levelname)s %(message)s"
8✔
126
        handlers = [handler, self.has_error_handler]
8✔
127
        logging.basicConfig(level=level, format=format_, handlers=handlers)
8✔
128

129
        # Cache
130
        if self.no_cache:
8✔
131
            CACHE.disable()
×
132

133
        return self
8✔
134

135
    def __exit__(self, exc_type, exc_value, tb):
8✔
136
        if exc_type or self.has_error_handler.has_errors:
8✔
137
            if exc_type is KeyboardInterrupt:
8✔
NEW
138
                self.console.print("[red]Aborted.")
×
139
            else:
140
                self.console.print("[red][bold]Failed.")
8✔
141
            sys.exit(1)
8✔
142

143

144
@click.group(cls=MainGroup, context_settings={"help_option_names": ["-h", "--help"]})
8✔
145
@click.option("-v", "--verbose", count=True, help="Increase Verbosity.")
8✔
146
@click.option("-C", "--no-cache", is_flag=True, help="Disable Caching.")
8✔
147
@click.option("--no-color", is_flag=True, help="Disable Coloring.", envvar="UCDP_NO_COLOR")
8✔
148
@click.version_option()
8✔
149
@click.pass_context
8✔
150
def ucdp(ctx, verbose=0, no_cache=False, no_color=False):
8✔
151
    """Unified Chip Design Platform."""
152
    ctx.obj = ctx.with_resource(Ctx.create(verbose=verbose, no_cache=no_cache, no_color=no_color))
8✔
153

154

155
pass_ctx = click.make_pass_decorator(Ctx)
8✔
156

157

158
def get_group(help=None):  # pragma: no cover
159
    """Create Command Group."""
160

161
    @click.group(help=help)
162
    @click.pass_context
163
    def group(ctx):
164
        ctx.obj = Ctx(console=Console(log_time=False, log_path=False))
165

166
    return group
167

168

169
def load_top(ctx: Ctx, top: str | TopModRef, paths: Iterable[str | Path], quiet: bool = False) -> Top:
8✔
170
    """Load Top Module."""
171
    lpaths = [Path(path) for path in paths]
8✔
172
    # Check if top seems to be some kind of file path
173
    topmodref = TopModRef.cast(guess_path(top) or top) if isinstance(top, str) else top
8✔
174
    if quiet:
8✔
175
        return load(topmodref, paths=lpaths)
8✔
176
    with ctx.console.status(f"Loading '{topmodref!s}'"):
8✔
177
        result = load(topmodref, paths=lpaths)
8✔
178
    ctx.console.log(f"'{topmodref!s}' checked.")
8✔
179
    return result
8✔
180

181

182
@ucdp.command(
8✔
183
    help=f"""
184
Load Data Model and Check.
185

186
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
187
"""
188
)
189
@arg_top
8✔
190
@opt_path
8✔
191
@click.option("--stat", default=False, is_flag=True, help="Show Statistics.")
8✔
192
@pass_ctx
8✔
193
def check(ctx, top, path, stat=False):
8✔
194
    """Check."""
195
    top = load_top(ctx, top, path)
8✔
196
    if stat:
8✔
197
        print("Statistics:")
8✔
198
        for name, value in top.get_stat().items():
8✔
199
            print(f"  {name}: {value}")
8✔
200

201

202
@ucdp.command(
8✔
203
    help=f"""
204
Load Data Model and Generate Files.
205

206
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
207
"""
208
)
209
@arg_tops
8✔
210
@opt_path
8✔
211
@opt_filelist
8✔
212
@opt_target
8✔
213
@opt_show_diff
8✔
214
@opt_maxworkers
8✔
215
@opt_defines
8✔
216
@opt_local
8✔
217
@opt_topsfile
8✔
218
@opt_check
8✔
219
@opt_create
8✔
220
@pass_ctx
8✔
221
def gen(
8✔
222
    ctx,
223
    tops,
224
    path,
225
    filelist,
226
    target=None,
227
    show_diff=False,
228
    maxworkers=None,
229
    define=None,
230
    local=None,
231
    check=False,
232
    create=False,
233
    tops_file=None,
234
):
235
    """Generate."""
236
    tops = list(tops)
8✔
237
    for filepath in tops_file or []:
8✔
238
        tops.extend(read_file(filepath))
8✔
239
    makolator = get_makolator(show_diff=show_diff, paths=path, create=create)
8✔
240
    data = defines2data(define)
8✔
241
    filelist = filelist or ["*"]
8✔
242
    with Generator(makolator=makolator, maxworkers=maxworkers, check=check) as generator:
8✔
243
        for info in find(path, patterns=tuple(tops), local=local, is_top=True):
8✔
244
            try:
8✔
245
                top = load_top(ctx, info.topmodref, path)
8✔
246
            except Exception as exc:
×
247
                LOGGER.warning(f"Cannot load '{info.topmodref}'")
×
248
                LOGGER.warning(str(exc))
×
249
                LOGGER.warning(f"Debug with 'ucdp check {info.topmodref}'")
×
250
                continue
×
251
            for item in filelist:
8✔
252
                generator.generate(top, item, target=target, data=data)
8✔
253

254

255
@ucdp.command(
8✔
256
    help=f"""
257
Load Data Model and Render Template and Create File.
258

259
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
260

261
TEMPLATE_FILEPATHS: Templates to render. Environment Variable 'UCDP_TEMPLATE_FILEPATHS'
262
                    Templates in `templates` folders are found automatically.
263

264
GENFILE: Generated File.
265
"""
266
)
267
@arg_top
8✔
268
@opt_path
8✔
269
@arg_template_filepaths
8✔
270
@click.argument("genfile", type=PathType, shell_complete=auto_path, nargs=1)
8✔
271
@opt_show_diff
8✔
272
@opt_defines
8✔
273
@opt_create
8✔
274
@pass_ctx
8✔
275
def rendergen(ctx, top, path, template_filepaths, genfile, show_diff=False, define=None, create=False):
8✔
276
    """Render Generate."""
277
    top = load_top(ctx, top, path)
8✔
278
    makolator = get_makolator(show_diff=show_diff, paths=path, create=create)
8✔
279
    data = defines2data(define)
8✔
280
    render_generate(top, template_filepaths, genfile=genfile, makolator=makolator, data=data)
8✔
281

282

283
@ucdp.command(
8✔
284
    help=f"""
285
Load Data Model and Render Template and Update File.
286

287
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
288

289
TEMPLATE_FILEPATHS: Templates to render. Environment Variable 'UCDP_TEMPLATE_FILEPATHS'
290
                    Templates in `templates` folders are found automatically.
291

292
INPLACEFILE: Inplace File.
293
"""
294
)
295
@arg_top
8✔
296
@opt_path
8✔
297
@arg_template_filepaths
8✔
298
@click.argument("inplacefile", type=PathType, shell_complete=auto_path, nargs=1)
8✔
299
@opt_show_diff
8✔
300
@opt_defines
8✔
301
@opt_create
8✔
302
@click.option("--ignore_unknown", "-i", default=False, is_flag=True, help="Ignore Unknown Placeholder.")
8✔
303
@pass_ctx
8✔
304
def renderinplace(
8✔
305
    ctx, top, path, template_filepaths, inplacefile, show_diff=False, define=None, ignore_unknown=False, create=False
306
):
307
    """Render Inplace."""
308
    top = load_top(ctx, top, path)
8✔
309
    makolator = get_makolator(show_diff=show_diff, paths=path, create=create)
8✔
310
    data = defines2data(define)
8✔
311
    render_inplace(
8✔
312
        top,
313
        template_filepaths,
314
        inplacefile=inplacefile,
315
        makolator=makolator,
316
        data=data,
317
        ignore_unknown=ignore_unknown,
318
    )
319

320

321
@ucdp.command(
8✔
322
    help=f"""
323
Load Data Model and REMOVE Generated Files.
324

325
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
326
"""
327
)
328
@arg_top
8✔
329
@opt_path
8✔
330
@opt_filelist
8✔
331
@opt_target
8✔
332
@opt_show_diff
8✔
333
@opt_dry_run
8✔
334
@opt_maxworkers
8✔
335
@pass_ctx
8✔
336
def cleangen(ctx, top, path, filelist, target=None, show_diff=False, maxworkers=None, dry_run=False):
8✔
337
    """Clean Generated Files."""
338
    top = load_top(ctx, top, path)
8✔
339
    makolator = get_makolator(show_diff=show_diff, paths=path)
8✔
340
    for item in filelist or ["*"]:
8✔
341
        clean(top, item, target=target, makolator=makolator, maxworkers=maxworkers, dry_run=dry_run)
8✔
342

343

344
@ucdp.command(
8✔
345
    help=f"""
346
Load Data Model and Generate File List.
347

348
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
349
"""
350
)
351
@arg_top
8✔
352
@opt_path
8✔
353
@opt_filelist
8✔
354
@opt_target
8✔
355
@opt_file
8✔
356
@pass_ctx
8✔
357
def filelist(ctx, top, path, filelist, target=None, file=None):
8✔
358
    """File List."""
359
    # Load quiet, otherwise stdout is messed-up
360
    top = load_top(ctx, top, path, quiet=True)
8✔
361
    for item in filelist or ["*"]:
8✔
362
        fileset = FileSet.from_mod(top.mod, item, target=target)
8✔
363
        for line in fileset:
8✔
364
            print(line, file=file)
8✔
365

366

367
@ucdp.command(
8✔
368
    help=f"""
369
Load Data Model and Show File Information
370

371
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
372
"""
373
)
374
@arg_top
8✔
375
@opt_path
8✔
376
@opt_filelist
8✔
377
@opt_target
8✔
378
@opt_maxlevel
8✔
379
@click.option("--minimal", "-m", default=False, is_flag=True, help="Skip defaults.")
8✔
380
@opt_file
8✔
381
@pass_ctx
8✔
382
def fileinfo(ctx, top, path, filelist, target=None, maxlevel=None, minimal=False, file=None):
8✔
383
    """File List."""
384
    # Load quiet, otherwise stdout is messed-up
385
    top = load_top(ctx, top, path, quiet=True)
8✔
386
    console = Console(file=file) if file else ctx.console
8✔
387
    for item in filelist or ["*"]:
8✔
388
        data = defaultdict(list)
8✔
389
        for mod, modfilelist in iter_modfilelists(top.mod, item, target=target, maxlevel=maxlevel):
8✔
390
            data[str(mod)].append(modfilelist.model_dump(exclude_defaults=minimal))
8✔
391
        pprint(dict(data), indent_guides=False, console=console)
8✔
392

393

394
@ucdp.command(
8✔
395
    help="""
396
              List Available Data Models.
397

398
              PATTERN: Limit list to these modules only.
399

400
              Examples:
401

402
                ucdp ls
403

404
                ucdp ls -n
405

406
                ucdp ls glbl_lib*
407
              """
408
)
409
@arg_tops
8✔
410
@opt_path
8✔
411
@click.option("--names", "-n", default=False, is_flag=True, help="Just print names")
8✔
412
@click.option("--top/--no-top", "-t/-T", default=None, is_flag=True, help="List loadable top modules only.")
8✔
413
@click.option("--tb/--no-tb", "-b/-B", default=None, is_flag=True, help="List testbench modules only.")
8✔
414
@click.option("--generic-tb", "-g", default=False, is_flag=True, help="List Generic Testbench modules only.")
8✔
415
@opt_local
8✔
416
@click.option("--base", "-A", default=False, is_flag=True, help="Show Base Classes.")
8✔
417
@click.option("--filepath", "-f", default=False, is_flag=True, help="Show File Path.")
8✔
418
@click.option("--abs-filepath", "-F", default=False, is_flag=True, help="Show Absolute File Path.")
8✔
419
@opt_tag
8✔
420
@pass_ctx
8✔
421
def ls(  # noqa: C901
8✔
422
    ctx,
423
    path=None,
424
    tops=None,
425
    names=False,
426
    top=None,
427
    tb=None,
428
    local=None,
429
    generic_tb=False,
430
    tag=None,
431
    base=False,
432
    filepath=False,
433
    abs_filepath=False,
434
):
435
    """List Modules."""
436
    with ctx.console.status("Searching"):
8✔
437
        infos = find(path, patterns=tops or ["*"], local=local)
8✔
438
    if top is not None:
8✔
439
        infos = [info for info in infos if info.is_top == top]
8✔
440
    if tb is not None:
8✔
441
        infos = [info for info in infos if bool(info.tb) == tb]
8✔
442
    if generic_tb:
8✔
443
        infos = [info for info in infos if info.tb == "Generic"]
8✔
444
    if tag:
8✔
445
        filter_ = namefilter(tag)
8✔
446
        infos = [info for info in infos if any(filter_(tag) for tag in info.tags)]
8✔
447

448
    def fill_row(row, info):
8✔
449
        if base:
8✔
450
            row.append(info.modbasecls.__name__)
8✔
451
        if filepath:
8✔
452
            row.append(str(relative(info.filepath)))
8✔
453
        if abs_filepath:
8✔
454
            row.append(str(info.filepath))
8✔
455

456
    if names:
8✔
457
        for info in infos:
8✔
458
            row = [info.topmodref]
8✔
459
            fill_row(row, info)
8✔
460
            print(*row)
8✔
461
    else:
462
        table = Table(expand=filepath or abs_filepath)
8✔
463
        table.add_column("Reference")
8✔
464
        table.add_column("Top", justify="center")
8✔
465
        table.add_column("Tb ", justify="center")
8✔
466
        table.add_column("Tags")
8✔
467
        if base:
8✔
468
            table.add_column("Bases on", justify="right")
8✔
469
        if filepath:
8✔
470
            table.add_column("Filepath")
×
471
        if abs_filepath:
8✔
472
            table.add_column("Absolute Filepath")
×
473
        for info in infos:
8✔
474
            row = [
8✔
475
                str(info.topmodref),
476
                "X" if info.is_top else "",
477
                "X" if info.tb else "",
478
                ",".join(sorted(info.tags)),
479
            ]
480
            fill_row(row, info)
8✔
481
            table.add_row(*row)
8✔
482
        ctx.console.print(table)
8✔
483

484

485
@ucdp.command(
8✔
486
    help=f"""
487
Load Data Model and Module Information.
488

489
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
490
"""
491
)
492
@arg_tops
8✔
493
@opt_path
8✔
494
@opt_local
8✔
495
@click.option("--top", "-t", default=None, is_flag=True, help="List loadable top modules only.")
8✔
496
@click.option("--sub", "-S", default=False, is_flag=True, help="Show Submodules.")
8✔
497
@pass_ctx
8✔
498
def modinfo(ctx, tops, path, local, top, sub):
8✔
499
    """Module Information."""
500
    sep = ""
8✔
501
    for info in find(path, patterns=tops, local=local, is_top=top):
8✔
502
        try:
8✔
503
            top = load_top(ctx, info.topmodref, path, quiet=True)
8✔
504
        except Exception as exc:
8✔
505
            LOGGER.warning(str(exc))
8✔
506
            continue
8✔
507
        print(sep + top.mod.get_info(sub=sub))
8✔
508
        sep = "\n\n"
8✔
509

510

511
@ucdp.command(
8✔
512
    help=f"""
513
Load Data Model and Show Module Overview.
514

515
TOP: Top Module. {PAT_TOPMODREF}. Environment Variable 'UCDP_TOP'
516
"""
517
)
518
@arg_top
8✔
519
@opt_path
8✔
520
@click.option("--minimal", "-m", default=False, is_flag=True, help="Skip modules without specific details")
8✔
521
@opt_filepath
8✔
522
@opt_tag
8✔
523
@pass_ctx
8✔
524
def overview(ctx, top, path, minimal=False, file=None, tag=None):
8✔
525
    """Overview."""
526
    # Load quiet, otherwise stdout is messed-up
527
    top = load_top(ctx, top, path, quiet=True)
8✔
528
    data = {"minimal": minimal, "tags": tag}
8✔
529
    render_generate(top, [PATH / "ucdp-templates" / "overview.txt.mako"], genfile=file, data=data, no_stat=True)
8✔
530

531

532
@ucdp.group(context_settings={"help_option_names": ["-h", "--help"]})
8✔
533
def info():
8✔
534
    """Information."""
535

536

537
@info.command()
8✔
538
@pass_ctx
8✔
539
def examples(ctx):
8✔
540
    """Path to Examples."""
541
    examples_path = Path(__file__).parent / "examples"
8✔
542
    print(str(examples_path))
8✔
543

544

545
@info.command()
8✔
546
@opt_path
8✔
547
@pass_ctx
8✔
548
def template_paths(ctx, path):
8✔
549
    """Template Paths."""
550
    makolator = get_makolator(paths=path)
8✔
551
    for template_path in makolator.config.template_paths:
8✔
552
        print(str(template_path))
8✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc