ruby-anything 0.1.0 → 0.2.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +9 -2
- package/README.md +36 -4
- package/action.yml +56 -0
- package/adapters/node/harness.mjs +28 -2
- package/adapters/node/package-lock.json +26 -26
- package/adapters/node/package.json +7 -7
- package/adapters/polyglot/harness.py +350 -350
- package/adapters/polyglot/lang_csharp.py +222 -222
- package/adapters/polyglot/lang_java.py +510 -510
- package/adapters/polyglot/lang_rust.py +430 -430
- package/adapters/polyglot/lang_swift.py +337 -337
- package/adapters/python/harness.py +42 -0
- package/adapters/ruby/harness.rb +134 -0
- package/harness/ruby_replay.rb +11 -0
- package/package.json +8 -7
- package/skills/ruby-anything/SKILL.md +17 -1
- package/skills/ruby-anything/whole-app.md +37 -1
- package/src/adapters.js +60 -60
- package/src/app.js +102 -25
- package/src/cli.js +7 -2
- package/src/cli_app.js +251 -0
- package/src/drift.js +124 -0
- package/src/effects.js +145 -0
- package/src/fromtests.js +105 -0
- package/src/go.js +30 -4
- package/src/units.js +11 -3
|
@@ -361,7 +361,45 @@ def observable(result):
|
|
|
361
361
|
return json.dumps({k: result[k] for k in ("outcome", "stdout", "stderr", "effects")}, sort_keys=True)
|
|
362
362
|
|
|
363
363
|
|
|
364
|
+
PIN_EPOCH = 1767225600 # 2026-01-01T00:00:00Z
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def pin_clock():
|
|
368
|
+
"""Freeze the clock at PIN_EPOCH for code imported after this (time, datetime). Opt-in: pin_clock."""
|
|
369
|
+
import datetime as _dt
|
|
370
|
+
import time as _time
|
|
371
|
+
|
|
372
|
+
_time.time = lambda: float(PIN_EPOCH)
|
|
373
|
+
_time.time_ns = lambda: PIN_EPOCH * 1_000_000_000
|
|
374
|
+
real = _dt.datetime
|
|
375
|
+
|
|
376
|
+
class PinnedDatetime(real):
|
|
377
|
+
@classmethod
|
|
378
|
+
def now(cls, tz=None):
|
|
379
|
+
utc = real.fromtimestamp(PIN_EPOCH, _dt.timezone.utc)
|
|
380
|
+
return utc.astimezone(tz) if tz else utc.replace(tzinfo=None)
|
|
381
|
+
|
|
382
|
+
@classmethod
|
|
383
|
+
def utcnow(cls):
|
|
384
|
+
return real.fromtimestamp(PIN_EPOCH, _dt.timezone.utc).replace(tzinfo=None)
|
|
385
|
+
|
|
386
|
+
@classmethod
|
|
387
|
+
def today(cls):
|
|
388
|
+
return cls.now()
|
|
389
|
+
|
|
390
|
+
class PinnedDate(_dt.date):
|
|
391
|
+
@classmethod
|
|
392
|
+
def today(cls):
|
|
393
|
+
return _dt.date(2026, 1, 1)
|
|
394
|
+
|
|
395
|
+
_dt.datetime = PinnedDatetime
|
|
396
|
+
_dt.date = PinnedDate
|
|
397
|
+
|
|
398
|
+
|
|
364
399
|
def record(req):
|
|
400
|
+
pinned = bool(req.get("pin_clock"))
|
|
401
|
+
if pinned:
|
|
402
|
+
pin_clock()
|
|
365
403
|
fn = load_function(req["module_file"], req["function"])
|
|
366
404
|
cases = list(req.get("cases", []))
|
|
367
405
|
gen = req.get("generate") or {}
|
|
@@ -370,7 +408,11 @@ def record(req):
|
|
|
370
408
|
emit("log", message=f"recording {len(cases)} cases for {req['function']} (python {sys.version.split()[0]})")
|
|
371
409
|
emit("plan", total=len(cases), runtime=f"python {sys.version.split()[0]}")
|
|
372
410
|
for index, case in enumerate(cases):
|
|
411
|
+
if pinned:
|
|
412
|
+
random.seed(0)
|
|
373
413
|
first = run_case(fn, case)
|
|
414
|
+
if pinned:
|
|
415
|
+
random.seed(0)
|
|
374
416
|
second = run_case(fn, case)
|
|
375
417
|
stable = observable(first) == observable(second)
|
|
376
418
|
emit("case", index=index, ref=case.get("ref"), origin=case.get("origin", "manual"), args=case.get("args", []),
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# PortPilot Ruby adapter.
|
|
2
|
+
#
|
|
3
|
+
# Runs in a separate process (never inside Rails). Reads one JSON request on stdin and
|
|
4
|
+
# writes JSON lines on stdout. The migrated code must define `module Migrated` with
|
|
5
|
+
# singleton methods named like the original functions.
|
|
6
|
+
#
|
|
7
|
+
# Commands: replay (run each case once, capture behaviour), bench (time N iterations per case).
|
|
8
|
+
require "json"
|
|
9
|
+
require "stringio"
|
|
10
|
+
require "tmpdir"
|
|
11
|
+
require "digest"
|
|
12
|
+
require "set"
|
|
13
|
+
|
|
14
|
+
REAL_STDOUT = $stdout.dup
|
|
15
|
+
REAL_STDOUT.sync = true
|
|
16
|
+
|
|
17
|
+
def emit(event, **data)
|
|
18
|
+
REAL_STDOUT.write(JSON.generate(data.merge(event: event)) + "\n")
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def encode(value)
|
|
22
|
+
case value
|
|
23
|
+
when nil, true, false, String, Integer then value
|
|
24
|
+
when Float
|
|
25
|
+
return { "$float" => "nan" } if value.nan?
|
|
26
|
+
return { "$float" => value.positive? ? "inf" : "-inf" } if value.infinite?
|
|
27
|
+
return { "$float" => "-0.0" } if value.zero? && (1.0 / value).negative?
|
|
28
|
+
return { "$float" => value.to_s } if value == value.floor && value.abs > 2**53 # inexact integral double
|
|
29
|
+
|
|
30
|
+
value
|
|
31
|
+
when Array then value.map { |v| encode(v) }
|
|
32
|
+
when Hash then value.to_h { |k, v| [ k.to_s, encode(v) ] }
|
|
33
|
+
when Set then { "$set" => value.map { |v| encode(v) }.sort_by { |v| JSON.generate(v) } }
|
|
34
|
+
else { "$repr" => value.inspect[0, 200] }
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def decode(value)
|
|
39
|
+
case value
|
|
40
|
+
when Array then value.map { |v| decode(v) }
|
|
41
|
+
when Hash
|
|
42
|
+
if value.key?("$float")
|
|
43
|
+
{ "nan" => Float::NAN, "inf" => Float::INFINITY, "-inf" => -Float::INFINITY, "-0.0" => -0.0 }.fetch(value["$float"]) { Float(value["$float"]) }
|
|
44
|
+
elsif value.key?("$bytes") then value["$bytes"].unpack1("m0").b
|
|
45
|
+
elsif value.key?("$set") then Set.new(decode(value["$set"]))
|
|
46
|
+
else value.transform_values { |v| decode(v) }
|
|
47
|
+
end
|
|
48
|
+
else value
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def snapshot(root)
|
|
53
|
+
Dir.glob("**/*", File::FNM_DOTMATCH, base: root).filter_map do |rel|
|
|
54
|
+
full = File.join(root, rel)
|
|
55
|
+
next unless File.file?(full)
|
|
56
|
+
data = File.binread(full)
|
|
57
|
+
{ "path" => rel, "size" => data.bytesize, "sha256" => Digest::SHA256.hexdigest(data) }
|
|
58
|
+
end.sort_by { |e| e["path"] }
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def call(function, case_data)
|
|
62
|
+
args = decode(case_data.fetch("args", []))
|
|
63
|
+
kwargs = decode(case_data.fetch("kwargs", {})).transform_keys(&:to_sym)
|
|
64
|
+
kwargs.empty? ? Migrated.public_send(function, *args) : Migrated.public_send(function, *args, **kwargs)
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def run_case(function, case_data)
|
|
68
|
+
out = StringIO.new
|
|
69
|
+
err = StringIO.new
|
|
70
|
+
Dir.mktmpdir("pp-case-") do |scratch|
|
|
71
|
+
Dir.chdir(scratch) do
|
|
72
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
|
|
73
|
+
$stdout, $stderr = out, err
|
|
74
|
+
outcome =
|
|
75
|
+
begin
|
|
76
|
+
{ "kind" => "return", "value" => encode(call(function, case_data)) }
|
|
77
|
+
rescue StandardError => e
|
|
78
|
+
{ "kind" => "raise", "type" => e.class.name, "message" => e.message }
|
|
79
|
+
ensure
|
|
80
|
+
$stdout, $stderr = STDOUT, STDERR
|
|
81
|
+
end
|
|
82
|
+
duration = (Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) - started) / 1000
|
|
83
|
+
{ "outcome" => outcome, "stdout" => out.string, "stderr" => err.string,
|
|
84
|
+
"effects" => snapshot(scratch), "duration_us" => duration }
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def load_code(path)
|
|
90
|
+
# Silence output produced while loading the file itself.
|
|
91
|
+
$stdout = StringIO.new
|
|
92
|
+
load(path)
|
|
93
|
+
ensure
|
|
94
|
+
$stdout = STDOUT
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
request = JSON.parse($stdin.read)
|
|
98
|
+
load_code(request.fetch("code_file"))
|
|
99
|
+
function = request.fetch("function")
|
|
100
|
+
unless defined?(Migrated) && Migrated.respond_to?(function)
|
|
101
|
+
emit("fatal", message: "Migrated.#{function} is not defined. Define `module Migrated; def self.#{function}(...)`.")
|
|
102
|
+
exit 2
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
emit("plan", total: request["cases"].size, runtime: "ruby #{RUBY_VERSION}")
|
|
106
|
+
case request.fetch("command")
|
|
107
|
+
when "replay"
|
|
108
|
+
request["cases"].each { |c| emit("case", ref: c["ref"], **run_case(function, c).transform_keys(&:to_sym)) }
|
|
109
|
+
when "bench"
|
|
110
|
+
iterations = request.fetch("iterations", 30).to_i.clamp(1, 10_000)
|
|
111
|
+
request["cases"].each do |c|
|
|
112
|
+
samples = Dir.mktmpdir("pp-bench-") do |scratch|
|
|
113
|
+
Dir.chdir(scratch) do
|
|
114
|
+
$stdout = StringIO.new
|
|
115
|
+
Array.new(iterations) do
|
|
116
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
|
|
117
|
+
begin
|
|
118
|
+
call(function, c)
|
|
119
|
+
rescue StandardError
|
|
120
|
+
nil
|
|
121
|
+
end
|
|
122
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) - started
|
|
123
|
+
end
|
|
124
|
+
ensure
|
|
125
|
+
$stdout = STDOUT
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
emit("case", ref: c["ref"], samples_ns: samples, peak_memory_bytes: nil)
|
|
129
|
+
end
|
|
130
|
+
else
|
|
131
|
+
emit("fatal", message: "unknown command")
|
|
132
|
+
exit 2
|
|
133
|
+
end
|
|
134
|
+
emit("done")
|
package/harness/ruby_replay.rb
CHANGED
|
@@ -65,6 +65,17 @@ def snapshot(root)
|
|
|
65
65
|
end
|
|
66
66
|
|
|
67
67
|
request = JSON.parse($stdin.read)
|
|
68
|
+
|
|
69
|
+
# Recorded with --pin-clock: the original saw 2026-01-01T00:00:00Z, so the port sees it too.
|
|
70
|
+
# (Random numbers cannot be pinned across languages: pass them in as arguments instead.)
|
|
71
|
+
if request["pin_clock"]
|
|
72
|
+
require "date"
|
|
73
|
+
PIN_TIME = Time.at(1_767_225_600).utc.freeze
|
|
74
|
+
Time.singleton_class.prepend(Module.new { def now(**) = PIN_TIME.dup })
|
|
75
|
+
Date.singleton_class.prepend(Module.new { def today(*) = Date.new(2026, 1, 1) })
|
|
76
|
+
DateTime.singleton_class.prepend(Module.new { def now(*) = DateTime.new(2026, 1, 1, 0, 0, 0) })
|
|
77
|
+
end
|
|
78
|
+
|
|
68
79
|
$stdout = StringIO.new
|
|
69
80
|
begin
|
|
70
81
|
if request["rails_root"]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ruby-anything",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Migrate any app (TypeScript, JavaScript, Python, Go, Java/Spring, Kotlin, C#, PHP, Rust, Swift) to Ruby on Rails with Hotwire, Tailwind and daisyUI, one piece at a time, checked against the original's recorded behavior at every step.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ruby",
|
|
@@ -18,12 +18,12 @@
|
|
|
18
18
|
"license": "MIT",
|
|
19
19
|
"repository": {
|
|
20
20
|
"type": "git",
|
|
21
|
-
"url": "git+https://github.com/akkisavi/
|
|
21
|
+
"url": "git+https://github.com/akkisavi/ruby-anything.git",
|
|
22
22
|
"directory": "packages/ruby-anything"
|
|
23
23
|
},
|
|
24
|
-
"homepage": "https://github.com/akkisavi/
|
|
24
|
+
"homepage": "https://github.com/akkisavi/ruby-anything#readme",
|
|
25
25
|
"bugs": {
|
|
26
|
-
"url": "https://github.com/akkisavi/
|
|
26
|
+
"url": "https://github.com/akkisavi/ruby-anything/issues"
|
|
27
27
|
},
|
|
28
28
|
"bin": {
|
|
29
29
|
"ruby-anything": "bin/ruby-anything.js"
|
|
@@ -38,11 +38,12 @@
|
|
|
38
38
|
".mcp.json",
|
|
39
39
|
"README.md",
|
|
40
40
|
"LICENSE",
|
|
41
|
-
"docs"
|
|
41
|
+
"docs",
|
|
42
|
+
"action.yml",
|
|
43
|
+
"!adapters/node/node_modules"
|
|
42
44
|
],
|
|
43
45
|
"scripts": {
|
|
44
|
-
"
|
|
45
|
-
"test": "node test/run.js"
|
|
46
|
+
"test": "node scripts/test.js"
|
|
46
47
|
},
|
|
47
48
|
"engines": {
|
|
48
49
|
"node": ">=18"
|
|
@@ -71,8 +71,19 @@ objects).
|
|
|
71
71
|
ruby-anything bridge <repo> <unit-id> # Ruby skeleton + rails/port/TASK.md; never overwrites a method
|
|
72
72
|
ruby-anything record <repo> <unit-id> # the original's behavior on edge cases -> rails/port/cases/*.jsonl
|
|
73
73
|
ruby-anything record <repo> <unit-id> --inputs real.jsonl # {"fn": name, "args": [...]} per line
|
|
74
|
+
ruby-anything record <repo> <unit-id> --from-tests -- pytest # or: npx jest, npx vitest run, node --test
|
|
75
|
+
ruby-anything record <repo> <unit-id> --pin-clock # time and dates read 2026-01-01T00:00:00Z
|
|
74
76
|
```
|
|
75
77
|
|
|
78
|
+
- **The original has tests? Record their calls**: `--from-tests -- <test command>` runs the suite
|
|
79
|
+
with the function instrumented (Python, TypeScript, JavaScript), and every distinct call it makes
|
|
80
|
+
becomes a case next to the generated ones (`--no-generate` for only those). The source file is
|
|
81
|
+
restored byte for byte afterwards, also after a crash.
|
|
82
|
+
- **The function reads the clock** (`datetime.now`, `Date.now`, `time.time`, `date.today`):
|
|
83
|
+
record with `--pin-clock`. The original then sees 2026-01-01T00:00:00Z and `diff` runs the port
|
|
84
|
+
with `Time.now`, `Date.today` and `DateTime.now` frozen at the same instant. Random numbers cannot
|
|
85
|
+
match across languages: make the random value an argument (or inject a generator) instead.
|
|
86
|
+
|
|
76
87
|
**A port keeps behavior, bugs included.** Port a known bug as it is; fix it in its own change
|
|
77
88
|
after `gate` passes, with each case it changes in `rails/port/known-diffs.jsonl`
|
|
78
89
|
(`{"unit", "args", "actual", "reason"}`) and the user's yes.
|
|
@@ -103,7 +114,12 @@ corrects how the port behaves, add it right away: `ruby-anything rules <repo> --
|
|
|
103
114
|
ruby-anything diff <repo> <unit-id> # must be N/N; groups mismatches and names where each first differs
|
|
104
115
|
```
|
|
105
116
|
|
|
106
|
-
A mismatch is a behavior difference: fix the port, never the recording.
|
|
117
|
+
A mismatch is a behavior difference: fix the port, never the recording.
|
|
118
|
+
|
|
119
|
+
**The original keeps changing?** After pulling upstream changes (and in CI while the original is
|
|
120
|
+
still developed), run `ruby-anything drift <repo>`: it re-runs the original on every recorded unit
|
|
121
|
+
case and HTTP/CLI case and lists what now answers differently, plus routes no case records. For
|
|
122
|
+
each drifted unit: `record` again, then `diff`; the new mismatches are what changed upstream. When `diff` says the port
|
|
107
123
|
is **stalled** (three changes to the port in a row gained no matching case), stop editing: show the
|
|
108
124
|
user the remaining mismatches and ask. They may know the rule you are missing.
|
|
109
125
|
|
|
@@ -95,6 +95,34 @@ token in `headers`), and the error paths (bad input, missing records, forbidden,
|
|
|
95
95
|
failures). Every GET runs twice: values that change between runs become `[..]` wildcards. Ask the
|
|
96
96
|
user about each one: is the order part of the contract?
|
|
97
97
|
|
|
98
|
+
**Side effects.** If the app calls other APIs, sends email or writes a database, record those too,
|
|
99
|
+
or a port that forgets to charge the card or send the receipt would pass:
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
ruby-anything app record <repo> --http --inputs ... \
|
|
103
|
+
--effect-env PAYMENT_API_URL=http,SMTP_HOST=smtp_host,SMTP_PORT=smtp_port \
|
|
104
|
+
--db-dump "sqlite3 db.sqlite3 .dump" --db-reset "<reset command>" -- <start command>
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`--effect-env NAME=KIND` points the app's own setting at a local stand-in: `http` (a URL that
|
|
108
|
+
records every call and answers 200 `{}`, or what `rails/port/app-cases/effect-replies.json`
|
|
109
|
+
says: `[{"method", "path", "status", "body"}]`), `smtp` (an `smtp://host:port` URL), `smtp_host`
|
|
110
|
+
and `smtp_port`. Find the variable names in the app's config; ask the user when it hardcodes a
|
|
111
|
+
URL. `--db-dump` runs after every non-GET request and its rows are part of the case. Replay sets
|
|
112
|
+
the same variables for the Rails app, so Rails must read them too: the payment client's base URL
|
|
113
|
+
from the same env var, Action Mailer's `smtp_settings` from `SMTP_HOST`/`SMTP_PORT` (with
|
|
114
|
+
`delivery_method :smtp` in development), and the same database the dump reads.
|
|
115
|
+
|
|
116
|
+
**CLI apps.** For a command-line tool there is no server: list invocations in
|
|
117
|
+
`rails/port/app-cases/cli.jsonl` (`{"name", "args": [...], "stdin", "env"}`: every command and
|
|
118
|
+
flag, `--help`, bad input, each error exit code) and record with
|
|
119
|
+
`ruby-anything app record <repo> --cli --inputs rails/port/app-cases/cli.jsonl -- python tool.py`
|
|
120
|
+
(or `ruby-anything go --cli -- python tool.py`). Each invocation runs twice in a throwaway copy of
|
|
121
|
+
the repo; exit code, stdout, stderr and the files it writes are the case. The front door is
|
|
122
|
+
`rails/bin/<name>`: a command wired with `app wire <repo> <unit> --command <name>` (`*` for the
|
|
123
|
+
default) runs `Cli::<Unit>.call(argv)` from `rails/app/cli/<unit>.rb` inside the Rails app and
|
|
124
|
+
returns the exit code; every other invocation execs the original.
|
|
125
|
+
|
|
98
126
|
## 4. Build the front door
|
|
99
127
|
|
|
100
128
|
```sh
|
|
@@ -154,7 +182,15 @@ ruby-anything app lift <repo> # refuses until nothing falls back; repla
|
|
|
154
182
|
|
|
155
183
|
## 7. Prove it, then cut over
|
|
156
184
|
|
|
157
|
-
Run `ruby-anything app replay <repo>` and `bin/rails test` in CI
|
|
185
|
+
Run `ruby-anything app replay <repo>` and `bin/rails test` in CI, plus `ruby-anything drift <repo>`
|
|
186
|
+
while the original is still developed. In GitHub Actions, the bundled action runs the gate on
|
|
187
|
+
every pull request:
|
|
188
|
+
|
|
189
|
+
```yaml
|
|
190
|
+
- uses: <owner>/<repo>/packages/ruby-anything@master # or the published copy
|
|
191
|
+
with:
|
|
192
|
+
app: "true"
|
|
193
|
+
``` A mismatch is a bug in the
|
|
158
194
|
port, never in the cases: change a case only with the user's approval, recorded in an ADR.
|
|
159
195
|
|
|
160
196
|
After the lift the Rails app no longer has to mirror the original's structure. Offer a reshape
|
package/src/adapters.js
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
|
-
'use strict'
|
|
2
|
-
// Runs
|
|
3
|
-
// Recording EXECUTES the original: work on a copy, with a test database.
|
|
4
|
-
const fs = require('node:fs')
|
|
5
|
-
const path = require('node:path')
|
|
6
|
-
const { PKG, python, which, runHarness } = require('./util')
|
|
7
|
-
|
|
8
|
-
const POLYGLOT = { go: 'go', java: 'javac', kotlin: 'kotlinc', csharp: 'dotnet', php: 'php', rust: 'rustc', swift: 'swiftc', ruby: 'ruby' }
|
|
9
|
-
|
|
10
|
-
function adaptersDir() {
|
|
11
|
-
const bundled = path.join(PKG, 'adapters')
|
|
12
|
-
if (fs.existsSync(path.join(bundled, 'polyglot'))) return bundled
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
const { events } = await runHarness(h.argv,
|
|
54
|
-
return {
|
|
55
|
-
runtime: events.find((e) => e.event === 'plan')?.runtime,
|
|
56
|
-
cases: events.filter((e) => e.event === 'case'),
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
module.exports = { adaptersDir, harnessFor, supported, analyzeUnits, record }
|
|
1
|
+
'use strict'
|
|
2
|
+
// Runs the language adapters (the recorders) on the original code.
|
|
3
|
+
// Recording EXECUTES the original: work on a copy, with a test database.
|
|
4
|
+
const fs = require('node:fs')
|
|
5
|
+
const path = require('node:path')
|
|
6
|
+
const { PKG, python, which, runHarness, canon } = require('./util')
|
|
7
|
+
|
|
8
|
+
const POLYGLOT = { go: 'go', java: 'javac', kotlin: 'kotlinc', csharp: 'dotnet', php: 'php', rust: 'rustc', swift: 'swiftc', ruby: 'ruby' }
|
|
9
|
+
|
|
10
|
+
function adaptersDir() {
|
|
11
|
+
const bundled = path.join(PKG, 'adapters')
|
|
12
|
+
if (fs.existsSync(path.join(bundled, 'polyglot'))) return bundled
|
|
13
|
+
throw new Error('language adapters missing: reinstall ruby-anything')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// argv + env for a language's harness, or throws with what to install.
|
|
17
|
+
function harnessFor(lang) {
|
|
18
|
+
const dir = adaptersDir()
|
|
19
|
+
const py = python()
|
|
20
|
+
if (lang === 'python') {
|
|
21
|
+
if (!py) throw new Error('python 3 is required to record Python code')
|
|
22
|
+
return { argv: [py, '-X', 'utf8', '-I', '-B', path.join(dir, 'python', 'harness.py')], env: {} }
|
|
23
|
+
}
|
|
24
|
+
if (lang === 'javascript' || lang === 'typescript') {
|
|
25
|
+
return { argv: [process.execPath, '--enable-source-maps', path.join(dir, 'node', 'harness.mjs')], env: {} }
|
|
26
|
+
}
|
|
27
|
+
if (POLYGLOT[lang]) {
|
|
28
|
+
if (!py) throw new Error(`python 3 is required to drive the ${lang} recorder`)
|
|
29
|
+
if (!which(POLYGLOT[lang])) throw new Error(`${POLYGLOT[lang]} is not installed (needed to record ${lang}); run ruby-anything doctor`)
|
|
30
|
+
return { argv: [py, '-X', 'utf8', '-B', path.join(dir, 'polyglot', 'harness.py')], env: { PORTPILOT_LANGUAGE: lang } }
|
|
31
|
+
}
|
|
32
|
+
throw new Error(`no recorder for ${lang}`)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function supported(lang) {
|
|
36
|
+
return lang === 'python' || lang === 'javascript' || lang === 'typescript' || !!POLYGLOT[lang]
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function analyzeUnits(root, lang) {
|
|
40
|
+
const h = harnessFor(lang)
|
|
41
|
+
const { events } = await runHarness(h.argv, { command: 'analyze' }, { env: { ...h.env, PORTPILOT_SRC: root }, cwd: root })
|
|
42
|
+
return {
|
|
43
|
+
files: events.filter((e) => e.event === 'file'),
|
|
44
|
+
units: events.filter((e) => e.event === 'unit'),
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function record(root, lang, { moduleFile, fn, cases = [], count = 40, seed = 1, mode = 'edge', pinClock = false, onEvent }) {
|
|
49
|
+
const h = harnessFor(lang)
|
|
50
|
+
const req = { command: 'record', module_file: moduleFile, function: fn, cases: '__CASES__', generate: count ? { count, seed, mode } : null, pin_clock: !!pinClock }
|
|
51
|
+
// cases keep their int/float kinds ({ $n } values) on the way in
|
|
52
|
+
const raw = JSON.stringify(req).replace('"__CASES__"', canon(cases))
|
|
53
|
+
const { events } = await runHarness(h.argv, raw, { env: { ...h.env, PORTPILOT_SRC: root }, cwd: root, onEvent })
|
|
54
|
+
return {
|
|
55
|
+
runtime: events.find((e) => e.event === 'plan')?.runtime,
|
|
56
|
+
cases: events.filter((e) => e.event === 'case'),
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { adaptersDir, harnessFor, supported, analyzeUnits, record }
|