8000 GitHub - trainiac-hq/samey: Finds code that's already been written, so nobody writes it twice. TypeScript and Gleam. · GitHub
[go: up one dir, main page]

Skip to content
trainiac-hqPublic

About

Finds code that's already been written, so nobody writes it twice. TypeScript and Gleam.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

samey

samey finds code that's already been written, so nobody writes it twice, and code that nothing uses. It reads TypeScript, JavaScript and Gleam.

It's made for coding agents, which often write a helper that's already there because they haven't seen it. Run it when you lint. It says where the copies are, which one to keep and what to import instead. It only fails on what's new, so you can start using it on code that already repeats itself.

$ samey
82c05baf  The same function, but for the names of locals: 2 copies of 5 lines
  src/lib/money.ts:2  price  (keep this one: it was there first)
  src/pages/Receipt.tsx:3  formatMoney  (new; import {price} from '../lib/money.ts')
  Import it and delete the new one.

56ef957b  The same expression, but for the names of locals: 2 copies of 4 lines
  server/src/shop/report.gleam:8  in weekly  (new; import shop/stock, then stock.low)
  server/src/shop/stock.gleam:6  in low  (keep this one: it was there first)
  low does this already. Call it in the new one instead.

2 things to merge. Read 6 files in 0.1 s.
If copies are meant to be there, say where and why in samey.config.json's exceptions.

How to use it

You need Bun 1.4.5 or newer. samey isn't on npm yet, so add it from GitHub:

bun add -d github:trainiac-hq/samey

Then run it after your linter:

"scripts": {
	"lint": "bun lint && samey"
}
Command What it does
samey [paths] Says what's been copied since the baseline
samey --since origin/master Does the same for what your branch changed, compared with everything
samey list [paths] Says everything that's been copied, new or not
samey find src/price.ts:12 Says whether there's anything like what's on that line
samey find - --as src/new.ts Says whether there's anything like the code on stdin
samey accept Writes the baseline the first time
samey accept --prune Takes what's been fixed out of the baseline
samey dead [paths] Says what nothing uses

Add --json to get JSON, and --time to see where the time went. samey exits with 0 when there's nothing to do, 1 when there's something to do and 2 when it couldn't look, for example because a file doesn't parse.

For agents

You need three commands.

Before you write a helper, ask if it's there

Give samey find a draft, and say which file it's for. The draft doesn't have to be right, finished or imported from anywhere, as long as it parses:

$ samey find - --as src/pages/Refund.ts < draft.ts
src/lib/money.ts:2  price  (the same as lines 1 to 5 but for the names of locals; import {price} from '../lib/money.ts')
src/pages/Receipt.tsx:3  formatMoney  (the same as lines 1 to 5 but for the names of locals; it isn't exported)

The lines are the draft's. When there's nothing it says Nothing like it. You can also ask about code that's there already, with samey find src/pages/Receipt.tsx:5.

When you've written something, run samey

It exits with 1 when you've written something that was there, and says what to use instead of it:

$ samey
82c05baf  The same function, but for the names of locals: 2 copies of 5 lines
  src/lib/money.ts:2  price  (keep this one: it was there first)
  src/pages/Receipt.tsx:3  formatMoney  (new; import {price} from '../lib/money.ts')
  Import it and delete the new one.

1 thing to merge. Read 6 files in 0.0 s.
If copies are meant to be there, say where and why in samey.config.json's exceptions.

samey --since origin/master only says what your branch has added.

When you've merged copies it knew about, take them off the list

Copies that were there before anyone started using samey are in its baseline. When you merge some, samey asks you to take them out of it:

$ samey
82c05baf  These aren't copies any more
  src/lib/money.ts  price
  src/pages/Receipt.tsx  formatMoney

samey.baseline.json is out of date: run `samey accept --prune` and commit it.

Nothing new, 1 known already. Read 6 files in 0.0 s.

$ samey accept --prune
samey.baseline.json had 2 and now has 1.

Nothing is ever added to the baseline, so don't try. There's no comment that turns samey off either. If two copies have to be there, write an exception that says why.

You could put this in your AGENTS.md:

The lint step runs samey, which fails on code that's already been written and says
what to use instead. Before you write a helper, ask `samey find - --as <file>` with
a draft on stdin. After merging copies it knew about, run `samey accept --prune`.

What it finds

samey compares syntax trees. Comments and formatting make no difference. Nor do the names of locals, as long as they're renamed consistently.

It finds whole functions, classes, types and constants. It also finds statements in a row, expressions, elements of a list or of JSX, arms of a match, and the steps of a pipeline or a chain of calls. There are three kinds:

  • The same code.
  • The same code once local names are changed.
  • Nearly the same code. The copies differ in a few literals or names from outside, and it says which.

It reports the biggest copy and leaves out its pieces. To decide which to keep it goes by what's exported and used, then by which module imports the least. In Gleam it sends a function to the module its type is in, and knows when two modules can't import each other. It writes imports as your files do, with import or require.

It takes these to be the same:

  • In both languages, functions that say they return something else.
  • In Gleam, a |> f(b) and f(a, b), use and the callback it stands for, f(_, b) and the function it stands for, short labels and long ones, labels in another order when the order can't matter, and names with their module and without it.
  • In TypeScript and JavaScript, function and arrow functions, an arrow with a body that only returns and one without, optional braces and brackets, quotes, short properties, const and let, an interface and the same type, and the same thing by another name, whichever way it's imported.

It doesn't do that with these:

  • if and a ternary, or a loop and map.
  • Arguments without labels, or properties, in another order.
  • A literal in one and a local in the other.
  • In Gleam, an argument with its label and one without.
  • Code with something extra in the middle of it. That counts as two pieces.
  • Code in different languages.

What it leaves alone

Merging code has a price, so samey works out how much shorter the code would be afterwards. It counts what would have to be passed and returned, the import, and whether the copies are in packages that import each other. It only says something when enough is saved. It leaves out copies that can't be made into a function because they return early or assign to something around them.

Tests are free to repeat themselves. In what a test does, samey only looks for long runs of set-up. Helpers and fixtures that tests share count like any other code, and so does a test that's there twice.

It doesn't read generated or squeezed files, declaration files, config files, or what's in a folder called examples, fixtures, migrations or the like. It reads the files git has, and new ones that git doesn't ignore.

In TypeScript and JavaScript, something that changes is a different thing in each module, however alike the code that makes it is. A list of listeners is one. So code that uses it isn't the same either.

An app with a lockfile of its own has its own copies of what it installs, and a hook that gets another app's React breaks. So samey doesn't tell such apps to import from each other what uses an installed package.

The rules are in src/worth.ts. We picked them by reading findings by hand, in TypeScript and Gleam, from about twenty public repositories. Then we read some from repositories that the rules hadn't been tried on:

Repositories Findings We'd merge Arguable No
Two, in TypeScript and Gleam 40 32 6 2
axios, eslint, express and mocha, which are the JavaScript ones we tried 74 60 13 1

Most of the arguable ones in JavaScript are axios's smoke tests, which are there once for each kind of module on purpose.

What nothing uses

samey dead starts from what's run, follows every name from there, and says what it never came to:

$ samey dead
packages/old  nothing uses it (212 lines)
packages/lib/src/lib/price.gleam:14  rounded  nothing uses it (6 lines)
server/src/shop/report.gleam:40  with_clock  only tests use it (3 lines)
src/lib/money.ts:9  Currency  only its own file uses it, so it needn't be exported
server/gleam.toml  birl  nothing uses it
src/dev/package.json  left-pad  nothing uses it

Nothing uses 4, only tests use 1 and only its own file uses 1. The first two are 221 lines. Read 6 files.
If something outside of the code uses one, say what in samey.config.json's used.

A compiler or a linter sees one file or one package, so anything that's exported looks used to it. samey sees the whole repository. Two functions that only use each other are dead, and so is a package that's a dependency of another which never imports it. It tells you about:

  • packages, files, functions, types and constants that nothing uses, or only tests
  • what's exported, or public in Gleam, that only its own file uses
  • what a package.json or a gleam.toml lists that nothing needs, and what's a dependency in a gleam.toml that only tests use

These are where it starts from:

  • In Gleam, every public main, and the functions of tests that end in _test.
  • In TypeScript and JavaScript, tests, files with a #!, with import.meta.main, or with a comment that says how to run them, and what a package.json names.
  • Files that any other file names by their path: HTML, YAML, a shell script, or a command in Markdown.
  • Gleam functions that Erlang or a shell script calls.
  • Code that samey doesn't read for copies, such as config files and generated ones.

When a package isn't private, all that it gives is used. In Gleam that goes for a repository's only package when nothing in it is run.

What's only there for tests can say so, with @internal: the attribute in Gleam, and in a comment in TypeScript.

What something else starts, such as a framework that makes a page of each file, goes in the config.

The baseline

samey accept writes what's there now to samey.baseline.json, which you commit. From then on samey fails on anything that isn't in it. It has a line for each finding:

{"id":"82c05baf","size":45,"copies":["src/lib/money.ts#price","src/pages/Receipt.tsx#formatMoney"]}

The list only gets shorter. When you fix something, samey fails until its entry has gone too, and samey accept --prune takes it out. accept won't add anything to a baseline, or make one again that's committed and has been deleted. samey also fails if someone adds to it by hand. Only another version of samey, which may find more, can make it again.

An entry has no line numbers, so it stays the same when code moves around a file. If you edit one of two copies and part of them is still the same, samey says so, because the other may need the same fix. If you edit both in the same way, they're still known, unless they've grown. Then samey fails, because having to write the same thing twice is the time to merge them.

Config

You may not need any. If you do, put a samey.config.json at the top of the repository:

{
	"ignore": ["tools/vendored"],
	"saving": 20,
	"exceptions": [
		{
			"copies": ["src/price.ts#round", "src/legacy/price.ts#round"],
			"reason": "The old one is frozen until the last shop has moved"
		}
	],
	"used": [
		{"files": ["src/pages/**"], "by": "The router makes a page of each"},
		{"files": ["package.json"], "names": ["react-dom"], "by": "The router needs it"}
	]
}
  • ignore is a list of paths or globs to leave out.

  • saving is how many nodes of the tree fewer there have to be before samey says something. It's 20 unless you change it.

  • exceptions are copies that are meant to be there. copies are paths or globs, with #name for one definition in a file. An exception covers a finding when every copy is in one of them and each of them has a copy.

  • used is for samey dead. It's what something outside of the code uses: all that some files give, or only these names in them. A name can also be a package that a package.json or a gleam.toml lists.

Every exception needs a reason, and one that covers nothing any more is an error. There are no comments that turn samey off, because they'd be copied along with the code. The config is JSON so that a program can read and change it without running it.

How fast it is

These are the medians of 7 runs on 27 November 2026, with Bun 1.4.6 on an M4 Max with 16 cores and 48 GB, while other work kept more than half of it busy. They're for the whole process. Nothing is kept from before on the first run. The files and lines are the ones it reads.

Repository Files Lines First run After that
A private one in TypeScript and Gleam 1,063 280,000 0.43 s 0.16 s
arc (Gleam, JavaScript) 385 211,000 0.47 s 0.23 s
trpc 754 142,000 0.28 s 0.14 s
eslint 842 460,000 0.46 s 0.26 s
outline 2,480 401,000 0.55 s 0.27 s
tldraw 2,351 486,000 0.78 s 0.41 s

When one file has changed, the private one takes 0.19 s.

Trees are hashed as they're made. Files that have changed are parsed by workers, each of which reads only one language. What was parsed is kept in your cache folder by what was in the file, so all of a repository's worktrees share it. A file whose size and time haven't changed isn't opened. Set SAMEY_CACHE to keep it somewhere else.

When nothing has changed, about a third of the time goes on gathering code that could be a copy and another third on comparing it. Both are done again on every run. The rest is starting up, listing files with git and reading what was kept.

Parsers

For TypeScript we use oxc. All of these read every one of 618 files:

Parser Time Installed size
oxc 146 ms 5.6 MB
TypeScript 6 126 to 194 ms 24 MB
Babel 216 to 291 ms 0.6 MB

oxc and TypeScript are as fast as each other and oxc is much smaller. TypeScript 7 has no parser that JavaScript can call.

For Gleam we wrote a parser, in src/languages/gleam. On 397 files:

Parser Time Installed size
Ours 55 to 71 ms None
glance, which is in Gleam, built for JavaScript 740 to 816 ms 0.5 MB
tree-sitter-gleam, built for wasm 1,225 ms 4.5 MB

Ours agrees with glance, down to the positions, on all of 1,578 files. They include the Gleam compiler's own tests. bun scripts/agree.ts <folder> checks that, which is all that glance is here for.

Both languages become the same small tree of branches, locals, names from outside and literals. Everything after that is one engine.

What others don't do

jscpd, PMD's CPD, fallow and similarity-ts are good at finding copies. When we looked, none of them read Gleam. samey says which copy to keep, what to import and what a shared function would take, and it checks that locals are renamed consistently rather than ignoring names.

Limits

  • It doesn't know types. In Gleam it won't merge code whose parameters say they have different types, but in TypeScript it can suggest a function that has to be generic.
  • It compares long strings whole, so two nearly identical SQL queries are two different strings.
  • It doesn't read Flow, or code inside Vue, Svelte or Markdown files. Any other file it can't parse makes it fail, so ignore those.
  • It looks at one repository at a time.

Working on it

bun install
bun test
bun check
bun lint

bun test/glance/build.ts builds glance again, which needs Gleam.

Change the version in package.json when you change what samey finds. Baselines can only be made again by another version.

Licence

MIT

About

Finds code that's already been written, so nobody writes it twice. TypeScript and Gleam.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0