svg.escobar.life

A simple SVG markup editor for the web

d-fold.py (1672B)

 1 #!/usr/bin/python3
 2 # A simple utility to fold the `d` attribute of <path> tags without breaking 
 3 # the image
 4 
 5 import argparse
 6 
 7 def split_at(s, length, sep=" "):
 8     """Split a string in 'lines' of length ~ `length`"""
 9 
10     s_lines = [sep + line for line in s.split(sep)]
11      
12     if not len(s_lines):
13         return []
14 
15     s_lines[0] = s_lines[0].strip(sep)
16 
17     lines = []
18     line = ""
19     i = 0
20 
21     # Construct the lines of the new file
22     while i < len(s_lines):
23         j = i
24 
25         # Construct a single line
26         while i < len(s_lines) and len(line + s_lines[i]) <= length:
27             line += s_lines[i]
28             i += 1
29 
30         # Append the line to lines
31         if i != j:
32             lines.append(line.strip())
33             line = ""
34         # Line is longer than 50 chars
35         else:
36             lines.append(s_lines[i].strip())
37             i += 1
38 
39     return lines
40 
41 def main():
42     parser = argparse.ArgumentParser()
43     parser.add_argument("--input", "-i", type=str, action="store"
44                        , default= "-", help="The input file")
45     parser.add_argument("--chars", "-n", type=int, default=50, action="store"
46                        , help="The number of characters in each line")
47 
48     args = parser.parse_args()
49     path = args.input if args.input != "-" else "/dev/stdin"
50 
51     with open(path, "r") as f:
52         s = f.read().replace("\n", "")
53         lines = []
54 
55         for line in split_at(s, args.chars):
56             if len(line) <= args.chars:
57                 lines.append(line)
58             else:
59                 lines += split_at(line, args.chars, "-")
60 
61         print("\n".join(lines))
62 
63 if __name__ == "__main__":
64     main()
65 
66