Debian Codegraph @

bin/toxcmd3.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: UTF-8 -*-
3 """
4 Provides a command container for additional tox commands, used in "tox.ini".
5
6 COMMANDS:
7
8 * copytree
9 * copy
10 * py2to3
11
12 REQUIRES:
13 * argparse
14 """
15
16 from glob import glob
17 import argparse
18 import inspect
19 import os.path
20 import shutil
21 import sys
22 import collections
23
24 __author__ = "Jens Engel"
25 __copyright__ = "(c) 2013 by Jens Engel"
26 __license__ = "BSD"
27
28 # -----------------------------------------------------------------------------
29 # CONSTANTS:
30 # -----------------------------------------------------------------------------
31 VERSION = "0.1.0"
32 FORMATTER_CLASS = argparse.RawDescriptionHelpFormatter
33
34
35 # -----------------------------------------------------------------------------
36 # SUBCOMMAND: copytree
37 # -----------------------------------------------------------------------------
38 def command_copytree(args):
39 """
40 Copy one or more source directory(s) below a destination directory.
41 Parts of the destination directory path are created if needed.
42 Similar to the UNIX command: 'cp -R srcdir destdir'
43 """
44 for srcdir in args.srcdirs:
45 basename = os.path.basename(srcdir)
46 destdir2 = os.path.normpath(os.path.join(args.destdir, basename))
47 if os.path.exists(destdir2):
48 shutil.rmtree(destdir2)
49 sys.stdout.write("copytree: %s => %s\n" % (srcdir, destdir2))
50 shutil.copytree(srcdir, destdir2)
51 return 0
52
53
54 def setup_parser_copytree(parser):
55 parser.add_argument("srcdirs", nargs="+", help="Source directory(s)")
56 parser.add_argument("destdir", help="Destination directory")
57
58
59 command_copytree.usage = "%(prog)s srcdir... destdir"
60 command_copytree.short = "Copy source dir(s) below a destination directory."
61 command_copytree.setup_parser = setup_parser_copytree
62
63
64 # -----------------------------------------------------------------------------
65 # SUBCOMMAND: copy
66 # -----------------------------------------------------------------------------
67 def command_copy(args):
68 """
69 Copy one or more source-files(s) to a destpath (destfile or destdir).
70 Destdir mode is used if:
71 * More than one srcfile is provided
72 * Last parameter ends with a slash ("/").
73 * Last parameter is an existing directory
74
75 Destination directory path is created if needed.
76 Similar to the UNIX command: 'cp srcfile... destpath'
77 """
78 sources = args.sources
79 destpath = args.destpath
80 source_files = []
81 for file_ in sources:
82 if "*" in file_:
83 selected = glob(file_)
84 source_files.extend(selected)
85 elif os.path.isfile(file_):
86 source_files.append(file_)
87
88 if destpath.endswith("/") or os.path.isdir(destpath) or len(sources) > 1:
89 # -- DESTDIR-MODE: Last argument is a directory.
90 destdir = destpath
91 else:
92 # -- DESTFILE-MODE: Copy (and rename) one file.
93 assert len(source_files) == 1
94 destdir = os.path.dirname(destpath)
95
96 # -- WORK-HORSE: Copy one or more files to destpath.
97 if not os.path.isdir(destdir):
98 sys.stdout.write("copy: Create dir %s\n" % destdir)
99 os.makedirs(destdir)
100 for source in source_files:
101 destname = os.path.join(destdir, os.path.basename(source))
102 sys.stdout.write("copy: %s => %s\n" % (source, destname))
103 shutil.copy(source, destname)
104 return 0
105
106
107 def setup_parser_copy(parser):
108 parser.add_argument("sources", nargs="+", help="Source files.")
109 parser.add_argument("destpath", help="Destination path")
110
111
112 command_copy.usage = "%(prog)s sources... destpath"
113 command_copy.short = "Copy one or more source files to a destinition."
114 command_copy.setup_parser = setup_parser_copy
115
116
117 # -----------------------------------------------------------------------------
118 # SUBCOMMAND: mkdir
119 # -----------------------------------------------------------------------------
120 def command_mkdir(args):
121 """
122 Create a non-existing directory (or more ...).
123 If the directory exists, the step is skipped.
124 Similar to the UNIX command: 'mkdir -p dir'
125 """
126 errors = 0
127 for directory in args.dirs:
128 if os.path.exists(directory):
129 if not os.path.isdir(directory):
130 # -- SANITY CHECK: directory exists, but as file...
131 sys.stdout.write("mkdir: %s\n" % directory)
132 sys.stdout.write("ERROR: Exists already, but as file...\n")
133 errors += 1
134 else:
135 # -- NORMAL CASE: Directory does not exits yet.
136 assert not os.path.isdir(directory)
137 sys.stdout.write("mkdir: %s\n" % directory)
138 os.makedirs(directory)
139 return errors
140
141
142 def setup_parser_mkdir(parser):
143 parser.add_argument("dirs", nargs="+", help="Directory(s)")
144
145 command_mkdir.usage = "%(prog)s dir..."
146 command_mkdir.short = "Create non-existing directory (or more...)."
147 command_mkdir.setup_parser = setup_parser_mkdir
148
149 # -----------------------------------------------------------------------------
150 # SUBCOMMAND: py2to3
151 # -----------------------------------------------------------------------------
152 command_py2to4_work_around3k = True
153 def command_py2to3(args):
154 """
155 Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.
156 """
157 from lib2to3.main import main
158 args2 = []
159 if command_py2to4_work_around3k:
160 if args.no_diffs:
161 args2.append("--no-diffs")
162 if args.write:
163 args2.append("-w")
164 if args.nobackups:
165 args2.append("-n")
166 args2.extend(args.sources)
167 sys.exit(main("lib2to3.fixes", args=args2))
168
169
170 def setup_parser4py2to3(parser):
171 if command_py2to4_work_around3k:
172 parser.add_argument("--no-diffs", action="store_true",
173 help="Don't show diffs of the refactoring")
174 parser.add_argument("-w", "--write", action="store_true",
175 help="Write back modified files")
176 parser.add_argument("-n", "--nobackups", action="store_true", default=False,
177 help="Don't write backups for modified files.")
178 parser.add_argument("sources", nargs="+", help="Source files.")
179
180
181 command_py2to3.name = "2to3"
182 command_py2to3.usage = "%(prog)s sources..."
183 command_py2to3.short = "Apply python's 2to3 tool to Python sources."
184 command_py2to3.setup_parser = setup_parser4py2to3
185
186
187 # -----------------------------------------------------------------------------
188 # COMMAND HELPERS/UTILS:
189 # -----------------------------------------------------------------------------
190 def discover_commands():
191 commands = []
192 for name, func in inspect.getmembers(inspect.getmodule(toxcmd_main)):
193 if name.startswith("__"):
194 continue
195 if name.startswith("command_") and isinstance(func, collections.Callable):
196 command_name0 = name.replace("command_", "")
197 command_name = getattr(func, "name", command_name0)
198 commands.append(Command(command_name, func))
199 return commands
200
201
202 class Command(object):
203 def __init__(self, name, func):
204 assert isinstance(name, str)
205 assert isinstance(func, collections.Callable)
206 self.name = name
207 self.func = func
208 self.parser = None
209
210 def setup_parser(self, command_parser):
211 setup_parser = getattr(self.func, "setup_parser", None)
212 if setup_parser and isinstance(setup_parser, collections.Callable):
213 setup_parser(command_parser)
214 else:
215 command_parser.add_argument("args", nargs="*")
216
217 @property
218 def usage(self):
219 usage = getattr(self.func, "usage", None)
220 return usage
221
222 @property
223 def short_description(self):
224 short_description = getattr(self.func, "short", "")
225 return short_description
226
227 @property
228 def description(self):
229 return inspect.getdoc(self.func)
230
231 def __call__(self, args):
232 return self.func(args)
233
234
235 # -----------------------------------------------------------------------------
236 # MAIN-COMMAND:
237 # -----------------------------------------------------------------------------
238 def toxcmd_main(args=None):
239 """Command util with subcommands for tox environments."""
240 usage = "USAGE: %(prog)s [OPTIONS] COMMAND args..."
241 if args is None:
242 args = sys.argv[1:]
243
244 # -- STEP: Build command-line parser.
245 parser = argparse.ArgumentParser(description=inspect.getdoc(toxcmd_main),
246 formatter_class=FORMATTER_CLASS)
247 common_parser = parser.add_argument_group("Common options")
248 common_parser.add_argument("--version", action="version", version=VERSION)
249 subparsers = parser.add_subparsers(help="commands")
250 for command in discover_commands():
251 command_parser = subparsers.add_parser(command.name,
252 usage=command.usage,
253 description=command.description,
254 help=command.short_description,
255 formatter_class=FORMATTER_CLASS)
256 command_parser.set_defaults(func=command)
257 command.setup_parser(command_parser)
258 command.parser = command_parser
259
260 # -- STEP: Process command-line and run command.
261 options = parser.parse_args(args)
262 command_function = options.func
263 return command_function(options)
264
265
266 # -----------------------------------------------------------------------------
267 # MAIN:
268 # -----------------------------------------------------------------------------
269 if __name__ == "__main__":
270 sys.exit(toxcmd_main())