Esempio n. 1
0
    def _store_tree(self, tree):
        if tree and tree.hascontent:
            if self._meta is not None:
                tree.meta.update(self._meta)  # Preserver headers
            elif self.source_file.exists():
                # Try getting headers from file
                try:
                    text = self.source_file.read()
                except zim.newfs.FileNotFoundError:
                    return None
                else:
                    parser = self.format.Parser()
                    tree = parser.parse(text)
                    self._meta = tree.meta
                    tree.meta.update(self._meta)  # Preserver headers
            else:  # not self.source_file.exists()
                now = datetime.now()
                tree.meta['Creation-Date'] = now.isoformat()

            lines = self.format.Dumper().dump(tree, file_output=True)
            self._last_etag = self.source_file.writelines_with_etag(
                lines, self._last_etag)
            self._meta = tree.meta
        else:
            self.source_file.remove()
            self._last_etag = None
            self._meta = None
Esempio n. 2
0
    def _dump(self):
        '''Returns the page source'''
        tree = self.get_parsetree()
        if tree is None:
            raise AssertionError, 'BUG: Can not store a page without content'

        #~ print 'STORE', tree.tostring()
        if tree.hascontent:
            new = False
            if self.properties is None:
                self.properties = HeadersDict()
                new = True
            self.properties['Content-Type'] = 'text/x-zim-wiki'
            self.properties['Wiki-Format'] = WIKI_FORMAT_VERSION
            if new:
                now = datetime.now()
                self.properties['Creation-Date'] = now.isoformat()

            # Note: No "Modification-Date" here because it causes conflicts
            # when merging branches with version control, use mtime from filesystem
            # If we see this header, remove it because it will not be updated.
            try:
                del self.properties['Modification-Date']
            except:
                pass

            lines = self.properties.dump()
            lines.append('\n')
            lines.extend(self.format.Dumper().dump(tree))
            return lines
        else:
            return []
Esempio n. 3
0
	def __call__(self, dict, format, date=None):
		format = str(format) # Needed to please datetime.strftime()
		try:
			if date is None:
				date = datetime.now()
			return datetime.strfcal(format, date)
		except:
			logger.exception('Error in strftime "%s"', format)
Esempio n. 4
0
def template_strfcal(format, date=None):
    '''Template function wrapper for strfcal'''
    try:
        if date is None:
            date = datetime.now()
        return datetime.strfcal(format, date)
    except:
        logger.exception('Error in strftime "%s"', format)
Esempio n. 5
0
def template_strfcal(format, date=None):
	'''Template function wrapper for strfcal'''
	try:
		if date is None:
			date = datetime.now()
		return datetime.strfcal(format, date)
	except:
		logger.exception('Error in strftime "%s"', format)
Esempio n. 6
0
 def __call__(self, dict, format, date=None):
     format = str(format)  # Needed to please datetime.strftime()
     try:
         if date is None:
             date = datetime.now()
         return datetime.strfcal(format, date)
     except:
         logger.exception('Error in strftime "%s"', format)
Esempio n. 7
0
	def _store_tree(self, tree):
		if tree and tree.hascontent:
			if not self.source_file.exists():
				# New page
				now = datetime.now()
				tree.meta['Creation-Date'] = now.isoformat()

			lines = self.format.Dumper().dump(tree, file_output=True)
			self._last_etag = self.source_file.writelines_with_etag(lines, self._last_etag)
		else:
			self.source_file.remove()
			self._last_etag = None
Esempio n. 8
0
    def runTest(self):
        # now()
        dt = datetime.now()
        s = dt.isoformat()
        self.assertTrue(isinstance(s, str) and len(s) > 0)

        s = dt.strftime("%z")
        self.assertTrue(isinstance(s, str) and len(s) > 0)

        s = dt.strftime("%Z")
        self.assertTrue(isinstance(s, str) and len(s) > 0)

        # strftime
        s = datetime.strftime('%a', dt)
        self.assertTrue(isinstance(s, str) and len(s) > 0)

        s = datetime.strftime('%%', dt)
        self.assertEqual(s, '%')

        # Failed under msys python3.7.2
        #s = datetime.strftime('%u', dt)
        #self.assertTrue(isinstance(s, str) and len(s) > 0)

        #s = datetime.strftime('%V', dt)
        #self.assertTrue(isinstance(s, str) and len(s) > 0)

        # strfcal
        s = datetime.strfcal('%w', dt)
        self.assertTrue(isinstance(s, str) and len(s) > 0)

        s = datetime.strfcal('%W', dt)
        self.assertTrue(isinstance(s, str) and len(s) > 0)

        s = datetime.strfcal('%Y', dt)
        self.assertTrue(isinstance(s, str) and len(s) > 0)

        s = datetime.strfcal('%%', dt)
        self.assertEqual(s, '%')

        # weekcalendar
        year, week, weekday = datetime.weekcalendar(dt)
        self.assertTrue(isinstance(year, int) and 1900 < year and 3000 > year)
        self.assertTrue(isinstance(week, int) and 1 <= week and 53 >= week)
        self.assertTrue(
            isinstance(weekday, int) and 1 <= weekday and 7 >= weekday)

        # dates_for_week
        start, end = datetime.dates_for_week(year, week)
        self.assertTrue(isinstance(start, datetime.date))
        self.assertTrue(isinstance(end, datetime.date))
        self.assertTrue(start <= dt.date() and end >= dt.date())
Esempio n. 9
0
	def _store_tree(self, tree):
		if tree and tree.hascontent:
			if self._meta is not None:
				tree.meta.update(self._meta) # Preserver headers
			elif self.source_file.exists():
				# Try getting headers from file
				try:
					text = self.source_file.read()
				except zim.newfs.FileNotFoundError:
					return None
				else:
					parser = self.format.Parser()
					tree = parser.parse(text)
					self._meta = tree.meta
					tree.meta.update(self._meta) # Preserver headers
			else: # not self.source_file.exists()
				now = datetime.now()
				tree.meta['Creation-Date'] = now.isoformat()

			lines = self.format.Dumper().dump(tree, file_output=True)

			try:  #save new lines on disk
				logger.debug('Saving page')
				self._last_etag = self.source_file.writelines_with_etag(lines, self._last_etag)
				self._store_last_lines(lines)
			except zim.newfs.FileChangedError as fserror: #Catch case where file has been changed
				logger.debug('File changed on disk')
				if self._automerge :
					logger.debug('Saving will be made through merging')
					self._refresh_view_merge_changes()
					#lines = self.format.Dumper().dump(self.get_parsetree(), file_output=True)
					try:
						logger.debug('FILE IS BEING SAVED AGAIN with updated etags and content')
						if self._last_lines is None:
							self._last_etag = self.source_file.writelines_with_etag(
									self.format.Dumper().dump(self.get_parsetree(),file_output=True), self._last_etag)
						else:
							self._last_etag = self.source_file.writelines_with_etag(self._last_lines, self._last_etag)

					except zim.newfs.FileChangedError as fserror:
						logger.error('FILE STILL IN CONFLICT!!!')
						raise fserror
				else:
					raise fserror

			#self._store_last_lines(self.format.Dumper().dump(self.get_parsetree(),file_output=True))
			self._meta = tree.meta
		else:
			self.source_file.remove()
			self._last_etag = None
			self._meta = None
Esempio n. 10
0
	def runTest(self):
		# now()
		dt = datetime.now()
		s = dt.isoformat()
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		s = dt.strftime("%z")
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		s = dt.strftime("%Z")
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		# strftime
		s = datetime.strftime('%a', dt)
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		s = datetime.strftime('%%', dt)
		self.assertEqual(s, '%')

		s = datetime.strftime('%u', dt)
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		s = datetime.strftime('%V', dt)
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		# strfcal
		s = datetime.strfcal('%w', dt)
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		s = datetime.strfcal('%W', dt)
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		s = datetime.strfcal('%Y', dt)
		self.assertTrue(isinstance(s, basestring) and len(s) > 0)

		s = datetime.strfcal('%%', dt)
		self.assertEqual(s, '%')

		# weekcalendar
		year, week, weekday = datetime.weekcalendar(dt)
		self.assertTrue(isinstance(year, int) and 1900 < year and 3000 > year)
		self.assertTrue(isinstance(week, int) and 1 <= week and 53 >= week)
		self.assertTrue(isinstance(weekday, int) and 1 <= weekday and 7 >= weekday)

		# dates_for_week
		start, end = datetime.dates_for_week(year, week)
		self.assertTrue(isinstance(start, datetime.date))
		self.assertTrue(isinstance(end, datetime.date))
		self.assertTrue(start <= dt.date() and end >= dt.date())
Esempio n. 11
0
	def __call__(self, dict, format, date=None):
		format = str(format) # Needed to please datetime.strftime()
		try:
			if date is None:
				string = datetime.now().strftime(format)
			elif isinstance(date, (datetime.date, datetime.datetime)):
				string = date.strftime(format)
			else:
				raise Error, 'Not a datetime object: %s' % date
			return string.decode(locale.getpreferredencoding())
				# strftime returns locale as understood by the C api
				# unfortunately there is no guarantee we can actually
				# decode it ...
		except:
			logger.exception('Error in strftime "%s"', format)
Esempio n. 12
0
 def __call__(self, dict, format, date=None):
     format = str(format)  # Needed to please datetime.strftime()
     try:
         if date is None:
             string = datetime.now().strftime(format)
         elif isinstance(date, (datetime.date, datetime.datetime)):
             string = date.strftime(format)
         else:
             raise Error, 'Not a datetime object: %s' % date
         return string.decode(locale.getpreferredencoding())
         # strftime returns locale as understood by the C api
         # unfortunately there is no guarantee we can actually
         # decode it ...
     except:
         logger.exception('Error in strftime "%s"', format)
Esempio n. 13
0
def template_strftime(format, date=None):
    '''Template function wrapper for strftime'''
    try:
        if date is None:
            string = datetime.strftime(format, datetime.now())
        elif isinstance(date, (datetime.date, datetime.datetime)):
            string = datetime.strftime(format, date)
        else:
            raise Error, 'Not a datetime object: %s' % date

        # strftime returns locale as understood by the C api
        # unfortunately there is no guarantee we can actually
        # decode it ...
        return string
    except:
        logger.exception('Error in strftime "%s"', format)
Esempio n. 14
0
def template_strftime(format, date=None):
	'''Template function wrapper for strftime'''
	try:
		if date is None:
			string = datetime.strftime(format, datetime.now())
		elif isinstance(date, (datetime.date, datetime.datetime)):
			string = datetime.strftime(format, date)
		else:
			raise Error, 'Not a datetime object: %s' % date

		# strftime returns locale as understood by the C api
		# unfortunately there is no guarantee we can actually
		# decode it ...
		return string
	except:
		logger.exception('Error in strftime "%s"', format)
Esempio n. 15
0
    def get_data_as_page(self, me):
        """ Opcion de exportacion
        """

        zPages = {}
        myTag = ''
        myCode = ''

        self.do_delete_QDA()

        sWhere = self._getWStmt(self.plugin.preferences['export_only'] or self.plugin.preferences['labels'])
        sOrder = 'tag, description, source, citnumber'

        for row in self.plugin.list_codes(parent=None, orderBy=sOrder, whereStmt=sWhere):

            path = self.plugin.get_path(row)
            if path is None: continue

            # Format description
            tag = row['tag'].decode('utf-8')
            code = row['description'].decode('utf-8')
            source = path.name
            nroCita = "{0:03d}".format(row['citnumber'])

            # Break by Tag
            if tag != myTag:
                myTag = tag
                zPages[ myTag ] = '====== {} ======\n'.format(tag)
                zPages[ myTag ] += 'Created {} \n\n'.format(datetime.now().isoformat())

            # Break by Code
            if code != myCode:
                myCode = code
                zPages[ myTag ] += '===== {} =====\n\n'.format(code)

            # Break by Page
            zPages[ myTag ] += '[[{0}]]  **{1}**\n'.format(source, nroCita)
            zPages[ myTag ] += '{}\n\n'.format(row['citation'].decode('utf-8'))


        masterPageIx = '====== Summary ======\nCreated: {}\n\n'.format(datetime.now().isoformat())

        masterPath = self.plugin.preferences['namespace']
        for tag in zPages:
            zPage = zPages[ tag ]
            newpage = self.plugin.ui.new_page_from_text(zPage , '{0}:{1}'.format(masterPath, tag)  , open_page=False)

            masterPageIx += '[[{}]]\n'.format(newpage.name)

        masterPageIx += '\n'

        self.plugin.ui.append_text_to_page(masterPath , masterPageIx)

        # TOC
        if self.plugin.preferences['table_of_contents'] :
            self.do_table_of_contents()
            self.do_code_detail( True )
            self.do_code_detail( False )

        # Open de index page ( QDA Namespace root )
        newpage = Path(masterPath)
        self.ui.open_page(newpage)
Esempio n. 16
0
    def do_exportQdaTags(self):

        zPages = {}
        myTag = ''
        myCode = ''

        # Borra el Namespace de exportacion
        masterPath = self.qda.plugin.preferences['namespace_qda']
        self.qda.plugin.ui.delete_page(Path(masterPath)) 


        sWhere = self.qda._getWStmt(self.qda.plugin.preferences['qda_labels'])
        sOrder = 'tag, description, source, citnumber'

        for row in self.qda.plugin.list_codes(parent=None, orderBy=sOrder, whereStmt=sWhere):

            path = self.qda.plugin.get_path(row)
            if path is None: continue

            # Format description
            tag = row['tag'].decode('utf-8')
            code = row['description'].decode('utf-8')
            source = path.name
            nroCita = "{0:03d}".format(row['citnumber'])

            # Break by Tag
            if tag != myTag:
                myTag = tag
                zPages[ myTag ] = '====== {} ======\n'.format(tag)
                zPages[ myTag ] += 'Created {} \n\n'.format(datetime.now().isoformat())

            # Break by Code
            try:
                if code != myCode:
                    myCode = code
                    zPages[ myTag ] += '===== {} =====\n\n'.format(code)
            except: 
                pass 


            # Break by Page
            try: 
                zPages[ myTag ] += '__{0}__  {1}\n'.format(source, nroCita)
                zPages[ myTag ] += '{}\n\n'.format(row['citation'].decode('utf-8'))
            except: 
                pass 


        masterPageIx = '====== Summary ======\nCreated: {}\n\n'.format(datetime.now().isoformat())

        masterPath = self.qda.plugin.preferences['namespace_qda']
        for tag in zPages:
            zPage = zPages[ tag ]
            newpage = self.qda.plugin.ui.new_page_from_text(zPage,'{0}:CODE-{1}'.format(masterPath, sluglify(tag), open_page=False))
            pagename = newpage.name
            
            # Se asegura q sea absoluto ( issue  Win - Linux ) 
            if pagename[0] != ':' : pagename = ':' + pagename 
            masterPageIx += '__{}__\n'.format(pagename)

        masterPageIx += '\n'

        self.qda.plugin.ui.append_text_to_page(masterPath , masterPageIx)