Commits

wistful  committed 8f9039a

nautilus-opener: fix issue with reading non existing config file

  • Participants
  • Parent commits 6432710
  • Tags nautilus-opener-1.2

Comments (0)

Files changed (3)

File deb/nautilus-opener/debian/changelog

+nautilus-opener (1.2~quantal) quantal; urgency=low
+
+  * fix issue with reading non existing config file
+
+ -- wistful <wst.public.mail@gmail.com>  Sun, 21 Oct 2012 12:33:44 +0300
+
+
 nautilus-opener (1.1~precise) precise; urgency=low
 
   * Initial Release.

File deb/nautilus-opener/debian/copyright

  On Debian systems, the complete text of the GNU General
  Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
 
-# Please also look if there are files or directories which have a
-# different copyright/license attached and list them here.
-# Please avoid to pick license terms that are more restrictive than the
-# packaged work, as it may make Debian's contributions unacceptable upstream.

File deb/nautilus-opener/nautilus-opener/nautilus-opener.py

+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+#    Copyleft 2011-3011 wistful (wst[dot]public[dot]mail[dot]gmail[dot]com)
+#
+#    This is a free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+from ConfigParser import ConfigParser
+from subprocess import Popen
+import traceback
+import datetime
+import os
+import urllib
+import re
+
+
+try:
+    # for old versions of python-nautilus
+    import nautilus
+    import pygtk
+    pygtk.require('2.0')
+
+    class GObject(object):
+        class GObject(object):
+            pass
+except ImportError, ex:
+    # for new versions of python-nautilus
+    from gi.repository import Nautilus as nautilus
+    from gi.repository import GObject
+
+if not os.path.exists(os.path.expanduser('~/.config/nautilus-opener')):
+    os.mkdir(os.path.expanduser('~/.config/nautilus-opener'))
+SETTINGS_PATH = os.path.expanduser('~/.config/nautilus-opener/nautilus-opener.conf')
+LOG_PATH = os.path.expanduser('~/.config/nautilus-opener/nautilus-opener.log')
+
+
+def logger(message):
+    """ write messages to log file """
+    fd = open(LOG_PATH, 'a+')
+    fd.write(message)
+    fd.write("\n")
+
+
+def error_wrapper(fn):
+    """
+    catch Exceptions and write it to the log file
+    """
+    name = fn.__name__
+
+    def new_fn(*args, **kwargs):
+        try:
+            result = fn(*args, **kwargs)
+            return result
+        except Exception, err:
+            logger("{date} Error in the {name}:\n{traceback}\n\n".format(
+                    date=datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"),
+                    name=name, traceback=traceback.format_exc()))
+            raise
+    return new_fn
+
+
+@error_wrapper
+def read_config(config_path):
+    config = ConfigParser()
+    config.read([config_path])
+    rules = [item.strip() for item in config._sections['settings']['rules'].split(',')]
+    result = {}
+    for rule in rules:
+        if config.has_section(rule):
+            result[rule] = dict((item[0], item[1]) for item in config.items(rule))
+    return result
+
+
+def get_paths(nautilus_path_list):
+    for item in nautilus_path_list:
+        yield urllib.unquote(item.get_uri()[7:])
+
+
+class NautilusOpener(GObject.GObject, nautilus.MenuProvider, nautilus.InfoProvider):
+
+    def __init__(self):
+        self.rules = read_config(SETTINGS_PATH)
+        if os.path.exists(LOG_PATH):
+            os.remove(LOG_PATH)
+
+    def run(self, menu, param):
+        item, rule_name = param
+        exec_path = self.rules[rule_name].get('exec_path', None)
+        if exec_path:
+            return Popen([exec_path, item]).pid
+
+    @error_wrapper
+    def get_file_items(self, window, files):
+        if len(files) > 1 or not self.rules:
+            return
+
+        # get items which match to mask ("item" option)
+        item_path_list = [(item, rule_name) for rule_name, rule in self.rules.items()
+                                                for item in get_paths(files)
+                                                    if rule.get('item', None) and
+                                                       re.search(rule['item'], os.path.split(item)[1])]
+
+        # get childes which match to mask ("child" option)
+        child_path_list = [(item, rule_name) for rule_name, rule in self.rules.items()
+                                                for item in get_paths(files)
+                                                    if os.path.isdir(item)
+                                                        for child in os.listdir(item)
+                                                           if rule.get('child', None) and
+                                                                re.search(rule['child'], child)]
+        item_path_list.extend(child_path_list)
+
+        menus = []
+        for item, rule_name in item_path_list:
+            label = self.rules[rule_name].get('label')
+            help_label = self.rules[rule_name].get('help')
+            if not label:
+                continue
+            menus.append(nautilus.MenuItem(name='NautilusOpener::' + rule_name.replace(' ', '_') + '_opener',
+                                           label=label,
+                                           tip=help_label))
+            menus[-1].connect('activate', self.run, (item, rule_name))
+
+        return menus
+
+    @error_wrapper
+    def update_file_info(self, file_item):
+        # get emblems which match to mask ("item" option)
+        item_path_list = [rule['emblem'] for rule_name, rule in self.rules.items()
+                                                for item in get_paths([file_item])
+                                                    if rule.get('item', None) and rule.get('emblem', None) and
+                                                       re.search(rule['item'], os.path.split(item)[1])]
+
+        # get emblems which match to mask ("child" option)
+        child_path_list = [rule['emblem'] for rule_name, rule in self.rules.items()
+                                                for item in get_paths([file_item])
+                                                    if os.path.isdir(item)
+                                                        for child in os.listdir(item)
+                                                            if rule.get('child', None) and rule.get('emblem', None) and
+                                                                re.search(rule['child'], child)]
+        item_path_list.extend(child_path_list)
+
+        if item_path_list:
+            # if emblem not exist -> nothing happens
+            file_item.add_emblem(item_path_list[-1])