subcmds: Use repo logger

Bug: b/292704435
Change-Id: Ia3a45d87fc0bf0d4a1ba53050d9c3cd2dba20e55
Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/386236
Reviewed-by: Jason Chang <jasonnc@google.com>
Commit-Queue: Aravind Vasudevan <aravindvasudev@google.com>
Tested-by: Aravind Vasudevan <aravindvasudev@google.com>
This commit is contained in:
Aravind Vasudevan 2023-09-14 08:46:44 +00:00 committed by LUCI
parent c3d7c8536c
commit c993c5068e
12 changed files with 121 additions and 115 deletions

View File

@ -15,7 +15,6 @@
import collections import collections
import functools import functools
import itertools import itertools
import sys
from command import Command from command import Command
from command import DEFAULT_LOCAL_JOBS from command import DEFAULT_LOCAL_JOBS
@ -23,6 +22,10 @@ from error import RepoError
from error import RepoExitError from error import RepoExitError
from git_command import git from git_command import git
from progress import Progress from progress import Progress
from repo_logging import RepoLogger
logger = RepoLogger(__file__)
class AbandonError(RepoExitError): class AbandonError(RepoExitError):
@ -126,18 +129,12 @@ It is equivalent to "git branch -D <branchname>".
if err: if err:
for br in err.keys(): for br in err.keys():
err_msg = "error: cannot abandon %s" % br err_msg = "error: cannot abandon %s" % br
print(err_msg, file=sys.stderr) logger.error(err_msg)
for proj in err[br]: for proj in err[br]:
print( logger.error(" " * len(err_msg) + " | %s", _RelPath(proj))
" " * len(err_msg) + " | %s" % _RelPath(proj),
file=sys.stderr,
)
raise AbandonError(aggregate_errors=aggregate_errors) raise AbandonError(aggregate_errors=aggregate_errors)
elif not success: elif not success:
print( logger.error("error: no project has local branch(es) : %s", nb)
"error: no project has local branch(es) : %s" % nb,
file=sys.stderr,
)
raise AbandonError(aggregate_errors=aggregate_errors) raise AbandonError(aggregate_errors=aggregate_errors)
else: else:
# Everything below here is displaying status. # Everything below here is displaying status.

View File

@ -13,7 +13,6 @@
# limitations under the License. # limitations under the License.
import functools import functools
import sys
from typing import NamedTuple from typing import NamedTuple
from command import Command from command import Command
@ -22,6 +21,10 @@ from error import GitError
from error import RepoExitError from error import RepoExitError
from progress import Progress from progress import Progress
from project import Project from project import Project
from repo_logging import RepoLogger
logger = RepoLogger(__file__)
class CheckoutBranchResult(NamedTuple): class CheckoutBranchResult(NamedTuple):
@ -99,12 +102,9 @@ The command is equivalent to:
if err_projects: if err_projects:
for p in err_projects: for p in err_projects:
print( logger.error("error: %s/: cannot checkout %s", p.relpath, nb)
"error: %s/: cannot checkout %s" % (p.relpath, nb),
file=sys.stderr,
)
raise CheckoutCommandError(aggregate_errors=err) raise CheckoutCommandError(aggregate_errors=err)
elif not success: elif not success:
msg = f"error: no project has branch {nb}" msg = f"error: no project has branch {nb}"
print(msg, file=sys.stderr) logger.error(msg)
raise MissingBranchError(msg) raise MissingBranchError(msg)

View File

@ -18,9 +18,11 @@ import sys
from command import Command from command import Command
from error import GitError from error import GitError
from git_command import GitCommand from git_command import GitCommand
from repo_logging import RepoLogger
CHANGE_ID_RE = re.compile(r"^\s*Change-Id: I([0-9a-f]{40})\s*$") CHANGE_ID_RE = re.compile(r"^\s*Change-Id: I([0-9a-f]{40})\s*$")
logger = RepoLogger(__file__)
class CherryPick(Command): class CherryPick(Command):
@ -52,7 +54,7 @@ change id will be added.
try: try:
p.Wait() p.Wait()
except GitError: except GitError:
print(p.stderr, file=sys.stderr) logger.error(p.stderr)
raise raise
sha1 = p.stdout.strip() sha1 = p.stdout.strip()
@ -67,9 +69,7 @@ change id will be added.
try: try:
p.Wait() p.Wait()
except GitError: except GitError:
print( logger.error("error: Failed to retrieve old commit message")
"error: Failed to retrieve old commit message", file=sys.stderr
)
raise raise
old_msg = self._StripHeader(p.stdout) old_msg = self._StripHeader(p.stdout)
@ -85,14 +85,13 @@ change id will be added.
try: try:
p.Wait() p.Wait()
except GitError as e: except GitError as e:
print(str(e)) logger.error(e)
print( logger.warn(
"NOTE: When committing (please see above) and editing the " "NOTE: When committing (please see above) and editing the "
"commit message, please remove the old Change-Id-line and " "commit message, please remove the old Change-Id-line and "
"add:" "add:\n%s",
self._GetReference(sha1),
) )
print(self._GetReference(sha1), file=sys.stderr)
print(file=sys.stderr)
raise raise
if p.stdout: if p.stdout:
@ -115,10 +114,7 @@ change id will be added.
try: try:
p.Wait() p.Wait()
except GitError: except GitError:
print( logger.error("error: Failed to update commit message")
"error: Failed to update commit message",
file=sys.stderr,
)
raise raise
def _IsChangeId(self, line): def _IsChangeId(self, line):

View File

@ -19,9 +19,11 @@ from command import Command
from error import GitError from error import GitError
from error import NoSuchProjectError from error import NoSuchProjectError
from error import RepoExitError from error import RepoExitError
from repo_logging import RepoLogger
CHANGE_RE = re.compile(r"^([1-9][0-9]*)(?:[/\.-]([1-9][0-9]*))?$") CHANGE_RE = re.compile(r"^([1-9][0-9]*)(?:[/\.-]([1-9][0-9]*))?$")
logger = RepoLogger(__file__)
class DownloadCommandError(RepoExitError): class DownloadCommandError(RepoExitError):
@ -109,21 +111,16 @@ If no project is specified try to use current directory as a project.
except NoSuchProjectError: except NoSuchProjectError:
project = None project = None
if project not in projects: if project not in projects:
print( logger.error(
"error: %s matches too many projects; please " "error: %s matches too many projects; please "
"re-run inside the project checkout." % (a,), "re-run inside the project checkout.",
file=sys.stderr, a,
) )
for project in projects: for project in projects:
print( logger.error(
" %s/ @ %s" " %s/ @ %s",
% ( project.RelPath(local=opt.this_manifest_only),
project.RelPath(
local=opt.this_manifest_only
),
project.revisionExpr, project.revisionExpr,
),
file=sys.stderr,
) )
raise NoSuchProjectError() raise NoSuchProjectError()
else: else:
@ -156,18 +153,21 @@ If no project is specified try to use current directory as a project.
dl = project.DownloadPatchSet(change_id, ps_id) dl = project.DownloadPatchSet(change_id, ps_id)
if not opt.revert and not dl.commits: if not opt.revert and not dl.commits:
print( logger.error(
"[%s] change %d/%d has already been merged" "[%s] change %d/%d has already been merged",
% (project.name, change_id, ps_id), project.name,
file=sys.stderr, change_id,
ps_id,
) )
continue continue
if len(dl.commits) > 1: if len(dl.commits) > 1:
print( logger.error(
"[%s] %d/%d depends on %d unmerged changes:" "[%s] %d/%d depends on %d unmerged changes:",
% (project.name, change_id, ps_id, len(dl.commits)), project.name,
file=sys.stderr, change_id,
ps_id,
len(dl.commits),
) )
for c in dl.commits: for c in dl.commits:
print(" %s" % (c), file=sys.stderr) print(" %s" % (c), file=sys.stderr)
@ -204,9 +204,10 @@ If no project is specified try to use current directory as a project.
project._Checkout(dl.commit) project._Checkout(dl.commit)
except GitError: except GitError:
print( logger.error(
"[%s] Could not complete the %s of %s" "[%s] Could not complete the %s of %s",
% (project.name, mode, dl.commit), project.name,
file=sys.stderr, mode,
dl.commit,
) )
raise raise

View File

@ -28,8 +28,10 @@ from command import DEFAULT_LOCAL_JOBS
from command import MirrorSafeCommand from command import MirrorSafeCommand
from command import WORKER_BATCH_SIZE from command import WORKER_BATCH_SIZE
from error import ManifestInvalidRevisionError from error import ManifestInvalidRevisionError
from repo_logging import RepoLogger
logger = RepoLogger(__file__)
_CAN_COLOR = [ _CAN_COLOR = [
"branch", "branch",
"diff", "diff",
@ -293,10 +295,10 @@ without iterating through the remaining projects.
rc = rc or errno.EINTR rc = rc or errno.EINTR
except Exception as e: except Exception as e:
# Catch any other exceptions raised # Catch any other exceptions raised
print( logger.error(
"forall: unhandled error, terminating the pool: %s: %s" "forall: unhandled error, terminating the pool: %s: %s",
% (type(e).__name__, e), type(e).__name__,
file=sys.stderr, e,
) )
rc = rc or getattr(e, "errno", 1) rc = rc or getattr(e, "errno", 1)
if rc != 0: if rc != 0:

View File

@ -24,6 +24,10 @@ from error import InvalidArgumentsError
from error import SilentRepoExitError from error import SilentRepoExitError
from git_command import GitCommand from git_command import GitCommand
from project import Project from project import Project
from repo_logging import RepoLogger
logger = RepoLogger(__file__)
class GrepColoring(Coloring): class GrepColoring(Coloring):
@ -371,7 +375,7 @@ contain a line that matches both expressions:
if opt.revision: if opt.revision:
if "--cached" in cmd_argv: if "--cached" in cmd_argv:
msg = "fatal: cannot combine --cached and --revision" msg = "fatal: cannot combine --cached and --revision"
print(msg, file=sys.stderr) logger.error(msg)
raise InvalidArgumentsError(msg) raise InvalidArgumentsError(msg)
have_rev = True have_rev = True
cmd_argv.extend(opt.revision) cmd_argv.extend(opt.revision)
@ -396,5 +400,5 @@ contain a line that matches both expressions:
sys.exit(0) sys.exit(0)
elif have_rev and bad_rev: elif have_rev and bad_rev:
for r in opt.revision: for r in opt.revision:
print("error: can't search revision %s" % r, file=sys.stderr) logger.error("error: can't search revision %s", r)
raise GrepCommandError(aggregate_errors=errors) raise GrepCommandError(aggregate_errors=errors)

View File

@ -23,9 +23,12 @@ from error import UpdateManifestError
from git_command import git_require from git_command import git_require
from git_command import MIN_GIT_VERSION_HARD from git_command import MIN_GIT_VERSION_HARD
from git_command import MIN_GIT_VERSION_SOFT from git_command import MIN_GIT_VERSION_SOFT
from repo_logging import RepoLogger
from wrapper import Wrapper from wrapper import Wrapper
logger = RepoLogger(__file__)
_REPO_ALLOW_SHALLOW = os.environ.get("REPO_ALLOW_SHALLOW") _REPO_ALLOW_SHALLOW = os.environ.get("REPO_ALLOW_SHALLOW")
@ -330,11 +333,11 @@ to update the working directory files.
def Execute(self, opt, args): def Execute(self, opt, args):
git_require(MIN_GIT_VERSION_HARD, fail=True) git_require(MIN_GIT_VERSION_HARD, fail=True)
if not git_require(MIN_GIT_VERSION_SOFT): if not git_require(MIN_GIT_VERSION_SOFT):
print( logger.warning(
"repo: warning: git-%s+ will soon be required; please upgrade " "repo: warning: git-%s+ will soon be required; "
"your version of git to maintain support." "please upgrade your version of git to maintain "
% (".".join(str(x) for x in MIN_GIT_VERSION_SOFT),), "support.",
file=sys.stderr, ".".join(str(x) for x in MIN_GIT_VERSION_SOFT),
) )
rp = self.manifest.repoProject rp = self.manifest.repoProject
@ -357,10 +360,7 @@ to update the working directory files.
) )
except wrapper.CloneFailure as e: except wrapper.CloneFailure as e:
err_msg = "fatal: double check your --repo-rev setting." err_msg = "fatal: double check your --repo-rev setting."
print( logger.error(err_msg)
err_msg,
file=sys.stderr,
)
self.git_event_log.ErrorEvent(err_msg) self.git_event_log.ErrorEvent(err_msg)
raise RepoUnhandledExceptionError(e) raise RepoUnhandledExceptionError(e)

View File

@ -17,6 +17,10 @@ import os
import sys import sys
from command import PagedCommand from command import PagedCommand
from repo_logging import RepoLogger
logger = RepoLogger(__file__)
class Manifest(PagedCommand): class Manifest(PagedCommand):
@ -132,7 +136,7 @@ to indicate the remote ref to push changes to via 'repo upload'.
manifest.SetUseLocalManifests(not opt.ignore_local_manifests) manifest.SetUseLocalManifests(not opt.ignore_local_manifests)
if opt.json: if opt.json:
print("warning: --json is experimental!", file=sys.stderr) logger.warn("warning: --json is experimental!")
doc = manifest.ToDict( doc = manifest.ToDict(
peg_rev=opt.peg_rev, peg_rev=opt.peg_rev,
peg_rev_upstream=opt.peg_rev_upstream, peg_rev_upstream=opt.peg_rev_upstream,
@ -159,13 +163,13 @@ to indicate the remote ref to push changes to via 'repo upload'.
if output_file != "-": if output_file != "-":
fd.close() fd.close()
if manifest.path_prefix: if manifest.path_prefix:
print( logger.warn(
f"Saved {manifest.path_prefix} submanifest to " "Saved %s submanifest to %s",
f"{output_file}", manifest.path_prefix,
file=sys.stderr, output_file,
) )
else: else:
print(f"Saved manifest to {output_file}", file=sys.stderr) logger.warn("Saved manifest to %s", output_file)
def ValidateOptions(self, opt, args): def ValidateOptions(self, opt, args):
if args: if args:

View File

@ -17,6 +17,10 @@ import sys
from color import Coloring from color import Coloring
from command import Command from command import Command
from git_command import GitCommand from git_command import GitCommand
from repo_logging import RepoLogger
logger = RepoLogger(__file__)
class RebaseColoring(Coloring): class RebaseColoring(Coloring):
@ -104,17 +108,15 @@ branch but need to incorporate new upstream changes "underneath" them.
one_project = len(all_projects) == 1 one_project = len(all_projects) == 1
if opt.interactive and not one_project: if opt.interactive and not one_project:
print( logger.error(
"error: interactive rebase not supported with multiple " "error: interactive rebase not supported with multiple projects"
"projects",
file=sys.stderr,
) )
if len(args) == 1: if len(args) == 1:
print( logger.warn(
"note: project %s is mapped to more than one path" "note: project %s is mapped to more than one path", args[0]
% (args[0],),
file=sys.stderr,
) )
return 1 return 1
# Setup the common git rebase args that we use for all projects. # Setup the common git rebase args that we use for all projects.
@ -145,10 +147,9 @@ branch but need to incorporate new upstream changes "underneath" them.
cb = project.CurrentBranch cb = project.CurrentBranch
if not cb: if not cb:
if one_project: if one_project:
print( logger.error(
"error: project %s has a detached HEAD" "error: project %s has a detached HEAD",
% _RelPath(project), _RelPath(project),
file=sys.stderr,
) )
return 1 return 1
# Ignore branches with detached HEADs. # Ignore branches with detached HEADs.
@ -157,10 +158,9 @@ branch but need to incorporate new upstream changes "underneath" them.
upbranch = project.GetBranch(cb) upbranch = project.GetBranch(cb)
if not upbranch.LocalMerge: if not upbranch.LocalMerge:
if one_project: if one_project:
print( logger.error(
"error: project %s does not track any remote branches" "error: project %s does not track any remote branches",
% _RelPath(project), _RelPath(project),
file=sys.stderr,
) )
return 1 return 1
# Ignore branches without remotes. # Ignore branches without remotes.

View File

@ -13,15 +13,18 @@
# limitations under the License. # limitations under the License.
import optparse import optparse
import sys
from command import Command from command import Command
from command import MirrorSafeCommand from command import MirrorSafeCommand
from error import RepoExitError from error import RepoExitError
from repo_logging import RepoLogger
from subcmds.sync import _PostRepoFetch from subcmds.sync import _PostRepoFetch
from subcmds.sync import _PostRepoUpgrade from subcmds.sync import _PostRepoUpgrade
logger = RepoLogger(__file__)
class SelfupdateError(RepoExitError): class SelfupdateError(RepoExitError):
"""Exit error for failed selfupdate command.""" """Exit error for failed selfupdate command."""
@ -66,7 +69,7 @@ need to be performed by an end-user.
else: else:
result = rp.Sync_NetworkHalf() result = rp.Sync_NetworkHalf()
if result.error: if result.error:
print("error: can't update repo", file=sys.stderr) logger.error("error: can't update repo")
raise SelfupdateError(aggregate_errors=[result.error]) raise SelfupdateError(aggregate_errors=[result.error])
rp.bare_git.gc("--auto") rp.bare_git.gc("--auto")

View File

@ -17,6 +17,10 @@ import sys
from color import Coloring from color import Coloring
from command import InteractiveCommand from command import InteractiveCommand
from git_command import GitCommand from git_command import GitCommand
from repo_logging import RepoLogger
logger = RepoLogger(__file__)
class _ProjectList(Coloring): class _ProjectList(Coloring):
@ -62,7 +66,7 @@ The '%prog' command stages files to prepare the next commit.
if p.IsDirty() if p.IsDirty()
] ]
if not all_projects: if not all_projects:
print("no projects have uncommitted modifications", file=sys.stderr) logger.error("no projects have uncommitted modifications")
return return
out = _ProjectList(self.manifest.manifestProject.config) out = _ProjectList(self.manifest.manifestProject.config)

View File

@ -29,10 +29,12 @@ from git_command import GitCommand
from git_refs import R_HEADS from git_refs import R_HEADS
from hooks import RepoHook from hooks import RepoHook
from project import ReviewableBranch from project import ReviewableBranch
from repo_logging import RepoLogger
from subcmds.sync import LocalSyncState from subcmds.sync import LocalSyncState
_DEFAULT_UNUSUAL_COMMIT_THRESHOLD = 5 _DEFAULT_UNUSUAL_COMMIT_THRESHOLD = 5
logger = RepoLogger(__file__)
class UploadExitError(SilentRepoExitError): class UploadExitError(SilentRepoExitError):
@ -70,16 +72,16 @@ def _VerifyPendingCommits(branches: List[ReviewableBranch]) -> bool:
# If any branch has many commits, prompt the user. # If any branch has many commits, prompt the user.
if many_commits: if many_commits:
if len(branches) > 1: if len(branches) > 1:
print( logger.warn(
"ATTENTION: One or more branches has an unusually high number " "ATTENTION: One or more branches has an unusually high number "
"of commits." "of commits."
) )
else: else:
print( logger.warn(
"ATTENTION: You are uploading an unusually high number of " "ATTENTION: You are uploading an unusually high number of "
"commits." "commits."
) )
print( logger.warn(
"YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across " "YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across "
"branches?)" "branches?)"
) )
@ -93,7 +95,7 @@ def _VerifyPendingCommits(branches: List[ReviewableBranch]) -> bool:
def _die(fmt, *args): def _die(fmt, *args):
msg = fmt % args msg = fmt % args
print("error: %s" % msg, file=sys.stderr) logger.error("error: %s", msg)
raise UploadExitError(msg) raise UploadExitError(msg)
@ -748,16 +750,13 @@ Gerrit Code Review: https://www.gerritcodereview.com/
for result in results: for result in results:
project, avail = result project, avail = result
if avail is None: if avail is None:
print( logger.error(
'repo: error: %s: Unable to upload branch "%s". ' 'repo: error: %s: Unable to upload branch "%s". '
"You might be able to fix the branch by running:\n" "You might be able to fix the branch by running:\n"
" git branch --set-upstream-to m/%s" " git branch --set-upstream-to m/%s",
% (
project.RelPath(local=opt.this_manifest_only), project.RelPath(local=opt.this_manifest_only),
project.CurrentBranch, project.CurrentBranch,
project.manifest.branch, project.manifest.branch,
),
file=sys.stderr,
) )
elif avail: elif avail:
pending.append(result) pending.append(result)
@ -772,14 +771,11 @@ Gerrit Code Review: https://www.gerritcodereview.com/
if not pending: if not pending:
if opt.branch is None: if opt.branch is None:
print( logger.error("repo: error: no branches ready for upload")
"repo: error: no branches ready for upload", file=sys.stderr
)
else: else:
print( logger.error(
'repo: error: no branches named "%s" ready for upload' 'repo: error: no branches named "%s" ready for upload',
% (opt.branch,), opt.branch,
file=sys.stderr,
) )
return 1 return 1
@ -809,10 +805,9 @@ Gerrit Code Review: https://www.gerritcodereview.com/
project_list=pending_proj_names, worktree_list=pending_worktrees project_list=pending_proj_names, worktree_list=pending_worktrees
): ):
if LocalSyncState(manifest).IsPartiallySynced(): if LocalSyncState(manifest).IsPartiallySynced():
print( logger.error(
"Partially synced tree detected. Syncing all projects " "Partially synced tree detected. Syncing all projects "
"may resolve issues you're seeing.", "may resolve issues you're seeing."
file=sys.stderr,
) )
ret = 1 ret = 1
if ret: if ret: