Synopsis - Cross-Reference

File: Synopsis/Formatters/__init__.py
 1#
 2# Copyright (C) 2008 Stefan Seefeld
 3# All rights reserved.
 4# Licensed to the public under the terms of the GNU LGPL (>= 2),
 5# see the file COPYING for details.
 6#
 7
 8import os, stat, md5
 9
10
11def quote_name(name):
12    """Quotes a (file-) name to remove illegal characters and keep it
13    within a reasonable length for the filesystem.
14   
15    The md5 hash function is used if the length of the name after quoting is
16    more than 100 characters. If it is used, then as many characters at the
17    start of the name as possible are kept intact, and the hash appended to
18    make 100 characters.
19   
20    Do not pass filenames with meaningful extensions to this function, as the
21    hash could destroy them."""
22
23    original = name # save the old name
24
25    # a . is usually an extension, eg source page filename: "_page-foo.hpp" + .html
26    # name = re.sub('\.','_',name) 
27    # The . is arbitrary..
28    for p in [('<', '.L'), ('>', '.R'), ('(', '.l'), (')', '.r'), ('::', '-'),
29              (':', '.'), ('&', '.A'), ('*', '.S'), (' ', '.s'), (',', '.c'), (';', '.C')]:
30        name = name.replace(*p)
31
32    if len(name) > 100:
33        hash = md5.md5(original).hexdigest()
34        # Keep as much of the name as possible
35        name = name[:100 - len(hash)] + hash
36
37    return name
38
39
40def open_file(path, mode=511):
41    """Open a file for writing. Create all intermediate directories."""
42
43    directory = os.path.dirname(path)
44    if directory and not os.path.isdir(directory):
45        os.makedirs(directory, mode)
46    return open(path, 'w+')
47
48
49def copy_file(src, dest):
50    """Copy src to dest, if dest doesn't exist yet or is outdated."""
51
52    filetime = os.stat(src)[stat.ST_MTIME]
53    if not os.path.exists(dest) or filetime > os.stat(dest)[stat.ST_MTIME]:
54        open_file(dest).write(open(src, 'r').read())
55
56