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

Convert to be able to work with python3 #34

Open
wants to merge 5 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
*.pyc
dist/
.functional-sandbox/
plypatch.egg-info/
plypatch3.egg-info/
build/
*.egg-info
12 changes: 9 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
================================
ply - git-based patch management
================================
=================================
ply3 - git-based patch management
=================================


Description
Expand All @@ -11,6 +11,12 @@ project. These patches are stored as files in a separate git repositiory so
that they can themselves be versioned. These patches can then be applied to
create a patched version of the code to be used for packaging and deployment.

This version is a fork of original ``ply`` utility written by Rick Harris. I
forked it cause original repo looks abandoned and no issues were addressed for
like a 4 years. This version is the same as original one but works with
python3, that's the difference. Upstream version still points to original one
though.


Concepts
========
Expand Down
25 changes: 15 additions & 10 deletions plypatch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ def _get_commit_hash_and_patch_name(self, cmd_arg=None, count=1,
return commit_hash, patch_name

def _applied_patches(self, new_upper_bound=50):
"""Return a list of patches that have already been applied to this
branch.
"""Return a list of patches that have already been applied to this branch.

We can have 3 types of commits, upstream (U), applied (A), and new
(N), which makes the history look like:
Expand All @@ -98,6 +97,7 @@ def _applied_patches(self, new_upper_bound=50):
we don't find an applied patch within that number of queries, we
consider no patches as having been applied.
"""

applied = []

skip = 0
Expand Down Expand Up @@ -138,6 +138,7 @@ def patch_repo(self):
"""Return a patch repo object associated with this working repo via
the ply.patchrepo git config.
"""

if not hasattr(self, '_patch_repo'):
if not self.patch_repo_path:
raise exc.NoLinkedPatchRepo
Expand Down Expand Up @@ -275,7 +276,7 @@ def _get_restore_stats(self):

if os.path.exists(self._restore_stats_path):
with open(self._restore_stats_path, 'r') as f:
updated, removed = map(int, f.read().strip().split(' '))
updated, removed = list(map(int, f.read().strip().split(' ')))

return updated, removed

Expand All @@ -295,7 +296,8 @@ def _ensure_name_and_email_set(self):
raise exc.GitConfigRequired('user.name')

def restore(self, three_way_merge=True, commit_msg=None,
fetch_remotes=True, customize_commit_msg=False):
fetch_remotes=True, customize_commit_msg=False,
no_commit=False):
"""Applies a series of patches to the working repo's current
branch.
"""
Expand Down Expand Up @@ -384,7 +386,9 @@ def restore(self, three_way_merge=True, commit_msg=None,
template = None

# Determine whether we need to prompt the user to edit commit message
if commit_msg:
if no_commit:
pass
elif commit_msg:
if customize_commit_msg:
msgs = []

Expand All @@ -406,7 +410,8 @@ def restore(self, three_way_merge=True, commit_msg=None,
updated, removed)]

try:
self.patch_repo.commit(msgs=msgs, template=template)
if not no_commit:
self.patch_repo.commit(msgs=msgs, template=template)
finally:
if template:
os.unlink(template)
Expand Down Expand Up @@ -454,7 +459,7 @@ def _create_patches(self, since):
with open(from_path) as from_file:
original = from_file.read()
fixed = fixup_patch.fixup_patch(original)
to_file.write(fixed)
to_file.write(fixed.encode('utf-8'))

# Strip 0001- prefix that git-format-patch uses
source_path = os.path.join(self.path, filename.split('-', 1)[1])
Expand Down Expand Up @@ -690,7 +695,7 @@ def initialize(self):
self.init(self.path)

if not os.path.exists(self.series_path):
with open(self.series_path, 'w') as f:
with open(self.series_path, 'w') as f: # noqa
pass

self.add('series')
Expand Down Expand Up @@ -783,7 +788,7 @@ def patch_dependencies(self):
{(dependent, parent): set(file_both_touch1, file_both_touch2, ...)}
"""
graph = collections.defaultdict(set)
for filename, patch_names in self._changes_by_filename().iteritems():
for filename, patch_names in self._changes_by_filename().items():
parent = None
for dependent in patch_names:
if parent:
Expand All @@ -796,7 +801,7 @@ def patch_dependency_dot_graph(self):
lines = ['digraph patchdeps {']

for (dependent, parent), changed_files in\
self.patch_dependencies().iteritems():
self.patch_dependencies().items():
label = ', '.join(sorted(changed_files))
lines.append('"%s" -> "%s" [label="%s"];' % (
dependent, parent, label))
Expand Down
45 changes: 25 additions & 20 deletions plypatch/cli.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,39 @@
"""
ply: git-based patch management
"""
from __future__ import print_function

import argparse
import sys

import plypatch
from plypatch import git


def die(msg):
exit(msg, 1)


def exit(msg, code=0):
print msg
print(msg)
sys.exit(code)


def die_on_conflicts(threeway_merged=True):
print "Patch did not apply cleanly.",
print("Patch did not apply cleanly.", end=' ')
if threeway_merged:
print "Threeway-merge was completed but resulted in conflicts. To fix:"
print("Threeway-merge was completed but resulted in conflicts. "
"To fix:")
else:
print "Unable to threeway-merge. To fix:"
print
print("Unable to threeway-merge. To fix:")
print()
if threeway_merged:
print "\t1) Fix conflicts in affected files"
print("\t1) Fix conflicts in affected files")
else:
print "\t1) Manually apply '.git/rebase-apply/patch' (git apply" \
" --reject usually works) then resolve conflicts"
print "\n\t2) `git add` affected files"
print "\n\t3) Run `ply resolve` to refresh the patch and"\
" apply the rest\n\t of the patches in the series."
print("\t1) Manually apply '.git/rebase-apply/patch' (git apply"
" --reject usually works) then resolve conflicts")
print("\n\t2) `git add` affected files")
print("\n\t3) Run `ply resolve` to refresh the patch and"
" apply the rest\n\t of the patches in the series.")
sys.exit(1)


Expand Down Expand Up @@ -85,28 +87,28 @@ def do(self, args):
except plypatch.exc.NoLinkedPatchRepo:
die('Not linked to a patch-repo')

print status.upper()
print(status.upper())

if status == 'ok':
return

if errors['no_file']:
print 'Entry in series-file but patch not present:'
print('Entry in series-file but patch not present:')
for patch_name in errors['no_file']:
print '\t- %s' % patch_name
print('\t- %s' % patch_name)

if errors['no_series_entry']:
print 'Patch is present but no entry in series file:'
print('Patch is present but no entry in series file:')
for patch_name in errors['no_series_entry']:
print '\t- %s' % patch_name
print('\t- %s' % patch_name)


class GraphCommand(CLICommand):
__command__ = 'graph'

def do(self, args):
"""Graph patch dependencies in DOT format"""
print self.working_repo.patch_repo.patch_dependency_dot_graph()
print(self.working_repo.patch_repo.patch_dependency_dot_graph())


class InitCommand(CLICommand):
Expand All @@ -133,7 +135,7 @@ def do(self, args):
try:
self.working_repo.link(args.path)
except plypatch.exc.AlreadyLinkedToSamePatchRepo:
print 'Already linked to this patch-repo'
print('Already linked to this patch-repo')
except plypatch.exc.AlreadyLinkedToDifferentPatchRepo as e:
die('Already linked to a different patch-repo: %s'
% e.patch_repo_path)
Expand Down Expand Up @@ -162,12 +164,15 @@ class RestoreCommand(CLICommand):
def add_arguments(self, subparser):
subparser.add_argument('-m', '--message', action='store_true',
help='Prompt for a custom commit message')
subparser.add_argument('-n', '--no-commit', action='store_true',
help='Don\'t make a commit in the patch repo')

def do(self, args):
"""Apply the patch series to the the current branch of the
working-repo"""
try:
self.working_repo.restore(customize_commit_msg=args.message)
self.working_repo.restore(customize_commit_msg=args.message,
no_commit=args.no_commit)
except plypatch.exc.GitConfigRequired as e:
die("Required git config '%s' is unset." % e)
except plypatch.exc.RestoreInProgress:
Expand Down
24 changes: 14 additions & 10 deletions plypatch/git/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import print_function

import functools
import os
import subprocess
import sys

from plypatch import utils
from plypatch.git import exc
from plypatch import utils


def cmd(fn):
Expand All @@ -25,7 +27,7 @@ def __init__(self, path, quiet=False, supress_warnings=False):

def warn(self, msg):
if not self.supress_warnings:
print >> sys.stderr, 'warning: %s' % msg
print('warning: %s' % msg, file=sys.stderr)

@cmd
def add(self, filename):
Expand Down Expand Up @@ -60,14 +62,14 @@ def am(self, *patch_paths, **kwargs):
stdout, stderr = proc.communicate()

if not quiet:
print stderr
print stdout
print(stderr)
print(stdout)

if proc.returncode == 0:
if 'atch already applied' in stdout:
if 'atch already applied' in stdout.decode():
raise exc.PatchAlreadyApplied
else:
if 'sha1 information is lacking or useless' in stderr:
if 'sha1 information is lacking or useless' in stderr.decode():
raise exc.PatchBlobSHA1Invalid
else:
raise exc.PatchDidNotApplyCleanly
Expand Down Expand Up @@ -143,7 +145,7 @@ def config(self, cmd, config_key=None, config_value=None):
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise exc.GitException((proc.returncode, stdout, stderr))
lines = [line.strip() for line in stdout.split('\n') if line]
lines = [line.strip() for line in stdout.decode().split('\n') if line]
return lines

@cmd
Expand All @@ -156,7 +158,8 @@ def diff_index(self, treeish, name_only=False):
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise exc.GitException((proc.returncode, stdout, stderr))
filenames = [line.strip() for line in stdout.split('\n') if line]
filenames = [
line.strip() for line in stdout.decode().split('\n') if line]
return filenames

@cmd
Expand Down Expand Up @@ -189,7 +192,8 @@ def format_patch(self, since, keep_subject=False, no_numbered=False,
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise exc.GitException((proc.returncode, stdout, stderr))
filenames = [line.strip() for line in stdout.split('\n') if line]
filenames = [
line.strip() for line in stdout.decode().split('\n') if line]
return filenames

@cmd
Expand Down Expand Up @@ -220,7 +224,7 @@ def log(self, cmd_arg=None, count=None, pretty=None, skip=None):
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise exc.GitException((proc.returncode, stdout, stderr))
return stdout
return stdout.decode()

@cmd
def notes(self, command, message=None):
Expand Down
2 changes: 1 addition & 1 deletion plypatch/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def meaningful_diff(source_path, dest_path, diff_output=None):
% proc.returncode)

last_index_perms = None
lines = diff_output.split('\n')
lines = diff_output.decode().split('\n')

for line in lines:
line = line.strip()
Expand Down
2 changes: 1 addition & 1 deletion plypatch/version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# http://stackoverflow.com/questions/2058802/
# how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package
__version__ = '0.4.1'
__version__ = '0.4.3'
11 changes: 6 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@


setuptools.setup(
name='plypatch',
name='plypatch3',
version=__version__,
description='Ply: Git-based Patch Management',
url='https://github.com/rconradharris/ply',
url='https://github.com/sorrowless/ply',
license='MIT',
author='Rick Harris',
author_email='[email protected]',
author='Rick Harris, Stan Bogatkin',
author_email='[email protected], [email protected]',
packages=setuptools.find_packages(),
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6'
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3'
],
install_requires=[],
entry_points={
Expand Down