Use logging from gbp and delete the msger module
authorEd Bartosh <eduard.bartosh@intel.com>
Wed, 14 Nov 2012 16:32:34 +0000 (18:32 +0200)
committerEd Bartosh <eduard.bartosh@intel.com>
Thu, 6 Dec 2012 11:02:38 +0000 (13:02 +0200)
As gbs already depends on gbp it makes sense to use its logging facility
instead of msger, which is copy&pasted from another project. Gbp logging
is based on standard Python logging functionality. It basically only
adds color output to it. This change adds a minimal functionality to the
'gitbuildsys.log' module to act as a GBS-specific logger.

This change is also takes more than 400 lines of code from the project
and decreases amount of pylint errors on more than 30% (120->84)

Change-Id: I4bd4d2b9299bf7aa79d5ea9da182312d53e8c3ff
Signed-off-by: Ed Bartosh <eduard.bartosh@intel.com>
Signed-off-by: Markus Lehtonen <markus.lehtonen@linux.intel.com>
16 files changed:
gitbuildsys/cmd_build.py
gitbuildsys/cmd_changelog.py
gitbuildsys/cmd_chroot.py
gitbuildsys/cmd_export.py
gitbuildsys/cmd_import.py
gitbuildsys/cmd_remotebuild.py
gitbuildsys/cmd_submit.py
gitbuildsys/conf.py
gitbuildsys/log.py
gitbuildsys/msger.py [deleted file]
gitbuildsys/oscapi.py
gitbuildsys/runner.py
gitbuildsys/utils.py
tests/test_changelog.py
tests/test_import.py
tools/gbs

index 2e86140ef921b4dfc679011d03002d726fc7001d..79447d29a1712391b8b0c4537e172a86ad0c3ffe 100644 (file)
@@ -24,14 +24,17 @@ import shutil
 import pwd
 import re
 
-from gitbuildsys import msger, utils, runner, errors
+from gitbuildsys import utils, runner
+from gitbuildsys.errors import GbsError, Usage
 from gitbuildsys.conf import configmgr
 from gitbuildsys.safe_url import SafeURL
 from gitbuildsys.cmd_export import transform_var_format_from_shell_to_python, \
                                    get_packaging_dir
+from gitbuildsys.log import LOGGER as log
 
 from gbp.rpm.git import GitRepositoryError, RpmGitRepository
 
+
 CHANGE_PERSONALITY = {
             'ia32':  'linux32',
             'i686':  'linux32',
@@ -93,7 +96,7 @@ def prepare_repos_and_build_conf(args, arch, profile):
     cachedir  = cache.path
     if not os.path.exists(cachedir):
         os.makedirs(cachedir)
-    msger.info('generate repositories ...')
+    log.info('generate repositories ...')
 
     if args.skip_conf_repos:
         repos = []
@@ -105,46 +108,46 @@ def prepare_repos_and_build_conf(args, arch, profile):
             try:
                 opt_repo = SafeURL(i)
             except ValueError, err:
-                msger.warning('Invalid repo %s: %s' % (i, str(err)))
+                log.warning('Invalid repo %s: %s' % (i, str(err)))
             else:
                 repos.append(opt_repo)
 
     if not repos:
-        msger.error('No package repository specified.')
+        raise GbsError('No package repository specified.')
 
     repoparser = utils.RepoParser(repos, cachedir)
     repourls = repoparser.get_repos_by_arch(arch)
     if not repourls:
-        msger.error('no available repositories found for arch %s under the '
-                    'following repos:\n%s' % (arch, '\n'.join(repos)))
+        raise GbsError('no available repositories found for arch %s under the '
+                       'following repos:\n%s' % (arch, '\n'.join(repos)))
     cmd_opts += [('--repository=%s' % url.full) for url in repourls]
 
     if args.dist:
         distconf = args.dist
         if not os.path.exists(distconf):
-            msger.error('specified build conf %s does not exists' % distconf)
+            raise GbsError('specified build conf %s does not exists' % distconf)
     else:
         if repoparser.buildconf is None:
-            msger.error('failed to get build conf from repos, please '
-                        'use snapshot repo or specify build config using '
-                        '-D option')
+            raise GbsError('failed to get build conf from repos, please '
+                           'use snapshot repo or specify build config using '
+                           '-D option')
         else:
             shutil.copy(repoparser.buildconf, TMPDIR)
             distconf = os.path.join(TMPDIR, os.path.basename(\
                                     repoparser.buildconf))
-            msger.info('build conf has been downloaded at:\n      %s' \
+            log.info('build conf has been downloaded at:\n      %s' \
                        % distconf)
 
     if distconf is None:
-        msger.error('No build config file specified, please specify in '\
-                    '~/.gbs.conf or command line using -D')
+        raise GbsError('No build config file specified, please specify in '\
+                       '~/.gbs.conf or command line using -D')
 
     # must use abspath here, because build command will also use this path
     distconf = os.path.abspath(distconf)
 
     if not distconf.endswith('.conf') or '-' in os.path.basename(distconf):
-        msger.error("build config file must end with .conf, and can't "
-                    "contain '-'")
+        raise GbsError("build config file must end with .conf, and can't "
+                       "contain '-'")
     dist = os.path.basename(distconf)[:-len('.conf')]
     cmd_opts += ['--dist=%s' % dist]
     cmd_opts += ['--configdir=%s' % os.path.dirname(distconf)]
@@ -177,7 +180,7 @@ def prepare_depanneur_opts(args):
         cmd_opts += ['--keep-packs']
     if args.binary_list:
         if not os.path.exists(args.binary_list):
-            msger.error('specified binary list file %s not exists' %\
+            raise GbsError('specified binary list file %s not exists' % \
                         args.binary_list)
         cmd_opts += ['--binary=%s' % args.binary_list]
     cmd_opts += ['--threads=%s' % args.threads]
@@ -237,11 +240,11 @@ def main(args):
     """gbs build entry point."""
 
     if args.commit and args.include_all:
-        raise errors.Usage('--commit can\'t be specified together with '\
-                           '--include-all')
+        raise Usage('--commit can\'t be specified together with '\
+                    '--include-all')
     if args.noinit and (args.clean or args.clean_once):
-        raise errors.Usage('--noinit can\'t be specified together with '\
-                           '--clean or --clean-once')
+        raise Usage('--noinit can\'t be specified together with '\
+                    '--clean or --clean-once')
     workdir = args.gitdir
 
     try:
@@ -249,27 +252,27 @@ def main(args):
         workdir = repo.path
     except GitRepositoryError:
         if args.spec:
-            msger.error("git project can't be found for --spec, "
-                        "give it in argument or cd into it")
+            raise GbsError("git project can't be found for --spec, "
+                           "give it in argument or cd into it")
 
     hostarch = os.uname()[4]
     if args.arch:
         buildarch = args.arch
     else:
         buildarch = hostarch
-        msger.info('No arch specified, using system arch: %s' % hostarch)
+        log.info('No arch specified, using system arch: %s' % hostarch)
 
     if not buildarch in SUPPORTEDARCHS:
-        msger.error('arch %s not supported, supported archs are: %s ' % \
-                   (buildarch, ','.join(SUPPORTEDARCHS)))
+        raise GbsError('arch %s not supported, supported archs are: %s ' % \
+                       (buildarch, ','.join(SUPPORTEDARCHS)))
 
     if buildarch in BUILDARCHMAP:
         buildarch = BUILDARCHMAP[buildarch]
 
     if buildarch not in CAN_ALSO_BUILD.get(hostarch, []):
         if buildarch not in QEMU_CAN_BUILD:
-            msger.error('hostarch: %s can\'t build target arch %s' % \
-                       (hostarch, buildarch))
+            raise GbsError("hostarch: %s can't build target arch %s" %
+                            (hostarch, buildarch))
 
     profile = get_profile(args)
     if args.buildroot:
@@ -335,9 +338,9 @@ def main(args):
     if args.spec:
         cmd += ['--spec=%s' % args.spec]
 
-    msger.debug("running command: %s" % ' '.join(cmd))
+    log.debug("running command: %s" % ' '.join(cmd))
     retcode = os.system(' '.join(cmd))
     if retcode != 0:
-        msger.error('rpmbuild fails')
+        raise GbsError('rpmbuild fails')
     else:
-        msger.info('Done')
+        log.info('Done')
index 418fb8548ba9fad4a5c1e69e20266069ce4789ec..460ba4b76874232acdfe0dcc4a5750ab4374f4e3 100644 (file)
@@ -23,9 +23,10 @@ import os
 import datetime
 import glob
 
-from gitbuildsys import msger
 from gitbuildsys.utils import guess_spec, edit_file
 from gitbuildsys.cmd_export import get_packaging_dir
+from gitbuildsys.errors import GbsError
+from gitbuildsys.log import LOGGER as log
 
 from gbp.rpm.git import GitRepositoryError, RpmGitRepository
 
@@ -84,7 +85,7 @@ def main(args):
     try:
         repo = RpmGitRepository(args.gitdir)
     except GitRepositoryError, err:
-        msger.error(str(err))
+        raise GbsError(str(err))
 
     project_root_dir = repo.path
 
@@ -101,7 +102,7 @@ def main(args):
     else:
         fn_changes = changes_file_list[0]
         if len(changes_file_list) > 1:
-            msger.warning("Found more than one changes files, %s is taken " \
+            log.warning("Found more than one changes files, %s is taken "
                            % (changes_file_list[0]))
 
     # get the commit start from the args.since
@@ -116,14 +117,14 @@ def main(args):
             commitid_since = repo.rev_parse(since)
         except GitRepositoryError:
             if args.since:
-                msger.error("Invalid commit: %s" % (since))
+                raise GbsError("Invalid commit: %s" % (since))
             else:
-                msger.error("Can't find last commit ID in the log, "\
-                            "please specify it by '--since'")
+                raise GbsError("Can't find last commit ID in the log, "\
+                               "please specify it by '--since'")
 
     commits = repo.get_commits(commitid_since, 'HEAD')
     if not commits:
-        msger.error("Nothing found between %s and HEAD" % commitid_since)
+        raise GbsError("Nothing found between %s and HEAD" % commitid_since)
 
     if args.message:
         author = repo.get_author_info()
@@ -139,7 +140,7 @@ def main(args):
 
     content = get_all_entries(fn_changes, new_entries)
     if edit_file(fn_changes, content):
-        msger.info("Change log has been updated.")
+        log.info("Change log has been updated.")
     else:
-        msger.info("Change log has not been updated")
+        log.info("Change log has not been updated")
 
index c126e8f7a2c42cd5483c121b5f8a0807408a8408..498f080772ec96f6fd1d8e93aa9b8054e4d738f8 100644 (file)
@@ -21,7 +21,8 @@
 import os
 import subprocess
 
-from gitbuildsys import msger
+from gitbuildsys.errors import GbsError
+from gitbuildsys.log import LOGGER as log
 
 def main(args):
     """gbs chroot entry point."""
@@ -30,9 +31,9 @@ def main(args):
 
     running_lock = '%s/not-ready' % build_root
     if os.path.exists(running_lock):
-        msger.error('build root %s is not ready' % build_root)
+        raise GbsError('build root %s is not ready' % build_root)
 
-    msger.info('chroot %s' % build_root)
+    log.info('chroot %s' % build_root)
     user = 'abuild'
     if args.root:
         user = 'root'
@@ -42,13 +43,13 @@ def main(args):
         subprocess.call(['sudo', 'cp', '/etc/resolv.conf', build_root + \
                          '/etc/resolv.conf'])
     except OSError:
-        msger.warning('failed to setup /etc/resolv.conf')
+        log.warning('failed to setup /etc/resolv.conf')
 
     try:
         build_env = os.environ
         build_env['PS1'] = "(tizen-build-env)@\h \W]\$ "
         subprocess.call(cmd, env=build_env)
     except OSError, err:
-        msger.error('failed to chroot to %s: %s' % (build_root, err))
+        raise GbsError('failed to chroot to %s: %s' % (build_root, err))
     except KeyboardInterrupt:
-        msger.info('keyboard interrupt ...')
+        log.info('keyboard interrupt ...')
index d9a75a40311b1333b9f3fb84835fe5805547cedc..dd1d44338cb853f1680ba4ef53b2ccc6d8a6b283 100644 (file)
@@ -25,8 +25,10 @@ import shutil
 import errno
 from urlparse import urlparse
 
-from gitbuildsys import msger, utils, errors
+from gitbuildsys import utils
 from gitbuildsys.conf import configmgr
+from gitbuildsys.errors import GbsError, Usage
+from gitbuildsys.log import LOGGER as log
 
 from gbp.scripts.buildpackage_rpm import main as gbp_build
 from gbp.rpm.git import GitRepositoryError, RpmGitRepository
@@ -86,17 +88,17 @@ def check_export_branches(repo, args):
     if repo.has_branch(upstream_branch) and \
        not repo.has_branch('pristine-tar') and \
        'pristine-tar' in remote_branches:
-        msger.warning('pristine-tar branch exist in remote branches, '
-                      'you can checkout it to enable exporting upstrean '
-                      'tarball from pristine-tar branch')
+        log.warning('pristine-tar branch exist in remote branches, '
+                    'you can checkout it to enable exporting upstrean '
+                    'tarball from pristine-tar branch')
 
     # all upstream and pristine-tar are not exist
     if not repo.has_branch(upstream_branch) and \
        not repo.has_branch('pristine-tar') and  \
        'pristine-tar' in remote_branches and upstream_branch in remote_branches:
-        msger.warning('pristine-tar and %s branches exist in remote branches, '
-                      'you can checkout them to enable upstream tarball and '
-                      'patch-generation ' % upstream_branch)
+        log.warning('pristine-tar and %s branches exist in remote branches, '
+                    'you can checkout them to enable upstream tarball and '
+                    'patch-generation ' % upstream_branch)
 
 def create_gbp_export_args(repo, commit, export_dir, tmp_dir, spec, args,
                            force_native=False):
@@ -112,8 +114,8 @@ def create_gbp_export_args(repo, commit, export_dir, tmp_dir, spec, args,
     else:
         upstream_tag = configmgr.get('upstream_tag', 'general')
         upstream_tag = transform_var_format_from_shell_to_python(upstream_tag)
-    msger.debug("Using upstream branch: %s" % upstream_branch)
-    msger.debug("Using upstream tag format: '%s'" % upstream_tag)
+    log.debug("Using upstream branch: %s" % upstream_branch)
+    log.debug("Using upstream tag format: '%s'" % upstream_tag)
 
     # Get patch squashing option
     if args.squash_patches_until:
@@ -194,46 +196,45 @@ def export_sources(repo, commit, export_dir, spec, args):
         ret = gbp_build(gbp_args)
         if ret == 2 and not is_native_pkg(repo, args):
             # Try falling back to old logic of one monolithic tarball
-            msger.warning("Generating upstream tarball and/or generating "\
-                          "patches failed. GBS tried this as you have "\
-                          "upstream branch in you git tree. This is a new "\
-                          "mode introduced in GBS v0.10. "\
-                          "Consider fixing the problem by either:\n"\
-                          "  1. Update your upstream branch and/or fix the "\
-                          "spec file. Also, check the upstream tag format.\n"\
+            log.warning("Generating upstream tarball and/or generating "
+                          "patches failed. GBS tried this as you have "
+                          "upstream branch in you git tree. This is a new "
+                          "mode introduced in GBS v0.10. "
+                          "Consider fixing the problem by either:\n"
+                          "  1. Update your upstream branch and/or fix the "
+                          "spec file. Also, check the upstream tag format.\n"
                           "  2. Remove or rename the upstream branch")
-            msger.info("Falling back to the old method of generating one "\
+            log.info("Falling back to the old method of generating one "
                        "monolithic source archive")
             gbp_args = create_gbp_export_args(repo, commit, export_dir,
                                               tmp.path, spec, args,
                                               force_native=True)
             ret = gbp_build(gbp_args)
         if ret:
-            msger.error("Failed to export packaging files from git tree")
+            raise GbsError("Failed to export packaging files from git tree")
     except GitRepositoryError, excobj:
-        msger.error("Repository error: %s" % excobj)
+        raise GbsError("Repository error: %s" % excobj)
 
 
 def main(args):
     """gbs export entry point."""
 
     if args.commit and args.include_all:
-        raise errors.Usage('--commit can\'t be specified together with '\
-                           '--include-all')
+        raise Usage("--commit can't be specified together with --include-all")
 
     workdir = args.gitdir
     try:
         repo = RpmGitRepository(workdir)
     except GitRepositoryError, err:
-        msger.error(str(err))
+        raise GbsError(str(err))
 
     utils.git_status_checker(repo, args)
     workdir = repo.path
 
     packaging_dir = get_packaging_dir(args)
     if not os.path.exists(os.path.join(workdir, packaging_dir)):
-        msger.error("No packaging directory '%s/', so there is nothing to "
-                    "export." % packaging_dir)
+        raise GbsError("No packaging directory '%s/', so there is nothing to "
+                       "export." % packaging_dir)
 
     # Only guess spec filename here, parse later when we have the correct
     # spec file at hand
@@ -265,17 +266,17 @@ def main(args):
     try:
         spec = rpm.parse_spec(os.path.join(export_dir, specfile))
     except GbpError, err:
-        msger.error('%s' % err)
+        raise GbsError('%s' % err)
 
     if not spec.name or not spec.version:
-        msger.error('can\'t get correct name or version from spec file.')
+        raise GbsError('can\'t get correct name or version from spec file.')
     else:
         outdir = "%s/%s-%s-%s" % (outdir, spec.name, spec.upstreamversion,
                                   spec.release)
         shutil.rmtree(outdir, ignore_errors=True)
         shutil.move(export_dir, outdir)
         if args.source_rpm:
-            msger.info('source rpm generated to:\n     %s/%s.src.rpm' % \
+            log.info('source rpm generated to:\n     %s/%s.src.rpm' % \
                        (outdir, os.path.basename(outdir)))
 
-    msger.info('package files have been exported to:\n     %s' % outdir)
+    log.info('package files have been exported to:\n     %s' % outdir)
index 95a841c0fc8350a15bf963c737a903e31e4dace7..c59b4a6ab017d0b91ea4a5f5dffcea93fc970b47 100644 (file)
@@ -20,8 +20,9 @@
 """
 import os
 
-from gitbuildsys import msger
+from gitbuildsys.errors import GbsError
 from gitbuildsys.cmd_export import get_packaging_dir
+from gitbuildsys.log import LOGGER as log
 
 from gbp.scripts.import_srpm import main as gbp_import_srpm
 from gbp.scripts.import_orig_rpm import main as gbp_import_orig
@@ -46,18 +47,18 @@ def main(args):
     if path.endswith('.src.rpm') or path.endswith('.spec'):
         ret = gbp_import_srpm(params)
         if ret == 2:
-            msger.warning("Importing of patches into packaging branch failed! "
-                          "Please import manually (apply and commit to git, "
-                          "remove files from packaging dir and spec) in order "
-                          "to enable automatic patch generation.")
+            log.warning("Importing of patches into packaging branch failed! "
+                        "Please import manually (apply and commit to git, "
+                        "remove files from packaging dir and spec) in order "
+                        "to enable automatic patch generation.")
         elif ret:
-            msger.error("Failed to import %s" % path)
+            raise GbsError("Failed to import %s" % path)
     else:
         if args.merge:
             params.append('--merge')
         else:
             params.append('--no-merge')
         if gbp_import_orig(params):
-            msger.error('Failed to import %s' % path)
+            raise GbsError('Failed to import %s' % path)
 
-    msger.info('done.')
+    log.info('done.')
index 0a4f7911174d2176500af98b3bc58de21a9bd0ca..4c1cbbae7d700f56a7842a06a178eadf56daf07e 100644 (file)
 import os
 import glob
 
-from gitbuildsys import msger, errors, utils
+from gitbuildsys import utils
 
+from gitbuildsys.errors import Usage, ObsError, GbsError
 from gitbuildsys.conf import configmgr, encode_passwd
 from gitbuildsys.oscapi import OSC, OSCError
 from gitbuildsys.cmd_export import export_sources, get_packaging_dir
 from gitbuildsys.cmd_build import get_profile
+from gitbuildsys.log import LOGGER as log
+from gitbuildsys.log import DEBUG
 
 import gbp.rpm
 from gbp.rpm.git import GitRepositoryError, RpmGitRepository
@@ -52,28 +55,29 @@ def main(args):
     obsconf = get_profile(args).obs
 
     if not obsconf or not obsconf.url:
-        msger.error('no obs api found, please add it to gbs conf and try again')
+        raise GbsError('no obs api found, please add it to gbs conf '
+                       'and try again')
 
     apiurl = obsconf.url
 
     if not apiurl.user:
-        msger.error('empty user is not allowed for remotebuild, '
-                    'please add user/passwd to gbs conf, and try again')
+        raise GbsError('empty user is not allowed for remotebuild, please '\
+                       'add user/passwd to gbs conf, and try again')
 
     if args.commit and args.include_all:
-        raise errors.Usage('--commit can\'t be specified together with '
+        raise Usage('--commit can\'t be specified together with '
                            '--include-all')
 
     obs_repo = args.repository
     obs_arch = args.arch
 
     if args.buildlog and None in (obs_repo, obs_arch):
-        msger.error('please specify arch(-A) and repository(-R)')
+        raise GbsError('please specify arch(-A) and repository(-R)')
 
     try:
         repo = RpmGitRepository(args.gitdir)
     except GitRepositoryError, err:
-        msger.error(str(err))
+        raise GbsError(str(err))
 
     workdir = repo.path
 
@@ -99,8 +103,8 @@ def main(args):
     else:
         content = utils.show_file_from_rev(workdir, relative_spec, commit)
         if content is None:
-            msger.error('failed to checkout %s '
-                        'from commit: %s' % (relative_spec, commit))
+            raise GbsError('failed to checkout %s from commit: %s' % 
+                            (relative_spec, commit))
 
         tmp_spec = utils.Temp(content=content)
         spec_to_parse = tmp_spec.path
@@ -109,10 +113,10 @@ def main(args):
     try:
         spec = gbp.rpm.parse_spec(spec_to_parse)
     except GbpError, err:
-        msger.error('%s' % err)
+        raise GbsError('%s' % err)
 
     if not spec.name:
-        msger.error('can\'t get correct name.')
+        raise GbsError("can't get correct name.")
     package = spec.name
 
     base_prj = None
@@ -134,8 +138,8 @@ def main(args):
     api_passwd = apiurl.passwd if apiurl.passwd else ''
     # Create temporary oscrc
     oscrc = OSCRC_TEMPLATE % {
-                "http_debug": 1 if msger.get_loglevel() == 'debug' else 0,
-                "debug": 1 if msger.get_loglevel() == 'verbose' else 0,
+                "http_debug": 1 if log.level == DEBUG else 0,
+                "debug": 1 if log.level == DEBUG else 0,
                 "apiurl": apiurl,
                 "user": apiurl.user,
                 "passwdx": encode_passwd(api_passwd),
@@ -160,15 +164,15 @@ def main(args):
                     archlist.append('%-15s%-15s' % (build_repo, arch))
             if not obs_repo or not obs_arch or obs_repo not in status.keys() \
                    or obs_arch not in status[obs_repo].keys():
-                msger.error('no valid repo / arch specified for buildlog, '\
-                            'valid arguments of repo and arch are:\n%s' % \
-                            '\n'.join(archlist))
+                raise GbsError('no valid repo / arch specified for buildlog, '\
+                               'valid arguments of repo and arch are:\n%s' % \
+                               '\n'.join(archlist))
             if status[obs_repo][obs_arch] not in ['failed', 'succeeded',
                                                   'building', 'finishing']:
-                msger.error('build status of %s for %s/%s is %s, no build log.'\
-                            % (package, obs_repo, obs_arch,
-                               status[obs_repo][obs_arch]))
-            msger.info('build log for %s/%s/%s/%s' % (target_prj, package,
+                raise GbsError('build status of %s for %s/%s is %s, '\
+                               'no build log.' % (package, obs_repo, obs_arch,
+                                                  status[obs_repo][obs_arch]))
+            log.info('build log for %s/%s/%s/%s' % (target_prj, package,
                                                       obs_repo, obs_arch))
             print api.get_buildlog(target_prj, package, obs_repo, obs_arch)
 
@@ -183,12 +187,12 @@ def main(args):
                 for arch in status[build_repo]:
                     stat = status[build_repo][arch]
                     results.append('%-15s%-15s%-15s' % (build_repo, arch, stat))
-            msger.info('build results from build server:\n%s' \
+            log.info('build results from build server:\n%s' \
                        % '\n'.join(results))
             return 0
 
     except OSCError, err:
-        msger.error(str(err))
+        raise GbsError(str(err))
 
     with utils.Workdir(workdir):
         export_sources(repo, commit, exportdir, relative_spec, args)
@@ -196,53 +200,53 @@ def main(args):
     try:
         commit_msg = repo.get_commit_info(args.commit or 'HEAD')['subject']
     except GitRepositoryError, exc:
-        msger.error('failed to get commit info: %s' % exc)
+        raise GbsError('failed to get commit info: %s' % exc)
 
     files = glob.glob("%s/*" % exportdir)
     build_repos = None
     try:
-        msger.info('checking status of obs project: %s ...' % target_prj)
+        log.info('checking status of obs project: %s ...' % target_prj)
         if not api.exists(target_prj):
-            msger.info('creating new project %s' % (target_prj))
+            log.info('creating new project %s' % (target_prj))
             api.create_project(target_prj, base_prj)
         else:
             build_repos = api.get_repos_of_project(target_prj)
             if not build_repos:
-                msger.warning("no available build repos for %s" % target_prj)
+                log.warning("no available build repos for %s" % target_prj)
         if api.exists(target_prj, package):
             old, _not_changed, changed, new = api.diff_files(target_prj,
                                                              package, files)
             if old:
-                msger.info("removing old files from OBS project")
+                log.info("removing old files from OBS project")
                 api.remove_files(target_prj, package, old)
             commit_files = changed + new
         else:
-            msger.info('creating new package %s/%s' % (target_prj, package))
+            log.info('creating new package %s/%s' % (target_prj, package))
             api.create_package(target_prj, package)
             # new project - submitting all local files
             commit_files = files
     except OSCError, err:
-        msger.error(str(err))
+        raise GbsError(str(err))
 
     if not commit_files:
         if build_repos:
-            msger.warning("no local changes found. Triggering rebuild")
+            log.warning("no local changes found. Triggering rebuild")
             api.rebuild(target_prj, package, obs_arch)
         else:
-            msger.warning("no local changes found. can't trigger rebuild "
+            log.warning("no local changes found. can't trigger rebuild "
                           "as no available build repos found")
             return 0
     else:
-        msger.info('commit packaging files to build server ...')
+        log.info('commit packaging files to build server ...')
         commit_files = [(fpath, fpath in commit_files) for fpath in files]
         try:
             api.commit_files(target_prj, package, commit_files, commit_msg)
-        except errors.ObsError, exc:
-            msger.error('commit packages fail: %s, please check the permission '
-                        'of target project:%s' % (exc, target_prj))
+        except ObsError as exc:
+            raise GbsError('commit packages fail: %s, please check the '
+                       'permission of target project:%s' % (exc, target_prj))
 
-        msger.info('local changes submitted to build server successfully')
+        log.info('local changes submitted to build server successfully')
 
-    msger.info('follow the link to monitor the build progress:\n'
+    log.info('follow the link to monitor the build progress:\n'
                '  %s/package/show?package=%s&project=%s' \
                % (apiurl.replace('api', 'build'), package, target_prj))
index 374eac0ed6a16b0dbcbcc67a4df3daf093d106ca..34a7059eaad85344473de6c2f9226459c4f2d94e 100644 (file)
@@ -21,8 +21,9 @@
 import os
 import time
 
-from gitbuildsys import msger
 from gitbuildsys.utils import edit
+from gitbuildsys.errors import GbsError
+from gitbuildsys.log import LOGGER as log
 
 from gbp.rpm.git import GitRepositoryError, RpmGitRepository
 
@@ -52,14 +53,14 @@ def main(args):
         message = args.msg
 
     if not message:
-        msger.error("tag message is required")
+        raise GbsError("tag message is required")
 
     try:
         repo = RpmGitRepository(workdir)
         commit = repo.rev_parse(args.commit)
         current_branch = repo.get_branch()
     except GitRepositoryError, err:
-        msger.error(str(err))
+        raise GbsError(str(err))
 
     try:
         upstream = repo.get_upstream_branch(current_branch)
@@ -70,14 +71,14 @@ def main(args):
         if upstream:
             args.remote = upstream.split('/')[0]
         else:
-            msger.info("no upstream set for the current branch, using "
+            log.info("no upstream set for the current branch, using "
                        "'origin' as the remote server")
             args.remote = 'origin'
     if not args.target:
         if upstream and upstream.startswith(args.remote):
             args.target = os.path.basename(upstream)
         else:
-            msger.warning("Can't find upstream branch for current branch "
+            log.warning("Can't find upstream branch for current branch "
                           "%s. Gbs uses the local branch name as the target. "
                           "Please consider to use git-branch --set-upstream "
                           "to set upstream remote branch." % current_branch)
@@ -88,17 +89,17 @@ def main(args):
             args.target = 'trunk'
         tagname = 'submit/%s/%s' % (args.target, time.strftime( \
                                     '%Y%m%d.%H%M%S', time.gmtime()))
-        msger.info('creating tag: %s' % tagname)
+        log.info('creating tag: %s' % tagname)
         repo.create_tag(tagname, msg=message, commit=commit, sign=args.sign,
                         keyid=args.user_key)
     except GitRepositoryError, err:
-        msger.error('failed to create tag %s: %s ' % (tagname, str(err)))
+        raise GbsError('failed to create tag %s: %s ' % (tagname, str(err)))
 
     try:
-        msger.info("pushing tag to remote '%s'" % args.remote)
+        log.info("pushing tag to remote '%s'" % args.remote)
         repo.push_tag(args.remote, tagname)
     except GitRepositoryError, err:
         repo.delete_tag(tagname)
-        msger.error('failed to push tag %s :%s' % (tagname, str(err)))
+        raise GbsError('failed to push tag %s :%s' % (tagname, str(err)))
 
-    msger.info('done.')
+    log.info('done.')
index 96a57c9a69cb102cf43c290f7da08374ad683858..8bb2851b28db1ededfbff5e2aec244cc373e81d2 100644 (file)
@@ -28,10 +28,10 @@ from collections import namedtuple
 from ConfigParser import SafeConfigParser, NoSectionError, \
                          MissingSectionHeaderError, Error
 
-from gitbuildsys import msger, errors
+from gitbuildsys import errors
 from gitbuildsys.safe_url import SafeURL
 from gitbuildsys.utils import Temp
-
+from gitbuildsys.log import LOGGER as log
 
 def decode_passwdx(passwdx):
     '''decode passwdx into plain format'''
@@ -301,8 +301,8 @@ url = http://download.tizen.org/releases/trunk/daily/ivi/latest/
             wfile.write(self.DEFAULT_CONF_TEMPLATE)
         os.chmod(fpath, 0600)
 
-        msger.warning('Created a new config file %s. Please check and edit '
-            'your authentication information.' % fpath)
+        log.warning('Created a new config file %s. Please check and edit '
+                    'your authentication information.' % fpath)
 
     def _check_passwd(self):
         'convert passwd item to passwdx and then update origin conf files'
@@ -329,8 +329,8 @@ url = http://download.tizen.org/releases/trunk/daily/ivi/latest/
                             dirty.add(cfgparser)
 
         if dirty:
-            msger.warning('plaintext password in config files will '
-                          'be replaced by encoded ones')
+            log.warning('plaintext password in config files will '
+                        'be replaced by encoded ones')
             self.update(dirty)
 
     def _get(self, opt, section='general'):
@@ -383,7 +383,7 @@ url = http://download.tizen.org/releases/trunk/daily/ivi/latest/
             try:
                 cfgparser.update()
             except IOError, err:
-                msger.warning('update config file error: %s' % err)
+                log.warning('update config file error: %s' % err)
 
 
 URL = namedtuple('URL', 'url user password')
@@ -543,7 +543,7 @@ class BizConfigManager(ConfigMgr):
         except IOError, err:
             raise errors.ConfigError(err)
 
-        msger.warning('subcommand oriented style of config is deprecated. '
+        log.warning('subcommand oriented style of config is deprecated. '
             'Please check %s, a new profile oriented style of config which'
             ' was converted from your current settings.' % fname)
 
@@ -591,8 +591,8 @@ class BizConfigManager(ConfigMgr):
             for repo in repos.split(','):
                 repo = repo.strip()
                 if not repo.startswith('repo.'):
-                    msger.warning('ignore %s, repo section name should start '
-                                  'with string "repo."' % repo)
+                    log.warning('ignore %s, repo section name should start '
+                                'with string "repo."' % repo)
                     continue
 
                 repoconf = RepoConf(profile, repo,
index 022a3fd0e66e4e09b30534e8df2f2d1a4eb08256..015725c264cdf65b9346d51b1a41c4e34fd74f22 100644 (file)
@@ -20,6 +20,9 @@ import functools
 import sys
 import threading
 
+import gbp.log
+from gbp.log import DEBUG, INFO, WARNING, ERROR
+
 def waiting(func):
     """
     Function decorator to show simple waiting message for long time operations.
@@ -52,3 +55,34 @@ def waiting(func):
     return _wait_with_print
 
 
+def setup(verbose, debug=False):
+    """Basic logging setup"""
+
+    # Change logging level names to lower case
+    for level in (DEBUG, INFO, WARNING, ERROR):
+        gbp.log.logging.addLevelName(level,
+                                 gbp.log.logging.getLevelName(level).lower())
+    # Set verbosity
+    verbose = verbose or debug
+    if verbose:
+        LOGGER.setLevel(DEBUG)
+    else:
+        LOGGER.setLevel(INFO)
+
+    # Set output format
+    log_fmt = '%(color)s%(levelname)s: %(coloroff)s%(message)s'
+    LOGGER.set_format(log_fmt)
+    gbp.log.LOGGER.set_format(log_fmt)
+
+    # Set output colors
+    color_scheme = {DEBUG: gbp.log.COLORS['magenta'],
+                    INFO: gbp.log.COLORS['green'],
+                    WARNING: gbp.log.COLORS['yellow'],
+                    ERROR: gbp.log.COLORS['red']}
+    LOGGER.set_color_scheme(color_scheme)
+    gbp.log.LOGGER.set_color_scheme(color_scheme)
+
+
+# Module initialization
+LOGGER = gbp.log.getLogger("gbs")
+
diff --git a/gitbuildsys/msger.py b/gitbuildsys/msger.py
deleted file mode 100644 (file)
index 1011863..0000000
+++ /dev/null
@@ -1,454 +0,0 @@
-#!/usr/bin/python -tt
-# vim: ai ts=4 sts=4 et sw=4
-#
-# Copyright (c) 2009, 2010, 2011 Intel, Inc.
-#
-# This program is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License as published by the Free
-# Software Foundation; version 2 of the License
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
-# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# for more details.
-#
-# You should have received a copy of the GNU General Public License along
-# with this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os, sys
-import re
-import time
-
-__ALL__ = ['set_mode',
-           'get_loglevel',
-           'set_loglevel',
-           'set_logfile',
-           'enable_logstderr',
-           'disable_logstderr',
-           'raw',
-           'debug',
-           'verbose',
-           'info',
-           'warning',
-           'error',
-           'ask',
-           'pause',
-           'waiting',
-           'PrintBuf',
-           'PrintBufWrapper',
-          ]
-
-# COLORs in ANSI
-INFO_COLOR = 32 # green
-WARN_COLOR = 33 # yellow
-ERR_COLOR  = 31 # red
-ASK_COLOR  = 34 # blue
-DEBUG_COLOR = 35 # Magenta
-NO_COLOR = 0
-
-# save the timezone info at import time
-HOST_TIMEZONE = time.timezone
-
-PREFIX_RE = re.compile('^<(.*?)>\s*(.*)', re.S)
-
-INTERACTIVE = True
-
-LOG_LEVEL = 1
-LOG_LEVELS = {
-                'quiet': 0,
-                'normal': 1,
-                'verbose': 2,
-                'debug': 3,
-                'never': 4,
-             }
-
-LOG_FILE_FP = None
-LOG_CONTENT = ''
-CATCHERR_BUFFILE_FD = -1
-CATCHERR_BUFFILE_PATH = None
-CATCHERR_SAVED_2 = -1
-
-# save the original stdout/stderr at the very start
-STDOUT = sys.stdout
-STDERR = sys.stderr
-
-# Configure gbp logging
-import gbp.log
-for level in (gbp.log.DEBUG, gbp.log.INFO, gbp.log.WARNING, gbp.log.ERROR):
-    gbp.log.logging.addLevelName(level,
-                                 gbp.log.logging.getLevelName(level).lower())
-gbp.log.LOGGER.set_format('%(color)s%(levelname)s: '
-                          '%(coloroff)s%(message)s')
-
-# Mapping for gbs->gbp log levels
-GBP_LOG_LEVELS = {
-                    'quiet': gbp.log.ERROR,
-                    'normal': gbp.log.INFO,
-                    'verbose': gbp.log.DEBUG,
-                    'debug': gbp.log.DEBUG,
-                    'never': gbp.log.ERROR
-                 }
-
-class PrintBuf(object):
-    """Object to buffer the output of 'print' statement string
-    """
-
-    def __init__(self):
-        self.buf1 = \
-        self.buf2 = \
-        self.old1 = \
-        self.old2 = None
-
-    def start(self):
-        """Start to buffer, redirect stdout to string
-        """
-
-        if get_loglevel() != 'debug':
-            import StringIO
-            self.buf1 = StringIO.StringIO()
-            self.buf2 = StringIO.StringIO()
-
-            self.old1 = sys.stdout
-            self.old2 = sys.stderr
-            sys.stdout = self.buf1
-            sys.stderr = self.buf2
-
-    def stop(self):
-        """Stop buffer, restore the original stdout, and flush the
-        buffer string, return the content
-        """
-
-        if self.buf1:
-            msg1 = self.buf1.getvalue().strip()
-            msg2 = self.buf2.getvalue().strip()
-            self.buf1.close()
-            self.buf2.close()
-
-            sys.stdout = self.old1
-            sys.stderr = self.old2
-
-            self.buf1 = \
-            self.buf2 = \
-            self.old1 = \
-            self.old2 = None
-
-            return (msg1, msg2)
-
-        return ('', '')
-
-class PrintBufWrapper(object):
-    """Wrapper class for another class, to catch the print output and
-    handlings.
-    """
-
-    def __init__(self, wrapped_class, msgfunc_1, msgfunc_2, *args, **kwargs):
-        """Arguments:
-          wrapped_class: the class to be wrapped
-          msgfunc_1: function to deal with msg from stdout(1)
-          msgfunc_2: function to deal with msg from stderr(2)
-          *args, **kwargs: the original args of wrapped_class
-        """
-
-        self.pbuf = PrintBuf()
-        self.func1 = msgfunc_1
-        self.func2 = msgfunc_2
-
-        self.pbuf.start()
-        self.wrapped_inst = wrapped_class(*args, **kwargs)
-        stdout_msg, stderr_msg = self.pbuf.stop()
-        if stdout_msg:
-            self.func1(stdout_msg)
-        if stderr_msg:
-            self.func2(stderr_msg)
-
-    def __getattr__(self, attr):
-        orig_attr = getattr(self.wrapped_inst, attr)
-        if callable(orig_attr):
-            def hooked(*args, **kwargs):
-                self.pbuf.start()
-                try:
-                    result = orig_attr(*args, **kwargs)
-                except:
-                    raise
-                finally:
-                    stdout_msg, stderr_msg = self.pbuf.stop()
-                    if stdout_msg:
-                        self.func1(stdout_msg)
-                    if stderr_msg:
-                        self.func2(stderr_msg)
-
-                return result
-
-            return hooked
-        else:
-            return orig_attr
-
-def _general_print(head, color, msg = None, stream = None, level = 'normal'):
-    global LOG_CONTENT
-
-    if LOG_LEVELS[level] > LOG_LEVEL:
-        # skip
-        return
-
-    if stream is None:
-        stream = STDOUT
-
-    errormsg = ''
-    if CATCHERR_BUFFILE_FD > 0:
-        size = os.lseek(CATCHERR_BUFFILE_FD , 0, os.SEEK_END)
-        os.lseek(CATCHERR_BUFFILE_FD, 0, os.SEEK_SET)
-        errormsg = os.read(CATCHERR_BUFFILE_FD, size)
-        os.ftruncate(CATCHERR_BUFFILE_FD, 0)
-
-    if LOG_FILE_FP:
-        if errormsg:
-            LOG_CONTENT += errormsg
-
-        if msg and msg.strip():
-            timestr = time.strftime("[%m/%d %H:%M:%S] ",
-                                    time.gmtime(time.time() - HOST_TIMEZONE))
-            LOG_CONTENT += timestr + msg.strip() + '\n'
-
-    if errormsg:
-        _color_print('', NO_COLOR, errormsg, stream, level)
-
-    _color_print(head, color, msg, stream, level)
-
-def _color_print(head, color, msg, stream, _level):
-    colored = True
-    if color == NO_COLOR or \
-       not stream.isatty() or \
-       os.getenv('ANSI_COLORS_DISABLED') is not None:
-        colored = False
-
-    if head.startswith('\r'):
-        # need not \n at last
-        newline = False
-    else:
-        newline = True
-
-    if colored:
-        head = '\033[%dm%s:\033[0m ' % (color, head)
-        if not newline:
-            # ESC cmd to clear line
-            head = '\033[2K' + head
-    else:
-        if head:
-            head += ': '
-            if head.startswith('\r'):
-                head = head.lstrip()
-                newline = True
-
-    if msg is not None:
-        stream.write('%s%s' % (head, msg))
-        if newline:
-            stream.write('\n')
-
-    stream.flush()
-
-def _color_perror(head, color, msg, level = 'normal'):
-    if CATCHERR_BUFFILE_FD > 0:
-        _general_print(head, color, msg, STDOUT, level)
-    else:
-        _general_print(head, color, msg, STDERR, level)
-
-def _split_msg(head, msg):
-    if isinstance(msg, list):
-        msg = '\n'.join(map(str, msg))
-
-    if msg.startswith('\n'):
-        # means print \n at first
-        msg = msg.lstrip()
-        head = '\n' + head
-
-    elif msg.startswith('\r'):
-        # means print \r at first
-        msg = msg.lstrip()
-        head = '\r' + head
-
-    match = PREFIX_RE.match(msg)
-    if match:
-        head += ' <%s>' % match.group(1)
-        msg = match.group(2)
-
-    return head, msg
-
-def get_loglevel():
-    return (k for k, v in LOG_LEVELS.items() if v==LOG_LEVEL).next()
-
-def set_loglevel(level):
-    global LOG_LEVEL
-    if level not in LOG_LEVELS:
-        # no effect
-        return
-
-    LOG_LEVEL = LOG_LEVELS[level]
-
-    # set git-buildpackage log level
-    gbp.log.LOGGER.setLevel(GBP_LOG_LEVELS[level])
-
-def set_interactive(mode=True):
-    global INTERACTIVE
-    if mode:
-        INTERACTIVE = True
-    else:
-        INTERACTIVE = False
-
-def raw(msg=''):
-    _general_print('', NO_COLOR, msg)
-
-def info(msg):
-    head, msg = _split_msg('info', msg)
-    _general_print(head, INFO_COLOR, msg)
-
-def verbose(msg):
-    head, msg = _split_msg('verbose', msg)
-    _general_print(head, INFO_COLOR, msg, level = 'verbose')
-
-def warning(msg):
-    head, msg = _split_msg('warning', msg)
-    _color_perror(head, WARN_COLOR, msg)
-
-def debug(msg):
-    head, msg = _split_msg('debug', msg)
-    _color_perror(head, DEBUG_COLOR, msg, level = 'debug')
-
-def error(msg):
-    head, msg = _split_msg('error', msg)
-    _color_perror(head, ERR_COLOR, msg)
-    sys.exit(1)
-
-def waiting(func):
-    """
-    Function decorator to show simple waiting message for
-    long time operations.
-    """
-
-    import functools
-
-    @functools.wraps(func)
-    def _wait_with_print(*args, **kwargs):
-        import threading
-
-        class _WaitingTimer(threading.Thread):
-            def __init__(self):
-                threading.Thread.__init__(self)
-                self.event = threading.Event()
-                self.waited = False
-
-            def run(self):
-                while not self.event.is_set():
-                    # put the waiting above the actual
-                    # printing to avoid unnecessary msg
-                    self.event.wait(1)
-                    if self.event.is_set():
-                        break
-
-                    self.waited = True
-                    STDERR.write('.')
-                    STDERR.flush()
-
-            def stop(self):
-                self.event.set()
-
-                if self.waited:
-                    STDERR.write('\n')
-                    STDERR.flush()
-
-        timer = _WaitingTimer()
-        timer.start()
-
-        try:
-            out = func(*args, **kwargs)
-        except:
-            raise
-        finally:
-            timer.stop()
-
-        return out
-
-    return _wait_with_print
-
-def ask(msg, default=True):
-    _general_print('\rQ', ASK_COLOR, '')
-    try:
-        if default:
-            msg += '(Y/n) '
-        else:
-            msg += '(y/N) '
-        if INTERACTIVE:
-            while True:
-                repl = raw_input(msg)
-                if repl.lower() == 'y':
-                    return True
-                elif repl.lower() == 'n':
-                    return False
-                elif not repl.strip():
-                    # <Enter>
-                    return default
-
-                # else loop
-        else:
-            if default:
-                msg += ' Y'
-            else:
-                msg += ' N'
-            _general_print('', NO_COLOR, msg)
-
-            return default
-    except KeyboardInterrupt:
-        sys.stdout.write('\n')
-        sys.exit(2)
-
-def pause(msg=None):
-    if INTERACTIVE:
-        _general_print('\rQ', ASK_COLOR, '')
-        if msg is None:
-            msg = 'press <ENTER> to continue ...'
-        raw_input(msg)
-
-def set_logfile(fpath):
-    global LOG_FILE_FP
-
-    def _savelogf():
-        if LOG_FILE_FP:
-            if not os.path.exists(os.path.dirname(LOG_FILE_FP)):
-                os.makedirs(os.path.dirname(LOG_FILE_FP))
-            fhandle = open(LOG_FILE_FP, 'w')
-            fhandle.write(LOG_CONTENT)
-            fhandle.close()
-
-    if LOG_FILE_FP is not None:
-        warning('duplicate log file configuration')
-
-    LOG_FILE_FP = os.path.abspath(os.path.expanduser(fpath))
-
-    import atexit
-    atexit.register(_savelogf)
-
-def enable_logstderr(fpath):
-    global CATCHERR_BUFFILE_FD
-    global CATCHERR_BUFFILE_PATH
-    global CATCHERR_SAVED_2
-
-    if os.path.exists(fpath):
-        os.remove(fpath)
-    CATCHERR_BUFFILE_PATH = fpath
-    CATCHERR_BUFFILE_FD = os.open(CATCHERR_BUFFILE_PATH, os.O_RDWR|os.O_CREAT)
-    CATCHERR_SAVED_2 = os.dup(2)
-    os.dup2(CATCHERR_BUFFILE_FD, 2)
-
-def disable_logstderr():
-    global CATCHERR_BUFFILE_FD
-    global CATCHERR_BUFFILE_PATH
-    global CATCHERR_SAVED_2
-
-    raw(msg=None) # flush message buffer and print it
-    os.dup2(CATCHERR_SAVED_2, 2)
-    os.close(CATCHERR_SAVED_2)
-    os.close(CATCHERR_BUFFILE_FD)
-    os.unlink(CATCHERR_BUFFILE_PATH)
-    CATCHERR_BUFFILE_FD = -1
-    CATCHERR_BUFFILE_PATH = None
-    CATCHERR_SAVED_2 = -1
index 787ec44a410607b17d95edd058cb65de5a83e42a..f1c40e295600da4addf211754ad90ffb6af7d9b1 100644 (file)
@@ -31,14 +31,13 @@ import ssl
 from collections import defaultdict
 from urllib import quote_plus, pathname2url
 
-from gitbuildsys import msger
 from gitbuildsys.utils import hexdigest
 from gitbuildsys.errors import ObsError
 from gitbuildsys.log import waiting
+from gitbuildsys.log import LOGGER as logger
 
 from osc import conf, core
 
-
 class OSCError(Exception):
     """Local exception class."""
     pass
@@ -102,9 +101,9 @@ class OSC(object):
             raise ObsError('base project: %s not exists' % src)
 
         if self.exists(target):
-            msger.warning('target project: %s exists' % target)
+            logger.warning('target project: %s exists' % target)
             if rewrite:
-                msger.warning('rewriting target project %s' % target)
+                logger.warning('rewriting target project %s' % target)
             else:
                 return
 
@@ -124,7 +123,7 @@ class OSC(object):
                     meta += "<arch>%s</arch>\n" % arch
                 meta += "</repository>\n"
         else:
-            msger.warning('no project repos in target project, please add '
+            logger.warning('no project repos in target project, please add '
                 'repos from OBS webUI manually, or specify base project '
                 'with -B <base_prj>, then gbs can help to set repos '
                 'using the settings of the specified base project.')
index 7ba98c2a50b7961700291ccc0abf22e0363f96c2..d67194718a91b85e35aaff9347814613828cf34e 100644 (file)
@@ -19,7 +19,8 @@
 import os
 import subprocess
 
-from gitbuildsys import msger
+from gitbuildsys.errors import GbsError
+from gitbuildsys.log import LOGGER as log
 
 def runtool(cmdln_or_args, catch=1):
     """ wrapper for most of the subprocess calls
@@ -59,7 +60,7 @@ def runtool(cmdln_or_args, catch=1):
     except OSError, exc:
         if exc.errno == 2:
             # [Errno 2] No such file or directory
-            msger.error('Cannot run command: %s, lost dependency?' % cmd)
+            raise GbsError('Cannot run command: %s, lost dependency?' % cmd)
         else:
             raise # relay
     finally:
@@ -68,7 +69,7 @@ def runtool(cmdln_or_args, catch=1):
     return (process.returncode, out)
 
 def show(cmdln_or_args):
-    # show all the message using msger.verbose
+    # show all the message using log.debug
 
     rcode, out = runtool(cmdln_or_args, catch=3)
 
@@ -87,7 +88,7 @@ def show(cmdln_or_args):
             msg += '\n  | %s' % line
         msg += '\n  +----------------'
 
-    msger.verbose(msg)
+    log.debug(msg)
     return rcode
 
 def outs(cmdln_or_args, catch=1):
index ac7a77572016d1a3f758de878c5d022eef644e16..334938862a3bc2d85ffed802d1a42d9fda0718e9 100644 (file)
@@ -28,7 +28,8 @@ import subprocess
 import xml.etree.ElementTree as ET
 from collections import defaultdict
 
-from gitbuildsys import errors, msger
+from gitbuildsys.errors import UrlError, GbsError
+from gitbuildsys.log import LOGGER as log
 
 from gbp.rpm.git import GitRepositoryError
 from gbp.errors import GbpError
@@ -62,12 +63,12 @@ def guess_spec(git_path, packaging_dir, given_spec, commit_id='WC.UNTRACKED'):
     if given_spec:
         spec = os.path.join(packaging_dir, given_spec)
         if not check(spec):
-            msger.error(msg % spec)
+            raise GbsError(msg % spec)
         return spec
 
     specs = glob_(os.path.join(packaging_dir, '*.spec'))
     if not specs:
-        msger.error("can't find any spec file")
+        raise GbsError("can't find any spec file")
 
     project_name =  os.path.basename(git_path)
     spec = os.path.join(packaging_dir, '%s.spec' % project_name)
@@ -110,8 +111,8 @@ class Temp(object):
                     with file(path, 'w+') as fobj:
                         fobj.write(content)
         except OSError, err:
-            raise errors.GbsError("Failed to create dir or file on %s: %s" % \
-                            (target_dir, str(err)))
+            raise GbsError("Failed to create dir or file on %s: %s" % \
+                          (target_dir, str(err)))
         self.path = path
 
     def __del__(self):
@@ -151,7 +152,7 @@ class TempCopy(object):
             os.unlink(self.name)
 
 
-class PageNotFound(errors.UrlError):
+class PageNotFound(UrlError):
     'page not found error: 404'
 
 class URLGrabber(object):
@@ -204,24 +205,23 @@ class URLGrabber(object):
         try:
             curl.perform()
         except pycurl.error, err:
-            msger.debug('fetching error:%s' % str(err))
+            log.debug('fetching error:%s' % str(err))
 
             errcode, errmsg = err.args
             http_code = curl.getinfo(pycurl.HTTP_CODE)
 
             if errcode == pycurl.E_OPERATION_TIMEOUTED:
-                raise errors.UrlError("connect timeout to %s, maybe it's "
-                                      "caused by proxy settings, please "
-                                      "check." % curl.url)
+                raise UrlError("connect timeout to %s, maybe it's caused by "
+                               "proxy settings, please check." % curl.url)
             elif errcode == pycurl.E_ABORTED_BY_CALLBACK:
                 raise KeyboardInterrupt(err)
             elif http_code in (401, 403):
-                raise errors.UrlError('authenticate failed on: %s' % curl.url)
+                raise UrlError('authenticate failed on: %s' % curl.url)
             elif http_code == 404:
                 raise PageNotFound(err)
             else:
-                raise errors.UrlError('URL error on %s: (%s: "%s")' %
-                                     (curl.url, errcode, errmsg))
+                raise UrlError('URL error on %s: (%s: "%s")' %
+                               (curl.url, errcode, errmsg))
         finally:
             signal.signal(signal.SIGINT, original_handler)
 
@@ -233,7 +233,7 @@ class URLGrabber(object):
     def grab(self, url, filename, user=None, passwd=None):
         '''grab url to filename'''
 
-        msger.debug("fetching %s => %s" % (url, filename))
+        log.debug("fetching %s => %s" % (url, filename))
 
         with open(filename, 'w') as outfile:
             self.change_url(url, outfile, user, passwd)
@@ -263,7 +263,7 @@ class RepoParser(object):
         try:
             etree = ET.parse(build_xml)
         except ET.ParseError:
-            msger.warning('Not well formed xml: %s' % build_xml)
+            log.warning('Not well formed xml: %s' % build_xml)
             return
 
         meta = {}
@@ -335,7 +335,7 @@ class RepoParser(object):
         if not meta or \
             'buildconf' not in meta or \
             not meta['buildconf']:
-            msger.warning("No build.conf in build.xml "
+            log.warning("No build.conf in build.xml "
                           "of repo: %s" % latest_repo_url)
             return
 
@@ -389,7 +389,7 @@ class RepoParser(object):
                 if os.path.exists(repo):
                     local_repos.append(repo)
                 else:
-                    msger.warning('No such repo path:%s' % repo)
+                    log.warning('No such repo path:%s' % repo)
             else:
                 remotes.append(repo)
 
@@ -411,7 +411,7 @@ class RepoParser(object):
                 if not url.startswith('http://') and \
                     not url.startswith('https://') and \
                     not (url.startswith('/') and os.path.exists(url)):
-                    msger.warning('ignore invalid repo url: %s' % url)
+                    log.warning('ignore invalid repo url: %s' % url)
                 else:
                     rets.append(url)
             return rets
@@ -426,7 +426,7 @@ def git_status_checker(git, opts):
         is_clean = git.is_clean()[0]
         status = git.status()
     except (GbpError, GitRepositoryError), err:
-        msger.error(str(err))
+        raise GbsError(str(err))
 
     untracked_files = status['??']
     uncommitted_files = []
@@ -437,19 +437,19 @@ def git_status_checker(git, opts):
 
     if not is_clean and not opts.include_all:
         if untracked_files:
-            msger.warning('the following untracked files would NOT be '\
-                       'included:\n   %s' % '\n   '.join(untracked_files))
+            log.warning('the following untracked files would NOT be '
+                        'included:\n   %s' % '\n   '.join(untracked_files))
         if uncommitted_files:
-            msger.warning('the following uncommitted changes would NOT be '\
-                       'included:\n   %s' % '\n   '.join(uncommitted_files))
-        msger.warning('you can specify \'--include-all\' option to '\
-                      'include these uncommitted and untracked files.')
+            log.warning('the following uncommitted changes would NOT be '
+                        'included:\n   %s' % '\n   '.join(uncommitted_files))
+        log.warning('you can specify \'--include-all\' option to '
+                    'include these uncommitted and untracked files.')
     if not is_clean and opts.include_all:
         if untracked_files:
-            msger.info('the following untracked files would be included'  \
+            log.info('the following untracked files would be included'
                        ':\n   %s' % '\n   '.join(untracked_files))
         if uncommitted_files:
-            msger.info('the following uncommitted changes would be included'\
+            log.info('the following uncommitted changes would be included'
                        ':\n   %s' % '\n   '.join(uncommitted_files))
 
 def hexdigest(fhandle, block_size=4096):
@@ -470,8 +470,8 @@ def show_file_from_rev(git_path, relative_path, commit_id):
     try:
         return subprocess.check_output(cmd, shell=True)
     except (subprocess.CalledProcessError, OSError), err:
-        msger.debug('failed to checkout %s from %s:%s' % (relative_path,
-                                                          commit_id, str(err)))
+        log.debug('failed to checkout %s from %s:%s' % (relative_path,
+                                                        commit_id, str(err)))
     return None
 
 
@@ -484,7 +484,7 @@ def file_exists_in_rev(git_path, relative_path, commit_id):
     try:
         output = subprocess.check_output(cmd, shell=True)
     except (subprocess.CalledProcessError, OSError), err:
-        raise errors.GbsError('failed to check existence of %s in %s:%s' % (
+        raise GbsError('failed to check existence of %s in %s:%s' % (
             relative_path, commit_id, str(err)))
 
     return output != ''
@@ -500,7 +500,7 @@ def glob_in_rev(git_path, pattern, commit_id):
     try:
         output = subprocess.check_output(cmd, shell=True)
     except (subprocess.CalledProcessError, OSError), err:
-        raise errors.GbsError('failed to glob %s in %s:%s' % (
+        raise GbsError('failed to glob %s in %s:%s' % (
             pattern, commit_id, str(err)))
 
     return fnmatch.filter(output.splitlines(), pattern)
@@ -536,5 +536,5 @@ def edit_file(target_fname, initial_content=None):
         with open(target_fname, 'w') as fobj:
             fobj.write(changes)
     except IOError, err:
-        msger.error("Can't update %s: %s" % (target_fname, str(err)))
+        raise GbsError("Can't update %s: %s" % (target_fname, str(err)))
     return True
index a44bcd37bb4a18b20518b2abcd3e4cbf677df3e4..a71855174378d65ec2cb7a04cd367cf0627097db 100644 (file)
@@ -30,6 +30,8 @@ from nose.tools import eq_, raises
 
 from gbp.git.repository import GitRepository
 
+from gitbuildsys.errors import GbsError
+
 GBS = imp.load_source("gbs", "./tools/gbs").main
 ENV = {}
 
@@ -133,19 +135,19 @@ class TestChangelog(unittest.TestCase):
         eq_(GBS(argv=["gbs ", "changelog"]), None)
 
     @staticmethod
-    @raises(SystemExit)
+    @raises(GbsError)
     def test_no_new_changes():
         """Test failure when no new changes can be generated."""
         eq_(GBS(argv=["gbs", "changelog"]), None)
         GBS(argv=["gbs", "changelog"])
 
     @staticmethod
-    @raises(SystemExit)
+    @raises(GbsError)
     def test_wrong_since():
         """Test failure with wrong --since value."""
         GBS(argv=["gbs", "changelog", "--since", "bla"])
 
-    @raises(SystemExit)
+    @raises(GbsError)
     def test_non_existent_commit(self):
         """Test failure with wrong commit id in the changelog."""
         with open(self.changes, "w") as changes:
@@ -154,13 +156,13 @@ class TestChangelog(unittest.TestCase):
         GBS(argv=["gbs", "changelog"])
 
     @staticmethod
-    @raises(SystemExit)
+    @raises(GbsError)
     def test_not_in_git_repository():
         """Test failure when run not in git repo."""
         os.chdir('..')
         GBS(argv=["gbs", "changelog"])
 
-    @raises(SystemExit)
+    @raises(GbsError)
     def test_no_spec(self):
         """Test failure when there is not spec in packaging dir."""
         os.unlink(self.spec)
index db0b79781451b0fa7dbb2f2396b404302070a6d9..b9980980f5c4b5d2ca6d1318e615dc14a1b9daca 100644 (file)
@@ -28,6 +28,8 @@ from functools import wraps
 
 from nose.tools import eq_, raises
 
+from gitbuildsys.errors import GbsError
+
 from gbp.git.repository import GitRepository
 
 GBS = imp.load_source("gbs", "./tools/gbs").main
@@ -129,19 +131,19 @@ class TestImport(unittest.TestCase):
         eq_(repo.get_local_branches(), ['master', 'pristine-tar', 'upstream'])
         eq_(repo.get_tags(), ['upstream/0.2.29', 'vendor/0.2.29-2.3'])
 
-    @raises(SystemExit)
+    @raises(GbsError)
     @with_data("bison-1.27.tar.gz")
     def test_is_not_git_repository(self, tarball):
         """Test raising exception when importing tarball outside of git."""
         GBS(argv=["gbs", "import", tarball])
 
-    @raises(SystemExit)
+    @raises(GbsError)
     @with_data("bad.src.rpm")
     def test_error_reading_pkg_header(self, srcrpm):
         """Test raising exception when importing from bad package."""
         GBS(argv=["gbs", "import", srcrpm])
 
-    @raises(SystemExit)
+    @raises(GbsError)
     @with_data("bad.spec")
     def test_cant_parse_specfile(self, spec):
         """Test raising exception when importing from non-parseable spec."""
@@ -157,7 +159,8 @@ class TestImport(unittest.TestCase):
         """Test raising exception when running gbs with too many arguments."""
         GBS(argv=["gbs", "import", "1", "2"])
 
-    @raises(SystemExit)
+    @raises(GbsError)
     def test_path_doesnt_exist(self):
         """Test raising exception when running gbs with not existing path."""
         GBS(argv=["gbs", "import", "I don't exist!"])
+
index 9cfa7d6b23f0e4903a11bc4372d724d1e14953a2..e2a1448a9ec0ffa03607eecfbf0ec21ddb61b522 100755 (executable)
--- a/tools/gbs
+++ b/tools/gbs
@@ -24,8 +24,9 @@ import os
 from argparse import ArgumentParser
 
 from gitbuildsys import __version__
-from gitbuildsys import msger, errors
+from gitbuildsys import errors
 from gitbuildsys.parsing import subparser, GbsHelpFormatter, basename_type
+from gitbuildsys import log
 
 
 @subparser
@@ -418,12 +419,7 @@ def main(argv):
     # Parse arguments
     args = parser.parse_args(argv[1:])
 
-    # Set log level for --debug and --verbose
-    if args.verbose:
-        msger.set_loglevel('verbose')
-
-    if args.debug:
-        msger.set_loglevel('debug')
+    log.setup(verbose=args.verbose, debug=args.debug)
 
     # Process configuration file if --conf is used
     if args.conf:
@@ -436,24 +432,26 @@ def main(argv):
 
 
 if __name__ == '__main__':
+    log.setup(verbose=False)
     try:
         sys.exit(main(sys.argv))
     except KeyboardInterrupt:
-        msger.error('\n^C caught, program aborted.')
+        log.LOGGER.error('^C caught, program aborted.')
 
     except errors.Usage, usage:
-        msger.error(str(usage))
+        log.LOGGER.error(str(usage))
 
     except errors.Abort, msg:
-        msger.info(str(msg))
+        log.LOGGER.info(str(msg))
 
     except errors.CmdError, err:
-        if msger.get_loglevel() == 'debug':
+        if log.LOGGER.level == log.DEBUG:
             import traceback
-            msger.error(traceback.format_exc())
+            log.LOGGER.error(traceback.format_exc())
         else:
-            msger.error('\n'+str(err))
+            log.LOGGER.error(str(err))
 
     except Exception:
         import traceback
-        msger.error(traceback.format_exc())
+        log.LOGGER.error(traceback.format_exc())
+    sys.exit(1)