Browse Source

Add all hierarchical tags

Getty Ritter 4 years ago
parent
commit
09c37f38ba
2 changed files with 18 additions and 5 deletions
  1. 10 5
      lc/model.py
  2. 8 0
      tests/model.py

+ 10 - 5
lc/model.py

@@ -3,7 +3,7 @@ import datetime
 from passlib.apps import custom_app_context as pwd
 import peewee
 import playhouse.shortcuts
-from typing import List, Optional, Tuple
+from typing import Iterator, List, Optional, Tuple
 
 import lc.config as c
 import lc.error as e
@@ -144,10 +144,9 @@ class Link(Model):
             user=user,
         )
         for tag_name in link.tags:
-            t = Tag.get_or_create_tag(user, tag_name)
-            HasTag.create(
-                link=l, tag=t,
-            )
+            tag = Tag.get_or_create_tag(user, tag_name)
+            for t in tag.get_family():
+                HasTag.get_or_create(link=l, tag=t)
         return l
 
     def update_from_request(self, user: User, link: r.Link):
@@ -222,6 +221,12 @@ class Tag(Model):
         )
         return links, pagination
 
+    def get_family(self) -> Iterator["Tag"]:
+        yield self
+        p = self
+        while (p := p.parent) :
+            yield p
+
     @staticmethod
     def is_valid_tag_name(tag_name: str) -> bool:
         return all((c.isalnum() or c == "/" for c in tag_name))

+ 8 - 0
tests/model.py

@@ -93,6 +93,14 @@ class Testdb:
         assert t.id == m.Tag.get(name="food/bread/rye").id
         assert t2.id == m.Tag.get(name="food/bread/baguette").id
 
+    def test_add_hierarchy(self):
+        u = self.mk_user()
+        req = r.Link("http://foo.com", "foo", "", False, ["food/bread/rye"])
+        l = m.Link.from_request(u, req)
+        assert l.name == req.name
+        tag_names = {t.tag.name for t in l.tags} # type: ignore
+        assert tag_names == {"food", "food/bread", "food/bread/rye"}
+
     def test_create_invite(self):
         u = self.mk_user()
         invite = m.UserInvite.manufacture(u)