#!/usr/bin/env python3 # SPDX-License-Identifier: CC0-1.0 # # Copyright (C) 2022 Wojtek Kosior # # Available under the terms of Creative Commons Zero v1.0 Universal. import json import random import click import sys from pathlib import Path MAX_WIDTH = 80 INDENT = 3 here = Path(__file__).resolve().parent trans_suggestions = { 'en': 'suggestions', 'pl': 'sugestie' } trans_hint = { 'en': 'Random digital freedom hint', 'pl': 'Losowa wskazówka dla wolności cyfrowej' } trans_note = { 'en': 'FSF concerns', 'pl': 'zastrzeżenia FSF' } no_dangling_chars_langs = {'pl'} def wrap_text_block(text, max_width, forbid_dangling_chars=False, subsequent_indent=0): lines = [] for paragraph in text.split('\n'): line = '' accumulated_word = '' for word in paragraph.split(' '): if not word: continue accumulated_word += word if forbid_dangling_chars and len(accumulated_word) == 1: accumulated_word += ' ' continue if len(line) + len(accumulated_word) + 1 <= max_width: if line: line += ' ' line += accumulated_word else: lines.append(line) line = ' ' * subsequent_indent + accumulated_word accumulated_word = '' if line and line != ' ' * subsequent_indent: lines.append(line) line = '' return lines def format_hint(hint, hint_id, langs, max_width=MAX_WIDTH, indent=INDENT, continuation_char=' '): lines = [] for lang in langs: lines.append(f'{trans_hint[lang]} #{hint_id}: {hint["name"][lang]}') block = wrap_text_block(hint['text'][lang], max_width - indent, lang in no_dangling_chars_langs) lines.extend(' ' * indent + l for l in block) suggested = hint.get('suggested') if suggested: lines.append('/'.join(trans_suggestions[l] for l in langs) + ':') for sug_id, sug in enumerate(suggested): sug_line = f'{sug_id + 1}. {sug["name"]} <{sug["url"]}>' block = wrap_text_block(sug_line, max_width, lang in no_dangling_chars_langs, indent) lines.extend(block) note = sug.get('note') if not note: continue for lang in langs: block = wrap_text_block(f'{trans_note[lang]}: {note[lang]}', max_width - indent, lang in no_dangling_chars_langs, indent) lines.extend(' ' * indent + l for l in block) lines = [continuation_char + l[1:] if l[0] == ' ' else l for l in lines] return '\n'.join(lines) hints = json.load((here / 'hints.json').open()) @click.command() @click.option('-i', '--hint-id', default='-1', type=click.types.INT, show_default=True, help='which hint to format (-1 for random)') @click.option('-c', '--continuation-char', default=' ', type=click.types.STRING, show_default=True, help='how to start indented lines') def main(hint_id, continuation_char): if hint_id == -1: [(hint_id, hint)] = random.sample([*hints.items()], 1) else: hint_id = str(hint_id) hint = hints.get(hint_id) if hint is None: print("No such hint!", file=sys.stderr) return sys.exit(1) print(format_hint(hint, hint_id, [*hint['name'].keys()], continuation_char=continuation_char[0])) if __name__ == '__main__': main()