Conditions | 17 |
Total Lines | 140 |
Code Lines | 85 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like cookiecutter.generate.generate_files() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | """Functions for generating a project from a project template.""" |
||
272 | def generate_files( |
||
273 | repo_dir, |
||
274 | context=None, |
||
275 | output_dir='.', |
||
276 | overwrite_if_exists=False, |
||
277 | skip_if_file_exists=False, |
||
278 | accept_hooks=True, |
||
279 | keep_project_on_failure=False, |
||
280 | ): |
||
281 | """Render the templates and saves them to files. |
||
282 | |||
283 | :param repo_dir: Project template input directory. |
||
284 | :param context: Dict for populating the template's variables. |
||
285 | :param output_dir: Where to output the generated project dir into. |
||
286 | :param overwrite_if_exists: Overwrite the contents of the output directory |
||
287 | if it exists. |
||
288 | :param skip_if_file_exists: Skip the files in the corresponding directories |
||
289 | if they already exist |
||
290 | :param accept_hooks: Accept pre and post hooks if set to `True`. |
||
291 | :param keep_project_on_failure: If `True` keep generated project directory even when |
||
292 | generation fails |
||
293 | """ |
||
294 | template_dir = find_template(repo_dir) |
||
295 | logger.debug('Generating project from %s...', template_dir) |
||
296 | context = context or OrderedDict([]) |
||
297 | |||
298 | envvars = context.get('cookiecutter', {}).get('_jinja2_env_vars', {}) |
||
299 | |||
300 | unrendered_dir = os.path.split(template_dir)[1] |
||
301 | ensure_dir_is_templated(unrendered_dir) |
||
302 | env = StrictEnvironment(context=context, keep_trailing_newline=True, **envvars) |
||
303 | try: |
||
304 | project_dir, output_directory_created = render_and_create_dir( |
||
305 | unrendered_dir, context, output_dir, env, overwrite_if_exists |
||
306 | ) |
||
307 | except UndefinedError as err: |
||
308 | msg = f"Unable to create project directory '{unrendered_dir}'" |
||
309 | raise UndefinedVariableInTemplate(msg, err, context) from err |
||
310 | |||
311 | # We want the Jinja path and the OS paths to match. Consequently, we'll: |
||
312 | # + CD to the template folder |
||
313 | # + Set Jinja's path to '.' |
||
314 | # |
||
315 | # In order to build our files to the correct folder(s), we'll use an |
||
316 | # absolute path for the target folder (project_dir) |
||
317 | |||
318 | project_dir = os.path.abspath(project_dir) |
||
319 | logger.debug('Project directory is %s', project_dir) |
||
320 | |||
321 | # if we created the output directory, then it's ok to remove it |
||
322 | # if rendering fails |
||
323 | delete_project_on_failure = output_directory_created and not keep_project_on_failure |
||
324 | |||
325 | if accept_hooks: |
||
326 | _run_hook_from_repo_dir( |
||
327 | repo_dir, 'pre_gen_project', project_dir, context, delete_project_on_failure |
||
328 | ) |
||
329 | |||
330 | with work_in(template_dir): |
||
331 | env.loader = FileSystemLoader(['.', '../templates']) |
||
332 | |||
333 | for root, dirs, files in os.walk('.'): |
||
334 | # We must separate the two types of dirs into different lists. |
||
335 | # The reason is that we don't want ``os.walk`` to go through the |
||
336 | # unrendered directories, since they will just be copied. |
||
337 | copy_dirs = [] |
||
338 | render_dirs = [] |
||
339 | |||
340 | for d in dirs: |
||
341 | d_ = os.path.normpath(os.path.join(root, d)) |
||
342 | # We check the full path, because that's how it can be |
||
343 | # specified in the ``_copy_without_render`` setting, but |
||
344 | # we store just the dir name |
||
345 | if is_copy_only_path(d_, context): |
||
346 | logger.debug('Found copy only path %s', d) |
||
347 | copy_dirs.append(d) |
||
348 | else: |
||
349 | render_dirs.append(d) |
||
350 | |||
351 | for copy_dir in copy_dirs: |
||
352 | indir = os.path.normpath(os.path.join(root, copy_dir)) |
||
353 | outdir = os.path.normpath(os.path.join(project_dir, indir)) |
||
354 | outdir = env.from_string(outdir).render(**context) |
||
355 | logger.debug('Copying dir %s to %s without rendering', indir, outdir) |
||
356 | |||
357 | # The outdir is not the root dir, it is the dir which marked as copy |
||
358 | # only in the config file. If the program hits this line, which means |
||
359 | # the overwrite_if_exists = True, and root dir exists |
||
360 | if os.path.isdir(outdir): |
||
361 | shutil.rmtree(outdir) |
||
362 | shutil.copytree(indir, outdir) |
||
363 | |||
364 | # We mutate ``dirs``, because we only want to go through these dirs |
||
365 | # recursively |
||
366 | dirs[:] = render_dirs |
||
367 | for d in dirs: |
||
368 | unrendered_dir = os.path.join(project_dir, root, d) |
||
369 | try: |
||
370 | render_and_create_dir( |
||
371 | unrendered_dir, context, output_dir, env, overwrite_if_exists |
||
372 | ) |
||
373 | except UndefinedError as err: |
||
374 | if delete_project_on_failure: |
||
375 | rmtree(project_dir) |
||
376 | _dir = os.path.relpath(unrendered_dir, output_dir) |
||
377 | msg = f"Unable to create directory '{_dir}'" |
||
378 | raise UndefinedVariableInTemplate(msg, err, context) from err |
||
379 | |||
380 | for f in files: |
||
381 | infile = os.path.normpath(os.path.join(root, f)) |
||
382 | if is_copy_only_path(infile, context): |
||
383 | outfile_tmpl = env.from_string(infile) |
||
384 | outfile_rendered = outfile_tmpl.render(**context) |
||
385 | outfile = os.path.join(project_dir, outfile_rendered) |
||
386 | logger.debug( |
||
387 | 'Copying file %s to %s without rendering', infile, outfile |
||
388 | ) |
||
389 | shutil.copyfile(infile, outfile) |
||
390 | shutil.copymode(infile, outfile) |
||
391 | continue |
||
392 | try: |
||
393 | generate_file( |
||
394 | project_dir, infile, context, env, skip_if_file_exists |
||
395 | ) |
||
396 | except UndefinedError as err: |
||
397 | if delete_project_on_failure: |
||
398 | rmtree(project_dir) |
||
399 | msg = f"Unable to create file '{infile}'" |
||
400 | raise UndefinedVariableInTemplate(msg, err, context) from err |
||
401 | |||
402 | if accept_hooks: |
||
403 | _run_hook_from_repo_dir( |
||
404 | repo_dir, |
||
405 | 'post_gen_project', |
||
406 | project_dir, |
||
407 | context, |
||
408 | delete_project_on_failure, |
||
409 | ) |
||
410 | |||
411 | return project_dir |
||
412 |