diff frontends/src/jp/cmd_blog.py @ 2532:772447ec070f

jp: pubsub options refactoring: There is now only "use_pubsub", and specification are set using "pubsub_flags" argument when instantiating CommandBase. Options are more Python Zen compliant by using explicit arguments for item, draft, url instead of trying to guess with magic keyword and type detection. Pubsub node and item are now always using respecively "-n" and "-i" even when required, this way shell history can be used to change command more easily, and it's globally less confusing for user. if --pubsub-url is used, elements can be overwritten with individual option (e.g. change item id with --item). New "use_draft" argument in CommandBase, to re-use current draft or open a file path as draft. Item can now be specified when using a draft. If it already exists, its content will be added to current draft (with a separator), to avoid loosing data. common.BaseEdit.getItemPath could be simplified thanks to those changes. Pubsub URI handling has been moved to base.py.
author Goffi <goffi@goffi.org>
date Wed, 21 Mar 2018 19:13:22 +0100
parents 512c443a58ba
children dcc77f23e370
line wrap: on
line diff
--- a/frontends/src/jp/cmd_blog.py	Wed Mar 21 19:07:06 2018 +0100
+++ b/frontends/src/jp/cmd_blog.py	Wed Mar 21 19:13:22 2018 +0100
@@ -76,38 +76,28 @@
 OUTPUT_OPT_NO_HEADER = u'no-header'
 
 
-class BlogCommon(object):
-
-    def __init__(self, host):
-        self.host = host
-
-    def addServiceNodeArgs(self):
-        self.parser.add_argument("-n", "--node", type=base.unicode_decoder, default=u'', help=_(u"PubSub node to request (default: microblog namespace)"))
-        self.parser.add_argument("-s", "--service", type=base.unicode_decoder, default=u'', help=_(u"JID of the PubSub service (default: request profile own blog)"))
-
-    def guessSyntaxFromPath(self, sat_conf, path):
-        """Return syntax guessed according to filename extension
+def guessSyntaxFromPath(host, sat_conf, path):
+    """Return syntax guessed according to filename extension
 
-        @param sat_conf(ConfigParser.ConfigParser): instance opened on sat configuration
-        @param path(str): path to the content file
-        @return(unicode): syntax to use
-        """
-        # we first try to guess syntax with extension
-        ext = os.path.splitext(path)[1][1:] # we get extension without the '.'
-        if ext:
-            for k,v in SYNTAX_EXT.iteritems():
-                if k and ext == v:
-                    return k
+    @param sat_conf(ConfigParser.ConfigParser): instance opened on sat configuration
+    @param path(str): path to the content file
+    @return(unicode): syntax to use
+    """
+    # we first try to guess syntax with extension
+    ext = os.path.splitext(path)[1][1:] # we get extension without the '.'
+    if ext:
+        for k,v in SYNTAX_EXT.iteritems():
+            if k and ext == v:
+                return k
 
-        # if not found, we use current syntax
-        return self.host.bridge.getParamA("Syntax", "Composition", "value", self.profile)
+    # if not found, we use current syntax
+    return host.bridge.getParamA("Syntax", "Composition", "value", host.profile)
 
 
 class BlogPublishCommon(object):
     """handle common option for publising commands (Set and Edit)"""
 
     def add_parser_options(self):
-        self.addServiceNodeArgs()
         self.parser.add_argument("-T", '--title', type=base.unicode_decoder, help=_(u"title of the item"))
         self.parser.add_argument("-t", '--tag', type=base.unicode_decoder, action='append', help=_(u"tag (category) of your item"))
         self.parser.add_argument("-C", "--comments", action='store_true', help=_(u"enable comments"))
@@ -134,24 +124,22 @@
             mb_data['title'] = self.args.title
 
 
-class Set(base.CommandBase, BlogCommon, BlogPublishCommon):
+class Set(base.CommandBase, BlogPublishCommon):
 
     def __init__(self, host):
-        base.CommandBase.__init__(self, host, 'set', help=_(u'publish a new blog item or update an existing one'))
-        BlogCommon.__init__(self, self.host)
+        base.CommandBase.__init__(self, host, 'set', use_pubsub=True, pubsub_flags={C.SINGLE_ITEM},
+                                  help=_(u'publish a new blog item or update an existing one'))
         BlogPublishCommon.__init__(self)
         self.need_loop=True
 
     def add_parser_options(self):
         BlogPublishCommon.add_parser_options(self)
-        self.parser.add_argument("item", type=base.unicode_decoder, nargs='?', default=None, help=_(u"id of the item to publish"))
 
     def mbSendCb(self):
         self.disp(u"Item published")
         self.host.quit(C.EXIT_OK)
 
     def start(self):
-        common.checkURI(self.args)
         self.pubsub_item = self.args.item
         mb_data = {}
         self.setMbDataFromArgs(mb_data)
@@ -169,20 +157,17 @@
                             exit_code=C.EXIT_BRIDGE_ERRBACK))
 
 
-class Get(base.CommandBase, BlogCommon):
+class Get(base.CommandBase):
     TEMPLATE = u"blog/articles.html"
 
     def __init__(self, host):
         extra_outputs = {'default': self.default_output,
                          'fancy': self.fancy_output}
-        base.CommandBase.__init__(self, host, 'get', use_verbose=True, use_output=C.OUTPUT_COMPLEX, extra_outputs=extra_outputs, help=_(u'get blog item(s)'))
-        BlogCommon.__init__(self, self.host)
+        base.CommandBase.__init__(self, host, 'get', use_verbose=True, use_pubsub=True, pubsub_flags={C.MULTI_ITEMS},
+                                  use_output=C.OUTPUT_COMPLEX, extra_outputs=extra_outputs, help=_(u'get blog item(s)'))
         self.need_loop=True
 
     def add_parser_options(self):
-        self.addServiceNodeArgs()
-        self.parser.add_argument("-i", "--item", type=base.unicode_decoder, action='append', default=[], dest='items',
-                                 help=_(u"item(s) id(s) to get (default: request all items)"))
         self.parser.add_argument("-m", "--max", type=int, default=10, help=_(u"maximum number of items to get ({} to get all items)".format(C.NO_LIMIT)))
         # TODO: a key(s) argument to select keys to display
         self.parser.add_argument("-k", "--key", type=base.unicode_decoder, action='append', dest='keys',
@@ -339,7 +324,6 @@
         self.host.quit(C.EXIT_BRIDGE_ERRBACK)
 
     def start(self):
-        common.checkURI(self.args)
         self.host.bridge.mbGet(
             self.args.service,
             self.args.node,
@@ -351,19 +335,23 @@
             errback=self.mbGetEb)
 
 
-class Edit(base.CommandBase, BlogCommon, BlogPublishCommon, common.BaseEdit):
+class Edit(base.CommandBase, BlogPublishCommon, common.BaseEdit):
 
     def __init__(self, host):
-        base.CommandBase.__init__(self, host, 'edit', use_verbose=True, help=_(u'edit an existing or new blog post'))
-        BlogCommon.__init__(self, self.host)
+        base.CommandBase.__init__(self, host, 'edit', use_pubsub=True, pubsub_flags={C.SINGLE_ITEM},
+                                  use_draft=True, use_verbose=True, help=_(u'edit an existing or new blog post'))
         BlogPublishCommon.__init__(self)
         common.BaseEdit.__init__(self, self.host, BLOG_TMP_DIR, use_metadata=True)
 
+    @property
+    def current_syntax(self):
+        if self._current_syntax is None:
+            self._current_syntax = self.host.bridge.getParamA("Syntax", "Composition", "value", self.profile)
+        return self._current_syntax
+
     def add_parser_options(self):
         BlogPublishCommon.add_parser_options(self)
         self.parser.add_argument("-P", "--preview", action="store_true", help=_(u"launch a blog preview in parallel"))
-        self.parser.add_argument("item", type=base.unicode_decoder, nargs='?', default=u'new', help=_(u"URL of the item to edit, or keyword"))
-        common.BaseEdit.add_parser_options(self)
 
     def buildMetadataFile(self, content_file_path, mb_data=None):
         """Build a metadata file using json
@@ -436,8 +424,6 @@
 
     def getTmpSuff(self):
         # we get current syntax to determine file extension
-        if self.current_syntax is None:
-            self.current_syntax = self.host.bridge.getParamA("Syntax", "Composition", "value", self.profile)
         return SYNTAX_EXT.get(self.current_syntax, SYNTAX_EXT[''])
 
     def getItemData(self, service, node, item):
@@ -466,26 +452,26 @@
     def start(self):
         # if there are user defined extension, we use them
         SYNTAX_EXT.update(config.getConfig(self.sat_conf, 'jp', CONF_SYNTAX_EXT, {}))
-        self.current_syntax = self.args.syntax
-        if self.current_syntax is not None:
+        self._current_syntax = self.args.syntax
+        if self._current_syntax is not None:
             try:
-                self.current_syntax = self.args.syntax = self.host.bridge.syntaxGet(self.current_syntax)
+                self._current_syntax = self.args.syntax = self.host.bridge.syntaxGet(self.current_syntax)
             except Exception as e:
                 if "NotFound" in unicode(e):  # FIXME: there is not good way to check bridge errors
                     self.parser.error(_(u"unknown syntax requested ({syntax})").format(syntax=self.args.syntax))
                 else:
                     raise e
 
-        self.pubsub_service, self.pubsub_node, self.pubsub_item, content_file_path, content_file_obj, mb_data = self.getItemPath(self.args.item)
+        self.pubsub_service, self.pubsub_node, self.pubsub_item, content_file_path, content_file_obj, mb_data = self.getItemPath()
 
         self.edit(content_file_path, content_file_obj, mb_data=mb_data)
 
 
-class Preview(base.CommandBase, BlogCommon):
+class Preview(base.CommandBase):
+    # TODO: need to be rewritten with template output
 
     def __init__(self, host):
         base.CommandBase.__init__(self, host, 'preview', use_verbose=True, help=_(u'preview a blog content'))
-        BlogCommon.__init__(self, self.host)
 
     def add_parser_options(self):
         self.parser.add_argument("--inotify", type=str, choices=('auto', 'true', 'false'), default=u'auto', help=_(u"use inotify to handle preview"))
@@ -626,7 +612,7 @@
 
 class Import(base.CommandAnswering):
     def __init__(self, host):
-        super(Import, self).__init__(host, 'import', use_progress=True, help=_(u'import an external blog'))
+        super(Import, self).__init__(host, 'import', use_pubsub=True, use_progress=True, help=_(u'import an external blog'))
         self.need_loop=True
 
     def add_parser_options(self):
@@ -637,10 +623,6 @@
         self.parser.add_argument("--ignore-tls-errors", action="store_true", help=_("ignore invalide TLS certificate for uploads"))
         self.parser.add_argument('-o', '--option', action='append', nargs=2, default=[], metavar=(u'NAME', u'VALUE'),
             help=_(u"importer specific options (see importer description)"))
-        self.parser.add_argument('--service', type=base.unicode_decoder, default=u'', metavar=u'PUBSUB_SERVICE',
-            help=_(u"PubSub service where the items must be uploaded (default: server)"))
-        self.parser.add_argument('-n', '--node', type=base.unicode_decoder, default=u'', metavar=u'PUBSUB_NODE',
-            help=_(u"PubSub node where the items must be uploaded (default: tickets' defaults)"))
         self.parser.add_argument("location", type=base.unicode_decoder, nargs='?',
             help=_(u"importer data location (see importer description), nothing to show importer description"))