Exemplo n.º 1
0
    def testShadowed(self):
        self.repos = self.openRepository()
        self.addTestPkg(1, 
                        content='''r.Create("/etc/foo", 
                                            contents="old contents\\n")''')
        self.mkbranch(self.cfg.buildLabel, "@rpl:branch", "test1:source",
                      shadow=True)
        self.cfg.buildLabel = versions.Label('localhost@rpl:branch')
        self.cfg.installLabelPath = \
                    conarycfg.CfgLabelList([self.cfg.buildLabel])
        # modify the trove on the shadow
        self.addTestPkg(1, content='''r.Create("/etc/foo", 
                                            contents="new contents\\n")''')
        self.cookTestPkg(1)
        self.updatePkg(self.rootDir, 'test1', depCheck=False)
        self.writeFile(self.rootDir + "/etc/foo", 'newer contents\\n')

        (fd, path) = tempfile.mkstemp()
        os.close(fd)
        self.localChangeset(self.rootDir, 'test1', path)
        commit.doCommit(self.cfg, path,
                        'localhost@commit:branch')
        assert(self.repos.hasTrove('test1', versions.VersionFromString(
                '/localhost@rpl:linux//branch//commit:branch/1.0-1.1-1.0.1'),
                deps.Flavor()))

        # commit it again to make sure the version gets incremented
        commit.doCommit(self.cfg, path,
                        'localhost@commit:branch')
        assert(self.repos.hasTrove('test1', versions.VersionFromString(
                '/localhost@rpl:linux//branch//commit:branch/1.0-1.1-1.0.2'),
                deps.Flavor()))

        os.remove(path)
Exemplo n.º 2
0
 def _logDifferenceInPrebuiltReqs(self, trv, buildReqTups, preBuiltReqs):
     existsTrv = trove.Trove('@update',  
                            versions.NewVersion(),
                            deps.Flavor(), None)
     availableTrv = trove.Trove('@update', 
                                versions.NewVersion(), 
                                deps.Flavor(), None)
     for troveNVF in preBuiltReqs:
         existsTrv.addTrove(*troveNVF)
     for troveNVF in buildReqTups:
         availableTrv.addTrove(*troveNVF)
     jobs = availableTrv.diff(existsTrv)[2]
     formatter = display.JobTupFormatter(affinityDb=None)
     formatter.dcfg.setTroveDisplay(fullVersions=True,
                                    fullFlavors=True,
                                    showComponents=True)
     formatter.dcfg.setJobDisplay(compressJobs=True)
     formatter.prepareJobLists([jobs])
     self.logger.info('Could count %s=%s[%s]{%s} as prebuilt - the'
                      ' following changes have been made in its'
                      ' buildreqs:' % trv.getNameVersionFlavor(
                                                         withContext=True))
     for line in formatter.formatJobTups(jobs):
         self.logger.info(line)
     self.logger.info('...Rebuilding')
Exemplo n.º 3
0
    def testTroveMultiFlavor(self):
        # create a package with 3 components, each use a different use
        # flag.  add the package before the components.  the goal is
        # to make the trovestore create more than one flavor
        flags = ('foo', 'bar', 'baz')
        flavors = []
        for flag in flags:
            flavor = deps.Flavor()
            flavor.addDep(
                deps.UseDependency,
                deps.Dependency('use', [(flag, deps.FLAG_SENSE_REQUIRED)]))
            flavor.addDep(deps.InstructionSetDependency,
                          deps.Dependency('x86', []))
            flavors.append(flavor)

        v10 = ThawVersion("/conary.rpath.com@test:trunk/10:1.2-10")
        store = self._connect()

        # create components to add to the package
        troves = []
        for flag, flavor in zip(flags, flavors):
            trv = trove.Trove('test:%s' % flag, v10, flavor, None)
            trv.computeDigests()
            troves.append(trv)

        # add the package
        union = deps.Flavor()
        for flavor in flavors:
            union.union(flavor)
        trv2 = trove.Trove("test", v10, union, None)
        for trv in troves:
            trv2.addTrove(trv.getName(), v10, trv2.getFlavor())
        trv2.computeDigests()
        store.addTroveSetStart([], [], [])
        troveInfo = store.addTrove(trv2, trv2.diff(None)[0])
        store.addTroveDone(troveInfo)
        store.addTroveSetDone()

        # add the troves
        store.addTroveSetStart([], [], [])
        for trv in troves:
            troveInfo = store.addTrove(trv, trv.diff(None)[0])
            store.addTroveDone(troveInfo)
        store.addTroveSetDone()

        for trv in troves:
            self.assertEqual(
                trv,
                store.getTrove(trv.getName(), trv.getVersion(),
                               trv.getFlavor()))

        troveFlavors = store.getTroveFlavors({'test': [v10]})
        self.assertEqual(troveFlavors['test'][v10], [union.freeze()])
Exemplo n.º 4
0
 def testNextVersions(self):
     trv = self.addComponent('foo:source', '1')
     self.addComponent('foo:run', '1')
     self.addCollection('foo', '1', [':run'])
     localVersion = VFS('/local@local:COOK/1.0-1')
     sourceList = [(trv.getVersion(), ['foo'], deps.Flavor()),
                   (localVersion, ['bar'], deps.Flavor())]
     repos = self.openRepository()
     nextVersions = nextversion.nextVersions(repos, self.openDatabase(),
                                             sourceList)
     assert(nextVersions == [VFS('/localhost@rpl:linux/1-1-2'),
                             VFS('/local@local:COOK/1.0-1-1')])
Exemplo n.º 5
0
    def testDistributedRedirect(self):
        store = self._connect()
        cu = store.db.cursor()

        flavor = deps.Flavor()
        localVer1 = ThawVersion("/localhost@test:trunk/10:1.1-10")
        localVer2 = ThawVersion("/localhost@test:trunk/20:1.2-20")
        remoteVer = ThawVersion("/localhost1@test:trunk/10:1.2-10")

        # this places /localhost1@test:trunk into the branch table, but not
        # the labels table
        trv = trove.Trove("group-foo",
                          localVer1,
                          flavor,
                          None,
                          type=trove.TROVE_TYPE_REDIRECT)
        trv.addRedirect("target", remoteVer.branch(), flavor)
        trv.computeDigests()
        store.addTroveSetStart([], [], [])
        ti = store.addTrove(trv, trv.diff(None)[0], hidden=True)
        store.addTroveDone(ti)

        # and this needs the label to exist
        trv = trove.Trove("group-foo", localVer2, flavor, None)
        trv.addTrove("target", remoteVer, flavor)
        trv.computeDigests()
        ti = store.addTrove(trv, trv.diff(None)[0], hidden=True)
        store.addTroveDone(ti)
Exemplo n.º 6
0
def createFlavor(recipeName, *flagIterables, **kw):
    """ create a dependency set consisting of all of the flags in the
        given flagIterables.  Note that is a broad category that includes
        lists, iterators, etc. RecipeName is the recipe which local flags
        should be relative to, can be set to None if there are definitely
        no local flags in the flagIterables.
    """
    targetDep = kw.pop('targetDep', False)
    if targetDep:
        depType = deps.TargetInstructionSetDependency
    else:
        depType = deps.InstructionSetDependency
    majArch = None
    archFlags = {}
    subsumed = {}
    useFlags = []
    set = deps.Flavor()
    for flag in itertools.chain(*flagIterables):
        flagType = type(flag)
        if flagType == MajorArch:
            if not flag._get():
                continue
            set.union(flag._toDependency(depType=depType))
        elif flagType ==  SubArch:
            set.union(flag._toDependency(depType=depType))
        elif flagType == UseFlag:
            set.union(flag._toDependency())
        elif flagType == LocalFlag:
            assert(recipeName)
            set.union(flag._toDependency(recipeName))
        elif flagType == PackageFlag:
            set.union(flag._toDependency(flag._parent._name))
    return set
Exemplo n.º 7
0
 def _toDependency(self, recipeName):
     depFlags =  [('.'.join((recipeName, self._name)),
                                           self._getDepSense())]
     set = deps.Flavor()
     dep = deps.Dependency('use', depFlags)
     set.addDep(deps.UseDependency, dep)
     return set
Exemplo n.º 8
0
 def _toDependency(self):
     set = deps.Flavor()
     sense = self._getDepSense()
     depFlags = [ (self._name, sense) ]
     dep = deps.Dependency('use', depFlags)
     set.addDep(deps.UseDependency, dep)
     return set
Exemplo n.º 9
0
    def getCheckoutLog(self, targetDir, newerOnly=False, versionList=None):
        """
        Returns list of lines of log messages relative to the specified
        targetDirectory.
        @param targetDir: name of directory for which to fetch status.
        @type targetDir: string
        @param newerOnly: (C{False}) whether to return only log messages
        newer than the current contents of the checkout.
        @type newerOnly: bool
        @param versionList: (C{None}) if set, a list of versions for
        which to return log messages.  If C{None}, return all log
        messages.
        @type versionList: list of strings or (opaque) conary version objects
        @return: list of strings
        """
        repos, sourceState = self._getRepositoryStateFromDirectory(targetDir)
        troveName = sourceState.getName()

        if versionList is None:
            if newerOnly:
                versionList = self._getNewerRepositoryVersions(targetDir)
            else:
                versionList = self._getRepositoryVersions(targetDir)
        else:
            versionList = [self._getVersion(x) for x in versionList]

        emptyFlavor = deps.Flavor()
        nvfList = [(troveName, v, emptyFlavor) for v in versionList]
        troves = repos.getTroves(nvfList)

        return [message for message in checkin.iterLogMessages(troves)]
Exemplo n.º 10
0
        def testOne(dir, flagList, emptyPreferred=True):
            files = os.listdir(dir)
            for fileName in files:
                os.unlink(os.path.join(dir, fileName))

            for (flag, sense) in flagList:
                f = open(os.path.join(dir, flag), "w")
                if sense == deps.FLAG_SENSE_PREFERRED:
                    if not emptyPreferred:
                        f.write('sense preferred\n')
                elif sense == deps.FLAG_SENSE_PREFERNOT:
                    f.write('sense prefernot\n')
                elif sense == deps.FLAG_SENSE_DISALLOWED:
                    f.write('sense disallowed\n')
                elif sense == deps.FLAG_SENSE_REQUIRED:
                    f.write('sense required\n')
                else:
                    assert (0)

                f.close()

            use = flavorcfg.FlavorConfig(dir, '')
            cmp = deps.Flavor()
            cmp.addDep(deps.UseDependency, deps.Dependency('use', flagList))
            assert (use.toDependency() == cmp)
Exemplo n.º 11
0
    def testRoleFilters(self):
        db = self._setupDB()
        na = netauth.NetworkAuthorization(db, "conary.rpath.com")
        self._addUserRole(na, "testuser", "testpass")
        roleId = na._getRoleIdByName('testuser')
        geoip = {
                '1.2.3.4': deps.parseFlavor('country.XC'),
                '5.6.7.8': deps.parseFlavor('country.XB'),
                }
        na.geoIp.getFlags = lambda x: geoip[x]

        na.setRoleFilters({'testuser': (
            deps.parseFlavor('!country.XA,!country.XB'), None)})
        self.assertEqual(na.getRoleFilters(['testuser']),
                {'testuser': (
                    deps.parseFlavor('!country.XA,!country.XB'), deps.Flavor())})

        token = AuthToken('testuser', 'testpass', remote_ip='1.2.3.4')
        self.assertEqual(
                na.getAuthRoles(db.cursor(), token), set([roleId]))

        token = AuthToken('testuser', 'testpass', remote_ip='5.6.7.8')
        level = netauth.log.level
        netauth.log.setLevel(100)
        try:
            self.assertRaises(errors.InsufficientPermission,
                    na.getAuthRoles, db.cursor(), token)
        finally:
            netauth.log.setLevel(level)
Exemplo n.º 12
0
def reduce_flavors(package, target_cfg, flavors_in):
    '''
    Reduce the set of flavors to be built for a given trove to specify
    only:
     * The instruction set
     * Package use flags (for this package only)
     * Flavors specified in a "use" config item for the package
    '''

    flavors_out = set()

    if target_cfg and (target_cfg.flavor or target_cfg.flavor_set):
        # An explicit set of flavors was provided. They should be used instead
        # of whatever we were given.
        flavors_out = expand_targets(target_cfg)
    elif target_cfg and target_cfg.flavor_mask != deps.Flavor():
        # A flavor mask was provided. Use this to select which flavors are
        # unique, and build only variations on them.
        flavors_out = set()
        for flavor in flavors_in:
            flavors_out.add(mask_flavor(flavor, target_cfg.flavor_mask))
    elif package.startswith('group-'):
        # With groups it's impossible to guess which flavors are useful; and
        # usually we want them all anyway since groups are where the set of
        # flavors to be built originate.
        flavors_out = flavors_in
    else:
        # No rules were specified. Keep instruction set and package flags
        # for this package only.
        flavors_out = set()
        for flavor in flavors_in:
            flavors_out.add(fragment_flavor(package, flavor))

    return flavors_out
Exemplo n.º 13
0
    def testHidden(self):
        store = self._connect()
        cu = store.db.cursor()

        flavor = deps.Flavor()
        version = ThawVersion("/conary.rpath.com@test:trunk/10:1.2-10")

        f = files.FileFromFilesystem("/etc/passwd", self.id)
        trv = trove.Trove("junk:data", version, flavor, None)
        trv.computeDigests()

        store.addTroveSetStart([], set(['/etc']), set(['passwd']))
        ti = store.addTrove(trv, trv.diff(None)[0], hidden=True)
        store.addTroveDone(ti)
        store.addTroveSetDone()

        assert (cu.execute("select count(*) from latestcache").fetchall()[0][0]
                == 0)
        assert (cu.execute("select isPresent from instances").fetchall()[0][0]
                == instances.INSTANCE_PRESENT_HIDDEN)

        store.presentHiddenTroves()
        assert (cu.execute("select count(*) from latestcache").fetchall()[0][0]
                == 3)
        assert (cu.execute("select isPresent from instances").fetchall()[0][0]
                == instances.INSTANCE_PRESENT_NORMAL)
Exemplo n.º 14
0
    def testCommonFiles(self):
        # this test simulates a trove having the ame file in different
        # path locations with only changed mtimes.
        store = self._connect()
        flavor = deps.Flavor()
        version = ThawVersion("/conary.rpath.com@test:trunk/10:1.2-10")

        baseNames = set(['file'])
        dirNames = set(['/junk1', '/junk2'])

        f = files.FileFromFilesystem("/etc/passwd", self.id)
        trv = trove.Trove("junk:data", version, flavor, None)
        trv.addFile(self.id1, "/junk1/file", version, f.fileId())
        trv.addFile(self.id2, "/junk2/file", version, f.fileId())
        trv.computeDigests()

        store.db.transaction()
        store.addTroveSetStart([], dirNames, baseNames)
        ti = store.addTrove(trv, trv.diff(None)[0])
        f.inode.mtime.set(1)
        ti.addFile(self.id1,
                   "/junk1/file",
                   f.fileId(),
                   version,
                   fileStream=f.freeze())
        f.inode.mtime.set(2)
        ti.addFile(self.id2,
                   "/junk2/file",
                   f.fileId(),
                   version,
                   fileStream=f.freeze())
        store.addTroveDone(ti)
        store.commit()
Exemplo n.º 15
0
    def testNextVersionMultipleBranchesWithDepth2(self):
        self.addCollection('foo=/localhost@rpl:1//2//3/2:1-2-0.1', [':run'])

        repos = self.openRepository()
        sourceList = [(VFS('/localhost@rpl:2//3/1-2'), ['foo'], deps.Flavor())]
        nextVersions = nextversion.nextVersions(repos, self.openDatabase(),
                                                sourceList)
        assert(nextVersions == [VFS('/localhost@rpl:2//3/1-2-0.2')])
Exemplo n.º 16
0
    def testLoadedTrovesWithAutoLoad(self):
        self.logFilter.add()
        repos = self.openRepository()
        if 'x86_64' not in str(self.cfg.buildFlavor):
            raise testhelp.SkipTestException('Skip test on x86 arch')

        self.cfg.autoLoadRecipes.append('other')

        self.overrideBuildFlavor('is: x86 x86_64')

        header = '''
    if Arch.x86: pass
'''
        self.addComponent(
            'other:recipe=2.0[is:x86 x86_64]',
            [('simplesuper.recipe', simpleSuperRecipe.replace('1.0', '2.0'))])
        self.addCollection('other=2.0[is:x86 x86_64]', [':recipe'])
        self.addTestPkg(1, version='1.0', header=header)
        self.addTestPkg(2, header='loadRecipe("test1")')

        use.track()
        rldep = deps.parseFlavor('readline')
        ssldep = deps.parseFlavor('ssl')
        nobsdep = deps.parseFlavor('~!bootstrap')
        emptydep = deps.Flavor()
        x64dep = deps.parseFlavor('is:x86_64')
        v1 = versions.VersionFromString('/localhost@rpl:linux/1.0-1')

        loader = self._testSubload(repos, "loadInstalled('test2')")
        FooLoaded = loader.getLoadedSpecs()
        assertEq = self.assertEqual
        assertEq(FooLoaded['test2'][0], ('test2:source', v1, emptydep))

        Test2Loaded = FooLoaded['test2'][1]
        assertEq(Test2Loaded['test1'][0], ('test1:source', v1, x64dep))

        Test1Loaded = Test2Loaded['test1'][1]
        assertEq(Test1Loaded, {})

        loadedTroves = loader.getLoadedTroves()
        assertEq(len(loadedTroves), 2)
        assertEq(loadedTroves[0], ('test1:source', v1, x64dep))
        assertEq(loadedTroves[1], ('test2:source', v1, emptydep))

        # Now reset and load again w/ overrides specified
        branch = versions.VersionFromString('/localhost@rpl:foo/')
        oldLoadedSpecs = loader.getLoadedSpecs()
        # move ILP and buildLabel over to another branch, and use overrides
        # to load exactly what we want anyway.
        cfg = copy.copy(self.cfg)
        self.overrideBuildFlavor('!readline, !ssl')
        overrides = oldLoadedSpecs
        loader = self._testSubload(repos,
                                   "loadInstalled('test2')",
                                   cfg=cfg,
                                   overrides=overrides)
        assert (loadedTroves[0] == ('test1:source', v1, x64dep))
        assert (loadedTroves[1] == ('test2:source', v1, emptydep))
Exemplo n.º 17
0
 def __init__(self):
     self.flavor = deps.Flavor()
     self.recipeType = None
     self.loadedSpecsList = []
     self.loadedTroves = []
     self.packages = set()
     self.delayedRequirements = set()
     self.buildRequirements = set()
     self.crossRequirements = set()
Exemplo n.º 18
0
    def initializeFlavors(self):
        """
        Initialize flavor preferences based on files typically
        found in /etc/conary/arch (archDirs) and /etc/conary/use

        @raises RuntimeError: Raised if use flags conflict in
        a way which cannot be reconciled
        (see L{deps.DependencyClass.MergeFlags})

        """
        self.flavorConfig = flavorcfg.FlavorConfig(self.useDirs, self.archDirs)
        if self.flavor == []:
            self.flavor = [deps.Flavor()]

        self.flavor = self.flavorConfig.toDependency(override=self.flavor)

        newFlavors = []
        hasIns = False

        # if any flavor has an instruction set, don't merge
        for flavor in self.flavor:
            if deps.DEP_CLASS_IS in flavor.getDepClasses():
                hasIns = True
                break

        if not hasIns:
            # use all the flavors for the main arch first
            for depList in arch.currentArch:
                for flavor in self.flavor:
                    insSet = deps.Flavor()
                    for dep in depList:
                        insSet.addDep(deps.InstructionSetDependency, dep)
                    newFlavor = flavor.copy()
                    newFlavor.union(insSet)
                    newFlavors.append(newFlavor)
            self.flavor = newFlavors

        # buildFlavor is installFlavor + overrides
        self.buildFlavor = deps.overrideFlavor(self.flavor[0],
                                               self.buildFlavor)
        if self.isDefault('flavorPreferences'):
            self.flavorPreferences = arch.getFlavorPreferencesFromFlavor(
                self.flavor[0])
        self.flavorConfig.populateBuildFlags()
Exemplo n.º 19
0
 def testNextVersionLatestDevelOnThisBranch(self):
     # depth 3
     self.addCollection('foo=/localhost@rpl:1//2//3/1:1-2-0.0.1', [':run'])
     # depth 2 and latest
     self.addCollection('foo=/localhost@rpl:1//3/2:1-2-0.1[is:x86]', 
                        [':run'])
     sourceList = [(VFS('/localhost@rpl:1//3/1-2'), ['foo'], deps.Flavor())]
     nextVersions = nextversion.nextVersions(self.openRepository(),
                                             self.openDatabase(), sourceList)
     assert(nextVersions == [VFS('/localhost@rpl:1//3/1-2-0.1')])
Exemplo n.º 20
0
 def _getFlags(self, authToken):
     flags = deps.Flavor()
     for addr in authToken.getAllIps():
         if not addr:
             continue
         try:
             flags.union(self.geoIp.getFlags(addr))
         except:
             continue
     return flags
Exemplo n.º 21
0
 def testGetProductStoreByLabel(self):
     from rbuild_plugins import init
     co = init.Init('init', None, None)
     co.setHandle(mock.MockObject())
     returnTuple = ('product-definition:source', 
                    VFS('/foo.rpath.org@rpl:proddef-1/1.0-1'), deps.Flavor())
     co.handle.facade.conary._findTrove._mock.setReturn(returnTuple,
                 'product-definition:source',
                 'foo.rpath.org@rpl:proddef-1')
     assert(co.getProductVersionByLabel('foo.rpath.org@rpl:proddef-1') 
             == '/foo.rpath.org@rpl:proddef-1/1.0-1')
Exemplo n.º 22
0
def getCrossCompileSettings(flavor):
    flavorTargetSet = flavor.getDepClasses().get(deps.DEP_CLASS_TARGET_IS,
                                                 None)
    if flavorTargetSet is None:
        return None

    targetFlavor = deps.Flavor()
    for insSet in flavorTargetSet.getDeps():
        targetFlavor.addDep(deps.InstructionSetDependency, insSet)
    isCrossTool = flavor.stronglySatisfies(crossFlavor)
    return None, targetFlavor, isCrossTool
Exemplo n.º 23
0
def getBuiltFlavor(flavor):
    if not hasTarget(flavor):
        majorArch = getTargetArch(flavor)[1]
        if majorArch:
            f = deps.Flavor()
            f.addDep(deps.InstructionSetDependency, deps.Dependency(majorArch))
            flavor = deps.overrideFlavor(flavor, f)
        return flavor
    if flavor.stronglySatisfies(crossFlavor):
        return flavor
    return setISFromTargetFlavor(flavor)
Exemplo n.º 24
0
    def testNextVersionMultipleBranchesWithDepth(self):
        # this has depth 3, but the trove we're building has depth 2.
        # so we can't consider it the "latest" and just increment its source
        # count.
        self.addCollection('foo=/localhost@rpl:1//2//3/2:1-2-0.0.1', [':run'])

        repos = self.openRepository()
        sourceList = [(VFS('/localhost@rpl:2//3/1-2'), ['foo'], deps.Flavor())]
        nextVersions = nextversion.nextVersions(repos, self.openDatabase(),
                                                sourceList)
        assert(nextVersions == [VFS('/localhost@rpl:2//3/1-2-0.1')])
Exemplo n.º 25
0
    def getId(self, flavorId):
        if flavorId == 0:
            return deps.Flavor()

        cu = self.db.cursor()
        cu.execute("SELECT flavor FROM Flavors WHERE flavorId = ?",
                   flavorId)
        try:
            return deps.ThawFlavor(cu.next()[0])
        except StopIteration:
            raise KeyError, flavorId
Exemplo n.º 26
0
 def createSourceTrove(self,
                       name,
                       label,
                       upstreamVersion,
                       pathDict,
                       changeLog,
                       factory=None,
                       pkgCreatorData=None,
                       metadata=None):
     """
         Create a source trove.
         @param name: trove name of source components.
         @type name: str
         @param label: trove label
         @type label: str
         @param upstreamVersion: upstream version of source component
         @type upstreamVersion: str
         @param pathDict: Dictionary mapping path strings to
         conaryclient.filetypes._File objects, which represent the contents
         of each file
         @type pathDict: dict(str: conaryclient.filetypes._File)
         @param changeLog: Change log associated with this source trove.
         @type changeLog: changelog.ChangeLog
         @param factory: designate a factory associated with this source
         trove.
         @type factory: str
         @param pkgCreatorData: arbitrary string set in
         _TROVEINFO_TAG_PKGCREATORDATA
         @type pkgCreatorData: str
         @param metadata: additional metadata to be attached to the source
         trove
         @type metadata: dict
     """
     if not name.endswith(':source'):
         raise RuntimeError('Only source components allowed')
     versionStr = '/%s/%s-1' % (label, upstreamVersion)
     version = versions.VersionFromString(versionStr).copy()
     version.resetTimeStamps()
     troveObj = trove.Trove(name,
                            version,
                            deps.Flavor(),
                            changeLog=changeLog)
     troveObj.setFactory(factory)
     if pkgCreatorData:
         troveObj.troveInfo.pkgCreatorData.set(pkgCreatorData)
     if metadata:
         mi = trove.MetadataItem()
         for k, v in metadata.iteritems():
             mi.keyValue[k] = v
         troveObj.troveInfo.metadata.addItem(mi)
     return self._createTroves([(troveObj, pathDict)])
Exemplo n.º 27
0
def getAlternateFlavorMessage(query):
    """
        Returns a message that describes any available alternate flavors
        that could be passed in to return a query result.
    """

    minimalMatches = []
    archMinimalMatches = []
    archPartialMatches = []
    for searchQueue, alternateList in query.iterAlternatesByQueue():
        if not alternateList:
            continue

        flavors = set([x[2] for x in itertools.chain(*searchQueue)])
        for flavor in flavors:
            if flavor is None:
                flavor = deps.Flavor()
            ISD = deps.InstructionSetDependency
            archNames = set(x.name for x in flavor.iterDepsByClass(ISD))
            for toMatchFlavor in alternateList:
                minimalMatch = deps.getMinimalCompatibleChanges(flavor,
                                                                toMatchFlavor,
                                                                keepArch=True)
                minimalMatches.append(minimalMatch)
                matchArchNames = set(
                    x.name for x in toMatchFlavor.iterDepsByClass(ISD))
                if not matchArchNames - archNames:
                    # if we don't have to change architectures to match
                    # this flavor, that's much better than the alternative.
                    archMinimalMatches.append(minimalMatch)
                if matchArchNames & archNames:
                    archPartialMatches.append(minimalMatch)
    if archMinimalMatches:
        minimalMatches = archMinimalMatches
    elif archPartialMatches:
        minimalMatches = archPartialMatches
    if minimalMatches:
        minimalMatches = set(minimalMatches)
        matchesByLength = sorted(
            ((_getFlavorLength(x), x) for x in minimalMatches),
            key=lambda x: x[0])
        shortestMatchLength = matchesByLength[0][0]
        # only return the flavors that require the least amount of change
        # to our current query.
        minimalMatches = [
            x[1] for x in matchesByLength if x[0] == shortestMatchLength
        ]
        flavorStrs = '], ['.join([str(x) for x in sorted(minimalMatches)])
        return ' (Closest alternate flavors found: [%s])' % flavorStrs
    return ''
Exemplo n.º 28
0
    def testBreakOnUpdate(self):
        # create a package which provides a file, then update that package to 
        # a version which does not provide that library while installing a 
        # package which requires that file. it should cause a dep failure.
        self.resetRepository()
        self.resetRoot()

        (built, d) = self.buildRecipe(recipes.bashRecipe, "Bash")
        bashVersion = built[0][1]
        (built, d) = self.buildRecipe(recipes.bashMissingRecipe, "Bash")
        noBashVersion = built[0][1]

        (built, d) = self.buildRecipe(recipes.bashUserRecipe, "BashUser")
        userVersion = built[0][1]

        repos = self.openRepository()
        # this changeset updates bash to a trove which removed /bin/bash
        # and installs bashuser, which requies /bin/bash
        cs = repos.createChangeSet([("bash", 
                                     (VersionFromString(bashVersion), deps.parseFlavor('ssl')), 
                                     (VersionFromString(noBashVersion), deps.parseFlavor('ssl')), 
                                    0),
                                    ("bashuser", (None, None),
                                     (VersionFromString(userVersion), 
                                      deps.Flavor()), 
                                    0)
                                  ])

        (fd, fileName) = tempfile.mkstemp()
        os.close(fd)
        cs.writeToFile(fileName)

        try:
            self.updatePkg(self.rootDir, 'bash', version = bashVersion)
            (rc, s) = self.captureOutput(self.updatePkg, self.rootDir, fileName)
        finally:
            os.unlink(fileName)
        expectedStr = """\
The following dependencies would not be met after this update:

  bashuser:runtime=0-1-1 (Would be newly installed) requires:
    file: /bin/bash
  which is provided by:
    bash:runtime=0-1-1 (Would be updated to 1-1-1)
"""
        assert(s == expectedStr)

        # since /bin/bash is still installed, this should work fine
        self.updatePkg(self.rootDir, 'bashuser', version = bashVersion)
Exemplo n.º 29
0
class CfgFlavor(CfgType):

    default = deps.Flavor()

    def copy(self, val):
        return val.copy()

    def parseString(self, val):
        try:
            f = deps.parseFlavor(val)
        except Exception, e:
            raise ParseError, e
        if f is None:
            raise ParseError, 'Invalid flavor %s' % val
        return f
Exemplo n.º 30
0
    def _addUnownedNewFiles(self, newFileList):
        if not newFileList: return

        cs = changeset.ChangeSet()
        ver = versions.VersionFromString(
            '/localhost@local:LOCAL/1.0-1-1').copy()
        ver.resetTimeStamps()
        trv = trove.Trove("@new:files", ver, deps.Flavor())
        for path in newFileList:
            self._addFile(cs, trv, path)

        trvDiff = trv.diff(None, absolute=False)[0]
        cs.newTrove(trvDiff)

        self._handleChangeSet([trv.getNameVersionFlavor()], cs)