/usr/share/pyshared/Pyblosxom/tools.py is in pyblosxom 1.5.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 | #######################################################################
# This file is part of Pyblosxom.
#
# Copyright (C) 2003-2011 by the Pyblosxom team. See AUTHORS.
#
# Pyblosxom is distributed under the MIT license. See the file
# LICENSE for distribution details.
#######################################################################
"""Utility module for functions that are useful to Pyblosxom and plugins.
"""
import sgmllib
import re
import os
import time
import os.path
import stat
import sys
import locale
import urllib
import inspect
import textwrap
# Pyblosxom imports
from Pyblosxom import plugin_utils
# Note: month names tend to differ with locale
# month name (Jan) to number (1)
month2num = None
# month number (1) to name (Jan)
num2month = None
# list of all month numbers and names
MONTHS = None
# regular expression for detection and substituion of variables.
_VAR_REGEXP = re.compile(r"""
(?<!\\) # if the $ is escaped, then this isn't a variable
\$ # variables start with a $
(
(?:\w|\-|::\w)+ # word char, - or :: followed by a word char
(?:
\( # an open paren
.*? # followed by non-greedy bunch of stuff
(?<!\\)\) # with an end paren that's not escaped
)? # 0 or 1 of these ( ... ) blocks
|
\(
(?:\w|\-|::\w)+ # word char, - or :: followed by a word char
(?:
\( # an open paren
.*? # followed by non-greedy bunch of stuff
(?<!\\)\) # with an end paren that's not escaped
)? # 0 or 1 of these ( ... ) blocks
\)
)
""", re.VERBOSE)
# reference to the pyblosxom config dict
_config = {}
def initialize(config):
"""Initializes the tools module.
This gives the module a chance to use configuration from the
pyblosxom config.py file.
This should be called from ``Pyblosxom.pyblosxom.Pyblosxom.initialize``.
"""
global _config
_config = config
# Month names tend to differ with locale
global month2num
try:
month2num = {'nil' : '00',
locale.nl_langinfo(locale.ABMON_1) : '01',
locale.nl_langinfo(locale.ABMON_2) : '02',
locale.nl_langinfo(locale.ABMON_3) : '03',
locale.nl_langinfo(locale.ABMON_4) : '04',
locale.nl_langinfo(locale.ABMON_5) : '05',
locale.nl_langinfo(locale.ABMON_6) : '06',
locale.nl_langinfo(locale.ABMON_7) : '07',
locale.nl_langinfo(locale.ABMON_8) : '08',
locale.nl_langinfo(locale.ABMON_9) : '09',
locale.nl_langinfo(locale.ABMON_10) : '10',
locale.nl_langinfo(locale.ABMON_11) : '11',
locale.nl_langinfo(locale.ABMON_12) : '12'}
except AttributeError:
# Windows doesn't have nl_langinfo, so we use one that
# only return English.
# FIXME - need a better hack for this issue.
month2num = {'nil': '00',
"Jan": '01',
"Feb": '02',
"Mar": '03',
"Apr": '04',
"May": '05',
"Jun": '06',
"Jul": '07',
"Aug": '08',
"Sep": '09',
"Oct": '10',
"Nov": '11',
"Dec": '12'}
# This is not python 2.1 compatible (Nifty though)
# num2month = dict(zip(month2num.itervalues(), month2num))
global num2month
num2month = {}
for month_abbr, month_num in month2num.items():
num2month[month_num] = month_abbr
num2month[int(month_num)] = month_abbr
# all the valid month possibilities
global MONTHS
MONTHS = num2month.keys() + month2num.keys()
def pwrap(s):
"""Wraps the text and prints it.
"""
starter = ""
linesep = os.linesep
if s.startswith("- "):
starter = "- "
s = s[2:]
linesep = os.linesep + " "
print starter + linesep.join(textwrap.wrap(s, 72))
def pwrap_error(s):
"""Wraps an error message and prints it to stderr.
"""
starter = ""
linesep = os.linesep
if s.startswith("- "):
starter = "- "
s = s[2:]
linesep = os.linesep + " "
sys.stderr.write(starter + linesep.join(textwrap.wrap(s, 72)) + "\n")
def deprecated_function(func):
def _deprecated_function(*args, **kwargs):
return func(*args, **kwargs)
_deprecated_function.__doc__ = ("DEPRECATED. Use %s instead." %
func.__name__)
_deprecated_function.__dict__.update(func.__dict__)
return _deprecated_function
class ConfigSyntaxErrorException(Exception):
"""Thrown when ``convert_configini_values`` encounters a syntax
error.
"""
pass
def convert_configini_values(configini):
"""Takes a dict containing config.ini style keys and values, converts
the values, and returns a new config dict.
:param confini: dict containing the config.ini style keys and values
:raises ConfigSyntaxErrorException: when there's a syntax error
:returns: new config dict
"""
def s_or_i(text):
"""
Takes a string and if it begins with \" or \' and ends with
\" or \', then it returns the string. If it's an int, returns
the int. Otherwise it returns the text.
"""
text = text.strip()
if (((text.startswith('"') and not text.endswith('"'))
or (not text.startswith('"') and text.endswith('"')))):
raise ConfigSyntaxErrorException(
"config syntax error: string '%s' missing start or end \"" %
text)
elif (((text.startswith("'") and not text.endswith("'"))
or (not text.startswith("'") and text.endswith("'")))):
raise ConfigSyntaxErrorException(
"config syntax error: string '%s' missing start or end '" %
text)
elif text.startswith('"') and text.endswith('"'):
return text[1:-1]
elif text.startswith("'") and text.endswith("'"):
return text[1:-1]
elif text.isdigit():
return int(text)
return text
config = {}
for key, value in configini.items():
# in configini.items, we pick up a local_config which seems
# to be a copy of what's in configini.items--puzzling.
if isinstance(value, dict):
continue
value = value.strip()
if (((value.startswith("[") and not value.endswith("]"))
or (not value.startswith("[") and value.endswith("]")))):
raise ConfigSyntaxErrorException(
"config syntax error: list '%s' missing [ or ]" %
value)
elif value.startswith("[") and value.endswith("]"):
value2 = value[1:-1].strip().split(",")
if len(value2) == 1 and value2[0] == "":
# handle the foo = [] case
config[key] = []
else:
config[key] = [s_or_i(s.strip()) for s in value2]
else:
config[key] = s_or_i(value)
return config
def escape_text(s):
"""Takes in a string and converts:
* ``&`` to ``&``
* ``>`` to ``>``
* ``<`` to ``<``
* ``\"`` to ``"``
* ``'`` to ``'``
* ``/`` to ``/``
Note: if ``s`` is ``None``, then we return ``None``.
>>> escape_text(None)
None
>>> escape_text("")
""
>>> escape_text("a'b")
"a'b"
>>> escape_text('a"b')
"a"b"
"""
if not s:
return s
for mem in (("&", "&"), (">", ">"), ("<", "<"), ("\"", """),
("'", "'"), ("/", "/")):
s = s.replace(mem[0], mem[1])
return s
def urlencode_text(s):
"""Calls ``urllib.quote`` on the string ``s``.
Note: if ``s`` is ``None``, then we return ``None``.
>>> urlencode_text(None)
None
>>> urlencode_text("")
""
>>> urlencode_text("a c")
"a%20c"
>>> urlencode_text("a&c")
"a%26c"
>>> urlencode_text("a=c")
"a%3Dc"
"""
if not s:
return s
return urllib.quote(s)
STANDARD_FILTERS = {"escape": lambda req, vd, s: escape_text(s),
"urlencode": lambda req, vd, s: urlencode_text(s)}
class Stripper(sgmllib.SGMLParser):
"""
SGMLParser that removes HTML formatting code.
"""
def __init__(self):
"""
Initializes the instance.
"""
self.data = []
sgmllib.SGMLParser.__init__(self)
def unknown_starttag(self, tag, attrs):
"""
Implements unknown_starttag. Appends a space to the buffer.
"""
self.data.append(" ")
def unknown_endtag(self, tag):
"""
Implements unknown_endtag. Appends a space to the buffer.
"""
self.data.append(" ")
def handle_data(self, data):
"""
Implements handle_data. Appends data to the buffer.
"""
self.data.append(data)
def gettext(self):
"""
Returns the buffer.
"""
return "".join(self.data)
def commasplit(s):
"""
Splits a string that contains strings by comma. This is
more involved than just an ``s.split(",")`` because this handles
commas in strings correctly.
Note: commasplit doesn't remove extranneous spaces.
>>> tools.commasplit(None)
[]
>>> tools.commasplit("")
[""]
>>> tools.commasplit("a")
["a"]
>>> tools.commasplit("a, b, c")
["a", " b", " c"]
>>> tools.commasplit("'a', 'b, c'")
["a", " 'b, c'"]
>>> tools.commasplit("'a', \"b, c\"")
["a", " \"b, c\""]
:param s: the string to split
:returns: list of strings
"""
if s is None:
return []
if not s:
return [""]
startstring = None
t = []
l = []
for c in s:
if c == startstring:
startstring = None
t.append(c)
elif c == "'" or c == '"':
startstring = c
t.append(c)
elif not startstring and c == ",":
l.append("".join(t))
t = []
else:
t.append(c)
if t:
l.append("".join(t))
return l
class Replacer:
"""
Class for replacing variables in a template
This class is a utility class used to provide a bound method to the
``re.sub()`` function. Originally from OPAGCGI.
"""
def __init__(self, request, encoding, var_dict):
"""
Its only duty is to populate itself with the replacement
dictionary passed.
:param request: the Request object
:param encoding: the encoding to use. ``utf-8`` is good.
:param var_dict: the dict containing variable substitutions
"""
self._request = request
self._encoding = encoding
self.var_dict = var_dict
def replace(self, matchobj):
"""
This is passed a match object by ``re.sub()`` which represents
a template variable without the ``$``. parse manipulates the
variable and returns the expansion of that variable using the
following rules:
1. if the variable ``v`` is an identifier, but not in the
variable dict, then we return the empty string, or
2. if the variable ``v`` is an identifier in the variable
dict, then we return ``var_dict[v]``, or
3. if the variable ``v`` is a function call where the function
is an identifier in the variable dict, then
- if ``v`` has no passed arguments and the function takes
no arguments we return ``var_dict[v]()`` (this is the old
behavior
- if ``v`` has no passed arguments and the function takes
two arguments we return ``var_dict[v](request, vd)``
- if ``v`` has passed arguments, we return
``var_dict[v](request, vd, *args)`` after some mild
processing of the arguments
Also, for backwards compatability reasons, we convert things
like::
$id_escaped
$id_urlencoded
$(id_escaped)
$(id_urlencoded)
to::
$escape(id)
$urlencode(id)
:param matchobj: the regular expression match object
:returns: the substituted string
"""
vd = self.var_dict
request = self._request
key = matchobj.group(1)
# if the variable is using $(foo) syntax, then we strip the
# outer parens here.
if key.startswith("(") and key.endswith(")"):
key = key[1:-1]
# do this for backwards-compatability reasons
if key.endswith("_escaped"):
key = "escape(%s)" % key[:-8]
elif key.endswith("_urlencoded"):
key = "urlencode(%s)" % key[:-11]
if key.find("(") != -1 and key.rfind(")") > key.find("("):
args = key[key.find("(")+1:key.rfind(")")]
key = key[:key.find("(")]
else:
args = None
if not vd.has_key(key):
return ""
r = vd[key]
# if the value turns out to be a function, then we call it
# with the args that we were passed.
if callable(r):
if args:
def fix(s, vd=vd):
# if it's an int, return an int
if s.isdigit():
return int(s)
# if it's a string, return a string
if s.startswith("'") or s.startswith('"'):
return s[1:-1]
# otherwise it might be an identifier--check
# the vardict and return the value if it's in
# there
if vd.has_key(s):
return vd[s]
if s.startswith("$") and vd.has_key(s[1:]):
return vd[s[1:]]
return s
args = [fix(arg.strip()) for arg in commasplit(args)]
# stick the request and var_dict in as the first and
# second arguments
args.insert(0, vd)
args.insert(0, request)
r = r(*args)
elif len(inspect.getargspec(r)[0]) == 2:
r = r(request, vd)
else:
# this case is here for handling the old behavior
# where functions took no arguments
r = r()
# convert non-strings to strings
if not isinstance(r, str):
if isinstance(r, unicode):
r = r.encode(self._encoding)
else:
r = str(r)
return r
def parse(request, var_dict, template):
"""
This method parses the ``template`` passed in using ``Replacer``
to expand template variables using values in the ``var_dict``.
Originally based on OPAGCGI, but mostly re-written.
:param request: the Request object
:param var_dict: the dict holding name/value pair variable replacements
:param template: the string template we're expanding variables in.
:returns: the template string with template variables expanded.
"""
encoding = request.config.get("blog_encoding", "utf-8")
replacer = Replacer(request, encoding, var_dict)
return _VAR_REGEXP.sub(replacer.replace, template)
def walk(request, root='.', recurse=0, pattern='', return_folders=0):
"""
This function walks a directory tree starting at a specified root
folder, and returns a list of all of the files (and optionally
folders) that match our pattern(s). Taken from the online Python
Cookbook and modified to own needs.
It will look at the config "ignore_directories" for a list of
directories to ignore. It uses a regexp that joins all the things
you list. So the following::
config.py["ignore_directories"] = ["CVS", "dev/pyblosxom"]
turns into the regexp::
.*?(CVS|dev/pyblosxom)$
It will also skip all directories that start with a period.
:param request: the Request object
:param root: the root directory to walk
:param recurse: the depth of recursion; defaults to 0 which goes all
the way down
:param pattern: the regexp object for matching files; defaults to
'' which causes Pyblosxom to return files with
file extensions that match those the entryparsers
handle
:param return_folders: True if you want only folders, False if you
want files AND folders
:returns: a list of file paths.
"""
# expand pattern
if not pattern:
ext = request.get_data()['extensions']
pattern = re.compile(r'.*\.(' + '|'.join(ext.keys()) + r')$')
ignore = request.get_configuration().get("ignore_directories", None)
if isinstance(ignore, str):
ignore = [ignore]
if ignore:
ignore = [re.escape(i) for i in ignore]
ignorere = re.compile(r'.*?(' + '|'.join(ignore) + r')$')
else:
ignorere = None
# must have at least root folder
if not os.path.isdir(root):
return []
return _walk_internal(root, recurse, pattern, ignorere, return_folders)
# We do this for backwards compatibility reasons.
Walk = deprecated_function(walk)
def _walk_internal(root, recurse, pattern, ignorere, return_folders):
"""
Note: This is an internal function--don't use it and don't expect
it to stay the same between Pyblosxom releases.
"""
# FIXME - we should either ditch this function and use os.walk or
# something similar, or optimize this version by removing the
# multiple stat calls that happen as a result of islink, isdir and
# isfile.
# initialize
result = []
try:
names = os.listdir(root)
except OSError:
return []
# check each file
for name in names:
fullname = os.path.normpath(os.path.join(root, name))
# grab if it matches our pattern and entry type
if pattern.match(name):
if ((os.path.isfile(fullname) and not return_folders) or
(return_folders and os.path.isdir(fullname) and
(not ignorere or not ignorere.match(fullname)))):
result.append(fullname)
# recursively scan other folders, appending results
if (recurse == 0) or (recurse > 1):
if name[0] != "." and os.path.isdir(fullname) and \
not os.path.islink(fullname) and \
(not ignorere or not ignorere.match(fullname)):
result = result + \
_walk_internal(fullname,
(recurse > 1 and [recurse - 1] or [0])[0],
pattern, ignorere, return_folders)
return result
def filestat(request, filename):
"""
Returns the filestat on a given file. We store the filestat in
case we've already retrieved it during this Pyblosxom request.
This returns the mtime of the file (same as returned by
``time.localtime()``) -- tuple of 9 ints.
:param request: the Request object
:param filename: the file name of the file to stat
:returns: the filestat (tuple of 9 ints) on the given file
"""
data = request.getData()
filestat_cache = data.setdefault("filestat_cache", {})
if filestat_cache.has_key(filename):
return filestat_cache[filename]
argdict = {"request": request,
"filename": filename,
"mtime": (0,) * 10}
MT = stat.ST_MTIME
argdict = run_callback("filestat",
argdict,
mappingfunc=lambda x, y: y,
donefunc=lambda x: x and x["mtime"][MT] != 0,
defaultfunc=lambda x: x)
# no plugin handled cb_filestat; we default to asking the
# filesystem
if argdict["mtime"][MT] == 0:
argdict["mtime"] = os.stat(filename)
timetuple = time.localtime(argdict["mtime"][MT])
filestat_cache[filename] = timetuple
return timetuple
def what_ext(extensions, filepath):
"""
Takes in a filepath and a list of extensions and tries them all
until it finds the first extension that works.
:param extensions: the list of extensions to test
:param filepath: the complete file path (minus the extension) to
test and find the extension for
:returns: the extension (string) of the file or ``None``.
"""
for ext in extensions:
if os.path.isfile(filepath + '.' + ext):
return ext
return None
def is_year(s):
"""
Checks to see if the string is likely to be a year or not. In
order to be considered to be a year, it must pass the following
criteria:
1. four digits
2. first two digits are either 19 or 20.
:param s: the string to check for "year-hood"
:returns: ``True`` if it is a year and ``False`` otherwise.
"""
if not s:
return False
if len(s) == 4 and s.isdigit() and \
(s.startswith("19") or s.startswith("20")):
return True
return False
def importname(modulename, name):
"""
Safely imports modules for runtime importing.
:param modulename: the package name of the module to import from
:param name: the name of the module to import
:returns: the module object or ``None`` if there were problems
importing.
"""
logger = getLogger()
if not modulename:
m = name
else:
m = "%s.%s" % (modulename, name)
try:
module = __import__(m)
for c in m.split(".")[1:]:
module = getattr(module, c)
return module
except ImportError, ie:
logger.error("Module %s in package %s won't import: %s" % \
(repr(modulename), repr(name), ie))
except StandardError, e:
logger.error("Module %s not in in package %s: %s" % \
(repr(modulename), repr(name), e))
return None
def generate_rand_str(minlen=5, maxlen=10):
"""
Generate a random string between ``minlen`` and ``maxlen``
characters long.
The generated string consists of letters and numbers.
:param minlen: the minimum length of the generated random string
:param maxlen: the maximum length of the generated random string
:returns: generated string
"""
import random, string
chars = string.letters + string.digits
randstr = []
randstr_size = random.randint(minlen, maxlen)
x = 0
while x < randstr_size:
randstr.append(random.choice(chars))
x += 1
return "".join(randstr)
generateRandStr = deprecated_function(generate_rand_str)
def run_callback(chain, input,
mappingfunc=lambda x, y: x,
donefunc=lambda x: 0,
defaultfunc=None):
"""
Executes a callback chain on a given piece of data. passed in is
a dict of name/value pairs. Consult the documentation for the
specific callback chain you're executing.
Callback chains should conform to their documented behavior. This
function allows us to do transforms on data, handling data, and
also callbacks.
The difference in behavior is affected by the mappingfunc passed
in which converts the output of a given function in the chain to
the input for the next function.
If this is confusing, read through the code for this function.
Returns the transformed input dict.
:param chain: the name of the callback chain to run
:param input: dict with name/value pairs that gets passed as the
args dict to all callback functions
:param mappingfunc: the function that maps output arguments to
input arguments for the next iteration. It
must take two arguments: the original dict and
the return from the previous function. It
defaults to returning the original dict.
:param donefunc: this function tests whether we're done doing what
we're doing. This function takes as input the
output of the most recent iteration. If this
function returns True then we'll drop out of the
loop. For example, if you wanted a callback to
stop running when one of the registered functions
returned a 1, then you would pass in:
``donefunc=lambda x: x`` .
:param defaultfunc: if this is set and we finish going through all
the functions in the chain and none of them
have returned something that satisfies the
donefunc, then we'll execute the defaultfunc
with the latest version of the input dict.
:returns: varies
"""
chain = plugin_utils.get_callback_chain(chain)
output = None
for func in chain:
# we call the function with the input dict it returns an
# output.
output = func(input)
# we fun the output through our donefunc to see if we should
# stop iterating through the loop. if the donefunc returns
# something true, then we're all done; otherwise we continue.
if donefunc(output):
break
# we pass the input we just used and the output we just got
# into the mappingfunc which will give us the input for the
# next iteration. in most cases, this consists of either
# returning the old input or the old output--depending on
# whether we're transforming the data through the chain or
# not.
input = mappingfunc(input, output)
# if we have a defaultfunc and we haven't satisfied the donefunc
# conditions, then we return whatever the defaultfunc returns when
# given the current version of the input.
if callable(defaultfunc) and not donefunc(output):
return defaultfunc(input)
# we didn't call the defaultfunc--so we return the most recent
# output.
return output
def addcr(text):
"""Adds a cr if it needs one.
>>> addrc("foo")
foo\\n
>>> addcr("foo\\n")
foo\\n
:returns: string with \\n at the end
"""
if not text.endswith("\n"):
return text + "\n"
return text
def create_entry(datadir, category, filename, mtime, title, metadata, body):
"""
Creates a new entry in the blog.
This is primarily used by the testing system, but it could be used
by scripts and other tools.
:param datadir: the datadir
:param category: the category the entry should go in
:param filename: the name of the blog entry (filename and
extension--no directory)
:param mtime: the mtime (float) for the entry in seconds since the
epoch
:param title: the title for the entry
:param metadata: dict of key/value metadata pairs
:param body: the body of the entry
:raises IOError: if the datadir + category directory exists, but
isn't a directory
"""
# format the metadata lines for the entry
metadatalines = ["#%s %s" % (key, metadata[key])
for key in metadata.keys()]
entry = addcr(title) + "\n".join(metadatalines) + body
# create the category directories
d = os.path.join(datadir, category)
if not os.path.exists(d):
os.makedirs(d)
if not os.path.isdir(d):
raise IOError("%s exists, but isn't a directory." % d)
# create the filename
fn = os.path.join(datadir, category, filename)
# write the entry to disk
f = open(fn, "w")
f.write(entry)
f.close()
# set the mtime on the entry
os.utime(fn, (mtime, mtime))
def get_cache(request):
"""
Retrieves the cache from the request or fetches a new CacheDriver
instance.
:param request: the Request object
:returns: a BlosxomCache object
"""
data = request.getData()
mycache = data.get("data_cache", "")
if not mycache:
config = request.getConfiguration()
cache_driver_config = config.get('cacheDriver', 'base')
cache_config = config.get('cacheConfig', '')
cache_driver = importname('Pyblosxom.cache', cache_driver_config)
mycache = cache_driver.BlosxomCache(request, cache_config)
data["data_cache"] = mycache
return mycache
def update_static_entry(cdict, entry_filename):
"""
This is a utility function that allows plugins to easily update
statically rendered entries without going through all the
rigamarole.
First we figure out whether this blog is set up for static
rendering. If not, then we return--no harm done.
If we are, then we call ``render_url`` for each ``static_flavour``
of the entry and then for each ``static_flavour`` of the index
page.
:param cdict: the config.py dict
:param entry_filename: the url path of the entry to be updated;
example: ``/movies/xmen2``
"""
staticdir = cdict.get("static_dir", "")
if not staticdir:
return
staticflavours = cdict.get("static_flavours", ["html"])
renderme = []
for mem in staticflavours:
renderme.append("/index" + "." + mem, "")
renderme.append(entry_filename + "." + mem, "")
for mem in renderme:
render_url_statically(cdict, mem[0], mem[1])
def render_url_statically(cdict, url, querystring):
"""Renders a url and saves the rendered output to the
filesystem.
:param cdict: config dict
:param url: url to render
:param querystring: querystring of the url to render or ""
"""
staticdir = cdict.get("static_dir", "")
# if there is no staticdir, then they're not set up for static
# rendering.
if not staticdir:
raise Exception("You must set static_dir in your config file.")
response = render_url(cdict, url, querystring)
response.seek(0)
fn = os.path.normpath(staticdir + os.sep + url)
if not os.path.isdir(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
# by using the response object the cheesy part of removing the
# HTTP headers from the file is history.
f = open(fn, "w")
f.write(response.read())
f.close()
def render_url(cdict, pathinfo, querystring=""):
"""
Takes a url and a querystring and renders the page that
corresponds with that by creating a Request and a Pyblosxom object
and passing it through. It then returns the resulting Response.
:param cdict: the config.py dict
:param pathinfo: the ``PATH_INFO`` string;
example: ``/dev/pyblosxom/firstpost.html``
:param querystring: the querystring (if any); example: debug=yes
:returns: a Pyblosxom ``Response`` object.
"""
from pyblosxom import Pyblosxom
if querystring:
request_uri = pathinfo + "?" + querystring
else:
request_uri = pathinfo
env = {
"HTTP_HOST": "localhost",
"HTTP_REFERER": "",
"HTTP_USER_AGENT": "static renderer",
"PATH_INFO": pathinfo,
"QUERY_STRING": querystring,
"REMOTE_ADDR": "",
"REQUEST_METHOD": "GET",
"REQUEST_URI": request_uri,
"SCRIPT_NAME": "",
"wsgi.errors": sys.stderr,
"wsgi.input": None
}
data = {"STATIC": 1}
p = Pyblosxom(cdict, env, data)
p.run(static=True)
return p.get_response()
#******************************
# Logging
#******************************
import logging
# A dict to keep track of created log handlers. Used to prevent
# multiple handlers from beeing added to the same logger.
_loghandler_registry = {}
class LogFilter(object):
"""
Filters out messages from log-channels that are not listed in the
log_filter config variable.
"""
def __init__(self, names=None):
"""
Initializes the filter to the list provided by the names
argument (or ``[]`` if ``names`` is ``None``).
:param names: list of strings to filter out
"""
if names == None:
names = []
self.names = names
def filter(self, record):
if record.name in self.names:
return 1
return 0
def get_logger(log_file=None):
"""Creates and retuns a log channel.
If no log_file is given the system-wide logfile as defined in
config.py is used. If a log_file is given that's where the created
logger logs to.
:param log_file: the file to log to. defaults to None which
causes Pyblosxom to check for the ``log_file``
config.py property and if that's blank, then the
log_file is stderr
:returns: a log channel (logger instance) which you can call
``error``, ``warning``, ``debug``, ``info``, ... on.
"""
custom_log_file = False
if log_file == None:
log_file = _config.get('log_file', 'stderr')
f = sys._getframe(1)
filename = f.f_code.co_filename
module = f.f_globals["__name__"]
# by default use the root logger
log_name = ""
for path in _config.get('plugin_dirs', []):
if filename.startswith(path):
# if it's a plugin, use the module name as the log
# channels name
log_name = module
break
# default to log level WARNING if it's not defined in
# config.py
log_level = _config.get('log_level', 'warning')
else:
# handle custom log_file
custom_log_file = True
# figure out a name for the log channel
log_name = os.path.splitext(os.path.basename(log_file))[0]
# assume log_level debug (show everything)
log_level = "debug"
global _loghandler_registry
# get the logger for this channel
logger = logging.getLogger(log_name)
# don't propagate messages up the logger hierarchy
logger.propagate = 0
# setup the handler if it doesn't allready exist. only add one
# handler per log channel.
key = "%s|%s" % (log_file, log_name)
if not key in _loghandler_registry:
# create the handler
if log_file == "stderr":
hdlr = logging.StreamHandler(sys.stderr)
else:
if log_file == "NONE": # user disabled logging
if os.name == 'nt': # windoze
log_file = "NUL"
else: # assume *nix
log_file = "/dev/null"
try:
hdlr = logging.FileHandler(log_file)
except IOError:
# couldn't open logfile, fallback to stderr
hdlr = logging.StreamHandler(sys.stderr)
# create and set the formatter
if log_name:
fmtr_s = '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
else: # root logger
fmtr_s = '%(asctime)s [%(levelname)s]: %(message)s'
hdlr.setFormatter(logging.Formatter(fmtr_s))
logger.addHandler(hdlr)
int_level = getattr(logging, log_level.upper())
logger.setLevel(int_level)
if not custom_log_file:
# only log messages from plugins listed in log_filter.
# add 'root' to the log_filter list to still allow
# application level messages.
log_filter = _config.get('log_filter', None)
if log_filter:
lfilter = LogFilter(log_filter)
logger.addFilter(lfilter)
# remember that we've seen this handler
_loghandler_registry[key] = True
return logger
getLogger = deprecated_function(get_logger)
def log_exception(log_file=None):
"""
Logs an exception to the given file. Uses the system-wide
log_file as defined in config.py if none is given here.
:param log_file: the file to log to. defaults to None which
causes Pyblosxom to check for the ``log_file``
config.py property and if that's blank, then the
log_file is stderr
"""
log = getLogger(log_file)
log.exception("Exception occured:")
def log_caller(frame_num=1, log_file=None):
"""
Logs some info about the calling function/method. Useful for
debugging.
Usage:
>>> import tools
>>> tools.log_caller() # logs frame 1
>>> tools.log_caller(2)
>>> tools.log_caller(3, log_file="/path/to/file")
:param frame_num: the index of the frame to log; defaults to 1
:param log_file: the file to log to. defaults to None which
causes Pyblosxom to check for the ``log_file``
config.py property and if that's blank, then the
log_file is stderr
"""
f = sys._getframe(frame_num)
module = f.f_globals["__name__"]
filename = f.f_code.co_filename
line = f.f_lineno
subr = f.f_code.co_name
log = getLogger(log_file)
log.info("\n module: %s\n filename: %s\n line: %s\n subroutine: %s",
module, filename, line, subr)
|