From adc1b1a10cbf826630c2186b75e12e1888af7f7a Mon Sep 17 00:00:00 2001
From: Marco Mariani <marco.mariani@nexedi.com>
Date: Fri, 2 Nov 2012 14:40:12 +0100
Subject: [PATCH] track multiple callbacks

---
 slapos/recipe/librecipe/generic.py | 19 ++++++++++++++++++-
 slapos/recipe/notifier.py          |  9 +++++----
 2 files changed, 23 insertions(+), 5 deletions(-)

diff --git a/slapos/recipe/librecipe/generic.py b/slapos/recipe/librecipe/generic.py
index 00ee68479..bb239f3b0 100644
--- a/slapos/recipe/librecipe/generic.py
+++ b/slapos/recipe/librecipe/generic.py
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+# vim: set et sts=2:
 ##############################################################################
 #
 # Copyright (c) 2010 Vifib SARL and Contributors. All Rights Reserved.
@@ -24,6 +26,7 @@
 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #
 ##############################################################################
+import io
 import logging
 import os
 import sys
@@ -90,6 +93,21 @@ class GenericBaseRecipe(object):
   def createExecutable(self, name, content, mode=0700):
     return self.createFile(name, content, mode)
 
+  def addLineToFile(self, filepath, line, encoding='utf8'):
+    """Append a single line to a text file, if the line does not exist yet.
+    
+    line must be unicode."""
+
+    try:
+      lines = io.open(filepath, 'r', encoding=encoding).readlines()
+    except IOError:
+      lines = []
+
+    if not line in lines:
+      lines.append(line)
+      with io.open(filepath, 'w+', encoding=encoding) as f:
+        f.write(u'\n'.join(lines))
+
   def createPythonScript(self, name, absolute_function, arguments=''):
     """Create a python script using zc.buildout.easy_install.scripts
 
@@ -115,7 +133,6 @@ class GenericBaseRecipe(object):
     Takes care of quoting.
     """
 
-    q = shlex.quote
     lines = [
             '#!/bin/sh',
             'exec %s' % shlex.quote(command)
diff --git a/slapos/recipe/notifier.py b/slapos/recipe/notifier.py
index c64b15e5a..5e35f768a 100644
--- a/slapos/recipe/notifier.py
+++ b/slapos/recipe/notifier.py
@@ -47,12 +47,13 @@ class Callback(GenericBaseRecipe):
 
   def createCallback(self, notification_id, callback):
     callback_id = sha512(notification_id).hexdigest()
-    callback = self.createFile(os.path.join(self.options['callbacks'],
-                                            callback_id),
-                               callback)
-    return callback
+
+    filepath = os.path.join(self.options['callbacks'], callback_id)
+    self.addLineToFile(filepath, callback)
+    return filepath
 
   def install(self):
+    # XXX this path is returned multiple times, one for each callback that has been added.
     return [self.createCallback(self.options['on-notification-id'],
                                 self.options['callback'])]
 
-- 
2.30.9