python3 fork piksemel

This commit is contained in:
Erkan IŞIK
2025-10-09 23:47:03 +03:00
commit 914b951029
14 changed files with 4788 additions and 0 deletions
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+202
View File
@@ -0,0 +1,202 @@
# Piksemel 2.0
Python XML API based on the iksemel library.
Copyright (C) 2005-2006 TUBITAK/UEKAE, 2019 Safa Arıman, 2020 Erdem Ersoy, 2022 Ersoy Kardesler
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version. Please read the COPYING file.
# Install
You don't need anything other than an installed Python 3 framework (Python 3.6+).
iksemel-lite source is included and compiled built-in to the module.
To compile and install:
```bash
python3 setup.py install
```
Or using pip:
```bash
pip3 install .
```
then you can import the piksemel module in your python programs.
# Documentation
## Module Constants
* TAG
* ATTRIBUTE
* DATA
These enumeration constants are used to report the type of the Node objects.
## Module Exceptions
### ParseError
Raised when given string or file contains invalid XML.
### NotTag
Raised when a function accepting a tag node got another type of object.
### NotData
Raised when a function accepting a data node got another type of object.
## Module Functions
### parse(filename)
Parses the given XML file, and returns the top level tag's node object.
### parseString(string)
Parses the given XML string and returns the top level tag's node object.
### newDocument(tagname)
Creates a new top level tag node object with given tag name.
## Module Objects
### Node
This object represents a node of the XML document tree. If you iterate
over a node object, you'll get the list of its child nodes.
## Node Object Methods
### type()
Returns the type of the node.
### data()
Returns character data for data nodes.
### name()
Returns the name of the tag for tag nodes.
### attributes()
Returns a list of node's attribute names. Returns an empty list
if there aren't any.
### getAttribute(attributename)
Returns the value of the given attribute for tag nodes. If such
an attribute doesn't exists, returns None.
### setAttribute(attributename, value)
Sets the given attribute's value for tag nodes. You can give
the value None for deleting an attribute.
### getTag(tagname)
Returns the first tag node child with the given name. If such a child
doesn't exists, returns None.
### getTagData(tagname)
Returns the contained character data from first tag node child with the
given name.
### tags(tagname=None)
Iterates over child tag nodes. If optional tagname is given, only
iterates over tags with the given name.
### firstChild()
Returns the first child node.
### parent()
Returns the parent node.
### root()
Returns the top level node.
### next()
Returns the next node. If this is the last sibling, returns None.
### nextTag(tagname=None)
Returns the next tag node. If optional tagname is given, returns the
next sibling tag node with the given name. Returns None if this is
the last such sibling.
### previous()
Returns the previous node. If this is the first sibling, returns None.
### previousTag(tagname=None)
Returns the previous tag node. If optional tagname is given, returns
the previous sibling tag node with the given name. Returns None if
this is the first such sibling.
### insertTag(tagname)
Inserts a new child tag node with given name to the child nodes.
Returns the newly created tag node object.
### insertData(data)
Inserts given character data to the child nodes. Returns the newly
created data node object.
### setData(data)
Deletes given tag's current child nodes, then inserts the data as
its child.
### insertNode(node)
Inserts given node tree to the child nodes. Returns the newly created
node object.
### appendTag(tagname)
Create a tag node with given name and append it as the next sibling.
Returns the newly created tag node object.
### appendData(data)
Appends given character data as the next sibling. Returns the newly
created data node object.
### prependTag(tagname)
Create a tag node with given name and append it as the previous
sibling. Returns the newly created tag node object.
### prependData(data)
Prepends given character data as the previous sibling. Returns the
newly created data node object.
### hide()
Deletes the node from document tree.
### toString()
Returns the XML string representation of node tree.
### toPrettyString()
Returns the XML string representation of node tree. Line feeds and
tabs are inserted into the document to make it look pretty.
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
import piksemel
import sys
def generate_hourly_stats(log, name=None):
hours = {}
total = 0
for item in log.tags("logentry"):
if name and item.getTagData("author") != name:
pass
else:
hour = int(item.getTagData("date")[11:13])
hours[hour] = hours.get(hour, 0) + 1
total += 1
for hour in range(0, 24):
print("%d: %d commit" % (hour, hours.get(hour, 0)))
print("total of %d commits" % total)
doc = piksemel.parse(sys.argv[1])
if len(sys.argv) == 3:
generate_hourly_stats(doc, sys.argv[2])
else:
generate_hourly_stats(doc)
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
import sys
import piksemel as iks
import xml.dom.minidom as mini
from Ft.Xml.Domlette import NoExtDtdReader
import Ft.Lib
import timeit
def piksor(name):
a = iks.parse(name)
total = 0
for b in a.tags():
size = b.getTagData("Size")
if size:
size = size.strip()
total += int(size)
def cdom(name):
doc = NoExtDtdReader.parseUri(Ft.Lib.Uri.OsPathToUri(name))
def suxor(name):
a = mini.parse(name)
if __name__ == "__main__":
name = sys.argv[1]
a = timeit.Timer('piksor("%s")' % name, "from __main__ import piksor")
b = timeit.Timer('cdom("%s")' % name, "from __main__ import cdom")
c = timeit.Timer('suxor("%s")' % name, "from __main__ import suxor")
print("piksemel", a.timeit(1))
print("cdom", b.timeit(1))
print("minidom", c.timeit(1))
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006 TUBITAK/UEKAE, 2019 Safa Arıman, 2020 Erdem Ersoy
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version. Please read the COPYING file.
#
import sys
import os
import glob
import shutil
import subprocess
from setuptools import setup, Extension
version = '2.0a1'
distfiles = """
README.md
setup.py
src/iksemel.c
src/iksemel.h
src/pyiks.c
tests/*.py
"""
if 'sdist' in sys.argv:
distdir = "piksemel-%s" % version
filelist = []
for t in distfiles.split():
filelist.extend(glob.glob(t))
if os.path.exists(distdir):
shutil.rmtree(distdir)
os.mkdir(distdir)
for file_ in filelist:
cum = distdir[:]
for d in os.path.dirname(file_).split('/'):
dn = os.path.join(cum, d)
cum = dn[:]
if not os.path.exists(dn):
os.mkdir(dn)
shutil.copy(file_, os.path.join(distdir, file_))
subprocess.run(["tar", "czf", "piksemel-" + version + ".tar.gz", distdir])
shutil.rmtree(distdir)
sys.exit(0)
elif 'test' in sys.argv:
fail = 0
for test in os.listdir("tests"):
if test.endswith(".py"):
if 0 != subprocess.call(["tests/" + test]):
fail += 1
print(test, "failed!")
if not fail:
print("all tests passed :)")
sys.exit(0)
sys.exit(1)
setup(
name='piksemel',
version=version,
author='TUBITAK/UEKAE, Safa Arıman, Erdem Ersoy, Ersoy Kardesler',
description='Python XML API based on the iksemel library',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
ext_modules=[
Extension(
'piksemel',
sources=['src/iksemel.c', 'src/pyiks.c'],
extra_compile_args=["-fvisibility=default"]
)
],
python_requires='>=3.6',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v2 (GPLv2)',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: C',
'Topic :: Text Processing :: Markup :: XML',
],
)
+383
View File
@@ -0,0 +1,383 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2007, TUBITAK/UEKAE
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version. Please read the COPYING file.
#
import piksemel
import inspect
import locale
# Global counter for keeping tag order
_autoPiksCounter = 0
# Enumerations
multiple, optional = list(range(1, 3))
class InvalidDocument(Exception):
"""Validation error while reading XML data."""
pass
class CharacterData:
"""Maps character data of the XML node into a variable."""
def parse(self, ctx, doc):
node = doc.firstChild()
if node.type() != piksemel.DATA or next(node) is not None:
ctx.error("this tag should only contain character data")
else:
ctx.use(self.varname, node.data())
def serialize(self, inst, doc):
doc.insertData(getattr(inst, self.varname))
class Attribute:
"""Maps an attribute of the XML node into a variable."""
def __init__(self, attrname, *args):
self.name = attrname
self.is_optional = False
self.choices = None
for arg in args:
if arg == optional:
self.is_optional = True
elif isinstance(arg, (tuple, list)):
self.choices = arg
else:
raise TypeError("Unknown argument '%s'" % arg)
def parse(self, ctx, doc):
value = doc.getAttribute(self.name)
if not self.is_optional and value == None:
ctx.error("required attribute '%s' is missing" % self.name)
if value and self.choices and not value in self.choices:
ctx.error("keyword '%s' is not accepted for attribute '%s'" % (value, self.name))
ctx.use(self.varname, value)
def serialize(self, inst, doc):
val = getattr(inst, self.varname)
if val:
doc.setAttribute(self.name, val)
class Tag:
"""Maps a child tag's data of the XML node into a variable."""
def __init__(self, tagname, *args):
global _autoPiksCounter
self.order = _autoPiksCounter
_autoPiksCounter += 1
self.name = tagname
self.is_optional = False
self.is_multiple = False
self.sub = None
for arg in args:
if arg == optional:
self.is_optional = True
elif arg == multiple:
self.is_multiple = True
elif issubclass(arg, AutoXML):
self.sub = arg
else:
raise TypeError("Unknown argument '%s'" % arg)
def parse(self, ctx, doc):
tags = list(doc.tags(self.name))
if not self.is_optional and len(tags) == 0:
ctx.error("missing tag <%s>" % self.name)
return
if not self.is_multiple and len(tags) > 1:
ctx.error("tag <%s> should not appear more than once" % self.name)
return
old_doc = ctx.doc
vals = []
for tag in tags:
ctx.doc = tag
if self.sub:
c = self.sub()
old_inst = ctx.inst
ctx.inst = c
c._autoPiksParse(ctx, tag)
ctx.inst = old_inst
vals.append(c)
else:
node = tag.firstChild()
if node.type() != piksemel.DATA or next(node) is not None:
ctx.error("this tag should only contain character data")
else:
vals.append(node.data())
if not self.is_multiple:
if len(vals) > 0:
vals = vals[0]
else:
vals = None
ctx.use(self.varname, vals)
ctx.doc = old_doc
def serialize(self, inst, doc):
vals = getattr(inst, self.varname)
if not vals:
return
if not self.is_multiple:
vals = [vals]
for val in vals:
tag = doc.insertTag(self.name)
if self.sub:
val.toString(tag)
else:
if val:
tag.insertData(val)
class TagCollection:
"""Maps a collection of child tags of the XML node into a variable."""
def __init__(self, tagname, kidname, *args):
global _autoPiksCounter
self.order = _autoPiksCounter
_autoPiksCounter += 1
self.name = tagname
self.kidname = kidname
self.is_optional = False
self.sub = None
for arg in args:
if arg == optional:
self.is_optional = True
elif issubclass(arg, AutoXML):
self.sub = arg
else:
raise TypeError("Unknown argument '%s'" % arg)
def parse(self, ctx, doc):
tags = list(doc.tags(self.name))
if len(tags) == 0:
if not self.is_optional:
ctx.error("missing tag <%s>" % self.name)
ctx.use(self.varname, [])
return
if len(tags) > 1:
ctx.error("tag <%s> should not appear more than once" % self.name)
return
tags = list(tags[0].tags())
old_doc = ctx.doc
vals = []
for tag in tags:
ctx.doc = tag
if tag.name() != self.kidname:
ctx.error("this is a collection of <%s> tags, not <%s>" % (self.kidname, tag.name()))
if self.sub:
c = self.sub()
old_inst = ctx.inst
ctx.inst = c
c._autoPiksParse(ctx, tag)
ctx.inst = old_inst
vals.append(c)
else:
node = tag.firstChild()
if node.type() != piksemel.DATA or next(node) is not None:
ctx.error("this tag should only contain character data")
else:
vals.append(node.data())
ctx.use(self.varname, vals)
ctx.doc = old_doc
def serialize(self, inst, doc):
vals = getattr(inst, self.varname)
if not vals:
return
parent = doc.insertTag(self.name)
for val in vals:
tag = parent.insertTag(self.kidname)
if self.sub:
val.toString(tag)
else:
if val:
tag.insertData(val)
class LocalText(dict):
@staticmethod
def get_lang():
lang, enc = locale.getlocale()
if not lang:
lang, enc = locale.getdefaultlocale()
if not lang:
return "en"
return lang[:2]
def __str__(self):
lang = self.get_lang()
# Return text for current language
t = self.get(lang, None)
if t:
return t
# Fallback to English
t = self.get("en", None)
if t:
return t
# Fallback to anything
if len(self) > 0:
return self[0]
return str()
class TagLocalized:
"""Maps the translated tags of the XML node into a dictionary variable."""
def __init__(self, tagname, opt=None):
global _autoPiksCounter
self.order = _autoPiksCounter
_autoPiksCounter += 1
self.name = tagname
self.is_optional = False
if opt == optional:
self.is_optional = True
def parse(self, ctx, doc):
tags = list(doc.tags(self.name))
if not self.is_optional and len(tags) == 0:
ctx.error("missing tag <%s>" % self.name)
return
val = LocalText()
for tag in tags:
lang = tag.getAttribute("xml:lang")
if not lang:
lang = "en"
node = tag.firstChild()
if node.type() != piksemel.DATA or next(node) is not None:
ctx.error("%s: Localized tag should only contain character data" % self.name)
else:
if lang in val:
ctx.error("%s: Duplicate translation for language %s" % (self.name, lang))
data = node.data()
val[lang] = data
ctx.use(self.varname, val)
def serialize(self, inst, doc):
val = getattr(inst, self.varname)
if not val:
return
langs = list(val.keys())
langs.sort()
for lang in langs:
tag = doc.insertTag(self.name)
if lang != "en":
tag.setAttribute("xml:lang", lang)
tag.insertData(val[lang])
class AutoPiksemelContext:
"""Utility class for passing parameters between validation functions."""
def __init__(self, inst):
self.inst = inst
self.errors = []
self.doc = None
def error(self, message):
path = []
doc = self.doc
while doc:
path.append(doc.name())
doc = doc.parent()
path.reverse()
self.errors.append("%s: %s" % ("/".join(path), message))
def use(self, varname, value):
setattr(self.inst, varname, value)
class AutoXML:
"""Automatic XML <-> Class attributes converter with validation."""
def __init__(self, root_tag=None, path=None, xmlstring=None):
self.root_tag = root_tag
doc = None
if path:
if xmlstring:
raise TypeError("Dont use both path and xmlstring in AutoPiksemel()")
doc = piksemel.parse(path)
elif xmlstring:
doc = piksemel.parseString(xmlstring)
if doc:
if doc.name() != root_tag:
err = "Root tag does not match: %s != %s" % (root_tag, doc.name())
raise InvalidDocument(err)
ctx = AutoPiksemelContext(self)
ctx.doc = doc
self._autoPiksParse(ctx, doc)
if len(ctx.errors) > 0:
raise InvalidDocument("\n".join(ctx.errors))
def _autoPiksScan(self):
"""Scan XML<->Class mappings and return indexed objects."""
# Generated data is cached as a Class variable
defs = getattr(self.__class__, "_autoPiksDefs", None)
if not defs:
members = inspect.getmembers(self.__class__)
cdata = None
attrs = {}
tags = {}
for name, obj in members:
if isinstance(obj, CharacterData):
cdata = obj
obj.varname = name
elif isinstance(obj, Attribute):
attrs[obj.name] = obj
obj.varname = name
elif isinstance(obj, (Tag, TagCollection, TagLocalized)):
tags[obj.name] = obj
obj.varname = name
if cdata and len(tags) > 0:
raise TypeError("Class %s defined both CharacterData() and Tag()s" % self.__class__)
defs = (cdata, attrs, tags)
self.__class__._autoPiksDefs = defs
return defs
def _autoPiksParse(self, ctx, doc):
"""Convert XML data to class attributes."""
cdata, attrs, tags = self._autoPiksScan()
# Check character data
if cdata:
cdata.parse(ctx, doc)
# Check attributes
for key in doc.attributes():
if not key in attrs:
ctx.error("unknown attribute '%s'" % key)
for obj in list(attrs.values()):
obj.parse(ctx, doc)
# Check tags
for tag in doc.tags():
if not tag.name() in tags:
ctx.error("unknown tag <%s>" % tag.name())
for obj in list(tags.values()):
obj.parse(ctx, doc)
# Custom validation
if len(ctx.errors) == 0:
# Since validater functions access members without checking
# we dont call them if there is already an error.
validate_func = getattr(self, "validate", None)
if validate_func:
validate_func(ctx)
def toString(self, doc=None):
if not doc:
doc = piksemel.newDocument(self.root_tag)
self.toString(doc)
return doc.toPrettyString()
cdata, attrs, tags = self._autoPiksScan()
attrs = list(attrs.values())
attrs.sort(key=lambda x: x.varname)
tags = list(tags.values())
tags.sort(key=lambda x: x.order)
for attr in attrs:
attr.serialize(self, doc)
if cdata:
cdata.serialize(self, doc)
else:
for tag in tags:
tag.serialize(self, doc)
+1997
View File
File diff suppressed because it is too large Load Diff
+407
View File
@@ -0,0 +1,407 @@
/* iksemel (XML parser for Jabber)
** Copyright (C) 2000-2004 Gurer Ozen <madcat@e-kolay.net>
** This code is free software; you can redistribute it and/or
** modify it under the terms of GNU Lesser General Public License.
*/
#ifndef IKSEMEL_H
#define IKSEMEL_H 1
#ifdef __cplusplus
#include <cstddef> /* size_t for C++ */
extern "C" {
#else
#include <stddef.h> /* size_t for C */
#endif
/***** object stack *****/
struct ikstack_struct;
typedef struct ikstack_struct ikstack;
ikstack *iks_stack_new (size_t meta_chunk, size_t data_chunk);
void *iks_stack_alloc (ikstack *s, size_t size);
char *iks_stack_strdup (ikstack *s, const char *src, size_t len);
char *iks_stack_strcat (ikstack *s, char *old, size_t old_len, const char *src, size_t src_len);
void iks_stack_stat (ikstack *s, size_t *allocated, size_t *used);
void iks_stack_delete (ikstack *s);
/***** utilities *****/
void *iks_malloc (size_t size);
void iks_free (void *ptr);
void iks_set_mem_funcs (void *(*malloc_func)(size_t size), void (*free_func)(void *ptr));
char *iks_strdup (const char *src);
char *iks_strcat (char *dest, const char *src);
int iks_strcmp (const char *a, const char *b);
int iks_strcasecmp (const char *a, const char *b);
int iks_strncmp (const char *a, const char *b, size_t n);
int iks_strncasecmp (const char *a, const char *b, size_t n);
size_t iks_strlen (const char *src);
char *iks_escape (ikstack *s, char *src, size_t len);
char *iks_unescape (ikstack *s, char *src, size_t len);
/***** dom tree *****/
enum ikstype {
IKS_NONE = 0,
IKS_TAG,
IKS_ATTRIBUTE,
IKS_CDATA
};
struct iks_struct;
typedef struct iks_struct iks;
iks *iks_new (const char *name);
iks *iks_new_within (const char *name, ikstack *s);
iks *iks_insert (iks *x, const char *name);
iks *iks_insert_sibling (iks *x, const char *name);
iks *iks_prepend(iks *x, const char *name);
iks *iks_insert_cdata (iks *x, const char *data, size_t len);
iks *iks_append_cdata(iks *x, const char *data, size_t len);
iks *iks_prepend_cdata(iks *x, const char *data, size_t len);
iks *iks_set_cdata(iks *x, const char *data, size_t len);
iks *iks_insert_attrib (iks *x, const char *name, const char *value);
iks *iks_insert_node (iks *x, iks *y);
void iks_hide (iks *x);
void iks_delete (iks *x);
iks *iks_next (iks *x);
iks *iks_next_tag (iks *x);
iks *iks_prev (iks *x);
iks *iks_prev_tag (iks *x);
iks *iks_parent (iks *x);
iks *iks_root (iks *x);
iks *iks_child (iks *x);
iks *iks_first_tag (iks *x);
iks *iks_attrib (iks *x);
iks *iks_find (iks *x, const char *name);
char *iks_find_cdata (iks *x, const char *name);
char *iks_find_attrib (iks *x, const char *name);
iks *iks_find_with_attrib (iks *x, const char *tagname, const char *attrname, const char *value);
ikstack *iks_stack (iks *x);
enum ikstype iks_type (iks *x);
char *iks_name (iks *x);
char *iks_cdata (iks *x);
size_t iks_cdata_size (iks *x);
int iks_has_children (iks *x);
int iks_has_attribs (iks *x);
char *iks_string (ikstack *s, iks *x);
iks *iks_copy (iks *x);
iks *iks_copy_within (iks *x, ikstack *s);
/***** sax parser *****/
enum ikserror {
IKS_OK = 0,
IKS_NOMEM,
IKS_BADXML,
IKS_HOOK
};
enum ikstagtype {
IKS_OPEN,
IKS_CLOSE,
IKS_SINGLE
};
typedef int (iksTagHook)(void *user_data, char *name, char **atts, int type);
typedef int (iksCDataHook)(void *user_data, char *data, size_t len);
typedef void (iksDeleteHook)(void *user_data);
struct iksparser_struct;
typedef struct iksparser_struct iksparser;
iksparser *iks_sax_new (void *user_data, iksTagHook *tagHook, iksCDataHook *cdataHook);
iksparser *iks_sax_extend (ikstack *s, void *user_data, iksTagHook *tagHook, iksCDataHook *cdataHook, iksDeleteHook *deleteHook);
ikstack *iks_parser_stack (iksparser *prs);
void *iks_user_data (iksparser *prs);
unsigned long iks_nr_bytes (iksparser *prs);
unsigned long iks_nr_lines (iksparser *prs);
int iks_parse (iksparser *prs, const char *data, size_t len, int finish);
void iks_parser_reset (iksparser *prs);
void iks_parser_delete (iksparser *prs);
/***** dom parser *****/
enum iksfileerror {
IKS_FILE_NOFILE = 4,
IKS_FILE_NOACCESS,
IKS_FILE_RWERR
};
iksparser *iks_dom_new (iks **iksptr);
void iks_set_size_hint (iksparser *prs, size_t approx_size);
iks *iks_tree (const char *xml_str, size_t len, int *err);
int iks_load (const char *fname, iks **xptr);
int iks_save (const char *fname, iks *x);
/***** transport layer *****/
typedef void (iksTClose)(void *socket);
typedef int (iksTConnect)(iksparser *prs, void **socketptr, const char *server, int port);
typedef int (iksTSend)(void *socket, const char *data, size_t len);
typedef int (iksTRecv)(void *socket, char *buffer, size_t buf_len, int timeout);
typedef int (iksTConnectFD)(iksparser *prs, void **socketptr, void *fd);
typedef void *(iksTGetFD)(void *socket);
enum iksasyncevents {
IKS_ASYNC_RESOLVED,
IKS_ASYNC_CONNECTED,
IKS_ASYNC_WRITE,
IKS_ASYNC_WRITTEN,
IKS_ASYNC_READ,
IKS_ASYNC_CLOSED,
IKS_ASYNC_ERROR
};
typedef int (iksAsyncNotify)(void *user_data, int event, void *event_data);
typedef int (iksTConnectAsync)(iksparser *prs, void **socketptr, const char *server, int port, void *notify_data, iksAsyncNotify *notify_func);
typedef struct ikstransport_struct {
/* basic api, connect can be NULL if one of the other connect funcs are used */
iksTConnect *connect;
iksTSend *send;
iksTRecv *recv;
iksTClose *close;
/* optional fd api */
iksTConnectFD *connect_fd;
iksTGetFD *get_fd;
/* optional async api */
iksTConnectAsync *connect_async;
} ikstransport;
extern ikstransport iks_default_transport;
/***** stream parser *****/
enum iksneterror {
IKS_NET_NODNS = 4,
IKS_NET_NOSOCK,
IKS_NET_NOCONN,
IKS_NET_RWERR,
IKS_NET_NOTSUPP,
IKS_NET_TLSFAIL
};
enum iksnodetype {
IKS_NODE_START,
IKS_NODE_NORMAL,
IKS_NODE_ERROR,
IKS_NODE_STOP
};
enum ikssasltype {
IKS_SASL_PLAIN,
IKS_SASL_DIGEST_MD5
};
#define IKS_JABBER_PORT 5222
typedef int (iksStreamHook)(void *user_data, int type, iks *node);
typedef void (iksLogHook)(void *user_data, const char *data, size_t size, int is_incoming);
iksparser *iks_stream_new (char *name_space, void *user_data, iksStreamHook *streamHook);
void *iks_stream_user_data (iksparser *prs);
void iks_set_log_hook (iksparser *prs, iksLogHook *logHook);
int iks_connect_tcp (iksparser *prs, const char *server, int port);
int iks_connect_fd (iksparser *prs, int fd);
int iks_connect_via (iksparser *prs, const char *server, int port, const char *server_name);
int iks_connect_with (iksparser *prs, const char *server, int port, const char *server_name, ikstransport *trans);
int iks_connect_async (iksparser *prs, const char *server, int port, void *notify_data, iksAsyncNotify *notify_func);
int iks_connect_async_with (iksparser *prs, const char *server, int port, const char *server_name, ikstransport *trans, void *notify_data, iksAsyncNotify *notify_func);
int iks_fd (iksparser *prs);
int iks_recv (iksparser *prs, int timeout);
int iks_send_header (iksparser *prs, const char *to);
int iks_send (iksparser *prs, iks *x);
int iks_send_raw (iksparser *prs, const char *xmlstr);
void iks_disconnect (iksparser *prs);
int iks_has_tls (void);
int iks_is_secure (iksparser *prs);
int iks_start_tls (iksparser *prs);
int iks_start_sasl (iksparser *prs, enum ikssasltype type, char *username, char *pass);
/***** jabber *****/
#define IKS_NS_CLIENT "jabber:client"
#define IKS_NS_SERVER "jabber:server"
#define IKS_NS_AUTH "jabber:iq:auth"
#define IKS_NS_AUTH_0K "jabber:iq:auth:0k"
#define IKS_NS_REGISTER "jabber:iq:register"
#define IKS_NS_ROSTER "jabber:iq:roster"
#define IKS_NS_XROSTER "jabber:x:roster"
#define IKS_NS_OFFLINE "jabber:x:offline"
#define IKS_NS_AGENT "jabber:iq:agent"
#define IKS_NS_AGENTS "jabber:iq:agents"
#define IKS_NS_BROWSE "jabber:iq:browse"
#define IKS_NS_CONFERENCE "jabber:iq:conference"
#define IKS_NS_DELAY "jabber:x:delay"
#define IKS_NS_VERSION "jabber:iq:version"
#define IKS_NS_TIME "jabber:iq:time"
#define IKS_NS_VCARD "vcard-temp"
#define IKS_NS_PRIVATE "jabber:iq:private"
#define IKS_NS_SEARCH "jabber:iq:search"
#define IKS_NS_OOB "jabber:iq:oob"
#define IKS_NS_XOOB "jabber:x:oob"
#define IKS_NS_ADMIN "jabber:iq:admin"
#define IKS_NS_FILTER "jabber:iq:filter"
#define IKS_NS_GATEWAY "jabber:iq:gateway"
#define IKS_NS_LAST "jabber:iq:last"
#define IKS_NS_SIGNED "jabber:x:signed"
#define IKS_NS_ENCRYPTED "jabber:x:encrypted"
#define IKS_NS_ENVELOPE "jabber:x:envelope"
#define IKS_NS_EVENT "jabber:x:event"
#define IKS_NS_EXPIRE "jabber:x:expire"
#define IKS_NS_XHTML "http://www.w3.org/1999/xhtml"
#define IKS_NS_XMPP_SASL "urn:ietf:params:xml:ns:xmpp-sasl"
#define IKS_NS_XMPP_BIND "urn:ietf:params:xml:ns:xmpp-bind"
#define IKS_NS_XMPP_SESSION "urn:ietf:params:xml:ns:xmpp-session"
#define IKS_ID_USER 1
#define IKS_ID_SERVER 2
#define IKS_ID_RESOURCE 4
#define IKS_ID_PARTIAL IKS_ID_USER | IKS_ID_SERVER
#define IKS_ID_FULL IKS_ID_USER | IKS_ID_SERVER | IKS_ID_RESOURCE
#define IKS_STREAM_STARTTLS 1
#define IKS_STREAM_SESSION 2
#define IKS_STREAM_BIND 4
#define IKS_STREAM_SASL_PLAIN 8
#define IKS_STREAM_SASL_MD5 16
typedef struct iksid_struct {
char *user;
char *server;
char *resource;
char *partial;
char *full;
} iksid;
iksid *iks_id_new (ikstack *s, const char *jid);
int iks_id_cmp (iksid *a, iksid *b, int parts);
enum ikspaktype {
IKS_PAK_NONE = 0,
IKS_PAK_MESSAGE,
IKS_PAK_PRESENCE,
IKS_PAK_IQ,
IKS_PAK_S10N
};
enum iksubtype {
IKS_TYPE_NONE = 0,
IKS_TYPE_ERROR,
IKS_TYPE_CHAT,
IKS_TYPE_GROUPCHAT,
IKS_TYPE_HEADLINE,
IKS_TYPE_GET,
IKS_TYPE_SET,
IKS_TYPE_RESULT,
IKS_TYPE_SUBSCRIBE,
IKS_TYPE_SUBSCRIBED,
IKS_TYPE_UNSUBSCRIBE,
IKS_TYPE_UNSUBSCRIBED,
IKS_TYPE_PROBE,
IKS_TYPE_AVAILABLE,
IKS_TYPE_UNAVAILABLE
};
enum ikshowtype {
IKS_SHOW_UNAVAILABLE = 0,
IKS_SHOW_AVAILABLE,
IKS_SHOW_CHAT,
IKS_SHOW_AWAY,
IKS_SHOW_XA,
IKS_SHOW_DND
};
typedef struct ikspak_struct {
iks *x;
iksid *from;
iks *query;
char *ns;
char *id;
enum ikspaktype type;
enum iksubtype subtype;
enum ikshowtype show;
} ikspak;
ikspak *iks_packet (iks *x);
iks *iks_make_auth (iksid *id, const char *pass, const char *sid);
iks *iks_make_msg (enum iksubtype type, const char *to, const char *body);
iks *iks_make_s10n (enum iksubtype type, const char *to, const char *msg);
iks *iks_make_pres (enum ikshowtype show, const char *status);
iks *iks_make_iq (enum iksubtype type, const char *xmlns);
iks *iks_make_resource_bind(iksid *id);
iks *iks_make_session(void);
int iks_stream_features(iks *x);
/***** jabber packet filter *****/
#define IKS_RULE_DONE 0
#define IKS_RULE_ID 1
#define IKS_RULE_TYPE 2
#define IKS_RULE_SUBTYPE 4
#define IKS_RULE_FROM 8
#define IKS_RULE_FROM_PARTIAL 16
#define IKS_RULE_NS 32
enum iksfilterret {
IKS_FILTER_PASS,
IKS_FILTER_EAT
};
typedef int (iksFilterHook)(void *user_data, ikspak *pak);
struct iksfilter_struct;
typedef struct iksfilter_struct iksfilter;
struct iksrule_struct;
typedef struct iksrule_struct iksrule;
iksfilter *iks_filter_new (void);
iksrule *iks_filter_add_rule (iksfilter *f, iksFilterHook *filterHook, void *user_data, ...);
void iks_filter_remove_rule (iksfilter *f, iksrule *rule);
void iks_filter_remove_hook (iksfilter *f, iksFilterHook *filterHook);
void iks_filter_packet (iksfilter *f, ikspak *pak);
void iks_filter_delete (iksfilter *f);
/***** sha1 *****/
struct iksha_struct;
typedef struct iksha_struct iksha;
iksha *iks_sha_new (void);
void iks_sha_reset (iksha *sha);
void iks_sha_hash (iksha *sha, const unsigned char *data, size_t len, int finish);
void iks_sha_print (iksha *sha, char *hash);
void iks_sha_delete (iksha *sha);
void iks_sha (const char *data, char *hash);
/***** md5 *****/
struct ikmd5_struct;
typedef struct iksmd5_struct iksmd5;
iksmd5 *iks_md5_new(void);
void iks_md5_reset(iksmd5 *md5);
void iks_md5_hash(iksmd5 *md5, const unsigned char *data, size_t slen, int finish);
void iks_md5_delete(iksmd5 *md5);
void iks_md5_print(iksmd5 *md5, char *buf);
void iks_md5_digest(iksmd5 *md5, unsigned char *digest);
void iks_md5(const char *data, char *buf);
/***** base64 *****/
char *iks_base64_decode(const char *buf);
char *iks_base64_encode(const char *buf, int len);
#ifdef __cplusplus
}
#endif
#endif /* IKSEMEL_H */
+1039
View File
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
import piksemel as iks
doc_xml = '<lala b="" c="42"/>'
doc = iks.newDocument("lala")
doc.setAttribute("a", "lala")
doc.setAttribute("b", "nanuk")
doc.setAttribute("b", "")
doc.setAttribute("a", None)
doc.setAttribute("c", "42")
assert(doc.toString() == doc_xml)
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
import piksemel as iks
doc_xml = """
<test>
<a><b><c/></b></a>
<item foo="lala">
<tuktuk>blah &amp; bleh</tuktuk>
<nanuk/>
</item>
<a/>
</test>
""".strip()
doc = iks.newDocument("test")
doc.insertData("\n ")
a = doc.insertTag("a")
a.insertTag("b").insertTag("c")
doc.insertData("\n ")
item = doc.insertTag("item")
item.setAttribute("foo", "lala")
item.insertData("\n ")
item.insertTag("tuktuk").insertData("blah & bleh")
item.insertData("\n ")
item.insertTag("nanuk")
item.insertData("\n ")
doc.insertData("\n ")
a = doc.insertTag("a")
doc.insertData("\n")
assert(doc.toString() == doc_xml)
# append test
doc = iks.newDocument("lala")
a = doc.insertTag("nanik")
b = a.appendData("lala")
a = b.appendTag("lolo")
a = a.appendTag("iki")
b.appendData("hede")
doc.firstChild().appendData("fii")
assert(doc.toString() == "<lala><nanik/>fiilalahede<lolo/><iki/></lala>")
# prepend test
doc = iks.newDocument("lala")
a = doc.insertTag("foo")
a = a.prependTag("a")
a = a.prependTag("b")
a.prependData("hihi").prependData("oh").appendData("i")
a.appendTag("c")
assert(doc.toString() == "<lala>ohihihi<b/><c/><a/><foo/></lala>")
# insertNode test
doc = iks.newDocument("a")
b = iks.newDocument("b")
b.setAttribute("lal", "foo")
b = doc.insertNode(b)
b.setAttribute("lal", "foofff")
assert(doc.toString() == '<a><b lal="foofff"/></a>')
# now with append, prepend and insertNode
doc = iks.newDocument("test")
a = iks.newDocument("a")
a.insertTag("b").insertTag("c")
item = iks.newDocument("item")
node = item.insertData("\n ")
node.appendTag("tuktuk").insertData("blah & bleh")
node = item.insertData("\n ")
node.appendTag("nanuk").appendData("\n ")
doc.insertNode(a).appendData("\n ")
doc.getTag("a").prependData("\n ")
del a
node = doc.insertNode(item)
node.setAttribute("foo", "lala")
del item
node = doc.insertData("\n ")
node.appendTag("a").appendData("\n")
assert(doc.toString() == doc_xml)
# setData test
doc = iks.newDocument("a")
x = doc.insertTag("b")
x.insertTag("lala")
y = x.insertTag("bibi")
y.prependData("hodo")
assert(x.toString() == "<b><lala/>hodo<bibi/></b>")
x.setData("merhaba")
assert(x.toString() == "<b>merhaba</b>")
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
import piksemel as iks
doc_xml = """
<test>
<a/>
<item id="1"/>
<a/>
<foo/>
<item id="2">
<tuktuk>blah &amp; bleh</tuktuk>
<a foo="bleh"/>
<nanuk/>
</item>
<a/>
<bar/>
<item/>
<item id="4"/>
<a/>
</test>
"""
doc = iks.parseString(doc_xml)
count = 0
for node in doc:
assert(node.type() == iks.TAG or node.type() == iks.DATA)
count += 1
assert(count == 21)
count = 0
for node in doc.tags():
assert(node.type() == iks.TAG)
count += 1
assert(count == 10)
count = 0
for node in doc.tags("a"):
assert(node.type() == iks.TAG)
assert(node.name() == "a")
assert(node.getAttribute("foo") == None)
count += 1
assert(count == 4)
count = 0
for node in doc.tags("item"):
assert(node.type() == iks.TAG)
assert(node.name() == "item")
count += 1
assert(count == 4)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
import piksemel
doc = piksemel.newDocument("lala")
try:
doc.appendTag("lala")
except piksemel.NotTag:
pass
try:
doc.appendData("lala")
except piksemel.NotTag:
pass
try:
doc.prependTag("lala")
except piksemel.NotTag:
pass
try:
doc.prependData("lala")
except piksemel.NotTag:
pass
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
import piksemel as iks
doc_xml = """
<test>
<item id="1"/>
<foo/>
<item id="2">
<tuktuk>blah &amp; bleh</tuktuk>
<nanuk/>
</item>
<bar/>
<item/>
<item id="4"/>
</test>
"""
doc = iks.parseString(doc_xml)
# sibling nodes
node = doc.firstChild()
last = None
count = 0
while node:
last = node
count += 1
node = node.next()
assert(count == 13)
node = last
while node:
count -= 1
node = node.previous()
assert(count == 0)
# sibling tags
item = doc.getTag("item")
last = None
while item:
last = item
assert(item.type() == iks.TAG)
assert(item.name() == "item")
count += 1
item = item.nextTag("item")
assert(count == 4)
item = last
while item:
assert(item.type() == iks.TAG)
assert(item.name() == "item")
count -= 1
item = item.previousTag("item")
assert(count == 0)
node = doc.getTag("item")
last = None
while node:
last = node
assert(node.type() == iks.TAG)
count += 1
node = node.nextTag()
assert(count == 6)
node = last
while node:
assert(node.type() == iks.TAG)
count -= 1
node = node.previousTag()
assert(count == 0)
# parent/child
node = doc.getTag("item").nextTag().nextTag().getTag("nanuk")
assert(node.type() == iks.TAG)
assert(node.name() == "nanuk")
item = node.parent()
assert(item.type() == iks.TAG)
assert(item.name() == "item")
top = node.root()
assert(top.type() == iks.TAG)
assert(top.name() == "test")