diff --git a/linkcheck/strformat.py b/linkcheck/strformat.py index d1b5ea07..449cfbdb 100644 --- a/linkcheck/strformat.py +++ b/linkcheck/strformat.py @@ -230,3 +230,32 @@ def strtimezone (): else: zone = time.timezone return "%+04d" % int(-zone/3600) + + +_sub_ws = re.compile(r"\s+").sub +def stripall (s): + """ + Remove all whitespace from given string. + """ + if not s: + return s + return _sub_ws("", s) + + +def limit (s, length=72): + """ + If the length of the string exceeds the given limit, it will be cut + off and three dots will be appended. + + @param s: the string to limit + @type s: string + @param length: maximum length + @type length: non-negative integer + @return: limited string, at most length+3 characters long + """ + assert length >= 0, "length limit must be a non-negative integer" + if not s or len(s) <= length: + return s + if length == 0: + return "" + return "%s..." % s[:length] diff --git a/linkcheck/tests/test_strformat.py b/linkcheck/tests/test_strformat.py index bf897ea3..b843e8ca 100644 --- a/linkcheck/tests/test_strformat.py +++ b/linkcheck/tests/test_strformat.py @@ -99,6 +99,17 @@ class TestStrFormat (unittest.TestCase): self.assertEquals(linkcheck.strformat.indent(s, ""), s) self.assertEquals(linkcheck.strformat.indent(s, " "), " "+s) + def test_stripall (self): + self.assertEquals(linkcheck.strformat.stripall("a\tb"), "ab") + self.assertEquals(linkcheck.strformat.stripall(" a\t b"), "ab") + self.assertEquals(linkcheck.strformat.stripall(" \r\na\t \nb\r"), "ab") + + def test_limit (self): + self.assertEquals(linkcheck.strformat.limit("", 0), "") + self.assertEquals(linkcheck.strformat.limit("a", 0), "") + self.assertEquals(linkcheck.strformat.limit("1", 1), "1") + self.assertEquals(linkcheck.strformat.limit("11", 1), "1...") + def test_suite (): """