beautify-bash 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ """beautify_bash - a code formatter for bash and zsh scripts.
2
+
3
+ Originally written by Paul Lutus; revived with a package layout, a Typer
4
+ command line interface and dialect support.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from importlib.metadata import PackageNotFoundError
10
+ from importlib.metadata import version as _version
11
+
12
+ from .beautifier import (
13
+ Beautifier,
14
+ BeautifyBash,
15
+ FormatError,
16
+ FormatResult,
17
+ beautify_string,
18
+ )
19
+ from .dialects import BASH, DIALECTS, ZSH, Dialect, detect_dialect, get_dialect
20
+
21
+ try:
22
+ #: Single source of truth: the ``version`` field in ``pyproject.toml``.
23
+ __version__ = _version("beautify-bash")
24
+ except PackageNotFoundError: # pragma: no cover - running from an unbuilt tree
25
+ __version__ = "0.0.0+unknown"
26
+ #: Historical spelling of the version constant.
27
+ PVERSION = __version__
28
+
29
+ __all__ = [
30
+ "BASH",
31
+ "DIALECTS",
32
+ "PVERSION",
33
+ "ZSH",
34
+ "Beautifier",
35
+ "BeautifyBash",
36
+ "Dialect",
37
+ "FormatError",
38
+ "FormatResult",
39
+ "__version__",
40
+ "beautify_string",
41
+ "detect_dialect",
42
+ "get_dialect",
43
+ ]
@@ -0,0 +1,6 @@
1
+ """Allow ``python -m beautify_bash``."""
2
+
3
+ from .cli import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
@@ -0,0 +1,305 @@
1
+ """The line-based shell script indenter.
2
+
3
+ The algorithm walks the script one line at a time, keeps a running indentation
4
+ level, and re-emits each line stripped and re-indented. Regions where
5
+ re-indenting would change the meaning of the script (here-documents and
6
+ multi-line quotes) are passed through verbatim.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import sys
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from typing import IO, List, Optional, Tuple, Union
16
+
17
+ from .dialects import (
18
+ DEFAULT_DIALECT,
19
+ Dialect,
20
+ command_position_pattern,
21
+ detect_dialect,
22
+ )
23
+
24
+ __all__ = [
25
+ "Beautifier",
26
+ "BeautifyBash",
27
+ "FormatError",
28
+ "FormatResult",
29
+ "beautify_string",
30
+ ]
31
+
32
+ PathLike = Union[str, "Path"]
33
+
34
+ # Quoted spans are blanked out before keyword counting so that a `done` inside
35
+ # a string cannot dedent the script.
36
+ _SINGLE_QUOTED = re.compile(r"'.*?'")
37
+ _DOUBLE_QUOTED = re.compile(r'".*?"')
38
+ _BACKTICKED = re.compile(r"`.*?`")
39
+ _ESCAPED_BACKTICK_QUOTE = re.compile(r"\\`.*?'")
40
+ _ESCAPED_CHAR = re.compile(r"\\.")
41
+ _COMMENT = re.compile(r"(\A|\s)(#.*)")
42
+ _HERE_DOC_START = re.compile(r"(?<!<)<<(?!<)-?")
43
+ # The tag may be quoted with '…', "…" or a leading backslash (`<<\EOF`), each
44
+ # of which suppresses expansion inside the body. The lookarounds keep the
45
+ # here-string operator `<<<` and the arithmetic left shift `1 << 2` out.
46
+ _HERE_DOC_TAG = re.compile(
47
+ r""".*(?<!<)<<(?!<)(?P<dash>-?)\s*(?:\\)?['"]?(?P<tag>[A-Za-z_][\w.-]*)['"]?.*"""
48
+ )
49
+ _OPEN_BRACKETS = re.compile(r"[{(\[]")
50
+ _CLOSE_BRACKETS = re.compile(r"[})\]]")
51
+ _CASE_KEYWORD = command_position_pattern("case")
52
+ _ESAC_KEYWORD = command_position_pattern("esac")
53
+ _CASE_PATTERN = re.compile(r"\A[^(]*\)")
54
+ _CASE_BREAK = re.compile(r";;")
55
+ _QUOTE_START = re.compile(r"""(\A|\s)('|")""")
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class FormatError:
60
+ """A syntax problem noticed while indenting."""
61
+
62
+ line: int
63
+ message: str
64
+
65
+ def render(self, path: str = "") -> str:
66
+ where = f"File {path}: " if path else ""
67
+ return f"{where}error: {self.message} in line {self.line}."
68
+
69
+
70
+ @dataclass
71
+ class FormatResult:
72
+ """Outcome of formatting one script."""
73
+
74
+ text: str
75
+ errors: List[FormatError] = field(default_factory=list)
76
+ dialect: Dialect = DEFAULT_DIALECT
77
+
78
+ @property
79
+ def ok(self) -> bool:
80
+ return not self.errors
81
+
82
+ def __str__(self) -> str: # pragma: no cover - convenience only
83
+ return self.text
84
+
85
+
86
+ class Beautifier:
87
+ """Re-indent shell scripts.
88
+
89
+ Args:
90
+ indent_char: the character used for one unit of indentation.
91
+ indent_size: how many ``indent_char`` per level.
92
+ dialect: the shell dialect to assume when none is detected.
93
+ backup: whether :meth:`beautify_file` keeps a ``file~`` copy.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ indent_char: str = " ",
99
+ indent_size: int = 2,
100
+ dialect: Dialect = DEFAULT_DIALECT,
101
+ backup: bool = True,
102
+ ) -> None:
103
+ if indent_size < 0:
104
+ raise ValueError("indent_size must not be negative")
105
+ if len(indent_char) != 1:
106
+ raise ValueError("indent_char must be exactly one character")
107
+ self.indent_char = indent_char
108
+ self.indent_size = indent_size
109
+ self.dialect = dialect
110
+ self.backup = backup
111
+
112
+ # -- backwards compatible aliases for the 1.x attribute names ----------
113
+ @property
114
+ def tab_str(self) -> str:
115
+ return self.indent_char
116
+
117
+ @tab_str.setter
118
+ def tab_str(self, value: str) -> None:
119
+ self.indent_char = value
120
+
121
+ @property
122
+ def tab_size(self) -> int:
123
+ return self.indent_size
124
+
125
+ @tab_size.setter
126
+ def tab_size(self, value: int) -> None:
127
+ self.indent_size = value
128
+
129
+ # -- file helpers ------------------------------------------------------
130
+ def read_file(self, path: PathLike) -> str:
131
+ return Path(path).read_text(encoding="utf-8")
132
+
133
+ def write_file(self, path: PathLike, data: str) -> None:
134
+ Path(path).write_text(data, encoding="utf-8")
135
+
136
+ # -- core --------------------------------------------------------------
137
+ def format(
138
+ self,
139
+ data: str,
140
+ dialect: Optional[Dialect] = None,
141
+ ) -> FormatResult:
142
+ """Indent ``data`` and report any syntax problems found on the way."""
143
+ active = dialect or self.dialect
144
+ indent_unit = self.indent_char * self.indent_size
145
+ level = 0
146
+ case_stack: List[int] = []
147
+ errors: List[FormatError] = []
148
+ output: List[str] = []
149
+
150
+ in_here_doc = False
151
+ here_tag = ""
152
+ here_doc_dash = False
153
+ in_ext_quote = False
154
+ defer_ext_quote = False
155
+ ext_quote_char = ""
156
+
157
+ line_no = 0
158
+ for line_no, raw in enumerate(data.split("\n"), start=1):
159
+ record = raw.rstrip()
160
+ stripped = record.strip()
161
+ test = self._strip_literals(stripped)
162
+
163
+ if in_here_doc:
164
+ # Here-doc bodies are data: emit them byte for byte.
165
+ output.append(raw)
166
+ # A `<<-` terminator may be indented, a plain `<<` one may not.
167
+ terminator = raw.strip() if here_doc_dash else raw
168
+ if terminator == here_tag:
169
+ in_here_doc = False
170
+ continue
171
+
172
+ # The line that *opens* a here-doc is still ordinary code, so note
173
+ # the tag now and switch over once the line has been emitted.
174
+ opens_here_doc = False
175
+ if _HERE_DOC_START.search(test):
176
+ match = _HERE_DOC_TAG.match(stripped)
177
+ if match is not None and match.group("tag"):
178
+ here_tag = match.group("tag")
179
+ here_doc_dash = bool(match.group("dash"))
180
+ opens_here_doc = True
181
+
182
+ # A quote left open on a previous line makes this line string data.
183
+ closes_ext_quote = False
184
+ if in_ext_quote:
185
+ if ext_quote_char in test:
186
+ # Keep whatever follows the closing quote for counting.
187
+ test = test.split(ext_quote_char, 1)[1]
188
+ in_ext_quote = False
189
+ closes_ext_quote = True
190
+ elif _QUOTE_START.search(test):
191
+ # The quote only takes effect after this line is emitted.
192
+ defer_ext_quote = True
193
+ ext_quote_char = re.sub(r""".*(['"]).*""", r"\1", test, count=1)
194
+ test = test.split(ext_quote_char, 1)[0]
195
+
196
+ if in_ext_quote:
197
+ # Wholly inside a multi-line string: emit byte for byte.
198
+ output.append(raw)
199
+ else:
200
+ opened = active.count_open(test) + len(_OPEN_BRACKETS.findall(test))
201
+ closed = active.count_close(test) + len(_CLOSE_BRACKETS.findall(test))
202
+
203
+ if _ESAC_KEYWORD.search(test):
204
+ if case_stack:
205
+ closed += case_stack.pop()
206
+ else:
207
+ errors.append(FormatError(line_no, '"esac" before "case"'))
208
+
209
+ if case_stack:
210
+ # `pattern)` inside a case opens a branch; `;;` closes it.
211
+ if _CASE_PATTERN.search(test):
212
+ closed -= 2 # undo the `)` counted above
213
+ case_stack[-1] += 1
214
+ if _CASE_BREAK.search(test):
215
+ closed += 1
216
+ case_stack[-1] -= 1
217
+ hanging = 0
218
+ net = opened - closed
219
+ else:
220
+ net = opened - closed
221
+ hangs = active.is_hanging(test) or (
222
+ net == 0 and active.starts_with_close(test)
223
+ )
224
+ hanging = -1 if hangs else 0
225
+
226
+ level += min(net, 0)
227
+ if closes_ext_quote:
228
+ # The leading whitespace of this line is string content.
229
+ output.append(record)
230
+ elif stripped:
231
+ output.append((indent_unit * max(0, level + hanging)) + stripped)
232
+ else:
233
+ output.append("")
234
+ level += max(net, 0)
235
+
236
+ if defer_ext_quote:
237
+ in_ext_quote = True
238
+ defer_ext_quote = False
239
+ if _CASE_KEYWORD.search(test):
240
+ case_stack.append(0)
241
+ if opens_here_doc:
242
+ in_here_doc = True
243
+
244
+ if level != 0:
245
+ errors.append(FormatError(line_no, f"indent/outdent mismatch: {level}"))
246
+ return FormatResult("\n".join(output), errors, active)
247
+
248
+ @staticmethod
249
+ def _strip_literals(stripped_record: str) -> str:
250
+ """Blank out quotes, escapes and comments before keyword counting."""
251
+ test = _SINGLE_QUOTED.sub("", stripped_record)
252
+ test = _DOUBLE_QUOTED.sub("", test)
253
+ test = _BACKTICKED.sub("", test)
254
+ test = _ESCAPED_BACKTICK_QUOTE.sub("", test)
255
+ test = _ESCAPED_CHAR.sub("", test)
256
+ return _COMMENT.sub("", test, count=1)
257
+
258
+ # -- 1.x compatible entry points --------------------------------------
259
+ def beautify_string(self, data: str, path: str = "") -> Tuple[str, bool]:
260
+ """Format ``data``; return ``(text, had_error)`` as version 1.x did."""
261
+ result = self.format(data, detect_dialect(data, path, self.dialect))
262
+ for error in result.errors:
263
+ sys.stderr.write(error.render(path) + "\n")
264
+ return result.text, not result.ok
265
+
266
+ def beautify_file(
267
+ self,
268
+ path: PathLike,
269
+ stdin: Optional[IO[str]] = None,
270
+ stdout: Optional[IO[str]] = None,
271
+ ) -> bool:
272
+ """Format a file in place (or stdin to stdout for ``-``).
273
+
274
+ Returns ``True`` when a syntax problem was reported.
275
+ """
276
+ if str(path) == "-":
277
+ data = (stdin or sys.stdin).read()
278
+ text, error = self.beautify_string(data, "(stdin)")
279
+ (stdout or sys.stdout).write(text)
280
+ return error
281
+ data = self.read_file(path)
282
+ text, error = self.beautify_string(data, str(path))
283
+ if data != text:
284
+ if self.backup:
285
+ self.write_file(f"{path}~", data)
286
+ self.write_file(path, text)
287
+ return error
288
+
289
+
290
+ #: Historical name kept so ``from beautify_bash import BeautifyBash`` keeps working.
291
+ BeautifyBash = Beautifier
292
+
293
+
294
+ def beautify_string(
295
+ data: str,
296
+ dialect: Optional[Dialect] = None,
297
+ indent_char: str = " ",
298
+ indent_size: int = 2,
299
+ ) -> FormatResult:
300
+ """Format ``data`` in one call.
301
+
302
+ When ``dialect`` is omitted it is detected from the script's shebang.
303
+ """
304
+ beautifier = Beautifier(indent_char=indent_char, indent_size=indent_size)
305
+ return beautifier.format(data, dialect or detect_dialect(data))
beautify_bash/cli.py ADDED
@@ -0,0 +1,190 @@
1
+ """Command line interface built on Typer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import sys
7
+ from enum import Enum
8
+ from pathlib import Path
9
+ from typing import List, Optional
10
+
11
+ import typer
12
+
13
+ from . import __version__
14
+ from .beautifier import Beautifier
15
+ from .dialects import DEFAULT_DIALECT, Dialect, detect_dialect, get_dialect
16
+
17
+ __all__ = ["DialectChoice", "app", "main"]
18
+
19
+
20
+ class DialectChoice(str, Enum):
21
+ """``--dialect`` values; ``auto`` inspects the shebang and file name."""
22
+
23
+ auto = "auto"
24
+ bash = "bash"
25
+ zsh = "zsh"
26
+
27
+
28
+ app = typer.Typer(
29
+ add_completion=True,
30
+ context_settings={"help_option_names": ["-h", "--help"]},
31
+ help="Re-indent bash and zsh scripts.",
32
+ )
33
+
34
+
35
+ def _version_callback(value: bool) -> None:
36
+ if value:
37
+ typer.echo(f"beautify-bash {__version__}")
38
+ raise typer.Exit
39
+
40
+
41
+ def _resolve_dialect(choice: DialectChoice, data: str, name: str) -> Dialect:
42
+ if choice is DialectChoice.auto:
43
+ return detect_dialect(data, name, DEFAULT_DIALECT)
44
+ return get_dialect(choice.value)
45
+
46
+
47
+ def _diff(before: str, after: str, name: str) -> str:
48
+ return "".join(
49
+ difflib.unified_diff(
50
+ before.splitlines(keepends=True),
51
+ after.splitlines(keepends=True),
52
+ fromfile=f"a/{name}",
53
+ tofile=f"b/{name}",
54
+ )
55
+ )
56
+
57
+
58
+ @app.command(no_args_is_help=True)
59
+ def main(
60
+ files: List[str] = typer.Argument(
61
+ ...,
62
+ metavar="FILES...",
63
+ help='Scripts to format; "-" reads standard input.',
64
+ ),
65
+ output: Optional[str] = typer.Option(
66
+ None,
67
+ "--output",
68
+ "-o",
69
+ metavar="PATH",
70
+ help='Write the result to PATH ("-" for stdout) instead of stdout.',
71
+ ),
72
+ write: bool = typer.Option(
73
+ False,
74
+ "--write",
75
+ "-w",
76
+ help="Rewrite each input file in place instead of printing.",
77
+ ),
78
+ indent_size: int = typer.Option(
79
+ 2, "--indent", "-i", min=0, help="Indentation width per level."
80
+ ),
81
+ use_tabs: bool = typer.Option(
82
+ False, "--tabs/--spaces", help="Indent with tab characters."
83
+ ),
84
+ dialect: DialectChoice = typer.Option(
85
+ DialectChoice.auto, "--dialect", "-d", help="Shell dialect to assume."
86
+ ),
87
+ check: bool = typer.Option(
88
+ False, "--check", help="Write nothing; exit 1 if a file would change."
89
+ ),
90
+ show_diff: bool = typer.Option(
91
+ False, "--diff", help="Print a unified diff instead of the result."
92
+ ),
93
+ backup: bool = typer.Option(
94
+ True, "--backup/--no-backup", help='With -w, keep the original as "FILE~".'
95
+ ),
96
+ quiet: bool = typer.Option(False, "--quiet", "-q", help="Suppress progress notes."),
97
+ version: Optional[bool] = typer.Option(
98
+ None,
99
+ "--version",
100
+ "-V",
101
+ callback=_version_callback,
102
+ is_eager=True,
103
+ help="Show the version and exit.",
104
+ ),
105
+ ) -> None:
106
+ """Print each formatted FILE to standard output.
107
+
108
+ Use ``-w`` to rewrite the files in place, or ``-o PATH`` to collect the
109
+ result in one file. ``--check`` and ``--diff`` never write anything.
110
+ """
111
+ _reject_conflicting_modes(files, output, write, check, show_diff)
112
+
113
+ exit_code = 0
114
+ collected: List[str] = []
115
+
116
+ for name in files:
117
+ try:
118
+ data = sys.stdin.read() if name == "-" else Path(name).read_text("utf-8")
119
+ except OSError as exc:
120
+ typer.echo(f"beautify-bash: {name}: {exc.strerror}", err=True)
121
+ exit_code = 2
122
+ continue
123
+
124
+ label = "(stdin)" if name == "-" else name
125
+ beautifier = Beautifier(
126
+ indent_char="\t" if use_tabs else " ",
127
+ indent_size=1 if use_tabs else indent_size,
128
+ backup=backup,
129
+ )
130
+ result = beautifier.format(data, _resolve_dialect(dialect, data, label))
131
+
132
+ for error in result.errors:
133
+ typer.echo(error.render(label), err=True)
134
+ exit_code = max(exit_code, 1)
135
+
136
+ changed = result.text != data
137
+ if changed and (check or show_diff):
138
+ exit_code = max(exit_code, 1)
139
+
140
+ if show_diff:
141
+ typer.echo(_diff(data, result.text, label), nl=False)
142
+ elif check:
143
+ if changed and not quiet:
144
+ typer.echo(f"would reformat {label}", err=True)
145
+ elif write:
146
+ if changed:
147
+ if backup:
148
+ Path(f"{name}~").write_text(data, encoding="utf-8")
149
+ Path(name).write_text(result.text, encoding="utf-8")
150
+ if not quiet:
151
+ typer.echo(f"reformatted {name}", err=True)
152
+ elif output is not None and output != "-":
153
+ collected.append(result.text)
154
+ else:
155
+ typer.echo(result.text, nl=False)
156
+
157
+ if collected:
158
+ assert output is not None # guaranteed by the branch that filled `collected`
159
+ try:
160
+ Path(output).write_text("".join(collected), encoding="utf-8")
161
+ except OSError as exc:
162
+ typer.echo(f"beautify-bash: {output}: {exc.strerror}", err=True)
163
+ exit_code = max(exit_code, 2)
164
+
165
+ raise typer.Exit(exit_code)
166
+
167
+
168
+ def _reject_conflicting_modes(
169
+ files: List[str],
170
+ output: Optional[str],
171
+ write: bool,
172
+ check: bool,
173
+ show_diff: bool,
174
+ ) -> None:
175
+ """Fail early on option combinations that cannot all be honoured."""
176
+ if write and output is not None:
177
+ raise typer.BadParameter("--write cannot be combined with --output.")
178
+ if write and "-" in files:
179
+ raise typer.BadParameter("--write cannot rewrite standard input.")
180
+ if check and show_diff:
181
+ raise typer.BadParameter("--check cannot be combined with --diff.")
182
+ for flag, name in ((check, "--check"), (show_diff, "--diff")):
183
+ if flag and write:
184
+ raise typer.BadParameter(f"{name} cannot be combined with --write.")
185
+ if flag and output is not None:
186
+ raise typer.BadParameter(f"{name} cannot be combined with --output.")
187
+
188
+
189
+ if __name__ == "__main__": # pragma: no cover
190
+ app()
@@ -0,0 +1,196 @@
1
+ """Shell dialect definitions.
2
+
3
+ A :class:`Dialect` describes the keywords that open and close an indentation
4
+ block for a given shell. The beautifier is otherwise dialect agnostic, so
5
+ adding a new shell is a matter of adding a :class:`Dialect` instance here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass, field
12
+ from typing import Dict, Optional, Pattern, Tuple
13
+
14
+ __all__ = [
15
+ "BASH",
16
+ "DIALECTS",
17
+ "ZSH",
18
+ "Dialect",
19
+ "command_position_pattern",
20
+ "detect_dialect",
21
+ "get_dialect",
22
+ ]
23
+
24
+
25
+ #: A shell reserved word only acts as a keyword in *command position*: at the
26
+ #: start of the line or right after one of these separators. Without this,
27
+ #: ``echo done`` would dedent the script.
28
+ _COMMAND_POSITION = r"(?:\A|[;&|(){}])\s*"
29
+
30
+
31
+ def _keyword_pattern(keywords: Tuple[str, ...], trailer: str) -> Pattern[str]:
32
+ """Build a regex matching any of ``keywords`` used as a reserved word."""
33
+ alternation = "|".join(re.escape(word) for word in keywords)
34
+ return re.compile(rf"{_COMMAND_POSITION}(?:{alternation})(?:{trailer})")
35
+
36
+
37
+ def command_position_pattern(keyword: str) -> Pattern[str]:
38
+ """Regex matching a single ``keyword`` used as a reserved word."""
39
+ return _keyword_pattern((keyword,), r";|\)|\||\Z|\s")
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Dialect:
44
+ """Indentation rules for one shell dialect."""
45
+
46
+ name: str
47
+ #: Keywords that open a block (``then``, ``do``, ...).
48
+ open_keywords: Tuple[str, ...]
49
+ #: Keywords that close a block (``fi``, ``done``, ...).
50
+ close_keywords: Tuple[str, ...]
51
+ #: Keywords printed one level to the left without changing the running
52
+ #: level (``else``, ``elif``).
53
+ hanging_keywords: Tuple[str, ...] = ("else", "elif")
54
+ #: File extensions that imply this dialect.
55
+ extensions: Tuple[str, ...] = ()
56
+ #: Interpreter basenames that imply this dialect via the shebang line.
57
+ interpreters: Tuple[str, ...] = ()
58
+
59
+ open_re: Pattern[str] = field(init=False, repr=False, compare=False)
60
+ close_re: Pattern[str] = field(init=False, repr=False, compare=False)
61
+ hanging_re: Pattern[str] = field(init=False, repr=False, compare=False)
62
+ starts_close_re: Pattern[str] = field(init=False, repr=False, compare=False)
63
+
64
+ def __post_init__(self) -> None:
65
+ # ``frozen=True`` blocks normal assignment; go through object.__setattr__.
66
+ object.__setattr__(
67
+ self, "open_re", _keyword_pattern(self.open_keywords, r";|\Z|\s")
68
+ )
69
+ object.__setattr__(
70
+ self, "close_re", _keyword_pattern(self.close_keywords, r";|\)|\||\Z|\s")
71
+ )
72
+ alternation = "|".join(re.escape(word) for word in self.hanging_keywords)
73
+ object.__setattr__(self, "hanging_re", re.compile(rf"^({alternation})\b"))
74
+ closers = "|".join(re.escape(word) for word in self.close_keywords)
75
+ object.__setattr__(
76
+ self, "starts_close_re", re.compile(rf"^(?:[)}}\]]|(?:{closers})\b)")
77
+ )
78
+
79
+ def count_open(self, text: str) -> int:
80
+ """Number of block-opening keywords in ``text``."""
81
+ return len(self.open_re.findall(text))
82
+
83
+ def count_close(self, text: str) -> int:
84
+ """Number of block-closing keywords in ``text``."""
85
+ return len(self.close_re.findall(text))
86
+
87
+ def is_hanging(self, text: str) -> bool:
88
+ """True when ``text`` starts with a keyword such as ``else``.
89
+
90
+ Such a line is printed one level to the left without changing the
91
+ running indentation level.
92
+ """
93
+ return self.hanging_re.search(text) is not None
94
+
95
+ def starts_with_close(self, text: str) -> bool:
96
+ """True when ``text`` opens with a closing bracket or keyword.
97
+
98
+ Combined with a net indentation change of zero this identifies
99
+ "close then reopen" lines such as ``} else {`` or zsh's
100
+ ``} always {``, which belong one level to the left.
101
+ """
102
+ return self.starts_close_re.search(text) is not None
103
+
104
+
105
+ #: POSIX-ish bash. ``elif`` closes the previous branch and the ``then`` that
106
+ #: follows on the same line reopens it, so it is listed as a close keyword.
107
+ BASH = Dialect(
108
+ name="bash",
109
+ open_keywords=("case", "then", "do"),
110
+ close_keywords=("esac", "fi", "done", "elif"),
111
+ extensions=(".sh", ".bash", ".bashrc", ".ksh"),
112
+ interpreters=("sh", "bash", "ksh", "dash"),
113
+ )
114
+
115
+ #: zsh understands everything bash does plus the csh-flavoured ``foreach ...
116
+ #: end`` and ``while ... end`` loop forms.
117
+ ZSH = Dialect(
118
+ name="zsh",
119
+ open_keywords=("case", "then", "do", "foreach"),
120
+ close_keywords=("esac", "fi", "done", "elif", "end"),
121
+ extensions=(".zsh", ".zshrc", ".zshenv", ".zprofile", ".zlogin", ".zlogout"),
122
+ interpreters=("zsh",),
123
+ )
124
+
125
+ DIALECTS: Dict[str, Dialect] = {d.name: d for d in (BASH, ZSH)}
126
+
127
+ DEFAULT_DIALECT = BASH
128
+
129
+ _SHEBANG_RE = re.compile(r"^#!\s*(?P<path>\S+)(?P<rest>.*)$")
130
+
131
+
132
+ def get_dialect(name: str) -> Dialect:
133
+ """Look up a dialect by name.
134
+
135
+ Raises:
136
+ KeyError: if ``name`` is not a known dialect.
137
+ """
138
+ try:
139
+ return DIALECTS[name.lower()]
140
+ except KeyError:
141
+ known = ", ".join(sorted(DIALECTS))
142
+ raise KeyError(f"unknown dialect {name!r}; known dialects: {known}") from None
143
+
144
+
145
+ def detect_dialect(
146
+ data: str = "",
147
+ filename: str = "",
148
+ default: Dialect = DEFAULT_DIALECT,
149
+ ) -> Dialect:
150
+ """Guess the dialect from a shebang line, falling back to the file name.
151
+
152
+ The shebang wins over the extension because it is what actually runs the
153
+ script. ``env`` wrappers (``#!/usr/bin/env zsh``) are unwrapped.
154
+ """
155
+ dialect = _from_shebang(data)
156
+ if dialect is not None:
157
+ return dialect
158
+ dialect = _from_filename(filename)
159
+ if dialect is not None:
160
+ return dialect
161
+ return default
162
+
163
+
164
+ def _from_shebang(data: str) -> Optional[Dialect]:
165
+ first_line = data.split("\n", 1)[0].strip()
166
+ match = _SHEBANG_RE.match(first_line)
167
+ if match is None:
168
+ return None
169
+ words = [match.group("path"), *match.group("rest").split()]
170
+ # Skip `env` and any VAR=value / -flag arguments it may carry.
171
+ interpreter = ""
172
+ for word in words:
173
+ base = word.rsplit("/", 1)[-1]
174
+ if base == "env" or base.startswith("-") or "=" in base:
175
+ continue
176
+ interpreter = base
177
+ break
178
+ for dialect in DIALECTS.values():
179
+ if interpreter in dialect.interpreters:
180
+ return dialect
181
+ return None
182
+
183
+
184
+ def _from_filename(filename: str) -> Optional[Dialect]:
185
+ if not filename:
186
+ return None
187
+ base = filename.rsplit("/", 1)[-1]
188
+ suffix = base[base.rindex(".") :].lower() if "." in base[1:] else ""
189
+ name = base.lower()
190
+ for dialect in DIALECTS.values():
191
+ if suffix and suffix in dialect.extensions:
192
+ return dialect
193
+ # Dotfiles such as `.zshrc` have no suffix in the usual sense.
194
+ if f".{name.lstrip('.')}" in dialect.extensions:
195
+ return dialect
196
+ return None
beautify_bash/py.typed ADDED
File without changes
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.5
2
+ Name: beautify-bash
3
+ Version: 2.0.0
4
+ Summary: Code formatter / beautifier for bash and zsh shell scripts.
5
+ Project-URL: Homepage, https://github.com/ewiger/beautify_bash
6
+ Project-URL: Repository, https://github.com/ewiger/beautify_bash
7
+ Project-URL: Issues, https://github.com/ewiger/beautify_bash/issues
8
+ Project-URL: Changelog, https://github.com/ewiger/beautify_bash/blob/master/CHANGELOG.md
9
+ Author: Paul Lutus
10
+ Maintainer-email: Yauhen Yakimovich <yauhen.yakimovich.mail@gmail.com>
11
+ License-Expression: GPL-2.0-or-later
12
+ License-File: LICENSE
13
+ Keywords: bash,beautifier,formatter,indent,shell,zsh
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Unix Shell
25
+ Classifier: Topic :: Software Development :: Quality Assurance
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.9
28
+ Requires-Dist: typer>=0.12
29
+ Description-Content-Type: text/markdown
30
+
31
+ # beautify_bash
32
+
33
+ [![CI](https://github.com/ewiger/beautify_bash/actions/workflows/ci.yml/badge.svg)](https://github.com/ewiger/beautify_bash/actions/workflows/ci.yml)
34
+ [![PyPI](https://img.shields.io/pypi/v/beautify-bash)](https://pypi.org/project/beautify-bash/)
35
+
36
+ A code formatter / beautifier for **bash** and **zsh** shell scripts.
37
+
38
+ Originally written in Ruby, then Python, by [Paul Lutus][arachnoid]; revived
39
+ here with a proper package layout, a [Typer][typer] CLI, [uv][uv] tooling,
40
+ a test suite, and support for shell dialects.
41
+
42
+ [arachnoid]: http://arachnoid.com/python/beautify_bash_program.html
43
+ [typer]: https://typer.tiangolo.com/
44
+ [uv]: https://docs.astral.sh/uv/
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ uv tool install beautify-bash # as a standalone command
50
+ uv add beautify-bash # as a project dependency
51
+ pipx install beautify-bash # or with pipx
52
+ ```
53
+
54
+ Run it without installing:
55
+
56
+ ```bash
57
+ uvx beautify-bash script.sh
58
+ ```
59
+
60
+ Requires Python 3.9 or newer (tested through 3.14).
61
+
62
+ ## Use
63
+
64
+ Like `shfmt` and `gofmt`, it prints to standard output and changes nothing on
65
+ disk unless you ask it to:
66
+
67
+ ```bash
68
+ beautify-bash script.sh # print the formatted script
69
+ beautify-bash -w script.sh # rewrite in place, keeping script.sh~
70
+ beautify-bash -w --no-backup script.sh # rewrite without a backup
71
+ beautify-bash -o tidy.sh script.sh # write the result to another file
72
+ beautify-bash --check src/*.sh # exit 1 if anything would change (CI)
73
+ beautify-bash --diff script.sh # show a unified diff, write nothing
74
+ beautify-bash --indent 4 script.sh # four spaces per level
75
+ beautify-bash --tabs script.sh # indent with tabs
76
+ beautify-bash -d zsh script.zsh # force a dialect
77
+ cat script.sh | beautify-bash - # stdin to stdout
78
+ beautify-bash -w src/*.sh # format a whole directory
79
+ python -m beautify_bash script.sh # same thing via the module
80
+ ```
81
+
82
+ Standard output carries only the formatted script; progress notes, diffs of
83
+ the `--check` kind, and errors go to standard error, so `beautify-bash x.sh >
84
+ y.sh` is safe.
85
+
86
+ ### Options
87
+
88
+ | Option | Meaning |
89
+ | --- | --- |
90
+ | *(none)* | Print the formatted script to stdout; several inputs are concatenated. |
91
+ | `-w`, `--write` | Rewrite each input file in place. |
92
+ | `-o`, `--output PATH` | Write the result to `PATH` (`-` means stdout). |
93
+ | `-i`, `--indent N` | Spaces per indentation level (default `2`). |
94
+ | `--tabs` / `--spaces` | Indent with tab characters instead of spaces. |
95
+ | `-d`, `--dialect` | `auto` (default), `bash`, or `zsh`. |
96
+ | `--check` | Write nothing; exit `1` if a file would change. |
97
+ | `--diff` | Print a unified diff instead of writing. |
98
+ | `--backup` / `--no-backup` | With `-w`, keep the original as `FILE~` (default on). |
99
+ | `-q`, `--quiet` | Suppress per-file progress notes. |
100
+ | `-V`, `--version` | Print the version and exit. |
101
+
102
+ `-w`, `-o`, `--check` and `--diff` are mutually exclusive, and `-w` cannot
103
+ rewrite standard input.
104
+
105
+ Exit codes: `0` clean, `1` a file changed (under `--check`/`--diff`) or a
106
+ syntax problem was reported, `2` a file could not be read or written, or the
107
+ options conflict.
108
+
109
+ ## Dialects
110
+
111
+ `--dialect auto` picks the dialect from the shebang line first, then the file
112
+ name (`.zsh`, `.zshrc`, `.zshenv`, …), and falls back to bash.
113
+
114
+ | Dialect | Block keywords |
115
+ | --- | --- |
116
+ | `bash` | `case`/`esac`, `if`/`then`/`elif`/`else`/`fi`, `do`/`done`, `{}`, `()`, `[]` |
117
+ | `zsh` | everything bash has, plus `foreach … end` and `} always {` |
118
+
119
+ Adding a shell means adding one `Dialect` instance in
120
+ [dialects.py](src/beautify_bash/dialects.py) — the indenter itself is dialect
121
+ agnostic.
122
+
123
+ ## Library use
124
+
125
+ ```python
126
+ from beautify_bash import ZSH, Beautifier, beautify_string
127
+
128
+ result = beautify_string(open("script.sh").read())
129
+ print(result.text)
130
+ print(result.dialect.name, result.ok, result.errors)
131
+
132
+ # Explicit configuration
133
+ tidy = Beautifier(indent_char="\t", indent_size=1, dialect=ZSH)
134
+ print(tidy.format("foreach f (a b)\nprint $f\nend").text)
135
+ ```
136
+
137
+ The 1.x API (`BeautifyBash`, `beautify_string(data, path) -> (text, error)`,
138
+ `beautify_file`, `tab_str`, `tab_size`) still works.
139
+
140
+ ## What is preserved verbatim
141
+
142
+ Re-indenting must never change what a script does, so these regions are passed
143
+ through byte for byte:
144
+
145
+ - here-document bodies (`<<EOF`, and `<<-EOF` with its indented terminator),
146
+ - lines inside a multi-line `'…'` or `"…"` string,
147
+ - everything inside comments and quotes is ignored for keyword counting.
148
+
149
+ Shell reserved words only count as keywords in *command position* — at the
150
+ start of a line or after `;`, `&`, `|`, or a bracket — so `echo done` no longer
151
+ dedents the following lines.
152
+
153
+ ## Pre-commit
154
+
155
+ ```yaml
156
+ repos:
157
+ - repo: local
158
+ hooks:
159
+ - id: beautify-bash
160
+ name: beautify-bash
161
+ entry: beautify-bash -w
162
+ language: system
163
+ types: [shell]
164
+ ```
165
+
166
+ ## Development
167
+
168
+ ```bash
169
+ uv sync # create .venv and install dev dependencies
170
+ uv run pytest # run the tests
171
+ uv run pytest --cov # with coverage
172
+ uv run ruff check . # lint
173
+ uv run ruff format . # format the Python sources
174
+ uv run mypy # type check
175
+ ```
176
+
177
+ The test suite is in [tests/](tests/):
178
+
179
+ - [test_beautifier.py](tests/test_beautifier.py) — the indenting core,
180
+ - [test_dialects.py](tests/test_dialects.py) — dialect detection and zsh syntax,
181
+ - [test_cli.py](tests/test_cli.py) — the CLI, via Typer's `CliRunner`,
182
+ - [test_mocks.py](tests/test_mocks.py) — worked `unittest.mock` examples
183
+ (patching methods, `mock_open`, fake streams, spies, stubs, autospec).
184
+
185
+ ## Roadmap
186
+
187
+ See [TODO.md](TODO.md).
188
+
189
+ ## License
190
+
191
+ GPL-2.0-or-later. See [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ beautify_bash/__init__.py,sha256=t30PhAgmaY1Uonezgl1BcHWpszsp100DGOi2tuWnYkk,1079
2
+ beautify_bash/__main__.py,sha256=IpDBb626Lpk5U5JnwjUj78NAIdDOqeOqQZ5OfWMwT2U,101
3
+ beautify_bash/beautifier.py,sha256=IW5JBRUPRZqxO7eCD4CBEjsbkpHc6IDgXMAtTayvh5Q,10814
4
+ beautify_bash/cli.py,sha256=OOF5RObXqoBR7lltAK9Jko7yGaCKtJuU6RMmF6NypBo,6023
5
+ beautify_bash/dialects.py,sha256=1CyeidZKAFsub2q7TXC-TEdJRoctDuHd1MkS-BKAxhk,6942
6
+ beautify_bash/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ beautify_bash-2.0.0.dist-info/METADATA,sha256=_4--XuzLThedK8iIBg3tsLEp7-rA-JGORiRpbDMpR-A,7050
8
+ beautify_bash-2.0.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
9
+ beautify_bash-2.0.0.dist-info/entry_points.txt,sha256=M2L6UHBRYQf374w5A09We6IL3986SAi-HLkT7ZTvpjc,94
10
+ beautify_bash-2.0.0.dist-info/licenses/LICENSE,sha256=7a72Msu2Q-TnoiFxemxEGkwafJGObk1W3rw9hzmyM_Y,17984
11
+ beautify_bash-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ beautify-bash = beautify_bash.cli:app
3
+ beautify_bash = beautify_bash.cli:app
@@ -0,0 +1,338 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
+ <https://fsf.org/>
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, see <https://www.gnu.org/licenses/>.
308
+
309
+ Also add information on how to contact you by electronic and paper mail.
310
+
311
+ If the program is interactive, make it output a short notice like this
312
+ when it starts in an interactive mode:
313
+
314
+ Gnomovision version 69, Copyright (C) year name of author
315
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
316
+ This is free software, and you are welcome to redistribute it
317
+ under certain conditions; type `show c' for details.
318
+
319
+ The hypothetical commands `show w' and `show c' should show the appropriate
320
+ parts of the General Public License. Of course, the commands you use may
321
+ be called something other than `show w' and `show c'; they could even be
322
+ mouse-clicks or menu items--whatever suits your program.
323
+
324
+ You should also get your employer (if you work as a programmer) or your
325
+ school, if any, to sign a "copyright disclaimer" for the program, if
326
+ necessary. Here is a sample; alter the names:
327
+
328
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
329
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
330
+
331
+ <signature of Moe Ghoul>, 1 April 1989
332
+ Moe Ghoul, President of Vice
333
+
334
+ This General Public License does not permit incorporating your program into
335
+ proprietary programs. If your program is a subroutine library, you may
336
+ consider it more useful to permit linking proprietary applications with the
337
+ library. If this is what you want to do, use the GNU Lesser General
338
+ Public License instead of this License.