DC resource. More merge tests.
authorŁukasz Rekucki <lrekucki@gmail.com>
Tue, 22 Sep 2009 15:20:21 +0000 (17:20 +0200)
committerŁukasz Rekucki <lrekucki@gmail.com>
Tue, 22 Sep 2009 15:20:21 +0000 (17:20 +0200)
apps/api/handlers.py
apps/api/tests/__init__.py
apps/api/urls.py
apps/api/utils.py
lib/wlrepo/backend_mercurial.py
lib/wlrepo/tests/test_mercurial.py

index 352e35e..2f2bea1 100644 (file)
@@ -9,6 +9,8 @@ from datetime import date
 from django.core.urlresolvers import reverse
 from wlrepo import MercurialLibrary, CabinetNotFound
 
 from django.core.urlresolvers import reverse
 from wlrepo import MercurialLibrary, CabinetNotFound
 
+from librarian import dcparser
+
 #
 # Document List Handlers
 #
 #
 # Document List Handlers
 #
@@ -98,7 +100,10 @@ class BasicDocumentHandler(AnonymousBaseHandler):
             result['parts'] = document.parts()
 
         return result   
             result['parts'] = document.parts()
 
         return result   
-        
+
+#
+# Document Meta Data
+#
 class DocumentHandler(BaseHandler):
     allowed_methods = ('GET', 'PUT')
     anonymous = BasicDocumentHandler
 class DocumentHandler(BaseHandler):
     allowed_methods = ('GET', 'PUT')
     anonymous = BasicDocumentHandler
@@ -113,6 +118,9 @@ class DocumentHandler(BaseHandler):
               
         document = lib.cabinet(docid, request.user.username, \
                 create=opts.cleaned_data['autocabinet'] ).retrieve()
               
         document = lib.cabinet(docid, request.user.username, \
                 create=opts.cleaned_data['autocabinet'] ).retrieve()
+
+        if not document:
+            return rc.NOT_HERE
                 
         shared = lib.main_cabinet.retrieve(docid)
 
                 
         shared = lib.main_cabinet.retrieve(docid)
 
@@ -154,4 +162,35 @@ class DocumentTextHandler(BaseHandler):
             lib.document(docid, request.user.username).write(data)
             return rc.ALL_OK
         except (CabinetNotFound, KeyError):
             lib.document(docid, request.user.username).write(data)
             return rc.ALL_OK
         except (CabinetNotFound, KeyError):
-            return rc.NOT_HERE
\ No newline at end of file
+            return rc.NOT_HERE
+
+
+#
+# Dublin Core handlers
+#
+# @requires librarian
+#
+class DocumentDublinCoreHandler(BaseHandler):
+    allowed_methods = ('GET', 'PUT')
+
+    def read(self, request, docid):
+        """Read document as raw text"""
+        lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
+        try:
+            doc = lib.document(docid, request.user.username)
+
+            # TODO: RAL:document should support file-like ops
+            bookinfo = dcparser.BookInfo.from_string(doc.read())
+            return bookinfo.serialize()
+        except CabinetNotFound:
+            return rc.NOT_HERE
+
+    def update(self, request, docid):
+        lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
+        try:
+            data = request.PUT['contents']
+            lib.document(docid, request.user.username).write(data)
+            return rc.ALL_OK
+        except (CabinetNotFound, KeyError):
+            return rc.NOT_HERE
+
index 671978a..ca575fe 100644 (file)
@@ -21,8 +21,14 @@ import tempfile
 
 REPO_TEMPLATES = join(dirname(__file__), 'data')
 
 
 REPO_TEMPLATES = join(dirname(__file__), 'data')
 
+
+
 def temprepo(name):
 def temprepo(name):
-    def decorator(func):   
+    from functools import wraps
+
+    def decorator(func):
+
+        @wraps(func)
         def decorated(self, *args, **kwargs):
             clean = False
             try:
         def decorated(self, *args, **kwargs):
             clean = False
             try:
@@ -39,7 +45,7 @@ def temprepo(name):
 
                 shutil.rmtree(temp, True)
                 settings.REPOSITORY_PATH = ''
 
                 shutil.rmtree(temp, True)
                 settings.REPOSITORY_PATH = ''
-            
+           
         return decorated
     return decorator   
     
         return decorated
     return decorator   
     
index ada879c..913acb7 100644 (file)
@@ -9,20 +9,24 @@ from api.utils import TextEmitter, DjangoAuth
 
 authdata = {'authentication': DjangoAuth()}
 
 
 authdata = {'authentication': DjangoAuth()}
 
-FORMAT_EXT = r"\.(?P<emitter_format>xml|json|yaml|django)$"
+FORMAT_EXT = r"\.(?P<emitter_format>xml|json|yaml)$"
 
 library_resource = Resource(LibraryHandler, **authdata)
 document_resource = Resource(DocumentHandler, **authdata)
 document_text_resource = Resource(DocumentTextHandler, **authdata)
 
 library_resource = Resource(LibraryHandler, **authdata)
 document_resource = Resource(DocumentHandler, **authdata)
 document_text_resource = Resource(DocumentTextHandler, **authdata)
+document_dc_resource = Resource(DocumentDublinCoreHandler, **authdata)
 
 urlpatterns = patterns('',
 #    url(r'^hello$', hello_resource, {'emitter_format': 'json'}),
 #    url(r'^hello\.(?P<emitter_format>.+)$', hello_resource),
 
     # Documents
 
 urlpatterns = patterns('',
 #    url(r'^hello$', hello_resource, {'emitter_format': 'json'}),
 #    url(r'^hello\.(?P<emitter_format>.+)$', hello_resource),
 
     # Documents
-    url(r'^documents$', library_resource, {'emitter_format': 'json'},
-        name="document_list_view"),
+    url(r'^documents$', library_resource,
+        {'emitter_format': 'json'}, name="document_list_view"),
 
 
+    url(r'^documents'+FORMAT_EXT, library_resource,
+        name="document_list_view_withformat"),
+        
     url(r'^documents/(?P<docid>[^/]+)'+FORMAT_EXT,
         document_resource, name="document_view_withformat"),
 
     url(r'^documents/(?P<docid>[^/]+)'+FORMAT_EXT,
         document_resource, name="document_view_withformat"),
 
@@ -34,8 +38,12 @@ urlpatterns = patterns('',
         document_text_resource, {'emitter_format': 'rawxml'},
         name="doctext_view"),
 
         document_text_resource, {'emitter_format': 'rawxml'},
         name="doctext_view"),
 
+    url(r'^documents/(?P<docid>[^/]+)/dc' + FORMAT_EXT,
+        document_dc_resource,
+        name="docdc_view_withformat"),
+
     url(r'^documents/(?P<docid>[^/]+)/dc$',
     url(r'^documents/(?P<docid>[^/]+)/dc$',
-        document_resource, {'emitter_format': 'json'},
+        document_dc_resource, {'emitter_format': 'json'},
         name="docdc_view"),
 
     url(r'^documents/(?P<docid>[^/]+)/parts$',
         name="docdc_view"),
 
     url(r'^documents/(?P<docid>[^/]+)/parts$',
index 67e8ea5..4b004ee 100644 (file)
@@ -13,8 +13,7 @@ class TextEmitter(Emitter):
         return unicode(self.construct())
 
 Emitter.register('text', TextEmitter, 'text/plain; charset=utf-8')
         return unicode(self.construct())
 
 Emitter.register('text', TextEmitter, 'text/plain; charset=utf-8')
-Emitter.register('rawxml', TextEmitter, 'application/xml; charset=utf-8')
-
+Emitter.register('rawxml', TextEmitter, 'application/xml; charset=UTF-8')
 
 class DjangoAuth(object):
 
 
 class DjangoAuth(object):
 
index 94bf52a..dfcef09 100644 (file)
@@ -60,6 +60,10 @@ class MercurialLibrary(wlrepo.Library):
         finally:
             lock.release()
 
         finally:
             lock.release()
 
+    @property
+    def ospath(self):
+        return self._ospath
+
     @property
     def main_cabinet(self):
         return self._maincab
     @property
     def main_cabinet(self):
         return self._maincab
@@ -68,6 +72,9 @@ class MercurialLibrary(wlrepo.Library):
         return self.cabinet(docid, user, create=False).retrieve()
 
     def cabinet(self, docid, user, create=False):
         return self.cabinet(docid, user, create=False).retrieve()
 
     def cabinet(self, docid, user, create=False):
+        docid = self._sanitize_string(docid)
+        user = self._sanitize_string(user)
+        
         bname = self._bname(user, docid)
 
         lock = self._lock(True)
         bname = self._bname(user, docid)
 
         lock = self._lock(True)
@@ -91,6 +98,7 @@ class MercurialLibrary(wlrepo.Library):
                 
                 garbage = [fid for (fid, did) in l._filelist() if not did.startswith(docid)]                
                 l._filesrm(garbage)
                 
                 garbage = [fid for (fid, did) in l._filelist() if not did.startswith(docid)]                
                 l._filesrm(garbage)
+                print "removed: ", garbage
 
             # create the branch
             self._create_branch(bname, before_commit=cleanup_action)
 
             # create the branch
             self._create_branch(bname, before_commit=cleanup_action)
@@ -212,7 +220,9 @@ class MercurialLibrary(wlrepo.Library):
         self._checkout(self._branch_tip(branchname))
         return branchname        
 
         self._checkout(self._branch_tip(branchname))
         return branchname        
 
-    def shelf(self, nodeid):
+    def shelf(self, nodeid=None):
+        if nodeid is None:
+            nodeid = self._maincab._name
         return MercurialShelf(self, self._changectx(nodeid))   
 
 
         return MercurialShelf(self, self._changectx(nodeid))   
 
 
@@ -255,6 +265,7 @@ class MercurialCabinet(wlrepo.Cabinet):
         def retrieve_action(l,c):
             if l._fileexists(fileid):
                 return MercurialDocument(c, name=name, fileid=fileid)
         def retrieve_action(l,c):
             if l._fileexists(fileid):
                 return MercurialDocument(c, name=name, fileid=fileid)
+            print "File %s not found " % fileid
             return None
                 
         return self._execute_in_branch(retrieve_action)        
             return None
                 
         return self._execute_in_branch(retrieve_action)        
@@ -371,7 +382,7 @@ class MercurialDocument(wlrepo.Document):
             
             user = self._cabinet.username
 
             
             user = self._cabinet.username
 
-            main = self.shared().shelf()
+            main = self.library.shelf()
             local = self.shelf()
 
             no_changes = True
             local = self.shelf()
 
             no_changes = True
@@ -390,9 +401,9 @@ class MercurialDocument(wlrepo.Document):
             # no commit's since last update
 
             if main.ancestorof(local):
             # no commit's since last update
 
             if main.ancestorof(local):
+                print "case 1"
                 main.merge_with(local, user=user, message=message)
                 no_changes = False
                 main.merge_with(local, user=user, message=message)
                 no_changes = False
-
             # Case 2:
             #
             # main *  * local
             # Case 2:
             #
             # main *  * local
@@ -404,6 +415,7 @@ class MercurialDocument(wlrepo.Document):
             # Default has no changes, to update from this branch
             # since the last merge of local to default.
             elif local.has_common_ancestor(main):
             # Default has no changes, to update from this branch
             # since the last merge of local to default.
             elif local.has_common_ancestor(main):
+                print "case 2"
                 if not local.parentof(main):
                     main.merge_with(local, user=user, message=message)
                     no_changes = False
                 if not local.parentof(main):
                     main.merge_with(local, user=user, message=message)
                     no_changes = False
@@ -423,16 +435,18 @@ class MercurialDocument(wlrepo.Document):
             # Use the fact, that user is prepared to see changes, to
             # update his branch if there are any
             elif local.ancestorof(main):
             # Use the fact, that user is prepared to see changes, to
             # update his branch if there are any
             elif local.ancestorof(main):
+                print "case 3"
                 if not local.parentof(main):
                     local.merge_with(main, user=user, message='Local branch update.')
                     no_changes = False
             else:
                 if not local.parentof(main):
                     local.merge_with(main, user=user, message='Local branch update.')
                     no_changes = False
             else:
+                print "case 4"
                 local.merge_with(main, user=user, message='Local branch update.')
                 local.merge_with(main, user=user, message='Local branch update.')
-
-                self._refresh()
                 local = self.shelf()
                 local = self.shelf()
-
                 main.merge_with(local, user=user, message=message)
                 main.merge_with(local, user=user, message=message)
+
+            print "no_changes: ", no_changes
+            return no_changes
         finally:
             lock.release()
                
         finally:
             lock.release()
                
@@ -495,7 +509,7 @@ class MercurialShelf(wlrepo.Shelf):
 
     def has_common_ancestor(self, other):
         a = self._changectx.ancestor(other._changectx)
 
     def has_common_ancestor(self, other):
         a = self._changectx.ancestor(other._changectx)
-        print a, self._changectx.branch(), a.branch()
+        print a, self._changectx.branch(), a.branch()
 
         return (a.branch() == self._changectx.branch())
 
 
         return (a.branch() == self._changectx.branch())
 
@@ -504,6 +518,7 @@ class MercurialShelf(wlrepo.Shelf):
         try:
             self._library._checkout(self._changectx.node())
             self._library._merge(other._changectx.node())
         try:
             self._library._checkout(self._changectx.node())
             self._library._merge(other._changectx.node())
+            self._library._commit(user=user, message=message)
         finally:
             lock.release()
 
         finally:
             lock.release()
 
index 1bf5d5b..1f708d6 100644 (file)
@@ -14,18 +14,21 @@ import os, os.path, tempfile
 import shutil
 
 
 import shutil
 
 
-REPO_TEMPLATES = os.path.join( os.path.dirname(__file__), 'data/repos')
+REPO_TEMPLATES = os.path.join( os.path.dirname(__file__), 'data')
 
 def temprepo(name):
 
 def temprepo(name):
-    def decorator(func):
-        def decorated(self, *args, **kwargs):
+
+    from functools import wraps
+
+    def decorator(func):               
+        def decorated(*args, **kwargs):
             clean = False
             try:
                 temp = tempfile.mkdtemp("", "testdir_" )
             clean = False
             try:
                 temp = tempfile.mkdtemp("", "testdir_" )
-                path = join(temp, 'repo')
-                shutil.copytree(join(REPO_TEMPLATES, name), path, False)
-                repo = MercurialLibrary(path)
-                func(self, *args, library=repo, **kwargs)
+                path = os.path.join(temp, 'repo')
+                shutil.copytree(os.path.join(REPO_TEMPLATES, name), path, False)
+                kwargs['library'] = MercurialLibrary(path)
+                func(*args, **kwargs)
                 clean = True
             finally:
                 #if not clean and self.response:
                 clean = True
             finally:
                 #if not clean and self.response:
@@ -34,10 +37,11 @@ def temprepo(name):
                 #    print "<<<"
                 shutil.rmtree(temp, True)
 
                 #    print "<<<"
                 shutil.rmtree(temp, True)
 
-        return decorated
+        decorated = make_decorator(func)(decorated)
+        return decorated   
+    
     return decorator
 
     return decorator
 
-
 @temprepo('clean')
 def test_opening(library):
     pass
 @temprepo('clean')
 def test_opening(library):
     pass
@@ -72,7 +76,7 @@ def test_write_document(library):
 def test_create_document(library):
     doc = library.main_cabinet.create("another_file", "Some text")
     assert_equal( doc.read(), "Some text")
 def test_create_document(library):
     doc = library.main_cabinet.create("another_file", "Some text")
     assert_equal( doc.read(), "Some text")
-    assert_true( os.path.isfile( os.path.join(repopath, "pub_another_file.xml")) )
+    assert_true( os.path.isfile( os.path.join(library.ospath, "pub_another_file.xml")) )
 
 @temprepo('branched')
 def test_switch_branch(library):
 
 @temprepo('branched')
 def test_switch_branch(library):
@@ -120,7 +124,7 @@ def test_no_branches(library):
     assert_true( n3.has_common_ancestor(n3) )
 
 
     assert_true( n3.has_common_ancestor(n3) )
 
 
-@temprepo('branched_two')
+@temprepo('branched2')
 def test_once_branched(library):
     n7 = library.shelf(7)
     n6 = library.shelf(6)
 def test_once_branched(library):
     n7 = library.shelf(7)
     n6 = library.shelf(6)
@@ -201,16 +205,22 @@ def test_after_merge_and_local_commit(library):
 @temprepo('branched2')
 def test_merge_personal_to_default(library):   
     main = library.shelf(2)
 @temprepo('branched2')
 def test_merge_personal_to_default(library):   
     main = library.shelf(2)
+    print main
+    
     local = library.shelf(7)
     local = library.shelf(7)
+    print local
 
     document = library.document("ala", "admin")
     shared = document.shared()
 
     document = library.document("ala", "admin")
     shared = document.shared()
-    print document, shared
-
+    assert_true( shared is None )
     document.share("Here is my copy!")
 
     assert_equal( document.shelf(), local) # local didn't change
 
     document.share("Here is my copy!")
 
     assert_equal( document.shelf(), local) # local didn't change
 
+    shared = document.shared()
+    assert_true( shared is not None )
+
+    print library.shelf()
 
     new_main = shared.shelf()
     assert_not_equal( new_main, main) # main has new revision
 
     new_main = shared.shelf()
     assert_not_equal( new_main, main) # main has new revision
@@ -220,12 +230,7 @@ def test_merge_personal_to_default(library):
     assert_true( local.parentof(new_main) )
 
 @temprepo('clean')
     assert_true( local.parentof(new_main) )
 
 @temprepo('clean')
-def testCreateBranch(library):
-    library = MercurialLibrary(repopath)
-
+def test_create_branch(library):   
     tester_cab = library.cabinet("anotherone", "tester", create=True)
     tester_cab = library.cabinet("anotherone", "tester", create=True)
-    assert_equal( list(tester_cab.documents()), ['anotherone'])
-
-        
-
+    assert_equal( list(tester_cab.documents()), ['anotherone'])