From 30571e7e5611f5e18d9a0a65be4892051bd858ad Mon Sep 17 00:00:00 2001 From: thevickypedia Date: Sat, 23 Oct 2021 20:00:59 -0500 Subject: [PATCH] Add an option to generate `CHANGELOG` in reverse order Scrap logger and use secho with colors instead Abort if version is not bumped Generate CHANGELOG in reverse --- CHANGELOG | 127 +++++++++++++++++++----------------- README.md | 6 ++ changemaker/generator.py | 99 +++++++++++++++++----------- docs/README.html | 13 +++- docs/_sources/README.md.txt | 6 ++ docs/_static/searchtools.js | 8 +-- docs/genindex.html | 6 +- docs/index.html | 51 ++++++++++----- docs/objects.inv | Bin 376 -> 378 bytes docs/py-modindex.html | 2 +- docs/search.html | 7 +- docs/searchindex.js | 2 +- gen_docs.sh | 10 +++ version.py | 2 +- 14 files changed, 208 insertions(+), 131 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index b2d1914..51cde7a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,114 +1,121 @@ Change Log ========== -0.0.1 (08/30/2021) +0.2.5 (10/23/2021) ------------------ -- Initial commit +- Add an option to generate `CHANGELOG` in reverse order +- Scrap logger and use secho with colors instead +- Abort if version is not bumped +- Generate CHANGELOG in reverse -0.0.2 (08/30/2021) +0.2.4 (10/14/2021) ------------------ -- Add basic way to get details from `git log` +- Add project urls to pypi package -0.0.3 (08/30/2021) +0.2.3 (10/14/2021) ------------------ -- Get content required for a CHANGELOG +- Use click to make the changelog-generator to make it as a CLI tool +- Update docstrings and README.md -0.0.4 (08/30/2021) +0.2.2 (10/14/2021) ------------------ -- Add version numbers for each change -- Rename variable names +- Make Change Log the title as a heading -0.0.5 (08/30/2021) +0.2.1 (10/14/2021) ------------------ -- Get the number of commits automatically -- Add three digit version numbers +- Add title to the generated CHANGELOG -0.0.6 (08/30/2021) +0.2.0 (08/31/2021) ------------------ -- Wrap everything inside a class -- Print run time at the end +- Remove timestamp from CHANGELOG -0.0.7 (08/30/2021) +0.1.9 (08/31/2021) ------------------ -- Get the commit info from the trunk branch -- Add a destructor method -- Add docstrings +- Update CHANGELOG -0.0.8 (08/30/2021) +0.1.8 (08/31/2021) ------------------ -- Add pre-commit for linting, isort and flake8 +- Support up to 6 digit version numbers +- Fix versions() getting called repeatedly +- Add logger info -0.0.9 (08/30/2021) +0.1.7 (08/31/2021) ------------------ -- Add sphinx documentation -- README markdown and __init__ support for sphinx documentation -- Create gen_docs.sh -- Hook up the doc generation process to pre-commit +- bump version to run build -0.1.0 (08/30/2021) +0.1.6 (08/31/2021) ------------------ -- onboard docs.yml but only prints a statement +- Update sample code in README.md +- Bump version to 0.1.6 -0.1.1 (08/30/2021) +0.1.5 (08/31/2021) +------------------ +- Alter time counter in destructor method +- Update README.md, .gitignore, CHANGELOG +- Bump version + +0.1.4 (08/31/2021) ------------------ - auto upload to pypi when tagged a release version +0.1.3 (08/31/2021) +------------------ +- revert change on python-publish.yml + 0.1.2 (08/30/2021) ------------------ - Create a pypi package - Move generator.py within a source directory - Add __init__.py, CHANGELOT, LICENSE, MANIFEST.in, setup.cfg, setup.py, version.py -0.1.3 (08/31/2021) ------------------- -- revert change on python-publish.yml - -0.1.4 (08/31/2021) +0.1.1 (08/30/2021) ------------------ - auto upload to pypi when tagged a release version -0.1.5 (08/31/2021) +0.1.0 (08/30/2021) ------------------ -- Alter time counter in destructor method -- Update README.md, .gitignore, CHANGELOG -- Bump version +- onboard docs.yml but only prints a statement -0.1.6 (08/31/2021) +0.0.9 (08/30/2021) ------------------ -- Update sample code in README.md -- Bump version to 0.1.6 +- Add sphinx documentation +- README markdown and __init__ support for sphinx documentation +- Create gen_docs.sh +- Hook up the doc generation process to pre-commit -0.1.7 (08/31/2021) +0.0.8 (08/30/2021) ------------------ -- bump version to run build +- Add pre-commit for linting, isort and flake8 -0.1.8 (08/31/2021) +0.0.7 (08/30/2021) ------------------ -- Support up to 6 digit version numbers -- Fix versions() getting called repeatedly -- Add logger info +- Get the commit info from the trunk branch +- Add a destructor method +- Add docstrings -0.1.9 (08/31/2021) +0.0.6 (08/30/2021) ------------------ -- Update CHANGELOG +- Wrap everything inside a class +- Print run time at the end -0.2.0 (08/31/2021) +0.0.5 (08/30/2021) ------------------ -- Remove timestamp from CHANGELOG +- Get the number of commits automatically +- Add three digit version numbers -0.2.1 (10/14/2021) +0.0.4 (08/30/2021) ------------------ -- Add title to the generated CHANGELOG +- Add version numbers for each change +- Rename variable names -0.2.2 (10/14/2021) +0.0.3 (08/30/2021) ------------------ -- Make Change Log the title as a heading +- Get content required for a CHANGELOG -0.2.3 (10/14/2021) +0.0.2 (08/30/2021) ------------------ -- Use click to make the changelog-generator to make it as a CLI tool -- Update docstrings and README.md +- Add basic way to get details from `git log` -0.2.4 (10/14/2021) +0.0.1 (08/30/2021) ------------------ -- Add project urls to pypi package +- Initial commit diff --git a/README.md b/README.md index c47fbc6..117952e 100644 --- a/README.md +++ b/README.md @@ -24,10 +24,16 @@ Generate CHANGELOG from git commit history pip install changelog-generator ``` +###### Regular CHANGELOG ```shell changelog ``` +###### CHANGELOG in reverse order +```shell +changelog reverse +``` + ### Pre-Commit Install `pre-commit` to run `flake8` and `isort` for linting and `sphinx` for documentation generator. diff --git a/changemaker/generator.py b/changemaker/generator.py index 4797ceb..267f156 100644 --- a/changemaker/generator.py +++ b/changemaker/generator.py @@ -1,13 +1,10 @@ -import logging from datetime import datetime -from importlib import reload from os import path, remove, system -from pathlib import PurePath from subprocess import check_output from time import perf_counter from typing import Union -from click import command, pass_context +from click import argument, command, pass_context, secho class Generator: @@ -28,28 +25,22 @@ def __init__(self): - Removes ``CHANGELOG`` if a previous version is available. - Older versions are not required, since ``git log`` captures all the commits anyway. """ - reload(logging) - logging.basicConfig( - format='%(asctime)s - %(levelname)s - [%(module)s:%(lineno)d] - %(funcName)s - %(message)s', - datefmt='%b-%d-%Y %I:%M:%S %p' - ) - self.logger = logging.getLogger(PurePath(__file__).stem) - self.logger.setLevel(logging.INFO) branches = check_output("git branch", shell=True).decode('utf-8').replace('* ', '').strip().split('\n') self.trunk = 'main' if 'main' in branches else 'master' - self.logger.info(f'Identified trunk branch to be {self.trunk}') + secho(message=f'Identified trunk branch to be {self.trunk}', fg='bright_green') self.source = 'source_change_log.txt' self.change = 'CHANGELOG' - self.logger.info('Writing git log into a temp file.') + secho(message='Writing git log into a temp file.', fg='bright_green') system(f'git log --reverse > {self.source}') if path.isfile(self.change): + secho(message='WARNING: Found existing CHANGELOG. Recreating now.', fg='bright_yellow') remove(self.change) def __del__(self): """Removes the source file as it is temporary and prints the run time.""" - self.logger.info('Removing temp file.') + secho(message='Removing temp file.', fg='bright_green') remove(self.source) - self.logger.info(f'CHANGELOG was created in: {round(float(perf_counter()), 2)}s') + secho(message=f'CHANGELOG was created in: {round(float(perf_counter()), 2)}s', fg='bright_green') def get_commits(self) -> int: """Scans for the number of commits in the ``trunk`` branch. @@ -59,7 +50,7 @@ def get_commits(self) -> int: Number of commits. """ commits = int(check_output(f"git rev-list --count {self.trunk}", shell=True).decode('utf-8').split('\n')[0]) - self.logger.info(f'Number of commits: {commits}') + secho(message=f'Number of commits: {commits}', fg='bright_green') return commits def versions(self) -> Union[list, None]: @@ -102,7 +93,7 @@ def get_source(self) -> list: log = file.read().splitlines() return log - def run(self) -> None: + def generator(self) -> list: """Triggers the conversion process. Notes: @@ -113,37 +104,69 @@ def run(self) -> None: See Also: - Destructor ``__del__`` method executes upon exit which deletes the ``source_change_log.txt`` file. + + Returns: + list: + List of snippets that has to be written to ``CHANGELOG`` file. """ versions = self.versions() log = self.get_source() - self.logger.info('Generating CHANGELOG') + secho(message='Generating CHANGELOG', fg='bright_green') iterator = 0 + output = [] + for index, element in enumerate(log): + element = element.strip() + if element.startswith('commit') or element.startswith('Author'): + continue + if element.startswith('Date'): + ind = log.index(element) + element = ' '.join(element.lstrip('Date:').strip().split()[0:-1]) + datetime_obj = datetime.strptime(element, "%a %b %d %H:%M:%S %Y") + element = f'{versions[iterator]} ({datetime_obj.strftime("%m/%d/%Y")})' + iterator += 1 + log[ind + 1] = '-' * len(element) + # log.pop(ind + 1) # Use this to leave a blank line instead of '----' + elif element: + if element[0].isdigit(): + element = element.replace(element[0:2], '-') + if not element[0] == '-': + element = f'- {element}' + if not element: + output.append('^^') + else: + output.append(element + '\n') + return [snippet for snippet in ''.join(output).split('^^')] + + def run(self, reverse: bool = False): + """Writes the snippets into a ``CHANGELOG`` file. + + Args: + reverse: Takes a boolean argument whether or not to generate the ``CHANGELOG`` in reverse. + """ + snippets = self.generator() + snippets.reverse() if reverse else None with open(self.change, 'a') as file: file.write('Change Log\n==========\n\n') - for index, element in enumerate(log): - element = element.strip() - if not element.startswith('commit') and not element.startswith('Author'): - if element.startswith('Date'): - ind = log.index(element) - element = ' '.join(element.lstrip('Date:').strip().split()[0:-1]) - datetime_obj = datetime.strptime(element, "%a %b %d %H:%M:%S %Y") - element = f'{versions[iterator]} ({datetime_obj.strftime("%m/%d/%Y")})' - iterator += 1 - log[ind + 1] = '-' * len(element) - # log.pop(ind + 1) # Use this to leave a blank line instead of '----' - elif element: - if element[0].isdigit(): - element = element.replace(element[0:2], '-') - if not element[0] == '-': - element = f'- {element}' - file.write(element + '\n') + for index, each_snippet in enumerate(snippets): + file.write(f'{each_snippet}\n' if index + 1 < len(snippets) else each_snippet) @command() @pass_context -def main(*args): - """Generate change log file.""" - Generator().run() +@argument('reverse', required=False) +def main(*args, reverse: str = None): + """Generate change log file. + + Run 'changelog reverse' to generate changelog in reverse order. + """ + if reverse: + if reverse.lower() == 'reverse': + secho(message='Generating CHANGELOG from commit history in reverse order.', fg='bright_yellow') + Generator().run(reverse=True) + else: + secho(message='The only allowed options are:\n\t1. changelog\n\t2. changelog reverse', fg='bright_red') + else: + Generator().run() if __name__ == '__main__': diff --git a/docs/README.html b/docs/README.html index ec8d451..6a8fc05 100644 --- a/docs/README.html +++ b/docs/README.html @@ -65,10 +65,19 @@

Navigate to the repository and run:
pip install changelog-generator
 
+ +
+

Regular CHANGELOG

changelog
 
+
+

CHANGELOG in reverse order

+
changelog reverse
+
+
+

Pre-Commit

@@ -100,6 +109,8 @@

Table of Contents

  • Pypi Module
  • Usage
  • Pre-Commit
  • @@ -151,7 +162,7 @@

    Navigation

    \ No newline at end of file diff --git a/docs/_sources/README.md.txt b/docs/_sources/README.md.txt index c47fbc6..117952e 100644 --- a/docs/_sources/README.md.txt +++ b/docs/_sources/README.md.txt @@ -24,10 +24,16 @@ Generate CHANGELOG from git commit history pip install changelog-generator ``` +###### Regular CHANGELOG ```shell changelog ``` +###### CHANGELOG in reverse order +```shell +changelog reverse +``` + ### Pre-Commit Install `pre-commit` to run `flake8` and `isort` for linting and `sphinx` for documentation generator. diff --git a/docs/_static/searchtools.js b/docs/_static/searchtools.js index 58ff35c..e09f926 100644 --- a/docs/_static/searchtools.js +++ b/docs/_static/searchtools.js @@ -282,10 +282,7 @@ var Search = { complete: function(jqxhr, textstatus) { var data = jqxhr.responseText; if (data !== '' && data !== undefined) { - var summary = Search.makeSearchSummary(data, searchterms, hlterms); - if (summary) { - listItem.append(summary); - } + listItem.append(Search.makeSearchSummary(data, searchterms, hlterms)); } Search.output.append(listItem); setTimeout(function() { @@ -501,9 +498,6 @@ var Search = { */ makeSearchSummary : function(htmlText, keywords, hlwords) { var text = Search.htmlToText(htmlText); - if (text == "") { - return null; - } var textLower = text.toLowerCase(); var start = 0; $.each(keywords, function() { diff --git a/docs/genindex.html b/docs/genindex.html index ce577f5..b35ace9 100644 --- a/docs/genindex.html +++ b/docs/genindex.html @@ -56,9 +56,11 @@

    G

  • module
  • +
  • Generator (class in generator) +
  • +
    +
    +generator() list
    +

    Triggers the conversion process.

    +

    Notes

    +
      +
    • Calls the get_source() method.

    • +
    • Ignores lines containing commit sha and Author information.

    • +
    • Converts git datetime into a different format.

    • +
    • Adds - in front of the lines in description for all changes.

    • +
    +
    +

    See also

    +
      +
    • Destructor __del__ method executes upon exit which deletes the source_change_log.txt file.

    • +
    +
    +
    +
    Returns
    +

    List of snippets that has to be written to CHANGELOG file.

    +
    +
    Return type
    +

    list

    +
    +
    +
    +
    get_commits() int
    @@ -117,21 +144,13 @@

    Welcome to Changelog Generator’s documentation!
    -run() None
    -

    Triggers the conversion process.

    -

    Notes

    -
      -
    • Calls the get_source() method.

    • -
    • Ignores lines containing commit sha and Author information.

    • -
    • Converts git datetime into a different format.

    • -
    • Adds - in front of the lines in description for all changes.

    • -
    -
    -

    See also

    -
      -
    • Destructor __del__ method executes upon exit which deletes the source_change_log.txt file.

    • -
    -
    +run(reverse: bool = False) +

    Writes the snippets into a CHANGELOG file.

    +
    +
    Parameters
    +

    reverse – Takes a boolean argument whether or not to generate the CHANGELOG in reverse.

    +
    +

    @@ -222,7 +241,7 @@

    Navigation

    \ No newline at end of file diff --git a/docs/objects.inv b/docs/objects.inv index 54bd42bd98125942f2394e0adca19718d731d1c0..a5fe4bdd77a3a6a9887f79cd3452913be16ebea5 100644 GIT binary patch delta 257 zcmV+c0sj8@0{Q}wfq$KnO-{ow5QX>%bS=(^<4;rZT5|1T)>yAa9(T9fIuX;n?m8*+Q34zs8k%W8! zNf{ilzFgf@<@Id^`~1GskTEbuJfZ2SQBB-cf6TsYpV1S?1Dd!(1SVM5!f7<5VL$r& z>sx>bwH6%43t^dJZNnG54vy6&kY- HF)#NGPW*m` delta 255 zcmVu&dEcAyj7EoEFnQQ^3rngs2v^WJh5MprYc7+P&mhnA=q;)#C5;FH z=2PegccGDABw5>V82TaCr2dZvYQ4mBN#DA2ksbQbko$GW$9Qsiy)GfJS}2l`&mk#; z16DW7`>MQqsNk62cN#JV#)wxmJvFL{yX~LZm+dop;&?_ASBSs_t6DgXhBO>Ue}6j! zh)`?MvEcZLi!7e-o4(sF9}6jXovxoIm{kA3HeKA0JEa2(FY8kNavigation

    \ No newline at end of file diff --git a/docs/search.html b/docs/search.html index 457ee23..f9b3fdc 100644 --- a/docs/search.html +++ b/docs/search.html @@ -44,14 +44,13 @@

    Navigation

    Search

    -