[ccplugin] Add delete and log commands
authorVladimir Popescu <vladimir.popescu@logilab.fr>
Wed, 03 Jul 2013 19:26:09 +0200
changeset 189 36b1978f95bc
parent 188 9ddc873f7768
child 190 aac836fcd93d
[ccplugin] Add delete and log commands The log command enables application logging in a file called <instance>.log. The delete command deletes the files from the old path.
ccplugin.py
test/unittest_remake-uuid.py
--- a/ccplugin.py	Wed Jul 03 14:56:26 2013 +0200
+++ b/ccplugin.py	Wed Jul 03 19:26:09 2013 +0200
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 
-import sys
+import os
 from os import path as osp
 import shutil
 import logging
@@ -27,7 +27,7 @@
             logger.error('copy_file: %s\n' % ioer)
             raise
 
-def update_ident_fpath(session, subject_eid, uuid, logger=None):
+def update_ident_fpath(session, subject_eid, uuid, delete=False, logger=None):
     """ Update the identifier and paths of a subject
     """
     if logger:
@@ -48,8 +48,14 @@
             logger.info('update_ident_fpath: processing related entity %d\n' % concerned_eid)
         uuid = make_uid() + '_' + unicode(concerned_eid)
         session.execute('SET X identifier %(i)s WHERE X eid %(e)s', {'i': uuid, 'e': concerned_eid})
-        new_filepath = uuid + '_' + unicode(concerned_eid) + osp.basename(concerned_fpath)
+        new_filepath = uuid + '_' + osp.basename(concerned_fpath)
         copy_file(concerned_fpath, new_filepath, logger)
+        if delete:
+            try:
+                os.remove(concerned_fpath)
+            except OSError as oserr:
+                if logger:
+                    logger.error('update_ident_fpath: %s\n' % oserr)
         session.execute('SET X filepath %(i)s WHERE X eid %(e)s', {'i': new_filepath, 'e': concerned_eid})
 
 
@@ -61,7 +67,7 @@
 
     """
     name = 'remake-uid'
-    arguments = '<instance>'
+    arguments = '<instance> [log] [delete]'
 
     def _init_cw_connection(self, appid):
         logger = logging.getLogger('brainomics')
@@ -78,7 +84,7 @@
             try:
                 repo, cnx = in_memory_repo_cnx(config, login=login, password=pwd)
             except AuthenticationError:
-                logging.warning('remake-uuid: wrong user/password')
+                logger.warning('remake-uuid: wrong user/password')
             else:
                 break
         session = repo._get_session(cnx.sessionid)
@@ -88,13 +94,18 @@
         logger = logging.getLogger('brainomics')
         if len(args) > 0:
             appid = args.pop(0)
+            import ipdb; ipdb.set_trace()
             cw_cnx, session = self._init_cw_connection(appid)
             session.set_cnxset()
-            debug = True if len(args) > 0 and args.pop(0) == 'D' else False
+            log = True if args and args.pop(0) == 'log' else False
+            delete = True if args and args.pop(0) == 'delete' else False
+            if log:
+                log_file = logging.FileHandler(appid + '.log')
+                logger.addHandler(log_file)
             for subject_eid in session.execute('Any X WHERE X is Subject', build_descr=False):
                 subject_eid = subject_eid[0]
                 uuid = unicode(make_uid())
-                update_ident_fpath(session, subject_eid, uuid, logger)
+                update_ident_fpath(session, subject_eid, uuid, delete, logger)
             session.commit()
         else:
             logger.error("remake-uuid: Please specify Brainomics instance")
--- a/test/unittest_remake-uuid.py	Wed Jul 03 14:56:26 2013 +0200
+++ b/test/unittest_remake-uuid.py	Wed Jul 03 19:26:09 2013 +0200
@@ -1,6 +1,7 @@
 import os
 import os.path as osp
 import tempfile
+import logging
 from cubicweb.utils import make_uid
 from cubicweb.devtools.testlib import CubicWebTC
 from cubes.brainomics.ccplugin import copy_file, update_ident_fpath
@@ -35,23 +36,33 @@
                           label=u'anatomy', type=u'normalized T1', format=u'nii.hz',
                           completed=True, valid=True, filepath=u'3785/anat.nii.gz',
                           concerns=self.subject_2, related_study=_study)
+        self.log = logging.getLogger('brainomics test: remake-uuid')
+        fh = logging.FileHandler('brainomics_test.log')
+        self.log.addHandler(fh)
 
     def test_copy_file(self):
         for fpath in (scan.filepath for scan in (self.scan_11, self.scan_12, self.scan_21, self.scan_22)):
             dest_path = unicode(make_uid()) + '_' + osp.basename(fpath)
             with tempfile.NamedTemporaryFile(suffix=osp.basename(fpath)) as f:
-                copy_file(f.name, dest_path)
+                copy_file(f.name, dest_path, logger=self.log)
             if osp.isfile(dest_path):
                 os.remove(dest_path)
 
-    def test_update_ident_fpath(self):
+    def test_update_ident_fpath_nodelete(self):
         old_fpaths = self.rql('Any F WHERE X is IN (Scan, GenomicMeasure), X filepath F', build_descr=False)
         for s in self.rql('Any X WHERE X is Subject'):
-            update_ident_fpath(self.session, s[0], unicode(make_uid()))
+            update_ident_fpath(self.session, s[0], unicode(make_uid()), logger=self.log)
         new_fpaths = self.rql('Any F WHERE X is IN (Scan, GenomicMeasure), X filepath F', build_descr=False)
 
         self.assertNotEqual(old_fpaths, new_fpaths)
 
+    def test_update_ident_fpath_delete(self):
+        old_fpaths = self.rql('Any F WHERE X is IN (Scan, GenomicMeasure), X filepath F', build_descr=False)
+        for s in self.rql('Any X WHERE X is Subject'):
+            update_ident_fpath(self.session, s[0], unicode(make_uid()), delete=True, logger=self.log)
+        new_fpaths = self.rql('Any F WHERE X is IN (Scan, GenomicMeasure), X filepath F', build_descr=False)
+
+        self.assertNotEqual(old_fpaths, new_fpaths)
 
 if __name__ == '__main__':
     from logilab.common.testlib import unittest_main