2 # This file is part of LyX, the document processor.
3 # Licence details can be found in the file COPYING.
5 # author Richard Kimberly Heck, Alex Fernandez, Uwe Stöhr
7 # Full author contact details are available in file CREDITS
10 # ext_copy.py [-d] [-e ext1,ext2,...] [-t target_ext] from_file to_file
12 # This script is to be used as a "copier" script in the sense needed by
13 # the converter definitions. Given a from_file and to_file, it will copy
14 # all files in the directory in which from_file is found that have the
15 # extensions given in the -e argument, or all files in that directory if no
16 # such argument is given. So, for example, we can do:
17 # python ext_copy.py -e png,html,css /path/from/file.html /path/to/file.html
18 # and all html, png, and css files in /path/from/ will be copied to the
19 # (possibly new) directory /path/to/file.html.LyXconv/.
20 # The -t argument determines the extension added, the default being "LyXconv".
21 # If just . is given, no extension is added.
22 # If the -d option is given then the document directory /path/to/ will be used
23 # to copy the files no subdirectory will be created/used.
25 import getopt, os, shutil, sys
26 from lyxpreview_tools import error
30 msg = "Usage: %s [-d] [-e extensions] [-t target extension] from_file to_file"
31 return msg % prog_name
37 exts = [] #list of extensions for which we're checking
39 targext = "LyXconv" #extension for target directory
40 opts, args = getopt.getopt(sys.argv[1:], "de:t:")
51 error(usage(progname))
52 abs_from_file = args[0]
53 if not os.path.isabs(abs_from_file):
54 error(f"{abs_from_file} is not an absolute file name.\n{usage(progname)}")
55 from_dir = os.path.dirname(abs_from_file)
59 to_dir = os.path.dirname(args[1])
63 to_dir += "." + targext
64 if not os.path.isabs(to_dir):
65 error(f"{to_dir} is not an absolute file name.\n{usage(progname)}")
67 if not copy_all(from_dir, to_dir, exts):
68 # some kind of failure
73 def copy_all(from_dir, to_dir, exts):
74 "Copy all matching files in from_dir to to_dir"
75 for file in os.listdir(from_dir):
76 if os.path.isdir(os.path.join(from_dir, file)):
77 copy_all(os.path.join(from_dir, file), os.path.join(to_dir, file), exts)
79 junk, ext = os.path.splitext(os.path.basename(file))
80 ext = ext.lower()[1:] #strip the leading dot
81 # only create a directory and copy files when either
82 # exts is empty or when ext is in the exts list
83 if (exts) and (ext not in exts):
85 if not create_dir(to_dir):
87 from_file = os.path.join(from_dir, file)
88 to_file = os.path.join(to_dir, file)
89 shutil.copyfile(from_file, to_file)
91 shutil.copymode(from_file, to_file)
97 def create_dir(new_dir):
98 "Try to create the output directory if it doesn't exist"
99 if not os.path.isdir(new_dir):
103 error("Unable to create %s" % new_dir)
107 if __name__ == "__main__":