~launchpad-pqm/launchpad/devel

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
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Library access methods to gina."""

__metaclass__ = type


import hashlib
import os

from zope.component import getUtility

from canonical.launchpad.interfaces.librarian import ILibraryFileAliasSet


def _libType(fname):
    if fname.endswith(".dsc"):
        return "text/x-debian-source-package"
    if fname.endswith(".deb"):
        return "application/x-debian-package"
    if fname.endswith(".udeb"):
        return "application/x-micro-debian-package"
    if fname.endswith(".diff.gz"):
        return "application/gzipped-patch"
    if fname.endswith(".tar.gz"):
        return "application/gzipped-tar"
    return "application/octet-stream"


def getLibraryAlias(root, filename):
    librarian = getUtility(ILibraryFileAliasSet)
    if librarian is None:
        return None
    fname = os.path.join(root, filename)
    fobj = open(fname, "rb")
    size = os.stat(fname).st_size
    alias = librarian.create(filename, size, fobj,
                             contentType=_libType(filename))
    fobj.close()
    return alias


def checkLibraryForFile(path, filename):
    fullpath = os.path.join(path, filename)
    assert os.path.exists(fullpath)
    digester = hashlib.sha1()
    openfile = open(fullpath, "r")
    for chunk in iter(lambda: openfile.read(1024*4), ''):
        digester.update(chunk)
    digest = digester.hexdigest()
    openfile.close()
    librarian = getUtility(ILibraryFileAliasSet)
    return librarian.findBySHA1(digest).count() > 0