localtools-sql-formatter 1.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,223 @@
1
+ """Shared localtools runtime implementing kit/CONTRACT.md v1. Copy verbatim; tool code lives in __main__.py.
2
+
3
+ Multipart: Python 3.13 removed `cgi`, and email.parser buffers whole bodies in memory, so uploads are parsed with
4
+ `multipart` (defnull, MIT, single pure-Python file, no deps): parts over 64 KB spool to anonymous temp files that
5
+ the OS deletes on close; `form()` closes them after the request.
6
+ """
7
+ import argparse
8
+ import json
9
+ import mimetypes
10
+ import os
11
+ import signal
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ import urllib.request
16
+ import webbrowser
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass, field
19
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
20
+ from importlib.metadata import PackageNotFoundError, version as pkg_version
21
+ from pathlib import Path
22
+ from urllib.parse import urlsplit
23
+
24
+ import multipart
25
+
26
+
27
+ class HTTPError(Exception):
28
+ def __init__(self, code, message):
29
+ super().__init__(message)
30
+ self.code = code
31
+
32
+
33
+ @dataclass
34
+ class Tool:
35
+ slug: str
36
+ port: int
37
+ usage: str
38
+ ui: Path
39
+ routes: dict = field(default_factory=dict) # "POST /api/<action>" -> fn(handler)
40
+ cli: dict = field(default_factory=dict) # tool-specific subcommand -> fn(args) -> exit code | None
41
+
42
+ def __post_init__(self):
43
+ try:
44
+ self.version = pkg_version(f"localtools-{self.slug}")
45
+ except PackageNotFoundError:
46
+ self.version = "dev"
47
+
48
+
49
+ @contextmanager
50
+ def form(req):
51
+ """Yields {field name: multipart.MultipartPart}; use part.file (seekable), part.filename, part.value."""
52
+ ctype, opts = multipart.parse_options_header(req.headers.get("Content-Type", ""))
53
+ if ctype != "multipart/form-data" or "boundary" not in opts:
54
+ raise HTTPError(400, "expected multipart/form-data")
55
+ try:
56
+ parts = {p.name: p for p in multipart.MultipartParser(req.rfile, opts["boundary"], int(req.headers.get("Content-Length") or 0))}
57
+ except multipart.MultipartError as e:
58
+ raise HTTPError(400, f"malformed upload: {e}")
59
+ try:
60
+ yield parts
61
+ finally:
62
+ for p in parts.values():
63
+ p.close()
64
+
65
+
66
+ def make_handler(t):
67
+ """UI + /api/health + tool routes behind the Host (DNS rebinding) and Origin (CSRF) guards."""
68
+ own = {f"127.0.0.1:{t.port}", f"localhost:{t.port}"}
69
+ ui = {p.relative_to(t.ui).as_posix(): p for p in t.ui.rglob("*") if p.is_file()}
70
+
71
+ class Handler(BaseHTTPRequestHandler):
72
+ def log_message(self, *args):
73
+ pass
74
+
75
+ def send_body(self, code, body, ctype):
76
+ self.send_response(code)
77
+ self.send_header("Content-Type", ctype)
78
+ self.send_header("Content-Length", str(len(body)))
79
+ self.end_headers()
80
+ self.wfile.write(body)
81
+
82
+ def send_json(self, code, obj):
83
+ self.send_body(code, json.dumps(obj).encode(), "application/json")
84
+
85
+ def dispatch(self):
86
+ if self.headers.get("Host") not in own:
87
+ return self.send_json(403, {"error": "forbidden host"})
88
+ origin = self.headers.get("Origin")
89
+ if origin and self.command != "GET" and origin.removeprefix("http://") not in own:
90
+ return self.send_json(403, {"error": "forbidden origin"})
91
+ path = urlsplit(self.path).path
92
+ try:
93
+ if self.command == "GET" and path == "/api/health":
94
+ return self.send_json(200, {"tool": t.slug, "version": t.version, "ok": True})
95
+ if route := t.routes.get(f"{self.command} {path}"):
96
+ return route(self)
97
+ if self.command == "GET" and (f := ui.get("index.html" if path == "/" else path[1:])):
98
+ return self.send_body(200, f.read_bytes(), mimetypes.guess_type(f.name)[0] or "application/octet-stream")
99
+ self.send_json(404, {"error": "not found"})
100
+ except HTTPError as e:
101
+ self.send_json(e.code, {"error": str(e)})
102
+ except Exception as e:
103
+ self.send_json(500, {"error": str(e)})
104
+
105
+ do_GET = do_POST = dispatch
106
+
107
+ return Handler
108
+
109
+
110
+ class Server(ThreadingHTTPServer):
111
+ allow_reuse_address = os.name != "nt" # on Windows SO_REUSEADDR would let two servers share a port
112
+
113
+
114
+ def open_browser(url):
115
+ if os.environ.get("LOCALTOOLS_NO_OPEN") != "1":
116
+ webbrowser.open(url)
117
+
118
+
119
+ def localtools_root():
120
+ return Path(os.environ.get("LOCALTOOLS_HOME") or Path.home() / ".localtools")
121
+
122
+
123
+ def managed_by(exe, root, slug, action):
124
+ """Empty string when exe lives under <root>/<slug>/ (installed by our scripts); else the package-manager
125
+ command(s) to print instead of running update/uninstall (CONTRACT "package-manager installs")."""
126
+ if Path(exe).resolve().is_relative_to((Path(root) / slug).resolve()):
127
+ return ""
128
+ pkg, up = f"localtools-{slug}", action == "update"
129
+ pascal = "".join(w[:1].upper() + w[1:] for w in slug.split("-"))
130
+ cmds = {
131
+ "brew": f"brew {'upgrade' if up else 'uninstall'} {pkg}",
132
+ "scoop": f"scoop {'update' if up else 'uninstall'} {pkg}",
133
+ "winget": f"winget {'upgrade' if up else 'uninstall'} localtools.{pascal}",
134
+ "npm": f"npm i -g {pkg}@latest" if up else f"npm uninstall -g {pkg}",
135
+ "pipx": f"pipx {'upgrade' if up else 'uninstall'} {pkg}",
136
+ }
137
+ p = str(exe).replace("\\", "/").lower()
138
+ for pm, mark in (("brew", "/cellar/"), ("brew", "homebrew"), ("brew", "linuxbrew"), ("scoop", "/scoop/"),
139
+ ("winget", "/winget/"), ("npm", "node_modules"), ("pipx", "pipx")):
140
+ if mark in p:
141
+ return f"{pkg} was installed with {pm}; to {action} it run:\n {cmds[pm]}\n"
142
+ return (f"{pkg} was not installed by the localtools script; to {action} it use the package manager you installed it with:\n"
143
+ + "".join(f" {c}\n" for c in cmds.values()))
144
+
145
+
146
+ def run_script(slug, name, action):
147
+ """Re-run the public install/uninstall script. Windows: detached (so files can be replaced), logged to
148
+ <root>/<slug>-install.log (uninstall: <temp>/<slug>-uninstall.log). The bundled interpreter lives under <root>/<slug>/, a pipx/pip one does not."""
149
+ if hint := managed_by(sys.executable, localtools_root(), slug, action):
150
+ print(hint, end="")
151
+ return 0
152
+ base = f"https://raw.githubusercontent.com/chayprabs/localtools/main/{slug}/{name}"
153
+ env = {**os.environ, "LOCALTOOLS_NO_OPEN": "1"}
154
+ if os.name == "nt":
155
+ # the uninstaller may delete the root, so its log goes to the temp dir
156
+ log = (localtools_root() if name == "install" else Path(tempfile.gettempdir())) / f"{slug}-{name}.log"
157
+ log.parent.mkdir(parents=True, exist_ok=True)
158
+ with open(log, "w") as f:
159
+ subprocess.Popen(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", f"irm {base}.ps1 | iex"],
160
+ env=env, stdout=f, stderr=f, stdin=subprocess.DEVNULL)
161
+ print(f"{action} running in the background; progress and errors are logged to {log}")
162
+ return 0
163
+ # exec, not a child: the installer pkills everything under <root>/<slug>/, which includes this bundled python
164
+ os.execvpe("sh", ["sh", "-c", f"curl -fsSL {base}.sh | bash"], env)
165
+
166
+
167
+ def serve(t):
168
+ url = f"http://127.0.0.1:{t.port}"
169
+ try:
170
+ srv = Server(("127.0.0.1", t.port), make_handler(t))
171
+ except OSError:
172
+ try:
173
+ with urllib.request.urlopen(url + "/api/health", timeout=2) as r:
174
+ running = json.load(r).get("tool") == t.slug
175
+ except Exception:
176
+ running = False
177
+ if running:
178
+ print(f"localtools-{t.slug} already running at {url}")
179
+ open_browser(url)
180
+ return 0
181
+ print(f"error: port {t.port} is in use by another program; pick another with --port N", file=sys.stderr)
182
+ return 1
183
+ print(f"localtools-{t.slug} {t.version} running at {url} (Ctrl+C to stop)", flush=True)
184
+ open_browser(url)
185
+ signal.signal(signal.SIGTERM, signal.default_int_handler)
186
+ try:
187
+ srv.serve_forever()
188
+ except KeyboardInterrupt:
189
+ pass
190
+ finally:
191
+ srv.server_close()
192
+ return 0
193
+
194
+
195
+ def main(t, argv=None):
196
+ args = list(sys.argv[1:] if argv is None else argv)
197
+ sub = args.pop(0) if args and not args[0].startswith("-") else "serve"
198
+ try:
199
+ if sub in ("update", "uninstall"):
200
+ return run_script(t.slug, "install" if sub == "update" else "uninstall", sub)
201
+ if sub in t.cli:
202
+ return t.cli[sub](args) or 0
203
+ if sub != "serve":
204
+ raise ValueError(f'unknown command "{sub}" (see --help)')
205
+ p = argparse.ArgumentParser(prog=f"localtools-{t.slug}", add_help=False)
206
+ p.add_argument("--port", type=int, default=int(os.environ.get("LOCALTOOLS_PORT") or t.port))
207
+ p.add_argument("--no-open", action="store_true")
208
+ p.add_argument("--version", action="store_true")
209
+ p.add_argument("-h", "--help", action="store_true")
210
+ o = p.parse_args(args)
211
+ if o.help:
212
+ print(t.usage, end="")
213
+ return 0
214
+ if o.version:
215
+ print(t.version)
216
+ return 0
217
+ if o.no_open:
218
+ os.environ["LOCALTOOLS_NO_OPEN"] = "1"
219
+ t.port = o.port
220
+ return serve(t)
221
+ except Exception as e:
222
+ print(f"error: {e}", file=sys.stderr)
223
+ return 1
@@ -0,0 +1,294 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>SQL Formatter</title>
7
+ <link rel="stylesheet" href="kit/localtools.css">
8
+ <style>
9
+ #sql { min-height: 240px; }
10
+ .lt-files button { border: 0; background: none; color: var(--muted); font: 700 13px var(--mono); cursor: pointer; padding: 0 var(--s1); }
11
+ .lt-files button:hover { color: var(--accent); }
12
+ .lt-files li span:first-child { margin-right: auto; }
13
+ .row { display: grid; grid-template-columns: 1fr 1fr; gap: var(--s4); margin-top: var(--s4); }
14
+ .cfg { min-height: 38px; padding: var(--s2) var(--s3); place-items: start; text-align: left; }
15
+ .file { border-top: 3px solid var(--rule); }
16
+ .file:first-child { border-top: 0; }
17
+ .file h3 { margin: 0; font: 700 14px/1.3 var(--mono); overflow-wrap: anywhere; }
18
+ .count { font: 700 12px/1 var(--mono); letter-spacing: .04em; text-transform: uppercase; }
19
+ .count[data-n="0"] { color: var(--ok); }
20
+ .count:not([data-n="0"]) { color: var(--accent); }
21
+ .lt-table td:first-child, .lt-table td:nth-child(2) { white-space: nowrap; }
22
+ .lt-table a { font-weight: 700; }
23
+ .diff .add { color: var(--ok); }
24
+ .diff .del { color: var(--accent); }
25
+ .diff .hunk { color: var(--info); }
26
+ .note { padding: var(--s2) var(--s4); font: 12px/1.4 var(--mono); color: var(--muted); border-bottom: 1px solid var(--hair); }
27
+ .lt-tabs { border-bottom: 1px solid var(--rule); }
28
+ @media (max-width: 560px) { .row { grid-template-columns: 1fr; } }
29
+ </style>
30
+ </head>
31
+ <body>
32
+ <main class="lt-page">
33
+ <header class="lt-header">
34
+ <a class="lt-issue" href="https://github.com/chayprabs/localtools/issues/new?template=sql-formatter.yml" target="_blank" rel="noopener">Report an issue</a>
35
+ <h1 class="lt-title">SQL Formatter</h1>
36
+ <p class="lt-desc">Lint and auto-fix SQL in 28 dialects with sqlfluff, or transpile between dialects with sqlglot. Runs on your machine.</p>
37
+ </header>
38
+
39
+ <section class="lt-section" aria-labelledby="in-l">
40
+ <h2 class="lt-label" id="in-l">SQL</h2>
41
+ <textarea class="lt-textarea" id="sql" spellcheck="false" aria-label="SQL" placeholder="select a,b from t where x=1"></textarea>
42
+ <div class="lt-or">or</div>
43
+ <label class="lt-drop" id="drop">
44
+ <input type="file" id="file" multiple accept=".sql,.txt,text/plain,application/sql">
45
+ <strong>Drop .sql files here</strong>
46
+ <span>Several at once is fine. Up to <span id="lim">512 KB</span> per run.</span>
47
+ </label>
48
+ <ul class="lt-files" id="files"></ul>
49
+ </section>
50
+
51
+ <section class="lt-section" aria-labelledby="opt-l">
52
+ <h2 class="lt-label" id="opt-l">Options</h2>
53
+ <fieldset class="lt-field">
54
+ <legend>Action</legend>
55
+ <div class="lt-seg" id="mode">
56
+ <label><input type="radio" name="mode" value="lint" checked><span>Lint</span></label>
57
+ <label><input type="radio" name="mode" value="fix"><span>Fix</span></label>
58
+ <label><input type="radio" name="mode" value="transpile"><span>Transpile</span></label>
59
+ </div>
60
+ </fieldset>
61
+ <div id="fluff">
62
+ <div class="lt-options" style="margin-top: var(--s4)">
63
+ <div class="lt-field">
64
+ <label for="dialect">Dialect</label>
65
+ <select class="lt-select" id="dialect"><option>ansi</option></select>
66
+ </div>
67
+ <div class="lt-field">
68
+ <label for="templater">Templater</label>
69
+ <select class="lt-select" id="templater">
70
+ <option value="">none (or config)</option>
71
+ <option value="jinja">jinja {{ }}</option>
72
+ <option value="placeholder:colon">:name</option>
73
+ <option value="placeholder:question_mark">?</option>
74
+ <option value="placeholder:numeric_dollar">$1</option>
75
+ <option value="placeholder:dollar">$name</option>
76
+ <option value="placeholder:pyformat">%(name)s</option>
77
+ <option value="placeholder:percent">%s</option>
78
+ <option value="placeholder:at">@name</option>
79
+ </select>
80
+ </div>
81
+ <div class="lt-field">
82
+ <label for="rules">Only rules</label>
83
+ <input class="lt-input" id="rules" list="rule-list" placeholder="all" spellcheck="false">
84
+ </div>
85
+ <div class="lt-field">
86
+ <label for="exclude">Exclude rules</label>
87
+ <input class="lt-input" id="exclude" list="rule-list" placeholder="LT05,AM04" spellcheck="false">
88
+ </div>
89
+ </div>
90
+ <datalist id="rule-list"><option value="core"></datalist>
91
+ <div class="lt-field" style="margin-top: var(--s4)">
92
+ <label for="cfg">Config file</label>
93
+ <label class="lt-drop cfg" id="cfg-drop">
94
+ <input type="file" id="cfg" accept=".sqlfluff,.cfg,.ini,.toml">
95
+ <span>.sqlfluff, setup.cfg, tox.ini or pyproject.toml. Nothing in it is executed; path and python/dbt templater settings are ignored.</span>
96
+ </label>
97
+ <ul class="lt-files" id="cfg-files"></ul>
98
+ </div>
99
+ </div>
100
+ <div class="lt-options" id="tr" style="margin-top: var(--s4)" hidden>
101
+ <div class="lt-field">
102
+ <label for="read">From</label>
103
+ <select class="lt-select" id="read"><option value="">generic</option></select>
104
+ </div>
105
+ <div class="lt-field">
106
+ <label for="write">To</label>
107
+ <select class="lt-select" id="write"><option value="">generic</option></select>
108
+ </div>
109
+ </div>
110
+ </section>
111
+
112
+ <section class="lt-section">
113
+ <div class="lt-actions">
114
+ <button class="lt-btn lt-btn-primary" type="button" id="go">Lint</button>
115
+ <span class="lt-status" id="status" aria-live="polite"></span>
116
+ </div>
117
+ <div class="lt-error" id="err" role="alert" hidden></div>
118
+ </section>
119
+
120
+ <section class="lt-section" aria-labelledby="out-l">
121
+ <h2 class="lt-label" id="out-l">Output</h2>
122
+ <div class="lt-output" id="out">
123
+ <div class="lt-empty">Paste SQL or drop files, pick a dialect, press Lint.</div>
124
+ </div>
125
+ </section>
126
+ </main>
127
+
128
+ <script type="module">
129
+ import { dropZone, run, copy, download, fmtBytes, fmtMs } from "./kit/localtools.js";
130
+
131
+ const $ = (id) => document.getElementById(id);
132
+ const el = (tag, props = {}, ...kids) => { const e = Object.assign(document.createElement(tag), props); e.append(...kids); return e; };
133
+ const MAX_ROWS = 2000;
134
+ const picked = [];
135
+ let cfgFile = null;
136
+
137
+ function fileList(ul, list, onRemove) {
138
+ ul.replaceChildren(...list.map((f, i) => {
139
+ const x = el("button", { type: "button", textContent: "x", title: "Remove " + f.name });
140
+ x.setAttribute("aria-label", "Remove " + f.name);
141
+ x.onclick = () => onRemove(i);
142
+ return el("li", {}, el("span", { textContent: f.name }), el("span", { textContent: fmtBytes(f.size) }), x);
143
+ }));
144
+ }
145
+ const renderPicked = () => fileList($("files"), picked, (i) => { picked.splice(i, 1); renderPicked(); });
146
+ const renderCfg = () => fileList($("cfg-files"), cfgFile ? [cfgFile] : [], () => { cfgFile = null; renderCfg(); });
147
+ dropZone($("drop"), null, (fs) => { picked.push(...fs); $("file").value = ""; renderPicked(); });
148
+ dropZone($("cfg-drop"), null, (fs) => { cfgFile = fs[0] || cfgFile; $("cfg").value = ""; renderCfg(); });
149
+
150
+ const mode = () => document.querySelector('input[name="mode"]:checked').value;
151
+ $("mode").onchange = () => {
152
+ const m = mode();
153
+ $("go").textContent = m[0].toUpperCase() + m.slice(1);
154
+ $("fluff").hidden = m === "transpile";
155
+ $("tr").hidden = m !== "transpile";
156
+ };
157
+
158
+ fetch("/api/meta").then((r) => r.json()).then((m) => {
159
+ $("dialect").replaceChildren(...m.sqlfluff.map((d) => el("option", { value: d, textContent: d, selected: d === "ansi" })));
160
+ for (const id of ["read", "write"]) $(id).append(...m.sqlglot.map((d) => el("option", { value: d, textContent: d })));
161
+ $("read").value = "tsql"; $("write").value = "postgres";
162
+ $("rule-list").append(...m.rules.map((r) => el("option", { value: r.code, textContent: `${r.name}: ${r.description}` })));
163
+ $("lim").textContent = fmtBytes(m.limits.bytes);
164
+ });
165
+
166
+ function sources() {
167
+ const sql = $("sql").value;
168
+ if (!sql.trim() && !picked.length) throw new Error("Paste SQL or drop at least one .sql file.");
169
+ return { files: picked, sql };
170
+ }
171
+
172
+ function link(v) {
173
+ if (!v.docs) return document.createTextNode(v.code);
174
+ return el("a", { href: v.docs, target: "_blank", rel: "noopener", textContent: v.code, title: v.name });
175
+ }
176
+
177
+ function table(vs) {
178
+ const t = el("table", { className: "lt-table" });
179
+ t.createTHead().append(el("tr", {}, ...["Line:Col", "Rule", "Problem", ""].map((h) => el("th", { textContent: h }))));
180
+ const body = t.createTBody();
181
+ for (const v of vs.slice(0, MAX_ROWS)) {
182
+ const sev = ["PRS", "TMP", "LXR"].includes(v.code) ? "error" : v.warning ? "warn" : v.fixable ? "info" : "warn";
183
+ const badge = el("span", { className: "lt-badge", textContent: sev === "error" ? "parse" : v.fixable ? "fixable" : v.warning ? "warning" : "manual" });
184
+ badge.dataset.sev = sev;
185
+ body.append(el("tr", {}, el("td", { textContent: `${v.line}:${v.col}` }), el("td", {}, link(v)),
186
+ el("td", { textContent: v.description }), el("td", {}, badge)));
187
+ }
188
+ const wrap = el("div", { className: "lt-table-wrap" }, t);
189
+ return vs.length > MAX_ROWS ? [el("div", { className: "note", textContent: `Showing ${MAX_ROWS} of ${vs.length}; download the report for all.` }), wrap] : [wrap];
190
+ }
191
+
192
+ function bar(name, count, ...buttons) {
193
+ const c = el("span", { className: "count", textContent: count[1] });
194
+ c.dataset.n = count[0];
195
+ return el("div", { className: "lt-bar" }, el("h3", { textContent: name }), c, ...buttons);
196
+ }
197
+ function btn(label, fn) { const b = el("button", { className: "lt-btn", type: "button", textContent: label }); b.onclick = (e) => fn(e.currentTarget); return b; }
198
+ const sqlName = (n) => n.replace(/\.[^.\/\\]+$/, "") + ".sql";
199
+
200
+ function diffView(diff) {
201
+ const pre = el("pre", { className: "lt-pre diff" });
202
+ pre.append(...diff.split(/(?<=\n)/).map((l) => el("span", {
203
+ className: l.startsWith("@@") ? "hunk" : l.startsWith("+") && !l.startsWith("+++") ? "add" : l.startsWith("-") && !l.startsWith("---") ? "del" : "",
204
+ textContent: l,
205
+ })));
206
+ return pre;
207
+ }
208
+
209
+ let n = 0;
210
+ function tabbed(panes) {
211
+ const id = "t" + ++n;
212
+ const list = el("div", { className: "lt-tabs", role: "tablist" });
213
+ const boxes = panes.map(([label, node], i) => {
214
+ const b = el("button", { type: "button", role: "tab", textContent: label, id: `${id}-${i}` });
215
+ b.setAttribute("aria-selected", i === 0);
216
+ const p = el("div", { role: "tabpanel", hidden: i !== 0 }, node);
217
+ b.onclick = () => boxes.forEach(([bb, pp], j) => { bb.setAttribute("aria-selected", j === i); pp.hidden = j !== i; });
218
+ list.append(b);
219
+ return [b, p];
220
+ });
221
+ return [list, ...boxes.map(([, p]) => p)];
222
+ }
223
+
224
+ const render = {
225
+ lint(res) {
226
+ return res.files.map((f) => {
227
+ const k = f.violations.length;
228
+ return el("article", { className: "file" }, bar(f.name, [k, k ? `${k} violation${k > 1 ? "s" : ""}` : "clean"]), ...(k ? table(f.violations) : []));
229
+ });
230
+ },
231
+ fix(res) {
232
+ return res.files.map((f) => {
233
+ const r = f.remaining.length;
234
+ const status = f.unparsable ? [1, "does not parse; not fixed"] : !f.changed ? [r, r ? `${r} need manual fixes` : "already clean"]
235
+ : [r, `${f.fixed_count} fixed` + (r ? `, ${r} need manual fixes` : "")];
236
+ const blob = new Blob([f.fixed], { type: "application/sql" });
237
+ const body = f.changed ? tabbed([["Diff", diffView(f.diff)], ["Fixed SQL", el("pre", { className: "lt-pre", textContent: f.fixed })]]) : [];
238
+ return el("article", { className: "file" },
239
+ bar(f.name, status, btn("Copy", (b) => copy(f.fixed, b)), btn("Download", () => download(blob, sqlName(f.name)))),
240
+ ...body, ...(r ? table(f.remaining) : []));
241
+ });
242
+ },
243
+ transpile(res) {
244
+ return res.files.map((f) => {
245
+ const blob = new Blob([f.sql], { type: "application/sql" });
246
+ return el("article", { className: "file" },
247
+ bar(f.name, [0, `${$("read").value || "generic"} > ${$("write").value || "generic"}`],
248
+ btn("Copy", (b) => copy(f.sql, b)), btn("Download", () => download(blob, sqlName(f.name)))),
249
+ ...f.warnings.map((w) => el("div", { className: "note", textContent: "Unsupported: " + w })),
250
+ el("pre", { className: "lt-pre", textContent: f.sql }));
251
+ });
252
+ },
253
+ };
254
+
255
+ async function go(m = mode()) {
256
+ const t0 = performance.now();
257
+ const { files, sql } = sources();
258
+ const fields = { sql };
259
+ if (m === "transpile") Object.assign(fields, { read: $("read").value, write: $("write").value });
260
+ else Object.assign(fields, { dialect: $("dialect").value, templater: $("templater").value, rules: $("rules").value, exclude_rules: $("exclude").value });
261
+ const body = new FormData();
262
+ for (const f of files) body.append("file", f, f.name);
263
+ if (cfgFile && m !== "transpile") body.append("config", cfgFile, cfgFile.name);
264
+ for (const [k, v] of Object.entries(fields)) body.append(k, v);
265
+ $("out").replaceChildren(el("div", { className: "lt-empty", textContent: m === "transpile" ? "Transpiling..." : "sqlfluff is working. Big files take a while." }));
266
+ $("status").textContent = "";
267
+ let res;
268
+ try {
269
+ const r = await fetch("/api/" + m, { method: "POST", body });
270
+ res = await r.json().catch(() => ({ error: `${r.status} ${r.statusText}` }));
271
+ if (!r.ok) throw new Error(res.error);
272
+ } catch (e) {
273
+ $("out").replaceChildren(el("div", { className: "lt-empty", textContent: "No output." }));
274
+ throw e.message === "Failed to fetch" ? new Error("Cannot reach the local server. Is the tool still running?") : e;
275
+ }
276
+ const head = [];
277
+ if (res.ignored_config?.length) head.push(el("div", { className: "note", textContent: "Ignored config settings: " + res.ignored_config.join(", ") }));
278
+ if (m === "lint") {
279
+ const total = res.files.reduce((s, f) => s + f.violations.length, 0);
280
+ const report = new Blob([JSON.stringify(res, null, 2)], { type: "application/json" });
281
+ const fixBtn = btn("Fix all", () => { document.querySelector('input[value="fix"]').click(); $("go").click(); });
282
+ head.push(el("div", { className: "lt-bar" }, el("span", { className: "lt-status", textContent: `dialect ${res.dialect}` }),
283
+ ...(res.files.some((f) => f.violations.some((v) => v.fixable)) ? [fixBtn] : []), btn("Download report", () => download(report, "sqlfluff-report.json"))));
284
+ $("status").textContent = `${total} violation${total === 1 ? "" : "s"} in ${res.files.length} file${res.files.length > 1 ? "s" : ""} · ${fmtMs(performance.now() - t0)}`;
285
+ } else {
286
+ $("status").textContent = `${res.files.length} file${res.files.length > 1 ? "s" : ""} · ${fmtMs(performance.now() - t0)}`;
287
+ }
288
+ $("out").replaceChildren(...head, ...render[m](res));
289
+ }
290
+
291
+ $("go").onclick = () => run($("go"), $("err"), () => go());
292
+ </script>
293
+ </body>
294
+ </html>
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.