Commit Graph
150 Commits
Author SHA1 Message Date
Micha Reiser 32669b2743 [ty] Add project-manager.project configuration (#30568)
## Summary

Adds a new `project-manager.project = "uv" | "none"` configuration
setting, similar to the existing script setting, so that users can
opt-in without relying on `TY_UV`.


This PR does not implement the `auto`, that would derive the project
manager from the project layout. It's something we can add later. It
also doesn't add support for `project-mode = "sync" | "metadata"`.
Again, this is something we can do later. For now, `project-mode` is
always `metadata`.

Closes https://github.com/astral-sh/ty/issues/5067.

Testing: CLI, project, server, and file-watching tests passed.
2026-11-24 08:49:14 +00:00
Micha Reiser 85a318c426 Escape diagnostic messages and paths in GitHub Actions and Azure Pipelines output (#30831)
## Summary

Today, a line break in a diagnostic message ends the annotation in
GitHub Actions and Azure Pipelines. For example, an [invalid
`requires-python` value and the caret pointing to
it](https://github.com/astral-sh/ruff/pull/29768#discussion_r4665837003)
appear on separate log lines outside the annotation. A comma in a
filename can also truncate the path in GitHub Actions.

This PR updates Ruff and ty to escape line breaks and percent signs in
diagnostic messages and command properties. It also escapes delimiters
in property values such as file paths, following the rules in the
[GitHub Actions
toolkit](https://github.com/actions/toolkit/blob/0c3a9c332b678ff1e776f93d728a4ad279803abe/packages/core/src/command.ts#L103-L117)
and [Azure Pipelines task
library](https://github.com/microsoft/azure-pipelines-task-lib/blob/43673c958dc5fb40b898c5c7b5b7b5bf0ebd14bd/node/taskcommand.ts#L93-L110).
This keeps the full message in one annotation and preserves literal text
like `%0A`.

## Notes to reviewers

Escaping adds about 14–27 ns per short diagnostic in a local rendering
benchmark. I measured median wall time in ns per diagnostic over 24 runs
per variant in alternating order on an M5 Max with the profiling
profile. Each run rendered 2,048 prebuilt diagnostics into a reusable
string 64 times, excluding analysis and I/O.

| Message | GitHub main | GitHub PR | Azure main | Azure PR |
|---|---:|---:|---:|---:|
| Short | 147 | 174 | 68 | 82 |
| Headline and primary label | 157 | 185 | 78 | 93 |
| Long (492 bytes) | 152 | 183 | 73 | 93 |
| Multiline with literal `%0A` | 156 | 223 | 70 | 124 |

The renderer tests, full Ruff and ty CLI test suites, and Clippy passed
locally.
2026-11-23 15:49:50 +01:00
Micha Reiser 065e0a21de [ty] Rename ignore-comment-unknown-rule to unknown-rule-in-ignore-comment (#30827)
## Summary

Rename `ignore-comment-unknown-rule` to `unknown-rule-in-ignore-comment`
to match `renamed-rule-in-ignore-comment` and Ruff's ignore rules (and
make it easier to read).

The old name still works in configuration and ignore comments. Use `ty
check --fix` to update ignore comments automatically.

The focused CLI, IDE, and suppression tests passed.
2026-11-23 13:12:29 +01:00
Micha Reiser 981d44c9cb [ty] Rename uv-metadata diagnostic to project-manager and improve its wording (#30528)
## Summary

This does some polishing on the former `uv-metadata` diagnostic:


### Rename 
It renames the diagnostic from `uv-metadata` to `project-manager`. This
is to make it less uv focused (we could support other project managers)
and also make it less technical. `uv-metadata` is an implementation
detail. For as far as users are concerned, ty failed to run the project
manager to set up the Python environment or to load the project
metadata.

**Before**

```
warning[uv-metadata]: uv 0.12.2 is too old; upgrade `./old-uv` to uv 0.12.3 or newer
--> pyproject.toml:1:1

Found 1 diagnostic
```

**After**

```
warning[project-manager]: Failed to load project metadata from uv: Found uv 0.12.2, but uv 0.12.3 or newer is required
--> pyproject.toml:1:1
help: Upgrade `./old-uv` to uv 0.12.3 or newer

Found 1 diagnostic
```

### Setting subdiagnostic

We now also attach a sub diagnostic that explains why ty uses the
project manager when ty failed to find a supported uv version. This will
become more important once we make the uv integration for scripts opt
out.

**Before**

```
error[uv-metadata]: Failed to invoke `uv workspace metadata`: failed to resolve uv executable: cannot find binary path
--> script.py:2:1

Found 1 diagnostic
```

**After**

```
error[project-manager]: Setting up the Python environment with uv failed: could not find `uv` on `PATH`
--> script.py:2:1
info: ty uses uv to install this script's dependencies because `project-manager.script` is set to `"uv"`
 --> script.py:5:28
  |
5 | # project-manager.script = "uv"
  |                            ^^^^ configured here
info: To install uv, see https://docs.astral.sh/uv/

Found 1 diagnostic
```


### uv error message

I changed how we show uv's error message when it fails to resolve
dependencies:



**Before**

```
error[uv-metadata]: `uv workspace metadata` failed with `exit status: 1`
--> script.py:2:1
info: No solution found when resolving dependencies
  cause: Because missing-script-dependency was not found in the cache and you require missing-script-dependency==99.0.0, we can conclude that your requirements are unsatisfiable.

hint: Packages were unavailable because the network was disabled. When the network is disabled, registry packages may only be read from the cache.

Found 1 diagnostic
```

**After**

```
error[project-manager]: Setting up the Python environment with uv failed
--> script.py:2:1
error: No solution found when resolving dependencies
  cause: Because missing-script-dependency was not found in the cache and you require missing-script-dependency==99.0.0, we can conclude that your requirements are unsatisfiable.

hint: Packages were unavailable because the network was disabled. When the network is disabled, registry packages may only be read from the cache.
error: `uv workspace metadata` exited with status 1

Found 1 diagnostic
```

I don't love it, but formatting this one is a bit tricky, because uv
doesn't provide us with structured output and we need to preserve any
whitespace as is, to not mess up uv provided code frames.

And concise

```
script.py:2:1: error[project-manager] Setting up the Python environment with uv failed: No solution found when resolving dependencies
Found 1 diagnostic
```



## Notes to reviewers

Stacked on #30527.

Verified the diagnostics in full and concise CLI output and in the
language server.
2026-11-19 12:46:15 +00:00
Micha Reiser b6d8e21241 [ty] Add project-manager.script = "uv" (#30489)
## Summary

This PR adds a new `project-manager` table:

```toml
[project-manager]
project = "uv" | "auto" | "none"
project-mode = "sync" | "metadata"
script = "uv" | "none"
```

This PR only implements the script part, but I listed all options to
outline where we want to go with this in the future.

`script = "uv"` opts in to installing PEP 723 script dependencies with
uv (to reduce the need for `TY_UV`). For now, `project-manager.script`
defaults to `"none"`, but I plan to change this to `"uv"` in the near
future. The new option follows the same configuration precedence as
other script settings:

* A script with its own `tool.ty` section uses the value from its own
table to control whether it uses uv to sync its dependencies or not.
* Scripts without a `tool.ty` section use the project level
`project-manager.script`

For now, overriding the setting based on file patterns isn't supported
(I have no strong reason against it, it's mainly to cut scope).

`TY_UV` takes precedence over any setting in the configuration (similar
to other CLI options that support environment variables).

The recommended way to check untrusted code is to set `TY_UV=off`, which
overrides `project-manager.script`.

For now, we keep supporting `experimental.useUv` for scripts, but the
in-editor `configuration.project-manager.script` takes precedence over
`experimental.useUv`.

## Why is the setting not under `environment.

For projects, setting `project-manager.project = "metadata"` also
changes how we discover the project (we prefer the workspace over the
closest ty project), and `metadata` doesn't initialize the Python
environment.

## LSP watch mode

Changing `project-manager.script` at the project level requires saving
any open script (or closing and reopening) for the sync to start. This
simplified the implementation a fair bit and seems an okay trade off.
2026-11-18 12:42:42 +01:00
Micha Reiser 86f020e0e8 [ty] Resolve script file settings independently of uv (#30407)
## Summary

Today, ty suspends workspace diagnostics when a script's initial
synchronization is running. The (incorrect) documented reason for this
is that it prevents resolving the script's uv environment when checking
a file `a.py` that imports `script.py` (ty would then follow the import
and resolve its file settings).

Now, the concern here is valid, but the problem isn't specific to
workspace diagnostics. The same problem exists when using pull
diagnostics: The client can request diagnostics for `a.py` (or any file
using `a.py`), which then results in type checking `script.py`, which in
turn resolves its `file_settings`.

This PR decouples `file_settings` from the `script` query that returns a
resolved `Script` with its uv environment. Instead, `file_settings` now
uses the new `script_metadata` query that caches the script's parsed
`tool.ty` table.


This PR also changes that scripts stop validating the `[tool.ty.src]`
and `[[tool.ty.overrides]]` tables. They're unused, and we should not
skip checking a script because there's a semantic error in either of
them. Instead, we should report a warning that these tables are useless
(not part of this PR, but documented).

## Test plan

The project and CLI tests pass.
2026-11-17 16:06:41 +01:00
Alex Waygood 4357fa3666 [ty] Split missing-module-member out of import-not-found (#30342) 2026-11-16 13:52:25 +00:00
Alex Waygood ab1a1265b8 [ty] Avoid spurious syntax warnings when applying fixes (#30404) 2026-11-13 11:11:12 +00:00
Alex WaygoodandMicha Reiser 22e77392fb [ty] Split invalid-return-type into 3 focussed rules; rename empty-body and unsound-return (#29947)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-11-11 16:59:57 +00:00
Micha Reiser 0850829d2c [ty] Explain why a rule was removed in configuration and ignore comments (#30128)
## Summary

ty reports an `unknown-rule` or `unknown-rule-in-ignore-comment`
diagnostic when a user uses a removed rule.

This PR carries forward the removal reason and shows it in the
diagnostic's info text.

We may also want to have a separate `removed-rule` and
`removed-rule-in-ignore-comment` diagnostics, but that's a separate
change, and not something that we need to change now.


## Test Plan

Added CLI coverage for both warnings and verified their full and concise
output.
2026-11-09 08:31:59 +01:00
Alex WaygoodandBrent Westbrook ce0077c3e5 [ty] Distinguish attributes missing from some union members (#29944)
## Summary

Users can now suppress an attribute error that affects only some union
members and still catch names that are missing from every member. For
example, both lines below previously reported `unresolved-attribute`:

```python
def clean(value: str | int) -> str:
    value.stirp()          # missing-attribute: neither str nor int has stirp
    return value.strip()   # missing-union-attribute: str has strip, int does not
```

The motivation is that a project adopting ty may want `value.strip()` on
`str | None` to only warn while a typo remains an error-severity
diagnostic.

Both rules default to errors. The same distinction applies to optional
values such as `str | None` and to attribute deletion. Attributes
defined only conditionally on a class continue to use
`possibly-missing-attribute`.

### Comparison to other type checkers

Pyright distinguishes between `reportOptionalMemberAccess` (which is
specifically for unions with `None`) and `reportAttributeAccessIssue`,
which is for all other unions. mypy, meanwhile, distinguishes between
`union-attr` (which is an error code for all attribute-access errors on
union types) and `attr-defined` (which is an error code for all
attribute-access errors on non-union types). So this new split doesn't
_exactly_ align with either precedent -- but I _do_ think it's probably
the most useful split we can do, and it's the one that makes the most
sense _a priori_ in my opinion.

### Compatibility

`unresolved-attribute` remains an alias for `missing-attribute` in
configuration and inline ignores. To preserve a setting such as
`unresolved-attribute = "warn"` for both cases, also set
`missing-union-attribute = "warn"`. On an access that fails for only
some union members, replace `# ty: ignore[unresolved-attribute]` with `#
ty: ignore[missing-union-attribute]`. Tools that consume diagnostic
codes should recognize both new names.

Fixes astral-sh/ty#2839 and fixes astral-sh/ty#2471.

## Test Plan

A comparison with ty 0.0.96 on typeshed-stats, docstring-adder,
sphinx-lint, and typing_extensions found the same messages, locations,
and severities. Eight diagnostics received `missing-union-attribute`
across those four projects (two in sphinx-lint and six in
typing_extensions).

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-11-06 14:46:50 -05:00
Charlie Marsh 926ccc883c [ty] Handle output errors when generating shell completions (#29997)
## Summary

Piping shell completions into a command that stops reading early can
make ty panic. I reproduced this on Linux with ty 0.0.96 and `main`.

```bash
set -o pipefail
ty generate-shell-completion fish | head -n 1
echo "$?"  # 101 before this change, 0 after
```

The completion generator panics if its writer returns an error. We now
generate the script in memory and write it to stdout ourselves. This
lets ty handle a broken pipe normally and report other write failures,
such as a full filesystem.

The CLI regression test closes the read end of a pipe before starting ty
so the result is independent of scheduling.
2026-11-05 11:34:04 -05:00
Alex Waygood c86652abce [ty] Skip active Conda and Pixi environments during discovery if the environment doesn't contain Python (#30066) 2026-11-05 15:58:48 +00:00
Micha Reiser 64989ec2a4 [ty] Report invalid module globs once per override pattern (#30031)
## Summary

Before, a glob error in `analysis` was repeated for every
`overrides.analysis` that did not override this setting.

This PR validates the glob once. We only report invalid globs in
`[overrides.analysis]` that are specific to this `override`


## Test Plan

Added CLI regression coverage and ran the CLI suite.
2026-11-05 15:56:00 +01:00
Micha Reiser af4725acbd [ty] Preserve baseline matches when a rule is renamed (#30040) 2026-11-05 08:34:57 +00:00
Micha Reiser 48b1255e06 [ty] Avoid duplicate warnings for unknown rules and override sections (#30028)
## Summary

An unknown or renamed rule in `[rules]` could produce the same warning
for every override that inherited it. An unnecessary or empty
`[[overrides]]` section could also warn again for each script using the
same configuration.

ty now checks the options from each configuration source separately. A
warning points to the place that needs editing, and the same typo
written in two places gets a diagnostic at each.


## Test Plan

Added CLI regression coverage and ran the project, script, and editor
configuration tests.
2026-11-04 17:07:54 +00:00
Micha Reiser a2eec37a87 [ty] Warn when configuration uses a renamed rule (#30024)
## Summary

When configuration uses a renamed rule, ty reports the old and current
names and continues checking with the configured level. For example,
`unresolved-import = "ignore"` still suppresses missing imports and now
points to `import-not-found` as the replacement. In a configuration
file, the warning highlights the old rule name.

Builds on #30026.

## Test Plan

Ran the CLI, project, and editor configuration tests, including coverage
for rule overrides and standalone scripts.
2026-11-04 17:07:53 +00:00
Micha Reiser 27452ba5b0 [ty] Don't fail configuration deserialization on conflicting rule names (#30023)
## Summary

A configuration that sets different levels for the rule and its alias
(e.g. `unresolved-import` and `import-not-found`) currently fails to
deserialize. This PR removes the validation from the configuration
deserialization path because failing during deserialization:

* Means the LSP has to fallback to the default configuration, loosing
all other user configuration. This is certainly not what users wan.t
* ty stops config discovery if it finds an invalid `pyproject.toml`,
even if there's a higher precedence `ty.toml` (ty fails on a
configuration that it isn't even using)
* serde errors don't have the same nice code frames. E.g. the old
implementation underlined the entire rules table.


Instead, we should validate the settings when converting from options to
settings. This ensures:

* That we can recover in the LSP case
* It gives us nice code frames that point to the name in the rules
table.

However, I decided to remove the error altogether in favor of my stacked
PR that adds a warning when using a deprecated rule name. The reasoning
here is:

* I don't think we should show two warnings at the same location. 
* This aligns with how we handle misspelled rule names, which is also a
warning only (and is/was a long requested change on the ruff repository)
* It matches ruff's behavior
* I don't see much harm in running ty, especially because it also gives
much better recovery in the LSP.
* ty resolves overrides lazily when resolving the settings for a
specific files. At that point, it's too late to error if the main config
and the override use both the new and alias rule name
* There are cases where options appear as if they're from a single file
when they're not. E.g., VS Code merges user-level and workspace-level
configurations. For example,
  user-settings:
  ```json
  {
    "ty.configuration": {
      "rules": { "unresolved-import": "ignore" }
    }
  }
  ```
  workspace-settings:
  ```json
  {
    "ty.configuration": {
      "rules": { "import-not-found": "warn" },
      "environment": { "extra-paths": ["./stubs"] }
    }
  }
  ```
  are merged to:
  ```json
  {
    "rules": {
      "unresolved-import": "ignore",
      "import-not-found": "warn"
    },
    "environment": {
      "extra-paths": ["./stubs"]
    }
  }
  ```
It's now hard to make an argument what the user intention was, and
failing in this case seems overly strict to me.


The path taken in this PR is to, instead, give higher precedence to the
new rule name.
## Test Plan

Added CLI and editor regression coverage and ran the CLI, project, and
editor configuration tests.
2026-11-04 16:36:21 +00:00
Micha Reiser e501689d12 [ty] Inherit project settings and overrides for PEP 723 scripts (#29793)
## Summary

This changes how ty handles script options. Up to now, scripts never
inherited any settings from the project. I think this is overly
pedantic. While I consider script isolation important in terms of
dependencies, I don't think the same is true for type checking or linter
settings. The main motivation for not-inheriting project settings is
that scripts can be shared. Checking them in isolation ensures that
everyone gets a consistent experience. I don't think this is something
most users care about in terms of linting and type checking scripts. Our
own scripts are a good example. We have multiple scripts and we have no
intention to share them outside this project. In fact, we've found it
very annoying to repeat the same ty configuration in every script.

I also ran an experiment in https://github.com/astral-sh/ruff/pull/29768
to understand the ecosystem impact of using ty's current configuration
inheritance in Ruff. Without project inheritance, 17 of 38 scripts in
the seven projects sampled had diagnostics. Not only would this be a
very disruptive change. I also think that it's very reasonable that you
want to enforce the same standard to both regular python files as well
as scripts.

This PR changes how ty resolve script settings to:

* If a script has a `tool.ty` section, ignore the project's
configuration. Users who prefer the current behavior can restore it by
adding an empty `tool.ty` section to their script (or check their script
outside the project).
* If a script has no `tool.ty` section, inherit the project's
configuration. This is the main change.
* If a script has no `tool.ty` section, and the script matches an
`overrides` entry, inherit the project and override settings, like we do
for any other file. This allows users to extend the project
configuration (except for `environment` settings).

An explicit `--config-file` still overrides any settings specified in
the script. Matching file overrides from that config also apply.

A script's `requires-python` takes precedence over the project's Python
version. An inline `environment.python-version` takes precedence over
`requires-python`.


Fixes astral-sh/ty#4083 and addresses the [ignored file override
reported in
ty#4566](https://github.com/astral-sh/ty/issues/4566#issuecomment-5762949445).


## Considerations

The main downside of this change is that changing a script's
`environment.root` from `[]` to `["."]` implies opting out of the
project's config inheritance, because it requires adding a `tool.ty`
section. I don't have a good solution to this, other that we could
consider adding a `extend` configuration option in the future, that
allows explicitly inheriting from another configuration. Which is
something users have asked for before (for projects).


The other nuanced decision in this PR is that script's inherit a
project's `environment.extra-paths`. I think this is okay, given that
the main use case is to override e.g. typing stubs. But I could see an
argument that a script should not inherit any of the search path related
settings.

## Test Plan

All script CLI tests passed, including the uv integration tests.
2026-11-04 16:36:21 +00:00
Carl Meyer 03ed122646 [ty] Fix the empty VIRTUAL_ENV diagnostic snapshot (#29990)
The empty `VIRTUAL_ENV` test added in #29973 expects
`unresolved-import`, which #29960 renamed to `import-not-found`. This
updates the inline snapshot to match the diagnostic ty emits and fixes
the [failing CLI test on
main](https://github.com/astral-sh/ruff/actions/runs/41716499162/job/126198351930).
2026-11-03 21:56:34 +00:00
zaniebotandzaniebot 7c02bafe92 [ty] Ignore an empty VIRTUAL_ENV (#29973)
An empty `VIRTUAL_ENV` stops Python environment discovery before ty can
use a local `.venv` or active Conda environment. Treat the empty value
as unset, matching [uv’s environment
discovery](https://github.com/astral-sh/uv/blob/f5fde681577aadf322d056dc3c2b5330a8c0a002/crates/uv-python-discovery/src/virtualenv_discovery.rs#L8-L17).

Co-authored-by: zaniebot <242828183+zaniebot@users.noreply.github.com>
2026-11-03 14:52:00 -06:00
Alex Waygood 0471c14d1f [ty] Rename unresolved-import to import-not-found (#29960)
## Summary

ty currently reports `unresolved-import` for both a missing module and a
missing member in a `from` import. But the word "unresolved" is heavily
overloaded in Python, and has been reported by users as being confusing
(see https://github.com/astral-sh/ty/issues/2471). This PR renames the
rule to `import-not-found`, which describes the lookup failure in either
case.

Configuration, command-line flags, and ignore comments accept either
spelling. If several flags set this rule’s severity using different
spellings, the last flag wins. Existing baseline entries still match,
and rewriting a baseline uses the new name. Links to the old rule
heading still work.
2026-11-03 19:53:26 +00:00
Alex Waygood 91375d8550 Honor CLICOLOR=0 in Ruff and ty diagnostics (#29910) 2026-11-03 16:11:57 +00:00
Zsolt DollensteinandZsolt Dollenstein 82e55548e4 [ty] Warn on recoverable invalid globs (#29946)
Report `invalid-glob` as a warning when ty can continue type checking.
This includes invalid module globs in `allowed-unresolved-imports` or
`replace-imports-with-any` within an analysis override.

When an invalid glob prevents type checking, ty reports
`error[invalid-glob]`. A script’s top-level analysis settings are one
example.

---------

Co-authored-by: Zsolt Dollenstein <zsol@openai.com>
2026-11-03 14:47:43 +00:00
Alex Waygood 815c959e03 Give NO_COLOR precedence in Ruff and ty diagnostics (#29898)
## Summary

Today, if a CI job exports `FORCE_COLOR=1`, running `NO_COLOR=1 ruff
check .` still prints colored diagnostics. The same happens with `ty
check`. Giving a non-empty `NO_COLOR` priority lets users request plain
output without having to unset a variable inherited from their
environment. This matches how uv and the Python interpreter resolve that
conflict. Users who want color for one command can still pass
`--color=always`. [uv’s
resolver](https://github.com/astral-sh/uv/blob/39a02a0d9085f14dc3d5aa8655ac010a1fd377f8/crates/uv-cli/src/settings.rs#L172-L197)
· [Python’s color
precedence](https://docs.python.org/3/using/cmdline.html#controlling-color)

Previously, the shared resolver turned `FORCE_COLOR` into an override
before `colored` could honor `NO_COLOR`. The resolver now handles the
color environment for both tools, and `colored` styles diagnostics on
stdout according to that decision. The first matching rule wins.

1. Use an explicit `--color=always` or `--color=never`.
2. A non-empty `NO_COLOR` disables color.
3. A non-empty `FORCE_COLOR` or `CLICOLOR_FORCE` enables color,
including in a pipe.
4. If stdout is a pipe or file, disable color.
5. On a terminal, enable color if `CLICOLOR` is non-empty or `TERM` is
anything other than `dumb` (including unset).

All four color variables treat `0` as non-empty and an empty string as
unset. In particular, `FORCE_COLOR=""` previously disabled color. It now
lets the remaining settings and terminal detection decide.

## Comparison with the upstream conventions

- The [`NO_COLOR` convention](https://no-color.org/) specifies that a
non-empty value disables color by default and that command-line options
can override it. It gives no rule for a conflict with `FORCE_COLOR`. Its
FAQ also limits the convention to color, while Ruff and ty suppress
other diagnostic styling, such as bold text, when color is disabled.
- The [`FORCE_COLOR` convention](https://force-color.org/) specifies
that any non-empty value enables color, even in a pipe. Its example
applies `FORCE_COLOR` last, so the example produces colored output when
both variables are set. Here we follow uv and CPython in giving
`NO_COLOR` priority.
- The [CLICOLORS specification](https://bixense.com/clicolors/) gives
`NO_COLOR` priority over `CLICOLOR_FORCE` and makes `CLICOLOR` a
terminal-only request. We follow those rules, add `FORCE_COLOR` as an
alias for `CLICOLOR_FORCE`, and use `TERM=dumb` for the default the spec
leaves to applications.

## Comparison with uv

When `--color` is omitted, uv also checks non-empty `NO_COLOR` before
either force variable. In Ruff and ty, passing `--color=auto` has the
same effect as omitting it. In uv, passing it delegates the decision to
`anstream`, which recognizes `CLICOLOR_FORCE` but ignores `FORCE_COLOR`.

The terminal heuristics also differ: uv delegates to anstream, which
handles `TERM=dumb` differently depending on which platform uv is being
run on, and also honours the `CI` variable. I'd prefer not to have
platform-dependent behaviour or to have behaviour automatically be
different in CI; that feels too confusing/magical to me. [uv’s
resolver](https://github.com/astral-sh/uv/blob/39a02a0d9085f14dc3d5aa8655ac010a1fd377f8/crates/uv-cli/src/settings.rs#L172-L197)
· [`anstream`
detection](https://docs.rs/anstream/1.0.0/src/anstream/auto.rs.html#198-219)
· [`anstyle-query` environment
checks](https://docs.rs/anstyle-query/1.1.5/src/anstyle_query/lib.rs.html#23-82)

Each example assumes other color settings are unset.

| Case | Ruff and ty with this change | uv |
| --- | --- | --- |
| `FORCE_COLOR=1` with `--color=auto`, output piped | Colored, as when
the flag is omitted | Plain |
| `CLICOLOR=0 TERM=xterm`, on a terminal | Colored | Plain |
| `CLICOLOR="" TERM=dumb`, on a terminal | Plain | Colored |
| `CI=1 TERM=dumb`, on a terminal | Plain | Colored |
| `TERM` unset, on a terminal | Colored on all platforms | Plain on
non-Windows platforms, colored on Windows |

An empty `TERM` allows color on a terminal in both implementations.
2026-11-02 14:30:23 +00:00
Alex Waygood 4233a93546 [ty] Respect FORCE_COLOR in ty check (#29830) 2026-10-31 02:43:23 +00:00
Micha Reiser c618e8b138 [ty] Correctly handle line continuation when fixing unused ignore comments (#29781) 2026-10-27 20:24:49 -07:00
Micha Reiser 207ec3affe [ty] Add diagnostic baseline support (#27636) 2026-10-26 13:34:01 -07:00
Brent Westbrook 8334c5c57d [ty] Add support for SARIF output (#29635)
Summary
--

This PR fixes astral-sh/ty#2484 by moving our SARIF rendering from
`ruff_linter` into `ruff_db` and
wiring that up as an output format for ty.

The first commit introduces the metadata and makes some other
preparatory changes to the SARIF
emitter in Ruff. The second commit then moves the emitter to `ruff_db`
and removes the remaining
Ruff-specific calls. The third commit then wires that up to ty's CLI.

Test Plan
--

Existing tests, adapted to `ruff_db`, as well as a new ty CLI test
2026-10-23 14:57:03 -04:00
Brent Westbrook ef23c9c39e Update default and latest Python versions for 3.15 (#28792)
Summary
--

This PR updates our default Python version to 3.11, in line with 3.10
reaching [EOL] next month, and
updates our latest Python version to 3.15. I followed last year's PR
(#20725) to find everywhere
that needed to change. Fortunately there were not as many test changes
needed as last year's
deferred annotation issues.

I also updated the language classifier in our pyproject.toml.

[EOL]: https://devguide.python.org/versions/#supported-versions

Test Plan
--

Existing tests with updated snapshots. Most of the updates were to
snapshots for TC001, TC002, and
TC003, which now default to the lazy-import fix.

After updating the snapshots, I tried to make sure we still had coverage
for whatever changed. That
meant adding a few more mdtests for the TC rules, and one small mdtest
for RUF017 to restore
coverage for the `functools.reduce` fix.
2026-10-09 12:26:57 -04:00
Brent WestbrookandAlex Waygood 755d3aff4c Always show unsafe and display-only fixes in the CLI (#27810)
Summary
--

This is the CLI accompaniment to #27807. The main change here is showing
display-only fix diffs in
the CLI. However, display-only fixes don't have a corresponding flag
like `--unsafe-fixes`, and I
thought it would be weird to show them unconditionally when we don't do
the same for unsafe fixes,
so this PR also unconditionally renders unsafe fix diffs, even when that
flag isn't passed. We
already emit a note about the fix being unsafe, so I think it makes
sense always to show you the
fix, and make `--unsafe-fixes` enable actually applying the fix. We also
don't want to apply
display-only fixes, so enabling rendering of the fixes with
`--display-only-fixes` or similar would
also disagree with the semantics of the unsafe flag. I'm open to other
ideas here, though.

The sub-diagnostic for display-only fixes uses a higher severity than
the note for unsafe fixes and
renders in red, as shown below.

The change here also affects ty, which now has both unsafe and
display-only fixes.

I again checked what clippy and rustc do in these cases, and they don't
include any additional note or warning about the fix being unsafe:

<details><summary>Rust diagnostics</summary>
<p>

Here's a
[`clippy::needless_pass_by_value`](https://rust-lang.github.io/rust-clippy/rust-1.97.0/index.html#needless_pass_by_value)
diagnostic, which is `MaybeIncorrect` ( similar to our `Unsafe`):

```
warning: this argument is passed by value, but not consumed in the function body
 --> src/main.rs:3:15
  |
3 | fn size(data: Data) -> usize {
  |               ^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.97.0/index.html#needless_pass_by_value
  = note: requested on the command line with `-W clippy::needless-pass-by-value`
help: consider taking a reference instead
  |
3 | fn size(data: &Data) -> usize {
  |               +
```

and here's a rustc
[`LetLike`](https://github.com/rust-lang/rust/blob/8bab26f4f68e0e26f0bb7960be334d5b520ea452/compiler/rustc_trait_selection/src/errors.rs#L268-L288)
diagnostic, which is `has-placeholders` (similar to our `DisplayOnly`
but definitely produces invalid code in this case):

```
error[E0282]: type annotations needed for `Vec<_>`
 --> placeholder.rs:2:9
  |
2 |     let values = Vec::new();
  |         ^^^^^^   ---------- type must be known at this point
  |
help: consider giving `values` an explicit type, where the type for type parameter `T` is specified
  |
2 |     let values: Vec<T> = Vec::new();
  |               ++++++++
```

</p>
</details>

Fixes https://github.com/astral-sh/ty/issues/1679

Test Plan
--

Updated existing snapshots, and some manual testing in the CLI:

<img width="965" height="400" alt="image"
src="https://github.com/user-attachments/assets/888ad79a-6853-48d4-8344-48da4af47d74"
/>

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2026-10-09 12:26:57 -04:00
Micha Reiser 9368abfdb3 [ty] Fix executable-copy race in CLI tests (#29034) 2026-10-01 10:26:02 +02:00
Micha Reiser 0d7e203568 [ty] Improve uv metadata diagnostics (#28990)
## Summary

This PR improves the uv-metadata diagnostics. Specifically, it fixes
that uv-metadata diagnostics spawn multiple lines when using
`output-format=concise`.

* Concise: `warning[uv-metadata] Failed to load uv metadata: No solution
found when resolving dependencies`: `Failed to load uv metadata:
{first_line_in_uv_output}`.
* Full: `uv workspace metadata` failed with `{status}` + subdiagnostic
with the details
  ```
error[uv-metadata]: `uv workspace metadata` failed with `exit status: 1`
          --> script.py:2:1
          info: No solution found when resolving dependencies
cause: Because missing-script-dependency was not found in the cache and
you require missing-script-dependency==99.0.0, we can conclude that your
requirements are unsatisfiable.
  
hint: Packages were unavailable because the network was disabled. When
the network is disabled, registry packages may only be read from the
cache.
  
  ```


Now, this is all best-effort:

* Concise: Only taking the first line could theoretically result in a
mid-sentence truncation if uv emits a multiline summary message.
* Full: Rendering `info: {first_line}` risks that second line is
misaligned if it line e.g. annotates the first line.

I don't think there's much we can do about this without uv emitting
structured diagnostics.

The first two commits restructure the uv file watching tests and change
them to show the diagnostic output. While not strictly necessary for
this change, a separate PR felt a bit overkill.

I recommend reviewing this commit by commit.



## Test Plan

Focused CLI, LSP, and uv file-watching tests pass.
2026-09-29 15:59:40 +02:00
Micha Reiser 226201fef0 [ty] Refresh Python settings when virtual environments change (#28650)
## Summary

This PR is a first step towards updating the project's uv metadata when
the virtual environment changes. The scope of this PR is to add the
non-uv specific virtual environment file watching. That is, it adds the
necessary file watching handling to update the detected virtual
environment and its Python version when:

* a `pyenv.cfg` changes
* the default `.venv` or the explicitly specified `environment.python`
virtual environment gets created or deleted.


Unfortunately, this does require storing the path to the resolved
virtual environment in `ProgramSettings`. Otherwise, we'd have to
resolve it every time we see a related file watcher event. It's
unfortunate because it doesn't feel like a setting. But there isn't
really any better to carry forward this information.


I recommend reviewing this PR commit by commit.


## Test Plan

Native file-watching regression tests pass.
2026-09-27 18:48:09 +02:00
Zsolt Dollenstein 915bb2b4bf [ty] Prefer existing @ paths over response files in Ruff and ty (#28877)
Ruff and ty interpret `@list.py` as a response-file reference even when
that literal path exists. This can turn a filename supplied by an
integration into command-line options.

Give existing literal `@` paths precedence in both CLIs, including
dangling symlinks, arguments inside nested response files, and arguments
after `--`. When the literal path is absent, keep expanding the response
file. Both CLIs share the implementation in `ruff_cli`.
2026-09-24 18:01:24 +00:00
Micha Reiser af73c077aa [ty] Only skip uv workspace metadata for a single script (#28581) 2026-09-17 19:09:35 +02:00
Micha Reiser 0c40f14f9f [ty] Support dependency lints with --config-file (#28573) 2026-09-17 16:45:23 +02:00
Micha Reiser 30c3f85c82 [ty] Ignore Python version from uv metadata (#28646) 2026-09-17 16:26:25 +02:00
Micha Reiser a65f3d6a54 [ty] Escape glob characters in anchored directory paths (#28518) 2026-09-14 11:54:52 +00:00
Micha Reiser ed76d0f250 [ty] Anchor default exclude patterns at the project root (#28463) 2026-09-11 12:28:40 +02:00
Micha Reiser ad39986b5b [ty] Fix --force-exclude for directories with an excluded ancestor (#28451) 2026-09-09 15:06:04 +02:00
Alex WaygoodandMicha Reiser 12132db288 [ty] Isolate uv integration tests from inherited environment settings (#28342)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-09-08 13:09:55 +02:00
Zsolt Dollenstein 0444f4a4ab [ty] Stop passing --frozen to uv workspace metadata (#28224)
When dependency declarations change without updating `uv.lock`, ty's
frozen metadata query returns the old dependency graph. This can leave
`missing-direct-dependency` diagnostics after the dependency has been
declared.

Drop `--frozen` so uv can refresh the lockfile. Keep `--active` without
synchronizing installed packages. Add a stale-lock regression and update
the rule documentation and its generated copies.

CLI-only `uv check --frozen` and `--isolated` policies are not forwarded
to ty's metadata subprocess. Preserving those policies needs a uv-side
follow-up.
2026-09-01 18:57:11 +01:00
Zsolt Dollenstein 33648d47d7 [ty] Check direct dependencies in PEP 723 scripts (#28136)
`missing-direct-dependency` currently skips PEP 723 scripts. This
extends the rule to scripts using uv integration, checking imports
against the script's inline `dependencies` list and directing users
there when a declaration is missing.

Each script uses its own dependency graph, independently of the
workspace and other scripts. The dependency metadata is cached
separately from script settings so diagnostics update after
synchronization even when those settings are unchanged. The rule skips
scripts whose metadata is unavailable or out of date.
2026-08-29 09:59:52 +00:00
Alex Waygood ef08e25617 [ty] Format lint documentation the same way we format mdtests (#28135) 2026-08-28 18:18:07 +01:00
Zsolt Dollenstein 3c77dcc2a5 [ty] Warn when uv metadata cannot support dependency checks (#28133)
`missing-direct-dependency` currently skips checks without a diagnostic
when dependency metadata conversion or Python environment checks fail.
This PR reports one `uv-metadata` warning for the project, including the
reason and recovery advice where available. Ordinary type checking
continues.

The warning is emitted only when the rule is enabled globally or in a
file override. Existing uv discovery and refresh errors take precedence.

Dependency-free virtual workspaces no longer require module ownership
metadata, avoiding a spurious warning from the new diagnostics
implemented here.

> [!NOTE]
> A uv
[workspace](https://docs.astral.sh/uv/concepts/projects/workspaces/)
groups projects under a shared lockfile. The projects do not all need to
be installed as Python packages: uv also supports [“virtual”
projects](https://docs.astral.sh/uv/concepts/projects/dependencies/#virtual-dependencies),
for which it installs dependencies without building or installing the
project itself.
> If a workspace contains only such non-package projects and has no
external dependencies, there are no installed modules to associate with
packages. Its empty module ownership map is valid. ty previously treated
that metadata as unavailable and disabled dependency checks without a
diagnostic. This PR accepts it instead, avoiding a spurious uv-metadata
warning from the new diagnostics.

Depends on #28001.
2026-08-28 16:36:09 +00:00
Zsolt Dollenstein f4839591d6 [ty] Add a missing-direct-dependency rule (#28001)
This PR replaces #25027. It adds an opt-in check for imports of
installed distributions that the current project does not declare
directly in `pyproject.toml`.

## Overview

The check uses ty's existing uv workspace integration (`TY_UV=1`) to
call `uv workspace metadata --frozen --active`. uv now provides module
ownership without synchronizing the environment, so ty can read the
metadata without installing packages or updating `uv.lock`.

The metadata provides:

1. Each workspace project's runtime and optional dependencies.
2. Dependencies declared in dependency groups.
3. Importable modules and their owning distributions, including source
paths for editable installs.

During import inference, ty maps each resolved import to its
distribution and compares it against the importing project's direct
declarations. If the declaration is missing, ty emits
`missing-direct-dependency`, naming the distribution to add. Each
distribution is reported once per file, at its first unsuppressed
import.

The rule is disabled by default and requires an existing, synchronized
environment. Unavailable or incompatible dependency metadata disables
the check; rejected dependency metadata produces a debug message.

## Nuances

- Editable installs may lack entries in uv's module-owner map. ty uses
their source paths to attribute resolved imports.
- Files identified as package code require runtime or optional
dependencies. Non-package files, such as tests and scripts, can also use
dependency groups, but those groups' transitive dependencies still need
direct declarations.
- For `from package import child`, a resolved child module is checked
against its own distribution rather than the parent's. Imports with
unknown or ambiguous ownership are skipped.
- Ownership metadata is used only when the explicitly selected Python
environment matches uv's environment.
- The current integration covers directory checks. Explicit file
arguments, `--config-file`, and standalone PEP 723 scripts do not use
the workspace's dependency declarations.

The schema and rule documentation are regenerated. Most of the
rule-documentation diff consists of updated source-line links.
2026-08-28 14:01:44 +00:00
Micha Reiser 47c81c8b4a [ty] Move script environment initialization to the CLI and LSP (#28038)
## Summary

This PR moves from a lazy PEP 723 script discovery do eagerly discover
all scripts as part of the project's file discovery.


There are two motivations for doing this:

1. Initializing the script's environment before checking the script is
not sufficient. Other files can import the script, and type inference
can then resolve `file_settings` and `python_version_with_source` which
are both environment dependent (the former less so, but uv can tell us
the python version). Initializing all scripts before we start checking
ensures that type inference sees the right environment even when a
script has been imported. This is the bug that Zsolt identified in my
initial PEP 723 PR.
2. Today, the LSP only initialized scripts when the user opened them.
However, that means that their environment isn't available as part of
find references and workspace symbols. This can result in missed
references (note, making find references return all project and script
references when searching for references of a shared dependency requires
a few changes to find references as well, but this sets the foundation
for it). Initializing all environments when opening the project ensures
the environments are available when running find references (or the user
can rerun find references once all syncs are complete, but they don't
have to open every script just to make sure that find references will
show the references in them)
3. Knowing all scripts simplifies file watching because we now have
distinct points where script environments can change, and may require
updating the watched paths.


Now, there are a few downsides as well, but I think this is the right
trade off (honestly, I don't know how to fix 1 easily without it, and 3
was the main reason why I considered this approach even before Zsolt
found the bug).

* Unlike before, the LSP now indexes and reads all project files. This
can mean that startup now takes a second or so on very large projects
where it was instant before, because we didn't do any form of indexing.
This also means that the LSP retains more memory for projects that don't
use workspace diagnostics (or find references), because the LSP now
loads all files into memory to determine whether a file is a script.
This is inherent to the approach. I suspect that we can mitigate the
"all source in memory" in the future by only storing compressed source
text, which should reduce memory usage by about 70%.
* We now sync all scripts on LSP startup. I could see this become a
problem in workspaces with many (with 100 or 1000s scripts). If this
becomes a problem, I think we can a) limit script sync to on-open,
accepting that find-references etc. may require opening the relevant
scripts and/or b) allow users to selectively sync scripts by using a LSP
command. For now, I think syncing all scripts should be fine, given that
uv is fast (the first time might take a while)
* I had to make the uv sync queue unbounded. It's still bounded by the
number of scripts and projects. But we no longer apply back pressure if
the sync requests start piling up. The reason I had to remove it is
because we don't want a `didChange` or `didOpen` to block, only because
there are already 8 queued scripts. But more importantly, we don't want
to block the LSP startup until all scripts have synchronized, but
queuing them up during startup would just have done that (because the
main loop blocks everytime time the queue is full). I think this is
okay, and I'll add another PR on top of this one that adds cancellation
support for sync requests. I also think that our previous back pressure
wasn't as impactful as I thought
* We now sync scripts before checking the files. That means, ty no
longer makes progress on checking other project files while the syncs
are pending. This is the one I'm the most bumped about. It was so cool
that ty often checked the entire project while waiting on uv to finish
syncing. To mitigate, I increased the worker pool to N/4 where N is max
parallelism and, while testing, I also found that syncinc all scripts,
at least in Ruff's repo, is instant once uv is warm.

I think this also gets us into a position where adding support for
nested projects becomes much easier, because they'll naturally fit in.
We'll discover nested projects as part of indexing `Files` (we'd need to
move that off `Project`), synchronizing their environments can happen at
the exactly same points as synchronizing scripts. The biggest remaining
lift is to change `ty_project` and `ProjectDatabase` to no longer assume
that there's a single `Project` (but there is still one main project).


## Test Plan

CLI


https://github.com/user-attachments/assets/db370cde-d9db-4c85-8772-06b608ce6587



https://github.com/user-attachments/assets/ae6e825a-6814-4dc0-8b2f-630469de1a8d
2026-08-28 13:09:04 +02:00
Micha Reiser 0e60c897b8 [ty] Refresh uv project metadata in the background (#27933)
## Summary

This refactors the project's `uv workspace metadata` call to run in the
background, the same as for scripts. This ensures that the watch command
and the LSP remain responsive and show a progress indicator while uv is
running.

It should also make it easier to run `uv workspace metadata --sync` for
projects. Although, that does require some work so that we can surface
progress from the initial uv call (during project discovery) and not
have the LSP blocked until the command completes.

This PR does not change when we run `uv workspace metadata`. That is, it
doesn't add logic to detect when uv needs to rerun. The same as before,
`uv workspace metadata` is only called when the `pyproject.toml`
changed. It isn't run when a `uv.toml` or the virtual environment
changes. We should do so, but this should be its own PR.

This PR enables `TY_UV=1 ty check --watch`

## Review

I recommending reviewing this PR commit by commit and with whitespace
changes disabled.


## Test Plan

LSP:



https://github.com/user-attachments/assets/8c1ab9df-8209-44d5-b0b2-ba06cb824625



1. Simulate a long `uv metadata` command (e.g. when `uv sync` is holding
the lock for multiple seconds). You can see the progress report
2. Changes to a `pyproject.toml` trigger a refresh

CLI


https://github.com/user-attachments/assets/b3cde596-c7f5-4f2e-880b-d3885c02dcb8
2026-08-28 13:09:04 +02:00
Alex Waygood 8b807f65cf [ty] Fix compiler warning seen in cargo nextest run invocations locally (#28096) 2026-08-27 11:21:32 +01:00