| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''Classes for generating file output.''' |
| 5 |
|
| 6 |
|
| 7 |
_GENERATION_NOTICE = '''\ |
| 8 |
# This script was generated by crazy-complete. |
| 9 |
# crazy-complete: A tool that creates robust and reliable autocompletion scripts for Bash, Fish and Zsh. |
| 10 |
# For more information, visit: https://github.com/crazy-complete/crazy-complete''' |
| 11 |
|
| 12 |
|
| 13 |
class Output: |
| 14 |
'''Class for generating output.''' |
| 15 |
|
| 16 |
def __init__(self, config, helpers): |
| 17 |
self.config = config |
| 18 |
self.helpers = helpers |
| 19 |
self.output = [] |
| 20 |
|
| 21 |
def add(self, string): |
| 22 |
'''Add to output.''' |
| 23 |
self.output.append(string) |
| 24 |
|
| 25 |
def extend(self, strings): |
| 26 |
'''Add many to output.''' |
| 27 |
self.output.extend(strings) |
| 28 |
|
| 29 |
def add_as_block(self): |
| 30 |
'''Return a helper context manager for adding a multi-line block.''' |
| 31 |
|
| 32 |
class _Block: |
| 33 |
def __init__(self, parent): |
| 34 |
self.parent = parent |
| 35 |
self.lines = [] |
| 36 |
|
| 37 |
def add(self, line): |
| 38 |
'''Add a single line to the current block.''' |
| 39 |
self.lines.append(line) |
| 40 |
|
| 41 |
def extend(self, lines): |
| 42 |
'''Add multiple lines to current block.''' |
| 43 |
self.lines.extend(lines) |
| 44 |
|
| 45 |
def __enter__(self): |
| 46 |
return self |
| 47 |
|
| 48 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 49 |
block_text = "\n".join(self.lines) |
| 50 |
self.parent.output.append(block_text) |
| 51 |
|
| 52 |
return _Block(self) |
| 53 |
|
| 54 |
def add_generation_notice(self): |
| 55 |
'''Add the generation notice.''' |
| 56 |
self.add(_GENERATION_NOTICE) |
| 57 |
|
| 58 |
def add_comments(self): |
| 59 |
'''Add additional comments.''' |
| 60 |
if self.config.comments: |
| 61 |
self.add('\n'.join(f'# {c}' for c in self.config.comments)) |
| 62 |
|
| 63 |
def add_included_files(self): |
| 64 |
'''Add included files.''' |
| 65 |
for file in self.config.include_files: |
| 66 |
with open(file, 'r', encoding='utf-8') as fh: |
| 67 |
self.add(fh.read().strip()) |
| 68 |
|
| 69 |
def add_helper_functions_code(self): |
| 70 |
'''Add helper functions.''' |
| 71 |
for code in self.helpers.get_used_functions_code(): |
| 72 |
self.add(code) |
| 73 |
|
| 74 |
def add_vim_modeline(self, shell): |
| 75 |
'''Add the vim modeline.''' |
| 76 |
if self.config.vim_modeline: |
| 77 |
vim = 'vim' |
| 78 |
self.add(f'# {vim}: ft={shell} ts=2 sts=2 sw=2 et') |
| 79 |
|
| 80 |
def get(self): |
| 81 |
'''Return the output.''' |
| 82 |
return '\n\n'.join(filter(None, self.output)) |