Completed
Pull Request — master (#260)
by Kirill
01:25
created

char_to_version()   A

Complexity

Conditions 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
1
# -*- coding: utf-8 -*-
2
# Generated by Django 1.9.6 on 2017-03-17 08:04
3
from __future__ import unicode_literals
4
5
from django.db import migrations
6
from django.db.models import F
7
8
def convert_version_string_to_int(string, number_bits):
9
    """
10
    Take in a verison string e.g. '3.0.1'
11
    Store it as a converted int: 3*(2**number_bits[0])+0*(2**number_bits[1])+1*(2**number_bits[2])
12
13
    >>> convert_version_string_to_int('3.0.1',[8,8,16])
14
    50331649
15
    """
16
    numbers = [int(number_string) for number_string in string.split(".")]
17
18
    if len(numbers) > len(number_bits):
19
        raise NotImplementedError(
20
            "Versions with more than {0} decimal places are not supported".format(
21
                len(number_bits) - 1))
22
23
    # add 0s for missing numbers
24
    numbers.extend([0] * (len(number_bits) - len(numbers)))
25
26
    #convert to single int and return
27
    number = 0
28
    total_bits = 0
29
    for num, bits in reversed(list(zip(numbers, number_bits))):
30
        max_num = (bits + 1) - 1
31
        if num >= 1 << max_num:
32
            raise ValueError(
33
                "Number {0} cannot be stored with only {1} bits. Max is {2}".format(num, bits,
34
                                                                                    max_num))
35
        number += num << total_bits
36
        total_bits += bits
37
38
    return number
39
40
def char_to_version(apps, schema_editor):
41
    SparkleVersion = apps.get_model("sparkle", "SparkleVersion")
42
    versions = SparkleVersion.objects.iterator()
43
    for version in versions:
44
        version._version = convert_version_string_to_int(version.version, [16, 16])
45
        if version.short_version:
46
            version._short_version = convert_version_string_to_int(version.short_version, [8, 8, 16, 16])
47
        version.save()
48
49
50
51
52
class Migration(migrations.Migration):
53
54
    dependencies = [
55
        ('sparkle', '0010_auto_20170317_0804'),
56
    ]
57
58
    operations = [
59
        migrations.RunPython(
60
            char_to_version,
61
            reverse_code=migrations.RunPython.noop
62
        ),
63
    ]
64