patman: Convert camel case in gitutil.py

Convert this file to snake case and update all files which use it.

Signed-off-by: Simon Glass <sjg@chromium.org>
This commit is contained in:
Simon Glass 2022-01-29 14:14:11 -07:00
parent 967af26b6a
commit 0157b187f4
12 changed files with 99 additions and 99 deletions

View File

@ -442,7 +442,7 @@ class Builder:
""" """
self.commit = commit self.commit = commit
if checkout and self.checkout: if checkout and self.checkout:
gitutil.Checkout(commit.hash) gitutil.checkout(commit.hash)
def Make(self, commit, brd, stage, cwd, *args, **kwargs): def Make(self, commit, brd, stage, cwd, *args, **kwargs):
"""Run make """Run make
@ -1631,7 +1631,7 @@ class Builder:
# it but need to fetch from src_dir. # it but need to fetch from src_dir.
Print('\rFetching repo for thread %d' % thread_num, Print('\rFetching repo for thread %d' % thread_num,
newline=False) newline=False)
gitutil.Fetch(git_dir, thread_dir) gitutil.fetch(git_dir, thread_dir)
terminal.PrintClear() terminal.PrintClear()
elif os.path.isfile(git_dir): elif os.path.isfile(git_dir):
# This is a worktree of the src_dir repo, we don't need to # This is a worktree of the src_dir repo, we don't need to
@ -1645,12 +1645,12 @@ class Builder:
elif setup_git == 'worktree': elif setup_git == 'worktree':
Print('\rChecking out worktree for thread %d' % thread_num, Print('\rChecking out worktree for thread %d' % thread_num,
newline=False) newline=False)
gitutil.AddWorktree(src_dir, thread_dir) gitutil.add_worktree(src_dir, thread_dir)
terminal.PrintClear() terminal.PrintClear()
elif setup_git == 'clone' or setup_git == True: elif setup_git == 'clone' or setup_git == True:
Print('\rCloning repo for thread %d' % thread_num, Print('\rCloning repo for thread %d' % thread_num,
newline=False) newline=False)
gitutil.Clone(src_dir, thread_dir) gitutil.clone(src_dir, thread_dir)
terminal.PrintClear() terminal.PrintClear()
else: else:
raise ValueError("Can't setup git repo with %s." % setup_git) raise ValueError("Can't setup git repo with %s." % setup_git)
@ -1670,12 +1670,12 @@ class Builder:
builderthread.Mkdir(self._working_dir) builderthread.Mkdir(self._working_dir)
if setup_git and self.git_dir: if setup_git and self.git_dir:
src_dir = os.path.abspath(self.git_dir) src_dir = os.path.abspath(self.git_dir)
if gitutil.CheckWorktreeIsAvailable(src_dir): if gitutil.check_worktree_is_available(src_dir):
setup_git = 'worktree' setup_git = 'worktree'
# If we previously added a worktree but the directory for it # If we previously added a worktree but the directory for it
# got deleted, we need to prune its files from the repo so # got deleted, we need to prune its files from the repo so
# that we can check out another in its place. # that we can check out another in its place.
gitutil.PruneWorktrees(src_dir) gitutil.prune_worktrees(src_dir)
else: else:
setup_git = 'clone' setup_git = 'clone'

View File

@ -219,7 +219,7 @@ class BuilderThread(threading.Thread):
commit = self.builder.commits[commit_upto] commit = self.builder.commits[commit_upto]
if self.builder.checkout: if self.builder.checkout:
git_dir = os.path.join(work_dir, '.git') git_dir = os.path.join(work_dir, '.git')
gitutil.Checkout(commit.hash, git_dir, work_dir, gitutil.checkout(commit.hash, git_dir, work_dir,
force=True) force=True)
else: else:
commit = 'current' commit = 'current'

View File

@ -140,7 +140,7 @@ def DoBuildman(options, args, toolchains=None, make_func=None, boards=None,
) )
return 0 return 0
gitutil.Setup() gitutil.setup()
col = terminal.Color() col = terminal.Color()
options.git_dir = os.path.join(options.git, '.git') options.git_dir = os.path.join(options.git, '.git')
@ -236,10 +236,10 @@ def DoBuildman(options, args, toolchains=None, make_func=None, boards=None,
count = 1 count = 1
else: else:
if has_range: if has_range:
count, msg = gitutil.CountCommitsInRange(options.git_dir, count, msg = gitutil.count_commits_in_range(options.git_dir,
options.branch) options.branch)
else: else:
count, msg = gitutil.CountCommitsInBranch(options.git_dir, count, msg = gitutil.count_commits_in_branch(options.git_dir,
options.branch) options.branch)
if count is None: if count is None:
sys.exit(col.Color(col.RED, msg)) sys.exit(col.Color(col.RED, msg))
@ -276,9 +276,9 @@ def DoBuildman(options, args, toolchains=None, make_func=None, boards=None,
if has_range: if has_range:
range_expr = options.branch range_expr = options.branch
else: else:
range_expr = gitutil.GetRangeInBranch(options.git_dir, range_expr = gitutil.get_range_in_branch(options.git_dir,
options.branch) options.branch)
upstream_commit = gitutil.GetUpstream(options.git_dir, upstream_commit = gitutil.get_upstream(options.git_dir,
options.branch) options.branch)
series = patchstream.get_metadata_for_list(upstream_commit, series = patchstream.get_metadata_for_list(upstream_commit,
options.git_dir, 1, series=None, allow_overwrite=True) options.git_dir, 1, series=None, allow_overwrite=True)

View File

@ -267,11 +267,11 @@ class TestFunctional(unittest.TestCase):
def testGitSetup(self): def testGitSetup(self):
"""Test gitutils.Setup(), from outside the module itself""" """Test gitutils.Setup(), from outside the module itself"""
command.test_result = command.CommandResult(return_code=1) command.test_result = command.CommandResult(return_code=1)
gitutil.Setup() gitutil.setup()
self.assertEqual(gitutil.use_no_decorate, False) self.assertEqual(gitutil.use_no_decorate, False)
command.test_result = command.CommandResult(return_code=0) command.test_result = command.CommandResult(return_code=0)
gitutil.Setup() gitutil.setup()
self.assertEqual(gitutil.use_no_decorate, True) self.assertEqual(gitutil.use_no_decorate, True)
def _HandleCommandGitLog(self, args): def _HandleCommandGitLog(self, args):

View File

@ -21,7 +21,7 @@ RE_NOTE = re.compile(r'NOTE: (.*)')
def find_check_patch(): def find_check_patch():
top_level = gitutil.GetTopLevel() top_level = gitutil.get_top_level()
try_list = [ try_list = [
os.getcwd(), os.getcwd(),
os.path.join(os.getcwd(), '..', '..'), os.path.join(os.getcwd(), '..', '..'),

View File

@ -18,7 +18,7 @@ from patman import terminal
def setup(): def setup():
"""Do required setup before doing anything""" """Do required setup before doing anything"""
gitutil.Setup() gitutil.setup()
def prepare_patches(col, branch, count, start, end, ignore_binary, signoff): def prepare_patches(col, branch, count, start, end, ignore_binary, signoff):
"""Figure out what patches to generate, then generate them """Figure out what patches to generate, then generate them
@ -45,7 +45,7 @@ def prepare_patches(col, branch, count, start, end, ignore_binary, signoff):
""" """
if count == -1: if count == -1:
# Work out how many patches to send if we can # Work out how many patches to send if we can
count = (gitutil.CountCommitsToBranch(branch) - start) count = (gitutil.count_commits_to_branch(branch) - start)
if not count: if not count:
str = 'No commits found to process - please use -c flag, or run:\n' \ str = 'No commits found to process - please use -c flag, or run:\n' \
@ -55,7 +55,7 @@ def prepare_patches(col, branch, count, start, end, ignore_binary, signoff):
# Read the metadata from the commits # Read the metadata from the commits
to_do = count - end to_do = count - end
series = patchstream.get_metadata(branch, start, to_do) series = patchstream.get_metadata(branch, start, to_do)
cover_fname, patch_files = gitutil.CreatePatches( cover_fname, patch_files = gitutil.create_patches(
branch, start, to_do, ignore_binary, series, signoff) branch, start, to_do, ignore_binary, series, signoff)
# Fix up the patch files to our liking, and insert the cover letter # Fix up the patch files to our liking, and insert the cover letter
@ -138,7 +138,7 @@ def email_patches(col, series, cover_fname, patch_files, process_tags, its_a_go,
# Email the patches out (giving the user time to check / cancel) # Email the patches out (giving the user time to check / cancel)
cmd = '' cmd = ''
if its_a_go: if its_a_go:
cmd = gitutil.EmailPatches( cmd = gitutil.email_patches(
series, cover_fname, patch_files, dry_run, not ignore_bad_tags, series, cover_fname, patch_files, dry_run, not ignore_bad_tags,
cc_file, in_reply_to=in_reply_to, thread=thread, cc_file, in_reply_to=in_reply_to, thread=thread,
smtp_server=smtp_server) smtp_server=smtp_server)
@ -167,7 +167,7 @@ def send(args):
ok = check_patches(series, patch_files, args.check_patch, ok = check_patches(series, patch_files, args.check_patch,
args.verbose) args.verbose)
ok = ok and gitutil.CheckSuppressCCConfig() ok = ok and gitutil.check_suppress_cc_config()
its_a_go = ok or args.ignore_errors its_a_go = ok or args.ignore_errors
email_patches( email_patches(
@ -204,7 +204,7 @@ def patchwork_status(branch, count, start, end, dest_branch, force,
""" """
if count == -1: if count == -1:
# Work out how many patches to send if we can # Work out how many patches to send if we can
count = (gitutil.CountCommitsToBranch(branch) - start) count = (gitutil.count_commits_to_branch(branch) - start)
series = patchstream.get_metadata(branch, start, count - end) series = patchstream.get_metadata(branch, start, count - end)
warnings = 0 warnings = 0

View File

@ -208,7 +208,7 @@ class TestFunctional(unittest.TestCase):
cc_file = series.MakeCcFile(process_tags, cover_fname, cc_file = series.MakeCcFile(process_tags, cover_fname,
not ignore_bad_tags, add_maintainers, not ignore_bad_tags, add_maintainers,
None) None)
cmd = gitutil.EmailPatches( cmd = gitutil.email_patches(
series, cover_fname, args, dry_run, not ignore_bad_tags, series, cover_fname, args, dry_run, not ignore_bad_tags,
cc_file, in_reply_to=in_reply_to, thread=None) cc_file, in_reply_to=in_reply_to, thread=None)
series.ShowActions(args, cmd, process_tags) series.ShowActions(args, cmd, process_tags)
@ -466,7 +466,7 @@ complicated as possible''')
os.chdir(self.gitdir) os.chdir(self.gitdir)
# Check that it can detect the current branch # Check that it can detect the current branch
self.assertEqual(2, gitutil.CountCommitsToBranch(None)) self.assertEqual(2, gitutil.count_commits_to_branch(None))
col = terminal.Color() col = terminal.Color()
with capture_sys_output() as _: with capture_sys_output() as _:
_, cover_fname, patch_files = control.prepare_patches( _, cover_fname, patch_files = control.prepare_patches(
@ -476,7 +476,7 @@ complicated as possible''')
self.assertEqual(2, len(patch_files)) self.assertEqual(2, len(patch_files))
# Check that it can detect a different branch # Check that it can detect a different branch
self.assertEqual(3, gitutil.CountCommitsToBranch('second')) self.assertEqual(3, gitutil.count_commits_to_branch('second'))
with capture_sys_output() as _: with capture_sys_output() as _:
_, cover_fname, patch_files = control.prepare_patches( _, cover_fname, patch_files = control.prepare_patches(
col, branch='second', count=-1, start=0, end=0, col, branch='second', count=-1, start=0, end=0,
@ -622,7 +622,7 @@ diff --git a/lib/efi_loader/efi_memory.c b/lib/efi_loader/efi_memory.c
orig_dir = os.getcwd() orig_dir = os.getcwd()
os.chdir(self.gitdir) os.chdir(self.gitdir)
with self.assertRaises(ValueError) as exc: with self.assertRaises(ValueError) as exc:
gitutil.CountCommitsToBranch(None) gitutil.count_commits_to_branch(None)
self.assertIn( self.assertIn(
"Failed to determine upstream: fatal: no upstream configured for branch 'base'", "Failed to determine upstream: fatal: no upstream configured for branch 'base'",
str(exc.exception)) str(exc.exception))

View File

@ -12,10 +12,10 @@ from patman import settings
from patman import terminal from patman import terminal
from patman import tools from patman import tools
# True to use --no-decorate - we check this in Setup() # True to use --no-decorate - we check this in setup()
use_no_decorate = True use_no_decorate = True
def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False, def log_cmd(commit_range, git_dir=None, oneline=False, reverse=False,
count=None): count=None):
"""Create a command to perform a 'git log' """Create a command to perform a 'git log'
@ -49,7 +49,7 @@ def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False,
cmd.append('--') cmd.append('--')
return cmd return cmd
def CountCommitsToBranch(branch): def count_commits_to_branch(branch):
"""Returns number of commits between HEAD and the tracking branch. """Returns number of commits between HEAD and the tracking branch.
This looks back to the tracking branch and works out the number of commits This looks back to the tracking branch and works out the number of commits
@ -62,11 +62,11 @@ def CountCommitsToBranch(branch):
Number of patches that exist on top of the branch Number of patches that exist on top of the branch
""" """
if branch: if branch:
us, msg = GetUpstream('.git', branch) us, msg = get_upstream('.git', branch)
rev_range = '%s..%s' % (us, branch) rev_range = '%s..%s' % (us, branch)
else: else:
rev_range = '@{upstream}..' rev_range = '@{upstream}..'
pipe = [LogCmd(rev_range, oneline=True)] pipe = [log_cmd(rev_range, oneline=True)]
result = command.run_pipe(pipe, capture=True, capture_stderr=True, result = command.run_pipe(pipe, capture=True, capture_stderr=True,
oneline=True, raise_on_error=False) oneline=True, raise_on_error=False)
if result.return_code: if result.return_code:
@ -75,7 +75,7 @@ def CountCommitsToBranch(branch):
patch_count = len(result.stdout.splitlines()) patch_count = len(result.stdout.splitlines())
return patch_count return patch_count
def NameRevision(commit_hash): def name_revision(commit_hash):
"""Gets the revision name for a commit """Gets the revision name for a commit
Args: Args:
@ -91,7 +91,7 @@ def NameRevision(commit_hash):
name = stdout.split(' ')[1].strip() name = stdout.split(' ')[1].strip()
return name return name
def GuessUpstream(git_dir, branch): def guess_upstream(git_dir, branch):
"""Tries to guess the upstream for a branch """Tries to guess the upstream for a branch
This lists out top commits on a branch and tries to find a suitable This lists out top commits on a branch and tries to find a suitable
@ -107,21 +107,21 @@ def GuessUpstream(git_dir, branch):
Name of upstream branch (e.g. 'upstream/master') or None if none Name of upstream branch (e.g. 'upstream/master') or None if none
Warning/error message, or None if none Warning/error message, or None if none
""" """
pipe = [LogCmd(branch, git_dir=git_dir, oneline=True, count=100)] pipe = [log_cmd(branch, git_dir=git_dir, oneline=True, count=100)]
result = command.run_pipe(pipe, capture=True, capture_stderr=True, result = command.run_pipe(pipe, capture=True, capture_stderr=True,
raise_on_error=False) raise_on_error=False)
if result.return_code: if result.return_code:
return None, "Branch '%s' not found" % branch return None, "Branch '%s' not found" % branch
for line in result.stdout.splitlines()[1:]: for line in result.stdout.splitlines()[1:]:
commit_hash = line.split(' ')[0] commit_hash = line.split(' ')[0]
name = NameRevision(commit_hash) name = name_revision(commit_hash)
if '~' not in name and '^' not in name: if '~' not in name and '^' not in name:
if name.startswith('remotes/'): if name.startswith('remotes/'):
name = name[8:] name = name[8:]
return name, "Guessing upstream as '%s'" % name return name, "Guessing upstream as '%s'" % name
return None, "Cannot find a suitable upstream for branch '%s'" % branch return None, "Cannot find a suitable upstream for branch '%s'" % branch
def GetUpstream(git_dir, branch): def get_upstream(git_dir, branch):
"""Returns the name of the upstream for a branch """Returns the name of the upstream for a branch
Args: Args:
@ -139,7 +139,7 @@ def GetUpstream(git_dir, branch):
merge = command.output_one_line('git', '--git-dir', git_dir, 'config', merge = command.output_one_line('git', '--git-dir', git_dir, 'config',
'branch.%s.merge' % branch) 'branch.%s.merge' % branch)
except: except:
upstream, msg = GuessUpstream(git_dir, branch) upstream, msg = guess_upstream(git_dir, branch)
return upstream, msg return upstream, msg
if remote == '.': if remote == '.':
@ -152,7 +152,7 @@ def GetUpstream(git_dir, branch):
"'%s' remote='%s', merge='%s'" % (branch, remote, merge)) "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
def GetRangeInBranch(git_dir, branch, include_upstream=False): def get_range_in_branch(git_dir, branch, include_upstream=False):
"""Returns an expression for the commits in the given branch. """Returns an expression for the commits in the given branch.
Args: Args:
@ -162,13 +162,13 @@ def GetRangeInBranch(git_dir, branch, include_upstream=False):
Expression in the form 'upstream..branch' which can be used to Expression in the form 'upstream..branch' which can be used to
access the commits. If the branch does not exist, returns None. access the commits. If the branch does not exist, returns None.
""" """
upstream, msg = GetUpstream(git_dir, branch) upstream, msg = get_upstream(git_dir, branch)
if not upstream: if not upstream:
return None, msg return None, msg
rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch) rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
return rstr, msg return rstr, msg
def CountCommitsInRange(git_dir, range_expr): def count_commits_in_range(git_dir, range_expr):
"""Returns the number of commits in the given range. """Returns the number of commits in the given range.
Args: Args:
@ -178,7 +178,7 @@ def CountCommitsInRange(git_dir, range_expr):
Number of patches that exist in the supplied range or None if none Number of patches that exist in the supplied range or None if none
were found were found
""" """
pipe = [LogCmd(range_expr, git_dir=git_dir, oneline=True)] pipe = [log_cmd(range_expr, git_dir=git_dir, oneline=True)]
result = command.run_pipe(pipe, capture=True, capture_stderr=True, result = command.run_pipe(pipe, capture=True, capture_stderr=True,
raise_on_error=False) raise_on_error=False)
if result.return_code: if result.return_code:
@ -186,7 +186,7 @@ def CountCommitsInRange(git_dir, range_expr):
patch_count = len(result.stdout.splitlines()) patch_count = len(result.stdout.splitlines())
return patch_count, None return patch_count, None
def CountCommitsInBranch(git_dir, branch, include_upstream=False): def count_commits_in_branch(git_dir, branch, include_upstream=False):
"""Returns the number of commits in the given branch. """Returns the number of commits in the given branch.
Args: Args:
@ -196,12 +196,12 @@ def CountCommitsInBranch(git_dir, branch, include_upstream=False):
Number of patches that exist on top of the branch, or None if the Number of patches that exist on top of the branch, or None if the
branch does not exist. branch does not exist.
""" """
range_expr, msg = GetRangeInBranch(git_dir, branch, include_upstream) range_expr, msg = get_range_in_branch(git_dir, branch, include_upstream)
if not range_expr: if not range_expr:
return None, msg return None, msg
return CountCommitsInRange(git_dir, range_expr) return count_commits_in_range(git_dir, range_expr)
def CountCommits(commit_range): def count_commits(commit_range):
"""Returns the number of commits in the given range. """Returns the number of commits in the given range.
Args: Args:
@ -209,13 +209,13 @@ def CountCommits(commit_range):
Return: Return:
Number of patches that exist on top of the branch Number of patches that exist on top of the branch
""" """
pipe = [LogCmd(commit_range, oneline=True), pipe = [log_cmd(commit_range, oneline=True),
['wc', '-l']] ['wc', '-l']]
stdout = command.run_pipe(pipe, capture=True, oneline=True).stdout stdout = command.run_pipe(pipe, capture=True, oneline=True).stdout
patch_count = int(stdout) patch_count = int(stdout)
return patch_count return patch_count
def Checkout(commit_hash, git_dir=None, work_tree=None, force=False): def checkout(commit_hash, git_dir=None, work_tree=None, force=False):
"""Checkout the selected commit for this build """Checkout the selected commit for this build
Args: Args:
@ -235,7 +235,7 @@ def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
if result.return_code != 0: if result.return_code != 0:
raise OSError('git checkout (%s): %s' % (pipe, result.stderr)) raise OSError('git checkout (%s): %s' % (pipe, result.stderr))
def Clone(git_dir, output_dir): def clone(git_dir, output_dir):
"""Checkout the selected commit for this build """Checkout the selected commit for this build
Args: Args:
@ -247,7 +247,7 @@ def Clone(git_dir, output_dir):
if result.return_code != 0: if result.return_code != 0:
raise OSError('git clone: %s' % result.stderr) raise OSError('git clone: %s' % result.stderr)
def Fetch(git_dir=None, work_tree=None): def fetch(git_dir=None, work_tree=None):
"""Fetch from the origin repo """Fetch from the origin repo
Args: Args:
@ -263,7 +263,7 @@ def Fetch(git_dir=None, work_tree=None):
if result.return_code != 0: if result.return_code != 0:
raise OSError('git fetch: %s' % result.stderr) raise OSError('git fetch: %s' % result.stderr)
def CheckWorktreeIsAvailable(git_dir): def check_worktree_is_available(git_dir):
"""Check if git-worktree functionality is available """Check if git-worktree functionality is available
Args: Args:
@ -277,7 +277,7 @@ def CheckWorktreeIsAvailable(git_dir):
raise_on_error=False) raise_on_error=False)
return result.return_code == 0 return result.return_code == 0
def AddWorktree(git_dir, output_dir, commit_hash=None): def add_worktree(git_dir, output_dir, commit_hash=None):
"""Create and checkout a new git worktree for this build """Create and checkout a new git worktree for this build
Args: Args:
@ -294,7 +294,7 @@ def AddWorktree(git_dir, output_dir, commit_hash=None):
if result.return_code != 0: if result.return_code != 0:
raise OSError('git worktree add: %s' % result.stderr) raise OSError('git worktree add: %s' % result.stderr)
def PruneWorktrees(git_dir): def prune_worktrees(git_dir):
"""Remove administrative files for deleted worktrees """Remove administrative files for deleted worktrees
Args: Args:
@ -305,7 +305,7 @@ def PruneWorktrees(git_dir):
if result.return_code != 0: if result.return_code != 0:
raise OSError('git worktree prune: %s' % result.stderr) raise OSError('git worktree prune: %s' % result.stderr)
def CreatePatches(branch, start, count, ignore_binary, series, signoff = True): def create_patches(branch, start, count, ignore_binary, series, signoff = True):
"""Create a series of patches from the top of the current branch. """Create a series of patches from the top of the current branch.
The patch files are written to the current directory using The patch files are written to the current directory using
@ -345,7 +345,7 @@ def CreatePatches(branch, start, count, ignore_binary, series, signoff = True):
else: else:
return None, files return None, files
def BuildEmailList(in_list, tag=None, alias=None, warn_on_error=True): def build_email_list(in_list, tag=None, alias=None, warn_on_error=True):
"""Build a list of email addresses based on an input list. """Build a list of email addresses based on an input list.
Takes a list of email addresses and aliases, and turns this into a list Takes a list of email addresses and aliases, and turns this into a list
@ -371,18 +371,18 @@ def BuildEmailList(in_list, tag=None, alias=None, warn_on_error=True):
>>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>'] >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
>>> alias['boys'] = ['fred', ' john'] >>> alias['boys'] = ['fred', ' john']
>>> alias['all'] = ['fred ', 'john', ' mary '] >>> alias['all'] = ['fred ', 'john', ' mary ']
>>> BuildEmailList(['john', 'mary'], None, alias) >>> build_email_list(['john', 'mary'], None, alias)
['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>'] ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
>>> BuildEmailList(['john', 'mary'], '--to', alias) >>> build_email_list(['john', 'mary'], '--to', alias)
['--to "j.bloggs@napier.co.nz"', \ ['--to "j.bloggs@napier.co.nz"', \
'--to "Mary Poppins <m.poppins@cloud.net>"'] '--to "Mary Poppins <m.poppins@cloud.net>"']
>>> BuildEmailList(['john', 'mary'], 'Cc', alias) >>> build_email_list(['john', 'mary'], 'Cc', alias)
['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>'] ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
""" """
quote = '"' if tag and tag[0] == '-' else '' quote = '"' if tag and tag[0] == '-' else ''
raw = [] raw = []
for item in in_list: for item in in_list:
raw += LookupEmail(item, alias, warn_on_error=warn_on_error) raw += lookup_email(item, alias, warn_on_error=warn_on_error)
result = [] result = []
for item in raw: for item in raw:
if not item in result: if not item in result:
@ -391,7 +391,7 @@ def BuildEmailList(in_list, tag=None, alias=None, warn_on_error=True):
return ['%s %s%s%s' % (tag, quote, email, quote) for email in result] return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
return result return result
def CheckSuppressCCConfig(): def check_suppress_cc_config():
"""Check if sendemail.suppresscc is configured correctly. """Check if sendemail.suppresscc is configured correctly.
Returns: Returns:
@ -416,7 +416,7 @@ def CheckSuppressCCConfig():
return True return True
def EmailPatches(series, cover_fname, args, dry_run, warn_on_error, cc_fname, def email_patches(series, cover_fname, args, dry_run, warn_on_error, cc_fname,
self_only=False, alias=None, in_reply_to=None, thread=False, self_only=False, alias=None, in_reply_to=None, thread=False,
smtp_server=None): smtp_server=None):
"""Email a patch series. """Email a patch series.
@ -453,20 +453,20 @@ def EmailPatches(series, cover_fname, args, dry_run, warn_on_error, cc_fname,
>>> series = {} >>> series = {}
>>> series['to'] = ['fred'] >>> series['to'] = ['fred']
>>> series['cc'] = ['mary'] >>> series['cc'] = ['mary']
>>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \ >>> email_patches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
False, alias) False, alias)
'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \ 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
"m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" cover p1 p2' "m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" cover p1 p2'
>>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \ >>> email_patches(series, None, ['p1'], True, True, 'cc-fname', False, \
alias) alias)
'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \ 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
"m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" p1' "m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" p1'
>>> series['cc'] = ['all'] >>> series['cc'] = ['all']
>>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \ >>> email_patches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
True, alias) True, alias)
'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \ 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
send --cc-cmd cc-fname" cover p1 p2' send --cc-cmd cc-fname" cover p1 p2'
>>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \ >>> email_patches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
False, alias) False, alias)
'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \ 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
"f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \ "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
@ -475,7 +475,7 @@ send --cc-cmd cc-fname" cover p1 p2'
# Restore argv[0] since we clobbered it. # Restore argv[0] since we clobbered it.
>>> sys.argv[0] = _old_argv0 >>> sys.argv[0] = _old_argv0
""" """
to = BuildEmailList(series.get('to'), '--to', alias, warn_on_error) to = build_email_list(series.get('to'), '--to', alias, warn_on_error)
if not to: if not to:
git_config_to = command.output('git', 'config', 'sendemail.to', git_config_to = command.output('git', 'config', 'sendemail.to',
raise_on_error=False) raise_on_error=False)
@ -486,10 +486,10 @@ send --cc-cmd cc-fname" cover p1 p2'
"Or do something like this\n" "Or do something like this\n"
"git config sendemail.to u-boot@lists.denx.de") "git config sendemail.to u-boot@lists.denx.de")
return return
cc = BuildEmailList(list(set(series.get('cc')) - set(series.get('to'))), cc = build_email_list(list(set(series.get('cc')) - set(series.get('to'))),
'--cc', alias, warn_on_error) '--cc', alias, warn_on_error)
if self_only: if self_only:
to = BuildEmailList([os.getenv('USER')], '--to', alias, warn_on_error) to = build_email_list([os.getenv('USER')], '--to', alias, warn_on_error)
cc = [] cc = []
cmd = ['git', 'send-email', '--annotate'] cmd = ['git', 'send-email', '--annotate']
if smtp_server: if smtp_server:
@ -511,7 +511,7 @@ send --cc-cmd cc-fname" cover p1 p2'
return cmdstr return cmdstr
def LookupEmail(lookup_name, alias=None, warn_on_error=True, level=0): def lookup_email(lookup_name, alias=None, warn_on_error=True, level=0):
"""If an email address is an alias, look it up and return the full name """If an email address is an alias, look it up and return the full name
TODO: Why not just use git's own alias feature? TODO: Why not just use git's own alias feature?
@ -538,25 +538,25 @@ def LookupEmail(lookup_name, alias=None, warn_on_error=True, level=0):
>>> alias['all'] = ['fred ', 'john', ' mary '] >>> alias['all'] = ['fred ', 'john', ' mary ']
>>> alias['loop'] = ['other', 'john', ' mary '] >>> alias['loop'] = ['other', 'john', ' mary ']
>>> alias['other'] = ['loop', 'john', ' mary '] >>> alias['other'] = ['loop', 'john', ' mary ']
>>> LookupEmail('mary', alias) >>> lookup_email('mary', alias)
['m.poppins@cloud.net'] ['m.poppins@cloud.net']
>>> LookupEmail('arthur.wellesley@howe.ro.uk', alias) >>> lookup_email('arthur.wellesley@howe.ro.uk', alias)
['arthur.wellesley@howe.ro.uk'] ['arthur.wellesley@howe.ro.uk']
>>> LookupEmail('boys', alias) >>> lookup_email('boys', alias)
['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz'] ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
>>> LookupEmail('all', alias) >>> lookup_email('all', alias)
['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net'] ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
>>> LookupEmail('odd', alias) >>> lookup_email('odd', alias)
Alias 'odd' not found Alias 'odd' not found
[] []
>>> LookupEmail('loop', alias) >>> lookup_email('loop', alias)
Traceback (most recent call last): Traceback (most recent call last):
... ...
OSError: Recursive email alias at 'other' OSError: Recursive email alias at 'other'
>>> LookupEmail('odd', alias, warn_on_error=False) >>> lookup_email('odd', alias, warn_on_error=False)
[] []
>>> # In this case the loop part will effectively be ignored. >>> # In this case the loop part will effectively be ignored.
>>> LookupEmail('loop', alias, warn_on_error=False) >>> lookup_email('loop', alias, warn_on_error=False)
Recursive email alias at 'other' Recursive email alias at 'other'
Recursive email alias at 'john' Recursive email alias at 'john'
Recursive email alias at 'mary' Recursive email alias at 'mary'
@ -587,14 +587,14 @@ def LookupEmail(lookup_name, alias=None, warn_on_error=True, level=0):
print(col.Color(col.RED, msg)) print(col.Color(col.RED, msg))
return out_list return out_list
for item in alias[lookup_name]: for item in alias[lookup_name]:
todo = LookupEmail(item, alias, warn_on_error, level + 1) todo = lookup_email(item, alias, warn_on_error, level + 1)
for new_item in todo: for new_item in todo:
if not new_item in out_list: if not new_item in out_list:
out_list.append(new_item) out_list.append(new_item)
return out_list return out_list
def GetTopLevel(): def get_top_level():
"""Return name of top-level directory for this git repo. """Return name of top-level directory for this git repo.
Returns: Returns:
@ -603,12 +603,12 @@ def GetTopLevel():
This test makes sure that we are running tests in the right subdir This test makes sure that we are running tests in the right subdir
>>> os.path.realpath(os.path.dirname(__file__)) == \ >>> os.path.realpath(os.path.dirname(__file__)) == \
os.path.join(GetTopLevel(), 'tools', 'patman') os.path.join(get_top_level(), 'tools', 'patman')
True True
""" """
return command.output_one_line('git', 'rev-parse', '--show-toplevel') return command.output_one_line('git', 'rev-parse', '--show-toplevel')
def GetAliasFile(): def get_alias_file():
"""Gets the name of the git alias file. """Gets the name of the git alias file.
Returns: Returns:
@ -623,9 +623,9 @@ def GetAliasFile():
if os.path.isabs(fname): if os.path.isabs(fname):
return fname return fname
return os.path.join(GetTopLevel(), fname) return os.path.join(get_top_level(), fname)
def GetDefaultUserName(): def get_default_user_name():
"""Gets the user.name from .gitconfig file. """Gets the user.name from .gitconfig file.
Returns: Returns:
@ -634,7 +634,7 @@ def GetDefaultUserName():
uname = command.output_one_line('git', 'config', '--global', 'user.name') uname = command.output_one_line('git', 'config', '--global', 'user.name')
return uname return uname
def GetDefaultUserEmail(): def get_default_user_email():
"""Gets the user.email from the global .gitconfig file. """Gets the user.email from the global .gitconfig file.
Returns: Returns:
@ -643,7 +643,7 @@ def GetDefaultUserEmail():
uemail = command.output_one_line('git', 'config', '--global', 'user.email') uemail = command.output_one_line('git', 'config', '--global', 'user.email')
return uemail return uemail
def GetDefaultSubjectPrefix(): def get_default_subject_prefix():
"""Gets the format.subjectprefix from local .git/config file. """Gets the format.subjectprefix from local .git/config file.
Returns: Returns:
@ -654,19 +654,19 @@ def GetDefaultSubjectPrefix():
return sub_prefix return sub_prefix
def Setup(): def setup():
"""Set up git utils, by reading the alias files.""" """Set up git utils, by reading the alias files."""
# Check for a git alias file also # Check for a git alias file also
global use_no_decorate global use_no_decorate
alias_fname = GetAliasFile() alias_fname = get_alias_file()
if alias_fname: if alias_fname:
settings.ReadGitAliases(alias_fname) settings.ReadGitAliases(alias_fname)
cmd = LogCmd(None, count=0) cmd = log_cmd(None, count=0)
use_no_decorate = (command.run_pipe([cmd], raise_on_error=False) use_no_decorate = (command.run_pipe([cmd], raise_on_error=False)
.return_code == 0) .return_code == 0)
def GetHead(): def get_head():
"""Get the hash of the current HEAD """Get the hash of the current HEAD
Returns: Returns:

View File

@ -698,7 +698,7 @@ def get_list(commit_range, git_dir=None, count=None):
Returns Returns
str: String containing the contents of the git log str: String containing the contents of the git log
""" """
params = gitutil.LogCmd(commit_range, reverse=True, count=count, params = gitutil.log_cmd(commit_range, reverse=True, count=count,
git_dir=git_dir) git_dir=git_dir)
return command.run_pipe([params], capture=True).stdout return command.run_pipe([params], capture=True).stdout

View File

@ -16,7 +16,7 @@ def DetectProject():
The name of the project, like "linux" or "u-boot". Returns "unknown" The name of the project, like "linux" or "u-boot". Returns "unknown"
if we can't detect the project. if we can't detect the project.
""" """
top_level = gitutil.GetTopLevel() top_level = gitutil.get_top_level()
if os.path.exists(os.path.join(top_level, "include", "u-boot")): if os.path.exists(os.path.join(top_level, "include", "u-boot")):
return "u-boot" return "u-boot"

View File

@ -105,8 +105,8 @@ class Series(dict):
cmd: The git command we would have run cmd: The git command we would have run
process_tags: Process tags as if they were aliases process_tags: Process tags as if they were aliases
""" """
to_set = set(gitutil.BuildEmailList(self.to)); to_set = set(gitutil.build_email_list(self.to));
cc_set = set(gitutil.BuildEmailList(self.cc)); cc_set = set(gitutil.build_email_list(self.cc));
col = terminal.Color() col = terminal.Color()
print('Dry run, so not doing much. But I would do this:') print('Dry run, so not doing much. But I would do this:')
@ -136,7 +136,7 @@ class Series(dict):
print('Postfix:\t ', self.get('postfix')) print('Postfix:\t ', self.get('postfix'))
if self.cover: if self.cover:
print('Cover: %d lines' % len(self.cover)) print('Cover: %d lines' % len(self.cover))
cover_cc = gitutil.BuildEmailList(self.get('cover_cc', '')) cover_cc = gitutil.build_email_list(self.get('cover_cc', ''))
all_ccs = itertools.chain(cover_cc, *self._generated_cc.values()) all_ccs = itertools.chain(cover_cc, *self._generated_cc.values())
for email in sorted(set(all_ccs) - to_set - cc_set): for email in sorted(set(all_ccs) - to_set - cc_set):
print(' Cc: ', email) print(' Cc: ', email)
@ -261,14 +261,14 @@ class Series(dict):
for commit in self.commits: for commit in self.commits:
cc = [] cc = []
if process_tags: if process_tags:
cc += gitutil.BuildEmailList(commit.tags, cc += gitutil.build_email_list(commit.tags,
warn_on_error=warn_on_error) warn_on_error=warn_on_error)
cc += gitutil.BuildEmailList(commit.cc_list, cc += gitutil.build_email_list(commit.cc_list,
warn_on_error=warn_on_error) warn_on_error=warn_on_error)
if type(add_maintainers) == type(cc): if type(add_maintainers) == type(cc):
cc += add_maintainers cc += add_maintainers
elif add_maintainers: elif add_maintainers:
dir_list = [os.path.join(gitutil.GetTopLevel(), 'scripts')] dir_list = [os.path.join(gitutil.get_top_level(), 'scripts')]
cc += get_maintainer.get_maintainer(dir_list, commit.patch) cc += get_maintainer.get_maintainer(dir_list, commit.patch)
for x in set(cc) & set(settings.bounces): for x in set(cc) & set(settings.bounces):
print(col.Color(col.YELLOW, 'Skipping "%s"' % x)) print(col.Color(col.YELLOW, 'Skipping "%s"' % x))
@ -280,7 +280,7 @@ class Series(dict):
self._generated_cc[commit.patch] = cc self._generated_cc[commit.patch] = cc
if cover_fname: if cover_fname:
cover_cc = gitutil.BuildEmailList(self.get('cover_cc', '')) cover_cc = gitutil.build_email_list(self.get('cover_cc', ''))
cover_cc = list(set(cover_cc + all_ccs)) cover_cc = list(set(cover_cc + all_ccs))
if limit is not None: if limit is not None:
cover_cc = cover_cc[:limit] cover_cc = cover_cc[:limit]
@ -309,7 +309,7 @@ class Series(dict):
Return: Return:
Patch string, like 'RFC PATCH v5' or just 'PATCH' Patch string, like 'RFC PATCH v5' or just 'PATCH'
""" """
git_prefix = gitutil.GetDefaultSubjectPrefix() git_prefix = gitutil.get_default_subject_prefix()
if git_prefix: if git_prefix:
git_prefix = '%s][' % git_prefix git_prefix = '%s][' % git_prefix
else: else:

View File

@ -198,11 +198,11 @@ def CreatePatmanConfigFile(gitutil, config_fname):
Returns: Returns:
None None
""" """
name = gitutil.GetDefaultUserName() name = gitutil.get_default_user_name()
if name == None: if name == None:
name = raw_input("Enter name: ") name = raw_input("Enter name: ")
email = gitutil.GetDefaultUserEmail() email = gitutil.get_default_user_email()
if email == None: if email == None:
email = raw_input("Enter email: ") email = raw_input("Enter email: ")