bend-lint 0.2.2 → 0.3.1

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.
@@ -1,54 +1,59 @@
1
- # Edits to texts, and places in them: the edits to make, spans that must not touch, and the lines and columns of
2
- # offsets.
3
1
  import Base
4
- import bend-lint-api@0.2.2.0/shared/lists.bend as Lists
5
- import bend-lint-api@0.2.2.0/shared/names.bend as Names
6
- import bend-lint-api@0.2.2.0/shared/strings.bend as Strings
2
+ import bend-lint-api@0.3.1.0/shared.bend as Shared
3
+ import ./spec.bend as Spec
7
4
 
8
- # Edits
9
- # =====
5
+ # By place: a balanced (AVL) tree, by start, then end; `height` counts its levels. As spans never touch, their ends
6
+ # rise with their starts.
7
+ type Spans is Data:
8
+ SLeaf{}
9
+ SNode{height: U32, left: Spans, beg: U32, end: U32, right: Spans}
10
10
 
11
- # The text from `beg` to `end` in the file at `path`, replaced by `text`.
12
- type Edit is Data:
13
- Edit{path: String, beg: U32, end: U32, text: String}
11
+ type Place is Data:
12
+ Place{path: String, offset: U32}
14
13
 
15
- def Edit.path(edit: Edit) -> String:
14
+ def Spec.Spans():
15
+ Spans
16
+
17
+ def Spec.Spans.empty():
18
+ SLeaf{}
19
+
20
+ def Spec.Place():
21
+ Place
22
+
23
+ def Spec.Place.of(path, offset):
24
+ Place{path, offset}
25
+
26
+ # Edits
27
+ # =====
28
+ def Spec.Edit.path(edit):
16
29
  match edit:
17
- case Edit{path, beg, end, text}:
30
+ case Spec.Edit{path, beg, end, text}:
18
31
  path
19
32
 
20
- def Edit.is_le(a: Edit, b: Edit) -> Bool:
33
+ def Edit.is_le(a: Spec.Edit, b: Spec.Edit) -> Bool:
21
34
  match a b:
22
- case Edit{p, x, e, t} Edit{q, y, f, u}:
35
+ case Spec.Edit{p, x, e, t} Spec.Edit{q, y, f, u}:
23
36
  U32.is_le(x, y)
24
37
 
25
38
  # `rest`, the text from `at` on, with `edits` (in order) made, after the pieces of `out` (last first). The pieces join
26
39
  # once, at the end, so the text is copied once, whatever the number of edits.
27
- def apply.go(edits: List<&2, Edit>, +rest: String, +at: U32, out: List<&2, String>) -> String:
40
+ def apply.go(edits: List<&2, Spec.Edit>, +rest: String, +at: U32, out: List<&2, String>) -> String:
28
41
  match edits:
29
42
  case Nil{}:
30
- Strings.onto(rest <> out, "")
31
- case Con{Edit{p, beg, +end, text}, more}:
43
+ Shared.Strings.onto(rest <> out, "")
44
+ case Con{Spec.Edit{p, beg, +end, text}, more}:
32
45
  apply.go(
33
46
  more,
34
47
  String.drop(rest, U32.to_nat((end - at: U32))),
35
48
  end,
36
- text <> Strings.take(rest, U32.to_nat((beg - at: U32))) <> out
49
+ text <> Shared.Strings.take(rest, U32.to_nat((beg - at: U32))) <> out
37
50
  )
38
51
 
39
- # `text` with `edits` made. Edits must not overlap.
40
- def apply(edits: List<&2, Edit>, text: String) -> String:
41
- apply.go(Lists.sort(~Edit, ~Edit.is_le, edits), text, 0, [])
52
+ def Spec.apply(edits, text):
53
+ apply.go(Shared.Lists.sort(~Spec.Edit, ~Edit.is_le, edits), text, 0, [])
42
54
 
43
55
  # Spans
44
56
  # =====
45
-
46
- # Spans that never touch (`Spans.touches`), by place: a balanced (AVL) tree, by start, then end; `height` counts its
47
- # levels. As spans never touch, their ends rise with their starts.
48
- type Spans is Data:
49
- SLeaf{}
50
- SNode{height: U32, left: Spans, beg: U32, end: U32, right: Spans}
51
-
52
57
  def Spans.height(t: Spans) -> U32:
53
58
  match t:
54
59
  case SLeaf{}:
@@ -135,23 +140,21 @@ def Spans.cmp.of(starts: Cmp, e: U32, y: U32) -> Cmp:
135
140
  case GT{}:
136
141
  GT{}
137
142
 
138
- # How the span from `b` to `e` compares with the root's of `t`, by start, then end; GT past a leaf.
139
- def Spans.cmp(t: Spans, b: U32, e: U32) -> Cmp:
143
+ def Spec.Spans.cmp(t, b, e):
140
144
  match t:
141
145
  case SNode{h, l, x, y, r}:
142
146
  Spans.cmp.of(U32.cmp(b, x), e, y)
143
147
  case SLeaf{}:
144
148
  GT{}
145
149
 
146
- # `t` with the span from `b` to `e`; `side` is how it compares with the root's.
147
- def Spans.add(t: Spans, +b: U32, +e: U32, side: Cmp) -> Spans:
150
+ def Spec.Spans.add(t, b, e, side):
148
151
  match t side:
149
152
  case SLeaf{} _:
150
153
  SNode{1, SLeaf{}, b, e, SLeaf{}}
151
154
  case SNode{h, +l, x, y, r} LT{}:
152
- Spans.balance(Spans.add(l, b, e, Spans.cmp(l, b, e)), x, y, r)
155
+ Spans.balance(Spec.Spans.add(l, b, e, Spec.Spans.cmp(l, b, e)), x, y, r)
153
156
  case SNode{h, l, x, y, +r} _:
154
- Spans.balance(l, x, y, Spans.add(r, b, e, Spans.cmp(r, b, e)))
157
+ Spans.balance(l, x, y, Spec.Spans.add(r, b, e, Spec.Spans.cmp(r, b, e)))
155
158
 
156
159
  # Whether `t` holds the span from `b` to `e`; `side` is how it compares with the root's.
157
160
  def Spans.has(t: Spans, +b: U32, +e: U32, side: Cmp) -> Bool:
@@ -161,9 +164,9 @@ def Spans.has(t: Spans, +b: U32, +e: U32, side: Cmp) -> Bool:
161
164
  case SNode{h, l, x, y, r} EQ{}:
162
165
  True{}
163
166
  case SNode{h, +l, x, y, r} LT{}:
164
- Spans.has(l, b, e, Spans.cmp(l, b, e))
167
+ Spans.has(l, b, e, Spec.Spans.cmp(l, b, e))
165
168
  case SNode{h, l, x, y, +r} GT{}:
166
- Spans.has(r, b, e, Spans.cmp(r, b, e))
169
+ Spans.has(r, b, e, Spec.Spans.cmp(r, b, e))
167
170
 
168
171
  def Spans.starts_before(t: Spans, e: U32) -> Bool:
169
172
  match t:
@@ -190,11 +193,10 @@ def Spans.ends_after(last: Maybe<&2, U32>, b: U32) -> Bool:
190
193
  case None{}:
191
194
  False{}
192
195
 
193
- # Whether the span from `b` to `e` touches one of `t`: they share a character, or two insertions are at one place.
194
196
  def Spans.touches.insertion(insertion: Bool, +t: Spans, +b: U32, +e: U32) -> Bool:
195
197
  match insertion:
196
198
  case True{}:
197
- Spans.has(t, b, e, Spans.cmp(t, b, e))
199
+ Spans.has(t, b, e, Spec.Spans.cmp(t, b, e))
198
200
  case False{}:
199
201
  False{}
200
202
 
@@ -205,7 +207,7 @@ def Spans.touches.of(shares: Bool, t: Spans, +b: U32, +e: U32) -> Bool:
205
207
  case False{}:
206
208
  Spans.touches.insertion(U32.is_eq(b, e), t, b, e)
207
209
 
208
- def Spans.touches(+t: Spans, +b: U32, +e: U32) -> Bool:
210
+ def Spec.Spans.touches(t, b, e):
209
211
  Spans.touches.of(
210
212
  Spans.ends_after(Spans.last(t, e, None{}, Spans.starts_before(t, e)), b),
211
213
  t,
@@ -216,20 +218,12 @@ def Spans.touches(+t: Spans, +b: U32, +e: U32) -> Bool:
216
218
  # Places
217
219
  # ======
218
220
 
219
- # A place in a text: its line and its column, from 1. A column counts UTF-16 units, as editors do.
220
- type Position is Data:
221
- Position{line: U32, column: U32}
222
-
223
- # An offset in the file at `path`.
224
- type Place is Data:
225
- Place{path: String, offset: U32}
226
-
227
221
  # An offset to place, by its place among the offsets asked; and a place found, by the same.
228
222
  type Placed is Data:
229
223
  Placed{index: U32, offset: U32}
230
224
 
231
225
  type Located is Data:
232
- Located{index: U32, at: Position}
226
+ Located{index: U32, at: Spec.Position}
233
227
 
234
228
  # The offsets left to place, in offset order, and the places found, last first.
235
229
  type Walk is Data:
@@ -276,7 +270,7 @@ def Walk.emit(
276
270
  at,
277
271
  line,
278
272
  column,
279
- Located{i, Position{line, column}} <> out
273
+ Located{i, Spec.Position{line, column}} <> out
280
274
  )
281
275
  case _ _:
282
276
  Walk{pending, out}
@@ -286,6 +280,15 @@ def Walk.done(w: Walk) -> List<&2, Located>:
286
280
  case Walk{pending, out}:
287
281
  out
288
282
 
283
+ # The columns a character takes, `units` of UTF-16, before the text `rest`: none if it is a CR (`cr`) before an LF, as
284
+ # the two end the line, and an editor places nothing between them.
285
+ def Walk.width(units: U32, cr: Bool, rest: String) -> U32:
286
+ match rest:
287
+ case SCon{next, r}:
288
+ Bool.pick(U32, cr && Char.is_eq(next, '\n'), 0, units)
289
+ case SNil{}:
290
+ units
291
+
289
292
  # The offsets placed, one character of `text` at a time; offsets past its end are placed at its end.
290
293
  def Walk.go(text: String, +at: U32, +line: U32, column: U32, w: Walk) -> List<&2, Located>:
291
294
  match text w:
@@ -293,14 +296,21 @@ def Walk.go(text: String, +at: U32, +line: U32, column: U32, w: Walk) -> List<&2
293
296
  out
294
297
  case SNil{} Walk{pending, out}:
295
298
  Walk.done(Walk.emit(pending, True{}, 4294967295, line, column, out))
296
- case SCon{+c, t} Walk{+pending, out}:
299
+ case SCon{+c, +t} Walk{+pending, out}:
297
300
  +ends = Char.is_eq(c, '\n')
298
301
  +l = Bool.pick(U32, ends, (line + 1: U32), line)
299
302
  +col = Bool.pick(
300
303
  U32,
301
304
  ends,
302
305
  1,
303
- (column + Bool.pick(U32, U32.is_ge(Char.to_u32(c), 65536), 2, 1): U32)
306
+ (
307
+ column
308
+ + Walk.width(
309
+ Bool.pick(U32, U32.is_ge(Char.to_u32(c), 65536), 2, 1),
310
+ Char.is_eq(c, '\r'),
311
+ t
312
+ ): U32
313
+ )
304
314
  )
305
315
  Walk.go(
306
316
  t,
@@ -310,10 +320,13 @@ def Walk.go(text: String, +at: U32, +line: U32, column: U32, w: Walk) -> List<&2
310
320
  Walk.emit(pending, Walk.is_due(pending, (at + 1: U32)), (at + 1: U32), l, col, out)
311
321
  )
312
322
 
313
- def Walk.positions(located: List<&2, Located>, out: List<&2, Position>) -> List<&2, Position>:
323
+ def Walk.positions(
324
+ located: List<&2, Located>,
325
+ out: List<&2, Spec.Position>
326
+ ) -> List<&2, Spec.Position>:
314
327
  match located:
315
328
  case Nil{}:
316
- List.reverse(&2, Position, out)
329
+ List.reverse(&2, Spec.Position, out)
317
330
  case Con{Located{i, at}, rest}:
318
331
  Walk.positions(rest, at <> out)
319
332
 
@@ -321,13 +334,12 @@ def Walk.positions(located: List<&2, Located>, out: List<&2, Position>) -> List<
321
334
  def Walk.locate(+sorted: List<&2, Placed>, text: String) -> List<&2, Located>:
322
335
  Walk.go(text, 0, 1, 1, Walk.emit(sorted, Walk.is_due(sorted, 0), 0, 1, 1, []))
323
336
 
324
- # Where each offset of `offsets` is in `text`, in order: one pass over the text, whatever the number of offsets.
325
- def positions(text: String, offsets: List<&2, U32>) -> List<&2, Position>:
337
+ def Spec.positions(text, offsets):
326
338
  Walk.positions(
327
- Lists.sort(
339
+ Shared.Lists.sort(
328
340
  ~Located,
329
341
  ~Located.is_le,
330
- Walk.locate(Lists.sort(~Placed, ~Placed.is_le, Placed.of(offsets, 0, [])), text)
342
+ Walk.locate(Shared.Lists.sort(~Placed, ~Placed.is_le, Placed.of(offsets, 0, [])), text)
331
343
  ),
332
344
  []
333
345
  )
@@ -335,12 +347,11 @@ def positions(text: String, offsets: List<&2, U32>) -> List<&2, Position>:
335
347
  def Place.key(path: String, offset: U32) -> String:
336
348
  path ++ "\t" ++ U32.show(offset)
337
349
 
338
- # Where the offset `offset` of the file at `path` is, among `places` (what `places` gives); 1:1 if it is not there.
339
- def Place.at(places: Map<&2, Position>, path: String, offset: U32) -> Position:
350
+ def Spec.Place.at(places, path, offset):
340
351
  Pair.snd(
341
- Map<&2, Position>,
342
- Position,
343
- Map.get(Position, Position{1, 1}, places, Place.key(path, offset))
352
+ Map<&2, Spec.Position>,
353
+ Spec.Position,
354
+ Map.get(Spec.Position, Spec.Position{1, 1}, places, Place.key(path, offset))
344
355
  )
345
356
 
346
357
  # The requests by file, each offset numbered by itself, onto `groups`.
@@ -352,27 +363,27 @@ def places.group(
352
363
  case Nil{}:
353
364
  groups
354
365
  case Con{Place{path, +offset}, rest}:
355
- places.group(rest, Names.Group.add(Placed, groups, path, Placed{offset, offset}))
366
+ places.group(rest, Shared.Names.Group.add(Placed, groups, path, Placed{offset, offset}))
356
367
 
357
368
  # The places found in the file at `path`, by key, onto `out`.
358
369
  def places.keep(
359
370
  located: List<&2, Located>,
360
371
  +path: String,
361
- out: Map<&2, Position>
362
- ) -> Map<&2, Position>:
372
+ out: Map<&2, Spec.Position>
373
+ ) -> Map<&2, Spec.Position>:
363
374
  match located:
364
375
  case Nil{}:
365
376
  out
366
377
  case Con{Located{offset, at}, rest}:
367
- places.keep(rest, path, Map.set(&2, Position, out, Place.key(path, offset), at))
378
+ places.keep(rest, path, Map.set(&2, Spec.Position, out, Place.key(path, offset), at))
368
379
 
369
380
  # The requests of each file of `paths` placed in its text, onto `out`; a file `texts` lacks places them at its start.
370
381
  def places.walk(
371
382
  paths: List<&2, String>,
372
383
  +groups: Map<&2, List<&2, Placed>>,
373
384
  +texts: Map<&2, String>,
374
- out: Map<&2, Position>
375
- ) -> Map<&2, Position>:
385
+ out: Map<&2, Spec.Position>
386
+ ) -> Map<&2, Spec.Position>:
376
387
  match paths:
377
388
  case Nil{}:
378
389
  out
@@ -383,7 +394,7 @@ def places.walk(
383
394
  texts,
384
395
  places.keep(
385
396
  Walk.locate(
386
- Lists.sort(~Placed, ~Placed.is_le, Names.Group.get(Placed, groups, path)),
397
+ Shared.Lists.sort(~Placed, ~Placed.is_le, Shared.Names.Group.get(Placed, groups, path)),
387
398
  Pair.snd(Map<&2, String>, String, Map.get(String, "", texts, path))
388
399
  ),
389
400
  path,
@@ -391,8 +402,6 @@ def places.walk(
391
402
  )
392
403
  )
393
404
 
394
- # Where each requested offset is, by key (read with `Place.at`): one pass over each file asked about, whatever the
395
- # number of requests. `texts` holds the files' texts, by path.
396
- def places(texts: Map<&2, String>, requests: List<&2, Place>) -> Map<&2, Position>:
405
+ def Spec.places(texts, requests):
397
406
  +groups = places.group(requests, Map.new(&2, List<&2, Placed>))
398
- places.walk(Map.keys(&2, List<&2, Placed>, groups), groups, texts, Map.new(&2, Position))
407
+ places.walk(Map.keys(&2, List<&2, Placed>, groups), groups, texts, Map.new(&2, Spec.Position))
@@ -0,0 +1,82 @@
1
+ # Edits to texts, and places in them: the edits to make, spans that must not touch, and the lines and columns of
2
+ # offsets.
3
+ import Base
4
+
5
+ # The text from `beg` to `end` in the file at `path`, replaced by `text`.
6
+ type Edit is Data:
7
+ Edit{path: String, beg: U32, end: U32, text: String}
8
+
9
+ # Spans that never touch (`Spans.touches`).
10
+ law Spans:
11
+ Data
12
+
13
+ # No spans.
14
+ law Spans.empty:
15
+ Spans
16
+
17
+ # A place in a text: its line and its column, from 1. A column counts UTF-16 units, as editors do.
18
+ type Position is Data:
19
+ Position{line: U32, column: U32}
20
+
21
+ # An offset in a file.
22
+ law Place:
23
+ Data
24
+
25
+ # The offset `offset` in the file at `path`.
26
+ law Place.of:
27
+ for path: String
28
+ for offset: U32
29
+ Place
30
+
31
+ # The path of the file that `edit` changes.
32
+ law Edit.path:
33
+ for edit: Edit
34
+ String
35
+
36
+ # `text` with `edits` made. Edits must not overlap.
37
+ law apply:
38
+ for edits: List<&2, Edit>
39
+ for text: String
40
+ String
41
+
42
+ # How the span from `b` to `e` compares with the root's of `t`, by start, then end; GT past a leaf.
43
+ law Spans.cmp:
44
+ for t: Spans
45
+ for b: U32
46
+ for e: U32
47
+ Cmp
48
+
49
+ # `t` with the span from `b` to `e`; `side` is how it compares with the root's.
50
+ law Spans.add:
51
+ for t: Spans
52
+ for +b: U32
53
+ for +e: U32
54
+ for side: Cmp
55
+ Spans
56
+
57
+ # Whether the span from `b` to `e` touches one of `t`: they share a character, or two insertions are at one place.
58
+ law Spans.touches:
59
+ for +t: Spans
60
+ for +b: U32
61
+ for +e: U32
62
+ Bool
63
+
64
+ # Where each offset of `offsets` is in `text`, in order: one pass over the text, whatever the number of offsets.
65
+ law positions:
66
+ for text: String
67
+ for offsets: List<&2, U32>
68
+ List<&2, Position>
69
+
70
+ # Where the offset `offset` of the file at `path` is, among `places` (what `places` gives); 1:1 if it is not there.
71
+ law Place.at:
72
+ for places: Map<&2, Position>
73
+ for path: String
74
+ for offset: U32
75
+ Position
76
+
77
+ # Where each requested offset is, by key (read with `Place.at`): one pass over each file asked about, whatever the
78
+ # number of requests. `texts` holds the files' texts, by path.
79
+ law places:
80
+ for texts: Map<&2, String>
81
+ for requests: List<&2, Place>
82
+ Map<&2, Position>
@@ -1,171 +0,0 @@
1
- // The Bend bend-lint checks and builds with, bend2: a pinned commit on GitHub,
2
- // downloaded once, whatever bend is installed. Bend's releases do not run on
3
- // Windows, so there it is a commit of a fork that does, and bend-lint says so
4
- // on each run.
5
-
6
- // Imports
7
- // =======
8
-
9
- import { execFile, spawnSync } from "node:child_process";
10
- import * as nodeFs from "node:fs";
11
- import * as os from "node:os";
12
- import * as nodePath from "node:path";
13
- import * as url from "node:url";
14
-
15
- import pkg from "../../package.json" with { type: "json" };
16
- import { error } from "./result.ts";
17
- import type { Result } from "./result.ts";
18
- import {
19
- getErrorMessageFromUnknown,
20
- tryGet,
21
- tryGetUrlFromFolderPathOrUrl,
22
- writeNewFileAtomically,
23
- } from "./utils.ts";
24
-
25
- // Constants
26
- // =========
27
-
28
- // The Bend bend-lint uses, as `<owner>/<repo>/<ref>` on GitHub: Bend's newest
29
- // release this repo's checks passed with (src/meta/sync-bend.ts moves it), or,
30
- // on Windows, a commit of a fork that runs there.
31
- export const PINNED_BEND: string = process.platform === "win32" ? pkg.bendWindows : pkg.bendRelease;
32
-
33
- // What bend-lint says on each run on Windows, where it uses the fork.
34
- export const PINNED_BEND_NOTE: string | undefined =
35
- process.platform === "win32"
36
- ? "bend-lint: on Windows, bend-lint uses a fork of Bend, as Bend's releases do not run there: https://github.com/" +
37
- pkg.bendWindows.replace(/^([^/]+\/[^/]+)\//, "$1/tree/")
38
- : undefined;
39
-
40
- // bend-lint's cache: the downloaded Bend, and what the server keeps.
41
- export const getBendLintCacheDir = (): URL =>
42
- url.pathToFileURL(
43
- nodePath.join(
44
- process.env.XDG_CACHE_HOME ??
45
- (process.platform === "win32"
46
- ? (process.env.LOCALAPPDATA ?? nodePath.join(os.homedir(), "AppData", "Local"))
47
- : nodePath.join(os.homedir(), ".cache")),
48
- "bend-lint",
49
- ) + nodePath.sep,
50
- );
51
-
52
- // What bend-lint says on each run whose rules it built as JavaScript, as it
53
- // found no clang (see getClang).
54
- export const JAVASCRIPT_NOTE =
55
- "bend-lint: found no clang 14 or newer, so the rules run as JavaScript, about 3 to 8 times slower; install clang to speed them up";
56
-
57
- // How the line starts that says the installed bend is another version.
58
- const VERSION_NOTE = "bend-lint: your bend is ";
59
-
60
- // Functions
61
- // =========
62
-
63
- // Whether a line is one bend-lint prints about how this machine runs it: on
64
- // Windows, that it uses the fork; that the installed bend is another version;
65
- // or that the rules run as JavaScript.
66
- export const isMachineNote = (line: string): boolean =>
67
- line === PINNED_BEND_NOTE || line === JAVASCRIPT_NOTE || line.startsWith(VERSION_NOTE);
68
-
69
- // The clang Bend builds native programs with, if there is one, as Bend's
70
- // cc_find picks it (main.ts): the first of $CC, clang, each clang-NN on PATH
71
- // (the newest first), and on Windows where LLVM's installer puts it, that is
72
- // clang 14 or newer.
73
- export const getClang = (): string | undefined => {
74
- const getFileNames = (dir: string): string[] => tryGet(() => nodeFs.readdirSync(dir)) ?? [];
75
- const numbered = [
76
- ...new Set(
77
- (process.env.PATH ?? "")
78
- .split(nodePath.delimiter)
79
- .flatMap(getFileNames)
80
- .filter((f) => /^clang-\d+$/.test(f)),
81
- ),
82
- ].sort((a, b) => Number(b.slice(6)) - Number(a.slice(6)));
83
- return [
84
- ...(process.env.CC === undefined ? [] : [process.env.CC]),
85
- "clang",
86
- ...numbered,
87
- ...(process.platform === "win32"
88
- ? [nodePath.join(process.env.ProgramFiles ?? "C:\\Program Files", "LLVM", "bin", "clang.exe")]
89
- : []),
90
- ].find((cc) => {
91
- const version = /^(?:Apple )?(?:\w+ )?clang version (\d+)/m.exec(
92
- spawnSync(cc, ["--version"], { encoding: "utf8" }).stdout ?? "",
93
- )?.[1];
94
- return version !== undefined && Number(version) >= 14;
95
- });
96
- };
97
-
98
- // The line bend-lint prints when the `bend` on PATH is another version than
99
- // the Bend in the bend2 folder `dir`, which bend-lint checks and builds with;
100
- // undefined if it is the same, or if none is installed or `bend version` names
101
- // no version. It asks `bend version` on each run, as the `bend` on PATH can be
102
- // a script that runs a checkout, whose version changes while the script does
103
- // not. It runs by name: Windows runs a bend.cmd only that way.
104
- export const getBendVersionNote = async (dir: URL): Promise<string | undefined> => {
105
- const version = await new Promise<string | undefined>((resolve) => {
106
- const resolveVersion = (e: Error | null, stdout: string): void =>
107
- resolve(/^bend (\d+\.\d+\.\d+)(?:\r?\n|$)/.exec(e === null ? stdout : "")?.[1]);
108
- try {
109
- execFile("bend", ["version"], { encoding: "utf8", timeout: 10_000 }, resolveVersion);
110
- } catch (e) {
111
- resolveVersion(e as Error, "");
112
- }
113
- });
114
- const pinned = /^const VERSION = "([^"]+)";$/m.exec(
115
- nodeFs.readFileSync(new URL("main.ts", dir), "utf8"),
116
- )?.[1];
117
- return version === undefined || pinned === undefined || version === pinned
118
- ? undefined
119
- : `${VERSION_NOTE}${version}, and bend-lint checks with Bend ${pinned}; the two can disagree on a few files`;
120
- };
121
-
122
- // How to run the Bend in the bend2 folder `dir`: its CLI (main.ts) on this Bun,
123
- // in an environment that keeps it from asking bend-lang.com, once a day, for a
124
- // newer release (see main.ts).
125
- export const getBendCli = (dir: URL): { cmd: string[]; env: Record<string, string> } => ({
126
- cmd: [process.execPath, url.fileURLToPath(new URL("main.ts", dir))],
127
- env: { BEND_NO_TELEMETRY: "1" },
128
- });
129
-
130
- // bend2 at `pin` (`<owner>/<repo>/<ref>` on GitHub), kept in <cache>/<pin>/bend2.
131
- // Each file goes in whole, base.bend last, and none is ever replaced (see
132
- // writeNewFileAtomically): runs at once may each download, while others read
133
- // the files.
134
- const getDownloadedBend = async (pin: string): Promise<URL> => {
135
- if (!/^[\w.-]+\/[\w.-]+\/[\w.-]+$/.test(pin)) {
136
- throw new Error("not a GitHub <owner>/<repo>/<ref>: " + pin);
137
- }
138
- const dir = new URL(pin + "/bend2/", getBendLintCacheDir());
139
- // What a download holds besides base.bend and the effs/ files Base imports.
140
- const FILES = ["bend.ts", "comp.ts", "main.ts", "safe.ts"];
141
- const isMissing = (file: string): boolean => !nodeFs.existsSync(new URL(file, dir));
142
- if (![...FILES, "base.bend"].some(isMissing)) {
143
- return dir;
144
- }
145
- const getFetchedFile = async (file: string): Promise<[string, string]> => {
146
- const res = await fetch(`https://raw.githubusercontent.com/${pin}/bend2/${file}`, {
147
- signal: AbortSignal.timeout(30_000),
148
- });
149
- if (!res.ok) {
150
- throw new Error(`GitHub answered ${res.status} for bend2/${file}`);
151
- }
152
- return [file, await res.text()];
153
- };
154
- const base = await getFetchedFile("base.bend");
155
- const effs = new Set([...base[1].matchAll(/^\s*import "\.\/(effs\/[^"]+)"/gm)].map((m) => m[1]));
156
- const odd = [...effs].find((f) => !/^effs\/[\w.-]+$/.test(f));
157
- if (odd !== undefined) {
158
- throw new Error("base.bend imports " + odd + ", which is not a plain file in effs/");
159
- }
160
- [...(await Promise.all([...effs, ...FILES].map(getFetchedFile))), base].forEach(([file, body]) =>
161
- writeNewFileAtomically(url.fileURLToPath(new URL(file, dir)), body),
162
- );
163
- console.error("bend-lint: downloaded bend " + pin + " to " + url.fileURLToPath(dir));
164
- return dir;
165
- };
166
-
167
- // The bend2 folder to load: the pinned Bend's, downloaded if it is not yet.
168
- export const tryGetBend2SourceUrl = async (): Promise<Result<URL, string>> =>
169
- getDownloadedBend(PINNED_BEND).then(tryGetUrlFromFolderPathOrUrl, (e: unknown) =>
170
- error(`could not download bend ${PINNED_BEND} (${getErrorMessageFromUnknown(e)})`),
171
- );
@@ -1,57 +0,0 @@
1
- // A value under OK, or an error under ERROR, for callers that would rather
2
- // branch than catch. From iara's src/utils/result.ts, trimmed to what
3
- // bend-lint uses.
4
-
5
- // Types
6
- // =====
7
-
8
- export type ErrorShape<
9
- T extends string = string,
10
- U extends Record<string, unknown> = Record<string, unknown>,
11
- > = string | Error | { type: T; [ERROR_METADATA]?: U };
12
-
13
- export type ResultOk<T> = Readonly<{ readonly [OK]: T }>;
14
-
15
- export type ResultErr<E extends ErrorShape = ErrorShape> = Readonly<{ readonly [ERROR]: E }>;
16
-
17
- export type Result<T, E extends ErrorShape = ErrorShape> = ResultOk<T> | ResultErr<E>;
18
-
19
- // Constants
20
- // =========
21
-
22
- export const OK = "OK" as const;
23
-
24
- export const ERROR = "ERROR" as const;
25
-
26
- export const ERROR_METADATA = "ERROR_METADATA" as const;
27
-
28
- // Functions
29
- // =========
30
-
31
- export const ok = <T>(value: T): ResultOk<T> => ({ [OK]: value });
32
-
33
- export const error = <E extends ErrorShape>(value: E): ResultErr<E> => ({ [ERROR]: value });
34
-
35
- // The same result, with its error passed through `f`.
36
- export const mapError = <T, E extends ErrorShape, F extends ErrorShape>(
37
- res: Result<T, E>,
38
- f: (e: E) => F,
39
- ): Result<T, F> => (OK in res ? res : error(f(res[ERROR])));
40
-
41
- // The value, or a throw: an Error as it is, a string as an Error's message,
42
- // and a typed error as an Error with its metadata's message (else its
43
- // type), caused by the typed error.
44
- export const unwrap = <T, E extends ErrorShape>(res: Result<T, E>): T => {
45
- if (OK in res) {
46
- return res[OK];
47
- }
48
- const e = res[ERROR];
49
- if (e instanceof Error) {
50
- throw e;
51
- }
52
- if (typeof e === "string") {
53
- throw new Error(e);
54
- }
55
- const said = e[ERROR_METADATA]?.message;
56
- throw new Error(typeof said === "string" ? said : e.type, { cause: e });
57
- };