Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: argparse module and PEP-8 cleanup #9

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ bin/
build/
develop-eggs/
dist/
deb_dist/
eggs/
lib/
lib64/
Expand Down Expand Up @@ -52,3 +53,6 @@ coverage.xml
# Sphinx documentation
docs/_build/


# Other
MANIFEST
36 changes: 4 additions & 32 deletions git2changelog.spec → CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,36 +1,8 @@
Summary: To convert git logs into formatted changelog entries
Name: git2changelog
Version: 0.1
Release: 6%{dist}
Source0: http://people.redhat.com/jduncan/%{name}/%{name}-%{version}.tar.gz
License: GPLv2
BuildArch: noarch
Requires: python-dateutil
BuildRequires: python2-devel
BuildRequires: python-setuptools
Url: https://github.com/jduncan-rva/git2changelog
* Fri Sep 29 2017 Waldek Maleska <[email protected]> - 0.2-1
- PEP-8 cleanup
- switch to argparse module from optparse (obsolete)
- remove RPM spec file in preparation to build with setuptools instead

%description
git2changelog analyzes a git repository to create a formatted changelog

%prep
%setup -q -n %{name}-%{version}

%build
%{__python2} setup.py build

%install
%{__python2} setup.py install -O1 --root=$RPM_BUILD_ROOT

%files
%dir %{_docdir}/%{name}-%{version}
%{_docdir}/%{name}-%{version}/*
%{_mandir}/man8/%{name}.8*
%{python2_sitelib}/*egg-info
%{python2_sitelib}/%{name}*
%{_bindir}/%{name}

%changelog
* Mon Jun 09 2014 Jamie Duncan <[email protected]> - 0.1-6
- updated spec file to reflect r6
- added functionality to be able to parse files in different formats and updated docs. fixes #6 : Commit 42f6e76
Expand Down
1 change: 1 addition & 0 deletions README
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ git2changelog

# Purpose
git2changelog analyzes git repositories to generate formatted changelogs

# Origin

This is a fork of https://github.com/jduncan-rva/git2changelog
which appears to not be maintaned anymore.

# Usage
```bash
git2changelog -r REPO -b BEGIN_TAG [-e END_TAG -s SEARCH_STRING]
Expand All @@ -23,5 +29,7 @@ git2changelog -r REPO -b BEGIN_TAG [-e END_TAG -s SEARCH_STRING]
-r REPO, --repo=REPO Repository to Scan. defaults to current directory.

```
#Mailing Lists


# Mailing Lists
None Yet
46 changes: 32 additions & 14 deletions scripts/git2changelog
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,46 @@
# File Name : git2changelog
# Creation Date : 06-07-2014
# Created By : Jamie Duncan
# Last Modified : Sun 08 Jun 2014 05:58:37 AM EDT
# Last Modified : Fri 29 Sep 2017 15:56:02 AM BST
# Purpose : executable for converting a git log stanza into a usable spec file changelog

from optparse import OptionParser
from git2changelog import CLData
import argparse
import git2changelog
import os

def main():

parser = OptionParser(usage="%prog -b [-e -r -s]" )
parser.add_option("-b", "--begin_tag", dest="t_start", help="Tag to start data collecton from. required.", metavar="BEGIN_TAG")
parser.add_option("-e", "--end_tag", default='HEAD', dest="t_end", help="Tag to end the data collection. defaults to HEAD.", metavar="END_TAG")
parser.add_option("-f", "--log_format", default="rpm", dest="log_format", help="Format to Generate Changelog. defaults to rpm")
parser.add_option("-s", "--search", default=None, dest="search_term", help="Commit Search Criteria. optional.", metavar="SEARCH_TERM")
parser.add_option("-n", "--name", default=None, dest="tag_name", help="New Tag Name for untagged commits. optional.", metavar="TAG_NAME")
parser.add_option("-r", "--repo", default=None, dest="repo", help="Repository to Scan. defaults to current directory.", metavar="REPO")
def parse_args():
parser = argparse.ArgumentParser(
description='Generate changelog from Git history')
parser.add_argument("-b", "--begin_tag", dest="t_start",
help="Tag to start data collection from.",
required=True, metavar="BEGIN_TAG")
parser.add_argument("-e", "--end_tag", default='HEAD', dest="t_end",
help="Tag to end the data collection. defaults to "
"HEAD.",
metavar="END_TAG")
parser.add_argument("-f", "--log_format", default="rpm", dest="log_format",
help="Format to Generate Changelog. defaults to rpm")
parser.add_argument("-s", "--search", default=None, dest="search_term",
help="Commit Search Criteria. optional.",
metavar="SEARCH_TERM")
parser.add_argument("-n", "--name", default=None, dest="tag_name",
help="New Tag Name for untagged commits. optional.",
metavar="TAG_NAME")
parser.add_argument("-r", "--repo", default=None, dest="repo",
help="Repository to Scan. defaults to current "
"directory.",
metavar="REPO")
return parser.parse_args()


(options, args) = parser.parse_args()
def main():
options = parse_args()
if options.repo is None:
options.repo = os.getcwd()
clog = CLData(options)
clog.formatChangeLog()
clog = git2changelog.CLData(options)
clog.format_changelog()


if __name__ == '__main__':
main()
28 changes: 17 additions & 11 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,36 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
git2changelog module packaging configurationa

Fork of https://github.com/jduncan-rva/git2changelog
"""

from distutils.core import setup

version = '0.1'
version = '0.2'
name = 'git2changelog'

setup(
name=name,
license = 'GPLv2',
license='GPLv2',
version=version,
description='To analyze git repositories and create formatted changelogs',
author='Jamie Duncan',
author_email='[email protected]',
url='https://github.com/jduncan-rva/git2changelog',
maintainer='Jamie Duncan',
maintainer_email = 'jduncan@redhat.com',
url='https://github.com/weakcamel/git2changelog',
maintainer='Waldek Maleska',
maintainer_email='w.maleska@gmail.com',
long_description='git2changelog analyze gits repositories and generates formatted changelogs',
package_dir={'': 'src'},
py_modules=['git2changelog'],
scripts = ['scripts/git2changelog'],
scripts=['scripts/git2changelog'],
data_files=[
('/usr/share/doc/%s-%s' % (name,version), ['doc/LICENSE']),
('/usr/share/man/man8', ['doc/git2changelog.8.gz']),
],
('/usr/share/doc/%s-%s' % (name, version), ['doc/LICENSE']),
('/usr/share/man/man8', ['doc/git2changelog.8.gz']),
],
install_requires=[
"python-dateutil",
],
)


107 changes: 63 additions & 44 deletions src/git2changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,20 @@

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

# File Name : changelogup.py
# File Name : git2changelog.py
# Creation Date : 06-07-2014
# Created By : Jamie Duncan
# Last Modified : Mon 09 Jun 2014 01:28:56 PM EDT
# Last Modified : Fri 29 Sep 2017 15:56:02 AM BST
# Purpose : for converting a git log stanza into a usable spec file changelog

import subprocess
import csv
from dateutil.parser import parse
from optparse import OptionParser
import dateutil.parser
import os
import subprocess


#################################
#
Expand All @@ -36,59 +37,71 @@
class InvalidRepositoryError(Exception):
pass


class NoGitTagsError(Exception):
pass

class CLData:

class CLData:
def __init__(self, options):

self.t_start = options.t_start #start tag
self.t_end = options.t_end #end tag, defaults to 'HEAD'
self.t_start = options.t_start # start tag
self.t_end = options.t_end # end tag, defaults to 'HEAD'
self.search_terms = False
if options.search_term:
self.search_terms = options.search_term.split(',') #option search term to limit commit output, is passed as a comma-delimited list
self.repo = options.repo #git repo directory to run against - defaults to curr working directory
self.search_terms = options.search_term.split(
',') # option search term to limit commit output,
# is passed as a comma-delimited list
self.repo = options.repo # git repo directory to run against -
# defaults to curr working directory
self.tag_name = False
if options.tag_name:
self.tag_name = options.tag_name

#log_format - opens up the ability to have other log formats generated
#current supported formats
# log_format - opens up the ability to have other log formats
# generated
# current supported formats
# rpm - the default. and RPM spec file changelog

self.log_format = options.log_format.lower()

self._checkRepository()
self._checkTags()
self._check_repository()
self._check_tags()

def _checkRepository(self):
def _check_repository(self):
if not os.path.isdir(os.path.join(self.repo, '.git')):
raise InvalidRepositoryError("%s Does Not Appear to be a Valid git Repository" % self.repo)
raise InvalidRepositoryError(
"%s Does Not Appear to be a Valid git Repository" % self.repo)

def _checkTags(self):
#the logic here: if you don't have any tagged releases you should not be creating a spec file.
def _check_tags(self):
# the logic here: if you don't have any tagged releases you should
# not be creating a spec file.

git_command = 'git tag'
cl_raw = subprocess.Popen(git_command,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.repo)
cl_raw = subprocess.Popen(git_command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, cwd=self.repo)

tags = cl_raw.stdout.readlines()
if len(tags) == 0:
raise NoGitTagsError("The Repository Does Not Seem To Have any Tags Created. Please Verify.")
raise NoGitTagsError(
"The Repository Does Not Seem To Have any Tags Created. "
"Please Verify.")

def _formatDate(self, date):
#returns the date in the proper format for a changelog in a spec file
def _format_date(self, date):
# returns the date in the proper format for a changelog in a spec file

return parse(date).strftime('%a %b %d %Y')
return dateutil.parser.parse(date).strftime('%a %b %d %Y')

def _formatRelease(self, tag):
def _format_release(self, tag):
# takes the decoration value and figures out if it's a new tag or not
# if it's a new tag it takes it and prints out the full changelog entry
# if it's a new tag it takes it and prints out the full changelog
# entry
# if it's not it just prints the commit line
new_release = False
if 'HEAD' in tag:
if 'tag' in tag:
tag = "- %s" % tag.split(':')[1].strip(' ()').split(',')[0]
tag = "- %s" % tag.split(':')[1].strip(' ()').split(',')[0]
else:
if self.tag_name:
tag = "- %s" % self.tag_name
Expand All @@ -99,42 +112,48 @@ def _formatRelease(self, tag):
tag = "- %s" % tag.split(':')[1].strip(' ()')
new_release = True

return new_release,tag
return new_release, tag

def _getGitLog(self):
#grabs the raw git log data from the given repo
def _get_git_log(self):
# grabs the raw git log data from the given repo

git_command = 'git --no-pager log %s..%s --pretty --format=\'%%cD,%%cn,%%ce,%%h,"%%s","%%d"\'' % (self.t_start, self.t_end)
cl_raw = subprocess.Popen(git_command,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.repo)
git_command = 'git --no-pager log %s..%s --pretty --format=\'%%cD,' \
'%%cn,%%ce,%%h,"%%s","%%d"\'' % (
self.t_start, self.t_end)
cl_raw = subprocess.Popen(git_command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, cwd=self.repo)

return cl_raw.stdout.readlines()

def _generateRPMChangeLog(self, data):
def _generate_rpm_changelog(self, data):
# RPM Changelog Format Script
# called if log_format = 'rpm'

for row in data:
r_check,release = self._formatRelease(row[6])
r_check, release = self._format_release(row[6])
if r_check:
print "\n* %s %s <%s> %s" % (self._formatDate(row[1]),row[2],row[3],release)
print "\n* %s %s <%s> %s" % (
self._format_date(row[1]), row[2], row[3], release)
if self.search_terms:
for item in self.search_terms:
if item in row[5]:
print "- %s : Commit %s" % (row[5],row[4])
print "- %s : Commit %s" % (row[5], row[4])
break
else:
print "- %s : Commit %s" % (row[5],row[4])
print "- %s : Commit %s" % (row[5], row[4])
else:
if self.search_terms: #if we want to limit the output to lines with certain strings in the comment
if self.search_terms: # if we want to limit the output to
# lines with certain strings in the comment
for item in self.search_terms:
if item in row[5]:
print "- %s : Commit %s" % (row[5],row[4])
else: #if we want all of the commits - no search term given
print "- %s : Commit %s" % (row[5],row[4])
print "- %s : Commit %s" % (row[5], row[4])
else: # if we want all of the commits - no search term given
print "- %s : Commit %s" % (row[5], row[4])

def formatChangeLog(self):
def format_changelog(self):

data = self._getGitLog()
data = self._get_git_log()
raw_data = csv.reader(data)
if self.log_format == 'rpm':
self._generateRPMChangeLog(raw_data)
self._generate_rpm_changelog(raw_data)