Zum Inhalt

Documentação da API#

Changelog Module.

Changelog #

Changelog class.

Source code in incolume\py\changelog\changelog.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
class Changelog:
    """Changelog class."""

    def __init__(
        self: Changelog,
        file_output: Path | str = '',
        url_compare: str = '',
        *,
        reverse: bool = True,
        **kwargs: str,
    ) -> None:
        """Initialize from Changelog class.

        Args:
            file_output: The output file of changelog.
            reverse: reverse to the last update be the first.
            url_compare: Url to compare.
            url_convetional_commit(str): Url of convetional commit.
            url_keepachangelog(str): Url of keep a changelog.
            url_principal(str): Url principal do projeto.
            url_semver(str): Url of semantic version.
            **kwargs: Anyone of the positional items.

        Return:
            None

        """
        self.repo: git.Repo | None = None
        self.file_output = (
            file_output or kwargs.get('file_output') or Path('CHANGELOG.md')
        )
        self.url_compare = url_compare or kwargs.get('url_compare')
        self.reverse = reverse
        self.url_principal = kwargs.get(
            'url_pricipal',
            'https://gitlab.com/development-incolume/incolume.py.changelog',
        )
        self.url_keepachangelog = kwargs.get(
            'url_keepachangelog',
            'https://keepachangelog.com/en/1.0.0/',
        )
        self.url_semver = kwargs.get(
            'url_semver',
            'https://semver.org/spec/v2.0.0.html',
        )
        self.url_convetional_commit = kwargs.get(
            'url_convetional_commit',
            'https://www.conventionalcommits.org/pt-br/v1.0.0/',
        )

    @staticmethod
    def iter_logs(
        content: list[tuple[str, dict[str, Any]]],
        *,
        linked: bool = True,
    ) -> list[str]:
        r"""Iterador de registros git.

        Args:
            content: Content register in git.
            linked: If has link.

        Return:
            A list with the version, date and a message.

        Raises:
            None

        Examples:
            >>> Changelog.iter_logs(
            ...     content=[
            ...         (
            ...             '1.0.0a5',
            ...             {
            ...                 'date': '2023-12-21',
            ...                 'key': '1.0.0a5',
            ...                 'messages': {
            ...                     'Added': [
            ...                         'New function',
            ...                         'One more new function.',
            ...                     ],
            ...                     'Fixed': ['A bug of connection.'],
            ...                 },
            ...             },
            ...         )
            ...     ],
            ...     linked=False,
            ... )
            ['\n\n## 1.0.0a5\t — \t2023-12-21:', '\n### Added', '\n  - New function;', '\n  - One more new function.;', '\n### Fixed', '\n  - A bug of connection.;']

        """  # ruff: ignore[line-too-long]
        result = []
        for _, entrada in content:
            logging.debug(entrada)
            if linked:
                result.append(
                    f'\n\n## [{entrada["key"]}]\t — '
                    f'\t{entrada["date"]}:',
                )
            else:
                result.append(
                    f'\n\n## {entrada["key"]}\t — \t{entrada["date"]}:',
                )

            for label, msgs in entrada['messages'].items():
                result.append(f'\n### {label.capitalize()}')
                for msg in msgs:
                    frase = msg.strip()
                    frase = frase[0].upper() + frase[1:]
                    result.append(f'\n  - {frase};')
        return result

    def _header(self: Changelog) -> list[str]:
        r"""Header of changelog file.

        Return:
            Return a list with a header of changelog file.

        Raises:
            None

        Examples:
            >> Changelog()._header()
            ['# CHANGELOG\n\n\n', 'All notable changes to this project', ' will be documented in this file.\n\n', 'The format is based on ', '[Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ', 'this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and [Conventional Commit](https://www.conventionalcommits.org/pt-br/v1.0.0/).\n\n', 'This file was automatically generated for', ' [incolume.py.changelog](https://gitlab.com/development-incolume/incolume.py.changelog/-/tree/0.15.0a1)', '\n\n---\n']

            >> Changelog(url_keepachangelog='https://keepachangelog.com/en/2.0.0/', url_semver='https://semver.org/spec/v1.0.0.html')._header()
            ['# CHANGELOG\n\n\n', 'All notable changes to this project', ' will be documented in this file.\n\n', 'The format is based on ', '[Keep a Changelog](https://keepachangelog.com/en/2.0.0/), ', 'this project adheres to [Semantic Versioning](https://semver.org/spec/v1.0.0.html) and [Conventional Commit](https://www.conventionalcommits.org/pt-br/v1.0.0/).\n\n', 'This file was automatically generated for', ' [incolume.py.changelog](https://gitlab.com/development-incolume/incolume.py.changelog/-/tree/0.15.0a1)', '\n\n---\n']

        """  # ruff: ignore[line-too-long]
        return [
            '# CHANGELOG\n\n\n',
            'All notable changes to this project',
            ' will be documented in this file.\n\n',
            'The format is based on ',
            f'[Keep a Changelog]({self.url_keepachangelog}), ',
            (
                'this project adheres to '
                f'[Semantic Versioning]({self.url_semver}) '
                'and [Conventional Commit]('
                f'{self.url_convetional_commit}).\n\n'
            ),
            'This file was automatically generated for',
            f' [{__title__}]({self.url_principal}/-/tree/{__version__})',
            '\n\n---\n',
        ]

    def _footer(  # ruff:ignore[no-self-use]
        self: Changelog,
        content: list[tuple[str, dict[str, Any]]],
        content_formated: list[str],
        **kwargs: str,
    ) -> list[str]:
        r"""Footer of changelog file.

        Args:
            content: Content of changelog's footer
            content_formated: Content formated of changelog's footer
            urlcompare: Url to compare.
            **kwargs: Anyone of the positional items.

        Return:
            Return a list with a footer of changelog file.

        Raises:
            None

        Examples:
            >>> Changelog()._footer(
            ...     [
            ...         (
            ...             '1.0.2',
            ...             {
            ...                 'key': '1.0.2',
            ...                 'messages': {'Added': ['New function']},
            ...             },
            ...         ),
            ...         (
            ...             '1.0.1',
            ...             {
            ...                 'key': '1.0.1',
            ...                 'messages': {'Added': ['Other New Function']},
            ...             },
            ...         ),
            ...     ],
            ...     [],
            ... )
            ['\n\n---\n\n', '[1.0.2]: https://github.com/development-incolume/incolume.py.changelog/-/compare/1.0.1...1.0.2\n']

        """
        urlcompare = (
            kwargs.get('urlcompare')
            or 'https://github.com/development-incolume/'
            'incolume.py.changelog/-/compare'
        )
        logging.debug('urlcompare=%s', urlcompare)
        content_formated.append('\n\n---\n\n')
        y: dict[str, Any] = {}
        for _, x in content[::-1]:
            if y:
                content_formated.append(
                    f'[{x["key"]}]: {urlcompare}/{y["key"]}...{x["key"]}\n',
                )
            y = x
        return content_formated

    def __call__(
        self: Changelog,
        *args: str,
        **kwargs: str,
    ) -> Changelog:  # pragma: no cover
        """Call class.

        Args:
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.

        Return:
            Return a instance of Changelog class.

        Raises:
            None

        Examples:
            >>> Changelog().repo

        """
        logging.debug('args: %s; kwargs: %s', args, kwargs)
        self.repo = git.Repo()
        return self

__call__(*args, **kwargs) #

Call class.

Parameters:

Name Type Description Default
*args str

Variable length argument list.

()
**kwargs str

Arbitrary keyword arguments.

{}
Return

Return a instance of Changelog class.

Examples:

>>> Changelog().repo
Source code in incolume\py\changelog\changelog.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
def __call__(
    self: Changelog,
    *args: str,
    **kwargs: str,
) -> Changelog:  # pragma: no cover
    """Call class.

    Args:
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.

    Return:
        Return a instance of Changelog class.

    Raises:
        None

    Examples:
        >>> Changelog().repo

    """
    logging.debug('args: %s; kwargs: %s', args, kwargs)
    self.repo = git.Repo()
    return self

__init__(file_output='', url_compare='', *, reverse=True, **kwargs) #

Initialize from Changelog class.

Parameters:

Name Type Description Default
file_output Path | str

The output file of changelog.

''
reverse bool

reverse to the last update be the first.

True
url_compare str

Url to compare.

''
url_convetional_commit str

Url of convetional commit.

required
url_keepachangelog str

Url of keep a changelog.

required
url_principal str

Url principal do projeto.

required
url_semver str

Url of semantic version.

required
**kwargs str

Anyone of the positional items.

{}
Return

None

Source code in incolume\py\changelog\changelog.py
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def __init__(
    self: Changelog,
    file_output: Path | str = '',
    url_compare: str = '',
    *,
    reverse: bool = True,
    **kwargs: str,
) -> None:
    """Initialize from Changelog class.

    Args:
        file_output: The output file of changelog.
        reverse: reverse to the last update be the first.
        url_compare: Url to compare.
        url_convetional_commit(str): Url of convetional commit.
        url_keepachangelog(str): Url of keep a changelog.
        url_principal(str): Url principal do projeto.
        url_semver(str): Url of semantic version.
        **kwargs: Anyone of the positional items.

    Return:
        None

    """
    self.repo: git.Repo | None = None
    self.file_output = (
        file_output or kwargs.get('file_output') or Path('CHANGELOG.md')
    )
    self.url_compare = url_compare or kwargs.get('url_compare')
    self.reverse = reverse
    self.url_principal = kwargs.get(
        'url_pricipal',
        'https://gitlab.com/development-incolume/incolume.py.changelog',
    )
    self.url_keepachangelog = kwargs.get(
        'url_keepachangelog',
        'https://keepachangelog.com/en/1.0.0/',
    )
    self.url_semver = kwargs.get(
        'url_semver',
        'https://semver.org/spec/v2.0.0.html',
    )
    self.url_convetional_commit = kwargs.get(
        'url_convetional_commit',
        'https://www.conventionalcommits.org/pt-br/v1.0.0/',
    )

iter_logs(content, *, linked=True) staticmethod #

Iterador de registros git.

Parameters:

Name Type Description Default
content list[tuple[str, dict[str, Any]]]

Content register in git.

required
linked bool

If has link.

True
Return

A list with the version, date and a message.

Examples:

>>> Changelog.iter_logs(
...     content=[
...         (
...             '1.0.0a5',
...             {
...                 'date': '2023-12-21',
...                 'key': '1.0.0a5',
...                 'messages': {
...                     'Added': [
...                         'New function',
...                         'One more new function.',
...                     ],
...                     'Fixed': ['A bug of connection.'],
...                 },
...             },
...         )
...     ],
...     linked=False,
... )
['\n\n## 1.0.0a5\t — \t2023-12-21:', '\n### Added', '\n  - New function;', '\n  - One more new function.;', '\n### Fixed', '\n  - A bug of connection.;']
Source code in incolume\py\changelog\changelog.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
@staticmethod
def iter_logs(
    content: list[tuple[str, dict[str, Any]]],
    *,
    linked: bool = True,
) -> list[str]:
    r"""Iterador de registros git.

    Args:
        content: Content register in git.
        linked: If has link.

    Return:
        A list with the version, date and a message.

    Raises:
        None

    Examples:
        >>> Changelog.iter_logs(
        ...     content=[
        ...         (
        ...             '1.0.0a5',
        ...             {
        ...                 'date': '2023-12-21',
        ...                 'key': '1.0.0a5',
        ...                 'messages': {
        ...                     'Added': [
        ...                         'New function',
        ...                         'One more new function.',
        ...                     ],
        ...                     'Fixed': ['A bug of connection.'],
        ...                 },
        ...             },
        ...         )
        ...     ],
        ...     linked=False,
        ... )
        ['\n\n## 1.0.0a5\t — \t2023-12-21:', '\n### Added', '\n  - New function;', '\n  - One more new function.;', '\n### Fixed', '\n  - A bug of connection.;']

    """  # ruff: ignore[line-too-long]
    result = []
    for _, entrada in content:
        logging.debug(entrada)
        if linked:
            result.append(
                f'\n\n## [{entrada["key"]}]\t — '
                f'\t{entrada["date"]}:',
            )
        else:
            result.append(
                f'\n\n## {entrada["key"]}\t — \t{entrada["date"]}:',
            )

        for label, msgs in entrada['messages'].items():
            result.append(f'\n### {label.capitalize()}')
            for msg in msgs:
                frase = msg.strip()
                frase = frase[0].upper() + frase[1:]
                result.append(f'\n  - {frase};')
    return result

changelog_body(content, content_formated, **kwargs) #

Body of changelog file.

Parameters:

Name Type Description Default
content list[tuple[str, dict[str, Any]]]

Content of changelog.

required
content_formated list[str]

Content formated of changelog.

required
**kwargs str

Anyone of the positional items.

{}
Return

Return a list with a content of changelog's body.

Examples:

changelog_body([('1.0.1', {'Added': 'New function'}), ('1.0.2', {'Added': 'New other function'})], content_formated=[]) ['[1.0.1]', 'Added', 'New Function']

Source code in incolume\py\changelog\changelog.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def changelog_body(
    content: list[tuple[str, dict[str, Any]]],
    content_formated: list[str],
    **kwargs: str,
) -> list[str]:
    """Body of changelog file.

    Args:
        content: Content of changelog.
        content_formated: Content formated of changelog.
        **kwargs: Anyone of the positional items.

    Return:
        Return a list with a content of changelog's body.

    Raises:
        None

    Examples:
        >> changelog_body([('1.0.1', {'Added': 'New function'}), ('1.0.2', {'Added': 'New other function'})], content_formated=[])
        ['[1.0.1]', 'Added', 'New Function']

    """  # ruff: ignore[line-too-long]
    logging.debug(kwargs)
    content_formated.extend(Changelog.iter_logs(content[:-1]))
    content_formated.extend(Changelog.iter_logs(content[-1:], linked=False))
    return content_formated

Footer of changelog file.

Parameters:

Name Type Description Default
content list[tuple[str, dict[str, Any]]]

Content of changelog's footer

required
content_formated list[str]

Content formated of changelog's footer

required
urlcompare

Url to compare.

required
**kwargs str

Anyone of the positional items.

{}
Return

Return a list with a footer of changelog file.

Examples:

>>> changelog_footer(
...     [
...         (
...             '1.0.2',
...             {
...                 'key': '1.0.2',
...                 'messages': {'Added': ['New function']},
...             },
...         ),
...         (
...             '1.0.1',
...             {
...                 'key': '1.0.1',
...                 'messages': {'Added': ['Other New Function']},
...             },
...         ),
...     ],
...     [],
... )
['\n\n---\n\n', '[1.0.2]: https://github.com/development-incolume/incolume.py.changelog/-/compare/1.0.1...1.0.2\n']
Source code in incolume\py\changelog\changelog.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def changelog_footer(
    content: list[tuple[str, dict[str, Any]]],
    content_formated: list[str],
    **kwargs: str,
) -> list[str]:
    r"""Footer of changelog file.

    Args:
        content: Content of changelog's footer
        content_formated: Content formated of changelog's footer
        urlcompare: Url to compare.
        **kwargs: Anyone of the positional items.

    Return:
        Return a list with a footer of changelog file.

    Raises:
        None

    Examples:
        >>> changelog_footer(
        ...     [
        ...         (
        ...             '1.0.2',
        ...             {
        ...                 'key': '1.0.2',
        ...                 'messages': {'Added': ['New function']},
        ...             },
        ...         ),
        ...         (
        ...             '1.0.1',
        ...             {
        ...                 'key': '1.0.1',
        ...                 'messages': {'Added': ['Other New Function']},
        ...             },
        ...         ),
        ...     ],
        ...     [],
        ... )
        ['\n\n---\n\n', '[1.0.2]: https://github.com/development-incolume/incolume.py.changelog/-/compare/1.0.1...1.0.2\n']

    """
    urlcompare = (
        kwargs.get('urlcompare')
        or 'https://github.com/development-incolume/'
        'incolume.py.changelog/-/compare'
    )
    urlcompare.rstrip('/')
    logging.debug('urlcompare=%s', urlcompare)
    content_formated.append('\n\n---\n\n')
    y: dict[str, Any] = {}
    for _, x in content[::-1]:
        if y:
            content_formated.append(
                f'[{x["key"]}]: {urlcompare}/{y["key"]}...{x["key"]}\n',
            )
        y = x
    return content_formated

changelog_header(**kwargs) #

Header of changelog file.

Parameters:

Name Type Description Default
url_keepachangelog str

url for keep changelog.

required
url_semver str

url for semantic version.

required
url_convetional_commit str

url for convetional commit.

required
url_project str

url principal for project.

required
kwargs str

Anyone of the others items.

{}
Return

Return a list with a header of changelog file.

Examples:

changelog_header() ['# CHANGELOG\n\n\n', 'All notable changes to this project', ' will be documented in this file.\n\n', 'The format is based on ', 'Keep a Changelog, ', 'this project adheres to Semantic Versioning and Conventional Commit.\n\n', 'This file was automatically generated for', ' incolume.py.changelog', '\n\n---\n']

changelog_header(url_keepachangelog='https://keepachangelog.com/en/2.0.0/', url_semver='https://semver.org/spec/v1.0.0.html') ['# CHANGELOG\n\n\n', 'All notable changes to this project', ' will be documented in this file.\n\n', 'The format is based on ', 'Keep a Changelog, ', 'this project adheres to Semantic Versioning and Conventional Commit.\n\n', 'This file was automatically generated for', ' incolume.py.changelog', '\n\n---\n']

Source code in incolume\py\changelog\changelog.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def changelog_header(
    **kwargs: str,
) -> list[str]:
    r"""Header of changelog file.

    Args:
        url_keepachangelog (str): url for keep changelog.
        url_semver (str): url for semantic version.
        url_convetional_commit (str): url for convetional commit.
        url_project (str): url principal for project.
        kwargs: Anyone of the others items.

    Return:
        Return a list with a header of changelog file.

    Raises:
        None

    Examples:
        >> changelog_header()
        ['# CHANGELOG\n\n\n', 'All notable changes to this project', ' will be documented in this file.\n\n', 'The format is based on ', '[Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ', 'this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and [Conventional Commit](https://www.conventionalcommits.org/pt-br/v1.0.0/).\n\n', 'This file was automatically generated for', ' [incolume.py.changelog](https://github.com/development-incolume/incolume.py.changelog/-/tree/0.15.0a1)', '\n\n---\n']

        >> changelog_header(url_keepachangelog='https://keepachangelog.com/en/2.0.0/', url_semver='https://semver.org/spec/v1.0.0.html')
        ['# CHANGELOG\n\n\n', 'All notable changes to this project', ' will be documented in this file.\n\n', 'The format is based on ', '[Keep a Changelog](https://keepachangelog.com/en/2.0.0/), ', 'this project adheres to [Semantic Versioning](https://semver.org/spec/v1.0.0.html) and [Conventional Commit](https://www.conventionalcommits.org/pt-br/v1.0.0/).\n\n', 'This file was automatically generated for', ' [incolume.py.changelog](https://github.com/development-incolume/incolume.py.changelog/-/tree/0.15.0a1)', '\n\n---\n']

    """  # ruff: ignore[line-too-long]
    url_keepachangelog = kwargs.get(
        'url_keepachangelog',
        'https://keepachangelog.com/en/1.0.0/',
    )
    url_semver = kwargs.get(
        'url_semver',
        'https://semver.org/spec/v2.0.0.html',
    )
    url_convetional_commit = kwargs.get(
        'url_convetional_commit',
        'https://www.conventionalcommits.org/pt-br/v1.0.0/',
    )
    url_project = kwargs.get(
        'url_project',
        'https://github.com/development-incolume/incolume.py.changelog',
    )
    return [
        '# CHANGELOG\n\n\n',
        'All notable changes to this project',
        ' will be documented in this file.\n\n',
        'The format is based on ',
        f'[Keep a Changelog]({url_keepachangelog}), ',
        (
            'this project adheres to '
            f'[Semantic Versioning]({url_semver}) '
            f'and [Conventional Commit]({url_convetional_commit}).\n\n'
        ),
        'This file was automatically generated for',
        f' [{__title__}]({url_project}/tree/{__version__})',
        '\n\n---\n',
    ]

changelog_messages(*, text, start=None, end=None, **kwargs) #

Changelog messages sort and classify.

Parameters:

Name Type Description Default
end str | int | None

End of Message

None
start str | int | None

Start of Message

None
text str

Changelog's message

required
**kwargs str

Anyone of the positional items.

{}
Return

return a list of tuples with a changelog menssage per line.

Examples:

changelog_messages('1.0.0 Security: a;b;c;' 'Removed: 1;2;3; Changed: a;b;c;d;e;' 'Fixed: http://example.com; http://httpbin.com;' 'Deprecated: 1;2;3;a;s;b; Added: a1;a2;a3.', '1.1.0 Removed: 1;2' 'Added: g;u') [('1.0.0',{'key': '1.0.0', 'date': '2023-12-21', 'messages': { 'Added': ['a1', 'a2', 'a3.'], 'Changed': ['a', 'b', 'c', 'd', 'e'], 'Deprecated': ['1', '2', '3', 'a', 's', 'b'], 'Fixed': ['http://example.com', 'http://httpbin.com',], 'Removed': ['1', '2', '3'], 'Security': ['a', 'b', 'c'],},},), ('1.1.0',{'key': '1.1.0', 'date': '2023-12-21', 'messages': { 'Added': ['g', 'u'], 'Removed: ['1', '2'],},},)]

Source code in incolume\py\changelog\changelog.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def changelog_messages(
    *,
    text: str,
    start: str | int | None = None,
    end: str | int | None = None,
    **kwargs: str,
) -> list[tuple[str, dict[str, Any]]]:
    """Changelog messages sort and classify.

    Args:
        end: End of Message
        start: Start of Message
        text: Changelog's message
        **kwargs: Anyone of the positional items.

    Return:
        return a list of tuples with a changelog menssage per line.

    Raises:
        None

    Examples:
        >> changelog_messages('1.0.0 Security: a;b;c;'
        'Removed: 1;2;3; Changed: a;b;c;d;e;'
        'Fixed: http://example.com; http://httpbin.com;'
        'Deprecated: 1;2;3;a;s;b; Added: a1;a2;a3.',
        '1.1.0 Removed: 1;2'
        'Added: g;u')
        [('1.0.0',{'key': '1.0.0', 'date': '2023-12-21',
        'messages': {
        'Added': ['a1', 'a2', 'a3.'],
        'Changed': ['a', 'b', 'c', 'd', 'e'],
        'Deprecated': ['1', '2', '3', 'a', 's', 'b'],
        'Fixed': ['http://example.com', 'http://httpbin.com',],
        'Removed': ['1', '2', '3'],
        'Security': ['a', 'b', 'c'],},},),
        ('1.1.0',{'key': '1.1.0', 'date': '2023-12-21',
        'messages': {
        'Added': ['g', 'u'],
        'Removed: ['1', '2'],},},)]

    """
    logging.debug('parameters: (%s %s %s %s)', text, start, end, kwargs)
    lang: str = kwargs.get('lang', '')
    if start is not None:
        start = int(start)
    if end is not None:
        end = int(end)

    records = []
    for msg in text.strip().splitlines()[start:end]:
        logging.debug('msg=%s', msg)
        record = msg_classify(msg=msg, lang=lang)
        logging.debug('record=%s', record)
        records.append((record['key'], record))
    logging.debug('type return %s=%s', inspect.stack()[0][3], type(records))
    logging.debug('return %s=%s', inspect.stack()[0][3], records)
    return records

changelog_write(*, content, **kwargs) #

Write CHANGELOG.md file formatted.

Parameters:

Name Type Description Default
changelog_file

Path of changelog file.

required
content list[tuple[str, dict[str, Any]]]

Content to write the changelog

required
**kwargs str

Anyone of the positional items.

{}
Return

True if success.

Examples:

changelog_write(['Added: funcionalidade nova.']) True

Source code in incolume\py\changelog\changelog.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
def changelog_write(
    *,
    content: list[tuple[str, dict[str, Any]]],
    **kwargs: str,
) -> bool:
    """Write CHANGELOG.md file formatted.

    Args:
        changelog_file: Path of changelog file.
        content: Content to write the changelog
        **kwargs: Anyone of the positional items.

    Return:
        True if success.

    Raises:
        None

    Examples:
        >> changelog_write(['Added: funcionalidade nova.'])
        True

    """
    changelog_file = Path(kwargs.pop('changelog_file', '') or CHANGELOG_FILE)
    changelog_file.parent.mkdir(parents=True, exist_ok=True)
    logging.debug('changelog_file=%s', changelog_file)

    content_formated = changelog_header(**kwargs)
    content_formated = changelog_body(content, content_formated, **kwargs)
    content_formated = changelog_footer(content, content_formated, **kwargs)

    content_formated = [
        texto.encode(
            'iso-8859-1' if sys.platform.startswith('win') else 'utf-8'
        ).decode('utf-8')
        for texto in content_formated
    ]

    with changelog_file.open('w', encoding='utf-8') as f:
        f.writelines(content_formated)
    return True

generate_changelog_config_model(**kwargs) #

Generate a model of changelog configuration file.

Source code in incolume\py\changelog\changelog.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def generate_changelog_config_model(**kwargs: str | Path) -> Path:
    """Generate a model of changelog configuration file."""
    fl = kwargs.pop('conf_file', None) or 'changelog.toml.sample'
    conf_file = Path(fl)
    if conf_file.exists():
        logging.warning(
            'Configuration file already exists: %s',
            conf_file,
        )
        return conf_file
    ic(kwargs)  # type: ignore [reportPrivateUsage]
    changelog_conf_fl['settings'].update(**kwargs)
    ic(changelog_conf_fl)  # type: ignore [reportPrivateUsage]
    with conf_file.open('w', encoding='utf-8') as f:
        toml.dump(changelog_conf_fl, f)
    return conf_file

get_os_command(key) #

Generate command to git tag according OS.

Parameters:

Name Type Description Default
key str

Tag with semantic version.

required
Return

A string with the command referring to the OS.

Examples:

In Windows:

get_os_command('1.0.0') 'git show -s --format=%cs 1.0.0^^{commit} --'

In Linux:

get_os_command('1.0.0') 'git show -s --format=%cs 1.0.0^{commit} --'

Source code in incolume\py\changelog\changelog.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def get_os_command(key: str) -> str:
    """Generate command to git tag according OS.

    Args:
        key: Tag with semantic version.

    Return:
        A string with the command referring to the OS.

    Raises:
        None

    Examples:
        In Windows:
        >> get_os_command('1.0.0')
        'git show -s --format=%cs 1.0.0^^{commit} --'

        In Linux:
        >> get_os_command('1.0.0')
        'git show -s --format=%cs 1.0.0^{commit} --'

    """
    cmd_supply = {
        'win': r'^^{commit} --',
    }
    cmd = rf'git show -s --format=%cs {key}'
    os_id = sys.platform.casefold()[:3]
    cmd += cmd_supply.get(os_id, r'^{commit} --')

    logging.debug(cmd)
    return cmd

msg_classify(msg, lang='') #

Classify and sort one record for messages git tag -n.

Parameters:

Name Type Description Default
lang str

Language of command.

''
msg str

Message of command.

required
**kwargs

Anyone of the positional items.

required
Return

A dictionary with the version, date and a message.

Raises:

Type Description
ValueError

If lang selected don't have support.

Examples:

msg_classify('1.0.0 Adicionado: Nova funcionalidade.', 'pt-BR')

msg_classify('Corregido: corrección de error.', 'es-AR') ValueError: es-AR not suported! Use en-US, pt-BR

Source code in incolume\py\changelog\changelog.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def msg_classify(msg: str, lang: str = '') -> dict[str, Any]:
    """Classify and sort one record for messages git tag -n.

    Args:
        lang: Language of command.
        msg: Message of command.
        **kwargs: Anyone of the positional items.

    Return:
        A dictionary with the version, date and a message.

    Raises:
        ValueError: If lang selected don't have support.

    Examples:
        >> msg_classify('1.0.0 Adicionado: Nova funcionalidade.', 'pt-BR')
        {'key': '0.1.0', 'date': '2023-12-18', 'messages': {'Added': ['Nova funcionalidade.']}

        >> msg_classify('Corregido: corrección de error.', 'es-AR')
        ValueError: es-AR not suported! Use en-US, pt-BR

    """  # ruff: ignore[line-too-long]
    logging.debug(lang)
    suport_lang: dict[str, Mapping[str, str]] = {
        'en-US': {
            'Added': 'Added',
            'Changed': 'Changed',
            'Deprecated': 'Deprecated',
            'Removed': 'Removed',
            'Fixed': 'Fixed',
            'Security': 'Security',
        },
        'pt-BR': {
            'Adicionado': 'Added',
            'Modificado': 'Changed',
            'Obsoleto': 'Deprecated',
            'Removido': 'Removed',
            'Corrigido': 'Fixed',
            'Segurança': 'Security',
        },
    }
    suport_lang.update(
        {'all': {k: v for d in suport_lang.values() for k, v in d.items()}},
    )
    if lang not in suport_lang:
        logging.info(
            ValueError(
                f'Language {lang} not suported! Use {suport_lang.keys()}',
            ),
        )
        lang = 'all'

    key, msg = msg.split(maxsplit=1)
    cmd = get_os_command(key)
    date = subprocess.getoutput(cmd).strip()
    logging.debug(date)

    logging.debug('key=%s; date=%s; msg=%s', key, date, msg)
    selected_lang = suport_lang.get(lang, suport_lang['all'])
    regex: str = rf'({"|".join(selected_lang.keys())})\s?:'

    txt = re.sub(
        regex,
        r'§§\1§:',
        msg,
        flags=re.IGNORECASE,
    )
    logging.debug('txt=%s', txt)
    dct: dict[str, Any] = {}
    for i, j in sorted(
        x.strip().rstrip(';').split('§:') for x in txt.strip().split('§§') if x
    ):
        dct.setdefault(selected_lang[i.capitalize()], []).extend(
            j.strip().split(';'),
        )

    return {'key': key, 'date': date, 'messages': dct}

run() #

Examples ran.

Return

None

Source code in incolume\py\changelog\changelog.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
def run() -> None:
    """Examples ran.

    Return:
        None

    """
    msg = subprocess.getoutput('git tag -n').splitlines()[-14]
    logging.debug(msg)
    logging.debug('msg_classify=%s', msg_classify(msg=msg))

    msg = subprocess.getoutput('git tag -n')
    result = changelog_messages(text=msg)

    logging.debug('result=%s', result)
    logging.debug('type(result)=%s', type(result))
    result = sorted(result, reverse=True, key=key_versions_2_sort)
    logging.debug('result = %s; result type = %s', result, type(result))

    changelog_write(content=result)
    update_changelog()
    logging.info(
        msg_classify(
            '0.1.0           added: Projeto emancipado de '
            'https://gitlab.com/development-incolume/incolumepy.utils',
        ),
    )

update_changelog(changelog_file='', *, reverse=True, **kwargs) #

Update Changelog.md file.

Parameters:

Name Type Description Default
changelog_file str

changelog full filename.

''
reverse bool

reverse to the last update be the first.

True
urlcompare str

Url to compare.

required
**kwargs str

Anyone of the positional items.

{}
Return

True if success

Examples:

update_changelog() True update_changelog(changelog_file='/tmp/CHANGELOG.md') True update_changelog(changelog_file=Path('CHANGELOG.md'), urlcompare="https://github.com/development-incolume/" "incolume.py.changelog/-/compare") True

Source code in incolume\py\changelog\changelog.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def update_changelog(
    changelog_file: str = '',
    *,
    reverse: bool = True,
    **kwargs: str,
) -> bool:
    """Update Changelog.md file.

    Args:
        changelog_file: changelog full filename.
        reverse: reverse to the last update be the first.
        urlcompare(str): Url to compare.
        **kwargs: Anyone of the positional items.

    Return:
        True if success

    Raises:
        None

    Examples:
        >> update_changelog()
        True
        >> update_changelog(changelog_file='/tmp/CHANGELOG.md')
        True
        >> update_changelog(changelog_file=Path('CHANGELOG.md'),
        urlcompare="https://github.com/development-incolume/"
        "incolume.py.changelog/-/compare")
        True

    """
    logging.debug('argumentos=%s,%s,%s', changelog_file, reverse, kwargs)
    urlcompare: str = (
        kwargs.pop('urlcompare', '')
        or 'https://github.com/development-incolume'
        '/incolume.py.changelog/-/compare'
    )
    content: str = kwargs.pop('content', subprocess.getoutput('git tag -n'))
    logging.info('registros encontrados ..')
    logging.debug('content=%s', content)

    return changelog_write(
        content=sorted(
            changelog_messages(
                text=content,
                start=kwargs.get('start'),
                end=kwargs.get('end'),
            ),
            reverse=reverse,
            key=key_versions_2_sort,
        ),
        urlcompare=urlcompare,
        changelog_file=changelog_file,
        **kwargs,
    )

CLI - Command Line Interface module.

changelog(file_changelog, url='', *, reverse=True, generate_config=False) #

Operacionaliza uma interface CLI para módulo incolume.py.changelog.

Parameters:

Name Type Description Default
file_changelog str

changelog full filename.

required
url str

url compare from repository of project.

''
reverse bool

Reverse order of records.

True
generate_config bool

Generate configuration file for changelog.

False
Return

True if success

Raises:

Type Description
ValueError

When there is not git tag records.

Source code in incolume\py\changelog\cli.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@click.command()
@click.argument(
    'file_changelog',
    type=click.STRING,
    default=config.pop('file', 'CHANGELOG.md'),
)
@click.option(
    '--url',
    '-u',
    default=config.pop(
        'url_compare',
        URL_COMPARE,
    ),
    help='Url compare from repository of project.',
)
@click.option(
    '--reverse',
    '-r',
    default=config.pop('reverse', False),
    is_flag=True,
    help='Reverse order of records.',
)
@click.option(
    '--generate-config',
    '-g',
    is_flag=True,
    help='Generate configure file for changelog.',
)
def changelog(
    file_changelog: str,
    url: str = '',
    *,
    reverse: bool = True,
    generate_config: bool = False,
) -> None:
    """Operacionaliza uma interface CLI para módulo incolume.py.changelog.

    Args:
        file_changelog:  changelog full filename.
        url: url compare from repository of project.
        reverse: Reverse order of records.
        generate_config: Generate configuration file for changelog.

    Return:
        True if success

    Raises:
        ValueError: When there is not git tag records.

    """
    if generate_config:
        click.secho(
            'Generating configuration file for changelog...', fg='green'
        )
        generate_changelog_config_model(**config)
        click.secho('Done!', fg='green')
        return

    result = update_changelog(
        changelog_file=file_changelog,
        urlcompare=url,
        reverse=reverse,
        **config,
    )
    click.secho(f'{result}', fg='green')

greeting(nome) #

Retorna a saudação para o nome passado.

Parameters:

Name Type Description Default
nome str

Nome de usuário

required
Return

Não há retorno. Uma saudação é exibida na tela.

Examples:

>>> greeting Yoda
Oi Yoda!
>>> greeting
Oi <usuário logado>
Source code in incolume\py\changelog\cli.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@click.command()
@click.argument('nome', envvar='USERNAME', type=click.STRING)
def greeting(nome: str) -> None:
    """Retorna a saudação para o nome passado.

    Args:
      nome: Nome de usuário

    Return:
      Não há retorno. Uma saudação é exibida na tela.

    Raises:
      None

    Examples:
        >>> greeting Yoda
        Oi Yoda!

        >>> greeting
        Oi <usuário logado>

    """
    click.echo(f'Oi {nome.title()}!')