1+ #!/usr/bin/env python3
2+
13"""
24# URL shortener for .htaccess redirects
35
5658"""
5759
5860import itertools
61+ import sys
5962from collections .abc import Iterable , Iterator
6063from typing import NamedTuple , TextIO
6164from datetime import datetime
@@ -124,7 +127,7 @@ def update_htaccess(f: TextIO, directives: list[PathURL]) -> int:
124127 if directives :
125128 f .write (f'\n # appended { timestamp ()} \n ' )
126129 for path , url , _new in directives :
127- f .write (f'RedirectTemp /{ path } { url } \n ' )
130+ f .write (f'RedirectTemp /{ path } \t { url } \n ' )
128131 return len (directives )
129132
130133
@@ -145,3 +148,30 @@ def gen_unused_short(redirects: dict) -> Iterator[str]:
145148 for short in gen_short (2 ):
146149 if short not in redirects :
147150 yield short
151+
152+
153+ def main ():
154+ htaccess_path , urls_path = sys .argv [1 :3 ]
155+ with open (htaccess_path ) as f :
156+ hta = f .read ()
157+ assert 'RedirectTemp' in hta , 'No RedirecTemp in {htaccess_path}'
158+ with open (urls_path ) as f :
159+ urls = [u .rstrip () for u in f .readlines ()]
160+
161+ redirects , targets = load_redirects (parse_htaccess (hta ))
162+ path_urls = []
163+ path_gen = gen_unused_short (redirects )
164+ for url in urls :
165+ path_url = shorten_one (url , path_gen , redirects , targets )
166+ path_urls .append (path_url )
167+ path , url , new = path_url
168+ flag = '*' if new else ' '
169+ print (f'{ flag } /{ path } \t { url } ' )
170+
171+ with open (htaccess_path , 'a' ) as f :
172+ count = update_htaccess (f , path_urls )
173+ print (f'{ count } directives appended to { htaccess_path } ' , file = sys .stderr )
174+
175+
176+ if __name__ == '__main__' :
177+ main ()
0 commit comments