From fb038743626915f226f9733089620f94539e49bf Mon Sep 17 00:00:00 2001 From: Sascha Silbe Date: Tue, 07 Aug 2012 09:54:37 +0000 Subject: Optionally add extension to checked out files based on MIME type If available, gdatastore will now use sugar.mime to guess an extension to add to checked out files, based on their MIME type. The outside world (including emacs) is still surprisingly focused on file extensions rather than MIME types. By adding an extension to the file names returned by gdatastore we help other software that has to interface with legacy components. The alternative would be to add code to every piece of glue code to guess the extension and rename the file in a race-free way. Doing it in gdatastore reduces the overall complexity of the software system. --- diff --git a/gdatastore/datastore.py b/gdatastore/datastore.py index 72bf832..0fd7765 100644 --- a/gdatastore/datastore.py +++ b/gdatastore/datastore.py @@ -32,6 +32,13 @@ import dbus import dbus.service import gconf +try: + from sugar import mime as sugar_mime +except ImportError: + # Only used for helping legacy applications that use the file + # extension rather than the MIME type + sugar_mime = None + from gdatastore.index import Index @@ -534,13 +541,16 @@ class InternalApi(object): def get_data_path(self, (tree_id, version_id), sender=None): logging.debug('get_data_path((%r, %r), %r)', tree_id, version_id, sender) + metadata = self._index.retrieve((tree_id, version_id)) ref_name = _format_ref(tree_id, version_id) top_level_entries = self._git_call('ls-tree', [ref_name]).splitlines() if len(top_level_entries) == 1 and \ top_level_entries[0].endswith('\tdata'): blob_hash = top_level_entries[0].split('\t')[0].split(' ')[2] - return self._checkout_file(blob_hash) + mime_type = metadata.get('mime_type', '') + return self._checkout_file(blob_hash, + suffix=_guess_extension(mime_type)) return self._checkout_dir(ref_name) @@ -661,8 +671,8 @@ class InternalApi(object): for entry in old_versions: self.delete((entry['tree_id'], entry['version_id'])) - def _checkout_file(self, blob_hash): - fd, file_name = tempfile.mkstemp(dir=self._checkouts_dir) + def _checkout_file(self, blob_hash, suffix=''): + fd, file_name = tempfile.mkstemp(dir=self._checkouts_dir, suffix=suffix) try: self._git_call('cat-file', ['blob', blob_hash], stdout_fd=fd) finally: @@ -855,3 +865,12 @@ def to_native(value): def _format_ref(tree_id, version_id): return 'refs/gdatastore/%s/%s' % (tree_id, version_id) + + +def _guess_extension(mime_type): + if sugar_mime is None: + return '' + extension = sugar_mime.get_primary_extension(mime_type) + if not extension: + return '' + return '.' + extension -- cgit v0.9.1