コード例 #1
0
ファイル: cvccmd.py プロジェクト: fedora-conary/conary
    def runCommand(self, cfg, argSet, args, profile = False,
                   callback = None, repos = None):
        args = args[1:]
        level = log.getVerbosity()
        message = argSet.pop("message", None)
        test = argSet.pop("test", False)
        logfile = argSet.pop("log-file", None)

        if argSet or len(args) != 1: return self.usage()

        if message and logfile:
            raise errors.ConaryError("options --message and --log-file are "
                "mutually exclusive")
        if logfile:
            # Read the checkin message from the file
            if logfile == '-':
                message = sys.stdin.read()
            else:
                try:
                    message = open(logfile).read()
                except IOError, e:
                    raise errors.ConaryError("While opening %s: %s" % (
                        e.filename, e.strerror))
            # Get rid of trailing white spaces, they're probably not
            # intended to be there anyway
            message = message.rstrip()
コード例 #2
0
ファイル: cvccmd.py プロジェクト: pombreda/conary-1
    def runCommand(self,
                   cfg,
                   argSet,
                   args,
                   profile=False,
                   callback=None,
                   repos=None):
        args = args[1:]
        level = log.getVerbosity()
        message = argSet.pop("message", None)
        test = argSet.pop("test", False)
        logfile = argSet.pop("log-file", None)

        if argSet or len(args) != 1: return self.usage()

        if message and logfile:
            raise errors.ConaryError("options --message and --log-file are "
                                     "mutually exclusive")
        if logfile:
            # Read the checkin message from the file
            if logfile == '-':
                message = sys.stdin.read()
            else:
                try:
                    message = open(logfile).read()
                except IOError, e:
                    raise errors.ConaryError("While opening %s: %s" %
                                             (e.filename, e.strerror))
            # Get rid of trailing white spaces, they're probably not
            # intended to be there anyway
            message = message.rstrip()
コード例 #3
0
ファイル: command.py プロジェクト: pombreda/conary-1
 def usage(self, errNo=1):
     if not self.parser:
         self.setParser(self.mainHandler.getParserByClass(self))
     self.parser.print_help()
     if log.getVerbosity() > log.INFO:
         print
         print '(Use --verbose to get a full option listing)'
     return errNo
コード例 #4
0
ファイル: command.py プロジェクト: fedora-conary/conary
 def usage(self, errNo=1):
     if not self.parser:
         self.setParser(self.mainHandler.getParserByClass(self))
     self.parser.print_help()
     if log.getVerbosity() > log.INFO:
         print
         print '(Use --verbose to get a full option listing)'
     return errNo
コード例 #5
0
    def testLocalFactoryWithLocalRecipe(self):
        os.chdir(self.workDir)
        self.newpkg("foo", factory="test")
        os.chdir("foo")
        self.writeFile(
            "factory-test.recipe", """
class TestFactory(Factory):

    name = "factory-test"
    version = "1.0"

    def getRecipeClass(self):
        class TestSubclass(PackageRecipe):
            name = "testsubclass"
            version = "1.0"
            internalAbstractBaseClass = True
            clearBuildReqs()

        return TestSubclass
""")

        self.writeFile(
            "foo.recipe", """
# CNY-2813. importing log inside a recipe used to reset the loglevel
from conary.lib import log
class FooRecipe(FactoryRecipeClass):

    name = "foo"
    version = "1.1"

    def setup(self):
        self.Create("/etc/foo", "foo")
""")

        self.addfile("foo.recipe")
        repos = self.openRepository()
        cstate = state.ConaryStateFromFile('CONARY')
        level = log.getVerbosity()
        try:
            log.setVerbosity(log.INFO)
            klass = logging.getLoggerClass()
            self.discardOutput(cook.cookCommand, self.cfg, [cstate], False, {})
            self.assertEquals(klass, logging.getLoggerClass())
        finally:
            log.setVerbosity(level)
        ccs = changeset.ChangeSetFromFile(
            os.path.join(self.workDir, 'foo', 'foo-1.1.ccs'))
        trvs = [trove.Trove(x) for x in ccs.iterNewTroveList()]
        trv = [x for x in trvs if x.getName() == 'foo:debuginfo'][0]
        files = [x for x in trv.iterFileList() if \
                x[1] == '/usr/src/debug/buildlogs/foo-1.1-log.bz2']
        fileId, path, pathId, ver = files[0]
        fileInfo, fileObj = ccs.getFileContents(fileId, pathId)
        decomp = bz2.BZ2Decompressor()
        data = decomp.decompress(fileObj.f.read())
        self.assertFalse("+ Processing" not in data,
                         "build log data appears to be incomplete")
コード例 #6
0
ファイル: factorytest.py プロジェクト: pombr/conary
    def testLocalFactoryWithLocalRecipe(self):
        os.chdir(self.workDir)
        self.newpkg("foo", factory = "test")
        os.chdir("foo")
        self.writeFile("factory-test.recipe",
"""
class TestFactory(Factory):

    name = "factory-test"
    version = "1.0"

    def getRecipeClass(self):
        class TestSubclass(PackageRecipe):
            name = "testsubclass"
            version = "1.0"
            internalAbstractBaseClass = True
            clearBuildReqs()

        return TestSubclass
""")

        self.writeFile("foo.recipe",
"""
# CNY-2813. importing log inside a recipe used to reset the loglevel
from conary.lib import log
class FooRecipe(FactoryRecipeClass):

    name = "foo"
    version = "1.1"

    def setup(self):
        self.Create("/etc/foo", "foo")
""")

        self.addfile("foo.recipe")
        repos = self.openRepository()
        cstate = state.ConaryStateFromFile('CONARY')
        level = log.getVerbosity()
        try:
            log.setVerbosity(log.INFO)
            klass = logging.getLoggerClass()
            self.discardOutput(cook.cookCommand, self.cfg, [cstate], False, {})
            self.assertEquals(klass, logging.getLoggerClass())
        finally:
            log.setVerbosity(level)
        ccs = changeset.ChangeSetFromFile(os.path.join(self.workDir,
                'foo', 'foo-1.1.ccs'))
        trvs = [trove.Trove(x) for x in ccs.iterNewTroveList()]
        trv = [x for x in trvs if x.getName() == 'foo:debuginfo'][0]
        files = [x for x in trv.iterFileList() if \
                x[1] == '/usr/src/debug/buildlogs/foo-1.1-log.bz2']
        fileId, path, pathId, ver = files[0]
        fileInfo, fileObj = ccs.getFileContents(fileId, pathId)
        decomp = bz2.BZ2Decompressor()
        data = decomp.decompress(fileObj.f.read())
        self.assertFalse("+ Processing" not in data,
                "build log data appears to be incomplete")
コード例 #7
0
ファイル: commandtest.py プロジェクト: fedora-conary/rbuild
 def testProcessConfigOptions(self):
     configPath = self.rootDir + '/rbuildrc'
     self.writeFile(configPath, 'user newuser\n')
     cmd = command.BaseCommand()
     cmd.processConfigOptions(self.rbuildCfg, {},
                              {'config-file' : [configPath],
                               'verbose' : True })
     self.assertEquals(self.rbuildCfg.user, ('newuser', None))
     self.assertEquals(log.getVerbosity(), log.DEBUG)
コード例 #8
0
 def testProcessConfigOptions(self):
     configPath = self.rootDir + '/rbuildrc'
     self.writeFile(configPath, 'user newuser\n')
     cmd = command.BaseCommand()
     cmd.processConfigOptions(self.rbuildCfg, {}, {
         'config-file': [configPath],
         'verbose': True
     })
     self.assertEquals(self.rbuildCfg.user, ('newuser', None))
     self.assertEquals(log.getVerbosity(), log.DEBUG)
コード例 #9
0
 def format_help(self, formatter):
     if log.getVerbosity() > log.INFO:
         found = False
         for option in self.option_list:
             if (option.help_level == NORMAL_HELP
                     and option.help != optparse.SUPPRESS_HELP):
                 found = True
                 break
         if not found:
             return ''
     return optparse.OptionGroup.format_help(self, formatter)
コード例 #10
0
ファイル: options.py プロジェクト: pombr/conary
 def format_help(self, formatter):
    if log.getVerbosity() > log.INFO:
        found = False
        for option in self.option_list:
            if (option.help_level == NORMAL_HELP
                and option.help != optparse.SUPPRESS_HELP):
                found = True
                break
        if not found:
            return ''
    return optparse.OptionGroup.format_help(self, formatter)
コード例 #11
0
ファイル: command.py プロジェクト: sassoftware/rbuild
    def subCommandUsage(self, subCommandName, errNo=1):
        if not self._subCommands.has_key(subCommandName):
            print "%s %s: no such subcommand: %s" % \
                   (self.mainHandler.name, self.commands[0], subCommandName)
            sys.exit(1)

        thisCommand = self._subCommands[subCommandName]()
        thisCommand.setMainHandler(self.mainHandler)
        params, _ = thisCommand.prepare()
        usage = '%s %s %s %s' % (self.mainHandler.name, '/'.join(self.commands),
                                 subCommandName, thisCommand.paramHelp)
        kwargs = self.mainHandler._getParserFlags(thisCommand)
        kwargs['defaultGroup'] = None
        parser = options._getParser(params, {}, usage=usage, **kwargs)
        parser.print_help()
        if log.getVerbosity() > log.INFO:
            print '(Use --verbose to get a full option listing)'
        return errNo
コード例 #12
0
ファイル: command.py プロジェクト: pombreda/rbuild-1
    def subCommandUsage(self, subCommandName, errNo=1):
        if not self._subCommands.has_key(subCommandName):
            print "%s %s: no such subcommand: %s" % \
                   (self.mainHandler.name, self.commands[0], subCommandName)
            sys.exit(1)

        thisCommand = self._subCommands[subCommandName]()
        thisCommand.setMainHandler(self.mainHandler)
        params, _ = thisCommand.prepare()
        usage = '%s %s %s %s' % (self.mainHandler.name, '/'.join(self.commands),
                                 subCommandName, thisCommand.paramHelp)
        kwargs = self.mainHandler._getParserFlags(thisCommand)
        kwargs['defaultGroup'] = None
        parser = options._getParser(params, {}, usage=usage, **kwargs)
        parser.print_help()
        if log.getVerbosity() > log.INFO:
            print '(Use --verbose to get a full option listing)'
        return errNo
コード例 #13
0
ファイル: testcase.py プロジェクト: pombredanne/testutils
    def setUp(self):
        from conary.lib import log
        self._logLevel = log.getVerbosity()

        # Set the timezone to something consistent
        os.environ['TZ'] = self.TIMEZONE
        import time; time.tzset()
        import _strptime
        # Reset strptime's internal cache too
        try:
            _strptime._cache_lock.acquire()
            _strptime._TimeRE_cache.__init__(_strptime.LocaleTime())
        finally:
            _strptime._cache_lock.release()

        # save the original stdio fds for later
        self.savedStdin = sys.stdin
        self.savedStdout = sys.stdout
        self.savedStderr = sys.stderr
コード例 #14
0
ファイル: helper.py プロジェクト: pombredanne/rmake
 def displayJob(self, job, quiet=False):
     verbose = log.getVerbosity() <= log.DEBUG
     return buildcmd.displayBuildInfo(job, verbose=verbose,
                                      quiet=quiet)
コード例 #15
0
ファイル: options.py プロジェクト: pombr/conary
 def format_option(self, option):
     if option.help_level == VERBOSE_HELP and log.getVerbosity() > log.INFO:
         return ''
     return optparse.IndentedHelpFormatter.format_option(self, option)
コード例 #16
0
ファイル: cvccmd.py プロジェクト: fedora-conary/conary
    def runCommand(self, cfg, argSet, args, profile = False,
                   callback = None, repos = None):
        args = args[1:]
        level = log.getVerbosity()
        macros = {}
        prep = 0
        downloadOnly = False
        resume = None
        if argSet.has_key('flavor'):
            buildFlavor = deps.deps.parseFlavor(argSet['flavor'],
                                                raiseError=True)
            cfg.buildFlavor = deps.deps.overrideFlavor(cfg.buildFlavor,
                                                       buildFlavor)
            del argSet['flavor']

        if argSet.has_key('macros'):
            f = open(argSet['macros'])
            for row in f:
                row = row.strip()
                if not row or row[0] == '#':
                    continue
                cfg.configLine('macros ' + row.strip())
            f.close()
            del f
            del argSet['macros']

        if argSet.has_key('macro'):
            for macro in argSet['macro']:
                cfg.configLine('macros ' + macro)
            del argSet['macro']

        if argSet.has_key('prep'):
            del argSet['prep']
            prep = 1
        if argSet.has_key('ignore-buildreqs'):
            del argSet['ignore-buildreqs']
            ignoreDeps = True
        elif argSet.has_key('no-deps'):
            del argSet['no-deps']
            ignoreDeps = True
        else:
            ignoreDeps = False

        if argSet.has_key('download'):
            if argSet.has_key('prep') or prep==True:
                log.warn('download and prep should not be used together... prefering download only')
            del argSet['download']
            ignoreDeps = True
            downloadOnly = True

        showBuildReqs = argSet.pop('show-buildreqs', False)

        if argSet.has_key('quiet'):
            cfg.quiet = True
            del argSet['quiet']

        if 'no-clean' in argSet:
            cfg.cleanAfterCook = False
            del argSet['no-clean']

        allowFlavorChange = argSet.pop('allow-flavor-change', False)

        if argSet.has_key('resume'):
            resume = argSet['resume']
            del argSet['resume']
        if argSet.has_key('unknown-flags'):
            unknownFlags = argSet['unknown-flags']
            del argSet['unknown-flags']
        else:
            unknownFlags = False
        if argSet.has_key('debug-exceptions'):
            del argSet['debug-exceptions']
            cfg.debugRecipeExceptions = True

        crossCompile = argSet.pop('cross', None)
        if crossCompile:
            parts = crossCompile.split('--')
            isCrossTool = False

            if len(parts) == 1:
                crossTarget = crossCompile
                crossHost = None
            else:
                crossHost, crossTarget = parts
                if crossHost == 'local':
                    crossHost = None
                    isCrossTool = True

            crossCompile = (crossHost, crossTarget, isCrossTool)

        targetFile = argSet.pop("to-file", None)
        if argSet: return self.usage()

        groupOptions = cook.GroupCookOptions(alwaysBumpCount=True,
                                 errorOnFlavorChange=not allowFlavorChange,
                                 shortenFlavors=cfg.shortenGroupFlavors)

        # the remainder of the argument list are the things to build.
        # e.g., foo /path/to/bar.recipe, etc.
        items = args[1:]
        if not items:
            # if nothing was specified, try to build the package in the current
            # directory
            if os.path.isfile('CONARY'):
                conaryState = state.ConaryStateFromFile('CONARY', repos)
                items = [ conaryState ]

            if not items:
                # if we still don't have anything to build, throw a usage
                # message
                return self.usage()

        try:
            cook.cookCommand(cfg, items, prep, macros, resume=resume,
                         allowUnknownFlags=unknownFlags, ignoreDeps=ignoreDeps,
                         showBuildReqs=showBuildReqs, profile=profile,
                         crossCompile=crossCompile, downloadOnly=downloadOnly,
                         groupOptions=groupOptions,
                         changeSetFile=targetFile,
                         )
        except builderrors.GroupFlavorChangedError, err:
            err.args = (err.args[0] +
                        '\n(Add the --allow-flavor-change flag to override this error)\n',)
            raise
コード例 #17
0
    def formatInfo(self, trove):
        """ returns iterator of format lines about this local trove """
        # TODO: it'd be nice if this were set up to do arbitrary
        # formats...

        n, v, f = trove.getName(), trove.getVersion(), trove.getFlavor()
        dcfg = self.dcfg
        troveSource = dcfg.getTroveSource()

        sourceName = trove.getSourceName()
        sourceTrove = None

        if sourceName:
            try:
                sourceVer = v.getSourceVersion()
                if sourceVer.isOnLocalHost():
                    sourceVer = sourceVer.parentVersion()

                sourceTrove = troveSource.getTrove(sourceName,
                                                   sourceVer,
                                                   deps.Flavor(),
                                                   withFiles=False)
                # FIXME: all trove sources should return TroveMissing
                # on failed getTrove calls
            except errors.TroveMissing:
                pass
            except errors.InsufficientPermission:
                pass

        elif n.endswith(':source'):
            sourceTrove = trove

        if trove.getBuildTime():
            buildTime = time.strftime("%c",
                                      time.localtime(trove.getBuildTime()))
        else:
            buildTime = "(unknown)"

        if trove.getSize() is not None:
            size = "%s" % trove.getSize()
        else:
            size = "(unknown)"

        yield "%-30s %s" % \
            (("Name      : %s" % trove.getName(),
             ("Build time: %s" % buildTime)))

        if dcfg.fullVersions:
            yield "Version   : %s" % v
            yield "Label     : %s" % v.branch().label().asString()
        else:
            yield "%-30s %s" % \
                (("Version   : %s" %
                            v.trailingRevision().asString()),
                 ("Label     : %s" %
                            v.branch().label().asString()))

        yield '%-30s' % ("Size      : %s" % size)
        if hasattr(troveSource, 'trovesArePinned'):
            yield "Pinned    : %s" % troveSource.trovesArePinned([(n, v, f)
                                                                  ])[0]

        yield "%-30s" % ("Flavor    : %s" % deps.formatFlavor(f))
        if trove.getInstallTime():
            yield 'Installed : %s' % (time.strftime(
                "%c", time.localtime(trove.getInstallTime())))

        imageGroup = trove.troveInfo.imageGroup()
        if imageGroup is not None:
            yield 'Image Group: %s' % bool(imageGroup)

        for ln in self.formatMetadata(trove):
            yield ln
        if sourceTrove:
            if not n.endswith(':source'):
                yield 'Source    : %s' % trove.getSourceName()
            cl = sourceTrove.getChangeLog()
            if cl:
                yield "Change log: %s (%s)" % (cl.getName(), cl.getContact())
                lines = cl.getMessage().split("\n")[:-1]
                for l in lines:
                    yield "    " + l

        if log.getVerbosity() <= log.DEBUG:
            yield "%-30s %s" % (
                ("Incomp.   : %s" % bool(trove.troveInfo.incomplete())),
                ("TroveVer  : %s" % trove.troveInfo.troveVersion()))
            yield "%-30s" % (("Clone of  : %s" % trove.troveInfo.clonedFrom()))
            yield "%-30s" % (
                ("Conary version : %s" % trove.troveInfo.conaryVersion()))
コード例 #18
0
ファイル: displaytest.py プロジェクト: pombr/conary
    def testTroveDisplayInfo(self):
        trv = self.addComponent('test1:source=1.0-1')
        mi = self.createMetadataItem(categories=['cat1', 'cat2'],
                                     licenses=['GPL', 'GPLv3'],
                                     shortDesc='short',
                                     longDesc='long',
                                     crypto=['foo', 'foo2'],
                                     url=['url1'])


        self.addComponent('test1:run=1.0-1-1', metadata=mi, 
                          sourceName='test1:source')
        repos = self.openRepository()
        rs, s = self.captureOutput(queryrep.displayTroves, self.cfg,
                                   ['test1:run'], info=True)
        s = re.sub('Build time: .*', 'Build time: <TIME>', s)
        info = '''\
Name      : test1:run          Build time: <TIME>
Version   : 1.0-1-1            Label     : localhost@rpl:linux
Size      : 14                
Flavor    :                   
License   : GPL
License   : GPLv3
Crypto    : foo
Crypto    : foo2
Category  : cat1
Category  : cat2
Summary   : short
Url       : url1
Description: 
    long
Source    : test1:source
Change log:  ()
'''
        assert(s == info)

        # --debug mode
        debugInfo = '''\
Name      : test1:run          Build time: <TIME>
Version   : 1.0-1-1            Label     : localhost@rpl:linux
Size      : 14                
Committed : <TIME>
Flavor    :                   
License   : GPL
License   : GPLv3
Crypto    : foo
Crypto    : foo2
Category  : cat1
Category  : cat2
Summary   : short
Url       : url1
Description: 
    long
Source    : test1:source
Change log:  ()
Incomp.   : False              TroveVer  : 10
Clone of  : None              
Conary version :              
'''

        verbosity = log.getVerbosity()
        log.setVerbosity(log.DEBUG)
        try:
            rs, s = self.captureOutput(queryrep.displayTroves, self.cfg,
                    ['test1:run'], info=True)
        finally:
            log.setVerbosity(verbosity)

        s = re.sub('(Build time|Committed ): .*', r'\1: <TIME>', s)
        self.assertEqual(s, debugInfo)

        # test to make sure that we can display some info if :source
        # is not available to us
        noSourceInfo = '''\
Name      : test1:run          Build time: <TIME>
Version   : 1.0-1-1            Label     : localhost@rpl:linux
Size      : 14                
Flavor    :                   
License   : GPL
License   : GPLv3
Crypto    : foo
Crypto    : foo2
Category  : cat1
Category  : cat2
Summary   : short
Url       : url1
Description: 
    long
'''
        repos.deleteUserByName(self.cfg.buildLabel, 'anonymous')
        limitedRepos = self.setupUser(repos, self.cfg.buildLabel,
                                      'limited', 'bar',
                                      '[^:]+(:(?!debuginfo$|source$).*|$)',
                                      self.cfg.buildLabel)
        self.cfg.user.addServerGlob('*', 'limited', 'bar')
        rs, s = self.captureOutput(queryrep.displayTroves, self.cfg, 
                                   ['test1:run'],
                                   info=True)
        s = re.sub('Build time: .*', 'Build time: <TIME>', s)

        self.assertEqual(s, noSourceInfo)
コード例 #19
0
 def format_option(self, option):
     if option.help_level == VERBOSE_HELP and log.getVerbosity() > log.INFO:
         return ''
     return optparse.IndentedHelpFormatter.format_option(self, option)
コード例 #20
0
    if addDebugOptions:
        if argSet.has_key('debugger'):
            del argSet['debugger']
            from conary.lib import debugger
            debugger.set_trace()
            sys.excepthook = util.genExcepthook(debug=cfg.debugExceptions,
                                                debugCtrlC=True)

        if 'debug' in argSet:
            if argSet['debug'] is True:
                log.setVerbosity(log.DEBUG)
            else:
                log.setVerbosity(log.LOWLEVEL)
            del argSet['debug']
        else:
            if log.getVerbosity() > log.WARNING:
                log.setVerbosity(log.WARNING)

    return argSet, otherArgs, parser, options


def getOptionParser(params,
                    usage,
                    version=None,
                    useHelp=False,
                    defaultGroup=None,
                    interspersedArgs=True,
                    hobbleShortOpts=False,
                    description=None):
    parser = OptionParser(usage=usage,
                          add_help_option=useHelp,
コード例 #21
0
ファイル: cvccmd.py プロジェクト: pombreda/conary-1
    def runCommand(self,
                   cfg,
                   argSet,
                   args,
                   profile=False,
                   callback=None,
                   repos=None):
        args = args[1:]
        level = log.getVerbosity()
        macros = {}
        prep = 0
        downloadOnly = False
        resume = None
        if argSet.has_key('flavor'):
            buildFlavor = deps.deps.parseFlavor(argSet['flavor'],
                                                raiseError=True)
            cfg.buildFlavor = deps.deps.overrideFlavor(cfg.buildFlavor,
                                                       buildFlavor)
            del argSet['flavor']

        if argSet.has_key('macros'):
            f = open(argSet['macros'])
            for row in f:
                row = row.strip()
                if not row or row[0] == '#':
                    continue
                cfg.configLine('macros ' + row.strip())
            f.close()
            del f
            del argSet['macros']

        if argSet.has_key('macro'):
            for macro in argSet['macro']:
                cfg.configLine('macros ' + macro)
            del argSet['macro']

        if argSet.has_key('prep'):
            del argSet['prep']
            prep = 1
        if argSet.has_key('ignore-buildreqs'):
            del argSet['ignore-buildreqs']
            ignoreDeps = True
        elif argSet.has_key('no-deps'):
            del argSet['no-deps']
            ignoreDeps = True
        else:
            ignoreDeps = False

        if argSet.has_key('download'):
            if argSet.has_key('prep') or prep == True:
                log.warn(
                    'download and prep should not be used together... prefering download only'
                )
            del argSet['download']
            ignoreDeps = True
            downloadOnly = True

        showBuildReqs = argSet.pop('show-buildreqs', False)

        if argSet.has_key('quiet'):
            cfg.quiet = True
            del argSet['quiet']

        if 'no-clean' in argSet:
            cfg.cleanAfterCook = False
            del argSet['no-clean']

        allowFlavorChange = argSet.pop('allow-flavor-change', False)

        if argSet.has_key('resume'):
            resume = argSet['resume']
            del argSet['resume']
        if argSet.has_key('unknown-flags'):
            unknownFlags = argSet['unknown-flags']
            del argSet['unknown-flags']
        else:
            unknownFlags = False
        if argSet.has_key('debug-exceptions'):
            del argSet['debug-exceptions']
            cfg.debugRecipeExceptions = True

        crossCompile = argSet.pop('cross', None)
        if crossCompile:
            parts = crossCompile.split('--')
            isCrossTool = False

            if len(parts) == 1:
                crossTarget = crossCompile
                crossHost = None
            else:
                crossHost, crossTarget = parts
                if crossHost == 'local':
                    crossHost = None
                    isCrossTool = True

            crossCompile = (crossHost, crossTarget, isCrossTool)

        targetFile = argSet.pop("to-file", None)
        if argSet: return self.usage()

        groupOptions = cook.GroupCookOptions(
            alwaysBumpCount=True,
            errorOnFlavorChange=not allowFlavorChange,
            shortenFlavors=cfg.shortenGroupFlavors)

        # the remainder of the argument list are the things to build.
        # e.g., foo /path/to/bar.recipe, etc.
        items = args[1:]
        if not items:
            # if nothing was specified, try to build the package in the current
            # directory
            if os.path.isfile('CONARY'):
                conaryState = state.ConaryStateFromFile('CONARY', repos)
                items = [conaryState]

            if not items:
                # if we still don't have anything to build, throw a usage
                # message
                return self.usage()

        try:
            cook.cookCommand(
                cfg,
                items,
                prep,
                macros,
                resume=resume,
                allowUnknownFlags=unknownFlags,
                ignoreDeps=ignoreDeps,
                showBuildReqs=showBuildReqs,
                profile=profile,
                crossCompile=crossCompile,
                downloadOnly=downloadOnly,
                groupOptions=groupOptions,
                changeSetFile=targetFile,
            )
        except builderrors.GroupFlavorChangedError, err:
            err.args = (
                err.args[0] +
                '\n(Add the --allow-flavor-change flag to override this error)\n',
            )
            raise
コード例 #22
0
class RmakeMain(options.MainHandler):
    name = 'rmake'
    version = constants.version

    abstractCommand = command.rMakeCommand
    configClass = buildcfg.BuildConfiguration

    useConaryOptions = False

    commandList = command._commands

    def usage(self, rc=1, showAll=False):
        print 'rmake: front end to rMake build tool'
        if not showAll:
            print
            print 'Common Commands (use "rmake help" for the full list)'
        return options.MainHandler.usage(self, rc, showAll=showAll)

    def initializePlugins(self, argv):
        p = plugins.getPluginManager(argv, buildcfg.BuildConfiguration)
        p.callClientHook('client_preInit', self, argv)
        return p

    def getConfigFile(self, argv):
        pluginManager = self.initializePlugins(argv)
        if '--skip-default-config' in argv:
            argv.remove('--skip-default-config')
            read = False
        else:
            read = True

        buildConfig = buildcfg.BuildConfiguration(readConfigFiles=read)
        conaryConfig = conarycfg.ConaryConfiguration(readConfigFiles=read)
        return buildConfig, conaryConfig, pluginManager

    def runCommand(self, thisCommand, (buildConfig, conaryConfig,
                                       pluginManager), argSet, args):
        pluginManager.callClientHook('client_preCommand', self, thisCommand,
                                     (buildConfig, conaryConfig), argSet, args)
        compat.checkRequiredVersions()
        thisCommand.verbose = (log.getVerbosity() <= log.INFO)
        if args[1] != 'help':
            # NOTE: the help system assumes that the base level of output
            # you want is "warning", but rmake is more verbose than that.
            # Due to limitations in how configurable the help system is,
            # I can't easily fix that.  Someday I should though.  For now,
            # if we're running help, we make log.WARNING the default level,
            # and otherwise log.INFO is the default.
            log.setMinVerbosity(log.INFO)

        # don't let the buildFlavor be overridden yet
        client = helper.rMakeHelper(buildConfig=buildConfig,
                                    promptPassword=True)

        pluginManager.callClientHook('client_preCommand2', self, client,
                                     thisCommand)

        try:
            return options.MainHandler.runCommand(self, thisCommand, client,
                                                  buildConfig, argSet, args)
        except errors.BadParameters:
            if not thisCommand.verbose:
                log.setVerbosity(log.WARNING)
            thisCommand.usage()
            raise
コード例 #23
0
    def testTroveDisplayInfo(self):
        trv = self.addComponent('test1:source=1.0-1')
        mi = self.createMetadataItem(categories=['cat1', 'cat2'],
                                     licenses=['GPL', 'GPLv3'],
                                     shortDesc='short',
                                     longDesc='long',
                                     crypto=['foo', 'foo2'],
                                     url=['url1'])

        self.addComponent('test1:run=1.0-1-1',
                          metadata=mi,
                          sourceName='test1:source')
        repos = self.openRepository()
        rs, s = self.captureOutput(queryrep.displayTroves,
                                   self.cfg, ['test1:run'],
                                   info=True)
        s = re.sub('Build time: .*', 'Build time: <TIME>', s)
        info = '''\
Name      : test1:run          Build time: <TIME>
Version   : 1.0-1-1            Label     : localhost@rpl:linux
Size      : 14                
Flavor    :                   
License   : GPL
License   : GPLv3
Crypto    : foo
Crypto    : foo2
Category  : cat1
Category  : cat2
Summary   : short
Url       : url1
Description: 
    long
Source    : test1:source
Change log:  ()
'''
        assert (s == info)

        # --debug mode
        debugInfo = '''\
Name      : test1:run          Build time: <TIME>
Version   : 1.0-1-1            Label     : localhost@rpl:linux
Size      : 14                
Committed : <TIME>
Flavor    :                   
License   : GPL
License   : GPLv3
Crypto    : foo
Crypto    : foo2
Category  : cat1
Category  : cat2
Summary   : short
Url       : url1
Description: 
    long
Source    : test1:source
Change log:  ()
Incomp.   : False              TroveVer  : 10
Clone of  : None              
Conary version :              
'''

        verbosity = log.getVerbosity()
        log.setVerbosity(log.DEBUG)
        try:
            rs, s = self.captureOutput(queryrep.displayTroves,
                                       self.cfg, ['test1:run'],
                                       info=True)
        finally:
            log.setVerbosity(verbosity)

        s = re.sub('(Build time|Committed ): .*', r'\1: <TIME>', s)
        self.assertEqual(s, debugInfo)

        # test to make sure that we can display some info if :source
        # is not available to us
        noSourceInfo = '''\
Name      : test1:run          Build time: <TIME>
Version   : 1.0-1-1            Label     : localhost@rpl:linux
Size      : 14                
Flavor    :                   
License   : GPL
License   : GPLv3
Crypto    : foo
Crypto    : foo2
Category  : cat1
Category  : cat2
Summary   : short
Url       : url1
Description: 
    long
'''
        repos.deleteUserByName(self.cfg.buildLabel, 'anonymous')
        limitedRepos = self.setupUser(repos, self.cfg.buildLabel, 'limited',
                                      'bar',
                                      '[^:]+(:(?!debuginfo$|source$).*|$)',
                                      self.cfg.buildLabel)
        self.cfg.user.addServerGlob('*', 'limited', 'bar')
        rs, s = self.captureOutput(queryrep.displayTroves,
                                   self.cfg, ['test1:run'],
                                   info=True)
        s = re.sub('Build time: .*', 'Build time: <TIME>', s)

        self.assertEqual(s, noSourceInfo)
コード例 #24
0
 def displayJob(self, job, quiet=False):
     verbose = log.getVerbosity() <= log.DEBUG
     return buildcmd.displayBuildInfo(job, verbose=verbose,
                                      quiet=quiet)
コード例 #25
0
ファイル: display.py プロジェクト: pombr/conary
    def formatInfo(self, trove):
        """ returns iterator of format lines about this local trove """
        # TODO: it'd be nice if this were set up to do arbitrary
        # formats...

        n, v, f = trove.getName(), trove.getVersion(), trove.getFlavor()
        dcfg = self.dcfg
        troveSource = dcfg.getTroveSource()

        sourceName = trove.getSourceName()
        sourceTrove = None

        if sourceName:
            try:
                sourceVer = v.getSourceVersion()
                if sourceVer.isOnLocalHost():
                    sourceVer = sourceVer.parentVersion()

                sourceTrove = troveSource.getTrove(
                    sourceName, sourceVer, deps.Flavor(), withFiles = False)
                # FIXME: all trove sources should return TroveMissing
                # on failed getTrove calls
            except errors.TroveMissing:
                pass
            except errors.InsufficientPermission:
                pass

        elif n.endswith(':source'):
            sourceTrove = trove

        if trove.getBuildTime():
            buildTime = time.strftime("%c",
                                time.localtime(trove.getBuildTime()))
        else:
            buildTime = "(unknown)"

        if trove.getSize() is not None:
            size = "%s" % trove.getSize()
        else:
            size = "(unknown)"

        yield "%-30s %s" % \
            (("Name      : %s" % trove.getName(),
             ("Build time: %s" % buildTime)))

        if dcfg.fullVersions:
            yield "Version   : %s" %v
            yield "Label     : %s" % v.branch().label().asString()
        else:
            yield "%-30s %s" % \
                (("Version   : %s" %
                            v.trailingRevision().asString()),
                 ("Label     : %s" %
                            v.branch().label().asString()))

        yield '%-30s' % ("Size      : %s" % size)
        if hasattr(troveSource, 'trovesArePinned'):
            yield "Pinned    : %s" % troveSource.trovesArePinned(
                                                            [ (n, v, f) ])[0]

        commitTime = v.trailingRevision().timeStamp
        if commitTime:
            commitTime = time.strftime("%c", time.localtime(commitTime))
        else:
            commitTime = '(unknown)'
        if not trove.getBuildTime() or log.getVerbosity() <= log.DEBUG:
            yield "Committed : " + commitTime
        yield "%-30s" % ("Flavor    : %s" % deps.formatFlavor(f))
        if trove.getInstallTime():
            yield 'Installed : %s' % (time.strftime("%c",
                time.localtime(trove.getInstallTime())))

        imageGroup = trove.troveInfo.imageGroup()
        if imageGroup is not None:
            yield 'Image Group: %s' % bool(imageGroup)

        for ln in self.formatMetadata(trove):
            yield ln
        if sourceTrove:
            if not n.endswith(':source'):
                yield 'Source    : %s' % trove.getSourceName()
            cl = sourceTrove.getChangeLog()
            if cl:
                yield "Change log: %s (%s)" % (cl.getName(), cl.getContact())
                lines = cl.getMessage().split("\n")[:-1]
                for l in lines:
                    yield "    " + l
        if log.getVerbosity() <= log.DEBUG:
            yield "%-30s %s" % (("Incomp.   : %s" %
                                 bool(trove.troveInfo.incomplete())),
                                ("TroveVer  : %s" %
                                            trove.troveInfo.troveVersion()))
            yield "%-30s" % (("Clone of  : %s" % trove.troveInfo.clonedFrom()))
            subPackages = set(trove.troveInfo.subPackages())
            subPackages.discard(trove.getName())
            if subPackages:
                yield "%-30s" % (("Siblings  : %s" % (' '.join(sorted(subPackages)))))
            yield "%-30s" % (("Conary version : %s" % trove.troveInfo.conaryVersion()))
コード例 #26
0
ファイル: options.py プロジェクト: pombr/conary
    if addDebugOptions:
        if argSet.has_key('debugger'):
            del argSet['debugger']
            from conary.lib import debugger
            debugger.set_trace()
            sys.excepthook = util.genExcepthook(debug=cfg.debugExceptions,
                                                debugCtrlC=True)

        if 'debug' in argSet:
            if argSet['debug'] is True:
                log.setVerbosity(log.DEBUG)
            else:
                log.setVerbosity(log.LOWLEVEL)
            del argSet['debug']
        else:
            if log.getVerbosity() > log.WARNING:
                log.setVerbosity(log.WARNING)


    return argSet, otherArgs, parser, options

def getOptionParser(params, usage, version=None, useHelp=False,
                    defaultGroup=None, interspersedArgs=True,
                    hobbleShortOpts=False, description=None):
    parser = OptionParser(usage=usage, add_help_option=useHelp,
                          version=version,
                          hobbleShortOpts=hobbleShortOpts,
                          option_class=Option,
                          formatter=HelpFormatter(),
                          description=description)
    if not interspersedArgs: