Skip to content

Instantly share code, notes, and snippets.

@simonw

simonw/symbex.md Secret

Created April 23, 2025 04:53
Show Gist options
  • Select an option

  • Save simonw/c46390522bc839daab6c08bad3f87b39 to your computer and use it in GitHub Desktop.

Select an option

Save simonw/c46390522bc839daab6c08bad3f87b39 to your computer and use it in GitHub Desktop.

2025-04-23T04:48:43 conversation: 01jsgfnev4nez6e6ny269t85ep id: 01jsgfnevbbvynn5gtn7h8x774

Model: openai/o4-mini

Prompt

-- none --

Prompt fragments

c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4
Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
8d266b839a230044ff704388e9dbd034282abed397847920be444f67d2053dda
# Run tests and linters
@default: test lint

# Run pytest with supplied options
@test *options:
  pipenv run pytest {{options}}

# Run linters
@lint:
  pipenv run black . --check
  pipenv run cog --check README.md

# Rebuild docs with cog
@cog:
  pipenv run cog -r README.md

# Apply Black
@black:
  pipenv run black .

# Auto-format and fix things
@fix: cog black
7d6becc409c10cb533239acb7d53d9f6e8aff93e1988e857593a473221b8c43f
# Symbex

[![PyPI](https://img.shields.io/pypi/v/symbex.svg)](https://pypi.org/project/symbex/)
[![Changelog](https://img.shields.io/github/v/release/simonw/symbex?include_prereleases&label=changelog)](https://github.com/simonw/symbex/releases)
[![Tests](https://github.com/simonw/symbex/workflows/Test/badge.svg)](https://github.com/simonw/symbex/actions?query=workflow%3ATest)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/symbex/blob/master/LICENSE)

Find the Python code for specified symbols

Read [Symbex: search Python code for functions and classes, then pipe them into a LLM](https://simonwillison.net/2023/Jun/18/symbex/) for background on this project.

## Installation

Install this tool using `pip`:
```bash
pip install symbex
```
Or using Homebrew:
```bash
brew install simonw/llm/symbex
```
## Usage

`symbex` can search for names of functions and classes that occur at the top level of a Python file.

To search every `.py` file in your current directory and all subdirectories, run like this:

```bash
symbex my_function
```
You can search for more than one symbol at a time:
```bash
symbex my_function MyClass
```
Wildcards are supported - to search for every `test_` function run this (note the single quotes to avoid the shell interpreting the `*` as a wildcard):
```bash
symbex 'test_*'
```
To search for methods within classes, use `class.method` notation:
```bash
symbex Entry.get_absolute_url
```
Wildcards are supported here as well:
```bash
symbex 'Entry.*'
symbex '*.get_absolute_url'
symbex '*.get_*'
```
Or to view every method of every class:
```bash
symbex '*.*'
```
To search within a specific file, pass that file using the `-f` option. You can pass this more than once to search multiple files.

```bash
symbex MyClass -f my_file.py
```
To search within a specific directory and all of its subdirectories, use the `-d/--directory` option:
```bash
symbex Database -d ~/projects/datasette
```
If you know that you want to inspect one or more modules that can be imported by Python, you can use the `-m/--module name` option. This example shows the signatures for every symbol available in the `asyncio` package:
```bash
symbex -m asyncio -s --imports
```
You can search the directory containing the Python standard library using `--stdlib`. This can be useful for quickly looking up the source code for specific Python library functions:
```bash
symbex --stdlib -in to_thread
```
`-in` is explained below. If you provide `--stdlib` without any `-d` or `-f` options then `--silent` will be turned on automatically, since the standard library otherwise produces a number of different warnings.

The output starts like this:
```python
# from asyncio.threads import to_thread
async def to_thread(func, /, *args, **kwargs):
    """Asynchronously run function *func* in a separate thread.
    # ...
```
You can exclude files in specified directories using the `-x/--exclude` option:
```bash
symbex Database -d ~/projects/datasette -x ~/projects/datasette/tests
```
If `symbex` encounters any Python code that it cannot parse, it will print a warning message and continue searching:
```
# Syntax error in path/badcode.py: expected ':' (<unknown>, line 1)
```
Pass `--silent` to suppress these warnings:
```bash
symbex MyClass --silent
```
### Filters

In addition to searching for symbols, you can apply filters to the results.

The following filters are available:

- `--function` - only functions
- `--class` - only classes
- `--async` - only `async def` functions
- `--unasync` - only non-async functions
- `--documented` - functions/classes that have a docstring
- `--undocumented` - functions/classes that do not have a docstring
- `--public` - functions/classes that are public - don't have a `_name` prefix (or are `__*__` methods)
- `--private` - functions/classes that are private - have a `_name` prefix and are not `__*__`
- `--dunder` - functions matching `__*__` - this should usually be used with `*.*` to find all dunder methods
- `--typed` - functions that have at least one type annotation
- `--untyped` - functions that have no type annotations
- `--partially-typed` - functions that have some type annotations but not all
- `--fully-typed` - functions that have type annotations for every argument and the return value
- `--no-init` - Exclude `__init__(self)` methods. This is useful when combined with `--fully-typed '*.*'` to avoid returning `__init__(self)` methods that would otherwise be classified as fully typed, since `__init__` doesn't need argument or return type annotations.

For example, to see the signatures of every `async def` function in your project that doesn't have any type annotations:

```bash
symbex -s --async --untyped
```

For class methods instead of functions, you can combine filters with a symbol search argument of `*.*`.

This example shows the full source code of every class method in the Python standard library that has type annotations for all of the arguments and the return value:

```bash
symbex --fully-typed --no-init '*.*' --stdlib
```

To find all public functions and methods that lack documentation, just showing the signature of each one:

```bash
symbex '*' '*.*' --public --undocumented --signatures
```

### Example output

In a fresh checkout of [Datasette](https://github.com/simonw/datasette) I ran this command:

```bash
symbex MessagesDebugView get_long_description
```
Here's the output of the command:
```python
# File: setup.py Line: 5
def get_long_description():
    with open(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"),
        encoding="utf8",
    ) as fp:
        return fp.read()

# File: datasette/views/special.py Line: 60
class PatternPortfolioView(View):
    async def get(self, request, datasette):
        await datasette.ensure_permissions(request.actor, ["view-instance"])
        return Response.html(
            await datasette.render_template(
                "patterns.html",
                request=request,
                view_name="patterns",
            )
        )
```
### Just the signatures

The `-s/--signatures` option will list just the signatures of the functions and classes, for example:
```bash
symbex -s -f symbex/lib.py
```
<!-- [[[cog
import cog
from click.testing import CliRunner
import pathlib
from symbex.cli import cli

def sorted_chunks(text):
    chunks = text.strip().split("\n\n")
    chunks.sort()
    return "\n\n".join(chunks)

path = pathlib.Path("symbex").resolve()
runner = CliRunner()
result = runner.invoke(cli, ["-s", "-f", str(path / "lib.py")])
cog.out(
    "```python\n{}\n```\n".format(sorted_chunks(result.output))
)
]]] -->
```python
# File: symbex/lib.py Line: 107
def function_definition(function_node: AST):

# File: symbex/lib.py Line: 13
def find_symbol_nodes(code: str, filename: str, symbols: Iterable[str]) -> List[Tuple[(AST, Optional[str])]]:

# File: symbex/lib.py Line: 175
def class_definition(class_def):

# File: symbex/lib.py Line: 209
def annotation_definition(annotation: AST) -> str:

# File: symbex/lib.py Line: 227
def read_file(path):

# File: symbex/lib.py Line: 253
class TypeSummary:

# File: symbex/lib.py Line: 258
def type_summary(node: AST) -> Optional[TypeSummary]:

# File: symbex/lib.py Line: 304
def quoted_string(s):

# File: symbex/lib.py Line: 315
def import_line_for_function(function_name: str, filepath: str, possible_root_dirs: List[str]) -> str:

# File: symbex/lib.py Line: 37
def code_for_node(code: str, node: AST, class_name: str, signatures: bool, docstrings: bool) -> Tuple[(str, int)]:

# File: symbex/lib.py Line: 71
def add_docstring(definition: str, node: AST, docstrings: bool, is_method: bool) -> str:

# File: symbex/lib.py Line: 82
def match(name: str, symbols: Iterable[str]) -> bool:
```
<!-- [[[end]]] -->
This can be combined with other options, or you can run `symbex -s` to see every symbol in the current directory and its subdirectories.

To include estimated import paths, such as `# from symbex.lib import match`, use `--imports`. These will be calculated relative to the directory you specified, or you can pass one or more `--sys-path` options to request that imports are calculated relative to those directories as if they were on `sys.path`:

```bash
~/dev/symbex/symbex match --imports -s --sys-path ~/dev/symbex
```
Example output:
<!-- [[[cog
result = runner.invoke(cli, [
    "--imports", "-d", str(path), "match", "-s", "--sys-path", str(path.parent)
])
cog.out(
    "```python\n{}\n```\n".format(result.stdout.strip())
)
]]] -->
```python
# File: symbex/lib.py Line: 82
# from symbex.lib import match
def match(name: str, symbols: Iterable[str]) -> bool:
```
<!-- [[[end]]] -->
To suppress the `# File: ...` comments, use `--no-file` or `-n`.

So to both show import paths and suppress File comments, use `-in` as a shortcut:
```bash
symbex -in match
```
Output:
<!-- [[[cog
result = runner.invoke(cli, [
    "-in", "-d", str(path), "match", "-s", "--sys-path", str(path.parent)
])
cog.out(
    "```python\n{}\n```\n".format(result.stdout.strip())
)
]]] -->
```python
# from symbex.lib import match
def match(name: str, symbols: Iterable[str]) -> bool:
```
<!-- [[[end]]] -->

To include docstrings in those signatures, use `--docstrings`:
```bash
symbex match --docstrings -f symbex/lib.py
```
Example output:
<!-- [[[cog
result = runner.invoke(cli, ["match", "--docstrings", "-f", str(path / "lib.py")])
cog.out(
    "```python\n{}\n```\n".format(result.stdout.strip())
)
]]] -->
```python
# File: symbex/lib.py Line: 82
def match(name: str, symbols: Iterable[str]) -> bool:
    "Returns True if name matches any of the symbols, resolving wildcards"
```
<!-- [[[end]]] -->

## Counting symbols

If you just want to count the number of functions and classes that match your filters, use the `--count` option. Here's how to count your classes:

```bash
symbex --class --count
```
Or to count every async test function:
```bash
symbex --async 'test_*' --count
```
## Structured output

LLM defaults to outputting plain text (actually valid Python code, thanks to the way it uses comments).

You can request output in CSV, TSV, JSON or newline-delimited JSON instead, using the following options:

- `--json`: a JSON array, `[{"id": "...", "code": "..."}]`
- `--nl`: newline-delimited JSON, `{"id": "...", "code": "..."}` per line
- `--csv`: CSV with `id,code` as the heading row
- `--tsv`: TSV with `id\tcode` as the heading row

In each case the ID will be the path to the file containing the symbol, followed by a colon, followed by the line number of the symbol, for example:

```json
{
  "id": "symbex/lib.py:82",
  "code": "def match(name: str, symbols: Iterable[str]) -> bool:"
}
```
If you pass `-i/--imports` the ID will be the import line instead:
```json
{
  "id": "from symbex.lib import match",
  "code": "def match(name: str, symbols: Iterable[str]) -> bool:"
}
```
Pass `--id-prefix 'something:'` to add the specified prefix to the start of each ID.

This example will generate a CSV file of all of your test functions, using the import style of IDs and a prefix of `test:`:

```bash
symbex 'test_*' \
  --function \
  --imports \
  --csv > tests.csv
```

## Using with LLM

This tool is primarily designed to be used with [LLM](https://llm.datasette.io/), a CLI tool for working with Large Language Models.

`symbex` makes it easy to grab a specific class or function and pass it to the `llm` command.

For example, I ran this in the Datasette repository root:

```bash
symbex Response | llm --system 'Explain this code, succinctly'
```
And got back this:

> This code defines a custom `Response` class with methods for returning HTTP responses. It includes methods for setting cookies, returning HTML, text, and JSON responses, and redirecting to a different URL. The `asgi_send` method sends the response to the client using the ASGI (Asynchronous Server Gateway Interface) protocol.

The structured output feature is designed to be used with [LLM embeddings](https://llm.datasette.io/en/stable/embeddings/index.html). You can generate embeddings for every symbol in your codebase using [llm embed-multi](https://llm.datasette.io/en/stable/embeddings/cli.html#llm-embed-multi) like this:

```bash
symbex '*' '*:*' --nl | \
  llm embed-multi symbols - \
  --format nl --database embeddings.db --store
```
This creates a database in `embeddings.db` containing all of your symbols along with embedding vectors.

You can then search your code like this:
```bash
llm similar symbols -d embeddings.db -c 'test csv' | jq
```

## Replacing a matched symbol

The `--replace` option can be used to replace a single matched symbol with content piped in to standard input.

Given a file called `my_code.py` with the following content:
```python
def first_function():
    # This will be ignored
    pass

def second_function():
    # This will be replaced
    pass
```
Run the following:
```bash
echo "def second_function(a, b):
    # This is a replacement implementation
    return a + b + 3
" | symbex second_function --replace
```
The result will be an updated-in-place `my_code.py` containing the following:

```python
def first_function():
    # This will be ignored
    pass

def second_function(a, b):
    # This is a replacement implementation
    return a + b + 3
```
This feature should be used with care! I recommend only using this feature against code that is already checked into Git, so you can review changes it makes using `git diff` and revert them using `git checkout my_code.py`.

## Replacing a matched symbol by running a command

The `--rexec COMMAND` option can be used to replace a single matched symbol by running a command and using its output.

The command will be run with the matched symbol's definition piped to its standard input. The output of that command will be used as the replacement text.

Here's an example that uses `sed` to add a `# ` to the beginning of each matching line, effectively commenting out the matched function:

```bash
symbex first_function --rexec "sed 's/^/# /'"
```
This modified the first function in place to look like this:
```python
# def first_function():
#    # This will be ignored
#    pass
```
A much more exciting example uses LLM. This example will use the `gpt-3.5-turbo` model to add type hints and generate a docstring:

```bash
symbex second_function \
  --rexec "llm --system 'add type hints and a docstring'"
```
I ran this against this code:
```python
def first_function():
    # This will be ignored
    pass

def second_function(a, b):
    return a + b + 3
```
And the second function was updated in place to look like this:
```python
def second_function(a: int, b: int) -> int:
    """
    Returns the sum of two integers (a and b) plus 3.

    Parameters:
    a (int): The first integer.
    b (int): The second integer.

    Returns:
    int: The sum of a and b plus 3.
    """
    return a + b + 3
```
## Using in CI

The `--check` option causes `symbex` to return a non-zero exit code if any matches are found for your query.

You can use this in CI to guard against things like public functions being added without documentation:

```bash
symbex --function --public --undocumented --check
```
This will fail silently but set a `1` exit code if there are any undocumented functions.

Using this as a step in a CI tool such as GitHub Actions should result in a test failure.

Run this to see the exit code from the last command:
```bash
echo $?
```

`--check` will not output anything by default. Add `--count` to output a count of matching symbols, or `-s/--signatures` to output the signatures of the matching symbols, for example:
```bash
symbex --function --public --undocumented --check --count
```

## Similar tools

- [pyastgrep](https://github.com/spookylukey/pyastgrep) by Luke Plant offers advanced capabilities for viewing and searching through Python ASTs using XPath.
- [cq](https://github.com/fullstackio/cq) is a tool thet lets you "extract code snippets using CSS-like selectors", built using [Tree-sitter](https://tree-sitter.github.io/tree-sitter/) and primarily targetting JavaScript and TypeScript.

## symbex --help

<!-- [[[cog
result2 = runner.invoke(cli, ["--help"])
help = result2.output.replace("Usage: cli", "Usage: symbex")
cog.out(
    "```\n{}\n```".format(help)
)
]]] -->
```
Usage: symbex [OPTIONS] [SYMBOLS]...

  Find symbols in Python code and print the code for them.

  Example usage:

      # Search current directory and subdirectories
      symbex my_function MyClass

      # Search using a wildcard
      symbex 'test_*'

      # Find a specific class method
      symbex 'MyClass.my_method'

      # Find class methods using wildcards
      symbex '*View.handle_*'

      # Search a specific file
      symbex MyClass -f my_file.py

      # Search within a specific directory and its subdirectories
      symbex Database -d ~/projects/datasette

      # View signatures for all symbols in current directory and subdirectories
      symbex -s

      # View signatures for all test functions
      symbex 'test_*' -s

      # View signatures for all async functions with type definitions
      symbex --async --typed -s

      # Count the number of --async functions in the project
      symbex --async --count

      # Replace my_function with a new implementation:
      echo "def my_function(a, b):
          # This is a replacement implementation
          return a + b + 3
      " | symbex my_function --replace

      # Replace my_function with the output of a command:
      symbex first_function --rexec "sed 's/^/# /'"
      # This uses sed to comment out the function body

Options:
  --version                  Show the version and exit.
  -f, --file FILE            Files to search
  -d, --directory DIRECTORY  Directories to search
  --stdlib                   Search the Python standard library
  -x, --exclude DIRECTORY    Directories to exclude
  -s, --signatures           Show just function and class signatures
  -n, --no-file              Don't include the # File: comments in the output
  -i, --imports              Show 'from x import y' lines for imported symbols
  -m, --module TEXT          Modules to search within
  --sys-path TEXT            Calculate imports relative to these on sys.path
  --docs, --docstrings       Show function and class signatures plus docstrings
  --count                    Show count of matching symbols
  --silent                   Silently ignore Python files with parse errors
  --function                 Filter functions
  --async                    Filter async functions
  --unasync                  Filter non-async functions
  --class                    Filter classes
  --documented               Filter functions with docstrings
  --undocumented             Filter functions without docstrings
  --public                   Filter for symbols without a _ prefix
  --private                  Filter for symbols with a _ prefix
  --dunder                   Filter for symbols matching __*__
  --typed                    Filter functions with type annotations
  --untyped                  Filter functions without type annotations
  --partially-typed          Filter functions with partial type annotations
  --fully-typed              Filter functions with full type annotations
  --no-init                  Filter to exclude any __init__ methods
  --check                    Exit with non-zero code if any matches found
  --replace                  Replace matching symbol with text from stdin
  --rexec TEXT               Replace with the result of piping to this tool
  --csv                      Output as CSV
  --tsv                      Output as TSV
  --json                     Output as JSON
  --nl                       Output as newline-delimited JSON
  --id-prefix TEXT           Prefix to use for symbol IDs
  --help                     Show this message and exit.

```
<!-- [[[end]]] -->

## Development

To contribute to this tool, first checkout the code. Then create a new virtual environment:
```bash
cd symbex
python -m venv venv
source venv/bin/activate
```
Now install the dependencies and test dependencies:
```bash
pip install -e '.[test]'
```
To run the tests:
```bash
pytest
```
### just

You can also install [just](https://github.com/casey/just) and use it to run the tests and linters like this:

```bash
just
```
Or to list commands:
```bash
just -l
```
```
Available recipes:
    black         # Apply Black
    cog           # Rebuild docs with cog
    default       # Run tests and linters
    lint          # Run linters
    test *options # Run pytest with supplied options
```
1d5f2a0e81b2b6978c74edd78d9d2df086175091daecbb017e8f0151c64879fd
from setuptools import setup
import os

VERSION = "1.4.1"


def get_long_description():
    with open(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"),
        encoding="utf8",
    ) as fp:
        return fp.read()


setup(
    name="symbex",
    description="Find the Python code for specified symbols",
    long_description=get_long_description(),
    long_description_content_type="text/markdown",
    author="Simon Willison",
    url="https://github.com/simonw/symbex",
    project_urls={
        "Issues": "https://github.com/simonw/symbex/issues",
        "CI": "https://github.com/simonw/symbex/actions",
        "Changelog": "https://github.com/simonw/symbex/releases",
    },
    license="Apache License, Version 2.0",
    version=VERSION,
    packages=["symbex"],
    entry_points="""
        [console_scripts]
        symbex=symbex.cli:cli
    """,
    install_requires=["click"],
    extras_require={"test": ["pytest", "pytest-icdiff", "cogapp", "PyYAML", "ruff"]},
    python_requires=">=3.8",
)
de854f6efbb84fb752668768d4a5e2a67f12ba26572494728d67498e6a49adcc
.venv
__pycache__/
*.py[cod]
*$py.class
venv
.eggs
.pytest_cache
*.egg-info
.DS_Store
d574936991f145908c2bd86cb70650dfed277d2577e2199ea326f951cacc1534
# Tests for "symbex --imports --sys-path ..."
import pathlib
import pytest
from click.testing import CliRunner

from symbex.cli import cli


@pytest.fixture
def imports_dir(tmpdir):
    for path, content in (
        ("one/foo.py", "def foo1():\n    pass"),
        ("one/bar.py", "def bar1():\n    pass"),
        ("two/foo.py", "def foo2():\n    pass"),
        ("two/bar.py", "def bar2():\n    pass"),
        ("deep/nested/three/foo.py", "def foo3():\n    pass"),
        (
            "deep/nested/three/bar.py",
            ("class Bar3:\n" "    def __init__(self):\n" "        pass"),
        ),
    ):
        p = pathlib.Path(tmpdir / path)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(content, "utf-8")
    return tmpdir


@pytest.mark.parametrize(
    "args,sys_path,expected",
    (
        (["foo1"], None, "from one.foo import foo1"),
        (["foo2"], None, "from two.foo import foo2"),
        (["foo1"], "one/", "from foo import foo1"),
        # This should force a relative import:
        (["foo2"], "one/", "from .foo import foo2"),
        # Various deep nested examples
        (["foo3"], None, "from deep.nested.three.foo import foo3"),
        (["Bar3"], None, "from deep.nested.three.bar import Bar3"),
        (["foo3"], "deep/nested", "from three.foo import foo3"),
        # Test display of methods
        (["Bar3.*"], "deep/nested", "from three.bar import Bar3"),
    ),
)
def test_imports(args, sys_path, expected, imports_dir):
    runner = CliRunner()
    args = ["-in", "-d", str(imports_dir)] + args
    if sys_path:
        args.extend(("--sys-path", str(imports_dir / sys_path)))
    result = runner.invoke(cli, args, catch_exceptions=False)
    assert result.exit_code == 0
    import_line = [
        line[2:] for line in result.stdout.split("\n") if line.startswith("# from")
    ][0]
    assert import_line == expected
da8601ab9ab3642bcdd10589878d49e4984286085bf26ff2c26d036c5b333e28
from typing import Tuple


# Function with no arguments
def func_no_args():
    "This has a single line docstring"
    pass


# Function with positional arguments
def func_positional_args(a, b, c):
    """This has a
    multi-line docstring"""
    pass


# Async function
async def async_func(a, b, c):
    pass


# Function with default arguments
def func_default_args(a, b=2, c=3):
    pass


# Function with arbitrary number of positional arguments
def func_arbitrary_positional_args(*args):
    pass


# Function with arbitrary number of keyword arguments
def func_arbitrary_keyword_args(**kwargs):
    pass


# Function with both arbitrary positional and keyword arguments
def func_arbitrary_args(*args, **kwargs):
    pass


# Function with positional-only arguments (Python 3.8 and above)
def func_positional_only_args(a, /, b, c):
    pass


# Function with keyword-only arguments
def func_keyword_only_args(a, *, b, c):
    pass


# Function with type annotations (Python 3.5 and above)
def func_type_annotations(a: int, b: str) -> bool:
    pass


# Class with no base classes
class ClassNoBase:
    pass


# Class with a single base class
class ClassSingleBase(int):
    pass


# Class with multiple base classes
class ClassMultipleBase(int, str):
    pass


# Class with a metaclass
class ClassWithMeta(metaclass=type):
    pass


# Class with methods
class ClassWithMethods:
    def __init__(self, a):
        pass

    def method_types(self, b: int) -> bool:
        return True

    def method_positional_only_args(a, /, b, c):
        pass

    def method_keyword_only_args(a, *, b, c):
        pass

    async def async_method(a, b, c):
        pass


# Borrowed from Jedi
# https://github.com/simonw/symbex/issues/16
def function_with_non_pep_0484_annotation(
    x: "I can put anything here",
    xx: "",
    yy: "\r\n\0;+*&^564835(---^&*34",
    y: 3 + 3,
    zz: float,
) -> int("42"):
    pass


def complex_annotations(
    code: str, symbols: Iterable[str]
) -> List[Tuple[AST, Optional[str]]]:
    pass


# For testing --typed/--untyped/etc


def func_fully_typed(a: int, b: str) -> bool:
    pass


async def async_func_fully_typed(a: int, b: str) -> bool:
    pass


def func_partially_typed(a: int, b) -> bool:
    pass


def func_partially_typed_no_typed_return(a: int, b: int):
    pass


def func_partially_typed_only_typed_return(a, b) -> int:
    pass


def func_typed_no_params() -> None:
    pass


def _private() -> None:
    pass


class ClassForTypedTests:
    def __init__(self, a: int):
        pass

    def method_fully_typed(self, a: int, b: str) -> bool:
        "Single line"
        pass

    def method_partially_typed(self, a: int, b) -> bool:
        """Multiple
        lines"""
        pass

    def method_untyped(self, a, b):
        pass

    def _private_method(self):
        pass


class _PrivateClass:
    pass
785140474ee1bfee1e58055dde5e6094f42fc6a240507779a55f20af6d91ceaa
import pytest
from click.testing import CliRunner
from symbex.cli import cli


@pytest.mark.parametrize(
    "extra_args,expected,expected_error",
    (
        (["--json"], '[{"id": "symbex.py:1", "code": "def blah():"}]\n', None),
        (["--csv"], "id,code\nsymbex.py:1,def blah():\n", None),
        (["--tsv"], "id\tcode\nsymbex.py:1\tdef blah():\n", None),
        (["--nl"], '{"id": "symbex.py:1", "code": "def blah():"}\n', None),
        # ID prefix
        (
            ["--nl", "--id-prefix", "foo:"],
            '{"id": "foo:symbex.py:1", "code": "def blah():"}\n',
            None,
        ),
        # Error states
        (
            ["--json", "--csv"],
            None,
            "Only one of --csv, --tsv, --json, --nl can be used",
        ),
        (
            ["--id-prefix", "foo:"],
            None,
            "--id-prefix can only be used with --csv, --tsv, --json or --nl",
        ),
    ),
)
def test_output(extra_args, expected, expected_error):
    runner = CliRunner()
    with runner.isolated_filesystem():
        open("symbex.py", "w").write("def blah():\n    pass\n")
        result = runner.invoke(
            cli,
            ["blah", "-s"] + extra_args,
            catch_exceptions=False,
        )
    if expected_error:
        assert result.exit_code != 0
        assert expected_error in result.stdout
    else:
        assert result.exit_code == 0
        assert result.output == expected
d98bcddb65f6c38e0e580aff09790e8609e368a6984340e5d7f1bf4c82ac1b30
- original: |
    def one():
        pass

    def two():
        "Two"
  stdin: |
    def two(): pass
  args: ["two", "--replace"]
  expected: |
    def one():
        pass

    def two(): pass

- original: |
    import os

    @decorated
    def one():
        "This has multiple lines and a decorator"
        return 1 + 2

    def two():
        "Two"
  stdin: |
    def one():
        # No decorator now, but multiple lines
        a = 1 + 2
        return a * 3
  args: ["one", "--replace"]
  expected: |
    import os

    def one():
        # No decorator now, but multiple lines
        a = 1 + 2
        return a * 3


    def two():
        "Two"
8605bdc606b7aeeccf8fdf9d600833eaf2d417620c9d2bdc63090f8d99c0bf3f
import pathlib
import pytest
import textwrap
from click.testing import CliRunner

from symbex.cli import cli
from symbex.lib import read_file, quoted_string


def test_no_args_shows_help():
    runner = CliRunner()
    result = runner.invoke(cli, catch_exceptions=False)
    assert result.exit_code == 0
    assert "Usage: cli [OPTIONS]" in result.stdout


@pytest.fixture
def directory_full_of_code(tmpdir):
    for path, content in (
        ("foo.py", "def foo1():\n    pass\n\n@decorated\ndef foo2():\n    pass\n\n"),
        ("bar.py", "class BarClass:\n    pass\n\n"),
        ("nested.py/x/baz.py", 'def baz(delimiter=", ", type=str):\n    pass\n\n'),
        ("nested.py/error.py", "def baz_error()" + "bug:\n    pass\n\n"),
        (
            "methods.py",
            textwrap.dedent(
                """
        class MyClass:
            def __init__(self, a):
                self.a = a

            def method1(self, a=1):
                pass
        """
            ),
        ),
        (
            "async.py",
            textwrap.dedent(
                """
            async def async_func(a, b, c):
                pass

            class MyAsyncClass:
                async def async_method(a, b, c):
                    pass
            """
            ).strip(),
        ),
    ):
        p = pathlib.Path(tmpdir / path)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(content, "utf-8")
    return tmpdir


@pytest.mark.parametrize(
    "args,expected",
    (
        (["foo1", "--silent"], "# File: foo.py Line: 1\ndef foo1():\n    pass\n\n"),
        (
            ["foo*", "--silent"],
            "# File: foo.py Line: 1\ndef foo1():\n    pass\n\n# File: foo.py Line: 4\n@decorated\ndef foo2():\n    pass\n\n",
        ),
        (
            ["BarClass", "--silent"],
            "# File: bar.py Line: 1\nclass BarClass:\n    pass\n\n",
        ),
        (
            ["baz", "--silent"],
            '# File: nested.py/x/baz.py Line: 1\ndef baz(delimiter=", ", type=str):\n    pass\n\n',
        ),
        (
            ["async_func", "--silent"],
            "# File: async.py Line: 1\nasync def async_func(a, b, c):\n    pass\n\n",
        ),
        # The -f option
        (
            ["baz", "-f", "nested.py/x/baz.py", "--silent"],
            '# File: nested.py/x/baz.py Line: 1\ndef baz(delimiter=", ", type=str):\n    pass\n\n',
        ),
        # The -d option
        (
            ["baz", "-d", "nested.py", "--silent"],
            '# File: nested.py/x/baz.py Line: 1\ndef baz(delimiter=", ", type=str):\n    pass\n\n',
        ),
        # The -d option with -x to exclude
        (
            ["baz", "-d", "nested.py", "-x", "nested.py/x/", "--silent"],
            "",
        ),
        # -x to exclude top level directory
        (["baz", "-x", "nested.py", "--silent"], ""),
        # Classes
        (
            ["MyClass", "--silent"],
            "# File: methods.py Line: 2\n"
            "class MyClass:\n"
            "    def __init__(self, a):\n"
            "        self.a = a\n"
            "\n"
            "    def method1(self, a=1):\n"
            "        pass\n"
            "\n",
        ),
        (
            ["MyClass.__init__", "--silent"],
            "# File: methods.py Class: MyClass Line: 3\n"
            "    def __init__(self, a):\n"
            "        self.a = a\n"
            "\n",
        ),
        (
            ["MyClass.*", "--silent"],
            "# File: methods.py Class: MyClass Line: 3\n"
            "    def __init__(self, a):\n"
            "        self.a = a\n"
            "\n"
            "# File: methods.py Class: MyClass Line: 6\n"
            "    def method1(self, a=1):\n"
            "        pass\n"
            "\n",
        ),
        (
            ["*.method*", "--silent"],
            "# File: methods.py Class: MyClass Line: 6\n"
            "    def method1(self, a=1):\n"
            "        pass\n"
            "\n",
        ),
        (
            ["*.async_method", "--silent"],
            (
                "# File: async.py Class: MyAsyncClass Line: 5\n"
                "    async def async_method(a, b, c):\n"
                "        pass\n"
                "\n"
            ),
        ),
    ),
)
def test_fixture(directory_full_of_code, monkeypatch, args, expected):
    runner = CliRunner()
    monkeypatch.chdir(directory_full_of_code)
    result = runner.invoke(cli, args, catch_exceptions=False)
    assert result.exit_code == 0
    assert result.stdout == expected


@pytest.mark.parametrize(
    "args,expected",
    (
        (
            ["foo*", "--silent"],
            "# File: foo.py Line: 1\n"
            "def foo1():\n"
            "\n"
            "# File: foo.py Line: 5\n"
            "def foo2():",
        ),
        (["BarClass", "--silent"], "# File: bar.py Line: 1\n" "class BarClass:"),
        (
            ["baz", "--silent"],
            (
                "# File: nested.py/x/baz.py Line: 1\n"
                'def baz(delimiter=", ", type=str):'
            ),
        ),
        # Tests for the --module option
        (
            ["-m", "contextlib", "suppress", "--silent", "-sn"],
            ("class suppress(AbstractContextManager):"),
        ),
    ),
)
def test_symbex_symbols(directory_full_of_code, monkeypatch, args, expected):
    runner = CliRunner()
    monkeypatch.chdir(directory_full_of_code)
    result = runner.invoke(cli, args + ["-s"], catch_exceptions=False)
    assert result.exit_code == 0
    # Here expected is just the first two lines
    assert result.stdout.strip() == expected


def test_errors(directory_full_of_code, monkeypatch):
    # Test without --silent to see errors
    runner = CliRunner(mix_stderr=False)
    monkeypatch.chdir(directory_full_of_code)
    result = runner.invoke(cli, ["baz"], catch_exceptions=False)
    assert result.exit_code == 0
    expected = (
        "# File: nested.py/x/baz.py Line: 1\n"
        'def baz(delimiter=", ", type=str):\n'
        "    pass\n\n"
    )
    assert result.stdout == expected
    # This differs between different Python versions
    assert result.stderr.startswith("# Syntax error in nested.py/error.py:")


def test_read_file_with_encoding(tmpdir):
    # https://github.com/simonw/symbex/issues/18#issuecomment-1597546242
    path = tmpdir / "encoded.py"
    path.write_binary(
        b"# coding: iso-8859-5\n# (Unlikely to be the default encoding for most testers.)\n"
        b"# \xb1\xb6\xff\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef <- Cyrillic characters\n"
        b'u = "\xae\xe2\xf0\xc4"\n'
    )
    text = read_file(path)
    assert text == (
        "# coding: iso-8859-5\n"
        "# (Unlikely to be the default encoding for most testers.)\n"
        "# БЖџрстуфхцчшщъыьэюя <- Cyrillic characters\n"
        'u = "Ўт№Ф"\n'
    )


def test_quoted_string():
    # Single line, no quotes
    assert quoted_string("Hello, World!") == '"Hello, World!"'

    # Single line, with quotes
    assert quoted_string('Hello, "World"!') == '"Hello, \\"World\\"!"'

    # Multiline, no quotes
    multiline_str = "Hello,\nWorld!"
    expected_result = '"""Hello,\nWorld!"""'
    assert quoted_string(multiline_str) == expected_result

    # Multiline, with triple quotes
    multiline_str = '''Hello,
"World",
Here are some triple quotes: """ '''
    expected_multiline_result = (
        '"""Hello,\n"World",\nHere are some triple quotes: \\"\\"\\" """'
    )
    quoted_multiline_result = quoted_string(multiline_str)
    assert quoted_multiline_result == expected_multiline_result

    # Empty string
    assert quoted_string("") == '""'
1e411123e07b1e7ff12ebe07ce1a78f659acfe9881f8c4fa2858f2c0396ecc6c
# Tests for "symbex -s", using content of example_code.py
import pathlib
import pytest
import re
from click.testing import CliRunner

from symbex.cli import cli


@pytest.fixture
def symbols_text():
    runner = CliRunner()
    args = ["-s", "-f", str(pathlib.Path(__file__).parent / "example_symbols.py")]
    result = runner.invoke(cli, args, catch_exceptions=False)
    assert result.exit_code == 0
    return result.stdout


@pytest.mark.parametrize(
    "name,expected",
    (
        ("func_no_args", "def func_no_args()"),
        ("func_positional_args", "def func_positional_args(a, b, c)"),
        ("async_func", "async def async_func(a, b, c)"),
        ("func_default_args", "def func_default_args(a, b=2, c=3)"),
        ("func_arbitrary_positional_args", "def func_arbitrary_positional_args(*args)"),
        ("func_arbitrary_keyword_args", "def func_arbitrary_keyword_args(**kwargs)"),
        ("func_arbitrary_args", "def func_arbitrary_args(*args, **kwargs)"),
        ("func_positional_only_args", "def func_positional_only_args(a, /, b, c)"),
        ("func_keyword_only_args", "def func_keyword_only_args(a, *, b, c)"),
        ("func_type_annotations", "def func_type_annotations(a: int, b: str) -> bool"),
        ("ClassNoBase", "class ClassNoBase"),
        ("ClassSingleBase", "class ClassSingleBase(int)"),
        ("ClassMultipleBase", "class ClassMultipleBase(int, str)"),
        ("ClassWithMeta", "class ClassWithMeta(metaclass=type)"),
        (
            "function_with_non_pep_0484_annotation",
            "def function_with_non_pep_0484_annotation(x: ?, xx: ?, yy: ?, y: ?, zz: float) -> ?",
        ),
        (
            "complex_annotations",
            "complex_annotations(code: str, symbols: Iterable[str]) -> List[Tuple[(AST, Optional[str])]]",
        ),
    ),
)
def test_symbols(name, expected, symbols_text):
    # For error reporting try and find the relevant bit
    likely_line = [
        line
        for line in symbols_text.split("\n")
        if (f"{name}(" in line or line.startswith(f"class {name}"))
    ][0]
    assert expected in symbols_text, "\nexpected:\t{}\ngot:\t\t{}".format(
        expected, likely_line
    )
    # Special case to ensure we don't get ClassNoBase()
    assert "ClassNoBase()" not in symbols_text


def test_method_symbols():
    runner = CliRunner()
    args = [
        "*.async*",
        "-s",
        "-f",
        str(pathlib.Path(__file__).parent / "example_symbols.py"),
    ]
    result = runner.invoke(cli, args, catch_exceptions=False)
    assert result.exit_code == 0
    assert result.stdout == (
        "# File: tests/example_symbols.py Class: ClassWithMethods Line: 91\n"
        "    async def async_method(a, b, c):\n"
        "\n"
    )


def test_docstrings():
    runner = CliRunner()
    args = [
        "*.*",
        "*",
        "--documented",
        "--docstrings",
        "-f",
        str(pathlib.Path(__file__).parent / "example_symbols.py"),
    ]
    result = runner.invoke(cli, args, catch_exceptions=False)
    assert result.exit_code == 0
    expected = """
# File: tests/example_symbols.py Line: X
def func_no_args():
    "This has a single line docstring"

# File: tests/example_symbols.py Line: X
def func_positional_args(a, b, c):
    \"\"\"This has a
    multi-line docstring\"\"\"

# File: tests/example_symbols.py Class: ClassForTypedTests Line: X
    def method_fully_typed(self, a: int, b: str) -> bool:
        "Single line"

# File: tests/example_symbols.py Class: ClassForTypedTests Line: X
    def method_partially_typed(self, a: int, b) -> bool:
        \"\"\"Multiple
        lines\"\"\"
    """.strip()
    actual = result.stdout.strip()
    # Replace 'Line \d' with 'Line X' before comparison using re
    actual = re.sub(r"Line: \d+", "Line: X", actual)
    assert actual == expected


@pytest.mark.parametrize("no_file", (False, True))
def test_imports(no_file):
    runner = CliRunner()
    args = [
        "func_arbitrary*",
        "--imports",
        "-s",
        "-d",
        str(pathlib.Path(__file__).parent),
    ] + (["--no-file"] if no_file else [])
    result = runner.invoke(cli, args, catch_exceptions=False)
    assert result.exit_code == 0
    expected = """
# File: tests/example_symbols.py Line: 28
# from example_symbols import func_arbitrary_positional_args
def func_arbitrary_positional_args(*args):

# File: tests/example_symbols.py Line: 33
# from example_symbols import func_arbitrary_keyword_args
def func_arbitrary_keyword_args(**kwargs):

# File: tests/example_symbols.py Line: 38
# from example_symbols import func_arbitrary_args
def func_arbitrary_args(*args, **kwargs):
    """.strip()
    if no_file:
        lines = expected.split("\n")
        lines = [line for line in lines if not line.startswith("# File: ")]
        expected = "\n".join(lines)
    assert result.output.strip() == expected
90f3d6b279a73191a0cd3ddf743e73a85b5cc95870ac84504a912acbbf189c5e
# Tests for "symbex --async / --class / --typed etc"
import pathlib
import pytest
from click.testing import CliRunner

from symbex.cli import cli


@pytest.mark.parametrize(
    "args,expected",
    (
        (
            ["--function"],
            [
                "def func_no_args",
                "def func_positional_args",
                "async def async_func",
                "def func_default_args",
                "def func_arbitrary_positional_args",
                "def func_arbitrary_keyword_args",
                "def func_arbitrary_args",
                "def func_positional_only_args",
                "def func_keyword_only_args",
                "def func_type_annotations",
                "def function_with_non_pep_0484_annotation",
                "def complex_annotations",
                "def func_fully_typed",
                "async def async_func_fully_typed",
                "def func_partially_typed",
                "def func_partially_typed_no_typed_return",
                "def func_partially_typed_only_typed_return",
                "def func_typed_no_params",
                "def _private",
            ],
        ),
        (
            ["--class"],
            [
                "class ClassNoBase",
                "class ClassSingleBase",
                "class ClassMultipleBase",
                "class ClassWithMeta",
                "class ClassWithMethods",
                "class ClassForTypedTests",
                "class _PrivateClass",
            ],
        ),
        (
            ["--async"],
            [
                "async def async_func",
                "async def async_func_fully_typed",
            ],
        ),
        (
            ["--unasync"],
            [
                "def func_no_args",
                "def func_positional_args",
                "def func_default_args",
                "def func_arbitrary_positional_args",
                "def func_arbitrary_keyword_args",
                "def func_arbitrary_args",
                "def func_positional_only_args",
                "def func_keyword_only_args",
                "def func_type_annotations",
                "def function_with_non_pep_0484_annotation",
                "def complex_annotations",
                "def func_fully_typed",
                "def func_partially_typed",
                "def func_partially_typed_no_typed_return",
                "def func_partially_typed_only_typed_return",
                "def func_typed_no_params",
                "def _private",
            ],
        ),
        # This doesn't make sense, so should return []
        (
            ["--async", "--class"],
            [],
        ),
        # Various typing options
        (
            ["--typed"],
            [
                "def func_type_annotations",
                "def function_with_non_pep_0484_annotation",
                "def complex_annotations",
                "def func_fully_typed",
                "async def async_func_fully_typed",
                "def func_partially_typed",
                "def func_partially_typed_no_typed_return",
                "def func_partially_typed_only_typed_return",
                "def func_typed_no_params",
                "def _private",
            ],
        ),
        (
            ["--typed", "--async"],
            [
                "async def async_func_fully_typed",
            ],
        ),
        (
            ["--untyped"],
            [
                "def func_no_args",
                "def func_positional_args",
                "async def async_func",
                "def func_default_args",
                "def func_arbitrary_positional_args",
                "def func_arbitrary_keyword_args",
                "def func_arbitrary_args",
                "def func_positional_only_args",
                "def func_keyword_only_args",
            ],
        ),
        (
            ["--partially-typed"],
            [
                "def func_partially_typed",
                "def func_partially_typed_no_typed_return",
                "def func_partially_typed_only_typed_return",
            ],
        ),
        (
            ["--fully-typed"],
            [
                "def func_type_annotations",
                "def function_with_non_pep_0484_annotation",
                "def complex_annotations",
                "def func_fully_typed",
                "async def async_func_fully_typed",
                "def func_typed_no_params",
                "def _private",
            ],
        ),
        # Test against methods
        (
            ["--typed", "*.*"],
            [
                "def method_types",
                "def __init__",
                "def method_fully_typed",
                "def method_partially_typed",
            ],
        ),
        (
            ["--untyped", "*.*"],
            [
                "def __init__",
                "def method_positional_only_args",
                "def method_keyword_only_args",
                "async def async_method",
                "def method_untyped",
                "def _private_method",
            ],
        ),
        (
            ["--fully-typed", "*.*"],
            ["def method_types", "def __init__", "def method_fully_typed"],
        ),
        (
            ["--fully-typed", "--no-init", "*.*"],
            [
                "def method_types",
                "def method_fully_typed",
            ],
        ),
        (
            ["--partially-typed", "*.*"],
            ["def method_partially_typed"],
        ),
        # Documented and undocumented
        (
            ["--documented"],
            [
                "def func_no_args",
                "def func_positional_args",
            ],
        ),
        (
            ["--undocumented", "func_arbitrary_*"],
            [
                "def func_arbitrary_positional_args",
                "def func_arbitrary_keyword_args",
                "def func_arbitrary_args",
            ],
        ),
        (
            ["--documented", "*.*"],
            [
                "def method_fully_typed",
                "def method_partially_typed",
            ],
        ),
        (
            ["--undocumented", "*.method_*"],
            [
                "def method_types",
                "def method_positional_only_args",
                "def method_keyword_only_args",
                "def method_untyped",
            ],
        ),
        # Private and public and dunder
        (
            ["--public"],
            [
                "def func_no_args",
                "def func_positional_args",
                "async def async_func",
                "def func_default_args",
                "def func_arbitrary_positional_args",
                "def func_arbitrary_keyword_args",
                "def func_arbitrary_args",
                "def func_positional_only_args",
                "def func_keyword_only_args",
                "def func_type_annotations",
                "class ClassNoBase",
                "class ClassSingleBase",
                "class ClassMultipleBase",
                "class ClassWithMeta",
                "class ClassWithMethods",
                "def function_with_non_pep_0484_annotation",
                "def complex_annotations",
                "def func_fully_typed",
                "async def async_func_fully_typed",
                "def func_partially_typed",
                "def func_partially_typed_no_typed_return",
                "def func_partially_typed_only_typed_return",
                "def func_typed_no_params",
                "class ClassForTypedTests",
            ],
        ),
        (
            ["--public", "*.*"],
            [
                "def __init__",
                "def method_types",
                "def method_positional_only_args",
                "def method_keyword_only_args",
                "async def async_method",
                "def __init__",
                "def method_fully_typed",
                "def method_partially_typed",
                "def method_untyped",
            ],
        ),
        (["--private", "*.*"], ["def _private_method"]),
        (
            ["--public", "--class"],
            [
                "class ClassNoBase",
                "class ClassSingleBase",
                "class ClassMultipleBase",
                "class ClassWithMeta",
                "class ClassWithMethods",
                "class ClassForTypedTests",
            ],
        ),
        (
            ["--private", "--class"],
            [
                "class _PrivateClass",
            ],
        ),
        (["--private"], ["def _private", "class _PrivateClass"]),
        (["--dunder", "*.*"], ["def __init__", "def __init__"]),
    ),
)
def test_filters(args, expected):
    runner = CliRunner()
    full_args = args + [
        "-s",
        "-f",
        str(pathlib.Path(__file__).parent / "example_symbols.py"),
    ]
    result = runner.invoke(
        cli,
        full_args,
        catch_exceptions=False,
    )
    assert result.exit_code == 0
    # Remove # File: lines and blank lines
    lines = [
        line.strip()
        for line in result.stdout.splitlines()
        if line.strip() and not line.startswith("# File:")
    ]
    # We only match up to the opening "(" or ":"
    defs = [line.split("(")[0].split(":")[0] for line in lines]
    assert defs == expected

    # Test the --count option too
    expected_count = len(expected)
    result2 = runner.invoke(
        cli,
        full_args + ["--count"],
        catch_exceptions=False,
    )
    assert result2.exit_code == 0
    assert result2.stdout.strip() == str(expected_count)

    # And the --check option
    result3 = runner.invoke(
        cli,
        full_args + ["--check"],
        catch_exceptions=False,
    )
    if expected:
        assert result3.exit_code == 1
    else:
        assert result3.exit_code == 0
475bbf02f54d197448a7f2a02add49fca7e54d7b14e058095ceed1a04f895e5d
from click.testing import CliRunner
from symbex.cli import cli
import pathlib
import pytest
import sys
from unittest.mock import patch
import yaml


@pytest.mark.parametrize(
    "test", yaml.safe_load(open(pathlib.Path(__file__).parent / "replace_tests.yaml"))
)
def test_replace(test):
    original, stdin, args, expected = (
        test["original"],
        test["stdin"],
        test["args"],
        test["expected"],
    )
    runner = CliRunner()
    with runner.isolated_filesystem() as root:
        path = pathlib.Path(root) / "code.py"
        path.write_text(original, "utf-8")
        result = runner.invoke(cli, args, input=stdin, catch_exceptions=False)
        modified = path.read_text("utf-8")
    assert result.exit_code == 0
    assert modified.strip() == expected.strip()


@pytest.mark.parametrize(
    "files,args,error",
    (
        (
            {"foo.py": "def bar(): pass"},
            ["baz"],
            "Error: --replace only works with a single match, got 0",
        ),
        (
            {"foo.py": "def bar(): pass", "baz/foo.py": "def bar(): pass"},
            ["bar"],
            "Error: --replace only works with a single match, got 2",
        ),
        (
            {"foo.py": "def bar(): pass"},
            ["bar", "-s"],
            "Error: --replace cannot be used with --signatures",
        ),
        (
            {"foo.py": "def bar(): pass"},
            ["bar"],
            "Error: No input for --replace found on stdin",
        ),
    ),
)
def test_replace_errors(files, args, error):
    runner = CliRunner()
    with patch("symbex.cli.sys.stdin.isatty", return_value=True):
        with runner.isolated_filesystem() as root:
            root = pathlib.Path(root)
            for path, code in files.items():
                (root / path).parent.mkdir(parents=True, exist_ok=True)
                (root / path).write_text(code, "utf-8")
            result = runner.invoke(cli, args + ["--replace"], catch_exceptions=False)
    assert result.exit_code == 1
    assert result.output.strip() == error


INPUT_CODE = """
def foo(bar):
    return 1 + 2 + 3

class Foo:
    def bar(self):
        return 1 + 2 + 3
"""
REXEC_EXPECTED = """
DEF FOO(BAR):
    RETURN 1 + 2 + 3


class Foo:
    def bar(self):
        return 1 + 2 + 3
"""

TO_UPPER = """
import sys

print(sys.stdin.read().upper())
"""


def test_replace_rexec():
    runner = CliRunner()
    with runner.isolated_filesystem() as root:
        path = pathlib.Path(root) / "code.py"
        path.write_text(INPUT_CODE, "utf-8")
        to_upper = pathlib.Path(root) / "to_upper.py"
        to_upper.write_text(TO_UPPER, "utf-8")
        long_command = " ".join(
            [
                sys.executable,
                str(to_upper),
            ]
        )
        args = ["foo", "--rexec", long_command]
        result = runner.invoke(cli, args, catch_exceptions=False)
        modified = path.read_text("utf-8")
    assert result.exit_code == 0
    assert modified.strip() == REXEC_EXPECTED.strip()


def test_replace_rexec_error():
    runner = CliRunner()
    with runner.isolated_filesystem() as root:
        path = pathlib.Path(root) / "code.py"
        path.write_text(INPUT_CODE, "utf-8")
        to_upper = pathlib.Path(root) / "to_upper.py"
        to_upper.write_text("exit(1)", "utf-8")
        long_command = " ".join(
            [
                sys.executable,
                str(to_upper),
            ]
        )
        args = ["foo", "--rexec", long_command]
        result = runner.invoke(cli, args, catch_exceptions=False)
        not_modified = path.read_text("utf-8")
    assert result.exit_code == 1
    assert not_modified.strip() == INPUT_CODE.strip()
0a228a38ec9ce8d7bfee2833348b4c6696b923aa35d8b11b20fad053d6a5ed1a
import fnmatch
import ast
from ast import literal_eval, parse, AST, AsyncFunctionDef, FunctionDef, ClassDef
import codecs
from dataclasses import dataclass
from itertools import zip_longest
from pathlib import Path
import re
import textwrap
from typing import Iterable, List, Optional, Tuple


def find_symbol_nodes(
    code: str, filename: str, symbols: Iterable[str]
) -> List[Tuple[AST, Optional[str]]]:
    "Returns ast Nodes matching symbols"
    # list of (AST, None-or-class-name)
    matches = []
    module = parse(code)
    for node in module.body:
        if not isinstance(node, (ClassDef, FunctionDef, AsyncFunctionDef)):
            continue
        name = getattr(node, "name", None)
        if match(name, symbols):
            matches.append((node, None))
        # If it's a class search its methods too
        if isinstance(node, ClassDef):
            for child in node.body:
                if isinstance(child, (FunctionDef, AsyncFunctionDef)):
                    qualified_name = f"{name}.{child.name}"
                    if match(qualified_name, symbols):
                        matches.append((child, name))

    return matches


def code_for_node(
    code: str, node: AST, class_name: str, signatures: bool, docstrings: bool
) -> Tuple[str, int]:
    "Returns the code for a given node"
    lines = code.split("\n")
    start = None
    end = None
    if signatures:
        if isinstance(node, (FunctionDef, AsyncFunctionDef)):
            definition, lineno = function_definition(node), node.lineno
            if class_name:
                definition = "    " + definition
            definition = add_docstring(definition, node, docstrings, bool(class_name))
            return definition, lineno
        elif isinstance(node, ClassDef):
            definition, lineno = class_definition(node), node.lineno
            definition = add_docstring(definition, node, docstrings, bool(class_name))
            return definition, lineno
        else:
            # Not a function or class, fall back on just the line
            start = node.lineno - 1
            end = node.lineno
    else:
        # If the node has decorator_list, include those too
        if getattr(node, "decorator_list", None):
            start = node.decorator_list[0].lineno - 1
        else:
            start = node.lineno - 1
        end = node.end_lineno
    output = "\n".join(lines[start:end])
    # If it's in a class, indent it 4 spaces
    return output, start + 1


def add_docstring(definition: str, node: AST, docstrings: bool, is_method: bool) -> str:
    if not docstrings:
        return definition
    docstring = ast.get_docstring(node)
    if not docstring:
        return definition
    docstring = quoted_string(docstring)
    wrapped = textwrap.indent(docstring, "        " if is_method else "    ")
    return f"{definition}\n{wrapped}"


def match(name: str, symbols: Iterable[str]) -> bool:
    "Returns True if name matches any of the symbols, resolving wildcards"
    if name is None:
        return False
    for search in symbols:
        if "*" not in search:
            # Exact matches only
            if name == search:
                return True
        elif search.count(".") == 1:
            # wildcards are supported either side of the dot
            if "." in name:
                class_match, method_match = search.split(".")
                class_name, method_name = name.split(".")
                if fnmatch.fnmatch(class_name, class_match) and fnmatch.fnmatch(
                    method_name, method_match
                ):
                    return True
        else:
            if fnmatch.fnmatch(name, search) and "." not in name:
                return True

    return False


def function_definition(function_node: AST):
    function_name = function_node.name

    all_args = [
        *function_node.args.posonlyargs,
        *function_node.args.args,
        *function_node.args.kwonlyargs,
    ]

    # For position only args like "def foo(a, /, b, c)"
    # we can look at the length of args.posonlyargs to see
    # if any are set and, if so, at what index the `/` should go
    position_of_slash = len(function_node.args.posonlyargs)

    # For func_keyword_only_args(a, *, b, c) the length of
    # the kwonlyargs tells us how many spaces back from the
    # end the star should be displayed
    position_of_star = len(all_args) - len(function_node.args.kwonlyargs)

    # function_node.args.defaults may have defaults
    # corresponding to function_node.args.args - but
    # if defaults has 2 and args has 3 then those
    # defaults correspond to the last two args
    defaults = [None] * (len(all_args) - len(function_node.args.defaults))
    for default in function_node.args.defaults:
        try:
            value = literal_eval(default)
            if isinstance(value, str):
                value = f'"{value}"'
        except ValueError:
            value = getattr(default, "id", "...")
        defaults.append(value)

    arguments = []

    for i, (arg, default) in enumerate(zip_longest(all_args, defaults)):
        if position_of_slash and i == position_of_slash:
            arguments.append("/")
        if position_of_star and i == position_of_star:
            arguments.append("*")
        arg_str = arg.arg
        if arg.annotation:
            arg_str += f": {annotation_definition(arg.annotation)}"

        if default:
            arg_str = f"{arg_str}={default}"

        arguments.append(arg_str)

    if function_node.args.vararg:
        arguments.append(f"*{function_node.args.vararg.arg}")

    if function_node.args.kwarg:
        arguments.append(f"**{function_node.args.kwarg.arg}")

    arguments_str = ", ".join(arguments)

    return_annotation = ""
    if function_node.returns:
        return_annotation = f" -> {annotation_definition(function_node.returns)}"

    def_ = "def "
    if isinstance(function_node, AsyncFunctionDef):
        def_ = "async def "

    return f"{def_}{function_name}({arguments_str}){return_annotation}:"


def class_definition(class_def):
    # Base classes
    base_classes = []
    for base in class_def.bases:
        if getattr(base, "id", None):
            base_classes.append(base.id)
    base_classes_str = ", ".join(base_classes)

    # Keywords (including metaclass)
    keywords = {k.arg: getattr(k.value, "id", str(k.value)) for k in class_def.keywords}
    metaclass = keywords.pop("metaclass", None)
    keyword_str = ", ".join([f"{k}=..." for k in keywords])

    if base_classes_str and keyword_str:
        signature = f"{base_classes_str}, {keyword_str}"
    elif base_classes_str:
        signature = base_classes_str
    elif keyword_str:
        signature = keyword_str
    else:
        signature = ""

    if metaclass:
        sep = ", " if signature else ""
        signature = f"{signature}{sep}metaclass={metaclass}"

    if signature:
        signature = f"({signature})"

    class_definition = f"class {class_def.name}{signature}:"

    return class_definition


def annotation_definition(annotation: AST) -> str:
    if annotation is None:
        return ""
    elif isinstance(annotation, ast.Name):
        return annotation.id
    elif isinstance(annotation, ast.Subscript):
        value = annotation_definition(annotation.value)
        slice = annotation_definition(annotation.slice)
        return f"{value}[{slice}]"
    elif isinstance(annotation, ast.Index):
        return annotation_definition(annotation.value)
    elif isinstance(annotation, ast.Tuple):
        elements = ", ".join(annotation_definition(e) for e in annotation.elts)
        return f"({elements})"
    else:
        return "?"


def read_file(path):
    encoding_pattern = r"^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)"
    default_encoding = "utf-8"

    with open(path, "r", encoding=default_encoding, errors="ignore") as f:
        first_512_bytes = f.read(512)
        first_two_lines = "\n".join(first_512_bytes.split("\n")[:2])

        match = re.search(encoding_pattern, first_two_lines, re.MULTILINE)
        if match:
            encoding = match.group(1)
        else:
            encoding = default_encoding

    try:
        with codecs.open(path, "r", encoding=encoding) as f:
            content = f.read()
    except LookupError:
        # If the detected encoding is not valid, try again with utf-8
        with codecs.open(path, "r", encoding=default_encoding) as f:
            content = f.read()

    return content


@dataclass
class TypeSummary:
    fully: bool
    partially: bool


def type_summary(node: AST) -> Optional[TypeSummary]:
    if not isinstance(node, (FunctionDef, AsyncFunctionDef)):
        return None
    all_args = [
        *node.args.posonlyargs,
        *node.args.args,
        *node.args.kwonlyargs,
    ]
    num_arguments = len(all_args)
    has_untyped_self = False
    typed_args = []
    first = True
    for arg in all_args:
        # Special case if the first argument is self - note that we do not
        # check that we are a class method but ideally we would do that
        if first and arg.arg == "self":
            has_untyped_self = True
            continue
        if arg.annotation:
            typed_args.append(arg)
        first = False

    return_is_typed = bool(node.returns)

    partially = len(typed_args) > 0 or return_is_typed
    fully = False
    if len(typed_args) == num_arguments and return_is_typed:
        fully = True
    # Something is fully typed if either EVERY arg is typed
    # or all arguments except for the untyped self are typed
    if has_untyped_self and len(typed_args) == num_arguments - 1 and return_is_typed:
        fully = True
    # Another special case: __init__() doesn't need a return type
    if node.name == "__init__":
        if (has_untyped_self and len(typed_args) == num_arguments - 1) or len(
            typed_args
        ) == num_arguments:
            # Doesn't matter if we have a return type
            fully = True

    return TypeSummary(
        fully=fully,
        partially=partially,
    )


def quoted_string(s):
    if "\n" in s:
        # Escape triple double quotes
        s = s.replace('"""', '\\"\\"\\"')
        return f'"""{s}"""'
    else:
        # Escape double quotes
        s = s.replace('"', '\\"')
        return f'"{s}"'


def import_line_for_function(
    function_name: str, filepath: str, possible_root_dirs: List[str]
) -> str:
    """
    Returns eg 'from foo.bar import baz' if filepath is /Users/dev/foo/bar.py
    and function_name is baz and possible_root_dirs is a list that contains
    /Users/dev
    """
    filepath = Path(filepath).resolve()
    filename_without_extension = filepath.stem

    # Check for matches in possible_root_dirs
    for root_dir in possible_root_dirs:
        root_dir = Path(root_dir).resolve()
        try:
            relative_path = filepath.relative_to(root_dir)
            # Convert path separators to dots and assemble import line
            import_path = ".".join(
                relative_path.parts[:-1] + (filename_without_extension,)
            )
            return f"from {import_path} import {function_name}"
        except ValueError:
            # If ValueError is raised, the filepath is not under the root_dir
            continue

    # If none of the root_dirs matched return a relative import
    return f"from .{filename_without_extension} import {function_name}"
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
9060a5b693bbf728d5a5711eac995a7b949cdb690ea777afcb4f1dcb4499714d
import ast
import click
import csv
import dataclasses
import importlib
import inspect
import json
import pathlib
import site
import subprocess
import sys
from typing import TextIO, Iterable, Literal, Tuple

from .lib import (
    code_for_node,
    find_symbol_nodes,
    import_line_for_function,
    read_file,
    type_summary,
)


@dataclasses.dataclass
class Output:
    symbol_id: str
    output_identifier_line: str
    output_import_line: str
    snippet: str


@click.command()
@click.version_option()
@click.argument("symbols", nargs=-1)
@click.option(
    "files",
    "-f",
    "--file",
    type=click.Path(file_okay=True, dir_okay=False),
    multiple=True,
    help="Files to search",
)
@click.option(
    "directories",
    "-d",
    "--directory",
    type=click.Path(file_okay=False, dir_okay=True, resolve_path=True),
    multiple=True,
    help="Directories to search",
)
@click.option("--stdlib", is_flag=True, help="Search the Python standard library")
@click.option(
    "excludes",
    "-x",
    "--exclude",
    type=click.Path(file_okay=False, dir_okay=True, resolve_path=True),
    multiple=True,
    help="Directories to exclude",
)
@click.option(
    "-s",
    "--signatures",
    is_flag=True,
    help="Show just function and class signatures",
)
@click.option(
    "-n",
    "--no-file",
    is_flag=True,
    help="Don't include the # File: comments in the output",
)
@click.option(
    "-i",
    "--imports",
    is_flag=True,
    help="Show 'from x import y' lines for imported symbols",
)
@click.option(
    "modules", "-m", "--module", multiple=True, help="Modules to search within"
)
@click.option(
    "sys_paths",
    "--sys-path",
    multiple=True,
    help="Calculate imports relative to these on sys.path",
)
@click.option(
    "--docs",
    "--docstrings",
    is_flag=True,
    help="Show function and class signatures plus docstrings",
)
@click.option(
    "--count",
    is_flag=True,
    help="Show count of matching symbols",
)
@click.option(
    "--silent",
    is_flag=True,
    help="Silently ignore Python files with parse errors",
)
@click.option(
    "--function",
    is_flag=True,
    help="Filter functions",
)
@click.option(
    "async_",
    "--async",
    is_flag=True,
    help="Filter async functions",
)
@click.option(
    "unasync",
    "--unasync",
    is_flag=True,
    help="Filter non-async functions",
)
@click.option(
    "class_",
    "--class",
    is_flag=True,
    help="Filter classes",
)
@click.option(
    "--documented",
    is_flag=True,
    help="Filter functions with docstrings",
)
@click.option(
    "--undocumented",
    is_flag=True,
    help="Filter functions without docstrings",
)
@click.option(
    "--public",
    is_flag=True,
    help="Filter for symbols without a _ prefix",
)
@click.option(
    "--private",
    is_flag=True,
    help="Filter for symbols with a _ prefix",
)
@click.option(
    "--dunder",
    is_flag=True,
    help="Filter for symbols matching __*__",
)
@click.option(
    "--typed",
    is_flag=True,
    help="Filter functions with type annotations",
)
@click.option(
    "--untyped",
    is_flag=True,
    help="Filter functions without type annotations",
)
@click.option(
    "--partially-typed",
    is_flag=True,
    help="Filter functions with partial type annotations",
)
@click.option(
    "--fully-typed",
    is_flag=True,
    help="Filter functions with full type annotations",
)
@click.option(
    "--no-init",
    is_flag=True,
    help="Filter to exclude any __init__ methods",
)
@click.option(
    "--check", is_flag=True, help="Exit with non-zero code if any matches found"
)
@click.option(
    "--replace",
    is_flag=True,
    help="Replace matching symbol with text from stdin",
)
@click.option("--rexec", help="Replace with the result of piping to this tool")
# Output options
@click.option("csv_", "--csv", is_flag=True, help="Output as CSV")
@click.option("--tsv", is_flag=True, help="Output as TSV")
@click.option("json_", "--json", is_flag=True, help="Output as JSON")
@click.option("--nl", is_flag=True, help="Output as newline-delimited JSON")
@click.option("--id-prefix", help="Prefix to use for symbol IDs")
def cli(
    symbols,
    files,
    directories,
    stdlib,
    excludes,
    signatures,
    no_file,
    imports,
    modules,
    sys_paths,
    docs,
    count,
    silent,
    function,
    async_,
    unasync,
    class_,
    documented,
    undocumented,
    public,
    private,
    dunder,
    typed,
    untyped,
    partially_typed,
    fully_typed,
    no_init,
    check,
    replace,
    rexec,
    csv_,
    tsv,
    json_,
    nl,
    id_prefix,
):
    """
    Find symbols in Python code and print the code for them.

    Example usage:

    \b
        # Search current directory and subdirectories
        symbex my_function MyClass

    \b
        # Search using a wildcard
        symbex 'test_*'

    \b
        # Find a specific class method
        symbex 'MyClass.my_method'

    \b
        # Find class methods using wildcards
        symbex '*View.handle_*'

    \b
        # Search a specific file
        symbex MyClass -f my_file.py

    \b
        # Search within a specific directory and its subdirectories
        symbex Database -d ~/projects/datasette

    \b
        # View signatures for all symbols in current directory and subdirectories
        symbex -s

    \b
        # View signatures for all test functions
        symbex 'test_*' -s

    \b
        # View signatures for all async functions with type definitions
        symbex --async --typed -s

    \b
        # Count the number of --async functions in the project
        symbex --async --count

    \b
        # Replace my_function with a new implementation:
        echo "def my_function(a, b):
            # This is a replacement implementation
            return a + b + 3
        " | symbex my_function --replace

    \b
        # Replace my_function with the output of a command:
        symbex first_function --rexec "sed 's/^/# /'"
        # This uses sed to comment out the function body
    """
    # Only one of --json, --csv, --tsv, --nl
    output_formats = [csv_, tsv, json_, nl]
    if sum(output_formats) > 1:
        raise click.ClickException("Only one of --csv, --tsv, --json, --nl can be used")
    if id_prefix and not sum(output_formats):
        raise click.ClickException(
            "--id-prefix can only be used with --csv, --tsv, --json or --nl"
        )
    if id_prefix is None:
        id_prefix = ""

    if modules:
        module_dirs = []
        module_files = []
        for module in modules:
            try:
                mod = importlib.import_module(module)
                mod_path = pathlib.Path(inspect.getfile(mod))
                if mod_path.stem == "__init__":
                    module_dirs.append(mod_path.parent)
                else:
                    module_files.append(mod_path)
            except ModuleNotFoundError:
                raise click.ClickException("Module not found: {}".format(module))
        directories = [*directories, *module_dirs]
        files = [*files, *module_files]
        if module_dirs or module_files:
            if not symbols:
                symbols = ["*"]
            site_packages_dirs = site.getsitepackages()
            stdlib_dir = pathlib.Path(pathlib.__file__).parent
            sys_paths = [*site_packages_dirs, str(stdlib_dir), *sys_paths]

    if no_init:
        fully_typed = True
    if stdlib and not directories and not files:
        silent = True
    if stdlib:
        stdlib_folder = pathlib.Path(pathlib.__file__).parent.resolve()
        directories = [*directories, *[stdlib_folder]]
        if str(stdlib_folder) not in sys_paths:
            sys_paths = [*[str(stdlib_folder)], *sys_paths]
    if count or docs:
        signatures = True
    if imports and not symbols:
        signatures = True
    # Show --help if no filter options are provided:
    if not any(
        [
            symbols,
            signatures,
            async_,
            unasync,
            function,
            class_,
            documented,
            undocumented,
            public,
            private,
            dunder,
            typed,
            untyped,
            partially_typed,
            fully_typed,
            no_init,
            modules,
        ]
    ):
        ctx = click.get_current_context()
        click.echo(ctx.get_help())
        ctx.exit()

    if rexec:
        replace = True
        no_file = True

    if replace and signatures:
        raise click.ClickException("--replace cannot be used with --signatures")
    if replace:
        no_file = True
    # Default to '*' if --signatures or filters are provided without symbols
    if (
        any(
            [
                signatures,
                async_,
                unasync,
                function,
                class_,
                documented,
                undocumented,
                public,
                private,
                dunder,
                typed,
                untyped,
                partially_typed,
                fully_typed,
                no_init,
                modules,
            ]
        )
        and not symbols
    ):
        symbols = ["*"]
    if not files and not directories:
        directories = ["."]

    excludes = [pathlib.Path(exclude) for exclude in excludes]

    def iterate_files():
        yield from (pathlib.Path(f) for f in files)
        for directory in directories:
            for path in pathlib.Path(directory).rglob("*.py"):
                # Skip if path is inside any of 'excludes'
                if any(path.resolve().is_relative_to(exclude) for exclude in excludes):
                    continue
                if path.is_file():
                    yield path

    # If any --filters were supplied, handle them:
    if any(
        [
            async_,
            unasync,
            function,
            class_,
            documented,
            undocumented,
            public,
            private,
            dunder,
            typed,
            untyped,
            partially_typed,
            fully_typed,
            no_init,
        ]
    ):
        # Return just nodes matching filters
        def filter(node: ast.AST) -> bool:
            # Filters must ALL match
            if async_ and not isinstance(node, ast.AsyncFunctionDef):
                return False
            if function and not isinstance(
                node, (ast.FunctionDef, ast.AsyncFunctionDef)
            ):
                return False
            if unasync and not isinstance(node, ast.FunctionDef):
                return False
            if class_ and not isinstance(node, ast.ClassDef):
                return False
            if documented and not ast.get_docstring(node):
                return False
            if undocumented and ast.get_docstring(node):
                return False
            if public and node.name.startswith("_") and not is_dunder(node.name):
                return False
            if private and (is_dunder(node.name) or not node.name.startswith("_")):
                return False
            if dunder and not is_dunder(node.name):
                return False
            summary = type_summary(node)
            # if no summary, type filters all fail
            if not summary and (
                typed or untyped or partially_typed or fully_typed or no_init
            ):
                return False
            # Apply type filters
            if typed and not summary.partially:
                return False
            if untyped and summary.partially:
                return False
            if partially_typed and not (summary.partially and not summary.fully):
                return False
            if no_init and node.name == "__init__":
                return False
            if fully_typed and not summary.fully:
                return False
            return True

    else:
        # All nodes are allowed
        def filter(node: ast.AST) -> bool:
            return True

    pwd = pathlib.Path(".").resolve()
    num_matches = 0
    replace_matches = []

    def stuff_to_output():
        nonlocal num_matches
        for file in iterate_files():
            try:
                code = read_file(file)
            except UnicodeDecodeError as ex:
                if not silent:
                    click.secho(
                        f"# Unicode error in {file}: {ex}", err=True, fg="yellow"
                    )
                continue
            try:
                nodes = find_symbol_nodes(code, str(file), symbols)
            except SyntaxError as ex:
                if not silent:
                    click.secho(
                        f"# Syntax error in {file}: {ex}", err=True, fg="yellow"
                    )
                continue
            for node, class_name in nodes:
                if not filter(node):
                    continue
                if count or check:
                    num_matches += 1
                    if count or not signatures:
                        continue
                # If file is within pwd, print relative path
                if pwd in file.resolve().parents:
                    path = file.resolve().relative_to(pwd)
                else:
                    # else print absolute path
                    path = file.resolve()
                snippet, line_no = code_for_node(
                    code, node, class_name, signatures, docs
                )
                if replace:
                    replace_matches.append((file.resolve(), snippet, line_no))
                    continue

                output_identifier_line = None
                output_import_line = None
                symbol_id = None

                if not no_file:
                    bits = ["# File:", path]
                    if class_name:
                        bits.extend(["Class:", class_name])
                    bits.extend(["Line:", line_no])
                    symbol_id = "{}:{}".format(path, line_no)
                    output_identifier_line = " ".join(str(bit) for bit in bits)
                if imports:
                    import_line = import_line_for_function(
                        node.name, path, sys_paths or directories
                    )
                    # If it's a class then output '# from x import Class' instead
                    if class_name:
                        import_line = (
                            import_line.split(" import ")[0] + " import " + class_name
                        )
                    symbol_id = import_line
                    output_import_line = "# " + import_line

                yield Output(
                    symbol_id, output_identifier_line, output_import_line, snippet
                )

    if sum(output_formats) == 0:
        for item in stuff_to_output():
            if item.output_identifier_line:
                click.echo(item.output_identifier_line)
            if item.output_import_line:
                click.echo(item.output_import_line)
            click.echo(item.snippet)
            click.echo()
    else:
        # Do the fancy output formats thing
        to_output(
            sys.stdout,
            ((id_prefix + item.symbol_id, item.snippet) for item in stuff_to_output()),
            format="csv" if csv_ else "tsv" if tsv else "json" if json_ else "nl",
        )
        return

    if count:
        click.echo(num_matches)

    if check and num_matches > 0:
        sys.exit(1)

    if replace:
        # Only works if we got a single match
        if len(replace_matches) != 1:
            raise click.ClickException(
                "--replace only works with a single match, got {}".format(
                    len(replace_matches)
                )
            )
        filepath, to_replace = replace_matches[0][:2]
        if rexec:
            # Run to_replace through that command
            p = subprocess.Popen(
                rexec,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=True,
            )
            stdout, stderr = p.communicate(input=to_replace.encode())
            if p.returncode != 0:
                raise click.ClickException(
                    f"Command '{rexec}' failed with exit code {p.returncode}"
                    f", stderr: {stderr.decode()}"
                )

            replacement = stdout.decode()
        else:
            if sys.stdin.isatty():
                raise click.ClickException(
                    "--replace only works with text piped to it on stdin"
                )
            new_lines = sys.stdin.readlines()
            # Check if any lines were read
            if len(new_lines) == 0:
                raise click.ClickException("No input for --replace found on stdin")
            replacement = "".join(new_lines)
        old = filepath.read_text("utf-8")
        new = old.replace(to_replace, replacement)
        filepath.write_text(new, "utf-8")


def is_dunder(name):
    return name.startswith("__") and name.endswith("__")


def to_output(
    fp: TextIO,
    lines: Iterable[Tuple[str, str]],
    format: Literal["csv", "tsv", "json", "nl"] = "csv",
) -> None:
    if format == "nl":
        for id, content in lines:
            line = json.dumps({"id": id, "code": content})
            fp.write(line + "\n")
        return

    elif format == "json":
        fp.write("[")
        first = True
        for id, content in lines:
            line = json.dumps({"id": id, "code": content})
            if first:
                fp.write(line)
                first = False
            else:
                fp.write(",\n " + line)
        fp.write("]\n")
        return

    dialect = "excel" if format == "csv" else "excel-tab"
    writer = csv.writer(fp, dialect=dialect)

    # Write header
    writer.writerow(["id", "code"])

    # Write content
    for id, content in lines:
        writer.writerow([id, content])
f210ed5a568564adb82a17cdabf64a82d5ea607b034037adba4382325b1b5b44
from .cli import cli

if __name__ == "__main__":
    cli()
3e9c24207abf0bfc6fc063999301c5f946f5cef2942b84a7b4b1cefd1283ef5f
name: Publish Python Package

on:
  release:
    types: [created]

permissions:
  contents: read
  id-token: write

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
    steps:
    - uses: actions/checkout@v4
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v5
      with:
        python-version: ${{ matrix.python-version }}
        cache: pip
        cache-dependency-path: setup.py
    - name: Install dependencies
      run: |
        pip install '.[test]'
    - name: Run tests
      run: |
        python -m pytest
  deploy:
    runs-on: ubuntu-latest
    needs: [test]
    environment: release
    steps:
    - uses: actions/checkout@v3
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: "3.13"
        cache: pip
        cache-dependency-path: setup.py
    - name: Install dependencies
      run: |
        pip install setuptools wheel build
    - name: Build
      run: |
        python -m build
    - name: Publish
      uses: pypa/gh-action-pypi-publish@release/v1
0c068f8c17cfe5bc3bb50449c8fe512fe3a94a51724a48042e26001a8a8cd6f7
name: Test

on: [push, pull_request]

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
    steps:
    - uses: actions/checkout@v4
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v5
      with:
        python-version: ${{ matrix.python-version }}
        cache: pip
        cache-dependency-path: setup.py
    - name: Install dependencies
      run: |
        pip install '.[test]'
    - name: Run tests
      run: |
        python -m pytest
    - name: Lint with ruff
      run: |
        ruff check symbex
    - name: Check if cog needs to be run
      run: |
        cog README.md
        cog --check README.md
c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4
Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
76b5b21267fdc0d6ee512ab67bc99b323574c71bcd3a1eb55a3fed9d16d48c54
import llm
import html
import httpx
import json
import re
from typing import Dict, List, Any


@llm.hookimpl
def register_fragment_loaders(register):
    register("hn", hacker_news_loader)


def hacker_news_loader(argument: str) -> llm.Fragment:
    try:
        response = httpx.get(f"https://hn.algolia.com/api/v1/items/{argument}")
        response.raise_for_status()
        data = response.json()
    except Exception as ex:
        raise ValueError(f"Could not load Hacker News {argument}: {str(ex)}")
    return llm.Fragment(
        process_hn_comments(data),
        source=f"https://news.ycombinator.com/item?id={argument}",
    )


def convert_hn_to_thread_path(
    json_data: Dict[str, Any], path: str = "", result: List[str] = None
) -> List[str]:
    """
    Convert Hacker News JSON hierarchy to thread path notation.

    Args:
        json_data: The JSON data from HN API
        path: Current thread path (used in recursion)
        result: Accumulator for formatted comments

    Returns:
        List of formatted comments in thread path notation
    """
    if result is None:
        result = []

    # Handle root node
    if not path:
        # Root node needs special handling as it might not be in the standard format
        if "text" in json_data:  # It's a comment
            comment_text = clean_html_content(json_data.get("text", ""))
            result.append(f"[1] {json_data.get('author', 'Anonymous')}: {comment_text}")
            current_path = "1"
        else:  # It's a story or top-level item
            title = json_data.get("title", "")
            result.append(f"[1] {json_data.get('author', 'Anonymous')}: {title}")
            current_path = "1"
    else:
        current_path = path

    # Process children recursively
    if "children" in json_data and json_data["children"]:
        for i, child in enumerate(json_data["children"], 1):
            child_path = f"{current_path}.{i}" if current_path else f"{i}"

            # Handle the comment text, unescape HTML entities and clean HTML
            comment_text = clean_html_content(child.get("text", ""))

            result.append(
                f"[{child_path}] {child.get('author', 'Anonymous')}: {comment_text}"
            )

            # Process this child's children
            convert_hn_to_thread_path(child, child_path, result)

    return result


def clean_html_content(text: str) -> str:
    """
    Clean HTML content by unescaping entities and removing HTML tags.

    Args:
        text: HTML text to clean

    Returns:
        Cleaned text
    """
    if not text:
        return ""

    # First unescape HTML entities
    text = html.unescape(text)

    # Replace paragraph tags with newlines
    text = text.replace("<p>", "\n").replace("</p>", "")

    # Remove link tags but keep the link text
    text = re.sub(r"<a\s+href=[^>]*>(.*?)</a>", r"\1", text)

    # Remove all other HTML tags
    text = re.sub(r"<[^>]*>", "", text)

    return text


def process_hn_comments(json_str: str) -> str:
    """
    Process the JSON string from HN API and return thread path notation.

    Args:
        json_str: JSON string from HN API

    Returns:
        Formatted string with thread path notation
    """
    try:
        json_data = json.loads(json_str) if isinstance(json_str, str) else json_str
        formatted_comments = convert_hn_to_thread_path(json_data)
        return "\n\n".join(formatted_comments)
    except Exception as e:
        return f"Error processing JSON: {str(e)}"
cb0b0b1aae76cbe7f7ba5644f3f54f62bd4322b233cab628c95adf4c01481fbe
[project]
name = "llm-hacker-news"
version = "0.1"
description = "LLM plugin for pulling content from Hacker News"
readme = "README.md"
authors = [{name = "Simon Willison"}]
license = "Apache-2.0"
classifiers = []
requires-python = ">=3.9"
dependencies = [
    "llm>=0.24"
]

[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

[project.urls]
Homepage = "https://github.com/simonw/llm-hacker-news"
Changelog = "https://github.com/simonw/llm-hacker-news/releases"
Issues = "https://github.com/simonw/llm-hacker-news/issues"
CI = "https://github.com/simonw/llm-hacker-news/actions"

[project.entry-points.llm]
hacker_news = "llm_hacker_news"

[project.optional-dependencies]
test = ["pytest", "pytest-httpx"]
49255a891b377ccaba61a01026c98680de5f83d38795593d3658ffa91bc1280f # llm-hacker-news

PyPI Changelog Tests License

LLM plugin for pulling content from Hacker News

For background on how this works:

Installation

Install this plugin in the same environment as LLM.

llm install llm-hacker-news

Usage

You can feed a full conversation thread from Hacker News into LLM using the hn: fragment with the ID of the conversation. For example:

llm -f hn:43615912 'summary with illustrative direct quotes'

Item IDs can be found in the URL of the conversation thread.

Development

To set up this plugin locally, first checkout the code. Then create a new virtual environment:

cd llm-hacker-news
python -m venv venv
source venv/bin/activate

Now install the dependencies and test dependencies:

pip install -e '.[test]'

To run the tests:

python -m pytest
98769434d2c6001edd8f9cd236d0a137c37732d0796873c1c759927addfdf7fd
.venv
__pycache__/
*.py[cod]
*$py.class
venv
.eggs
.pytest_cache
*.egg-info
.DS_Store
.vscode
dist
build
fd9ae3faccb5bb2227ef436c186a560df2b04809bfa1273ed1278920560a130b
import llm
from llm_hacker_news import hacker_news_loader


def test_hacker_news_loader(httpx_mock):
    httpx_mock.add_response(json=EXAMPLE)
    fragment = hacker_news_loader("123456")
    assert isinstance(fragment, llm.Fragment)
    assert fragment.source == "https://news.ycombinator.com/item?id=123456"
    assert str(fragment) == (
        '[1] BeakMaster: Fish Spotting Techniques\n\n'
        '[1.1] CoastalFlyer: The dive technique works best when hunting in shallow waters.\n\n'
        '[1.1.1] PouchBill: Agreed. Have you tried the hover method near the pier?\n\n'
        '[1.1.2] WingSpan22: My bill gets too wet with that approach.\n\n'
        '[1.1.2.1] CoastalFlyer: Try tilting at a 40° angle like our Australian cousins.\n\n'
        '[1.2] BrownFeathers: Anyone spotted those "silver fish" near the rocks?\n\n'
        '[1.2.1] GulfGlider: Yes! They\'re best caught at dawn.\nJust remember: swoop > grab > lift'
    )


EXAMPLE = {
    "author": "BeakMaster",
    "title": "Fish Spotting Techniques",
    "children": [
        {
            "author": "CoastalFlyer",
            "text": "The dive technique works best when hunting in shallow waters.",
            "children": [
                {
                    "author": "PouchBill",
                    "text": "Agreed. Have you tried the hover method near the pier?",
                    "children": [],
                },
                {
                    "author": "WingSpan22",
                    "text": "My bill gets too wet with that approach.",
                    "children": [
                        {
                            "author": "CoastalFlyer",
                            "text": "Try tilting at a 40° angle like our Australian cousins.",
                            "children": [],
                        }
                    ],
                },
            ],
        },
        {
            "author": "BrownFeathers",
            "text": "Anyone spotted those &quot;silver fish&quot; near the rocks?",
            "children": [
                {
                    "author": "GulfGlider",
                    "text": "Yes! They're best caught at dawn.<p>Just remember: <code>swoop &gt; grab &gt; lift</code>",
                    "children": [],
                }
            ],
        },
    ],
}
fd7da2a5c82824ad71ed3e70e6f72082e37c860bdafec56be8a95c39142c108f
name: Publish Python Package

on:
  release:
    types: [created]

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
    steps:
    - uses: actions/checkout@v4
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v5
      with:
        python-version: ${{ matrix.python-version }}
        cache: pip
        cache-dependency-path: pyproject.toml
    - name: Install dependencies
      run: |
        pip install -e '.[test]'
    - name: Run tests
      run: |
        python -m pytest
  deploy:
    runs-on: ubuntu-latest
    needs: [test]
    environment: release
    permissions:
      id-token: write
    steps:
    - uses: actions/checkout@v4
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: "3.13"
        cache: pip
        cache-dependency-path: pyproject.toml
    - name: Install dependencies
      run: |
        pip install setuptools wheel build
    - name: Build
      run: |
        python -m build
    - name: Publish
      uses: pypa/gh-action-pypi-publish@release/v1
1a564a200569424b8ef1276a16daa3d1697dc5d615adc85a9f51a18cd453020c
name: Test

on: [push, pull_request]

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
    steps:
    - uses: actions/checkout@v4
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v5
      with:
        python-version: ${{ matrix.python-version }}
        cache: pip
        cache-dependency-path: pyproject.toml
    - name: Install dependencies
      run: |
        pip install -e '.[test]'
    - name: Run tests
      run: |
        python -m pytest

System

Write a new plugin as a single llm_fragments_symbex.py file which provides a custom loader which can be used like this: llm -f symbex:path/to/folder - it then loads in all of the python function signatures with their docstrings from that folder using the same trick that symbex uses, effectively the same as running symbex . '' '.*' --docs --imports -n

Response

The following is a single‐file LLM plugin that registers a symbex: fragment loader. You can install it alongside your normal LLM setup (e.g. put it in your PYTHONPATH or your current directory). Then:

llm -f symbex:/path/to/project 'explain these APIs'

will walk every .py under /path/to/project, extract every top‐level function and class‐method signature plus docstring, show an import line for each, suppress any # File: comments, and return the concatenated result as the fragment body.

Save this as llm_fragments_symbex.py:

import llm
import pathlib
from symbex.lib import read_file, find_symbol_nodes, code_for_node, import_line_for_function

@llm.hookimpl
def register_fragment_loaders(register):
    """
    Register the 'symbex' loader.  Usage:
        llm -f symbex:/path/to/folder ...
    """
    register("symbex", symbex_loader)

def symbex_loader(argument: str) -> llm.Fragment:
    """
    Walk the given directory, parse every .py file, and for every
    top-level function or class-method produce its signature and
    docstring plus an import line.  Equivalent to:
        symbex . '*' '*.*' --docs --imports -n
    """
    folder = pathlib.Path(argument).expanduser().resolve()
    if not folder.is_dir():
        raise ValueError(f"symbex loader: '{folder}' is not a directory")
    snippets = []
    # We'll treat the base folder as the root for import-line generation
    possible_roots = [str(folder)]
    # Recursively find all .py files
    for py_file in sorted(folder.rglob("*.py")):
        try:
            source = read_file(py_file)
        except Exception:
            # skip unreadable files
            continue
        # match everything: top-level defs (*) and methods (*.*)
        matches = find_symbol_nodes(source, str(py_file), ["*", "*.*"])
        for node, class_name in matches:
            # extract signature + docstring
            snippet, _lineno = code_for_node(
                source,
                node,
                class_name,
                signatures=True,
                docstrings=True,
            )
            # pick the correct symbol name for import
            symbol = class_name if class_name else node.name
            imp = import_line_for_function(symbol, str(py_file), possible_roots)
            # prepend the import line as a comment
            full = f"# {imp}\n{snippet}"
            snippets.append(full)
    body = "\n\n".join(snippets)
    return llm.Fragment(body, source=f"symbex:{folder}")

Explanation of the core steps:

  1. We import the internal parsing routines from symbex.lib (the same ones the symbex CLI uses).
  2. In symbex_loader() we:
    • Resolve and validate the argument as a directory.
    • Walk all .py files under it.
    • For each file, read it (respecting # coding: declarations).
    • Call find_symbol_nodes(..., ["*", "*.*"]) to get all top‐level functions and methods.
    • Pass each AST node to code_for_node(..., signatures=True, docstrings=True) to get just the signature plus any docstring.
    • Use import_line_for_function() to compute an appropriate from ... import ... line, and prepend it as # from ... import ....
  3. We package the concatenated snippets into a single llm.Fragment, with a synthetic source of symbex:/the/path.

Once this plugin file is on your PYTHONPATH (or simply in your working directory), llm will automatically pick it up and allow:

llm -f symbex:./my_project 'Please explain these APIs'

…giving you exactly the function and method interfaces plus their docs, saving you from manually running symbex.

Token usage:

27,819 input, 2,918 output, {"output_tokens_details": {"reasoning_tokens": 2048}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment