├── .gitchangelog.rc ├── .gitignore ├── LICENSE ├── README.md ├── git_patch ├── __init__.py └── git_patch.py └── setup.py /.gitchangelog.rc: -------------------------------------------------------------------------------- 1 | ## 2 | ## Format 3 | ## 4 | ## ACTION: [AUDIENCE:] COMMIT_MSG [!TAG ...] 5 | ## 6 | ## Description 7 | ## 8 | ## ACTION is one of 'chg', 'fix', 'new' 9 | ## 10 | ## Is WHAT the change is about. 11 | ## 12 | ## 'chg' is for refactor, small improvement, cosmetic changes... 13 | ## 'fix' is for bug fixes 14 | ## 'new' is for new features, big improvement 15 | ## 16 | ## AUDIENCE is optional and one of 'dev', 'usr', 'pkg', 'test', 'doc' 17 | ## 18 | ## Is WHO is concerned by the change. 19 | ## 20 | ## 'dev' is for developpers (API changes, refactors...) 21 | ## 'usr' is for final users (UI changes) 22 | ## 'pkg' is for packagers (packaging changes) 23 | ## 'test' is for testers (test only related changes) 24 | ## 'doc' is for doc guys (doc only changes) 25 | ## 26 | ## COMMIT_MSG is ... well ... the commit message itself. 27 | ## 28 | ## TAGs are additionnal adjective as 'refactor' 'minor' 'cosmetic' 29 | ## 30 | ## They are preceded with a '!' or a '@' (prefer the former, as the 31 | ## latter is wrongly interpreted in github.) Commonly used tags are: 32 | ## 33 | ## 'refactor' is obviously for refactoring code only 34 | ## 'minor' is for a very meaningless change (a typo, adding a comment) 35 | ## 'cosmetic' is for cosmetic driven change (re-indentation, 80-col...) 36 | ## 'wip' is for partial functionality but complete subfunctionality. 37 | ## 38 | ## Example: 39 | ## 40 | ## new: usr: support of bazaar implemented 41 | ## chg: re-indentend some lines !cosmetic 42 | ## new: dev: updated code to be compatible with last version of killer lib. 43 | ## fix: pkg: updated year of licence coverage. 44 | ## new: test: added a bunch of test around user usability of feature X. 45 | ## fix: typo in spelling my name in comment. !minor 46 | ## 47 | ## Please note that multi-line commit message are supported, and only the 48 | ## first line will be considered as the "summary" of the commit message. So 49 | ## tags, and other rules only applies to the summary. The body of the commit 50 | ## message will be displayed in the changelog without reformatting. 51 | 52 | 53 | ## 54 | ## ``ignore_regexps`` is a line of regexps 55 | ## 56 | ## Any commit having its full commit message matching any regexp listed here 57 | ## will be ignored and won't be reported in the changelog. 58 | ## 59 | ignore_regexps = [ 60 | r'@minor', r'!minor', 61 | r'@cosmetic', r'!cosmetic', 62 | r'@refactor', r'!refactor', 63 | r'@wip', r'!wip', 64 | r'^([cC]hg|[fF]ix|[nN]ew)\s*:\s*[p|P]kg:', 65 | r'^(.{3,3}\s*:)?\s*[fF]irst commit.?\s*$', 66 | ] 67 | 68 | 69 | ## ``section_regexps`` is a list of 2-tuples associating a string label and a 70 | ## list of regexp 71 | ## 72 | ## Commit messages will be classified in sections thanks to this. Section 73 | ## titles are the label, and a commit is classified under this section if any 74 | ## of the regexps associated is matching. 75 | ## 76 | section_regexps = [ 77 | ('New', [ 78 | r'^[nN]ew\s*:\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n]*)$', 79 | ]), 80 | ('Changes', [ 81 | r'^[cC]hg\s*:\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n]*)$', 82 | ]), 83 | ('Fix', [ 84 | r'^[fF]ix\s*:\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n]*)$', 85 | ]), 86 | 87 | ('Other', None ## Match all lines 88 | ), 89 | 90 | ] 91 | 92 | 93 | ## ``body_process`` is a callable 94 | ## 95 | ## This callable will be given the original body and result will 96 | ## be used in the changelog. 97 | ## 98 | ## Available constructs are: 99 | ## 100 | ## - any python callable that take one txt argument and return txt argument. 101 | ## 102 | ## - ReSub(pattern, replacement): will apply regexp substitution. 103 | ## 104 | ## - Indent(chars=" "): will indent the text with the prefix 105 | ## Please remember that template engines gets also to modify the text and 106 | ## will usually indent themselves the text if needed. 107 | ## 108 | ## - Wrap(regexp=r"\n\n"): re-wrap text in separate paragraph to fill 80-Columns 109 | ## 110 | ## - noop: do nothing 111 | ## 112 | ## - ucfirst: ensure the first letter is uppercase. 113 | ## (usually used in the ``subject_process`` pipeline) 114 | ## 115 | ## - final_dot: ensure text finishes with a dot 116 | ## (usually used in the ``subject_process`` pipeline) 117 | ## 118 | ## - strip: remove any spaces before or after the content of the string 119 | ## 120 | ## Additionally, you can `pipe` the provided filters, for instance: 121 | #body_process = Wrap(regexp=r'\n(?=\w+\s*:)') | Indent(chars=" ") 122 | #body_process = Wrap(regexp=r'\n(?=\w+\s*:)') 123 | #body_process = noop 124 | body_process = ReSub(r'((^|\n)[A-Z]\w+(-\w+)*: .*(\n\s+.*)*)+$', r'') | strip 125 | 126 | 127 | ## ``subject_process`` is a callable 128 | ## 129 | ## This callable will be given the original subject and result will 130 | ## be used in the changelog. 131 | ## 132 | ## Available constructs are those listed in ``body_process`` doc. 133 | subject_process = (strip | 134 | ReSub(r'^([cC]hg|[fF]ix|[nN]ew)\s*:\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n@]*)(@[a-z]+\s+)*$', r'\4') | 135 | ucfirst | final_dot) 136 | 137 | 138 | ## ``tag_filter_regexp`` is a regexp 139 | ## 140 | ## Tags that will be used for the changelog must match this regexp. 141 | ## 142 | tag_filter_regexp = r'^[0-9]+\.[0-9]+(\.[0-9]+)?$' 143 | 144 | 145 | ## ``unreleased_version_label`` is a string 146 | ## 147 | ## This label will be used as the changelog Title of the last set of changes 148 | ## between last valid tag and HEAD if any. 149 | unreleased_version_label = "%%version%% (unreleased)" 150 | 151 | 152 | ## ``output_engine`` is a callable 153 | ## 154 | ## This will change the output format of the generated changelog file 155 | ## 156 | ## Available choices are: 157 | ## 158 | ## - rest_py 159 | ## 160 | ## Legacy pure python engine, outputs ReSTructured text. 161 | ## This is the default. 162 | ## 163 | ## - mustache() 164 | ## 165 | ## Template name could be any of the available templates in 166 | ## ``templates/mustache/*.tpl``. 167 | ## Requires python package ``pystache``. 168 | ## Examples: 169 | ## - mustache("markdown") 170 | ## - mustache("restructuredtext") 171 | ## 172 | ## - makotemplate() 173 | ## 174 | ## Template name could be any of the available templates in 175 | ## ``templates/mako/*.tpl``. 176 | ## Requires python package ``mako``. 177 | ## Examples: 178 | ## - makotemplate("restructuredtext") 179 | ## 180 | output_engine = rest_py 181 | #output_engine = mustache("restructuredtext") 182 | #output_engine = mustache("markdown") 183 | #output_engine = makotemplate("restructuredtext") 184 | 185 | 186 | ## ``include_merge`` is a boolean 187 | ## 188 | ## This option tells git-log whether to include merge commits in the log. 189 | ## The default is to include them. 190 | include_merge = True 191 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | #Idea 92 | .idea 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # git-patch 2 | An iterative rebase to manage open source forks. 3 | 4 | Open Source project forks contain custom changes. Git Patch command helps manage the commits made on a 5 | fork in a structured manner. 6 | git-patch support the following development model: 7 | * OSS project has a master branch and tracks releases with tags or branches. 8 | * Forked project's development branch is a copy of a release branch or tag. 9 | 10 | The requirements of a patch management system are: 11 | 1. Apply and test patches on HEAD of `upstream/master`. 12 | Similar to CI, the patch system should facilitate detection of conflicts and unit test failures at regular intervals. 13 | Such a setup will help developers react to failures quickly and regularly. 14 | 2. Allow skipping of some patches. 15 | If conflicts or test failures are detected, developers should be able to skip or comment out some patches instead 16 | being forced to fix it. This requirement enables beta releases with some features missing. 17 | 3. Patch management functions. 18 | Provide functions to edit, combine and remove patches. 19 | 20 | For e.g. developers at Qubole, use the following model to develop on Apache Calcite. 21 | 22 | Apache Calcite has a master branch and tags (as well as branches) for each release. 23 | 24 | - Qubole developers create a branch from tag `calcite-1.12.0` - `q-calcite-12` which is the development branch. All feature branches are merged to `q-calcite-12`. 25 | - Qubole developers want to continously test custom features on the master branch to ensure compatibility in future releases. 26 | - They created `oss-master` which is a mirror of `master` in apache/calcite`. 27 | 28 | git-patch is used to manage patches and apply them on oss-master to test compatibility. 29 | Check [qubole/calcite](https://github.com/qubole/incubator-calcite/tree/oss-master/.patch) for an example. 30 | 31 | 32 | ## Install 33 | pip install git-patch 34 | 35 | 36 | ## Setup Local Repository 37 | 38 | git remote add upstream 39 | git fetch upstream 40 | 41 | ## Initialize Repository for patches 42 | 43 | git checkout upstream/master 44 | git checkout -b oss-master 45 | git patch init -b 46 | git add .patch 47 | git commit -m "Add patch configuration" 48 | git push -u origin oss-master 49 | 50 | 51 | ## Generate patches 52 | 53 | git checkout oss-master 54 | git patch generate 55 | 56 | ## Create a development branch 57 | 58 | # Creates a branch `git_patch` and rebases it upstream/master 59 | git patch create-branch 60 | 61 | ## Apply patches 62 | 63 | git checkout oss-master 64 | git patch apply 65 | 66 | ## Fix Conflicts 67 | If a patch has conflicts, `apply` command will fail. The conflicts have to be resolved 68 | and the patch has to be regenerated using the following commands: 69 | 70 | # Fix conflicts 71 | # IMPORTANT: All changes should be cached. 72 | # IMPORTANT Do not commit any changes. 73 | git patch fix-patch 74 | 75 | # If all steps are successful, a modified patch is available. 76 | # Copy the patch to oss-master and commit it. 77 | git checkout oss-master 78 | git add .patch/ 79 | git commit 80 | 81 | ## Edit Patches 82 | To edit a patch, use `apply` command will fail. Make edits and regenerate the patch. 83 | 84 | git patch apply --patch 85 | 86 | # Make edits 87 | # IMPORTANT: All changes should be cached. 88 | # IMPORTANT Do not commit any changes. 89 | git patch fix-patch 90 | 91 | # If all steps are successful, a modified patch is available. 92 | # Copy the patch to oss-master and commit it. 93 | git checkout oss-master 94 | git add .patch/ 95 | git commit 96 | 97 | ## Squash commits in a section 98 | Commits in a section can be squashed to a single commit. This is useful when there is no 99 | advantage in maintaining separate patches for a single feature or section. For e.g. lets say 100 | a feature has the following patches: 101 | 102 | - 0001-new-Add-new-feature.patch 103 | - 0001-fix-Fix-a-bug-in-new-feature.patch 104 | - 0001-new-redesign-internal-data-structures 105 | 106 | Once this feature has stabilized, these patches can be squashed to a single one. 107 | 108 | 109 | # Create a development branch 110 | git patch create-branch 111 | 112 | # Squash commits in a section. 113 | # Commit message from the specified patch file is copied. 114 | git patch
squash --patch 115 | 116 | -------------------------------------------------------------------------------- /git_patch/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'rajatv' 2 | -------------------------------------------------------------------------------- /git_patch/git_patch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import argparse 3 | import os 4 | import logging 5 | import re 6 | import subprocess 7 | from subprocess import CalledProcessError 8 | import sys 9 | import yaml 10 | 11 | _current_version = 1 12 | _supported_versions = [1] 13 | 14 | 15 | class UserAbortedException(Exception): 16 | pass 17 | 18 | 19 | def _log_init(): 20 | root = logging.getLogger() 21 | root.setLevel(logging.DEBUG) 22 | 23 | ch = logging.StreamHandler(sys.stdout) 24 | ch.setLevel(logging.DEBUG) 25 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 26 | ch.setFormatter(formatter) 27 | root.addHandler(ch) 28 | 29 | 30 | def _head(branch): 31 | output = subprocess.Popen(['git', 'ls-remote', '--heads', 'origin', 'refs/heads/%s' % branch], stdout=subprocess.PIPE).communicate()[0] 32 | return output.split()[0] 33 | 34 | 35 | def _write_config(patches): 36 | with open('.patch/config.yml', 'w') as outfile: 37 | outfile.write(yaml.dump(patches, default_flow_style=False)) 38 | 39 | 40 | def init(args, patches): 41 | config = { 42 | "tracking": { 43 | "branch": args.branch, 44 | "commit-id": _head(args.branch) 45 | }, 46 | "sections": [ 47 | { 48 | "name": "unclassified", 49 | "commits": [] 50 | } 51 | ], 52 | "version": _current_version 53 | } 54 | if not os.path.exists(".patch"): 55 | os.makedirs(".patch") 56 | 57 | _write_config(config) 58 | 59 | 60 | def create_branch(args, patches): 61 | try: 62 | subprocess.check_call(["git", "branch", "-D", args.name]) 63 | except CalledProcessError as err: 64 | logging.debug("Branch %s does not exist" % args.name) 65 | subprocess.check_call(["git", "checkout", "-b", args.name]) 66 | if args.fetch: 67 | subprocess.check_call(["git", "fetch", "upstream"]) 68 | subprocess.check_call(["git", "rebase", args.remote]) 69 | logging.info("Create and rebased branch %s" % args.name) 70 | 71 | 72 | def generate(args, patches): 73 | current = patches["tracking"]["commit-id"] 74 | head = _head(patches["tracking"]["branch"]) 75 | logging.debug("Current: %s, Head: %s" % (current, head)) 76 | 77 | generated = subprocess.Popen(['git', 'format-patch', '%s..%s' % (current, head), "-o", ".patch"], 78 | stdout=subprocess.PIPE).communicate()[0] 79 | 80 | commit_list = generated.splitlines(False) 81 | logging.info("%d commits processed." % len(commit_list)) 82 | patches["tracking"]["commit-id"] = head 83 | unclassified = None 84 | for p in patches["sections"]: 85 | if p["name"] == "unclassified": 86 | unclassified = p 87 | break 88 | 89 | for p in commit_list: 90 | unclassified["commits"].append(os.path.basename(p)) 91 | 92 | _write_config(patches) 93 | 94 | 95 | def list_patches(args, patches): 96 | print "\n".join([s["name"] for s in patches["sections"]]) 97 | 98 | 99 | def create_section(args, patches): 100 | patches["sections"].append({ 101 | "name": args.name, 102 | "commits": [] 103 | }) 104 | 105 | _write_config(patches) 106 | 107 | 108 | def move_patch(args, patches): 109 | # Find the patch 110 | found = False 111 | for section in patches["sections"]: 112 | if args.patch in section["commits"]: 113 | found = True 114 | section["commits"].remove(args.patch) 115 | break 116 | 117 | if found: 118 | found_section = False 119 | for section in patches["sections"]: 120 | if section["name"] == args.to: 121 | section["commits"].append(args.patch) 122 | found_section = True 123 | break 124 | if not found_section: 125 | raise Exception("Section `%s` not found" % args.to) 126 | else: 127 | raise Exception("Patch `%s` not found" % args.patch) 128 | 129 | _write_config(patches) 130 | 131 | 132 | def patch_apply(args, patches): 133 | for section in patches["sections"]: 134 | d = vars(args) 135 | d['section'] = section 136 | if section_apply(args, patches): 137 | args.from_patch = None 138 | 139 | def patch_commits(args, patches): 140 | print "\n".join(args.section["commits"]) 141 | 142 | 143 | def _generate_edit_metadata(commit, subject): 144 | head = subprocess.Popen(['git', 'rev-parse', 'HEAD'], 145 | stdout=subprocess.PIPE).communicate()[0].strip() 146 | # Write metadata to .patch/metadata_edit.yml 147 | metadata = { 148 | "patch": commit, 149 | "head": head, 150 | "subject": subject 151 | } 152 | 153 | with open('.patch/metadata_edit.yml', 'w') as outfile: 154 | outfile.write(yaml.dump(metadata, default_flow_style=False)) 155 | logging.info("Created metadata_edit file for %s" % commit) 156 | 157 | """ 158 | " If from_patch is set in args, then no patch will be applied until 159 | " the patch named by from_patch is found 160 | " 161 | " Returns True if either 162 | " 1. Patch passed through --from-patch is found in this section 163 | " 2. If --from-patch was not set 164 | """ 165 | def section_apply(args, patches): 166 | subject_re = re.compile("Subject: \[PATCH.*\] (.*)^\-\-\-\n", re.S | re.M) 167 | algo = "-3" 168 | if args.reject: 169 | algo = "--reject" 170 | 171 | patch_required = False 172 | if args.from_patch is None: 173 | patch_required = True 174 | 175 | for commit in args.section["commits"]: 176 | if not patch_required: 177 | if commit == os.path.basename(args.from_patch): 178 | patch_required = True 179 | # from_patch is excluded, fall through to continue 180 | logging.info("Skipping: %s " % commit) 181 | continue 182 | 183 | logging.info("Processing: %s " % commit) 184 | with open('.patch/%s' % commit, 'r') as commit_file: 185 | data = commit_file.read() 186 | subject = subject_re.search(data).group(1) 187 | logging.info(subject) 188 | try: 189 | subprocess.check_call(["git", "apply", algo, ".patch/%s" % commit]) 190 | if args.patch is not None and commit == os.path.basename(args.patch): 191 | _generate_edit_metadata(commit, subject) 192 | raise UserAbortedException("User aborted at %s " % commit) 193 | except CalledProcessError as err: 194 | logging.error("%s failed to apply" % commit) 195 | _generate_edit_metadata(commit, subject) 196 | raise err 197 | if args.reject: 198 | subprocess.check_call(["git", "add", "."]) 199 | subprocess.check_call(["git", "commit", "-m", "[Patch] %s" % subject]) 200 | return patch_required 201 | 202 | 203 | def squash(args, patches): 204 | subject_re = re.compile("Subject: \[PATCH.*\] (.*)^\-\-\-\n", re.S | re.M) 205 | edit_section = args.section 206 | for section in patches["sections"]: 207 | if section["name"] == edit_section["name"]: 208 | break 209 | logging.info("Processing section %s" % section["name"]) 210 | d = vars(args) 211 | d['section'] = section 212 | section_apply(args, patches) 213 | 214 | head = subprocess.Popen(['git', 'rev-parse', 'HEAD'], 215 | stdout=subprocess.PIPE).communicate()[0].strip() 216 | 217 | subject = None 218 | for commit in edit_section["commits"]: 219 | logging.info("Processing: %s " % commit) 220 | with open('.patch/%s' % commit, 'r') as commit_file: 221 | data = commit_file.read() 222 | if commit == args.patch: 223 | subject = subject_re.search(data).group(1) 224 | logging.info(subject) 225 | try: 226 | subprocess.check_call(["git", "apply", "-3", ".patch/%s" % commit]) 227 | except CalledProcessError as err: 228 | logging.error("%s failed to apply" % commit) 229 | raise err 230 | 231 | subprocess.check_call(["git", "commit", "-m", subject]) 232 | generated = subprocess.Popen(['git', 'format-patch', '%s..HEAD' % head, "-o", ".patch"], 233 | stdout=subprocess.PIPE).communicate()[0] 234 | logging.debug(generated) 235 | commit_list = generated.splitlines() 236 | assert(len(commit_list) == 1) 237 | edit_section["commits"] = commit_list 238 | _write_config(patches) 239 | 240 | 241 | def fix(args, patches): 242 | with open(".patch/metadata_edit.yml") as yml: 243 | metadata = yaml.safe_load(yml) 244 | logging.debug(metadata) 245 | subprocess.check_call(["git", "commit", "-m", metadata['subject']]) 246 | generated = subprocess.Popen(['git', 'format-patch', '%s..HEAD' % metadata['head'], "-o", ".patch"], 247 | stdout=subprocess.PIPE).communicate()[0] 248 | logging.debug(generated) 249 | commit_list = generated.splitlines() 250 | assert(len(commit_list) == 1) 251 | logging.info("Move %s to .patch/%s" % (commit_list[0], metadata['patch'])) 252 | os.rename("%s" % commit_list[0], ".patch/%s" % metadata['patch']) 253 | os.unlink(".patch/metadata_edit.yml") 254 | 255 | 256 | def main(): 257 | _log_init() 258 | parser = argparse.ArgumentParser() 259 | sub_parsers = parser.add_subparsers() 260 | 261 | init_parser = sub_parsers.add_parser("init", help="Initialize branch which will be patched") 262 | init_parser.add_argument("-b", "--branch", required=True, help="Development branch") 263 | init_parser.set_defaults(func=init) 264 | 265 | branch_parser = sub_parsers.add_parser("create-branch", help="Create a new development branch") 266 | branch_parser.add_argument("-n", "--name", help="Name of branch", default="git_patch") 267 | branch_parser.add_argument("-r", "--remote", help="Name of Git Remote", default="upstream/master") 268 | fetch_parser = branch_parser.add_mutually_exclusive_group(required=False) 269 | fetch_parser.add_argument("--no-fetch", dest='fetch', help="Do not fetch from upstream", action='store_false') 270 | fetch_parser.add_argument("--fetch", dest='fetch', help="Fetch from upstream", action='store_true') 271 | branch_parser.set_defaults(func=create_branch, fetch=True) 272 | 273 | list_parser = sub_parsers.add_parser("list", help="List all patches") 274 | list_parser.set_defaults(func=list_patches) 275 | 276 | generate_parser = sub_parsers.add_parser("generate", help="Generate patches from tracked branch") 277 | generate_parser.set_defaults(func=generate) 278 | 279 | create_section_parser = sub_parsers.add_parser("create-section", help="Create a new patch section") 280 | create_section_parser.add_argument("-n", "--name", required=True, help="Name of section") 281 | create_section_parser.set_defaults(func=create_section) 282 | 283 | move_patch_parser = sub_parsers.add_parser("move-patch", help="Move patch to a new section") 284 | move_patch_parser.add_argument("-p", "--patch", required=True, help="File name of patch") 285 | move_patch_parser.add_argument("-t", "--to", required=True, help="Name of destination section") 286 | move_patch_parser.set_defaults(func=move_patch) 287 | 288 | patch_apply_parser = sub_parsers.add_parser("apply", help="Apply all patch") 289 | patch_apply_parser.add_argument("-p", "--patch", help="File name of patch to stop") 290 | patch_apply_parser.add_argument("--from-patch", dest='from_patch', help="Applies patches after the given file") 291 | patch_apply_parser.add_argument("--reject", help="Patches are applied using 3-way. Use reject instead", 292 | action='store_true') 293 | patch_apply_parser.set_defaults(func=patch_apply) 294 | 295 | fix_parser = sub_parsers.add_parser("fix-patch", help="Begin editing a patch") 296 | fix_parser.set_defaults(func=fix) 297 | 298 | patches = None 299 | 300 | if os.path.exists(".patch/config.yml"): 301 | with open(".patch/config.yml") as yml: 302 | patches = yaml.safe_load(yml) 303 | 304 | if 'version' not in patches: 305 | patches['version'] = _current_version 306 | 307 | for s in patches["sections"]: 308 | p = sub_parsers.add_parser(s["name"], help="Operations for %s" % s["name"]) 309 | sub_sub = p.add_subparsers() 310 | sub_list = sub_sub.add_parser("list", help="List all commits") 311 | sub_list.set_defaults(func=patch_commits, section=s) 312 | 313 | sub_apply = sub_sub.add_parser("apply", help="Apply a patch") 314 | sub_apply.add_argument("-p", "--patch", help="File name of patch to stop") 315 | sub_apply.add_argument("--from-patch", dest='from_patch', help="Applies patches after the given file") 316 | sub_apply.add_argument("--reject", help="Patches are applied using 3-way. Use reject instead", 317 | action='store_true') 318 | sub_apply.set_defaults(func=section_apply, section=s) 319 | 320 | squash_parser = sub_sub.add_parser("squash", help="Begin editing a patch") 321 | squash_parser.add_argument("-p", "--patch", help="File name of patch", required=True) 322 | squash_parser.set_defaults(func=squash, section=s) 323 | 324 | argument = parser.parse_args() 325 | argument.func(argument, patches) 326 | 327 | if __name__ == "__main__": 328 | main() 329 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | __author__ = 'rajatv' 2 | 3 | from setuptools import setup, find_packages 4 | from os import path 5 | 6 | here = path.abspath(path.dirname(__file__)) 7 | 8 | setup( 9 | name='git_patch', 10 | version='2.1.1', 11 | description='Patch management for open source fork projects', 12 | 13 | author='Rajat Venkatesh', 14 | author_email='rajatvenkatesh@alumni.cmu.edu', 15 | 16 | license='Apache 2.0', 17 | 18 | classifiers=[ 19 | 'Development Status :: 4 - Beta', 20 | 21 | 'Intended Audience :: Developers', 22 | 'Topic :: Software Development :: Build Tools', 23 | 24 | 'Programming Language :: Python :: 2', 25 | 'Programming Language :: Python :: 2.6', 26 | 'Programming Language :: Python :: 2.7' 27 | ], 28 | 29 | packages=find_packages(), 30 | install_requires=['pyaml', 'argparse'], 31 | 32 | entry_points={ 33 | 'console_scripts': [ 34 | 'git-patch=git_patch.git_patch:main', 35 | ], 36 | }, 37 | ) 38 | --------------------------------------------------------------------------------