Beispiel #1
0
def test(methodname, input, output, *args):
    global tested_methods
    tested_methods[methodname] = 1
    if verbose:
        print '%r.%s(%s)' % (input, methodname, ", ".join(map(repr, args))),
    u = UserString(input)
    objects = [input, u, UserString(u)]
    res = [""] * 3
    for i in range(3):
        object = objects[i]
        try:
            f = getattr(object, methodname)
        except AttributeError:
            f = None
            res[i] = AttributeError
        else:
            try:
                res[i] = apply(f, args)
            except:
                res[i] = sys.exc_type
    if res[0] == res[1] == res[2] == output:
        if verbose:
            print 'yes'
    else:
        if verbose:
            print 'no'
        print (methodname, input, output, args, res[0], res[1], res[2])
Beispiel #2
0
  def __init__ (self, dep):
    if type (dep) == types.InstanceType:
      url = dep.url
    else:
      url = dep

    # This is better, but doesn't work for classic classes:
    #    super (Depot, self).__init__ (dep)
    # So, we're forced to hardcode the superclass for now:
    UserString.__init__ (self, url)
    
    self.archive = 0			# if depot is a zip archive

    self.url = url			# parent url
    self.pkg_url = url			# where to find packages
    self.type = urlparse (url).scheme   # URL scheme ('http', ...)
    self.local_path = None

    self.proxy = ProxyAuth ()
    self.auth = ProtocolAuth ()

    self.dist = None			# distribution name
    self.packages = []			# packages contained in depot

    self.indent_progressmeter = 4
    self.verify_checksum = False
Beispiel #3
0
def test(methodname, input, *args):
    global tested_methods
    tested_methods[methodname] = 1
    if verbose:
        print '%s.%s(%s) ' % (input, methodname, args),
    u = UserString(input)
    objects = [input, u, UserString(u)]
    res = [""] * 3
    for i in range(3):
        object = objects[i]
        try:
            f = getattr(object, methodname)
            res[i] = apply(f, args)
        except:
            res[i] = sys.exc_type
    if res[0] != res[1]:
        if verbose:
            print 'no'
        print `input`, f, `res[0]`, "<>", `res[1]`
    else:
        if verbose:
            print 'yes'
    if res[1] != res[2]:
        if verbose:
            print 'no'
        print `input`, f, `res[1]`, "<>", `res[2]`
    else:
        if verbose:
            print 'yes'
Beispiel #4
0
 def __init__(self, data='', f=None, pos=0, line=0, col=0):
   UserString.__init__(self, data)
   self.f = f
   self.pos = pos
   self.line = line
   self.col = col
   return
Beispiel #5
0
 def __init__(self, data='', f=None, pos=0, line=0, col=0):
     UserString.__init__(self, data)
     self.f = f
     self.pos = pos
     self.line = line
     self.col = col
     return
 def __init__(self, data=''):
     if data:
         UserString.__init__(self, data)
         return
     salt = ''.join([
         random.choice(string.ascii_letters + string.digits)
         for i in range(50)])
     UserString.__init__(self, salt)
Beispiel #7
0
 def __init__(self, data=''):
     if data:
         UserString.__init__(self, data)
         return
     salt = ''.join([
         random.choice(string.ascii_letters + string.digits)
         for i in range(50)])
     UserString.__init__(self, salt)
Beispiel #8
0
 def __init__(self, docstring=DEFAULTS['docstring'],
                    options=DEFAULTS['options'],
                    default=DEFAULTS['default'],
                    optional=DEFAULTS['optional'],
                    values=DEFAULTS['values'],
                    category=DEFAULTS['category'],
                    callback=DEFAULTS['callback'],
                    synopsis=DEFAULTS['synopsis'],
                    environ=DEFAULTS['environ'],
                    registry=DEFAULTS['registry'],
                    mandatory=None,
                    name=DEFAULTS['name'],
                    source=DEFAULTS['source']):
    UserString.__init__(self, '')
    GenericOption.initialize(self, locals())
Beispiel #9
0
 def __init__(self, docstring=DEFAULTS['docstring'],
                    options=DEFAULTS['options'],
                    default=DEFAULTS['default'],
                    optional=DEFAULTS['optional'],
                    values=DEFAULTS['values'],
                    category=DEFAULTS['category'],
                    callback=DEFAULTS['callback'],
                    synopsis=DEFAULTS['synopsis'],
                    environ=DEFAULTS['environ'],
                    registry=DEFAULTS['registry'],
                    mandatory=None,
                    name=DEFAULTS['name'],
                    source=DEFAULTS['source']):
    UserString.__init__(self, '')
    GenericOption.initialize(self, locals())
 def test_iadd(self):
     s = self.type2test("foo")
     s += "bar"
     self.assertEqual(s, "foobar")
     s += UserString("baz")
     self.assertEqual(s, "foobarbaz")
     s += 42
     self.assertEqual(s, "foobarbaz42")
 def test_setslice(self):
     s = self.type2test("foo")
     s[:] = "bar"
     self.assertEqual(s, "bar")
     s[1:2] = "foo"
     self.assertEqual(s, "bfoor")
     s[1:-1] = UserString("a")
     self.assertEqual(s, "bar")
     s[0:10] = 42
     self.assertEqual(s, "42")
Beispiel #12
0
    def __init__(self, seq=""):
        UserString.__init__(self, seq.decode("utf-8"))
        #self.spaces = spaces
        self.length = len(self)
        self.wordSet = []
        #if self.length<2:return
        #self.makeParagText()
        #print  "<br>$$$",self.data

        # the text-dictionary giving for a position (0.12309...) the corresponding paragraph:
        self.parFracText = self._getParFracText()
        self.parPos = sorted(self.parFracText.iterkeys())
        #print self.parPos

        #for k in self.parPos:
        #print "<br>***",k,": ",self.parFracText[k],"<br>"
        #print ")))))))))))))))))))init LIngtext fini<br><br><br>"

        self.makeWordSet()
Beispiel #13
0
 def test_string_likes(self):
     for thing in ['', 'a', u'\xe4', UserString('us'), MutableString('ms')]:
         assert_equals(is_str_like(thing), True, thing)
Beispiel #14
0
    def __init__(self, data, rawsource=""):
        UserString.__init__(self, data)

        self.rawsource = rawsource
        """The raw text from which this element was constructed."""
Beispiel #15
0
 def __init__(self, cmd, literal=None):
     UserString.__init__(self, cmd)
     self.literal = literal
Beispiel #16
0
    def __init__(self, data, rawsource=''):
        UserString.__init__(self, data)

        self.rawsource = rawsource
        """The raw text from which this element was constructed."""
Beispiel #17
0
 def __init__(self, cmd, literal=None):
     UserString.__init__(self, cmd)
     self.literal = literal
Beispiel #18
0
 def __init__(self, seq):
     UserString.__init__(self,seq)
Beispiel #19
0
 def __init__(self):
     UserString.__init__(self, '')
Beispiel #20
0
     ('', ),
     {},
 ),
 (
     "List",
     ([], ),
     {},
 ),
 (
     "Dict",
     ({}, ),
     {},
 ),
 (
     "UserString",
     (UserString(''), ),
     {},
 ),
 (
     "UserList",
     (UserList([]), ),
     {},
 ),
 (
     "UserDict",
     (UserDict({}), ),
     {},
 ),
 (
     "Object",
     (A(), ),
Beispiel #21
0
    def __repr__(self): return UserString.__str__(self)
# ==============================================================================
# Stores a comment at the end of a line
class Comment(BasicNonStatement):
Beispiel #22
0
class SliceInfo(object):
    '''Represents a single slice on a partition or slice.'''
    MAX_SLICES = 8
    MAX_VTOC = DiskSpace("2tb")

    BACKUP_SLICE = 2
    x86_BOOT_SLICE = 8
    x86_ALT_SLICE = 9
    UNUSED = (None, None)
    UNUSED_TEXT = "Unused"
    DEFAULT_POOL = UserString("")
    ZPOOL = tgt.Slice.AZPOOL
    ZPOOL_TYPES = [
        tgt.Slice.AZPOOL, tgt.Slice.EZPOOL, tgt.Slice.SZPOOL, tgt.Slice.CZPOOL
    ]
    ROOT_POOL = (ZPOOL, DEFAULT_POOL)
    LEGACY = "legacy"
    UFS = tgt.Slice.FS
    UFS_TEXT = "UFS"
    UNKNOWN = "???"

    TYPES = [UNUSED, ROOT_POOL]

    def __init__(self,
                 slice_num=0,
                 size=None,
                 offset=None,
                 blocksz=512,
                 slice_type=None,
                 readonly=False,
                 unmountable=True,
                 tag=None,
                 tgt_slice=None):
        '''Constructor takes either a tgt_slice, which should be a tgt.Slice
        object, or a set of parameters. If tgt_slice is supplied, all other
        parameters are ignored.
        
        '''
        self._tgt_slice = tgt_slice
        self._size = None
        self._offset = None
        self.previous_size = None
        if tgt_slice:
            size = str(tgt_slice.blocks * tgt_slice.geometry.blocksz) + "b"
            self.size = size
            offset = str(tgt_slice.offset * tgt_slice.geometry.blocksz) + "b"
            self.blocksz = tgt_slice.geometry.blocksz
            self.offset = offset
            self.number = tgt_slice.number
            self.readonly = tgt_slice.readonly
            self.type = (tgt_slice.type, tgt_slice.user)
            self.last_mount = tgt_slice.last_mount
            self.unmountable = tgt_slice.unmountable
            self.tag = tgt_slice.tag
        else:
            self.readonly = readonly
            if slice_type is None:
                slice_type = SliceInfo.UNUSED
            if len(slice_type) != 2:
                raise TypeError("slice_type must be tuple of length 2")
            self.type = slice_type
            self.unmountable = unmountable
            self.size = size
            self.blocksz = blocksz
            self.offset = offset
            self.number = slice_num
            self.last_mount = None
            self.tag = tag
        self.original_type = self.type

    def __str__(self):
        result = ["Slice Info (%s):" % self.number]
        result.append("Type: %s:%s" % self.type)
        result.append("Offset: %s" % self.offset)
        result.append("Size: %s" % self.size)
        return "\n".join(result)

    @staticmethod
    def compare(left, right):
        '''Returns an integer such that this method can be passed to
        list.sort() and the list will be sorted in disk layout order.
        
        The backup slice is always listed last
        
        '''
        if isinstance(left, tgt.Slice):
            left = SliceInfo(left)
        if not isinstance(left, SliceInfo):
            return NotImplemented

        if isinstance(right, tgt.Slice):
            right = SliceInfo(right)
        if not isinstance(right, SliceInfo):
            return NotImplemented

        if left.number == SliceInfo.BACKUP_SLICE:
            return 1
        elif right.number == SliceInfo.BACKUP_SLICE:
            return -1

        left_off = left.offset.size_as("b")
        right_off = right.offset.size_as("b")
        if left_off < right_off:
            return -1
        elif left_off > right_off:
            return 1
        else:
            return 0

    def get_offset(self):
        '''Return this slice's offset as a DiskSpace object'''
        return self._offset

    def set_offset(self, offset):
        '''Set this slice's offset. Must be either a DiskSpace object
        or a string that will be accepted by DiskSpace.__init__
        
        '''
        if isinstance(offset, DiskSpace):
            self._offset = deepcopy(offset)
        else:
            self._offset = DiskSpace(offset)

    def get_size(self):
        '''Returns this slice's size as a DiskSpace object'''
        return self._size

    def set_size(self, size):
        '''Set this slice's size. size must be either a DiskSpace or a
        string that will be accepted by DiskSpace.__init__
        
        '''
        if isinstance(size, DiskSpace):
            self._size = deepcopy(size)
        else:
            self._size = DiskSpace(size)

    def get_type(self):
        '''Returns this SliceInfo's 'type'
        Here for interface compatibility with PartitionInfo.get_type()'''
        return self.type

    def get_blocks(self):
        '''Return the number of blocks on this slice'''
        return int(self.size.size_as("b") / self.blocksz)

    size = property(get_size, set_size)
    offset = property(get_offset, set_offset)

    def get_description(self):
        '''Return a string suitable for representing this slice in a UI'''
        description = None
        if self.number == SliceInfo.BACKUP_SLICE:
            description = tgt.Slice.BACKUP
        elif self.type == SliceInfo.UNUSED:
            description = SliceInfo.UNUSED_TEXT
        elif self.type[0] == SliceInfo.UFS:
            if self.last_mount:
                description = self.last_mount
            else:
                description = SliceInfo.UFS_TEXT
        elif self.type[0] == tgt.Slice.UNKNOWN:
            if self.tag == tgt.Slice.UNKNOWN:
                description = SliceInfo.UNKNOWN
            else:
                description = self.tag
        elif self.type[1] and self.type[1] != tgt.Slice.UNKNOWN:
            description = self.type[1]
        else:
            description = self.type[0]
        return str(description)

    def cycle_type(self, parent, extra_types=None):
        '''Cycle this partition's type. If extra_types is given, it should
        be a list of additional types - these will be considered when cycling
        to the next type
        
        '''
        if extra_types is None:
            extra_types = []
        if self.number == SliceInfo.BACKUP_SLICE:
            return

        has_solaris_data = (parent.get_solaris_data() is not None)
        types = set()
        types.update(SliceInfo.TYPES)
        types.update(extra_types)
        types = list(types)
        types.sort()
        if self.type in types:
            logging.debug("type in types, cycling next")
            type_index = types.index(self.type)
            type_index = (type_index + 1) % len(types)
            self.type = types[type_index]
            logging.debug("now %s-%s", *self.type)
        else:
            logging.debug("type NOT in types, setting to types[0]")
            self.original_type = self.type
            self.type = types[0]
        if self.type == SliceInfo.UNUSED:
            self.previous_size = self.size
            self.size = "0GB"
        elif self.is_rpool():
            if has_solaris_data:
                self.cycle_type(parent, extra_types)

    def get_endblock(self):
        '''Returns the ending 'offset' of this slice, as a DiskSpace'''
        try:
            start_pt = self.offset.size_as("b")
            end_pt = self.size.size_as("b")
            return DiskSpace(str(start_pt + end_pt) + "b")
        except AttributeError:
            raise AttributeError("%s does not have valid size data" %
                                 self.__class__.__name__)

    def get_max_size(self, parent):
        '''Return the maximum possible size this slice could consume,
        in gigabytes, based on adjacent unused space
        
        '''
        if self.number == SliceInfo.BACKUP_SLICE:
            return self.size.size_as("gb")
        msg_str = "get_max_size:%s:" % self.number
        slices = parent.slices
        if self not in slices:
            raise ValueError("This slice not in the parent!")
        self_idx = slices.index(self)
        prev_slice = None
        next_slice = None

        # Search for the slice prior to this one with the largest "endblock"
        # Since existing slices may overlap, this could be any slice prior
        # to the current one.
        for slice_info in reversed(slices[:self_idx]):
            if (slice_info.type != SliceInfo.UNUSED
                    and slice_info.number != SliceInfo.BACKUP_SLICE):
                if (prev_slice is None or
                        slice_info.get_endblock() > prev_slice.get_endblock()):
                    prev_slice = slice_info
        for slice_info in slices[self_idx + 1:]:
            if (slice_info.type != SliceInfo.UNUSED
                    and slice_info.number != SliceInfo.BACKUP_SLICE):
                next_slice = slice_info
                break
        if prev_slice is None:
            msg_str += "prev_part=None:start_pt=0:"
            start_pt = 0
        else:
            msg_str += "prev_part=%s:" % prev_slice.number
            start_pt = prev_slice.get_endblock().size_as("gb")
            msg_str += "start_pt=" + str(start_pt) + ":"

        if next_slice is None:
            msg_str += "next_part=None:end_pt="
            for slice_info in reversed(slices):
                # Use the backup slice to define the absolute max size
                # any given slice can be. (This is usually the last slice,
                # hence the use of a reversed iterator)
                if slice_info.number == SliceInfo.BACKUP_SLICE:
                    end_pt = slice_info.size.size_as("gb")
                    break
            else:
                # Default to the parent's size if there happens to be no S2
                end_pt = parent.size.size_as("gb")
            msg_str += str(end_pt) + ":"
        else:
            msg_str += "next_part=%s:" % next_slice.number
            end_pt = next_slice.offset.size_as("gb")
            msg_str += "end_pt=%s:" % end_pt
        max_space = end_pt - start_pt
        if max_space < 0:
            max_space = 0
        msg_str += "max_size=%s" % max_space
        logging.debug(msg_str)
        return max_space

    def editable(self, dummy):
        '''Returns True if the installer is capable of resizing this Slice'''
        return self.is_rpool()

    def adjust_offset(self, parent):
        '''Adjust this slice's offset such that it no longer overlaps
        with prior or subsequent slices, by comparing this slice's 
        offset with prior slices, and its endblock with subsequent ones.
        
        Additionally, any unused slices found are shifted to align
        with this slice's trailing edge, if needed.
        
        This function should only be called after ensuring that this slice's
        size is less than or equal its max_size (as given by get_max_size);
        the behavior of this function when attempting to adjust in both
        directions is undefined. Additionally, the slices on the parent
        should already be sorted in disk order.
        
        '''
        if self.number == SliceInfo.BACKUP_SLICE:
            return
        parts = parent.get_parts()
        self_idx = parts.index(self)
        endblock = self.get_endblock()
        endblock_bytes = endblock.size_as("gb")
        unused_parts = []

        pre_shift = 0
        for part in parts[:self_idx]:
            if (part.type == SliceInfo.UNUSED
                    or part.number == SliceInfo.BACKUP_SLICE):
                continue
            overlap = (part.get_endblock().size_as("gb") -
                       self.offset.size_as("gb"))
            pre_shift = max(pre_shift, overlap)

        if pre_shift > 0:
            new_offset = self.offset.size_as("gb") + pre_shift
            self.offset = str(new_offset) + "gb"

        post_shift = None
        for part in parts[self_idx + 1:]:
            if part.offset.size_as("gb") < endblock_bytes:
                if part.type == SliceInfo.UNUSED:
                    unused_parts.append(part)
                elif part.number != SliceInfo.BACKUP_SLICE:
                    post_shift = endblock_bytes - part.offset.size_as("gb")
                    break
            else:
                break
        else:
            # Check to ensure we don't slip past the end of the disk/partition
            max_endblock = parent.size.size_as("gb")
            if endblock_bytes > max_endblock:
                post_shift = endblock_bytes - max_endblock

        if post_shift is not None:
            new_offset = max(0, self.offset.size_as("gb") - post_shift)
            self.offset = str(new_offset) + "gb"
        new_endblock = self.get_endblock()
        for part in unused_parts:
            part.offset = new_endblock

    def to_tgt(self, parent):
        '''Transfer the install profile information to tgt format'''
        # Create tgt.Slice object

        if self.get_type() == SliceInfo.UNUSED:
            return None

        if not self.modified():
            return self._tgt_slice

        # Don't need to include the 'backup' slice, libti will
        # automatically create one appropriately
        if self.number == SliceInfo.BACKUP_SLICE:
            return None

        # Something changed, need to create a new one
        geo = tgt.Geometry(parent.cylsz, self.blocksz)

        # offset must be a multiple of tgt.Geometry.cylsz
        off = int(self.offset.size_as("b") / self.blocksz)
        offset = round_to_multiple(off, geo.cylsz)

        blocks = round_to_multiple(self.get_blocks(), geo.cylsz)

        tag = tgt.Slice.UNASSIGNED
        slice_type = self.type[0]
        user = self.type[1]
        sl = tgt.Slice(geo,
                       self.number,
                       tag,
                       slice_type,
                       offset,
                       blocks,
                       modified=True,
                       user=str(user),
                       unmountable=self.unmountable,
                       readonly=self.readonly)
        return (sl)

    def modified(self, off_by=UI_PRECISION):
        '''Returns False if and only if this SliceInfo was instantiated from
        a tgt.Slice, and this SliceInfo does not differ in substance
        from the tgt.Slice from which it was instantiated.
        
        Size, offset, type and number are compared to determine
        whether this slice has been modified.
        
        off_by - A string or DiskSpace indicating a rounding factor. Any size
        data (offset, size) that differs by less than the given amount is
        assumed to be unchanged. e.g., if the tgt.Slice indicates a size
        of 10.05GB and this SliceInfo has a size of 10.1GB, and off_by
        is the default of 0.1GB, then it is assumed that the represented
        slice has not changed. (The original tgt.Slice size should be
        used, for accuracy)
        
        '''
        if self._tgt_slice is None:
            return True

        if not isinstance(off_by, DiskSpace):
            off_by = DiskSpace(off_by)
        off_by_bytes = off_by.size_as("b")

        if self.number != self._tgt_slice.number:
            return True

        if self.type[0] != self._tgt_slice.type:
            return True

        if self.type[1] != self._tgt_slice.user:
            return True

        tgt_size = self._tgt_slice.blocks * self._tgt_slice.geometry.blocksz
        if abs(tgt_size - self.size.size_as("b")) > off_by_bytes:
            return True

        tgt_offset = self._tgt_slice.offset * self._tgt_slice.geometry.blocksz
        if abs(tgt_offset - self.offset.size_as("b")) > off_by_bytes:
            return True

        return False

    def destroyed(self, off_by=UI_PRECISION):
        '''Returns True if this slice previously had data, and has also
        been modified.
        
        '''
        if self.is_rpool():
            return True
        return (self._tgt_slice is not None and self.modified(off_by))

    def is_rpool(self):
        '''Returns True this slice is the default pool
        
        '''
        return (self.type[0] in SliceInfo.ZPOOL_TYPES
                and self.type[1] == SliceInfo.DEFAULT_POOL)

    def is_solaris_data(self):
        return self.is_rpool()
Beispiel #23
0
#!/usr/bin/env python
Beispiel #24
0
 def __init__(self, seq):
     UserString.__init__(self, seq)
Beispiel #25
0
 def test_strings_are_not_list_like(self):
     for thing in ['str', u'unicode', UserString('user')]:
         assert_equal(is_list_like(thing), False, thing)
Beispiel #26
0
 def __init__(self, sComment, loc):
     BasicStatement.__init__(self, None, loc)
     UserString.__init__(self, sComment)