aboutsummaryrefslogtreecommitdiff
blob: 0868b93d65230391a9c530a2bc2afebaa63c5a09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# -*- coding: utf-8 -*-

"""
    fetch.py
    ~~~~~~~~
    
    This module implements a Python class responsible to fetch and update
    the package database and the auxiliary files.
    
    Used only by the live version of g-octave.
    
    :copyright: (c) 2009-2010 by Rafael Goncalves Martins
    :license: GPL-2, see LICENSE for more details.
"""

from __future__ import absolute_import

__all__ = [
    'need_update',
    'check_updates',
    'download_files',
    'check_db_cache',
]

from .config import Config
conf = Config(True) # fetch phase

from .exception import FetchException
from .compat import py3k

if py3k:
    import urllib.request as urllib
else:
    import urllib2 as urllib
import os
import json
import re
import tarfile
import portage.output

out = portage.output.EOutput()

re_files = {
    'info.json':              re.compile(r'info-([0-9]{10})-([0-9]+)\.json'),
    'octave-forge.db.tar.gz': re.compile(r'octave-forge-([0-9]{10})\.db\.tar\.gz'),
    'patches.tar.gz':         re.compile(r'patches-([0-9]{10})-([0-9]+)\.tar\.gz'),
}

def need_update():
    
    return not os.path.exists(os.path.join(conf.db, 'update.json'))


def check_updates():
    
    try:
        update = download_with_urllib2(conf.db_mirror + '/update.json', display_info=False)
    except Exception as error:
        # if we already have a file, that's ok
        if need_update():
            raise FetchException(error)
        with open(os.path.join(conf.db, 'update.json')) as fp:
            update = fp.read()
    else:
        with open(os.path.join(conf.db, 'update.json'), 'w') as fp:
            fp.write(update)
    
    updated_files = json.loads(update)
    
    old_files = []
    
    for _file in updated_files['files']:
        if not os.path.exists(os.path.join(conf.db, _file)):
            old_files.append(_file)
    
    return old_files


def download_files(files):
    
    for _file in files:
        download_with_urllib2(conf.db_mirror + '/' + _file, conf.db)
        add_file_to_db_cache(_file)
        extract(_file)
    

def download_with_urllib2(url, dest=None, display_info=True):
    
    my_file = os.path.basename(url)
    
    if display_info:
        out.ebegin('Downloading: %s' % my_file)
    try:
        fp = urllib.urlopen(url)
        file_content = fp.read()
        fp.close()
        if dest != None:
            if not os.path.exists(dest):
                os.makedirs(dest, 0o755)
            with open(os.path.join(dest, my_file), 'w') as fp:
                fp.write(file_content)
        else:
            if display_info:
                out.eend(0)
            return file_content
    except Exception as error:
        if display_info:
            out.eend(1)
        raise Exception('Failed to fetch the file (%s): %s' % (my_file, error))
    else:
        if display_info:
            out.eend(0)


def add_file_to_db_cache(_file):
    
    my_file = os.path.join(conf.db, 'cache.json')
    
    try:
        with open(my_file) as fp:
            files = json.load(fp)
    except:
        files = {'files': {}}
    
    for f in re_files:
        if re_files[f].match(_file) != None:
            files['files'][f] = _file
    
    with open(my_file, 'w') as fp:
        json.dump(files, fp)


def check_db_cache():
    
    try:
        with open(os.path.join(conf.db, 'cache.json')) as fp:
            cache = json.load(fp)
    except:
        cache = {'files': {}}
    
    try:
        with open(os.path.join(conf.db, 'update.json')) as fp:
            update = json.load(fp)
    except:
        my_cache = os.listdir(conf.db)
        update = {'files': []}
        for f in my_cache:
            for s in ['patches-', 'info-', 'octave-forge-']:
                if f.startswith(s) and f not in update['files']:
                    update['files'].append(f)
    
    for _file in update['files']:
        if _file not in list(cache['files'].values()):
            my_file = os.path.join(conf.db, _file)
            if not os.path.exists(my_file):
                download_with_wget(conf.db_mirror + '/' + _file, my_file)
            add_file_to_db_cache(_file)
            extract(_file)


def extract(gz_file, display_info=True):
     
    my_file = os.path.join(conf.db, gz_file)
    
    if tarfile.is_tarfile(my_file):
        if display_info:
            out.ebegin('Extracting: %s' % os.path.basename(gz_file))
        try:
            fp = tarfile.open(my_file, 'r:gz')
            fp.extractall(conf.db)
        except Exception as error:
            if display_info:
                out.eend(1)
            raise Exception('Failed to extract the file (%s): %s' % (my_file, error))
        else:
            if display_info:
                out.eend(0)