dcantrell / pyparted

Python bindings for GNU parted (libparted)
GNU General Public License v2.0
85 stars 42 forks source link

Convert Device.type -> str #79

Closed bergentroll closed 2 years ago

bergentroll commented 3 years ago

Is there a function to convert int Device type to str representation (like 'IDE' and 'SATA')? I only found a possibility to compare a value with parted.DEVICE_*.

dcantrell commented 3 years ago

No, there isn't. Mostly because there is no mapping like that in libparted, but I am not opposed to adding it as a convenience function in the Python module. I would just need a list of device ID to strings that you would want to see.

dcantrell commented 3 years ago

Do you have a list of device types to descriptive strings you would like to see?

bergentroll commented 3 years ago

I hoped it is easy because there is already DEVICE_* constants defined in _pedmodule.c. But It is not crucial enough to have one more mapping as for me.

bergentroll commented 2 years ago

I decided to use this dynamic way:

def _get_ped_const_mapping(prefix):
    """ Get names mapping for C-style parted constants
    """

    flags = [i for i in dir(parted._ped) if i.startswith(prefix)]

    result = {}

    for name in flags:
        value = getattr(parted, name)

        if type(value) is not int:
            print(f'Expected _ped.{name} to be int, but got {type(value).__name__}')

        result[value] = name[len(prefix):]

    return result

DEVICE_TYPE_DICT = _get_ped_const_mapping('DEVICE_')

It gives following for DEVICE_

{0: 'UNKNOWN',
 1: 'SCSI',
 2: 'IDE',
 3: 'DAC960',
 4: 'CPQARRAY',
 5: 'FILE',
 6: 'ATARAID',
 7: 'I2O',
 8: 'UBD',
 9: 'DASD',
 10: 'VIODASD',
 11: 'SX8',
 12: 'DM',
 13: 'XVD',
 14: 'SDMMC',
 15: 'VIRTBLK'}

Flags may overrides for other than DEVICE_ prefixes therefore, e. g. for PARTITION_ flags and types.

dcantrell commented 2 years ago

Alright, added dicts for units, devices, and partitions. I just manually constructed everything since I have to manually maintain the imports anyway. All strings are lowercase. Send PRs if you find issues.