]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/SetupGit.py
BaseTools/Scripts: Add log.mailmap to SetupGit.py
[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': 'log', 'option': 'mailmap', 'value': True},
78 {'section': 'notes', 'option': 'rewriteRef', 'value': 'refs/notes/commits'},
79 {'section': 'sendemail', 'option': 'chainreplyto', 'value': False},
80 {'section': 'sendemail', 'option': 'thread', 'value': True},
81 {'section': 'sendemail', 'option': 'transferEncoding', 'value': '8bit'},
82 ]
83
84
85 def locate_repo():
86 """Opens a Repo object for the current tree, searching upwards in the directory hierarchy."""
87 try:
88 repo = git.Repo(path='.', search_parent_directories=True)
89 except (git.InvalidGitRepositoryError, git.NoSuchPathError):
90 print("It doesn't look like we're inside a git repository - aborting.")
91 sys.exit(2)
92 return repo
93
94
95 def fuzzy_match_repo_url(one, other):
96 """Compares two repository URLs, ignoring protocol and optional trailing '.git'."""
97 oneresult = re.match(r'.*://(?P<oneresult>.*?)(\.git)*$', one)
98 otherresult = re.match(r'.*://(?P<otherresult>.*?)(\.git)*$', other)
99
100 if oneresult and otherresult:
101 onestring = oneresult.group('oneresult')
102 otherstring = otherresult.group('otherresult')
103 if onestring == otherstring:
104 return True
105
106 return False
107
108
109 def get_upstream(url):
110 """Extracts the dict for the current repo origin."""
111 for upstream in UPSTREAMS:
112 if fuzzy_match_repo_url(upstream['repo'], url):
113 return upstream
114 print("Unknown upstream '%s' - aborting!" % url)
115 sys.exit(3)
116
117
118 def check_versions():
119 """Checks versions of dependencies."""
120 version = git.cmd.Git().version_info
121
122 if version < MIN_GIT_VERSION:
123 print('Need git version %d.%d or later!' % (version[0], version[1]))
124 sys.exit(4)
125
126
127 def write_config_value(repo, section, option, data):
128 """."""
129 with repo.config_writer(config_level='repository') as configwriter:
130 configwriter.set_value(section, option, data)
131
132
133 if __name__ == '__main__':
134 check_versions()
135
136 PARSER = argparse.ArgumentParser(
137 description='Sets up a git repository according to TianoCore rules.')
138 PARSER.add_argument('-c', '--check',
139 help='check current config only, printing what would be changed',
140 action='store_true',
141 required=False)
142 PARSER.add_argument('-f', '--force',
143 help='overwrite existing settings conflicting with program defaults',
144 action='store_true',
145 required=False)
146 PARSER.add_argument('-v', '--verbose',
147 help='enable more detailed output',
148 action='store_true',
149 required=False)
150 ARGS = PARSER.parse_args()
151
152 REPO = locate_repo()
153 if REPO.bare:
154 print('Bare repo - please check out an upstream one!')
155 sys.exit(6)
156
157 URL = REPO.remotes.origin.url
158
159 UPSTREAM = get_upstream(URL)
160 if not UPSTREAM:
161 print("Upstream '%s' unknown, aborting!" % URL)
162 sys.exit(7)
163
164 # Set a list email address if our upstream wants it
165 if 'list' in UPSTREAM:
166 OPTIONS.append({'section': 'sendemail', 'option': 'to',
167 'value': UPSTREAM['list']})
168 # Append a subject prefix entry to OPTIONS if our upstream wants it
169 if 'prefix' in UPSTREAM:
170 OPTIONS.append({'section': 'format', 'option': 'subjectPrefix',
171 'value': "PATCH " + UPSTREAM['prefix']})
172
173 CONFIG = REPO.config_reader(config_level='repository')
174
175 for entry in OPTIONS:
176 exists = False
177 try:
178 # Make sure to read boolean/int settings as real type rather than strings
179 if isinstance(entry['value'], bool):
180 value = CONFIG.getboolean(entry['section'], entry['option'])
181 elif isinstance(entry['value'], int):
182 value = CONFIG.getint(entry['section'], entry['option'])
183 else:
184 value = CONFIG.get(entry['section'], entry['option'])
185
186 exists = True
187 # Don't bail out from options not already being set
188 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
189 pass
190
191 if exists:
192 if value == entry['value']:
193 if ARGS.verbose:
194 print("%s.%s already set (to '%s')" % (entry['section'],
195 entry['option'], value))
196 else:
197 if ARGS.force:
198 write_config_value(REPO, entry['section'], entry['option'], entry['value'])
199 else:
200 print("Not overwriting existing %s.%s value:" % (entry['section'],
201 entry['option']))
202 print(" '%s' != '%s'" % (value, entry['value']))
203 print(" add '-f' to command line to force overwriting existing settings")
204 else:
205 print("%s.%s => '%s'" % (entry['section'], entry['option'], entry['value']))
206 if not ARGS.check:
207 write_config_value(REPO, entry['section'], entry['option'], entry['value'])