codecop 0.1.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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Transaction shapes in source code (discovery, text only: nothing is run).
|
|
2
|
+
|
|
3
|
+
What is found per file, by language (Python, Go, Rust, TypeScript/JavaScript, Java/Kotlin):
|
|
4
|
+
|
|
5
|
+
- transaction blocks: explicit begin .. commit (`tx, err := db.BeginTx(..)` .. `tx.Commit()`, `let mut tx = pool.begin()`
|
|
6
|
+
.. `tx.commit()`, `execute("BEGIN IMMEDIATE")` .. `commit()`), `with`/closure forms (`with transaction.atomic():`,
|
|
7
|
+
`async with conn.transaction():`, `db.Transaction(func(tx *gorm.DB) error {..})`, `prisma.$transaction(async (tx) =>
|
|
8
|
+
{..})`, `knex.transaction(async trx => {..})`, `conn.transaction(|c| {..})`), annotations (`@transaction.atomic`,
|
|
9
|
+
`@Transactional`). Each with its first and last line, form, SQLite begin mode, isolation level, the enclosing function,
|
|
10
|
+
and what else happens inside (an HTTP/RPC/LLM call, a sleep, a publish, a subprocess), directly or one call away in
|
|
11
|
+
the same file;
|
|
12
|
+
- SQLite opens: where a SQLite database is opened and whether WAL, a busy timeout or an immediate transaction lock are
|
|
13
|
+
set in that file;
|
|
14
|
+
- read-modify-write through an ORM object: `obj = Model.objects.get(..)`, `obj.n += 1`, `obj.save()` with no
|
|
15
|
+
`select_for_update`.
|
|
16
|
+
|
|
17
|
+
The statements inside a block are not parsed here: the rules link the block to the query call sites discovery already
|
|
18
|
+
found (same file and lines, or a function the block calls with its transaction).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import re
|
|
24
|
+
|
|
25
|
+
LANGS = ("python", "go", "rust", "typescript", "javascript", "java", "kotlin")
|
|
26
|
+
|
|
27
|
+
# --- what else happens inside a transaction ------------------------------------------------------------------------------
|
|
28
|
+
CALLS = [
|
|
29
|
+
("llm", re.compile(r"\b(?:openai|anthropic|litellm)\.|\.chat\.completions\.create\(|\.messages\.create\(|\bacompletion\(|\bcompletion\(")),
|
|
30
|
+
("http", re.compile(r"\brequests\.(?:get|post|put|patch|delete|request|head)\(|\bhttpx\.(?:get|post|put|patch|delete|request|AsyncClient|Client)\b|"
|
|
31
|
+
r"\baiohttp\.|\burlopen\(|\bfetch\(\s*[`'\"a-zA-Z]|\baxios(?:\.\w+)?\(|\bgot\(|\bhttp\.(?:Get|Post|Head|NewRequest\w*)\(|"
|
|
32
|
+
r"\.Do\(\s*req|\breqwest::|\.send\(\)\s*\.await|\bhttp_client\.|\bRestTemplate\b|\b[rR]estTemplate\.\w+\(|\b[wW]ebClient\.\w+\(|\bWebClient\b|\bHttpClient\b|"
|
|
33
|
+
r"\bOkHttpClient\b|\bsession\.(?:get|post|put|patch|delete)\(\s*(?:url|f?['\"]https?:)")),
|
|
34
|
+
("rpc", re.compile(r"\bgrpc\.|\.Invoke\(ctx|\bstub\.\w+\(")),
|
|
35
|
+
("sleep", re.compile(r"\btime\.sleep\(|\basyncio\.sleep\(|\btime\.Sleep\(|\btokio::time::sleep\(|\bthread::sleep\(|\bThread\.sleep\(|"
|
|
36
|
+
r"\bsetTimeout\(|\bawait\s+sleep\(")),
|
|
37
|
+
("publish", re.compile(r"\.publish\(|\.Publish\(|\bsend_message\(|\.SendMessage\(|\.produce\(|\.WriteMessages\(|\bsend_mail\(|"
|
|
38
|
+
r"\bsmtplib\.|\.apply_async\(|\.delay\(\s*\w|\bsqs\.|\bsns\.|\bkafka\w*\.(?:send|produce)")),
|
|
39
|
+
("subprocess", re.compile(r"\bsubprocess\.|\bexec\.Command\(|\bCommand::new\(|\bchild_process\.|\bProcessBuilder\(")),
|
|
40
|
+
("storage", re.compile(r"\bboto3\.|\bs3(?:_client)?\.(?:put_object|upload_\w+|get_object)\(|\.PutObject\(|\.upload_file\(")),
|
|
41
|
+
]
|
|
42
|
+
COMMENT = {"python": re.compile(r"^\s*#"), "default": re.compile(r"^\s*(?://|\*|/\*)")}
|
|
43
|
+
|
|
44
|
+
# --- transaction blocks --------------------------------------------------------------------------------------------------
|
|
45
|
+
PY_WITH = re.compile(r"^(\s*)(?:async\s+)?with\s+(.*?(?:\btransaction\.atomic\b|\.atomic\(|\bdb\.atomic\(|\.begin\(|\.begin_nested\(|"
|
|
46
|
+
r"\.transaction\(|\.transaction\b(?!_)|\bSession\.begin\(|\bsession_scope\(|\btransaction\(\)).*):\s*(?:#.*)?$")
|
|
47
|
+
PY_DECOR = re.compile(r"^(\s*)@(?:transaction\.atomic|atomic|db_session|transactional|in_transaction)\b")
|
|
48
|
+
PY_BEGIN = re.compile(r"\.execute\(\s*[rbuf]?['\"]\s*BEGIN(\s+(?:IMMEDIATE|EXCLUSIVE|DEFERRED|TRANSACTION))?", re.I)
|
|
49
|
+
PY_COMMIT = re.compile(r"\.commit\(\)|\.execute\(\s*[rbuf]?['\"]\s*(?:COMMIT|END)\b", re.I)
|
|
50
|
+
GO_BEGIN = re.compile(r"(\w+)\s*,\s*\w+\s*:?=\s*[\w.\[\]()]+\.(?:Begin|BeginTx|Beginx|BeginTxx|MustBegin|MustBeginTx)\(")
|
|
51
|
+
GO_CLOSURE = re.compile(r"\.(?:Transaction|RunInTx|InTx|WithTx|WithTransaction|ExecTx|BeginFunc|BeginTxFunc|RunInTransaction|"
|
|
52
|
+
r"WithinTransaction|Tx|InTransaction|DoTx)\(\s*[^{]*?func\s*\(\s*(\w+)")
|
|
53
|
+
RS_BEGIN = re.compile(r"let\s+(?:mut\s+)?(\w+)\s*=\s*[^;]*?\.begin\(\)")
|
|
54
|
+
RS_CLOSURE = re.compile(r"\.(?:transaction|build_transaction\(\)\.run|transaction_async)\w*(?:::<[^>]*>)?\(\s*(?:move\s*)?\|\s*(?:mut\s+)?(\w+)")
|
|
55
|
+
TS_CLOSURE = re.compile(r"(?:\$transaction|\.transaction|\.transactionAsync|\.withTransaction)\(\s*(?:\{[^}]*\}\s*,\s*)?(?:async\s*)?"
|
|
56
|
+
r"(?:\(\s*(\w+)?[^)]*\)|(\w+))\s*=>")
|
|
57
|
+
TS_ARRAY = re.compile(r"\$transaction\(\s*\[")
|
|
58
|
+
TS_BEGIN = re.compile(r"\.(?:query|execute|raw|exec)\(\s*[`'\"]\s*BEGIN(\s+(?:IMMEDIATE|EXCLUSIVE|DEFERRED|TRANSACTION))?", re.I)
|
|
59
|
+
TS_COMMIT = re.compile(r"\.(?:query|execute|raw|exec)\(\s*[`'\"]\s*COMMIT|\.commit\(\)", re.I)
|
|
60
|
+
JAVA_ANN = re.compile(r"^\s*@Transactional\b(?:\(([^)]*)\))?")
|
|
61
|
+
JAVA_TEMPLATE = re.compile(r"\b\w*[tT]ransactionTemplate\.(?:execute|executeWithoutResult)\(")
|
|
62
|
+
JAVA_BEGIN = re.compile(r"\.setAutoCommit\(\s*false\s*\)")
|
|
63
|
+
JAVA_COMMIT = re.compile(r"\.commit\(\)")
|
|
64
|
+
GENERIC_COMMIT = re.compile(r"\.(?:Commit|commit)\(\)")
|
|
65
|
+
|
|
66
|
+
ISOLATION = re.compile(r"\b(SERIALIZABLE|REPEATABLE[ _]READ|READ[ _]COMMITTED|READ[ _]UNCOMMITTED|LevelSerializable|LevelRepeatableRead|"
|
|
67
|
+
r"LevelReadCommitted|Isolation\.\w+)\b", re.I)
|
|
68
|
+
SQLITE_MODE = re.compile(r"\bBEGIN\s+(IMMEDIATE|EXCLUSIVE|DEFERRED)\b|_txlock=(immediate|exclusive|deferred)|isolation_level\s*=\s*['\"](IMMEDIATE|EXCLUSIVE|DEFERRED)['\"]", re.I)
|
|
69
|
+
|
|
70
|
+
# --- SQLite opens and settings --------------------------------------------------------------------------------------------
|
|
71
|
+
SQLITE_OPEN = re.compile(r"\bsqlite3\.connect\(|\baiosqlite\.connect\(|sql\.Open\(\s*\"(?:sqlite3?|sqlite)\"|\bgorm\.Open\(\s*sqlite\.Open\(|"
|
|
72
|
+
r"\bSqlitePool(?:Options)?\b|\bSqliteConnectOptions\b|\brusqlite::Connection::open\w*\(|\bConnection::open(?:_with_flags)?\(|"
|
|
73
|
+
r"new\s+(?:Database|sqlite3\.Database)\(|\bcreate_engine\(\s*f?['\"]sqlite|\bdrizzle\(\s*new\s+Database|"
|
|
74
|
+
r"\bsqlite\+aiosqlite://|\bjdbc:sqlite:")
|
|
75
|
+
SQLITE_WAL = re.compile(r"journal_mode\s*[=(:]\s*['\"]?WAL|_journal_mode=WAL|_journal=WAL|journal_mode\(\s*\w*::Wal|\.journal_mode\(|pragma\(\s*['\"]journal_mode\s*=\s*WAL", re.I)
|
|
76
|
+
SQLITE_NOT_WAL = re.compile(r"journal_mode\s*=\s*['\"]?(DELETE|TRUNCATE|PERSIST|MEMORY|OFF)\b", re.I)
|
|
77
|
+
SQLITE_BUSY = re.compile(r"busy_timeout\s*[=(:]\s*['\"]?(\d+)|_busy_timeout=(\d+)|_timeout=(\d+)|\.busy_timeout\(\s*(?:Duration::from_(secs|millis)\(\s*)?(\d+)|"
|
|
78
|
+
r"sqlite3\.connect\([^)]*timeout\s*=\s*([\d.]+)|\btimeout\s*:\s*(\d+)", re.I)
|
|
79
|
+
|
|
80
|
+
# --- ORM read-modify-write (Python) --------------------------------------------------------------------------------------
|
|
81
|
+
PY_GET = re.compile(r"^\s*(\w+)\s*=\s*(?:await\s+)?([\w.]+)\.objects(?:\.\w+\([^)]*\))*?\.(?:get|first|last|aget|afirst)\(")
|
|
82
|
+
PY_INC = re.compile(r"^\s*(\w+)\.(\w+)\s*(\+=|-=|=\s*\1\.\2\s*[+-])")
|
|
83
|
+
PY_SAVE = re.compile(r"^\s*(?:await\s+)?(\w+)\.a?save\(")
|
|
84
|
+
PY_SFU = re.compile(r"select_for_update\(|F\(\s*['\"]")
|
|
85
|
+
|
|
86
|
+
FN = {
|
|
87
|
+
"python": re.compile(r"^(\s*)(?:async\s+)?def\s+(\w+)\s*\("),
|
|
88
|
+
"go": re.compile(r"^func\s+(?:\([^)]*\)\s*)?(\w+)\s*(?:\[[^\]]*\])?\("),
|
|
89
|
+
"rust": re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)"),
|
|
90
|
+
"typescript": re.compile(r"^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\s*\*?\s*(\w+)|(?:public|private|protected|static|readonly|\s)*"
|
|
91
|
+
r"(?:async\s+)?(\w+)\s*\([^)]*\)\s*(?::\s*[^{=]+)?\{|(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?(?:\([^)]*\)|\w+)\s*(?::\s*[^=]+)?=>)"),
|
|
92
|
+
"java": re.compile(r"^\s*(?:(?:public|private|protected|static|final|synchronized|abstract|override|suspend|open|internal)\s+)*"
|
|
93
|
+
r"(?:fun\s+(\w+)|[\w<>\[\],.? ]+\s+(\w+)\s*\([^;]*$)"),
|
|
94
|
+
}
|
|
95
|
+
FN["javascript"] = FN["typescript"]
|
|
96
|
+
FN["kotlin"] = FN["java"]
|
|
97
|
+
CONTROL = {"if", "for", "while", "switch", "catch", "return", "function", "else", "new", "await", "do", "try", "constructor"}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def strip_strings(line: str) -> str:
|
|
101
|
+
"""The line with string literal contents blanked (braces inside strings must not count)."""
|
|
102
|
+
return re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`", lambda m: m.group(0)[0] + " " * (len(m.group(0)) - 2) + m.group(0)[-1], line)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def match_brace(lines: list[str], start_line: int, start_col: int = 0, open_ch: str = "{", close_ch: str = "}") -> int | None:
|
|
106
|
+
"""The line (0-based) of the bracket closing the first `open_ch` at or after (start_line, start_col)."""
|
|
107
|
+
depth, opened = 0, False
|
|
108
|
+
in_block = False
|
|
109
|
+
for i in range(start_line, min(len(lines), start_line + 3000)):
|
|
110
|
+
text = strip_strings(lines[i])
|
|
111
|
+
if i == start_line:
|
|
112
|
+
text = " " * start_col + text[start_col:]
|
|
113
|
+
j = 0
|
|
114
|
+
while j < len(text):
|
|
115
|
+
two = text[j:j + 2]
|
|
116
|
+
if in_block:
|
|
117
|
+
if two == "*/":
|
|
118
|
+
in_block, j = False, j + 2
|
|
119
|
+
continue
|
|
120
|
+
j += 1
|
|
121
|
+
continue
|
|
122
|
+
if two == "//":
|
|
123
|
+
break
|
|
124
|
+
if two == "/*":
|
|
125
|
+
in_block, j = True, j + 2
|
|
126
|
+
continue
|
|
127
|
+
ch = text[j]
|
|
128
|
+
if ch == open_ch:
|
|
129
|
+
depth, opened = depth + 1, True
|
|
130
|
+
elif ch == close_ch and opened:
|
|
131
|
+
depth -= 1
|
|
132
|
+
if depth == 0:
|
|
133
|
+
return i
|
|
134
|
+
j += 1
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def functions(lines: list[str], lang: str) -> list[dict]:
|
|
139
|
+
"""[{name, start, end}] (0-based lines) of the functions of a file: by indentation (Python), by braces (others)."""
|
|
140
|
+
out = []
|
|
141
|
+
pat = FN.get(lang)
|
|
142
|
+
if not pat:
|
|
143
|
+
return out
|
|
144
|
+
if lang == "python":
|
|
145
|
+
for i, ln in enumerate(lines):
|
|
146
|
+
m = pat.match(ln)
|
|
147
|
+
if not m:
|
|
148
|
+
continue
|
|
149
|
+
ind = len(m.group(1))
|
|
150
|
+
j = i + 1
|
|
151
|
+
while j < len(lines) and (not lines[j].strip() or len(lines[j]) - len(lines[j].lstrip()) > ind or lines[j].lstrip().startswith(")")):
|
|
152
|
+
j += 1
|
|
153
|
+
out.append({"name": m.group(2), "start": i, "end": j - 1})
|
|
154
|
+
return out
|
|
155
|
+
for i, ln in enumerate(lines):
|
|
156
|
+
m = pat.match(ln)
|
|
157
|
+
if not m:
|
|
158
|
+
continue
|
|
159
|
+
name = next((g for g in m.groups() if g), None)
|
|
160
|
+
if not name or name in CONTROL:
|
|
161
|
+
continue
|
|
162
|
+
# the body: the first `{` on this line or the next few (a signature can wrap)
|
|
163
|
+
for k in range(i, min(len(lines), i + 40)):
|
|
164
|
+
col = strip_strings(lines[k]).find("{")
|
|
165
|
+
if col >= 0:
|
|
166
|
+
end = match_brace(lines, k, col)
|
|
167
|
+
if end is not None:
|
|
168
|
+
out.append({"name": name, "start": i, "end": end})
|
|
169
|
+
break
|
|
170
|
+
if strip_strings(lines[k]).rstrip().endswith(";"):
|
|
171
|
+
break
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def enclosing(funcs: list[dict], line0: int) -> dict | None:
|
|
176
|
+
best = None
|
|
177
|
+
for f in funcs:
|
|
178
|
+
if f["start"] <= line0 <= f["end"] and (best is None or f["start"] >= best["start"]):
|
|
179
|
+
best = f
|
|
180
|
+
return best
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def calls_in(lines: list[str], a: int, b: int, lang: str) -> list[dict]:
|
|
184
|
+
"""External work between lines a and b (0-based, inclusive): [{line (1-based), what, text}]."""
|
|
185
|
+
com = COMMENT.get(lang, COMMENT["default"])
|
|
186
|
+
out = []
|
|
187
|
+
for i in range(a, min(b, len(lines) - 1) + 1):
|
|
188
|
+
ln = lines[i]
|
|
189
|
+
if com.match(ln):
|
|
190
|
+
continue
|
|
191
|
+
for what, pat in CALLS:
|
|
192
|
+
if pat.search(ln):
|
|
193
|
+
out.append({"line": i + 1, "what": what, "text": ln.strip()[:100]})
|
|
194
|
+
break
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _block(form: str, a: int, b: int, lines: list[str], lang: str, funcs: list[dict], tx_var: str = "", head: str = "") -> dict:
|
|
199
|
+
fn = enclosing(funcs, a)
|
|
200
|
+
body = "\n".join(lines[a:b + 1])
|
|
201
|
+
mode = SQLITE_MODE.search(head or lines[a]) or SQLITE_MODE.search(body[:2000])
|
|
202
|
+
iso = ISOLATION.search(lines[a]) or ISOLATION.search(body[:800])
|
|
203
|
+
return {"line": a + 1, "end_line": b + 1, "form": form, "symbol": fn["name"] if fn else "", "tx_var": tx_var,
|
|
204
|
+
"begin_mode": next((g for g in mode.groups() if g), "").upper() if mode else "",
|
|
205
|
+
"isolation": iso.group(1).replace("_", " ").upper() if iso else ""}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def blocks(text: str, lang: str) -> list[dict]:
|
|
209
|
+
"""The transaction blocks of one file (1-based lines)."""
|
|
210
|
+
lines = text.splitlines()
|
|
211
|
+
funcs = functions(lines, lang)
|
|
212
|
+
out: list[dict] = []
|
|
213
|
+
com = COMMENT.get(lang, COMMENT["default"])
|
|
214
|
+
|
|
215
|
+
def fn_end(i: int) -> int:
|
|
216
|
+
f = enclosing(funcs, i)
|
|
217
|
+
return f["end"] if f else min(len(lines) - 1, i + 150)
|
|
218
|
+
|
|
219
|
+
def until(i: int, pat: re.Pattern, var: str = "") -> int:
|
|
220
|
+
end = fn_end(i)
|
|
221
|
+
for j in range(i + 1, end + 1):
|
|
222
|
+
if com.match(lines[j]):
|
|
223
|
+
continue
|
|
224
|
+
if pat.search(lines[j]) and (not var or var in lines[j] or not re.search(r"\w+\.(?:Commit|commit)\(", lines[j])):
|
|
225
|
+
return j
|
|
226
|
+
return end
|
|
227
|
+
|
|
228
|
+
for i, ln in enumerate(lines):
|
|
229
|
+
if com.match(ln):
|
|
230
|
+
continue
|
|
231
|
+
if lang in ("rust", "go") and re.search(r"(?:let\s+(?:mut\s+)?\w+\s*=|:?=)\s*[\w.&*]*\s*$", ln) and i + 1 < len(lines) \
|
|
232
|
+
and (ln.rstrip().endswith("=") or lines[i + 1].lstrip().startswith(".")):
|
|
233
|
+
# `let mut tx = self` / `.pool` / `.begin()`: one statement over several lines
|
|
234
|
+
ln = ln + " " + " ".join(x.strip() for x in lines[i + 1:i + 5])
|
|
235
|
+
if lang == "python":
|
|
236
|
+
m = PY_WITH.match(ln)
|
|
237
|
+
if m and not re.search(r"\bopen\(|\block\b|\bLock\(", m.group(2)):
|
|
238
|
+
ind = len(m.group(1))
|
|
239
|
+
j = i + 1
|
|
240
|
+
while j < len(lines) and (not lines[j].strip() or len(lines[j]) - len(lines[j].lstrip()) > ind):
|
|
241
|
+
j += 1
|
|
242
|
+
out.append(_block("with_block", i, j - 1, lines, lang, funcs, head=ln))
|
|
243
|
+
continue
|
|
244
|
+
m = PY_DECOR.match(ln)
|
|
245
|
+
if m:
|
|
246
|
+
for k in range(i + 1, min(len(lines), i + 6)):
|
|
247
|
+
if FN["python"].match(lines[k]):
|
|
248
|
+
f = next((x for x in funcs if x["start"] == k), None)
|
|
249
|
+
if f:
|
|
250
|
+
out.append(_block("annotation", k, f["end"], lines, lang, funcs, head=ln))
|
|
251
|
+
break
|
|
252
|
+
continue
|
|
253
|
+
if PY_BEGIN.search(ln):
|
|
254
|
+
out.append(_block("begin_commit", i, until(i, PY_COMMIT), lines, lang, funcs, head=ln))
|
|
255
|
+
elif lang == "go":
|
|
256
|
+
m = GO_BEGIN.search(ln)
|
|
257
|
+
if m:
|
|
258
|
+
var = m.group(1)
|
|
259
|
+
out.append(_block("begin_commit", i, until(i, re.compile(rf"\b{re.escape(var)}\.Commit\("), var), lines, lang, funcs, tx_var=var, head=ln))
|
|
260
|
+
continue
|
|
261
|
+
m = GO_CLOSURE.search(ln)
|
|
262
|
+
if m:
|
|
263
|
+
col = strip_strings(ln).find("{", m.end())
|
|
264
|
+
end = match_brace(lines, i, col) if col >= 0 else None
|
|
265
|
+
if end is not None:
|
|
266
|
+
out.append(_block("closure", i, end, lines, lang, funcs, tx_var=m.group(1), head=ln))
|
|
267
|
+
elif lang == "rust":
|
|
268
|
+
m = RS_BEGIN.search(ln)
|
|
269
|
+
if m and not re.search(r"\bfn\b", ln):
|
|
270
|
+
var = m.group(1)
|
|
271
|
+
out.append(_block("begin_commit", i, until(i, re.compile(rf"\b{re.escape(var)}\s*\.\s*commit\(\)"), var), lines, lang, funcs,
|
|
272
|
+
tx_var=var, head=ln))
|
|
273
|
+
continue
|
|
274
|
+
m = RS_CLOSURE.search(ln)
|
|
275
|
+
if m:
|
|
276
|
+
k, col = i, strip_strings(ln).find("{", m.end())
|
|
277
|
+
while col < 0 and k + 1 < len(lines) and k < i + 3:
|
|
278
|
+
k += 1
|
|
279
|
+
col = strip_strings(lines[k]).find("{")
|
|
280
|
+
end = match_brace(lines, k, col) if col >= 0 else None
|
|
281
|
+
if end is not None:
|
|
282
|
+
out.append(_block("closure", i, end, lines, lang, funcs, tx_var=m.group(1), head=ln))
|
|
283
|
+
elif lang in ("typescript", "javascript"):
|
|
284
|
+
m = TS_CLOSURE.search(ln)
|
|
285
|
+
if m:
|
|
286
|
+
col = strip_strings(ln).find("{", m.end())
|
|
287
|
+
end = match_brace(lines, i, col) if col >= 0 else None
|
|
288
|
+
if end is not None:
|
|
289
|
+
out.append(_block("closure", i, end, lines, lang, funcs, tx_var=m.group(1) or m.group(2) or "", head=ln))
|
|
290
|
+
continue
|
|
291
|
+
if TS_ARRAY.search(ln):
|
|
292
|
+
col = strip_strings(ln).find("[")
|
|
293
|
+
end = match_brace(lines, i, col, "[", "]")
|
|
294
|
+
if end is not None:
|
|
295
|
+
out.append(_block("closure", i, end, lines, lang, funcs, head=ln))
|
|
296
|
+
continue
|
|
297
|
+
if TS_BEGIN.search(ln):
|
|
298
|
+
out.append(_block("begin_commit", i, until(i, TS_COMMIT), lines, lang, funcs, head=ln))
|
|
299
|
+
elif lang in ("java", "kotlin"):
|
|
300
|
+
m = JAVA_ANN.match(ln)
|
|
301
|
+
if m and not re.search(r"\b(?:class|interface)\b", " ".join(lines[i + 1:i + 3])):
|
|
302
|
+
for k in range(i + 1, min(len(lines), i + 8)):
|
|
303
|
+
f = next((x for x in funcs if x["start"] == k), None)
|
|
304
|
+
if f:
|
|
305
|
+
b = _block("annotation", k, f["end"], lines, lang, funcs, head=ln)
|
|
306
|
+
if m.group(1) and "readOnly = true" in m.group(1).replace(" ", " "):
|
|
307
|
+
b["read_only"] = True
|
|
308
|
+
out.append(b)
|
|
309
|
+
break
|
|
310
|
+
continue
|
|
311
|
+
if JAVA_TEMPLATE.search(ln):
|
|
312
|
+
col = strip_strings(ln).find("{")
|
|
313
|
+
end = match_brace(lines, i, col) if col >= 0 else None
|
|
314
|
+
if end is not None:
|
|
315
|
+
out.append(_block("closure", i, end, lines, lang, funcs, head=ln))
|
|
316
|
+
continue
|
|
317
|
+
if JAVA_BEGIN.search(ln):
|
|
318
|
+
out.append(_block("begin_commit", i, until(i, JAVA_COMMIT), lines, lang, funcs, head=ln))
|
|
319
|
+
# nested duplicates (a with-block inside an annotated function): keep both, the inner is the narrower shape
|
|
320
|
+
seen, uniq = set(), []
|
|
321
|
+
for b in out:
|
|
322
|
+
key = (b["line"], b["end_line"])
|
|
323
|
+
if key not in seen:
|
|
324
|
+
seen.add(key)
|
|
325
|
+
uniq.append(b)
|
|
326
|
+
return uniq
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def block_calls(text: str, lang: str, block: dict) -> list[dict]:
|
|
330
|
+
"""External work inside a block: on its own lines, or one call away in a function of the same file."""
|
|
331
|
+
lines = text.splitlines()
|
|
332
|
+
a, b = block["line"] - 1, block["end_line"] - 1
|
|
333
|
+
found = calls_in(lines, a, b, lang)
|
|
334
|
+
funcs = {f["name"]: f for f in functions(lines, lang)}
|
|
335
|
+
own = enclosing(list(funcs.values()), a)
|
|
336
|
+
for i in range(a, min(b, len(lines) - 1) + 1):
|
|
337
|
+
for name in set(re.findall(r"\b(\w+)\s*\(", strip_strings(lines[i]))):
|
|
338
|
+
f = funcs.get(name)
|
|
339
|
+
if not f or (own and f["name"] == own["name"]) or name in CONTROL:
|
|
340
|
+
continue
|
|
341
|
+
inner = calls_in(lines, f["start"], f["end"], lang)
|
|
342
|
+
if inner:
|
|
343
|
+
found.append({"line": i + 1, "what": inner[0]["what"], "text": lines[i].strip()[:100], "via": name})
|
|
344
|
+
found.sort(key=lambda c: c["line"])
|
|
345
|
+
return found[:12]
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def callees(text: str, block: dict) -> list[dict]:
|
|
349
|
+
"""Calls inside a block that pass the transaction on (`repo.save(&mut tx, ..)`, `insert(tx, ..)`): [{line, name}]."""
|
|
350
|
+
var = block.get("tx_var") or ""
|
|
351
|
+
lines = text.splitlines()
|
|
352
|
+
out = []
|
|
353
|
+
for i in range(block["line"] - 1, min(block["end_line"], len(lines))):
|
|
354
|
+
ln = strip_strings(lines[i])
|
|
355
|
+
for m in re.finditer(r"\b(\w+)\s*\(([^()]*)", ln):
|
|
356
|
+
args = m.group(2)
|
|
357
|
+
if var and re.search(rf"(?:&mut\s+\*?|&|\*)?\b{re.escape(var)}\b", args) or re.search(r"&mut \*?(?:tx|txn|trx|transaction)\b", args):
|
|
358
|
+
if m.group(1) not in CONTROL and m.group(1) != var:
|
|
359
|
+
out.append({"line": i + 1, "name": m.group(1)})
|
|
360
|
+
return out
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def sqlite_opens(text: str, lang: str) -> list[dict]:
|
|
364
|
+
"""Where a SQLite database is opened, with the settings this file gives it: wal (True/False/None), busy timeout in
|
|
365
|
+
ms (None when not set), the transaction lock of a Go DSN (_txlock)."""
|
|
366
|
+
lines = text.splitlines()
|
|
367
|
+
wal = True if SQLITE_WAL.search(text) else (False if SQLITE_NOT_WAL.search(text) else None)
|
|
368
|
+
busy = None
|
|
369
|
+
m = SQLITE_BUSY.search(text)
|
|
370
|
+
if m:
|
|
371
|
+
g = list(m.groups()) # busy_timeout=, _busy_timeout=, _timeout=, secs|millis, its number, connect(timeout=s), timeout:
|
|
372
|
+
if g[5]: # sqlite3.connect(timeout=seconds)
|
|
373
|
+
busy = int(float(g[5]) * 1000)
|
|
374
|
+
elif g[3] and g[4]:
|
|
375
|
+
busy = int(g[4]) * (1000 if g[3] == "secs" else 1)
|
|
376
|
+
else:
|
|
377
|
+
val = next((x for x in (g[0], g[1], g[2], g[4], g[6]) if x), None)
|
|
378
|
+
busy = int(val) if val else None
|
|
379
|
+
txlock = re.search(r"_txlock=(\w+)", text)
|
|
380
|
+
out = []
|
|
381
|
+
com = COMMENT.get(lang, COMMENT["default"])
|
|
382
|
+
for i, ln in enumerate(lines):
|
|
383
|
+
if com.match(ln) or not SQLITE_OPEN.search(ln):
|
|
384
|
+
continue
|
|
385
|
+
default_timeout = 5000 if lang == "python" and "sqlite3.connect(" in ln and busy is None else None
|
|
386
|
+
out.append({"line": i + 1, "wal": wal, "busy_timeout_ms": busy if busy is not None else default_timeout,
|
|
387
|
+
"busy_basis": "set in this file" if busy is not None else ("Python sqlite3 default (5 s)" if default_timeout else "not set (0)"),
|
|
388
|
+
"txlock": txlock.group(1).lower() if txlock else "", "text": ln.strip()[:100]})
|
|
389
|
+
return out
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def orm_rmw(text: str, lang: str) -> list[dict]:
|
|
393
|
+
"""Python ORM read-modify-write: an object read, a field changed from its own value, saved; no select_for_update and
|
|
394
|
+
no F() expression in the function."""
|
|
395
|
+
if lang != "python" or ".save(" not in text:
|
|
396
|
+
return []
|
|
397
|
+
lines = text.splitlines()
|
|
398
|
+
out = []
|
|
399
|
+
for f in functions(lines, lang):
|
|
400
|
+
body = lines[f["start"]:f["end"] + 1]
|
|
401
|
+
joined = "\n".join(body)
|
|
402
|
+
if PY_SFU.search(joined):
|
|
403
|
+
continue
|
|
404
|
+
got = {}
|
|
405
|
+
for k, ln in enumerate(body):
|
|
406
|
+
m = PY_GET.match(ln)
|
|
407
|
+
if m:
|
|
408
|
+
got[m.group(1)] = (k, m.group(2))
|
|
409
|
+
continue
|
|
410
|
+
m = PY_INC.match(ln)
|
|
411
|
+
if m and m.group(1) in got:
|
|
412
|
+
var, field = m.group(1), m.group(2)
|
|
413
|
+
save = next((j for j in range(k + 1, len(body)) if (s := PY_SAVE.match(body[j])) and s.group(1) == var), None)
|
|
414
|
+
if save is not None:
|
|
415
|
+
out.append({"line": f["start"] + got[var][0] + 1, "end_line": f["start"] + save + 1, "symbol": f["name"],
|
|
416
|
+
"model": got[var][1].split(".")[-1], "field": field, "var": var, "inc_line": f["start"] + k + 1})
|
|
417
|
+
got.pop(var, None)
|
|
418
|
+
return out
|