]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/SetupGit.py
BaseTools/PatchCheck.py: Ignore CR and LF characters in subject length
[mirror_edk2.git] / BaseTools / Scripts / SetupGit.py
1 ## @file
2 # Set up the git configuration for contributing to TianoCore projects
3 #
4 # Copyright (c) 2019, Linaro Ltd. All rights reserved.<BR>
5 # Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
6 #
7 # SPDX-License-Identifier: BSD-2-Clause-Patent
8 #
9
10 from __future__ import print_function
11 import argparse
12 import os.path
13 import re
14 import sys
15
16 try:
17 import git
18 except ImportError:
19 print('Unable to load gitpython module - please install and try again.')
20 sys.exit(1)
21
22 try:
23 # Try Python 2 'ConfigParser' module first since helpful lib2to3 will
24 # otherwise automagically load it with the name 'configparser'
25 import ConfigParser
26 except ImportError:
27 # Otherwise, try loading the Python 3 'configparser' under an alias
28 try:
29 import configparser as ConfigParser
30 except ImportError:
31 print("Unable to load configparser/ConfigParser module - please install and try again!")
32 sys.exit(1)
33
34
35 # Assumptions: Script is in edk2/BaseTools/Scripts,
36 # templates in edk2/BaseTools/Conf
37 CONFDIR = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
38 'Conf')
39
40 UPSTREAMS = [
41 {'name': 'edk2',
42 'repo': 'https://github.com/tianocore/edk2.git',
43 'list': 'devel@edk2.groups.io'},
44 {'name': 'edk2-platforms',
45 'repo': 'https://github.com/tianocore/edk2-platforms.git',
46 'list': 'devel@edk2.groups.io', 'prefix': 'edk2-platforms'},
47 {'name': 'edk2-non-osi',
48 'repo': 'https://github.com/tianocore/edk2-non-osi.git',
49 'list': 'devel@edk2.groups.io', 'prefix': 'edk2-non-osi'}
50 ]
51
52 # The minimum version required for all of the below options to work
53 MIN_GIT_VERSION = (1, 9, 0)
54
55 # Set of options to be set identically for all repositories
56 OPTIONS = [
57 {'section': 'am', 'option': 'keepcr', 'value': True},
58 {'section': 'am', 'option': 'signoff', 'value': True},
59 {'section': 'cherry-pick', 'option': 'signoff', 'value': True},
60 {'section': 'color', 'option': 'diff', 'value': True},
61 {'section': 'color', 'option': 'grep', 'value': 'auto'},
62 {'section': 'commit', 'option': 'signoff', 'value': True},
63 {'section': 'core', 'option': 'abbrev', 'value': 12},
64 {'section': 'core', 'option': 'attributesFile',
65 'value': os.path.join(CONFDIR, 'gitattributes').replace('\\', '/')},
66 {'section': 'core', 'option': 'whitespace', 'value': 'cr-at-eol'},
67 {'section': 'diff', 'option': 'algorithm', 'value': 'patience'},
68 {'section': 'diff', 'option': 'orderFile',
69 'value': os.path.join(CONFDIR, 'diff.order').replace('\\', '/')},
70 {'section': 'diff', 'option': 'renames', 'value': 'copies'},
71 {'section': 'diff', 'option': 'statGraphWidth', 'value': '20'},
72 {'section': 'diff "ini"', 'option': 'xfuncname',
73 'value': '^\\\\[[A-Za-z0-9_., ]+]'},
74 {'section': 'format', 'option': 'coverLetter', 'value': True},
75 {'section': 'format', 'option': 'numbered', 'value': True},
76 {'section': 'format', 'option': 'signoff', 'value': False},
77 {'section': 'notes', 'option': 'rewriteRef', 'value': 'refs/notes/commits'},
78 {'section': 'sendemail', 'option': 'chainreplyto', 'value': False},
79 {'section': 'sendemail', 'option': 'thread', 'value': True},
80 {'section': 'sendemail', 'option': 'transferEncoding', 'value': '8bit'},
81 ]
82
83
84 def locate_repo():
85 """Opens a Repo object for the current tree, searching upwards in the directory hierarchy."""
86 try:
87 repo = git.Repo(path='.', search_parent_directories=True)
88 except (git.InvalidGitRepositoryError, git.NoSuchPathError):
89 print("It doesn't look like we're inside a git repository - aborting.")
90 sys.exit(2)
91 return repo
92
93
94 def fuzzy_match_repo_url(one, other):
95 """Compares two repository URLs, ignoring protocol and optional trailing '.git'."""
96 oneresult = re.match(r'.*://(?P<oneresult>.*?)(\.git)*$', one)
97 otherresult = re.match(r'.*://(?P<otherresult>.*?)(\.git)*$', other)
98
99 if oneresult and otherresult:
100 onestring = oneresult.group('oneresult')
101 otherstring = otherresult.group('otherresult')
102 if onestring == otherstring:
103 return True
104
105 return False
106
107
108 def get_upstream(url):
109 """Extracts the dict for the current repo origin."""
110 for upstream in UPSTREAMS:
111 if fuzzy_match_repo_url(upstream['repo'], url):
112 return upstream
113 print("Unknown upstream '%s' - aborting!" % url)
114 sys.exit(3)
115
116
117 def check_versions():
118 """Checks versions of dependencies."""
119 version = git.cmd.Git().version_info
120
121 if version < MIN_GIT_VERSION:
122 print('Need git version %d.%d or later!' % (version[0], version[1]))
123 sys.exit(4)
124
125
126 def write_config_value(repo, section, option, data):
127 """."""
128 with repo.config_writer(config_level='repository') as configwriter:
129 configwriter.set_value(section, option, data)
130
131
132 if __name__ == '__main__':
133 check_versions()
134
135 PARSER = argparse.ArgumentParser(
136 description='Sets up a git repository according to TianoCore rules.')
137 PARSER.add_argument('-c', '--check',
138 help='check current config only, printing what would be changed',
139 action='store_true',
140 required=False)
141 PARSER.add_argument('-f', '--force',
142 help='overwrite existing settings conflicting with program defaults',
143 action='store_true',
144 required=False)
145 PARSER.add_argument('-v', '--verbose',
146 help='enable more detailed output',
147 action='store_true',
148 required=False)
149 ARGS = PARSER.parse_args()
150
151 REPO = locate_repo()
152 if REPO.bare:
153 print('Bare repo - please check out an upstream one!')
154 sys.exit(6)
155
156 URL = REPO.remotes.origin.url
157
158 UPSTREAM = get_upstream(URL)
159 if not UPSTREAM:
160 print("Upstream '%s' unknown, aborting!" % URL)
161 sys.exit(7)
162
163 # Set a list email address if our upstream wants it
164 if 'list' in UPSTREAM:
165 OPTIONS.append({'section': 'sendemail', 'option': 'to',
166 'value': UPSTREAM['list']})
167 # Append a subject prefix entry to OPTIONS if our upstream wants it
168 if 'prefix' in UPSTREAM:
169 OPTIONS.append({'section': 'format', 'option': 'subjectPrefix',
170 'value': "PATCH " + UPSTREAM['prefix']})
171
172 CONFIG = REPO.config_reader(config_level='repository')
173
174 for entry in OPTIONS:
175 exists = False
176 try:
177 # Make sure to read boolean/int settings as real type rather than strings
178 if isinstance(entry['value'], bool):
179 value = CONFIG.getboolean(entry['section'], entry['option'])
180 elif isinstance(entry['value'], int):
181 value = CONFIG.getint(entry['section'], entry['option'])
182 else:
183 value = CONFIG.get(entry['section'], entry['option'])
184
185 exists = True
186 # Don't bail out from options not already being set
187 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
188 pass
189
190 if exists:
191 if value == entry['value']:
192 if ARGS.verbose:
193 print("%s.%s already set (to '%s')" % (entry['section'],
194 entry['option'], value))
195 else:
196 if ARGS.force:
197 write_config_value(REPO, entry['section'], entry['option'], entry['value'])
198 else:
199 print("Not overwriting existing %s.%s value:" % (entry['section'],
200 entry['option']))
201 print(" '%s' != '%s'" % (value, entry['value']))
202 print(" add '-f' to command line to force overwriting existing settings")
203 else:
204 print("%s.%s => '%s'" % (entry['section'], entry['option'], entry['value']))
205 if not ARGS.check:
206 write_config_value(REPO, entry['section'], entry['option'], entry['value'])