summaryrefslogtreecommitdiffstats
path: root/layman/overlays/tar.py
blob: 786f799100045c8e1a76838c43234ccd5daf2cf2 (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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/python
# -*- coding: utf-8 -*-
#################################################################################
# LAYMAN TAR OVERLAY HANDLER
#################################################################################
# File:       tar.py
#
#             Handles tar overlays
#
# Copyright:
#             (c) 2005 - 2008 Gunnar Wrobel
#             Distributed under the terms of the GNU General Public License v2
#
# Author(s):
#             Gunnar Wrobel <wrobel@gentoo.org>
#
''' Tar overlay support.'''

__version__ = "$Id: tar.py 310 2007-04-09 16:30:40Z wrobel $"

#===============================================================================
#
# Dependencies
#
#-------------------------------------------------------------------------------

import os, os.path, sys, urllib2, shutil
import xml.etree.ElementTree as ET # Python 2.5

from   layman.utils             import path, ensure_unicode
from   layman.overlays.overlay  import Overlay

#===============================================================================
#
# Class TarOverlay
#
#-------------------------------------------------------------------------------

class TarOverlay(Overlay):
    ''' Handles tar overlays.

    A dummy tar handler that overwrites the __init__ method
    so that we don't need to provide xml input:

    >>> from   layman.debug             import OUT
    >>> class DummyTar(TarOverlay):
    ...   def __init__(self):
    ...     self.name = 'dummy'
    ...     here = os.path.dirname(os.path.realpath(__file__))
    ...     self.src  = 'file://' + here + '/../tests/testfiles/layman-test.tar.bz2'
    ...     self.subpath = 'layman-test'
    ...     self.quiet = False
    ...     self.config = {'tar_command':'/bin/tar'}
    >>> testdir = os.tmpnam()
    >>> os.mkdir(testdir)
    >>> a = DummyTar()
    >>> OUT.color_off()
    >>> a.add(testdir) #doctest: +ELLIPSIS
    * Running command "/bin/tar -v -x -f...
    >>> sorted(os.listdir(testdir + '/dummy'))
    ['app-admin', 'app-portage']
    >>> shutil.rmtree(testdir)
    '''

    type = 'Tar'
    type_key = 'tar'

    def __init__(self, xml, config, ignore = 0, quiet = False):

        Overlay.__init__(self, xml, config, ignore)

        _subpath = xml.find('subpath')
        if _subpath != None:
            self.subpath = ensure_unicode(_subpath.text.strip())
        elif 'subpath' in xml.attrib:
            self.subpath = ensure_unicode(xml.attrib['subpath'])
        else:
            self.subpath = ''

        _category = xml.find('category')
        if _category != None:
            self.category = ensure_unicode(_category.text.strip())
        elif 'category' in xml.attrib:
            self.category = ensure_unicode(xml.attrib['category'])
        else:
            self.category = ''

        if self.subpath and self.category:
            raise Exception('Cannot use "category" and "subpath" at the same time!')

    def __eq__(self, other):
        res = super(TarOverlay, self).__eq__(other) \
            and self.subpath == other.subpath \
            and self.category == other.category
        return res

    def __ne__(self, other):
        return not self.__eq__(other)

    # overrider
    def to_xml(self):
        repo = super(TarOverlay, self).to_xml()
        if self.subpath:
            _subpath = ET.Element('subpath')
            _subpath.text = self.subpath
            repo.append(_subpath)
        if self.category:
            _category = ET.Element('category')
            _category.text = self.category
            repo.append(_category)
        return repo

    def add(self, base, quiet = False):
        '''Add overlay.'''

        self.supported()

        mdir = path([base, self.name])

        if os.path.exists(mdir):
            raise Exception('Directory ' + mdir + ' already exists. Will not ov'
                            'erwrite its contents!')

        ext = '.noidea'
        for i in [('tar.%s' % e) for e in ('bz2', 'gz', 'lzma', 'xz', 'Z')] \
                + ['tgz', 'tbz', 'taz', 'tlz', 'txz']:
            candidate_ext = '.%s' % i
            if self.src.endswith(candidate_ext):
                ext = candidate_ext
                break

        try:

            tar = urllib2.urlopen(self.src).read()

        except Exception, error:
            raise Exception('Failed to fetch the tar package from: '
                            + self.src + '\nError was:' + str(error))

        pkg = path([base, self.name + ext])

        try:

            out_file = open(pkg, 'w')
            out_file.write(tar)
            out_file.close()

        except Exception, error:
            raise Exception('Failed to store tar package in '
                            + pkg + '\nError was:' + str(error))

        if self.subpath:
            target = path([base, 'tmp'])
        else:
            if self.category:
                target = mdir + '/' + self.category
            else:
                target = mdir

        os.makedirs(target)

        result = self.cmd(self.command() + u' -v -x' + u' -f "' + pkg
                          + u'" -C "' + target + u'"')

        if self.subpath:
            source = target + '/' + self.subpath
            if os.path.exists(source):
                try:
                    os.rename(source, mdir)
                except Exception, error:
                    raise Exception('Failed to rename tar subdirectory ' +
                                    source + ' to ' + mdir + '\nError was:'
                                    + str(error))
            else:
                raise Exception('Given subpath "' + source + '" does not exist '
                                ' in the tar package!')
            try:
                shutil.rmtree(target)
            except Exception, error:
                raise Exception('Failed to remove unnecessary tar structure "'
                                + target + '"\nError was:' + str(error))

        os.unlink(pkg)

        return result

    def sync(self, base, quiet = False):
        '''Sync overlay.'''

        self.supported()

        self.delete(base)

        self.add(base)

    def supported(self):
        '''Overlay type supported?'''

        return Overlay.supported(self, [(self.command(),  'tar', 'app-arch/tar'), ])

if __name__ == '__main__':
    import doctest

    # Ignore warnings here. We are just testing
    from warnings     import filterwarnings, resetwarnings
    filterwarnings('ignore')

    doctest.testmod(sys.modules[__name__])

    resetwarnings()