Ir para o conteúdo

Documentação da API#

Documentação automática dos módulos do incolume.py.changelog, gerada com mkdocstrings a partir das docstrings do código.

Módulos#

Module incolume.py.changelog.

key_versions_2_sort(x, qdig=0, regex='') #

Sort by SemVer notation.

Parameters:

Name Type Description Default
regex str

regex to version format.

''
qdig int

Quantity digits to sort.

0
x tuple[str, ...] | list[str] | tuple[str, dict[str, Any]]

x[key, value] -> 'git tag -ln' output.

required
Return

Return a list sorted.

Raises:

Type Description
TypeError

if parameter x not be a tuple or list.

Examples:

>>> key_versions_2_sort(('1.1.1rc0', 'aaa'))
'000100010001.080000'
>>> key_versions_2_sort(('1.1.1post1',))
'000100010001.900001'
Source code in incolume/py/changelog/core.py
183
184
185
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
244
245
246
247
248
def key_versions_2_sort(
    x: tuple[str, ...] | list[str] | tuple[str, dict[str, Any]],
    qdig: int = 0,
    regex: str = '',
) -> str:
    """Sort by SemVer notation.

    Args:
        regex: regex to version format.
        qdig: Quantity digits to sort.
        x: x[key, value] -> 'git tag -ln' output.

    Return:
        Return a list sorted.

    Raises:
        TypeError: if parameter x not be a tuple or list.

    Examples:
        >>> key_versions_2_sort(('1.1.1rc0', 'aaa'))
        '000100010001.080000'
        >>> key_versions_2_sort(('1.1.1post1',))
        '000100010001.900001'

    """
    qdig = qdig or 5
    if not isinstance(x, Container):
        msg = f"'x={x}', must be tuple or list."  # type: ignore [unreachable]
        raise TypeError(msg)

    classifies = {
        'post': 9 * 10**qdig,
        'rc': 8 * 10 ** (qdig - 1),
        'alpha': 2 * 10 ** (qdig - 1),
        'a': 2 * 10 ** (qdig - 1),
        'dev': 0,
    }
    regex = regex or r'(\d+)\.(\d+)\.(\d+)((-?\D+)(\d+))?'
    get_major_minor_patch_build = re.compile(regex)
    logging.debug(get_major_minor_patch_build)

    def _format_from_match(match: re.Match[str] | None, qdig: int) -> str:
        if match is None:
            raise AttributeError
        # pegar major, minor e patch
        major = match.group(1)  # type: ignore [union-attr]
        minor = match.group(2)  # type: ignore [union-attr]
        patch = match.group(3)  # type: ignore [union-attr]
        build = match.group(6)  # type: ignore [union-attr]
        # pegar build, se não tiver colocar uma alta 99999
        build = build or '9' * qdig
        plus = classifies.get(
            re.sub(r'[-.]', '', str(match.group(5)).lower()),  # type: ignore [union-attr]
            0,
        )
        logging.debug('match.group(5): %s', plus)
        build = int(build) + plus
        return f'{major:0>4}{minor:0>4}{patch:0>4}.{build:0>6}'

    try:
        result = _format_from_match(
            get_major_minor_patch_build.search(x[0]), qdig
        )
    except AttributeError:
        result = str(x[0])
    return result

logger(*args, **kwargs) #

Logger function for log.

Parameters:

Name Type Description Default
args str | int | Path

str = positional arguments,

()
kwargs str | int | Path

str = keyword arguments,

{}
The positional/keyword arguments are
required
- str_format

str = format of string to log,

required
- datefmt

str = format date to log,

required
- level

int = can be (logging.DEBUG, logging.INFO, logging.WARNING,

required

logging.ERROR, logging.CRITICAL), - name: str = name of logger, - filelog: Path = log's file .py - filemode: str = mode to open log's file, can be 'a' or 'w'.

Return

Return a logging.Logger object.

Source code in incolume/py/changelog/core.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def logger(
    *args: str | int | Path,
    **kwargs: str | int | Path,
) -> logging.Logger:
    """Logger function for log.

    Args:
        args: str = positional arguments,
        kwargs: str = keyword arguments,
        The positional/keyword arguments are:
        - str_format: str = format of string to log,
        - datefmt: str = format date to log,
        - level: int = can be (logging.DEBUG, logging.INFO, logging.WARNING,
       logging.ERROR, logging.CRITICAL),
        - name: str = name of logger,
        - filelog: Path = log's file .py
        - filemode: str = mode to open log's file, can be 'a' or 'w'.

    Return:
        Return a logging.Logger object.

    """
    # logger variables
    pos: int = 0
    str_format: str = ''
    datefmt: str = ''
    level: int = logging.INFO
    name: str = ''
    filelog: Path = Path(__file__).with_suffix('.log')
    filemode: str = 'a'

    # load values for create logger
    if len(args) > pos:
        for key, value in logger_variables.items():
            try:
                logger_variables[key] = args[pos]
            except IndexError:
                logger_variables[key] = kwargs.get(key) or value
            pos += 1

    logging.basicConfig(
        filename=filelog,
        level=level,
        format=str_format,
        datefmt=datefmt,
        filemode=filemode,
    )

    # create logger
    console = logging.StreamHandler()
    formatter = logging.Formatter(str_format)
    console.setFormatter(formatter)
    logger_obj = logging.getLogger(name=name)
    logger_obj.addHandler(console)
    ic(
        f'>>> {logger_obj.level=}, {logger_obj.name=},'
        f' {logger_obj.getEffectiveLevel()=}',
    )
    return logger_obj

update_version(pyproject_fl, version_fl=None) #

Update version into file.

Source code in incolume/py/changelog/core.py
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
def update_version(pyproject_fl: Path, version_fl: Path | None = None) -> bool:
    """Update version into file."""
    pyproject_fl = pyproject_fl or confproject
    version_fl = version_fl or versionfile
    ic(version_fl)

    version_project, version_poetry, current_version = (
        '',
        '',
        '',
    )
    data: toml.TOMLDocument | None = None
    try:
        data = toml.load(pyproject_fl.open(encoding='utf-8'))
    except (FileExistsError, FileNotFoundError, UnicodeDecodeError):
        return False

    with contextlib.suppress(KeyError):
        version_project = data['project']['version']
        version_poetry = data['tool']['poetry']['version']

        current_version = max(
            version_poetry,
            version_project,
            key=lambda value: key_versions_2_sort((value,)),
        )
        ic(f'{current_version=}, {version_poetry=}, {version_project=}')

        data['tool']['poetry']['version'] = current_version
        data['project']['version'] = current_version

    version_fl.write_text(f'{current_version}\n', encoding='utf-8')
    toml.dump(data, pyproject_fl.open('w', encoding='utf-8'))

    return True

Changelog Module.

Changelog #

Changelog class.

Source code in incolume/py/changelog/changelog.py
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
class Changelog:
    """Changelog class."""

    def __init__(
        self: Changelog,
        file_output: Path | str = '',
        url_compare: str = '',
        *,
        reverse: bool = True,
        **kwargs: str | bool,
    ) -> 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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
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 | bool

Anyone of the positional items.

{}
Return

None

Source code in incolume/py/changelog/changelog.py
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
def __init__(
    self: Changelog,
    file_output: Path | str = '',
    url_compare: str = '',
    *,
    reverse: bool = True,
    **kwargs: str | bool,
) -> 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
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
@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 | bool

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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def changelog_body(
    content: list[tuple[str, dict[str, Any]]],
    content_formated: list[str],
    **kwargs: str | bool,
) -> 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 | bool

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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def changelog_footer(
    content: list[tuple[str, dict[str, Any]]],
    content_formated: list[str],
    **kwargs: str | bool,
) -> 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 = str(
        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 | bool

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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def changelog_header(
    **kwargs: str | bool,
) -> 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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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 | bool

Anyone of the positional items.

{}
Return

True if success.

Examples:

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

Source code in incolume/py/changelog/changelog.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def changelog_write(
    *,
    content: list[tuple[str, dict[str, Any]]],
    **kwargs: str | bool,
) -> 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(
        str(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)

    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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def generate_changelog_config_model(**kwargs: str | Path | bool) -> Path:
    """Generate a model of changelog configuration file."""
    fl = kwargs.pop('conf_file', None) or 'changelog.toml.sample'
    conf_file = Path(str(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_git_tags() #

Return the git tag -n output decoded as UTF-8.

The decoding is explicit so that the CHANGELOG does not depend on the environment locale (mojibake when git tag -n is decoded as latin-1).

Return

The annotated tags, one per line.

Examples:

>>> isinstance(get_git_tags(), str)
True
Source code in incolume/py/changelog/changelog.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def get_git_tags() -> str:
    """Return the ``git tag -n`` output decoded as UTF-8.

    The decoding is explicit so that the CHANGELOG does not depend on the
    environment locale (mojibake when ``git tag -n`` is decoded as latin-1).

    Return:
        The annotated tags, one per line.

    Raises:
        None

    Examples:
        >>> isinstance(get_git_tags(), str)
        True

    """
    return subprocess.run(
        ['git', 'tag', '-n'],
        capture_output=True,
        check=False,
    ).stdout.decode('utf-8', errors='replace')

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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def run() -> None:
    """Examples ran.

    Return:
        None

    """
    msg = get_git_tags().splitlines()[-14]
    logging.debug(msg)
    logging.debug('msg_classify=%s', msg_classify(msg=msg))

    msg = get_git_tags()
    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 | bool

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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
def update_changelog(
    changelog_file: str = '',
    *,
    reverse: bool = True,
    **kwargs: str | bool,
) -> 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 = str(
        kwargs.pop('urlcompare', '')
        or 'https://github.com/development-incolume'
        '/incolume.py.changelog/-/compare'
    )
    content: str = str(kwargs.pop('content', get_git_tags()))
    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,
    )

Principal module.

find_project_root(start_dir='', markers=None) #

Find the project root directory by looking for specific markers.

Source code in incolume/py/changelog/core.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def find_project_root(
    start_dir: Path | str = '', markers: tuple[str, ...] | None = None
) -> Path:
    """Find the project root directory by looking for specific markers."""
    if isinstance(start_dir, str):
        start_dir = Path(start_dir).resolve()

    if markers is None:
        markers = (
            'pyproject.toml',
            '.git',
            'requirements.txt',
            'setup.cfg',
            '.venv',
        )
    current = start_dir

    while current != current.parent:
        for marker in markers:
            if (current / marker).exists():
                return current
        current = current.parent

    msg = 'Project root not found (no markers detected).'
    raise FileNotFoundError(msg)

key_versions_2_sort(x, qdig=0, regex='') #

Sort by SemVer notation.

Parameters:

Name Type Description Default
regex str

regex to version format.

''
qdig int

Quantity digits to sort.

0
x tuple[str, ...] | list[str] | tuple[str, dict[str, Any]]

x[key, value] -> 'git tag -ln' output.

required
Return

Return a list sorted.

Raises:

Type Description
TypeError

if parameter x not be a tuple or list.

Examples:

>>> key_versions_2_sort(('1.1.1rc0', 'aaa'))
'000100010001.080000'
>>> key_versions_2_sort(('1.1.1post1',))
'000100010001.900001'
Source code in incolume/py/changelog/core.py
183
184
185
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
244
245
246
247
248
def key_versions_2_sort(
    x: tuple[str, ...] | list[str] | tuple[str, dict[str, Any]],
    qdig: int = 0,
    regex: str = '',
) -> str:
    """Sort by SemVer notation.

    Args:
        regex: regex to version format.
        qdig: Quantity digits to sort.
        x: x[key, value] -> 'git tag -ln' output.

    Return:
        Return a list sorted.

    Raises:
        TypeError: if parameter x not be a tuple or list.

    Examples:
        >>> key_versions_2_sort(('1.1.1rc0', 'aaa'))
        '000100010001.080000'
        >>> key_versions_2_sort(('1.1.1post1',))
        '000100010001.900001'

    """
    qdig = qdig or 5
    if not isinstance(x, Container):
        msg = f"'x={x}', must be tuple or list."  # type: ignore [unreachable]
        raise TypeError(msg)

    classifies = {
        'post': 9 * 10**qdig,
        'rc': 8 * 10 ** (qdig - 1),
        'alpha': 2 * 10 ** (qdig - 1),
        'a': 2 * 10 ** (qdig - 1),
        'dev': 0,
    }
    regex = regex or r'(\d+)\.(\d+)\.(\d+)((-?\D+)(\d+))?'
    get_major_minor_patch_build = re.compile(regex)
    logging.debug(get_major_minor_patch_build)

    def _format_from_match(match: re.Match[str] | None, qdig: int) -> str:
        if match is None:
            raise AttributeError
        # pegar major, minor e patch
        major = match.group(1)  # type: ignore [union-attr]
        minor = match.group(2)  # type: ignore [union-attr]
        patch = match.group(3)  # type: ignore [union-attr]
        build = match.group(6)  # type: ignore [union-attr]
        # pegar build, se não tiver colocar uma alta 99999
        build = build or '9' * qdig
        plus = classifies.get(
            re.sub(r'[-.]', '', str(match.group(5)).lower()),  # type: ignore [union-attr]
            0,
        )
        logging.debug('match.group(5): %s', plus)
        build = int(build) + plus
        return f'{major:0>4}{minor:0>4}{patch:0>4}.{build:0>6}'

    try:
        result = _format_from_match(
            get_major_minor_patch_build.search(x[0]), qdig
        )
    except AttributeError:
        result = str(x[0])
    return result

load_config(conf_changelog_fl) #

Check if the configuration file exists.

Source code in incolume/py/changelog/core.py
 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
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
def load_config(conf_changelog_fl: Path) -> Mapping[str, str | bool]:
    """Check if the configuration file exists."""
    loaded: toml.TOMLDocument = toml.load(conf_changelog_fl.open('rb'))
    config: Mapping[str, str | bool] = {}
    match loaded:
        case (
            {
                'settings': {'file': str()},
            }
            | {
                'settings': {'reverse': bool()},
            }
            | {
                'settings': {'url_compare': str()},
            }
            | {
                'settings': {'url_keepachangelog': str()},
            }
            | {
                'settings': {'url_semver': str()},
            }
            | {
                'settings': {'url_convetional_commit': str()},
            }
        ):
            config = loaded['settings']
        case (
            {
                'tool': {
                    'changelog': {
                        'settings': {
                            'file': str(),
                        }
                    }
                }
            }
            | {
                'tool': {
                    'changelog': {
                        'settings': {
                            'reverse': bool(),
                        }
                    }
                }
            }
            | {
                'tool': {
                    'changelog': {
                        'settings': {
                            'url_compare': str(),
                        }
                    }
                }
            }
            | {
                'tool': {
                    'changelog': {
                        'settings': {
                            'url_keepachangelog': str(),
                        }
                    }
                }
            }
            | {
                'tool': {
                    'changelog': {
                        'settings': {
                            'url_semver': str(),
                        }
                    }
                }
            }
            | {
                'tool': {
                    'changelog': {
                        'settings': {
                            'url_convetional_commit': str(),
                        }
                    }
                }
            }
        ):
            config = loaded['tool']['changelog']['settings']
        case _:
            msg = f'Invalid configuration: {conf_changelog_fl.as_posix()}'
            raise ValueError(msg)
    return config

logger(*args, **kwargs) #

Logger function for log.

Parameters:

Name Type Description Default
args str | int | Path

str = positional arguments,

()
kwargs str | int | Path

str = keyword arguments,

{}
The positional/keyword arguments are
required
- str_format

str = format of string to log,

required
- datefmt

str = format date to log,

required
- level

int = can be (logging.DEBUG, logging.INFO, logging.WARNING,

required

logging.ERROR, logging.CRITICAL), - name: str = name of logger, - filelog: Path = log's file .py - filemode: str = mode to open log's file, can be 'a' or 'w'.

Return

Return a logging.Logger object.

Source code in incolume/py/changelog/core.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def logger(
    *args: str | int | Path,
    **kwargs: str | int | Path,
) -> logging.Logger:
    """Logger function for log.

    Args:
        args: str = positional arguments,
        kwargs: str = keyword arguments,
        The positional/keyword arguments are:
        - str_format: str = format of string to log,
        - datefmt: str = format date to log,
        - level: int = can be (logging.DEBUG, logging.INFO, logging.WARNING,
       logging.ERROR, logging.CRITICAL),
        - name: str = name of logger,
        - filelog: Path = log's file .py
        - filemode: str = mode to open log's file, can be 'a' or 'w'.

    Return:
        Return a logging.Logger object.

    """
    # logger variables
    pos: int = 0
    str_format: str = ''
    datefmt: str = ''
    level: int = logging.INFO
    name: str = ''
    filelog: Path = Path(__file__).with_suffix('.log')
    filemode: str = 'a'

    # load values for create logger
    if len(args) > pos:
        for key, value in logger_variables.items():
            try:
                logger_variables[key] = args[pos]
            except IndexError:
                logger_variables[key] = kwargs.get(key) or value
            pos += 1

    logging.basicConfig(
        filename=filelog,
        level=level,
        format=str_format,
        datefmt=datefmt,
        filemode=filemode,
    )

    # create logger
    console = logging.StreamHandler()
    formatter = logging.Formatter(str_format)
    console.setFormatter(formatter)
    logger_obj = logging.getLogger(name=name)
    logger_obj.addHandler(console)
    ic(
        f'>>> {logger_obj.level=}, {logger_obj.name=},'
        f' {logger_obj.getEffectiveLevel()=}',
    )
    return logger_obj

modify_logger_runtime(var_name, new_value) #

Access the global scope dictionary directly.

Source code in incolume/py/changelog/core.py
175
176
177
178
179
180
def modify_logger_runtime(
    var_name: str,
    new_value: str | int | Path,
) -> None:
    """Access the global scope dictionary directly."""
    logger_variables[var_name] = new_value

select_configuration_fl(conf_changelog_fl=None, files=None, project_root=None) #

Check if the configuration file exists.

Source code in incolume/py/changelog/core.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def select_configuration_fl(
    conf_changelog_fl: Path | None = None,
    files: list[Path] | None = None,
    project_root: Path | None = None,
) -> Path:
    """Check if the configuration file exists."""
    project_root = project_root or find_project_root()
    candidates: list[Path | None] = (
        [conf_changelog_fl, *files]
        if isinstance(files, list)
        else [conf_changelog_fl, *(project_root / fl for fl in confchangelog)]
    )
    for file in [f for f in candidates if f is not None]:
        if file.exists():
            return file
    msg = (
        'Any Configuration file found: '
        f'{", ".join([file.name for file in candidates if file is not None])}'
    )
    raise FileNotFoundError(msg)

update_version(pyproject_fl, version_fl=None) #

Update version into file.

Source code in incolume/py/changelog/core.py
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
def update_version(pyproject_fl: Path, version_fl: Path | None = None) -> bool:
    """Update version into file."""
    pyproject_fl = pyproject_fl or confproject
    version_fl = version_fl or versionfile
    ic(version_fl)

    version_project, version_poetry, current_version = (
        '',
        '',
        '',
    )
    data: toml.TOMLDocument | None = None
    try:
        data = toml.load(pyproject_fl.open(encoding='utf-8'))
    except (FileExistsError, FileNotFoundError, UnicodeDecodeError):
        return False

    with contextlib.suppress(KeyError):
        version_project = data['project']['version']
        version_poetry = data['tool']['poetry']['version']

        current_version = max(
            version_poetry,
            version_project,
            key=lambda value: key_versions_2_sort((value,)),
        )
        ic(f'{current_version=}, {version_poetry=}, {version_project=}')

        data['tool']['poetry']['version'] = current_version
        data['project']['version'] = current_version

    version_fl.write_text(f'{current_version}\n', encoding='utf-8')
    toml.dump(data, pyproject_fl.open('w', encoding='utf-8'))

    return True

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
 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
111
112
@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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@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()}!')

Uso rápido#

Via API Python:

from incolume.py.changelog.changelog import update_changelog

update_changelog(changelog_file='docs/about/CHANGELOG', reverse=True)

Via CLI:

uv run changelog docs/about/CHANGELOG --reverse

Veja o Guia de Uso e a Instalação.