Showing preview only (1,131K chars total). Download the full file or copy to clipboard to get everything.
Repository: google/yapf
Branch: main
Commit: 120050952960
Files: 112
Total size: 1.1 MB
Directory structure:
gitextract_3wypp44j/
├── .coveragerc
├── .editorconfig
├── .flake8
├── .gitattributes
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ ├── ci.yml
│ ├── pre-commit-autoupdate.yml
│ └── pre-commit.yml
├── .gitignore
├── .isort.cfg
├── .pre-commit-config.yaml
├── .pre-commit-hooks.yaml
├── .python-version
├── .style.yapf
├── .vimrc
├── .vscode/
│ ├── extensions.json
│ └── settings.default.json
├── AUTHORS
├── CHANGELOG.md
├── CONTRIBUTING.md
├── CONTRIBUTORS
├── EDITOR SUPPORT.md
├── HACKING.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── plugins/
│ ├── README.md
│ ├── pre-commit.sh
│ └── vim/
│ ├── autoload/
│ │ └── yapf.vim
│ └── plugin/
│ └── yapf.vim
├── pylintrc
├── pyproject.toml
├── third_party/
│ ├── __init__.py
│ └── yapf_third_party/
│ ├── __init__.py
│ ├── _ylib2to3/
│ │ ├── Grammar.txt
│ │ ├── LICENSE
│ │ ├── PatternGrammar.txt
│ │ ├── README.rst
│ │ ├── __init__.py
│ │ ├── fixer_base.py
│ │ ├── fixer_util.py
│ │ ├── patcomp.py
│ │ ├── pgen2/
│ │ │ ├── __init__.py
│ │ │ ├── conv.py
│ │ │ ├── driver.py
│ │ │ ├── grammar.py
│ │ │ ├── literals.py
│ │ │ ├── parse.py
│ │ │ ├── pgen.py
│ │ │ ├── token.py
│ │ │ └── tokenize.py
│ │ ├── pygram.py
│ │ └── pytree.py
│ └── yapf_diff/
│ ├── LICENSE
│ ├── __init__.py
│ └── yapf_diff.py
├── tox.ini
├── yapf/
│ ├── __init__.py
│ ├── __main__.py
│ ├── _version.py
│ ├── pyparser/
│ │ ├── __init__.py
│ │ ├── pyparser.py
│ │ ├── pyparser_utils.py
│ │ ├── pyparser_visitor.py.tmpl
│ │ └── split_penalty_visitor.py
│ ├── pytree/
│ │ ├── __init__.py
│ │ ├── blank_line_calculator.py
│ │ ├── comment_splicer.py
│ │ ├── continuation_splicer.py
│ │ ├── pytree_unwrapper.py
│ │ ├── pytree_utils.py
│ │ ├── pytree_visitor.py
│ │ ├── split_penalty.py
│ │ └── subtype_assigner.py
│ └── yapflib/
│ ├── __init__.py
│ ├── errors.py
│ ├── file_resources.py
│ ├── format_decision_state.py
│ ├── format_token.py
│ ├── identify_container.py
│ ├── line_joiner.py
│ ├── logical_line.py
│ ├── object_state.py
│ ├── reformatter.py
│ ├── split_penalty.py
│ ├── style.py
│ ├── subtypes.py
│ └── yapf_api.py
└── yapftests/
├── __init__.py
├── blank_line_calculator_test.py
├── comment_splicer_test.py
├── file_resources_test.py
├── format_decision_state_test.py
├── format_token_test.py
├── line_joiner_test.py
├── logical_line_test.py
├── main_test.py
├── pytree_unwrapper_test.py
├── pytree_utils_test.py
├── pytree_visitor_test.py
├── reformatter_basic_test.py
├── reformatter_buganizer_test.py
├── reformatter_facebook_test.py
├── reformatter_pep8_test.py
├── reformatter_python3_test.py
├── reformatter_style_config_test.py
├── split_penalty_test.py
├── style_test.py
├── subtype_assigner_test.py
├── utils.py
├── yapf_test.py
└── yapf_test_helper.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .coveragerc
================================================
[report]
omit =
*/__main__.py
================================================
FILE: .editorconfig
================================================
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# 2 space indentation
[*.py]
indent_style = space
indent_size = 2
================================================
FILE: .flake8
================================================
[flake8]
ignore =
# 'toml' imported but unused
F401,
# closing bracket does not match visual indentation
E124,
# continuation line over-indented for hanging indent
E126,
# visually indented line with same indent as next logical line,
E129,
# line break before binary operator
W503,
# line break after binary operator
W504
indent-size = 2
max-line-length = 80
================================================
FILE: .gitattributes
================================================
.python-version eol=lf
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: "github-actions"
commit-message:
include: "scope"
prefix: "Actions"
directory: "/"
labels:
- "enhancement"
schedule:
interval: "weekly"
================================================
FILE: .github/workflows/ci.yml
================================================
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
name: Test with pytest
on:
pull_request:
push:
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
python-version: ["3.8", "3.11", "3.12"] # no particular need for 3.9 or 3.10
os: [macos-latest, ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v4.6.0
with:
python-version: ${{ matrix.python-version }}
- name: Upgrade pip
run: >-
python -m pip install
--upgrade
--disable-pip-version-check
pip
- name: Perform package installs
run: >-
pip install
.
pytest
pytest-cov
- name: Test with pytest
run: pytest
================================================
FILE: .github/workflows/pre-commit-autoupdate.yml
================================================
# Copyright (c) 2023 Sebastian Pipping <sebastian@pipping.org>
# Licensed under the Apache License Version 2.0
name: Keep pre-commit hooks up to date
on:
schedule:
- cron: '0 16 * * 5' # Every Friday 4pm
workflow_dispatch:
# NOTE: This will drop all permissions from GITHUB_TOKEN except metadata read,
# and then (re)add the ones listed below:
permissions:
contents: write
pull-requests: write
jobs:
pre_commit_autoupdate:
name: Detect outdated pre-commit hooks
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1
- name: Set up Python 3.11
uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
with:
python-version: 3.11
- name: Install pre-commit
run: |-
pip install \
--disable-pip-version-check \
--no-warn-script-location \
--user \
pre-commit
echo "PATH=${HOME}/.local/bin:${PATH}" >> "${GITHUB_ENV}"
- name: Check for outdated hooks
run: |-
pre-commit autoupdate
git diff -- .pre-commit-config.yaml
- name: Create pull request from changes (if any)
id: create-pull-request
uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7.0.5
with:
author: 'pre-commit <pre-commit@tools.invalid>'
base: main
body: |-
For your consideration.
:warning: Please **CLOSE AND RE-OPEN** this pull request so that [further workflow runs get triggered](https://github.com/peter-evans/create-pull-request/blob/main/docs/concepts-guidelines.md#triggering-further-workflow-runs) for this pull request.
branch: precommit-autoupdate
commit-message: "pre-commit: Autoupdate"
delete-branch: true
draft: true
labels: enhancement
title: "pre-commit: Autoupdate"
- name: Log pull request URL
if: "${{ steps.create-pull-request.outputs.pull-request-url }}"
run: |
echo "Pull request URL is: ${{ steps.create-pull-request.outputs.pull-request-url }}"
================================================
FILE: .github/workflows/pre-commit.yml
================================================
# Copyright (c) 2023 Sebastian Pipping <sebastian@pipping.org>
# Licensed under the Apache License Version 2.0
name: Run pre-commit
# Drop permissions to minimum for security
permissions:
contents: read
on:
pull_request:
push:
schedule:
- cron: '0 2 * * 5' # Every Friday at 2am
workflow_dispatch:
jobs:
pre_commit_run:
name: Run pre-commit
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1
- uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0
with:
python-version: 3.11
- name: Install yapf (to be available to pre-commit)
run: |-
pip install \
--disable-pip-version-check \
--no-warn-script-location \
--user \
.
echo "PATH=${HOME}/.local/bin:${PATH}" >> "${GITHUB_ENV}"
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
================================================
FILE: .gitignore
================================================
#==============================================================================#
# This file specifies intentionally untracked files that git should ignore.
# See: http://www.kernel.org/pub/software/scm/git/docs/gitignore.html
#
# This file is intentionally different from the output of `git svn show-ignore`,
# as most of those are useless.
#==============================================================================#
#==============================================================================#
# File extensions to be ignored anywhere in the tree.
#==============================================================================#
# Temp files created by most text editors.
*~
# Merge files created by git.
*.orig
# Compiled python.
*.pyc
*.pickle
# vim swap files
.*.sw?
.sw?
# OS X specific files.
.DS_store
#==============================================================================#
# Files to ignore
#==============================================================================#
/.coverage
# Directories to ignore (do not add trailing '/'s, they skip symlinks).
#==============================================================================#
/build
/dist
/.tox
/yapf.egg-info
# IDEs
/.idea
/.vscode/settings.json
# Virtual Environment
/.venv*/
# Worktrees
/.wt
================================================
FILE: .isort.cfg
================================================
[settings]
force_single_line=true
known_third_party=yapf_third_party
known_yapftests=yapftests
sections=FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER,YAPFTESTS
================================================
FILE: .pre-commit-config.yaml
================================================
# File introduces automated checks triggered on git events
# to enable run `pip install pre-commit && pre-commit install`
repos:
- repo: https://github.com/pycqa/isort
rev: 6.0.0
hooks:
- id: isort
name: isort (python)
- repo: local
hooks:
- id: yapf
name: yapf
language: python
entry: yapf
args: [-i]
types: [python]
- repo: https://github.com/pycqa/flake8
rev: 7.1.1
hooks:
- id: flake8
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: check-docstring-first
- id: check-added-large-files
- id: check-yaml
- id: debug-statements
- id: check-merge-conflict
- id: double-quote-string-fixer
- id: end-of-file-fixer
- repo: meta
hooks:
- id: check-hooks-apply
- id: check-useless-excludes
================================================
FILE: .pre-commit-hooks.yaml
================================================
# File configures YAPF to be used as a git hook with https://github.com/pre-commit/pre-commit
- id: yapf
name: yapf
description: "A formatter for Python files."
entry: yapf
args: [-i] #inplace
language: python
types: [python]
- id: yapf-diff
name: yapf-diff
description: "A formatter for Python files. (formats only changes included in commit)"
always_run: true
language: python
pass_filenames: false
stages: [pre-commit]
entry: |
bash -c "git diff -U0 --no-color --relative HEAD \
| yapf-diff \
| tee >(git apply --allow-empty -p0)"
================================================
FILE: .python-version
================================================
3.7.9
3.8.10
3.9.13
3.10.11
3.11.5
================================================
FILE: .style.yapf
================================================
[style]
based_on_style = yapf
================================================
FILE: .vimrc
================================================
" Force indentation styles for this directory
autocmd FileType python set shiftwidth=2
autocmd FileType python set tabstop=2
autocmd FileType python set softtabstop=2
================================================
FILE: .vscode/extensions.json
================================================
{
"recommendations": [
"eeyore.yapf",
"dangmai.workspace-default-settings",
"ms-python.flake8",
"ms-python.isort",
"ms-python.python",
],
// These are remarked as extenstions you should disable for this workspace.
// VSCode does not support disabling extensions via workspace config files.
"unwantedRecommendations": [
"ms-python.black-formatter",
"ms-python.pylint"
]
}
================================================
FILE: .vscode/settings.default.json
================================================
{
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"[python]": {
"diffEditor.ignoreTrimWhitespace": false,
"editor.defaultFormatter": "eeyore.yapf",
"editor.formatOnSaveMode": "file",
"editor.formatOnSave": true,
"editor.wordBasedSuggestions": false,
"files.trimTrailingWhitespace": true,
},
"python.analysis.extraPaths": [
"./third_party"
],
"python.analysis.typeCheckingMode": "basic",
"python.languageServer": "Pylance",
"files.exclude": {
"**/*$py.class": true
},
"json.schemas": [
{
"fileMatch": [
"/.vscode/settings.default.json"
],
"url": "vscode://schemas/settings/folder"
}
],
"workspace-default-settings.runOnActivation": true,
"workspace-default-settings.jsonIndentation": 4
}
================================================
FILE: AUTHORS
================================================
# This is the official list of YAPF authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS files.
# See the latter for an explanation.
# Names should be added to this file as:
# Name or Organization <email address>
# The email address is not required for organizations.
Google Inc.
================================================
FILE: CHANGELOG.md
================================================
# Change Log
# All notable changes to this project will be documented in this file.
# This project adheres to [Semantic Versioning](http://semver.org/).
## (0.41.0) UNRELEASED
### Added
- New `DISABLE_SPLIT_LIST_WITH_COMMENT` flag.
`DISABLE_SPLIT_LIST_WITH_COMMENT` is a new knob that changes the
behavior of splitting a list when a comment is present inside the list.
Before, we split a list containing a comment just like we split a list
containing a trailing comma: Each element goes on its own line (unless
`DISABLE_ENDING_COMMA_HEURISTIC` is true).
This new flag allows you to control the behavior of a list with a comment
*separately* from the behavior when the list contains a trailing comma.
This mirrors the behavior of clang-format, and is useful for e.g. forming
"logical groups" of elements in a list.
Without this flag:
```
[
a,
b, #
c
]
```
With this flag:
```
[
a, b, #
c
]
```
Before we had one flag that controlled two behaviors.
- `DISABLE_ENDING_COMMA_HEURISTIC=false` (default):
- Split a list that has a trailing comma.
- Split a list that contains a comment.
- `DISABLE_ENDING_COMMA_HEURISTIC=true`:
- Don't split on trailing comma.
- Don't split on comment.
Now we have two flags.
- `DISABLE_ENDING_COMMA_HEURISTIC=false` and `DISABLE_SPLIT_LIST_WITH_COMMENT=false` (default):
- Split a list that has a trailing comma.
- Split a list that contains a comment.
Behavior is unchanged from the default before.
- `DISABLE_ENDING_COMMA_HEURISTIC=true` and `DISABLE_SPLIT_LIST_WITH_COMMENT=false` :
- Don't split on trailing comma.
- Do split on comment. **This is a change in behavior from before.**
- `DISABLE_ENDING_COMMA_HEURISTIC=false` and `DISABLE_SPLIT_LIST_WITH_COMMENT=true` :
- Split on trailing comma.
- Don't split on comment.
- `DISABLE_ENDING_COMMA_HEURISTIC=true` and `DISABLE_SPLIT_LIST_WITH_COMMENT=true` :
- Don't split on trailing comma.
- Don't split on comment.
**You used to get this behavior just by setting one flag, but now you have to set both.**
Note the behavioral change above; if you set
`DISABLE_ENDING_COMMA_HEURISTIC=true` and want to keep the old behavior, you
now also need to set `DISABLE_SPLIT_LIST_WITH_COMMENT=true`.
### Changes
- Remove dependency on importlib-metadata
- Remove dependency on tomli when using >= py311
- Format '.pyi' type sub files.
### Fixed
- Fix SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED for one-item named argument lists
by taking precedence over SPLIT_BEFORE_NAMED_ASSIGNS.
- Fix SPLIT_ALL_COMMA_SEPARATED_VALUES and SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES
being too agressive for lambdas and unpacking.
## [0.40.2] 2023-09-22
### Changes
- The verification module has been removed. NOTE: this changes the public APIs
by removing the "verify" parameter.
- Changed FORCE_MULTILINE_DICT to override SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES.
- Adopt pyproject.toml (PEP 517) for build system
### Fixed
- Do not treat variables named `match` as the match keyword.
- Fix SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED for one-item argument lists.
- Fix trailing backslash-newline on Windows when using stdin.
## [0.40.1] 2023-06-20
### Fixed
- Corrected bad distribution v0.40.0 package.
## [0.40.0] 2023-06-13 [YANKED - [#1107](https://github.com/google/yapf/issues/1107)]
### Added
- Support for Python 3.11
- Add the `--print-modified` flag to print out file names of modified files when
running in in-place mode.
### Changes
- Replace the outdated and no-longer-supported lib2to3 with a fork of blib2to3,
Black's version of lib2to3.
### Removed
- Support for Python versions < 3.7 are no longer supported.
## [0.33.0] 2023-04-18 [YANKED - [#1154](https://github.com/google/yapf/issues/1154)]
### Added
- Add a new Python parser to generate logical lines.
- Added support for `# fmt: on` and `# fmt: off` pragmas.
### Changes
- Moved 'pytree' parsing tools into its own subdirectory.
- Add support for Python 3.10.
- Format generated dicts with respect to same rules as regular dicts
- Generalized the ending comma heuristic to subscripts.
- Supports "pyproject.toml" by default.
### Fixed
- Split line before all comparison operators.
## [0.32.0] 2021-12-26
### Added
- Look at the 'pyproject.toml' file to see if it contains ignore file information
for YAPF.
- New entry point `yapf_api.FormatTree` for formatting lib2to3 concrete
syntax trees.
- Add CI via GitHub Actions.
### Changes
- Change tests to support "pytest".
- Reformat so that "flake8" is happy.
- Use GitHub Actions instead of Travis for CI.
- Clean up the FormatToken interface to limit how much it relies upon the
pytree node object.
- Rename "unwrapped_line" module to "logical_line."
- Rename "UnwrappedLine" class to "LogicalLine."
### Fixed
- Added pyproject extra to install toml package as an optional dependency.
- Enable `BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF` knob for "pep8" style, so
method definitions inside a class are surrounded by a single blank line as
prescribed by PEP8.
- Fixed the '...' token to be spaced after a colon.
## [0.31.0] 2021-03-14
### Added
- Renamed 'master' branch to 'main'.
- Add 'BLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLES' to support setting
a custom number of blank lines between top-level imports and variable
definitions.
- Ignore end of line `# copybara:` directives when checking line length.
- Look at the 'pyproject.toml' file to see if it contains style information for
YAPF.
### Changed
- Do not scan excluded directories. Prior versions would scan an excluded
folder then exclude its contents on a file by file basis. Preventing the
folder being scanned is faster.
### Fixed
- Exclude directories on Windows.
## [0.30.0] 2020-04-23
### Added
- Added `SPACES_AROUND_LIST_DELIMITERS`, `SPACES_AROUND_DICT_DELIMITERS`,
and `SPACES_AROUND_TUPLE_DELIMITERS` to add spaces after the opening-
and before the closing-delimiters for lists, dicts, and tuples.
- Adds `FORCE_MULTILINE_DICT` knob to ensure dictionaries always split,
even when shorter than the max line length.
- New knob `SPACE_INSIDE_BRACKETS` to add spaces inside brackets, braces, and
parentheses.
- New knob `SPACES_AROUND_SUBSCRIPT_COLON` to add spaces around the subscript /
slice operator.
### Changed
- Renamed "chromium" style to "yapf". Chromium will now use PEP-8 directly.
- `CONTINUATION_ALIGN_STYLE` with `FIXED` or `VALIGN-RIGHT` now works with
space indentation.
### Fixed
- Honor a disable directive at the end of a multiline comment.
- Don't require splitting before comments in a list when
`SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES` is set. The knob is meant for
values, not comments, which may be associated with the current line.
- Don't over-indent a parameter list when not needed. But make sure it is
properly indented so that it doesn't collide with the lines afterwards.
- Don't split between two-word comparison operators: "is not", "not in", etc.
## [0.29.0] 2019-11-28
### Added
- Add the `--quiet` flag to suppress output. The return code is 1 if there are
changes, similarly to the `--diff` flag.
- Add the `indent_closing_brackets` option. This is the same as the
`dedent_closing_brackets` option except the brackets are indented the same
as the previous line.
### Changed
- Collect a parameter list into a single object. This allows us to track how a
parameter list is formatted, keeping state along the way. This helps when
supporting Python 3 type annotations.
- Catch and report `UnicodeDecodeError` exceptions.
- Improved description of .yapfignore syntax.
### Fixed
- Format subscript lists so that splits are essentially free after a comma.
- Don't add a space between a string and its subscript.
- Extend discovery of '.style.yapf' & 'setup.cfg' files to search the root
directory as well.
- Make sure we have parameters before we start calculating penalties for
splitting them.
- Indicate if a class/function is nested to ensure blank lines when needed.
- Fix extra indentation in async-for else statement.
- A parameter list with no elements shouldn't count as exceeding the column
limit.
- When splitting all comma separated values, don't treat the ending bracket as
special.
- The "no blank lines between nested classes or functions" knob should only
apply to the first nested class or function, not all of them.
## [0.28.0] 2019-07-11
### Added
- New knob `SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES` is a variation on
`SPLIT_ALL_COMMA_SEPARATED_VALUES` in which, if a subexpression with a comma
fits in its starting line, then the subexpression is not split (thus avoiding
unnecessary splits).
### Changed
- Set `INDENT_DICTIONARY_VALUE` for Google style.
- Set `JOIN_MULTIPLE_LINES = False` for Google style.
### Fixed
- `BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=False` wasn't honored because the
number of newlines was erroneously calculated beforehand.
- Lambda expressions shouldn't have an increased split penalty applied to the
'lambda' keyword. This prevents them from being properly formatted when they're
arguments to functions.
- A comment with continuation markers (??) shouldn't mess with the lineno count.
- Only emit unformatted if the "disable long line" is at the end of the line.
Otherwise we could mess up formatting for containers which have them
interspersed with code.
- Fix a potential race condition by using the correct style for opening a file
which may not exist.
## [0.27.0] 2019-04-07
### Added
- `SPLIT_BEFORE_ARITHMETIC_OPERATOR` splits before an arithmetic operator when
set. `SPLIT_PENALTY_ARITHMETIC_OPERATOR` allows you to set the split penalty
around arithmetic operators.
### Changed
- Catch lib2to3's "TokenError" exception and output a nicer message.
### Fixed
- Parse integer lists correctly, removing quotes if the list is within a
string.
- Adjust the penalties of bitwise operands for '&' and '^', similar to '|'.
- Avoid splitting after opening parens if SPLIT_BEFORE_FIRST_ARGUMENT is set
to False.
- Adjust default SPLIT_PENALTY_AFTER_OPENING_BRACKET.
- Re-enable removal of extra lines on the boundaries of formatted regions.
- Adjust list splitting to avoid splitting before a dictionary element, because
those are likely to be split anyway. If we do split, it leads to horrible
looking code.
- Dictionary arguments were broken in a recent version. It resulted in
unreadable formatting, where the remaining arguments were indented far more
than the dictionary. Fixed so that if the dictionary is the first argument in
a function call and doesn't fit on a single line, then it forces a split.
- Improve the connectiveness between items in a list. This prevents random
splitting when it's not 100% necessary.
- Don't remove a comment attached to a previous object just because it's part
of the "prefix" of a function/class node.
## [0.26.0] 2019-02-08
### Added
- `ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS` allows us to split before
default / named assignments.
- `ARITHMETIC_PRECEDENCE_INDICATION` removes spacing around binary operators
if they have higher precedence than other operators in the same expression.
### Changed
- `SPACES_BEFORE_COMMENT` can now be assigned to a specific value (standard
behavior) or a list of column values. When assigned to a list, trailing
comments will be horizontally aligned to the first column value within
the list that is greater than the maximum line length in the block.
- Don't modify the vertical spacing of a line that has a comment "pylint:
disable=line-too-long". The line is expected to be too long.
- improved `CONTINUATION_ALIGN_STYLE` to accept quoted or underline-separated
option value for passing option with command line arguments.
### Fixed
- When retrieving the opening bracket make sure that it's actually an opening
bracket.
- Don't completely deny a lambda formatting if it goes over the column limit.
Split only if absolutely necessary.
- Bump up penalty for splitting before a dot ('.').
- Ignore pseudo tokens when calculating split penalties.
- Increase the penalty for splitting before the first bit of a subscript.
- Improve splitting before dictionary values. Look more closely to see if the
dictionary entry is a container. If so, then it's probably split over
multiple lines with the opening bracket on the same line as the key.
Therefore, we shouldn't enforce a split because of that.
- Increase split penalty around exponent operator.
- Correct spacing when using binary operators on strings with the
`NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS` option enabled.
## [0.25.0] 2018-11-25
### Added
- Added `INDENT_BLANK_LINES` knob to select whether the blank lines are empty
or indented consistently with the current block.
- Support additional file exclude patterns in .yapfignore file.
### Fixed
- Correctly determine if a scope is the last in line. It avoids a wrong
computation of the line end when determining if it must split after the
opening bracket with `DEDENT_CLOSING_BRACKETS` enabled.
## [0.24.0] 2018-09-07
### Added
- Added 'SPLIT_BEFORE_DOT' knob to support "builder style" calls. The "builder
style" option didn't work as advertised. Lines would split after the dots,
not before them regardless of the penalties.
### Changed
- Support Python 3.7 in the tests. The old "comp_for" and "comp_if" nodes are
now "old_comp_for" and "old_comp_if" in lib2to3.
### Fixed
- Don't count inner function calls when marking arguments as named assignments.
- Make sure that tuples and the like are formatted nicely if they all can't fit
on a single line. This is similar to how we format function calls within an
argument list.
- Allow splitting in a subscript if it goes over the line limit.
- Increase the split penalty for an if-expression.
- Increase penalty for splitting in a subscript so that it's more likely to
split in a function call or other data literal.
- Cloning a pytree node doesn't transfer its a annotations. Make sure we do
that so that we don't lose information.
- Revert change that broke the "no_spaces_around_binary_operators" option.
- The "--style-help" option would output string lists and sets in Python types.
If the output was used as a style, then it wouldn't parse those values
correctly.
## [0.23.0] 2018-08-27
### Added
- `DISABLE_ENDING_COMMA_HEURISTIC` is a new knob to disable the heuristic which
splits a list onto separate lines if the list is comma-terminated.
### Fixed
- There's no need to increase N_TOKENS. In fact, it causes other things which
use lib2to3 to fail if called from YAPF.
- Change the exception message instead of creating a new one that's just a
clone.
- Make sure not to reformat when a line is disabled even if the --lines option
is specified.
- The "no spaces around operators" flag wasn't correctly converting strings to
sets. Changed the regexp to handle it better.
## [0.22.0] 2018-05-15
### Added
- The `BLANK_LINE_BEFORE_MODULE_DOCSTRING` knob adds a blank line before a
module's docstring.
- The `SPLIT_ALL_COMMA_SEPARATED_VALUES` knob causes all lists, tuples, dicts
function defs, etc... to split on all values, instead of maximizing the
number of elements on each line, when not able to fit on a single line.
### Changed
- Improve the heuristic we use to determine when to split at the start of a
function call. First check whether or not all elements can fit in the space
without wrapping. If not, then we split.
- Check all of the elements of a tuple. Similarly to how arguments are
analyzed. This allows tuples to be split more rationally.
- Adjust splitting penalties around arithmetic operators so that the code can
flow more freely. The code must flow!
- Try to meld an argument list's closing parenthesis to the last argument.
### Fixed
- Attempt to determine if long lambdas are allowed. This can be done on a
case-by-case basis with a "pylint" disable comment.
- A comment before a decorator isn't part of the decorator's line.
- Only force a new wrapped line after a comment in a decorator when it's the
first token in the decorator.
## [0.21.0] 2018-03-18
### Added
- Introduce a new option of formatting multiline literals. Add
`SPLIT_BEFORE_CLOSING_BRACKET` knob to control whether closing bracket should
get their own line.
- Added `CONTINUATION_ALIGN_STYLE` knob to choose continuation alignment style
when `USE_TABS` is enabled.
- Add 'BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION' knob to control the number
of blank lines between top-level function and class definitions.
### Fixed
- Don't split ellipses.
## [0.20.2] 2018-02-12
### Changed
- Improve the speed at which files are excluded by ignoring them earlier.
- Allow dictionaries to stay on a single line if they only have one entry
### Fixed
- Use tabs when constructing a continuation line when `USE_TABS` is enabled.
- A dictionary entry may not end in a colon, but may be an "unpacking"
operation: `**foo`. Take that into account and don't split after the
unpacking operator.
## [0.20.1] 2018-01-13
### Fixed
- Don't treat 'None' as a keyword if calling a function on it, like '__ne__()'.
- use_tabs=True always uses a single tab per indentation level; spaces are
used for aligning vertically after that.
- Relax the split of a paren at the end of an if statement. With
`dedent_closing_brackets` option requires that it be able to split there.
## [0.20.0] 2017-11-14
### Added
- Improve splitting of comprehensions and generators. Add
`SPLIT_PENALTY_COMPREHENSION` knob to control preference for keeping
comprehensions on a single line and `SPLIT_COMPLEX_COMPREHENSION` to enable
splitting each clause of complex comprehensions onto its own line.
### Changed
- Take into account a named function argument when determining if we should
split before the first argument in a function call.
- Split before the first argument in a function call if the arguments contain a
dictionary that doesn't fit on a single line.
- Improve splitting of elements in a tuple. We want to split if there's a
function call in the tuple that doesn't fit on the line.
### Fixed
- Enforce spaces between ellipses and keywords.
- When calculating the split penalty for a "trailer", process the child nodes
afterwards because their penalties may change. For example if a list
comprehension is an argument.
- Don't enforce a split before a comment after the opening of a container if it
doesn't it on the current line. We try hard not to move such comments around.
- Use a TextIOWrapper when reading from stdin in Python3. This is necessary for
some encodings, like cp936, used on Windows.
- Remove the penalty for a split before the first argument in a function call
where the only argument is a generator expression.
## [0.19.0] 2017-10-14
### Added
- Added `SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN` that enforces a split
after the opening paren of an expression that's surrounded by parens.
### Changed
- Split before the ending bracket of a comma-terminated tuple / argument list
if it's not a single element tuple / arg list.
### Fixed
- Prefer to split after a comma in an argument list rather than in the middle
of an argument.
- A non-multiline string may have newlines if it contains continuation markers
itself. Don't add a newline after the string when retaining the vertical
space.
- Take into account the "async" keyword when determining if we must split
before the first argument.
- Increase affinity for "atom" arguments in function calls. This helps prevent
lists from being separated when they don't need to be.
- Don't place a dictionary argument on its own line if it's the last argument
in the function call where that function is part of a builder-style call.
- Append the "var arg" type to a star in a star_expr.
## [0.18.0] 2017-09-18
### Added
- Option `ALLOW_SPLIT_BEFORE_DICT_VALUE` allows a split before a value. If
False, then it won't be split even if it goes over the column limit.
### Changed
- Use spaces around the '=' in a typed name argument to align with 3.6 syntax.
### Fixed
- Allow semicolons if the line is disabled.
- Fix issue where subsequent comments at decreasing levels of indentation
were improperly aligned and/or caused output with invalid syntax.
- Fix issue where specifying a line range removed a needed line before a
comment.
- Fix spacing between unary operators if one is 'not'.
- Indent the dictionary value correctly if there's a multi-line key.
- Don't remove needed spacing before a comment in a dict when in "chromium"
style.
- Increase indent for continuation line with same indent as next logical line
with 'async with' statement.
## [0.17.0] 2017-08-20
### Added
- Option `NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS` prevents adding spaces
around selected binary operators, in accordance with the current style guide.
### Changed
- Adjust blank lines on formatting boundaries when using the `--lines` option.
- Return 1 if a diff changed the code. This is in line with how GNU diff acts.
- Add `-vv` flag to print out file names as they are processed
### Fixed
- Corrected how `DEDENT_CLOSING_BRACKETS` and `COALESCE_BRACKETS` interacted.
- Fix return value to return a boolean.
- Correct vim plugin not to clobber edited code if yapf returns an error.
- Ensured comma-terminated tuples with multiple elements are split onto separate lines.
## [0.16.3] 2017-07-13
### Changed
- Add filename information to a ParseError exception.
### Fixed
- A token that ends in a continuation marker may have more than one newline in
it, thus changing its "lineno" value. This can happen if multiple
continuation markers are used with no intervening tokens. Adjust the line
number to account for the lines covered by those markers.
- Make sure to split after a comment even for "pseudo" parentheses.
## [0.16.2] 2017-05-19
### Fixed
- Treat expansion operators ('*', '**') in a similar way to function calls to
avoid splitting directly after the opening parenthesis.
- Increase the penalty for splitting after the start of a tuple.
- Increase penalty for excess characters.
- Check that we have enough children before trying to access them all.
- Remove trailing whitespaces from comments.
- Split before a function call in a list if the full list isn't able to fit on
a single line.
- Trying not to split around the '=' of a named assign.
- Changed split before the first argument behavior to ignore compound
statements like if and while, but not function declarations.
- Changed coalesce brackets not to line split before closing bracket.
## [0.16.1] 2017-03-22
### Changed
- Improved performance of cloning the format decision state object. This
improved the time in one *large* case from 273.485s to 234.652s.
- Relax the requirement that a named argument needs to be on one line. Going
over the column limit is more of an issue to pylint than putting named args
on multiple lines.
- Don't make splitting penalty decisions based on the original formatting. This
can and does lead to non-stable formatting, where yapf will reformat the same
code in different ways.
### Fixed
- Ensure splitting of arguments if there's a named assign present.
- Prefer to coalesce opening brackets if it's not at the beginning of a
function call.
- Prefer not to squish all of the elements in a function call over to the
right-hand side. Split the arguments instead.
- We need to split a dictionary value if the first element is a comment anyway,
so don't force the split here. It's forced elsewhere.
- Ensure tabs are used for continued indentation when USE_TABS is True.
## [0.16.0] 2017-02-05
### Added
- The `EACH_DICT_ENTRY_ON_SEPARATE_LINE` knob indicates that each dictionary
entry should be in separate lines if the full dictionary isn't able to fit on
a single line.
- The `SPLIT_BEFORE_DICT_SET_GENERATOR` knob splits before the `for` part of a
dictionary/set generator.
- The `BLANK_LINE_BEFORE_CLASS_DOCSTRING` knob adds a blank line before a
class's docstring.
- The `ALLOW_MULTILINE_DICTIONARY_KEYS` knob allows dictionary keys to span
more than one line.
### Fixed
- Split before all entries in a dict/set or list maker when comma-terminated,
even if there's only one entry.
- Will now try to set O_BINARY mode on stdout under Windows and Python 2.
- Avoid unneeded newline transformation when writing formatted code to
output on (affects only Python 2)
## [0.15.2] 2017-01-29
### Fixed
- Don't perform a global split when a named assign is part of a function call
which itself is an argument to a function call. I.e., don't cause 'a' to
split here:
func(a, b, c, d(x, y, z=42))
- Allow splitting inside a subscript if it's a logical or bitwise operating.
This should keep the subscript mostly contiguous otherwise.
## [0.15.1] 2017-01-21
### Fixed
- Don't insert a space between a type hint and the '=' sign.
- The '@' operator can be used in Python 3 for matrix multiplication. Give the
'@' in the decorator a DECORATOR subtype to distinguish it.
- Encourage the formatter to split at the beginning of an argument list instead
of in the middle. Especially if the middle is an empty parameter list. This
adjusts the affinity of binary and comparison operators. In particular, the
"not in" and other such operators don't want to have a split after it (or
before it) if at all possible.
## [0.15.0] 2017-01-12
### Added
- Keep type annotations intact as much as possible. Don't try to split the over
multiple lines.
### Fixed
- When determining if each element in a dictionary can fit on a single line, we
are skipping dictionary entries. However, we need to ignore comments in our
calculations and implicitly concatenated strings, which are already placed on
separate lines.
- Allow text before a "pylint" comment.
- Also allow text before a "yapf: (disable|enable)" comment.
## [0.14.0] 2016-11-21
### Added
- formatting can be run in parallel using the "-p" / "--parallel" flags.
### Fixed
- "not in" and "is not" should be subtyped as binary operators.
- A non-Node dictionary value may have a comment before it. In those cases, we
want to avoid encompassing only the comment in pseudo parens. So we include
the actual value as well.
- Adjust calculation so that pseudo-parentheses don't count towards the total
line length.
- Don't count a dictionary entry as not fitting on a single line in a
dictionary.
- Don't count pseudo-parentheses in the length of the line.
## [0.13.2] 2016-10-22
### Fixed
- REGRESSION: A comment may have a prefix with newlines in it. When calculating
the prefix indent, we cannot take the newlines into account. Otherwise, the
comment will be misplaced causing the code to fail.
## [0.13.1] 2016-10-17
### Fixed
- Correct emitting a diff that was accidentally removed.
## [0.13.0] 2016-10-16
### Added
- Added support to retain the original line endings of the source code.
### Fixed
- Functions or classes with comments before them were reformatting the comments
even if the code was supposed to be ignored by the formatter. We now don't
adjust the whitespace before a function's comment if the comment is a
"disabled" line. We also don't count "# yapf: {disable|enable}" as a disabled
line, which seems logical.
- It's not really more readable to split before a dictionary value if it's part
of a dictionary comprehension.
- Enforce two blank lines after a function or class definition, even before a
comment. (But not between a decorator and a comment.) This is related to PEP8
error E305.
- Remove O(n^2) algorithm from the line disabling logic.
## [0.12.2] 2016-10-09
### Fixed
- If `style.SetGlobalStyle(<create pre-defined style>)` was called and then
`yapf_api.FormatCode` was called, the style set by the first call would be
lost, because it would return the style created by `DEFAULT_STYLE_FACTORY`,
which is set to PEP8 by default. Fix this by making the first call set which
factory we call as the "default" style.
- Don't force a split before non-function call arguments.
- A dictionary being used as an argument to a function call and which can exist
on a single line shouldn't be split.
- Don't rely upon the original line break to determine if we should split
before the elements in a container. Especially split if there's a comment in
the container.
- Don't add spaces between star and args in a lambda expression.
- If a nested data structure terminates in a comma, then split before the first
element, but only if there's more than one element in the list.
## [0.12.1] 2016-10-02
### Changed
- Dictionary values will be placed on the same line as the key if *all* of the
elements in the dictionary can be placed on one line. Otherwise, the
dictionary values will be placed on the next line.
### Fixed
- Prefer to split before a terminating r-paren in an argument list if the line
would otherwise go over the column limit.
- Split before the first key in a dictionary if the dictionary cannot fit on a
single line.
- Don't count "pylint" comments when determining if the line goes over the
column limit.
- Don't count the argument list of a lambda as a named assign in a function
call.
## [0.12.0] 2016-09-25
### Added
- Support formatting of typed names. Typed names are formatted a similar way to
how named arguments are formatted, except that there's a space after the
colon.
- Add a knob, 'SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN', to allow adding spaces
around the assign operator on default or named assigns.
## Changed
- Turn "verification" off by default for external APIs.
- If a function call in an argument list won't fit on the current line but will
fit on a line by itself, then split before the call so that it won't be split
up unnecessarily.
## Fixed
- Don't add space after power operator if the next operator's a unary operator.
## [0.11.1] 2016-08-17
### Changed
- Issue #228: Return exit code 0 on success, regardless of whether files were
changed. (Previously, 0 meant success with no files
modified, and 2 meant success with at least one file modified.)
### Fixed
- Enforce splitting each element in a dictionary if comma terminated.
- It's okay to split in the middle of a dotted name if the whole expression is
going to go over the column limit.
- Asynchronous functions were going missing if they were preceded by a comment
(a what? exactly). The asynchronous function processing wasn't taking the
comment into account and thus skipping the whole function.
- The splitting of arguments when comma terminated had a conflict. The split
penalty of the closing bracket was set to the maximum, but it shouldn't be if
the closing bracket is preceded by a comma.
## [0.11.0] 2016-07-17
### Added
- The COALESCE_BRACKETS knob prevents splitting consecutive brackets when
DEDENT_CLOSING_BRACKETS is set.
- Don't count "pylint" directives as exceeding the column limit.
### Changed
- We split all of the arguments to a function call if there's a named argument.
In this case, we want to split after the opening bracket too. This makes
things look a bit better.
### Fixed
- When retaining format of a multiline string with Chromium style, make sure
that the multiline string doesn't mess up where the following comma ends up.
- Correct for when 'lib2to3' smooshes comments together into the same DEDENT
node.
## [0.10.0] 2016-06-14
### Added
- Add a knob, 'USE_TABS', to allow using tabs for indentation.
### Changed
- Performance enhancements.
### Fixed
- Don't split an import list if it's not surrounded by parentheses.
## [0.9.0] 2016-05-29
### Added
- Added a knob (SPLIT_PENALTY_BEFORE_IF_EXPR) to adjust the split penalty
before an if expression. This allows the user to place a list comprehension
all on one line.
- Added a knob (SPLIT_BEFORE_FIRST_ARGUMENT) that encourages splitting before
the first element of a list of arguments or parameters if they are going to
be split anyway.
- Added a knob (SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED) splits arguments to a
function if the list is terminated by a comma.
### Fixed
- Don't split before a first element list argument as we would before a first
element function call.
- Don't penalize when we must split a line.
- Allow splitting before the single argument in a function call.
## [0.8.2] 2016-05-21
### Fixed
- Prefer not to split after the opening of a subscript.
- Don't add space before the 'await' keyword if it's preceded by an opening
paren.
- When we're setting the split penalty for a continuous list, we don't want to
mistake a comment at the end of that list as part of the list.
- When calculating blank lines, don't assume the last seen object was a class
or function when we're in a class or function.
- Don't count the closing scope when determining if the current scope is the
last scope on the line.
## [0.8.1] 2016-05-18
### Fixed
- 'SPLIT_BEFORE_LOGICAL_OPERATOR' wasn't working correctly. The penalty was
being set incorrectly when it was part of a larger construct.
- Don't separate a keyword, like "await", from a left paren.
- Don't rely upon the original tokens' line number to determine if we should
perform splitting in Facebook mode. The line number isn't the line number of
the reformatted token, but the line number where it was in the original code.
Instead, we need to carefully determine if the line is liabel to be split and
act accordingly.
## [0.8.0] 2016-05-10
### Added
- Add a knob, 'SPACES_AROUND_POWER_OPERATOR', to allow adding spaces around the
power operator.
### Fixed
- There shouldn't be a space between a decorator and an intervening comment.
- If we split before a bitwise operator, then we assume that the programmer
knows what they're doing, more or less, and so we enforce a split before said
operator if one exists in the original program.
- Strengthen the bond between a keyword and value argument.
- Don't add a blank line after a multiline string.
- If the "for" part of a list comprehension can exist on the starting line
without going over the column limit, then let it remain there.
## [0.7.1] 2016-04-21
### Fixed
- Don't rewrite the file if there are no changes.
- Ensure the proper number of blank lines before an async function.
- Split after a bitwise operator when in PEP 8 mode.
- Retain the splitting within a dictionary data literal between the key and
value.
- Try to keep short function calls all on one line even if they're part of a
larger series of tokens. This stops us from splitting too much.
## [0.7.0] 2016-04-09
### Added
- Support for Python 3.5.
- Add 'ALLOW_MULTILINE_LAMBDAS' which allows lambdas to be formatted onto
multiple lines.
### Fixed
- Lessen penalty for splitting before a dictionary keyword.
- Formatting of trailing comments on disabled formatting lines.
- Disable / enable formatting at end of multi-line comment.
## [0.6.3] 2016-03-06
### Changed
- Documentation updated.
### Fixed
- Fix spacing of multiline comments when formatting is disabled.
## [0.6.2] 2015-11-01
### Changed
- Look at the 'setup.cfg' file to see if it contains style information for
YAPF.
- Look at the '~/.config/yapf/style' file to see if it contains global style
information for YAPF.
### Fixed
- Make lists that can fit on one line more likely to stay together.
- Correct formatting of '*args' and '**kwargs' when there are default values in
the argument list.
## [0.6.1] 2015-10-24
### Fixed
- Make sure to align comments in data literals correctly. Also make sure we
don't count a "#." in a string as an i18n comment.
- Retain proper vertical spacing before comments in a data literal.
- Make sure that continuations from a compound statement are distinguished from
the succeeding line.
- Ignore preceding comments when calculating what is a "dictionary maker".
- Add a small penalty for splitting before a closing bracket.
- Ensure that a space is enforced after we remove a pseudo-paren that's between
two names, keywords, numbers, etc.
- Increase the penalty for splitting after a pseudo-paren. This could lead to
less readable code in some circumstances.
## [0.6.0] 2015-10-18
### Added
- Add knob to indent the dictionary value if there is a split before it.
### Changed
- No longer check that a file is a "Python" file unless the '--recursive' flag
is specified.
- No longer allow the user to specify a directory unless the '--recursive' flag
is specified.
### Fixed
- When determining if we should split a dictionary's value to a new line, use
the longest entry instead of the total dictionary's length. This allows the
formatter to reformat the dictionary in a more consistent manner.
- Improve how list comprehensions are formatted. Make splitting dependent upon
whether the "comp_for" or "comp_if" goes over the column limit.
- Don't over indent if expression hanging indents if we expect to dedent the
closing bracket.
- Improve splitting heuristic when the first argument to a function call is
itself a function call with arguments. In cases like this, the remaining
arguments to the function call would look badly aligned, even though they are
technically correct (the best kind of correct!).
- Improve splitting heuristic more so that if the first argument to a function
call is a data literal that will go over the column limit, then we want to
split before it.
- Remove spaces around '**' operator.
- Retain formatting of comments in the middle of an expression.
- Don't add a newline to an empty file.
- Over indent a function's parameter list if it's not distinguished from the
body of the function.
## [0.5.0] 2015-10-11
### Added
- Add option to exclude files/directories from formatting.
- Add a knob to control whether import names are split after the first '('.
### Fixed
- Indent the continuation of an if-then statement when it's not distinguished
from the body of the if-then.
- Allow for sensible splitting of array indices where appropriate.
- Prefer to not split before the ending bracket of an atom. This produces
better code in most cases.
- Corrected how horizontal spaces were presevered in a disabled region.
## [0.4.0] 2015-10-07
### Added
- Support for dedenting closing brackets, "facebook" style.
### Fixed
- Formatting of tokens after a multiline string didn't retain their horizontal
spacing.
## [0.3.1] 2015-09-30
### Fixed
- Format closing scope bracket correctly when indentation size changes.
## [0.3.0] 2015-09-20
### Added
- Return a 2 if the source changed, 1 on error, and 0 for no change.
### Fixed
- Make sure we format if the "lines" specified are in the middle of a
statement.
## [0.2.9] - 2015-09-13
### Fixed
- Formatting of multiple files. It was halting after formatting the first file.
## [0.2.8] - 2015-09-12
### Added
- Return a non-zero exit code if the source was changed.
- Add bitwise operator splitting penalty and prefer to split before bitwise
operators.
### Fixed
- Retain vertical spacing between disabled and enabled lines.
- Split only at start of named assign.
- Retain comment position when formatting is disabled.
- Honor splitting before or after logical ops.
================================================
FILE: CONTRIBUTING.md
================================================
# How to Contribute
Want to contribute? Great! First, read this page (including the small print at
the end).
## Before you contribute
Before we can use your code, you must sign the [Google Individual Contributor
License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
## Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
## YAPF coding style
YAPF follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html)
with two exceptions:
- 2 spaces for indentation rather than 4.
- CamelCase for function and method names rather than `snake_case`.
The rationale for this is that YAPF was initially developed at Google where
these two exceptions are still part of the internal Python style guide.
## Getting started
YAPF supports using tox 3 for creating a local dev environment, testing, and
building redistributables. See [HACKING.md](HACKING.md) for more info.
```bash
$ pipx run --spec='tox<4' tox --devenv .venv
```
## Small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.
================================================
FILE: CONTRIBUTORS
================================================
# People who have agreed to one of the CLAs and can contribute patches.
# The AUTHORS file lists the copyright holders; this file
# lists people. For example, Google employees are listed here
# but not in AUTHORS, because Google holds the copyright.
#
# https://developers.google.com/open-source/cla/individual
# https://developers.google.com/open-source/cla/corporate
#
# Names should be added to this file as:
# Name <email address>
Bill Wendling <morbo@google.com>
Eli Bendersky <eliben@google.com>
Sam Clegg <sbc@google.com>
Łukasz Langa <ambv@fb.com>
Oleg Butuzov <butuzov@made.ua>
Mauricio Herrera Cuadra <mauricio@arareko.net>
Kyle Gottfried <kyle.gottfried@outlook.com>
================================================
FILE: EDITOR SUPPORT.md
================================================
# Using YAPF with your editor
YAPF is supported by multiple editors via community extensions or plugins.
- [IntelliJ/PyCharm](#intellijpycharm)
- [IPython](#ipython)
- [VSCode](#vscode)
## IntelliJ/PyCharm
Use the `File Watchers` plugin to run YAPF against a file when you perform a save.
1. Install the [File Watchers](https://www.jetbrains.com/help/idea/using-file-watchers.html) Plugin
1. Add the following `.idea/watcherTasks.xml` to your project. If you already have this file just add the `TaskOptions` section from below. This example uses Windows and a virtual environment, modify the `program` option as appropriate.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectTasksOptions">
<TaskOptions isEnabled="true">
<option name="arguments" value="-i $FilePathRelativeToProjectRoot$" />
<option name="checkSyntaxErrors" value="true" />
<option name="description" />
<option name="exitCodeBehavior" value="ERROR" />
<option name="fileExtension" value="py" />
<option name="immediateSync" value="true" />
<option name="name" value="yapf" />
<option name="output" value="" />
<option name="outputFilters">
<array />
</option>
<option name="outputFromStdout" value="false" />
<option name="program" value="$PROJECT_DIR$/.venv/Scripts/yapf.exe" />
<option name="runOnExternalChanges" value="true" />
<option name="scopeName" value="Project Files" />
<option name="trackOnlyRoot" value="false" />
<option name="workingDir" value="$Projectpath$" />
<envs />
</TaskOptions>
</component>
</project>
```
## IPython
IPython supports formatting lines automatically when you press the `<Enter>` button to submit the current code block.
Make sure that the YAPF module is available to the IPython runtime:
```shell
pip install ipython yapf
```
pipx example:
```shell
pipx install ipython
pipx inject ipython yapf
```
Add following to `~/.ipython/profile_default/ipython_config.py`:
```python
c.TerminalInteractiveShell.autoformatter = 'yapf'
```
## VSCode
VSCode has deprecated support for YAPF in its official Python extension [in favor of dedicated formatter extensions](https://github.com/microsoft/vscode-python/wiki/Migration-to-Python-Tools-Extensions).
1. Install EeyoreLee's [yapf](https://marketplace.visualstudio.com/items?itemName=eeyore.yapf) extension.
1. Install the yapf package from pip.
```
pip install yapf
```
1. Add the following to VSCode's `settings.json`:
```jsonc
"[python]": {
"editor.formatOnSaveMode": "file",
"editor.formatOnSave": true,
"editor.defaultFormatter": "eeyore.yapf" # choose this extension
},
```
================================================
FILE: HACKING.md
================================================
## Running YAPF on itself
- To run YAPF on all of YAPF:
```bash
$ pipx run --spec=${PWD} --no-cache yapf -m -i -r yapf/ yapftests/ third_party/
```
- To run YAPF on just the files changed in the current git branch:
```bash
$ pipx run --spec=${PWD} --no-cache yapf -m -i $(git diff --name-only @{upstream})
```
## Testing and building redistributables locally
YAPF uses tox 3 to test against multiple python versions and to build redistributables.
Tox will opportunistically use pyenv environments when available.
To configure pyenv run the following in bash:
```bash
$ xargs -t -n1 pyenv install < .python-version
```
Test against all supported Python versions that are currently installed:
```bash
$ pipx run --spec='tox<4' tox
```
Build and test the sdist and wheel against your default Python environment. The redistributables will be in the `dist` directory.
```bash
$ pipx run --spec='tox<4' tox -e bdist_wheel -e sdist
```
## Releasing a new version
1. Install all expected pyenv environements
```bash
$ xargs -t -n1 pyenv install < .python-version
```
1. Run tests against Python 3.7 - 3.11 with
```bash
$ pipx run --spec='tox<4' tox
```
1. Bump version in `yapf/_version.py`.
1. Build and test redistributables
```bash
$ pipx run --spec='tox<4' tox -e bdist_wheel -e sdist
```
1. Check that it looks OK.
1. Install it onto a virtualenv,
1. run tests, and
1. run yapf as a tool.
1. Push to PyPI:
```bash
$ pipx run twine upload dist/*
```
1. Test in a clean virtualenv that 'pip install yapf' works with the new
version.
1. Commit the version bump and add tag with:
```bash
$ git tag v$(VERSION_NUM)
$ git push --tags
```
================================================
FILE: LICENSE
================================================
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.
================================================
FILE: MANIFEST.in
================================================
include HACKING.md LICENSE AUTHORS CHANGELOG.md CONTRIBUTING.md CONTRIBUTORS
include .coveragerc .editorconfig .flake8 plugins/README.md
include plugins/vim/autoload/yapf.vim plugins/vim/plugin/yapf.vim pylintrc
include .style.yapf tox.ini .travis.yml .vimrc
================================================
FILE: README.md
================================================
# YAPF
<p align="center">
<a href="https://badge.fury.io/py/yapf"><img alt="PyPI Version" src="https://badge.fury.io/py/yapf.svg"></a>
<a href="https://github.com/google/yapf/actions/workflows/ci.yml"><img alt="Build Status" src="https://github.com/google/yapf/actions/workflows/ci.yml/badge.svg"></a>
<a href="https://github.com/google/yapf/actions/workflows/pre-commit.yml"><img alt="Actions Status" src="https://github.com/google/yapf/actions/workflows/pre-commit.yml/badge.svg"></a>
<a href="https://coveralls.io/github/google/yapf?branch=main"><img alt="Coverage Status" src="https://coveralls.io/repos/github/google/yapf/badge.svg?branch=main"></a>
</p>
## Introduction
YAPF is a Python formatter based on [`clang-format`](https://clang.llvm.org/docs/ClangFormat.html)
(developed by Daniel Jasper). In essence, the algorithm takes the code and
calculates the best formatting that conforms to the configured style. It takes
away a lot of the drudgery of maintaining your code.
The ultimate goal is that the code YAPF produces is as good as the code that a
programmer would write if they were following the style guide.
> **Note**
> YAPF is not an official Google product (experimental or otherwise), it is
> just code that happens to be owned by Google.
## Installation
To install YAPF from PyPI:
```bash
$ pip install yapf
```
YAPF is still considered in "beta" stage, and the released version may change
often; therefore, the best way to keep up-to-date with the latest development
is to clone this repository or install directly from github:
```bash
$ pip install git+https://github.com/google/yapf.git
```
Note that if you intend to use YAPF as a command-line tool rather than as a
library, installation is not necessary. YAPF supports being run as a directory
by the Python interpreter. If you cloned/unzipped YAPF into `DIR`, it's
possible to run:
```bash
$ PYTHONPATH=DIR python DIR/yapf [options] ...
```
## Using YAPF within your favorite editor
YAPF is supported by multiple editors via community extensions or plugins. See [Editor Support](EDITOR%20SUPPORT.md) for more info.
## Required Python versions
YAPF supports Python 3.7+.
## Usage
```console
usage: yapf [-h] [-v] [-d | -i | -q] [-r | -l START-END] [-e PATTERN]
[--style STYLE] [--style-help] [--no-local-style] [-p] [-m] [-vv]
[files ...]
Formatter for Python code.
positional arguments:
files reads from stdin when no files are specified.
optional arguments:
-h, --help show this help message and exit
-v, --version show program's version number and exit
-d, --diff print the diff for the fixed source
-i, --in-place make changes to files in place
-q, --quiet output nothing and set return value
-r, --recursive run recursively over directories
-l START-END, --lines START-END
range of lines to reformat, one-based
-e PATTERN, --exclude PATTERN
patterns for files to exclude from formatting
--style STYLE specify formatting style: either a style name (for
example "pep8" or "google"), or the name of a file
with style settings. The default is pep8 unless a
.style.yapf or setup.cfg or pyproject.toml file
located in the same directory as the source or one of
its parent directories (for stdin, the current
directory is used).
--style-help show style settings and exit; this output can be saved
to .style.yapf to make your settings permanent
--no-local-style don't search for local style definition
-p, --parallel run YAPF in parallel when formatting multiple files.
-m, --print-modified print out file names of modified files
-vv, --verbose print out file names while processing
```
### Return Codes
Normally YAPF returns zero on successful program termination and non-zero
otherwise.
If `--diff` is supplied, YAPF returns zero when no changes were necessary,
non-zero otherwise (including program error). You can use this in a CI workflow
to test that code has been YAPF-formatted.
### Excluding files from formatting (.yapfignore or pyproject.toml)
In addition to exclude patterns provided on commandline, YAPF looks for
additional patterns specified in a file named `.yapfignore` or `pyproject.toml`
located in the working directory from which YAPF is invoked.
`.yapfignore`'s syntax is similar to UNIX's filename pattern matching:
```
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq
```
Note that no entry should begin with `./`.
If you use `pyproject.toml`, exclude patterns are specified by `ignore_patterns` key
in `[tool.yapfignore]` section. For example:
```ini
[tool.yapfignore]
ignore_patterns = [
"temp/**/*.py",
"temp2/*.py"
]
```
Formatting style
================
The formatting style used by YAPF is configurable and there are many "knobs"
that can be used to tune how YAPF does formatting. See the `style.py` module
for the full list.
To control the style, run YAPF with the `--style` argument. It accepts one of
the predefined styles (e.g., `pep8` or `google`), a path to a configuration
file that specifies the desired style, or a dictionary of key/value pairs.
The config file is a simple listing of (case-insensitive) `key = value` pairs
with a `[style]` heading. For example:
```ini
[style]
based_on_style = pep8
spaces_before_comment = 4
split_before_logical_operator = true
```
The `based_on_style` setting determines which of the predefined styles this
custom style is based on (think of it like subclassing). Four
styles are predefined:
- `pep8` (default)
- `google` (based off of the [Google Python Style Guide](https://github.com/google/styleguide/blob/gh-pages/pyguide.md))
- `yapf` (for use with Google open source projects)
- `facebook`
See `_STYLE_NAME_TO_FACTORY` in [`style.py`](https://github.com/google/yapf/blob/main/yapf/yapflib/style.py) for details.
It's also possible to do the same on the command line with a dictionary. For
example:
```bash
--style='{based_on_style: pep8, indent_width: 2}'
```
This will take the `pep8` base style and modify it to have two space
indentations.
YAPF will search for the formatting style in the following manner:
1. Specified on the command line
2. In the `[style]` section of a `.style.yapf` file in either the current
directory or one of its parent directories.
3. In the `[yapf]` section of a `setup.cfg` file in either the current
directory or one of its parent directories.
4. In the `[tool.yapf]` section of a `pyproject.toml` file in either the current
directory or one of its parent directories.
5. In the `[style]` section of a `~/.config/yapf/style` file in your home
directory.
If none of those files are found, the default style PEP8 is used.
Example
=======
An example of the type of formatting that YAPF can do, it will take this ugly
code:
```python
x = { 'a':37,'b':42,
'c':927}
y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo ( object ):
def f (self ):
return 37*-+2
def g(self, x,y=42):
return y
def f ( a ) :
return 37+-+a[42-x : y**3]
```
and reformat it into:
```python
x = {'a': 37, 'b': 42, 'c': 927}
y = 'hello ' 'world'
z = 'hello ' + 'world'
a = 'hello {}'.format('world')
class foo(object):
def f(self):
return 37 * -+2
def g(self, x, y=42):
return y
def f(a):
return 37 + -+a[42 - x:y**3]
```
## Example as a module
The two main APIs for calling YAPF are `FormatCode` and `FormatFile`, these
share several arguments which are described below:
```python
>>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code
>>> formatted_code, changed = FormatCode("f ( a = 1, b = 2 )")
>>> formatted_code
'f(a=1, b=2)\n'
>>> changed
True
```
A `style_config` argument: Either a style name or a path to a file that
contains formatting style settings. If None is specified, use the default style
as set in `style.DEFAULT_STYLE_FACTORY`.
```python
>>> FormatCode("def g():\n return True", style_config='pep8')[0]
'def g():\n return True\n'
```
A `lines` argument: A list of tuples of lines (ints), [start, end], that we
want to format. The lines are 1-based indexed. It can be used by third-party
code (e.g., IDEs) when reformatting a snippet of code rather than a whole file.
```python
>>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])[0]
'def g():\n a = 1\n b = 2\n return a==b\n'
```
A `print_diff` (bool): Instead of returning the reformatted source, return a
diff that turns the formatted source into reformatted source.
```diff
>>> print(FormatCode("a==b", filename="foo.py", print_diff=True)[0])
--- foo.py (original)
+++ foo.py (reformatted)
@@ -1 +1 @@
-a==b
+a == b
```
Note: the `filename` argument for `FormatCode` is what is inserted into the
diff, the default is `<unknown>`.
`FormatFile` returns reformatted code from the passed file along with its encoding:
```python
>>> from yapf.yapflib.yapf_api import FormatFile # reformat a file
>>> print(open("foo.py").read()) # contents of file
a==b
>>> reformatted_code, encoding, changed = FormatFile("foo.py")
>>> formatted_code
'a == b\n'
>>> encoding
'utf-8'
>>> changed
True
```
The `in_place` argument saves the reformatted code back to the file:
```python
>>> FormatFile("foo.py", in_place=True)[:2]
(None, 'utf-8')
>>> print(open("foo.py").read()) # contents of file (now fixed)
a == b
```
## Formatting diffs
Options:
```console
usage: yapf-diff [-h] [-i] [-p NUM] [--regex PATTERN] [--iregex PATTERN][-v]
[--style STYLE] [--binary BINARY]
This script reads input from a unified diff and reformats all the changed
lines. This is useful to reformat all the lines touched by a specific patch.
Example usage for git/svn users:
git diff -U0 --no-color --relative HEAD^ | yapf-diff -i
svn diff --diff-cmd=diff -x-U0 | yapf-diff -p0 -i
It should be noted that the filename contained in the diff is used
unmodified to determine the source file to update. Users calling this script
directly should be careful to ensure that the path in the diff is correct
relative to the current working directory.
optional arguments:
-h, --help show this help message and exit
-i, --in-place apply edits to files instead of displaying a diff
-p NUM, --prefix NUM strip the smallest prefix containing P slashes
--regex PATTERN custom pattern selecting file paths to reformat
(case sensitive, overrides -iregex)
--iregex PATTERN custom pattern selecting file paths to reformat
(case insensitive, overridden by -regex)
-v, --verbose be more verbose, ineffective without -i
--style STYLE specify formatting style: either a style name (for
example "pep8" or "google"), or the name of a file
with style settings. The default is pep8 unless a
.style.yapf or setup.cfg or pyproject.toml file
located in the same directory as the source or one of
its parent directories (for stdin, the current
directory is used).
--binary BINARY location of binary to use for YAPF
```
## Python features not yet supported
* Python 3.12 – [PEP 695 – Type Parameter Syntax](https://peps.python.org/pep-0695/) – [YAPF #1170](https://github.com/google/yapf/issues/1170)
* Python 3.12 – [PEP 701 – Syntactic formalization of f-strings](https://peps.python.org/pep-0701/) – [YAPF #1136](https://github.com/google/yapf/issues/1136)
## Knobs
#### `ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT`
> Align closing bracket with visual indentation.
#### `ALLOW_MULTILINE_LAMBDAS`
> Allow lambdas to be formatted on more than one line.
#### `ALLOW_MULTILINE_DICTIONARY_KEYS`
> Allow dictionary keys to exist on multiple lines. For example:
```python
x = {
('this is the first element of a tuple',
'this is the second element of a tuple'):
value,
}
```
#### `ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS`
> Allow splitting before a default / named assignment in an argument list.
#### `ALLOW_SPLIT_BEFORE_DICT_VALUE`
> Allow splits before the dictionary value.
#### `ARITHMETIC_PRECEDENCE_INDICATION`
> Let spacing indicate operator precedence. For example:
```python
a = 1 * 2 + 3 / 4
b = 1 / 2 - 3 * 4
c = (1 + 2) * (3 - 4)
d = (1 - 2) / (3 + 4)
e = 1 * 2 - 3
f = 1 + 2 + 3 + 4
```
> will be formatted as follows to indicate precedence:
```python
a = 1*2 + 3/4
b = 1/2 - 3*4
c = (1+2) * (3-4)
d = (1-2) / (3+4)
e = 1*2 - 3
f = 1 + 2 + 3 + 4
```
#### `BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION`
> Sets the number of desired blank lines surrounding top-level function and
> class definitions. For example:
```python
class Foo:
pass
# <------ having two blank lines here
# <------ is the default setting
class Bar:
pass
```
#### `BLANK_LINE_BEFORE_CLASS_DOCSTRING`
> Insert a blank line before a class-level docstring.
#### `BLANK_LINE_BEFORE_MODULE_DOCSTRING`
> Insert a blank line before a module docstring.
#### `BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF`
> Insert a blank line before a `def` or `class` immediately nested within
> another `def` or `class`. For example:
```python
class Foo:
# <------ this blank line
def method():
pass
```
#### `BLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLES`
> Sets the number of desired blank lines between top-level imports and
> variable definitions. Useful for compatibility with tools like isort.
#### `COALESCE_BRACKETS`
> Do not split consecutive brackets. Only relevant when
> `DEDENT_CLOSING_BRACKETS` or `INDENT_CLOSING_BRACKETS` is set. For example:
```python
call_func_that_takes_a_dict(
{
'key1': 'value1',
'key2': 'value2',
}
)
```
> would reformat to:
```python
call_func_that_takes_a_dict({
'key1': 'value1',
'key2': 'value2',
})
```
#### `COLUMN_LIMIT`
> The column limit (or max line-length)
#### `CONTINUATION_ALIGN_STYLE`
> The style for continuation alignment. Possible values are:
> - `SPACE`: Use spaces for continuation alignment. This is default
> behavior.
> - `FIXED`: Use fixed number (`CONTINUATION_INDENT_WIDTH`) of columns
> (i.e. `CONTINUATION_INDENT_WIDTH`/`INDENT_WIDTH` tabs or
> `CONTINUATION_INDENT_WIDTH` spaces) for continuation alignment.
> - `VALIGN-RIGHT`: Vertically align continuation lines to multiple of
> `INDENT_WIDTH` columns. Slightly right (one tab or a few spaces) if cannot
> vertically align continuation lines with indent characters.
#### `CONTINUATION_INDENT_WIDTH`
> Indent width used for line continuations.
#### `DEDENT_CLOSING_BRACKETS`
> Put closing brackets on a separate line, dedented, if the bracketed
> expression can't fit in a single line. Applies to all kinds of brackets,
> including function definitions and calls. For example:
```python
config = {
'key1': 'value1',
'key2': 'value2',
} # <--- this bracket is dedented and on a separate line
time_series = self.remote_client.query_entity_counters(
entity='dev3246.region1',
key='dns.query_latency_tcp',
transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
start_ts=now()-timedelta(days=3),
end_ts=now(),
) # <--- this bracket is dedented and on a separate line
```
#### `DISABLE_ENDING_COMMA_HEURISTIC`
> Disable the heuristic which places each list element on a separate line if
> the list is comma-terminated.
>
> Note: The behavior of this flag changed in v0.40.3. Before, if this flag
> was true, we would split lists that contained a trailing comma or a
> comment. Now, we have a separate flag, `DISABLE_SPLIT_LIST_WITH_COMMENT`,
> that controls splitting when a list contains a comment. To get the old
> behavior, set both flags to true. More information in
> [CHANGELOG.md](CHANGELOG.md#new-disable_split_list_with_comment-flag).
#### `DISABLE_SPLIT_LIST_WITH_COMMENT`
> Don't put every element on a new line within a list that contains
> interstitial comments.
>
> Without this flag (default):
>
> ```
> [
> a,
> b, #
> c
> ]
> ```
>
> With this flag:
>
> ```
> [
> a, b, #
> c
> ]
> ```
>
> This mirrors the behavior of clang-format and is useful for forming
> "logical groups" of elements in a list. It also works in function
> declarations.
#### `EACH_DICT_ENTRY_ON_SEPARATE_LINE`
> Place each dictionary entry onto its own line.
#### `FORCE_MULTILINE_DICT`
> Respect `EACH_DICT_ENTRY_ON_SEPARATE_LINE` even if the line is shorter than
> `COLUMN_LIMIT`.
#### `I18N_COMMENT`
> The regex for an internationalization comment. The presence of this comment
> stops reformatting of that line, because the comments are required to be
> next to the string they translate.
#### `I18N_FUNCTION_CALL`
> The internationalization function call names. The presence of this function
> stops reformatting on that line, because the string it has cannot be moved
> away from the i18n comment.
#### `INDENT_BLANK_LINES`
> Set to `True` to prefer indented blank lines rather than empty
#### `INDENT_CLOSING_BRACKETS`
> Put closing brackets on a separate line, indented, if the bracketed
> expression can't fit in a single line. Applies to all kinds of brackets,
> including function definitions and calls. For example:
```python
config = {
'key1': 'value1',
'key2': 'value2',
} # <--- this bracket is indented and on a separate line
time_series = self.remote_client.query_entity_counters(
entity='dev3246.region1',
key='dns.query_latency_tcp',
transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
start_ts=now()-timedelta(days=3),
end_ts=now(),
) # <--- this bracket is indented and on a separate line
```
#### `INDENT_DICTIONARY_VALUE`
> Indent the dictionary value if it cannot fit on the same line as the
> dictionary key. For example:
```python
config = {
'key1':
'value1',
'key2': value1 +
value2,
}
```
#### `INDENT_WIDTH`
> The number of columns to use for indentation.
#### `JOIN_MULTIPLE_LINES`
> Join short lines into one line. E.g., single line `if` statements.
#### `NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS`
> Do not include spaces around selected binary operators. For example:
```python
1 + 2 * 3 - 4 / 5
```
> will be formatted as follows when configured with `*`, `/`:
```python
1 + 2*3 - 4/5
```
#### `SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET`
> Insert a space between the ending comma and closing bracket of a list, etc.
#### `SPACE_INSIDE_BRACKETS`
Use spaces inside brackets, braces, and parentheses. For example:
```python
method_call( 1 )
my_dict[ 3 ][ 1 ][ get_index( *args, **kwargs ) ]
my_set = { 1, 2, 3 }
```
#### `SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN`
> Set to `True` to prefer spaces around the assignment operator for default
> or keyword arguments.
#### `SPACES_AROUND_DICT_DELIMITERS`
> Adds a space after the opening '{' and before the ending '}' dict delimiters.
```python
{1: 2}
```
> will be formatted as:
```python
{ 1: 2 }
```
#### `SPACES_AROUND_LIST_DELIMITERS`
> Adds a space after the opening '[' and before the ending ']' list delimiters.
```python
[1, 2]
```
> will be formatted as:
```python
[ 1, 2 ]
```
#### `SPACES_AROUND_POWER_OPERATOR`
> Set to `True` to prefer using spaces around `**`.
#### `SPACES_AROUND_SUBSCRIPT_COLON`
> Use spaces around the subscript / slice operator. For example:
```python
my_list[1 : 10 : 2]
```
##### `SPACES_AROUND_TUPLE_DELIMITERS`
> Adds a space after the opening '(' and before the ending ')' tuple delimiters.
```python
(1, 2, 3)
```
> will be formatted as:
```python
( 1, 2, 3 )
```
#### `SPACES_BEFORE_COMMENT`
> The number of spaces required before a trailing comment.
> This can be a single value (representing the number of spaces
> before each trailing comment) or list of values (representing
> alignment column values; trailing comments within a block will
> be aligned to the first column value that is greater than the maximum
> line length within the block).
> **Note:** Lists of values may need to be quoted in some contexts
> (eg. shells or editor config files).
> For example, with `spaces_before_comment=5`:
```python
1 + 1 # Adding values
```
> will be formatted as:
```python
1 + 1 # Adding values <-- 5 spaces between the end of the statement and comment
```
> with `spaces_before_comment="15, 20"`:
```python
1 + 1 # Adding values
two + two # More adding
longer_statement # This is a longer statement
short # This is a shorter statement
a_very_long_statement_that_extends_beyond_the_final_column # Comment
short # This is a shorter statement
```
> will be formatted as:
```python
1 + 1 # Adding values <-- end of line comments in block aligned to col 15
two + two # More adding
longer_statement # This is a longer statement <-- end of line comments in block aligned to col 20
short # This is a shorter statement
a_very_long_statement_that_extends_beyond_the_final_column # Comment <-- the end of line comments are aligned based on the line length
short # This is a shorter statement
```
#### `SPLIT_ALL_COMMA_SEPARATED_VALUES`
> If a comma separated list (`dict`, `list`, `tuple`, or function `def`) is
> on a line that is too long, split such that each element is on a separate
> line.
#### `SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES`
> Variation on `SPLIT_ALL_COMMA_SEPARATED_VALUES` in which, if a
> subexpression with a comma fits in its starting line, then the
> subexpression is not split. This avoids splits like the one for
> `b` in this code:
```python
abcdef(
aReallyLongThing: int,
b: [Int,
Int])
```
> with the new knob this is split as:
```python
abcdef(
aReallyLongThing: int,
b: [Int, Int])
```
#### `SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED`
> Split before arguments if the argument list is terminated by a comma.
#### `SPLIT_BEFORE_ARITHMETIC_OPERATOR`
> Set to `True` to prefer splitting before `+`, `-`, `*`, `/`, `//`, or `@`
> rather than after.
#### `SPLIT_BEFORE_BITWISE_OPERATOR`
> Set to `True` to prefer splitting before `&`, `|` or `^` rather than after.
#### `SPLIT_BEFORE_CLOSING_BRACKET`
> Split before the closing bracket if a `list` or `dict` literal doesn't fit
> on a single line.
#### `SPLIT_BEFORE_DICT_SET_GENERATOR`
> Split before a dictionary or set generator (`comp_for`). For example, note
> the split before the `for`:
```python
foo = {
variable: 'Hello world, have a nice day!'
for variable in bar if variable != 42
}
```
#### `SPLIT_BEFORE_DOT`
> Split before the `.` if we need to split a longer expression:
```python
foo = ('This is a really long string: {}, {}, {}, {}'.format(a, b, c, d))
```
> would reformat to something like:
```python
foo = ('This is a really long string: {}, {}, {}, {}'
.format(a, b, c, d))
```
#### `SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN`
> Split after the opening paren which surrounds an expression if it doesn't
> fit on a single line.
#### `SPLIT_BEFORE_FIRST_ARGUMENT`
> If an argument / parameter list is going to be split, then split before the
> first argument.
#### `SPLIT_BEFORE_LOGICAL_OPERATOR`
> Set to `True` to prefer splitting before `and` or `or` rather than after.
#### `SPLIT_BEFORE_NAMED_ASSIGNS`
> Split named assignments onto individual lines.
#### `SPLIT_COMPLEX_COMPREHENSION`
> For list comprehensions and generator expressions with multiple clauses
> (e.g multiple `for` calls, `if` filter expressions) and which need to be
> reflowed, split each clause onto its own line. For example:
```python
result = [
a_var + b_var for a_var in xrange(1000) for b_var in xrange(1000)
if a_var % b_var]
```
> would reformat to something like:
```python
result = [
a_var + b_var
for a_var in xrange(1000)
for b_var in xrange(1000)
if a_var % b_var]
```
#### `SPLIT_PENALTY_AFTER_OPENING_BRACKET`
> The penalty for splitting right after the opening bracket.
#### `SPLIT_PENALTY_AFTER_UNARY_OPERATOR`
> The penalty for splitting the line after a unary operator.
#### `SPLIT_PENALTY_ARITHMETIC_OPERATOR`
> The penalty of splitting the line around the `+`, `-`, `*`, `/`, `//`, `%`,
> and `@` operators.
#### `SPLIT_PENALTY_BEFORE_IF_EXPR`
> The penalty for splitting right before an `if` expression.
#### `SPLIT_PENALTY_BITWISE_OPERATOR`
> The penalty of splitting the line around the `&`, `|`, and `^` operators.
#### `SPLIT_PENALTY_COMPREHENSION`
> The penalty for splitting a list comprehension or generator expression.
#### `SPLIT_PENALTY_EXCESS_CHARACTER`
> The penalty for characters over the column limit.
#### `SPLIT_PENALTY_FOR_ADDED_LINE_SPLIT`
> The penalty incurred by adding a line split to the logical line. The more
> line splits added the higher the penalty.
#### `SPLIT_PENALTY_IMPORT_NAMES`
> The penalty of splitting a list of `import as` names. For example:
```python
from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
long_argument_2,
long_argument_3)
```
> would reformat to something like:
```python
from a_very_long_or_indented_module_name_yada_yad import (
long_argument_1, long_argument_2, long_argument_3)
```
#### `SPLIT_PENALTY_LOGICAL_OPERATOR`
> The penalty of splitting the line around the `and` and `or` operators.
#### `USE_TABS`
> Use the Tab character for indentation.
## (Potentially) Frequently Asked Questions
### Why does YAPF destroy my awesome formatting?
YAPF tries very hard to get the formatting correct. But for some code, it won't
be as good as hand-formatting. In particular, large data literals may become
horribly disfigured under YAPF.
The reasons for this are manyfold. In short, YAPF is simply a tool to help
with development. It will format things to coincide with the style guide, but
that may not equate with readability.
What can be done to alleviate this situation is to indicate regions YAPF should
ignore when reformatting something:
```python
# yapf: disable
FOO = {
# ... some very large, complex data literal.
}
BAR = [
# ... another large data literal.
]
# yapf: enable
```
You can also disable formatting for a single literal like this:
```python
BAZ = {
(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
} # yapf: disable
```
To preserve the nice dedented closing brackets, use the
`dedent_closing_brackets` in your style. Note that in this case all
brackets, including function definitions and calls, are going to use
that style. This provides consistency across the formatted codebase.
### Why Not Improve Existing Tools?
We wanted to use clang-format's reformatting algorithm. It's very powerful and
designed to come up with the best formatting possible. Existing tools were
created with different goals in mind, and would require extensive modifications
to convert to using clang-format's algorithm.
### Can I Use YAPF In My Program?
Please do! YAPF was designed to be used as a library as well as a command line
tool. This means that a tool or IDE plugin is free to use YAPF.
### I still get non-PEP8 compliant code! Why?
YAPF tries very hard to be fully PEP 8 compliant. However, it is paramount
to not risk altering the semantics of your code. Thus, YAPF tries to be as
safe as possible and does not change the token stream
(e.g., by adding parentheses).
All these cases however, can be easily fixed manually. For instance,
```python
from my_package import my_function_1, my_function_2, my_function_3, my_function_4, my_function_5
FOO = my_variable_1 + my_variable_2 + my_variable_3 + my_variable_4 + my_variable_5 + my_variable_6 + my_variable_7 + my_variable_8
```
won't be split, but you can easily get it right by just adding parentheses:
```python
from my_package import (my_function_1, my_function_2, my_function_3,
my_function_4, my_function_5)
FOO = (my_variable_1 + my_variable_2 + my_variable_3 + my_variable_4 +
my_variable_5 + my_variable_6 + my_variable_7 + my_variable_8)
```
## Gory Details
### Algorithm Design
The main data structure in YAPF is the `LogicalLine` object. It holds a list
of `FormatToken`\s, that we would want to place on a single line if there
were no column limit. An exception being a comment in the middle of an
expression statement will force the line to be formatted on more than one line.
The formatter works on one `LogicalLine` object at a time.
An `LogicalLine` typically won't affect the formatting of lines before or
after it. There is a part of the algorithm that may join two or more
`LogicalLine`\s into one line. For instance, an if-then statement with a
short body can be placed on a single line:
```python
if a == 42: continue
```
YAPF's formatting algorithm creates a weighted tree that acts as the solution
space for the algorithm. Each node in the tree represents the result of a
formatting decision --- i.e., whether to split or not to split before a token.
Each formatting decision has a cost associated with it. Therefore, the cost is
realized on the edge between two nodes. (In reality, the weighted tree doesn't
have separate edge objects, so the cost resides on the nodes themselves.)
For example, take the following Python code snippet. For the sake of this
example, assume that line (1) violates the column limit restriction and needs to
be reformatted.
```python
def xxxxxxxxxxx(aaaaaaaaaaaa, bbbbbbbbb, cccccccc, dddddddd, eeeeee): # 1
pass # 2
```
For line (1), the algorithm will build a tree where each node (a
`FormattingDecisionState` object) is the state of the line at that token given
the decision to split before the token or not. Note: the `FormatDecisionState`
objects are copied by value so each node in the graph is unique and a change in
one doesn't affect other nodes.
Heuristics are used to determine the costs of splitting or not splitting.
Because a node holds the state of the tree up to a token's insertion, it can
easily determine if a splitting decision will violate one of the style
requirements. For instance, the heuristic is able to apply an extra penalty to
the edge when not splitting between the previous token and the one being added.
There are some instances where we will never want to split the line, because
doing so will always be detrimental (i.e., it will require a backslash-newline,
which is very rarely desirable). For line (1), we will never want to split the
first three tokens: `def`, `xxxxxxxxxxx`, and `(`. Nor will we want to
split between the `)` and the `:` at the end. These regions are said to be
"unbreakable." This is reflected in the tree by there not being a "split"
decision (left hand branch) within the unbreakable region.
Now that we have the tree, we determine what the "best" formatting is by finding
the path through the tree with the lowest cost.
And that's it!
================================================
FILE: plugins/README.md
================================================
# IDE Plugins
## Emacs
The `Emacs` plugin is maintained separately. Installation directions can be
found here: https://github.com/paetzke/py-yapf.el
## Vim
The `vim` plugin allows you to reformat a range of code. Copy `plugin` and
`autoload` directories into your `~/.vim` or use `:packadd` in Vim 8. Or use
a plugin manager like Plug or Vundle:
```vim
" Plug
Plug 'google/yapf', { 'rtp': 'plugins/vim', 'for': 'python' }
" Vundle
Plugin 'google/yapf', { 'rtp': 'plugins/vim' }
```
You can add key bindings in the `.vimrc` file:
```vim
map <C-Y> :call yapf#YAPF()<cr>
imap <C-Y> <c-o>:call yapf#YAPF()<cr>
```
Alternatively, you can call the command `YAPF`. If you omit the range, it will
reformat the whole buffer.
example:
```vim
:YAPF " formats whole buffer
:'<,'>YAPF " formats lines selected in visual mode
```
## Sublime Text
The `Sublime Text` plugin is also maintained separately. It is compatible with
both Sublime Text 2 and 3.
The plugin can be easily installed by using *Sublime Package Control*. Check
the project page of the plugin for more information: https://github.com/jason-kane/PyYapf
## git Pre-Commit Hook
The `git` pre-commit hook automatically formats your Python files before they
are committed to your local repository. Any changes `yapf` makes to the files
will stay unstaged so that you can diff them manually.
To install, simply download the raw file and copy it into your git hooks
directory:
```bash
# From the root of your git project.
$ curl -o pre-commit.sh https://raw.githubusercontent.com/google/yapf/main/plugins/pre-commit.sh
$ chmod a+x pre-commit.sh
$ mv pre-commit.sh .git/hooks/pre-commit
```
## Textmate 2
Plugin for `Textmate 2` requires `yapf` Python package installed on your
system:
```bash
$ pip install yapf
```
Also, you will need to activate `Python` bundle from `Preferences > Bundles`.
Finally, create a `~/Library/Application Support/TextMate/Bundles/Python.tmbundle/Commands/YAPF.tmCommand`
file with the following content:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>beforeRunningCommand</key>
<string>saveActiveFile</string>
<key>command</key>
<string>#!/bin/bash
TPY=${TM_PYTHON:-python}
"$TPY" "/usr/local/bin/yapf" "$TM_FILEPATH"</string>
<key>input</key>
<string>document</string>
<key>name</key>
<string>YAPF</string>
<key>scope</key>
<string>source.python</string>
<key>uuid</key>
<string>297D5A82-2616-4950-9905-BD2D1C94D2D4</string>
</dict>
</plist>
```
You will see a new menu item `Bundles > Python > YAPF`.
================================================
FILE: plugins/pre-commit.sh
================================================
#!/usr/bin/env bash
# Git pre-commit hook to check staged Python files for formatting issues with
# yapf.
#
# INSTALLING: Copy this script into `.git/hooks/pre-commit`, and mark it as
# executable.
#
# This requires that yapf is installed and runnable in the environment running
# the pre-commit hook.
#
# When running, this first checks for unstaged changes to staged files, and if
# there are any, it will exit with an error. Files with unstaged changes will be
# printed.
#
# If all staged files have no unstaged changes, it will run yapf against them,
# leaving the formatting changes unstaged. Changed files will be printed.
#
# BUGS: This does not leave staged changes alone when used with the -a flag to
# git commit, due to the fact that git stages ALL unstaged files when that flag
# is used.
# Find all staged Python files, and exit early if there aren't any.
PYTHON_FILES=()
while IFS=$'\n' read -r line; do PYTHON_FILES+=("$line"); done \
< <(git diff --name-only --cached --diff-filter=AM | grep --color=never '.py$')
if [ ${#PYTHON_FILES[@]} -eq 0 ]; then
exit 0
fi
########## PIP VERSION #############
# Verify that yapf is installed; if not, warn and exit.
if ! command -v yapf >/dev/null; then
echo 'yapf not on path; can not format. Please install yapf:'
echo ' pip install yapf'
exit 2
fi
######### END PIP VERSION ##########
########## PIPENV VERSION ##########
# if ! pipenv run yapf --version 2>/dev/null 2>&1; then
# echo 'yapf not on path; can not format. Please install yapf:'
# echo ' pipenv install yapf'
# exit 2
# fi
###### END PIPENV VERSION ##########
# Check for unstaged changes to files in the index.
CHANGED_FILES=()
while IFS=$'\n' read -r line; do CHANGED_FILES+=("$line"); done \
< <(git diff --name-only "${PYTHON_FILES[@]}")
if [ ${#CHANGED_FILES[@]} -gt 0 ]; then
echo 'You have unstaged changes to some files in your commit; skipping '
echo 'auto-format. Please stage, stash, or revert these changes. You may '
echo 'find `git stash -k` helpful here.'
echo 'Files with unstaged changes:' "${CHANGED_FILES[@]}"
exit 1
fi
# Format all staged files, then exit with an error code if any have uncommitted
# changes.
echo 'Formatting staged Python files . . .'
########## PIP VERSION #############
yapf -i -r "${PYTHON_FILES[@]}"
######### END PIP VERSION ##########
########## PIPENV VERSION ##########
# pipenv run yapf -i -r "${PYTHON_FILES[@]}"
###### END PIPENV VERSION ##########
CHANGED_FILES=()
while IFS=$'\n' read -r line; do CHANGED_FILES+=("$line"); done \
< <(git diff --name-only "${PYTHON_FILES[@]}")
if [ ${#CHANGED_FILES[@]} -gt 0 ]; then
echo 'Reformatted staged files. Please review and stage the changes.'
echo 'Files updated: ' "${CHANGED_FILES[@]}"
exit 1
else
exit 0
fi
================================================
FILE: plugins/vim/autoload/yapf.vim
================================================
" Copyright 2015 Google Inc. All Rights Reserved.
"
" 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.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" VIM Autoload script for YAPF support
"
" Place this script in your ~/.vim/autoload directory. You can add accessors to
" ~/.vimrc, e.g.:
"
" map <C-Y> :call yapf#YAPF()<cr>
" imap <C-Y> <c-o>:call yapf#YAPF()<cr>
"
function! yapf#YAPF() range
" Determine range to format.
let l:line_ranges = a:firstline . '-' . a:lastline
let l:cmd = 'yapf --lines=' . l:line_ranges
" Call YAPF with the current buffer
if exists('*systemlist')
let l:formatted_text = systemlist(l:cmd, join(getline(1, '$'), "\n") . "\n")
else
let l:formatted_text =
\ split(system(l:cmd, join(getline(1, '$'), "\n") . "\n"), "\n")
endif
if v:shell_error
echohl ErrorMsg
echomsg printf('"%s" returned error: %s', l:cmd, l:formatted_text[-1])
echohl None
return
endif
" Update the buffer.
execute '1,' . string(line('$')) . 'delete'
call setline(1, l:formatted_text)
" Reset cursor to first line of the formatted range.
call cursor(a:firstline, 1)
endfunction
================================================
FILE: plugins/vim/plugin/yapf.vim
================================================
" Copyright 2015 Google Inc. All Rights Reserved.
"
" 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.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" VIM command for YAPF support
"
" Place this script in your ~/.vim/plugin directory. You can call the
" command YAPF. If you omit the range, it will reformat the whole
" buffer.
"
" example:
" :YAPF " formats whole buffer
" :'<,'>YAPF " formats lines selected in visual mode
command! -range=% YAPF <line1>,<line2>call yapf#YAPF()
================================================
FILE: pylintrc
================================================
[MASTER]
# Specify a configuration file.
#rcfile=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Pickle collected data for later comparisons.
persistent=yes
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Use multiple processes to speed up Pylint.
jobs=1
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code
extension-pkg-whitelist=
# Allow optimization of some AST trees. This will activate a peephole AST
# optimizer, which will apply various small optimizations. For instance, it can
# be used to obtain the result of joining multiple strings with the addition
# operator. Joining a lot of strings can lead to a maximum recursion error in
# Pylint and this flag can prevent that. It has one side effect, the resulting
# AST will be different than the one from reality.
optimize-ast=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
confidence=
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
#enable=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=
# disabled by me,
locally-disabled,
missing-docstring,
fixme,
# disabled by default,
import-star-module-level,
old-octal-literal,
oct-method,
print-statement,
unpacking-in-except,
parameter-unpacking,
backtick,
old-raise-syntax,
old-ne-operator,
long-suffix,
dict-view-method,
dict-iter-method,
metaclass-assignment,
next-method-called,
raising-string,
indexing-exception,
raw_input-builtin,
long-builtin,
file-builtin,
execfile-builtin,
coerce-builtin,
cmp-builtin,
buffer-builtin,
basestring-builtin,
apply-builtin,
filter-builtin-not-iterating,
using-cmp-argument,
useless-suppression,
range-builtin-not-iterating,
suppressed-message,
no-absolute-import,
old-division,
cmp-method,
reload-builtin,
zip-builtin-not-iterating,
intern-builtin,
unichr-builtin,
reduce-builtin,
standarderror-builtin,
unicode-builtin,
xrange-builtin,
coerce-method,
delslice-method,
getslice-method,
setslice-method,
input-builtin,
round-builtin,
hex-method,
nonzero-method,
map-builtin-not-iterating,
[REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html. You can also give a reporter class, eg
# mypackage.mymodule.MyReporterClass.
output-format=text
# Put messages in a separate file for each module / package specified on the
# command line instead of printing them on stdout. Reports (if any) will be
# written in a file name "pylint_global.[txt|html]".
files-output=no
# Tells whether to display a full report or only the messages
reports=yes
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details
#msg-template=
[FORMAT]
# Maximum number of characters on a single line.
max-line-length=100
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,dict-separator
# Maximum number of lines in a module
max-module-lines=1000
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
[SPELLING]
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format
logging-modules=logging
[BASIC]
# List of builtins function names that should not be used, separated by a comma
bad-functions=map,filter,input
# Good variable names which should always be accepted, separated by a comma
good-names=i,e,s,_,fd,fp
# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Include a hint for the correct naming format with invalid-name
include-naming-hint=no
# Regular expression matching correct function names
# original:
#function-rgx=[a-z_][a-z0-9_]{2,30}$
function-rgx=[a-zA-Z_][a-zA-Z0-9_]{2,40}$
# Naming hint for function names
function-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct variable names
variable-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for variable names
variable-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct constant names
# original:
#const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
const-rgx=(([a-zA-Z_][a-zA-Z0-9_]*)|(__.*__))$
# Naming hint for constant names
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Regular expression matching correct attribute names
attr-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for attribute names
attr-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct argument names
argument-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for argument names
argument-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct class attribute names
# original:
#class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,40}|(__.*__))$
# Naming hint for class attribute names
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Regular expression matching correct inline iteration names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
# Naming hint for inline iteration names
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
# Regular expression matching correct class names
# original:
#class-rgx=[A-Z_][a-zA-Z0-9]+$
class-rgx=[a-zA-Z_][a-zA-Z0-9]+$
# Naming hint for class names
class-name-hint=[A-Z_][a-zA-Z0-9]+$
# Regular expression matching correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Naming hint for module names
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Regular expression matching correct method names
# original:
#method-rgx=[a-z_][a-z0-9_]{2,30}$
method-rgx=[a-zA-Z_][a-zA-Z0-9_]{2,40}$
# Naming hint for method names
method-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
[ELIF]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
[SIMILARITIES]
# Minimum lines number of a similarity.
min-similarity-lines=4
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
[TYPECHECK]
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# List of classes names for which member attributes should not be checked
# (useful for classes with attributes dynamically set). This supports can work
# with qualified names.
ignored-classes=
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,XXX,TODO
[VARIABLES]
# Tells whether we should check for unused import in __init__ files.
init-import=no
# A regular expression matching the name of dummy variables (i.e. expectedly
# not used).
dummy-variables-rgx=_$|dummy
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,_cb
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,__new__,setUp
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make
[DESIGN]
# Maximum number of arguments for function / method
max-args=5
# Argument names that match this expression will be ignored. Default to name
# with leading underscore
ignored-argument-names=_.*
# Maximum number of locals for function / method body
max-locals=15
# Maximum number of return / yield for function / method body
max-returns=6
# Maximum number of branch for function / method body
max-branches=12
# Maximum number of statements in function / method body
max-statements=50
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of boolean expressions in a if statement
max-bool-expr=5
[IMPORTS]
# Deprecated modules which should not be used, separated by a comma
deprecated-modules=regsub,TERMIOS,Bastion,rexec
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled)
import-graph=
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled)
ext-import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled)
int-import-graph=
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception
================================================
FILE: pyproject.toml
================================================
[build-system]
requires = ["setuptools>=58.5.0"]
build-backend = "setuptools.build_meta"
[project]
name = "yapf"
description = "A formatter for Python code"
authors = [{ name = "Google Inc." }]
maintainers = [{ name = "Bill Wendling", email = "morbo@google.com" }]
dynamic = ["version"]
license = { file = "LICENSE" }
readme = "README.md"
requires-python = ">=3.7"
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Quality Assurance',
]
dependencies = ['platformdirs>=3.5.1', 'tomli>=2.0.1; python_version<"3.11"']
[project.scripts]
yapf = "yapf:run_main"
yapf-diff = "yapf_third_party.yapf_diff.yapf_diff:main"
[project.urls]
# https://daniel.feldroy.com/posts/2023-08-pypi-project-urls-cheatsheet
Home = 'https://github.com/google/yapf'
Changelog = 'https://github.com/google/yapf/blob/main/CHANGELOG.md'
Docs = 'https://github.com/google/yapf/blob/main/README.md#yapf'
Issues = 'https://github.com/google/yapf/issues'
[tool.distutils.bdist_wheel]
python_tag = "py3"
[tool.setuptools]
include-package-data = true
package-dir = { yapf_third_party = 'third_party/yapf_third_party' }
[tool.setuptools.dynamic]
version = { attr = "yapf._version.__version__" }
[tool.setuptools.packages.find]
where = [".", 'third_party']
include = ["yapf*", 'yapftests*']
[tool.setuptools.package-data]
yapf_third_party = [
'yapf_diff/LICENSE',
'_ylib2to3/Grammar.txt',
'_ylib2to3/PatternGrammar.txt',
'_ylib2to3/LICENSE',
]
================================================
FILE: third_party/__init__.py
================================================
================================================
FILE: third_party/yapf_third_party/__init__.py
================================================
================================================
FILE: third_party/yapf_third_party/_ylib2to3/Grammar.txt
================================================
# Grammar for 2to3. This grammar supports Python 2.x and 3.x.
# NOTE WELL: You should also follow all the steps listed at
# https://devguide.python.org/grammar/
# Start symbols for the grammar:
# file_input is a module or sequence of commands read from an input file;
# single_input is a single interactive statement;
# eval_input is the input for the eval() and input() functions.
# NB: compound_stmt in single_input is followed by extra NEWLINE!
file_input: (NEWLINE | stmt)* ENDMARKER
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
eval_input: testlist NEWLINE* ENDMARKER
decorator: '@' namedexpr_test NEWLINE
decorators: decorator+
decorated: decorators (classdef | funcdef | async_funcdef)
async_funcdef: ASYNC funcdef
funcdef: 'def' NAME parameters ['->' test] ':' suite
parameters: '(' [typedargslist] ')'
# The following definition for typedarglist is equivalent to this set of rules:
#
# arguments = argument (',' argument)*
# argument = tfpdef ['=' test]
# kwargs = '**' tname [',']
# args = '*' [tname_star]
# kwonly_kwargs = (',' argument)* [',' [kwargs]]
# args_kwonly_kwargs = args kwonly_kwargs | kwargs
# poskeyword_args_kwonly_kwargs = arguments [',' [args_kwonly_kwargs]]
# typedargslist_no_posonly = poskeyword_args_kwonly_kwargs | args_kwonly_kwargs
# typedarglist = arguments ',' '/' [',' [typedargslist_no_posonly]])|(typedargslist_no_posonly)"
#
# It needs to be fully expanded to allow our LL(1) parser to work on it.
typedargslist: tfpdef ['=' test] (',' tfpdef ['=' test])* ',' '/' [
',' [((tfpdef ['=' test] ',')* ('*' [tname_star] (',' tname ['=' test])*
[',' ['**' tname [',']]] | '**' tname [','])
| tfpdef ['=' test] (',' tfpdef ['=' test])* [','])]
] | ((tfpdef ['=' test] ',')* ('*' [tname_star] (',' tname ['=' test])*
[',' ['**' tname [',']]] | '**' tname [','])
| tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
tname: NAME [':' test]
tname_star: NAME [':' (test|star_expr)]
tfpdef: tname | '(' tfplist ')'
tfplist: tfpdef (',' tfpdef)* [',']
# The following definition for varargslist is equivalent to this set of rules:
#
# arguments = argument (',' argument )*
# argument = vfpdef ['=' test]
# kwargs = '**' vname [',']
# args = '*' [vname]
# kwonly_kwargs = (',' argument )* [',' [kwargs]]
# args_kwonly_kwargs = args kwonly_kwargs | kwargs
# poskeyword_args_kwonly_kwargs = arguments [',' [args_kwonly_kwargs]]
# vararglist_no_posonly = poskeyword_args_kwonly_kwargs | args_kwonly_kwargs
# varargslist = arguments ',' '/' [','[(vararglist_no_posonly)]] | (vararglist_no_posonly)
#
# It needs to be fully expanded to allow our LL(1) parser to work on it.
varargslist: vfpdef ['=' test ](',' vfpdef ['=' test])* ',' '/' [',' [
((vfpdef ['=' test] ',')* ('*' [vname] (',' vname ['=' test])*
[',' ['**' vname [',']]] | '**' vname [','])
| vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
]] | ((vfpdef ['=' test] ',')*
('*' [vname] (',' vname ['=' test])* [',' ['**' vname [',']]]| '**' vname [','])
| vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
vname: NAME
vfpdef: vname | '(' vfplist ')'
vfplist: vfpdef (',' vfpdef)* [',']
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
('=' (yield_expr|testlist_star_expr))*)
annassign: ':' test ['=' (yield_expr|testlist_star_expr)]
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')
# For normal and annotated assignments, additional restrictions enforced by the interpreter
print_stmt: 'print' ( [ test (',' test)* [','] ] |
'>>' test [ (',' test)+ [','] ] )
del_stmt: 'del' exprlist
pass_stmt: 'pass'
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist_star_expr]
yield_stmt: yield_expr
raise_stmt: 'raise' [test ['from' test | ',' test [',' test]]]
import_stmt: import_name | import_from
import_name: 'import' dotted_as_names
import_from: ('from' ('.'* dotted_name | '.'+)
'import' ('*' | '(' import_as_names ')' | import_as_names))
import_as_name: NAME ['as' NAME]
dotted_as_name: dotted_name ['as' NAME]
import_as_names: import_as_name (',' import_as_name)* [',']
dotted_as_names: dotted_as_name (',' dotted_as_name)*
dotted_name: NAME ('.' NAME)*
global_stmt: ('global' | 'nonlocal') NAME (',' NAME)*
exec_stmt: 'exec' expr ['in' test [',' test]]
assert_stmt: 'assert' test [',' test]
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt | match_stmt
async_stmt: ASYNC (funcdef | with_stmt | for_stmt)
if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite]
while_stmt: 'while' namedexpr_test ':' suite ['else' ':' suite]
for_stmt: 'for' exprlist 'in' testlist_star_expr ':' suite ['else' ':' suite]
try_stmt: ('try' ':' suite
((except_clause ':' suite)+
['else' ':' suite]
['finally' ':' suite] |
'finally' ':' suite))
with_stmt: 'with' asexpr_test (',' asexpr_test)* ':' suite
# NB compile.c makes sure that the default except clause is last
except_clause: 'except' ['*'] [test [(',' | 'as') test]]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
# Backward compatibility cruft to support:
# [ x for x in lambda: True, lambda: False if x() ]
# even while also allowing:
# lambda x: 5 if x else 2
# (But not a mix of the two)
testlist_safe: old_test [(',' old_test)+ [',']]
old_test: or_test | old_lambdef
old_lambdef: 'lambda' [varargslist] ':' old_test
namedexpr_test: asexpr_test [':=' asexpr_test]
# This is actually not a real rule, though since the parser is very
# limited in terms of the strategy about match/case rules, we are inserting
# a virtual case (<expr> as <expr>) as a valid expression. Unless a better
# approach is thought, the only side effect of this seem to be just allowing
# more stuff to be parser (which would fail on the ast).
asexpr_test: test ['as' test]
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
star_expr: '*' expr
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: [AWAIT] atom trailer* ['**' factor]
atom: ('(' [yield_expr|testlist_gexp] ')' |
'[' [listmaker] ']' |
'{' [dictsetmaker] '}' |
'`' testlist1 '`' |
NAME | NUMBER | STRING+ | '.' '.' '.')
listmaker: (namedexpr_test|star_expr) ( old_comp_for | (',' (namedexpr_test|star_expr))* [','] )
testlist_gexp: (namedexpr_test|star_expr) ( old_comp_for | (',' (namedexpr_test|star_expr))* [','] )
lambdef: 'lambda' [varargslist] ':' test
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: (subscript|star_expr) (',' (subscript|star_expr))* [',']
subscript: test [':=' test] | [test] ':' [test] [sliceop]
sliceop: ':' [test]
exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
testlist: test (',' test)* [',']
dictsetmaker: ( ((test ':' asexpr_test | '**' expr)
(comp_for | (',' (test ':' asexpr_test | '**' expr))* [','])) |
((test [':=' test] | star_expr)
(comp_for | (',' (test [':=' test] | star_expr))* [','])) )
classdef: 'class' NAME ['(' [arglist] ')'] ':' suite
arglist: argument (',' argument)* [',']
# "test '=' test" is really "keyword '=' test", but we have no such token.
# These need to be in a single rule to avoid grammar that is ambiguous
# to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
# we explicitly match '*' here, too, to give it proper precedence.
# Illegal combinations and orderings are blocked in ast.c:
# multiple (test comp_for) arguments are blocked; keyword unpackings
# that precede iterable unpackings are blocked; etc.
argument: ( test [comp_for] |
test ':=' test [comp_for] |
test 'as' test |
test '=' asexpr_test |
'**' test |
'*' test )
comp_iter: comp_for | comp_if
comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
comp_if: 'if' old_test [comp_iter]
# As noted above, testlist_safe extends the syntax allowed in list
# comprehensions and generators. We can't use it indiscriminately in all
# derivations using a comp_for-like pattern because the testlist_safe derivation
# contains comma which clashes with trailing comma in arglist.
#
# This was an issue because the parser would not follow the correct derivation
# when parsing syntactically valid Python code. Since testlist_safe was created
# specifically to handle list comprehensions and generator expressions enclosed
# with parentheses, it's safe to only use it in those. That avoids the issue; we
# can parse code like set(x for x in [],).
#
# The syntax supported by this set of rules is not a valid Python 3 syntax,
# hence the prefix "old".
#
# See https://bugs.python.org/issue27494
old_comp_iter: old_comp_for | old_comp_if
old_comp_for: [ASYNC] 'for' exprlist 'in' testlist_safe [old_comp_iter]
old_comp_if: 'if' old_test [old_comp_iter]
testlist1: test (',' test)*
# not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl: NAME
yield_expr: 'yield' [yield_arg]
yield_arg: 'from' test | testlist_star_expr
# 3.10 match statement definition
# PS: normally the grammar is much much more restricted, but
# at this moment for not trying to bother much with encoding the
# exact same DSL in a LL(1) parser, we will just accept an expression
# and let the ast.parse() step of the safe mode to reject invalid
# grammar.
# The reason why it is more restricted is that, patterns are some
# sort of a DSL (more advanced than our LHS on assignments, but
# still in a very limited python subset). They are not really
# expressions, but who cares. If we can parse them, that is enough
# to reformat them.
match_stmt: "match" subject_expr ':' NEWLINE INDENT case_block+ DEDENT
# This is more permissive than the actual version. For example it
# accepts `match *something:`, even though single-item starred expressions
# are forbidden.
subject_expr: (namedexpr_test|star_expr) (',' (namedexpr_test|star_expr))* [',']
# cases
case_block: "case" patterns [guard] ':' suite
guard: 'if' namedexpr_test
patterns: pattern (',' pattern)* [',']
pattern: (expr|star_expr) ['as' expr]
================================================
FILE: third_party/yapf_third_party/_ylib2to3/LICENSE
================================================
A. HISTORY OF THE SOFTWARE
==========================
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations, which became
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.
All Python releases are Open Source (see https://opensource.org for
the Open Source Definition). Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.
Release Derived Year Owner GPL-
from compatible? (1)
0.9.0 thru 1.2 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI yes (2)
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2 and above 2.1.1 2001-now PSF yes
Footnotes:
(1) GPL-compatible doesn't mean that we're distributing Python under
the GPL. All Python licenses, unlike the GPL, let you distribute
a modified version without making your changes open source. The
GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
because its license has a choice of law clause. According to
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
is "not incompatible" with the GPL.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Python Software Foundation; All
Rights Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS"
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee. Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement. This Agreement together with
Python 1.6.1 may be located on the Internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the Internet
using the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
================================================
FILE: third_party/yapf_third_party/_ylib2to3/PatternGrammar.txt
================================================
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
# A grammar to describe tree matching patterns.
# Not shown here:
# - 'TOKEN' stands for any token (leaf node)
# - 'any' stands for any node (leaf or interior)
# With 'any' we can still specify the sub-structure.
# The start symbol is 'Matcher'.
Matcher: Alternatives ENDMARKER
Alternatives: Alternative ('|' Alternative)*
Alternative: (Unit | NegatedUnit)+
Unit: [NAME '='] ( STRING [Repeater]
| NAME [Details] [Repeater]
| '(' Alternatives ')' [Repeater]
| '[' Alternatives ']'
)
NegatedUnit: 'not' (STRING | NAME [Details] | '(' Alternatives ')')
Repeater: '*' | '+' | '{' NUMBER [',' NUMBER] '}'
Details: '<' Alternatives '>'
================================================
FILE: third_party/yapf_third_party/_ylib2to3/README.rst
================================================
A fork of python's lib2to3 with select features backported from black's blib2to3.
Reasons for forking:
- black's fork of lib2to3 already considers newer features like Structured Pattern matching
- lib2to3 itself is deprecated and no longer getting support
Maintenance moving forward:
- Most changes moving forward should only have to be done to the grammar files in this project.
================================================
FILE: third_party/yapf_third_party/_ylib2to3/__init__.py
================================================
"""fork of python's lib2to3 with some backports from black's blib2to3"""
================================================
FILE: third_party/yapf_third_party/_ylib2to3/fixer_base.py
================================================
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Base class for fixers (optional, but recommended)."""
# Python imports
import itertools
from . import pygram
from .fixer_util import does_tree_import
# Local imports
from .patcomp import PatternCompiler
class BaseFix(object):
"""Optional base class for fixers.
The subclass name must be FixFooBar where FooBar is the result of
removing underscores and capitalizing the words of the fix name.
For example, the class name for a fixer named 'has_key' should be
FixHasKey.
"""
PATTERN = None # Most subclasses should override with a string literal
pattern = None # Compiled pattern, set by compile_pattern()
pattern_tree = None # Tree representation of the pattern
options = None # Options object passed to initializer
filename = None # The filename (set by set_filename)
numbers = itertools.count(1) # For new_name()
used_names = set() # A set of all used NAMEs
order = 'post' # Does the fixer prefer pre- or post-order traversal
explicit = False # Is this ignored by refactor.py -f all?
run_order = 5 # Fixers will be sorted by run order before execution
# Lower numbers will be run first.
_accept_type = None # [Advanced and not public] This tells RefactoringTool
# which node type to accept when there's not a pattern.
keep_line_order = False # For the bottom matcher: match with the
# original line order
BM_compatible = False # Compatibility with the bottom matching
# module; every fixer should set this
# manually
# Shortcut for access to Python grammar symbols
syms = pygram.python_symbols
def __init__(self, options, log):
"""Initializer. Subclass may override.
Args:
options: a dict containing the options passed to RefactoringTool
that could be used to customize the fixer through the command line.
log: a list to append warnings and other messages to.
"""
self.options = options
self.log = log
self.compile_pattern()
def compile_pattern(self):
"""Compiles self.PATTERN into self.pattern.
Subclass may override if it doesn't want to use
self.{pattern,PATTERN} in .match().
"""
if self.PATTERN is not None:
PC = PatternCompiler()
self.pattern, self.pattern_tree = PC.compile_pattern(
self.PATTERN, with_tree=True)
def set_filename(self, filename):
"""Set the filename.
The main refactoring tool should call this.
"""
self.filename = filename
def match(self, node):
"""Returns match for a given parse tree node.
Should return a true or false object (not necessarily a bool).
It may return a non-empty dict of matching sub-nodes as
returned by a matching pattern.
Subclass may override.
"""
results = {'node': node}
return self.pattern.match(node, results) and results
def transform(self, node, results):
"""Returns the transformation for a given parse tree node.
Args:
node: the root of the parse tree that matched the fixer.
results: a dict mapping symbolic names to part of the match.
Returns:
None, or a node that is a modified copy of the
argument node. The node argument may also be modified in-place to
effect the same change.
Subclass *must* override.
"""
raise NotImplementedError()
def new_name(self, template='xxx_todo_changeme'):
"""Return a string suitable for use as an identifier
The new name is guaranteed not to conflict with other identifiers.
"""
name = template
while name in self.used_names:
name = template + str(next(self.numbers))
self.used_names.add(name)
return name
def log_message(self, message):
if self.first_log:
self.first_log = False
self.log.append('### In file %s ###' % self.filename)
self.log.append(message)
def cannot_convert(self, node, reason=None):
"""Warn the user that a given chunk of code is not valid Python 3,
but that it cannot be converted automatically.
First argument is the top-level node for the code in question.
Optional second argument is why it can't be converted.
"""
lineno = node.get_lineno()
for_output = node.clone()
for_output.prefix = ''
msg = 'Line %d: could not convert: %s'
self.log_message(msg % (lineno, for_output))
if reason:
self.log_message(reason)
def warning(self, node, reason):
"""Used for warning the user about possible uncertainty in the translation.
First argument is the top-level node for the code in question.
Optional second argument is why it can't be converted.
"""
lineno = node.get_lineno()
self.log_message('Line %d: %s' % (lineno, reason))
def start_tree(self, tree, filename):
"""Some fixers need to maintain tree-wide state.
This method is called once, at the start of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from.
"""
self.used_names = tree.used_names
self.set_filename(filename)
self.numbers = itertools.count(1)
self.first_log = True
def finish_tree(self, tree, filename):
"""Some fixers need to maintain tree-wide state.
This method is called once, at the conclusion of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from.
"""
pass
class ConditionalFix(BaseFix):
""" Base class for fixers which not execute if an import is found. """
# This is the name of the import which, if found, will cause the test to be
# skipped.
skip_on = None
def start_tree(self, *args):
super(ConditionalFix, self).start_tree(*args)
self._should_skip = None
def should_skip(self, node):
if self._should_skip is not None:
return self._should_skip
pkg = self.skip_on.split('.')
name = pkg[-1]
pkg = '.'.join(pkg[:-1])
self._should_skip = does_tree_import(pkg, name, node)
return self._should_skip
================================================
FILE: third_party/yapf_third_party/_ylib2to3/fixer_util.py
================================================
"""Utility functions, node construction macros, etc."""
# Author: Collin Winter
from . import patcomp
# Local imports
from .pgen2 import token
from .pygram import python_symbols as syms
from .pytree import Leaf
from .pytree import Node
###########################################################
# Common node-construction "macros"
###########################################################
def KeywordArg(keyword, value):
return Node(syms.argument, [keyword, Leaf(token.EQUAL, '='), value])
def LParen():
return Leaf(token.LPAR, '(')
def RParen():
return Leaf(token.RPAR, ')')
def Assign(target, source):
"""Build an assignment statement"""
if not isinstance(target, list):
target = [target]
if not isinstance(source, list):
source.prefix = ' '
source = [source]
return Node(syms.atom, target + [Leaf(token.EQUAL, '=', prefix=' ')] + source)
def Name(name, prefix=None):
"""Return a NAME leaf"""
return Leaf(token.NAME, name, prefix=prefix)
def Attr(obj, attr):
"""A node tuple for obj.attr"""
return [obj, Node(syms.trailer, [Dot(), attr])]
def Comma():
"""A comma leaf"""
return Leaf(token.COMMA, ',')
def Dot():
"""A period (.) leaf"""
return Leaf(token.DOT, '.')
def ArgList(args, lparen=LParen(), rparen=RParen()):
"""A parenthesised argument list, used by Call()"""
node = Node(syms.trailer, [lparen.clone(), rparen.clone()])
if args:
node.insert_child(1, Node(syms.arglist, args))
return node
def Call(func_name, args=None, prefix=None):
"""A function call"""
node = Node(syms.power, [func_name, ArgList(args)])
if prefix is not None:
node.prefix = prefix
return node
def Newline():
"""A newline literal"""
return Leaf(token.NEWLINE, '\n')
def BlankLine():
"""A blank line"""
return Leaf(token.NEWLINE, '')
def Number(n, prefix=None):
return Leaf(token.NUMBER, n, prefix=prefix)
def Subscript(index_node):
"""A numeric or string subscript"""
return Node(syms.trailer,
[Leaf(token.LBRACE, '['), index_node,
Leaf(token.RBRACE, ']')])
def String(string, prefix=None):
"""A string leaf"""
return Leaf(token.STRING, string, prefix=prefix)
def ListComp(xp, fp, it, test=None):
"""A list comprehension of the form [xp for fp in it if test].
If test is None, the "if test" part is omitted.
"""
xp.prefix = ''
fp.prefix = ' '
it.prefix = ' '
for_leaf = Leaf(token.NAME, 'for')
for_leaf.prefix = ' '
in_leaf = Leaf(token.NAME, 'in')
in_leaf.prefix = ' '
inner_args = [for_leaf, fp, in_leaf, it]
if test:
test.prefix = ' '
if_leaf = Leaf(token.NAME, 'if')
if_leaf.prefix = ' '
inner_args.append(Node(syms.comp_if, [if_leaf, test]))
inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)])
return Node(syms.atom,
[Leaf(token.LBRACE, '['), inner,
Leaf(token.RBRACE, ']')])
def FromImport(package_name, name_leafs):
""" Return an import statement in the form:
from package import name_leafs
"""
# XXX: May not handle dotted imports properly (eg, package_name='foo.bar')
# #assert package_name == '.' or '.' not in package_name, "FromImport has "\
# "not been tested with dotted package names -- use at your own "\
# "peril!"
for leaf in name_leafs:
# Pull the leaves out of their old tree
leaf.remove()
children = [
Leaf(token.NAME, 'from'),
Leaf(token.NAME, package_name, prefix=' '),
Leaf(token.NAME, 'import', prefix=' '),
Node(syms.import_as_names, name_leafs)
]
imp = Node(syms.import_from, children)
return imp
def ImportAndCall(node, results, names):
"""Returns an import statement and calls a method of the module:
import module
module.name()
"""
obj = results['obj'].clone()
if obj.type == syms.arglist:
newarglist = obj.clone()
else:
newarglist = Node(syms.arglist, [obj.clone()])
after = results['after']
if after:
after = [n.clone() for n in after]
new = Node(
syms.power,
Attr(Name(names[0]), Name(names[1])) + [
Node(syms.trailer,
[results['lpar'].clone(), newarglist, results['rpar'].clone()])
] + after)
new.prefix = node.prefix
return new
###########################################################
# Determine whether a node represents a given literal
###########################################################
def is_tuple(node):
"""Does the node represent a tuple literal?"""
if isinstance(node, Node) and node.children == [LParen(), RParen()]:
return True
return (isinstance(node, Node) and len(node.children) == 3 and
isinstance(node.children[0], Leaf) and
isinstance(node.children[1], Node) and
isinstance(node.children[2], Leaf) and
node.children[0].value == '(' and node.children[2].value == ')')
def is_list(node):
"""Does the node represent a list literal?"""
return (isinstance(node, Node) and len(node.children) > 1 and
isinstance(node.children[0], Leaf) and
isinstance(node.children[-1], Leaf) and
node.children[0].value == '[' and node.children[-1].value == ']')
###########################################################
# Misc
###########################################################
def parenthesize(node):
return Node(syms.atom, [LParen(), node, RParen()])
consuming_calls = {
'sorted', 'list', 'set', 'any', 'all', 'tuple', 'sum', 'min', 'max',
'enumerate'
}
def attr_chain(obj, attr):
"""Follow an attribute chain.
If you have a chain of objects where a.foo -> b, b.foo-> c, etc, use this to
iterate over all objects in the chain. Iteration is terminated by getattr(x,
attr) is None.
Args:
obj: the starting object
attr: the name of the chaining attribute
Yields:
Each successive object in the chain.
"""
next = getattr(obj, attr)
while next:
yield next
next = getattr(next, attr)
p0 = """for_stmt< 'for' any 'in' node=any ':' any* >
| comp_for< 'for' any 'in' node=any any* >
"""
p1 = """
power<
( 'iter' | 'list' | 'tuple' | 'sorted' | 'set' | 'sum' |
'any' | 'all' | 'enumerate' | (any* trailer< '.' 'join' >) )
trailer< '(' node=any ')' >
any*
>
"""
p2 = """
power<
( 'sorted' | 'enumerate' )
trailer< '(' arglist<node=any any*> ')' >
any*
>
"""
pats_built = False
def in_special_context(node):
""" Returns true if node is in an environment where all that is required
of it is being iterable (ie, it doesn't matter if it returns a list
or an iterator).
See test_map_nochange in test_fixers.py for some examples and tests.
"""
global p0, p1, p2, pats_built
if not pats_built:
p0 = patcomp.compile_pattern(p0)
p1 = patcomp.compile_pattern(p1)
p2 = patcomp.compile_pattern(p2)
pats_built = True
patterns = [p0, p1, p2]
for pattern, parent in zip(patterns, attr_chain(node, 'parent')):
results = {}
if pattern.match(parent, results) and results['node'] is node:
return True
return False
def is_probably_builtin(node):
"""Check that something isn't an attribute or function name etc."""
prev = node.prev_sibling
if prev is not None and prev.type == token.DOT:
# Attribute lookup.
return False
parent = node.parent
if parent.type in (syms.funcdef, syms.classdef):
return False
if parent.type == syms.expr_stmt and parent.children[0] is node:
# Assignment.
return False
if parent.type == syms.parameters or (parent.type == syms.typedargslist and (
(prev is not None and prev.type == token.COMMA) or
parent.children[0] is node)):
# The name of an argument.
return False
return True
def find_indentation(node):
"""Find the indentation of *node*."""
while node is not None:
if node.type == syms.suite and len(node.children) > 2:
indent = node.children[1]
if indent.type == token.INDENT:
return indent.value
node = node.parent
return ''
###########################################################
# The following functions are to find bindings in a suite
###########################################################
def make_suite(node):
if node.type == syms.suite:
return node
node = node.clone()
parent, node.parent = node.parent, None
suite = Node(syms.suite, [node])
suite.parent = parent
return suite
def find_root(node):
"""Find the top level namespace."""
# Scamper up to the top level namespace
while node.type != syms.file_input:
node = node.parent
if not node:
raise ValueError('root found before file_input node was found.')
return node
def does_tree_import(package, name, node):
""" Returns true if name is imported from package at the
top level of the tree which node belongs to.
To cover the case of an import like 'import foo', use
None for the package and 'foo' for the name.
"""
binding = find_binding(name, find_root(node), package)
return bool(binding)
def is_import(node):
"""Returns true if the node is an import statement."""
return node.type in (syms.import_name, syms.import_from)
def touch_import(package, name, node):
""" Works like `does_tree_import` but adds an import statement
if it was not imported. """
def is_import_stmt(node):
return (node.type == syms.simple_stmt and node.children and
is_import(node.children[0]))
root = find_root(node)
if does_tree_import(package, name, root):
return
# figure out where to insert the new import. First try to find
# the first import and then skip to the last one.
insert_pos = offset = 0
for idx, node in enumerate(root.children):
if not is_import_stmt(node):
continue
for offset, node2 in enumerate(root.children[idx:]):
if not is_import_stmt(node2):
break
insert_pos = idx + offset
break
# if there are no imports where we can insert, find the docstring.
# if that also fails, we stick to the beginning of the file
if insert_pos == 0:
for idx, node in enumerate(root.children):
if (node.type == syms.simple_stmt and node.children and
node.children[0].type == token.STRING):
insert_pos = idx + 1
break
if package is None:
import_ = Node(
syms.import_name,
[Leaf(token.NAME, 'import'),
Leaf(token.NAME, name, prefix=' ')])
else:
import_ = FromImport(package, [Leaf(token.NAME, name, prefix=' ')])
children = [import_, Newline()]
root.insert_child(insert_pos, Node(syms.simple_stmt, children))
_def_syms = {syms.classdef, syms.funcdef}
def find_binding(name, node, package=None):
""" Returns the node which binds variable name, otherwise None.
If optional argument package is supplied, only imports will
be returned.
See test cases for examples.
"""
for child in node.children:
ret = None
if child.type == syms.for_stmt:
if _find(name, child.children[1]):
return child
n = find_binding(name, make_suite(child.children[-1]), package)
if n:
ret = n
elif child.type in (syms.if_stmt, syms.while_stmt):
n = find_binding(name, make_suite(child.children[-1]), package)
if n:
ret = n
elif child.type == syms.try_stmt:
n = find_binding(name, make_suite(child.children[2]), package)
if n:
ret = n
else:
for i, kid in enumerate(child.children[3:]):
if kid.type == token.COLON and kid.value == ':':
# i+3 is the colon, i+4 is the suite
n = find_binding(name, make_suite(child.children[i + 4]), package)
if n:
ret = n
elif child.type in _def_syms and child.children[1].value == name:
ret = child
elif _is_import_binding(child, name, package):
ret = child
elif child.type == syms.simple_stmt:
ret = find_binding(name, child, package)
elif child.type == syms.expr_stmt:
if _find(name, child.children[0]):
ret = child
if ret:
if not package:
return ret
if is_import(ret):
return ret
return None
_block_syms = {syms.funcdef, syms.classdef, syms.trailer}
def _find(name, node):
nodes = [node]
while nodes:
node = nodes.pop()
if node.type > 256 and node.type not in _block_syms:
nodes.extend(node.children)
elif node.type == token.NAME and node.value == name:
return node
return None
def _is_import_binding(node, name, package=None):
""" Will return node if node will import name, or node
will import * from package. None is returned otherwise.
See test cases for examples.
"""
if node.type == syms.import_name and not package:
imp = node.children[1]
if imp.type == syms.dotted_as_names:
for child in imp.children:
if child.type == syms.dotted_as_name:
if child.children[2].value == name:
return node
elif child.type == token.NAME and child.value == name:
return node
elif imp.type == syms.dotted_as_name:
last = imp.children[-1]
if last.type == token.NAME and last.value == name:
return node
elif imp.type == token.NAME and imp.value == name:
return node
elif node.type == syms.import_from:
# str(...) is used to make life easier here, because
# from a.b import parses to ['import', ['a', '.', 'b'], ...]
if package and str(node.children[1]).strip() != package:
return None
n = node.children[3]
if package and _find('as', n):
# See test_from_import_as for explanation
return None
elif n.type == syms.import_as_names and _find(name, n):
return node
elif n.type == syms.import_as_name:
child = n.children[2]
if child.type == token.NAME and child.value == name:
return node
elif n.type == token.NAME and n.value == name:
return node
elif package and n.type == token.STAR:
return node
return None
================================================
FILE: third_party/yapf_third_party/_ylib2to3/patcomp.py
================================================
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Pattern compiler.
The grammar is taken from PatternGrammar.txt.
The compiler compiles a pattern to a pytree.*Pattern instance.
"""
__author__ = 'Guido van Rossum <guido@python.org>'
# Python imports
import io
# Really local imports
from . import pygram
from . import pytree
# Fairly local imports
from .pgen2 import driver
from .pgen2 import grammar
from .pgen2 import literals
from .pgen2 import parse
from .pgen2 import token
from .pgen2 import tokenize
class PatternSyntaxError(Exception):
pass
def tokenize_wrapper(input):
"""Tokenizes a string suppressing significant whitespace."""
skip = {token.NEWLINE, token.INDENT, token.DEDENT}
tokens = tokenize.generate_tokens(io.StringIO(input).readline)
for quintuple in tokens:
type, value, start, end, line_text = quintuple
if type not in skip:
yield quintuple
class PatternCompiler(object):
def __init__(self, grammar_file=None):
"""Initializer.
Takes an optional alternative filename for the pattern grammar.
"""
if grammar_file is None:
self.grammar = pygram.pattern_grammar
self.syms = pygram.pattern_symbols
else:
self.grammar = driver.load_grammar(grammar_file)
self.syms = pygram.Symbols(self.grammar)
self.pygrammar = pygram.python_grammar
self.pysyms = pygram.python_symbols
self.driver = driver.Driver(self.grammar, convert=pattern_convert)
def compile_pattern(self, input, debug=False, with_tree=False):
"""Compiles a pattern string to a nested pytree.*Pattern object."""
tokens = tokenize_wrapper(input)
try:
root = self.driver.parse_tokens(tokens, debug=debug)
except parse.ParseError as e:
raise PatternSyntaxError(str(e)) from None
if with_tree:
return self.compile_node(root), root
else:
return self.compile_node(root)
def compile_node(self, node):
"""Compiles a node, recursively.
This is one big switch on the node type.
"""
# XXX Optimize certain Wildcard-containing-Wildcard patterns
# that can be merged
if node.type == self.syms.Matcher:
node = node.children[0] # Avoid unneeded recursion
if node.type == self.syms.Alternatives:
# Skip the odd children since they are just '|' tokens
alts = [self.compile_node(ch) for ch in node.children[::2]]
if len(alts) == 1:
return alts[0]
p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1)
return p.optimize()
if node.type == self.syms.Alternative:
units = [self.compile_node(ch) for ch in node.children]
if len(units) == 1:
return units[0]
p = pytree.WildcardPattern([units], min=1, max=1)
return p.optimize()
if node.type == self.syms.NegatedUnit:
pattern = self.compile_basic(node.children[1:])
p = pytree.NegatedPattern(pattern)
return p.optimize()
assert node.type == self.syms.Unit
name = None
nodes = node.children
if len(nodes) >= 3 and nodes[1].type == token.EQUAL:
name = nodes[0].value
nodes = nodes[2:]
repeat = None
if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater:
repeat = nodes[-1]
nodes = nodes[:-1]
# Now we've reduced it to: STRING | NAME [Details] | (...) | [...]
pattern = self.compile_basic(nodes, repeat)
if repeat is not None:
assert repeat.type == self.syms.Repeater
children = repeat.children
child = children[0]
if child.type == token.STAR:
min = 0
max = pytree.HUGE
elif child.type == token.PLUS:
min = 1
max = pytree.HUGE
elif child.type == token.LBRACE:
assert children[-1].type == token.RBRACE
assert len(children) in (3, 5)
min = max = self.get_int(children[1])
if len(children) == 5:
max = self.get_int(children[3])
else:
assert False
if min != 1 or max != 1:
pattern = pattern.optimize()
pattern = pytree.WildcardPattern([[pattern]], min=min, max=max)
if name is not None:
pattern.name = name
return pattern.optimize()
def compile_basic(self, nodes, repeat=None):
# Compile STRING | NAME [Details] | (...) | [...]
assert len(nodes) >= 1
node = nodes[0]
if node.type == token.STRING:
value = str(literals.evalString(node.value))
return pytree.LeafPattern(_type_of_literal(value), value)
elif node.type == token.NAME:
value = node.value
if value.isupper():
if value not in TOKEN_MAP:
raise PatternSyntaxError('Invalid token: %r' % value)
if nodes[1:]:
raise PatternSyntaxError("Can't have details for token")
return pytree.LeafPattern(TOKEN_MAP[value])
else:
if value == 'any':
type = None
elif not value.startswith('_'):
type = getattr(self.pysyms, value, None)
if type is None:
raise PatternSyntaxError('Invalid symbol: %r' % value)
if nodes[1:]: # Details present
content = [self.compile_node(nodes[1].children[1])]
else:
content = None
return pytree.NodePattern(type, content)
elif node.value == '(':
return self.compile_node(nodes[1])
elif node.value == '[':
assert repeat is None
subpattern = self.compile_node(nodes[1])
return pytree.WildcardPattern([[subpattern]], min=0, max=1)
assert False, node
def get_int(self, node):
assert node.type == token.NUMBER
return int(node.value)
# Map named tokens to the type value for a LeafPattern
TOKEN_MAP = {
'NAME': token.NAME,
'STRING': token.STRING,
'NUMBER': token.NUMBER,
'TOKEN': None
}
def _type_of_literal(value):
if value[0].isalpha():
return token.NAME
elif value in grammar.opmap:
return grammar.opmap[value]
else:
return None
def pattern_convert(grammar, raw_node_info):
"""Converts raw node information to a Node or Leaf instance."""
type, value, context, children = raw_node_info
if children or type in grammar.number2symbol:
return pytree.Node(type, children, context=context)
else:
return pytree.Leaf(type, value, context=context)
def compile_pattern(pattern):
return PatternCompiler().compile_pattern(pattern)
================================================
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/__init__.py
================================================
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""The pgen2 package."""
================================================
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/conv.py
================================================
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Convert graminit.[ch] spit out by pgen to Python code.
Pgen is the Python parser generator. It is useful to quickly create a
parser from a grammar file in Python's grammar notation. But I don't
want my parsers to be written in C (yet), so I'm translating the
parsing tables to Python data structures and writing a Python parse
engine.
Note that the token numbers are constants determined by the standard
Python tokenizer. The standard token module defines these numbers and
their names (the names are not used much). The token numbers are
hardcoded into the Python tokenizer and into pgen. A Python
implementation of the Python tokenizer is also available, in the
standard tokenize module.
On the other hand, symbol numbers (representing the grammar's
non-terminals) are assigned by pgen based on the actual grammar
input.
Note: this module is pretty much obsolete; the pgen module generates
equivalent grammar tables directly from the Grammar.txt input file
without having to invoke the Python pgen C program.
"""
# Python imports
import re
# Local imports
from pgen2 import grammar
from pgen2 import token
class Converter(grammar.Grammar):
"""Grammar subclass that reads classic pgen output files.
The run() method reads the tables as produced by the pgen parser
generator, typically contained in two C files, graminit.h and
graminit.c. The other methods are for internal use only.
See the base class for more documentation.
"""
def run(self, graminit_h, graminit_c):
"""Load the grammar tables from the text files written by pgen."""
self.parse_graminit_h(graminit_h)
self.parse_graminit_c(graminit_c)
self.finish_off()
def parse_graminit_h(self, filename):
"""Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back.
"""
try:
f = open(filename)
except OSError as err:
print("Can't open %s: %s" % (filename, err))
return False
self.symbol2number = {}
self.number2symbol = {}
lineno = 0
for line in f:
lineno += 1
mo = re.match(r'^#define\s+(\w+)\s+(\d+)$', line)
if not mo and line.strip():
print("%s(%s): can't parse %s" % (filename, lineno, line.strip()))
else:
symbol, number = mo.groups()
number = int(number)
assert symbol not in self.symbol2number
assert number not in self.number2symbol
self.symbol2number[symbol] = number
self.number2symbol[number] = symbol
return True
def parse_graminit_c(self, filename):
"""Parse the .c file written by pgen. (Internal)
The file looks as follows. The first two lines are always this:
#include "pgenheaders.h"
#include "grammar.h"
After that come four blocks:
1) one or more state definitions
2) a table defining dfas
3) a table defining labels
4) a struct defining the grammar
A state definition has the following form:
- one or more arc arrays, each of the form:
static arc arcs_<n>_<m>[<k>] = {
{<i>, <j>},
...
};
- followed by a state array, of the form:
static state states_<s>[<t>] = {
{<k>, arcs_<n>_<m>},
...
};
"""
try:
f = open(filename)
except OSError as err:
print("Can't open %s: %s" % (filename, err))
return False
# The code below essentially uses f's iterator-ness!
lineno = 0
# Expect the two #include lines
lineno, line = lineno + 1, next(f)
assert line == '#include "pgenheaders.h"\n', (lineno, line)
lineno, line = lineno + 1, next(f)
assert line == '#include "grammar.h"\n', (lineno, line)
# Parse the state definitions
lineno, line = lineno + 1, next(f)
allarcs = {}
states = []
while line.startswith('static arc '):
while line.startswith('static arc '):
mo = re.match(r'static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$', line)
assert mo, (lineno, line)
n, m, k = list(map(int, mo.groups()))
arcs = []
for _ in range(k):
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+{(\d+), (\d+)},$', line)
assert mo, (lineno, line)
i, j = list(map(int, mo.groups()))
arcs.append((i, j))
lineno, line = lineno + 1, next(f)
assert line == '};\n', (lineno, line)
allarcs[(n, m)] = arcs
lineno, line = lineno + 1, next(f)
mo = re.match(r'static state states_(\d+)\[(\d+)\] = {$', line)
assert mo, (lineno, line)
s, t = list(map(int, mo.groups()))
assert s == len(states), (lineno, line)
state = []
for _ in range(t):
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+{(\d+), arcs_(\d+)_(\d+)},$', line)
assert mo, (lineno, line)
k, n, m = list(map(int, mo.groups()))
arcs = allarcs[n, m]
assert k == len(arcs), (lineno, line)
state.append(arcs)
states.append(state)
lineno, line = lineno + 1, next(f)
assert line == '};\n', (lineno, line)
lineno, line = lineno + 1, next(f)
self.states = states
# Parse the dfas
dfas = {}
mo = re.match(r'static dfa dfas\[(\d+)\] = {$', line)
assert mo, (lineno, line)
ndfas = int(mo.group(1))
for i in range(ndfas):
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$', line)
assert mo, (lineno, line)
symbol = mo.group(2)
number, x, y, z = list(map(int, mo.group(1, 3, 4, 5)))
assert self.symbol2number[symbol] == number, (lineno, line)
assert self.number2symbol[number] == symbol, (lineno, line)
assert x == 0, (lineno, line)
state = states[z]
assert y == len(state), (lineno, line)
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line)
assert mo, (lineno, line)
first = {}
rawbitset = eval(mo.group(1))
for i, c in enumerate(rawbitset):
byte = ord(c)
for j in range(8):
if byte & (1 << j):
first[i * 8 + j] = 1
dfas[number] = (state, first)
lineno, line = lineno + 1, next(f)
assert line == '};\n', (lineno, line)
self.dfas = dfas
# Parse the labels
labels = []
lineno, line = lineno + 1, next(f)
mo = re.match(r'static label labels\[(\d+)\] = {$', line)
assert mo, (lineno, line)
nlabels = int(mo.group(1))
for i in range(nlabels):
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line)
assert mo, (lineno, line)
x, y = mo.groups()
x = int(x)
if y == '0':
y = None
else:
y = eval(y)
labels.append((x, y))
lineno, line = lineno + 1, next(f)
assert line == '};\n', (lineno, line)
self.labels = labels
# Parse the grammar struct
lineno, line = lineno + 1, next(f)
assert line == 'grammar _PyParser_Grammar = {\n', (lineno, line)
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+(\d+),$', line)
assert mo, (lineno, line)
ndfas = int(mo.group(1))
assert ndfas == len(self.dfas)
lineno, line = lineno + 1, next(f)
assert line == '\tdfas,\n', (lineno, line)
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+{(\d+), labels},$', line)
assert mo, (lineno, line)
nlabels = int(mo.group(1))
assert nlabels == len(self.labels), (lineno, line)
lineno, line = lineno + 1, next(f)
mo = re.match(r'\s+(\d+)$', line)
assert mo, (lineno, line)
start = int(mo.group(1))
assert start in self.number2symbol, (lineno, line)
self.start = start
lineno, line = lineno + 1, next(f)
assert line == '};\n', (lineno, line)
try:
lineno, line = lineno + 1, next(f)
except StopIteration:
pass
else:
assert 0, (lineno, line)
def finish_off(self):
"""Create additional useful structures. (Internal)."""
self.keywords = {} # map from keyword strings to arc labels
self.tokens = {} # map from numeric token values to arc labels
for ilabel, (type, value) in enumerate(self.labels):
if type == token.NAME and value is not None:
self.keywords[value] = ilabel
elif value is None:
self.tokens[type] = ilabel
================================================
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/driver.py
================================================
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
# Modifications:
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Parser driver.
This provides a high-level interface to parse a file into a syntax tree.
"""
__author__ = 'Guido van Rossum <guido@python.org>'
__all__ = ['Driver', 'load_grammar']
import io
import logging
import os
import pkgutil
import sys
# Python imports
from contextlib import contextmanager
from dataclasses import dataclass
from dataclasses import field
from pathlib import Path
from typing import Any
from typing import Iterator
from typing import List
from typing import Optional
from platformdirs import user_cache_dir
from yapf._version import __version__ as yapf_version
# Pgen imports
from . import grammar
from . import parse
from . import pgen
from . import token
from . import tokenize
@dataclass
class ReleaseRange:
start: int
end: Optional[int] = None
tokens: List[Any] = field(default_factory=list)
def lock(self) -> None:
total_eaten = len(self.tokens)
self.end = self.start + total_eaten
class TokenProxy:
def __init__(self, generator: Any) -> None:
self._tokens = generator
self._counter = 0
self._release_ranges: List[ReleaseRange] = []
@contextmanager
def release(self) -> Iterator['TokenProxy']:
release_range = ReleaseRange(self._counter)
self._release_ranges.append(release_range)
try:
yield self
finally:
# Lock the last release range to the final position that
# has been eaten.
release_range.lock()
def eat(self, point: int) -> Any:
eaten_tokens = self._release_ranges[-1].tokens
if point < len(eaten_tokens):
return eaten_tokens[point]
else:
while point >= len(eaten_tokens):
token = next(self._tokens)
eaten_tokens.append(token)
return token
def __iter__(self) -> 'TokenProxy':
return self
def __next__(self) -> Any:
# If the current position is already compromised (looked up)
# return the eaten token, if not just go further on the given
# token producer.
for release_range in self._release_ranges:
assert release_range.end is not None
start, end = release_range.start, release_range.end
if start <= self._counter < end:
token = release_range.tokens[self._counter - start]
break
else:
token = next(self._tokens)
self._counter += 1
return token
def can_advance(self, to: int) -> bool:
# Try to eat, fail if it can't. The eat operation is cached
# so there wont be any additional cost of eating here
try:
self.eat(to)
except StopIteration:
return False
else:
return True
class Driver(object):
def __init__(self, grammar, convert=None, logger=None):
self.grammar = grammar
if logger is None:
logger = logging.getLogger()
self.logger = logger
self.convert = convert
def parse_tokens(self, tokens, debug=False):
"""Parse a series of tokens and return the syntax tree."""
# XXX Move the prefix computation into a wrapper around tokenize.
p = parse.Parser(self.grammar, self.convert)
proxy = TokenProxy(tokens)
p.setup(proxy=proxy)
lineno = 1
column = 0
type = value = start = end = line_text = None
prefix = ''
for quintuple in proxy:
type, value, start, end, line_text = quintuple
if start != (lineno, column):
assert (lineno, column) <= start, ((lineno, column), start)
s_lineno, s_column = start
if lineno < s_lineno:
prefix += '\n' * (s_lineno - lineno)
lineno = s_lineno
column = 0
if column < s_column:
prefix += line_text[column:s_column]
column = s_column
if type in (tokenize.COMMENT, tokenize.NL):
prefix += value
lineno, column = end
if value.endswith('\n'):
lineno += 1
column = 0
continue
if type == token.OP:
type = grammar.opmap[value]
if debug:
self.logger.debug('%s %r (prefix=%r)', token.tok_name[type], value,
prefix)
if p.addtoken(type, value, (prefix, start)):
if debug:
self.logger.debug('Stop.')
break
prefix = ''
lineno, column = end
if value.endswith('\n'):
lineno += 1
column = 0
else:
# We never broke out -- EOF is too soon (how can this happen???)
raise parse.ParseError('incomplete input', type, value, (prefix, start))
return p.rootnode
def parse_stream_raw(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline)
return self.parse_tokens(tokens, debug)
def parse_stream(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
return self.parse_stream_raw(stream, debug)
def parse_file(self, filename, encoding=None, debug=False):
"""Parse a file and return the syntax tree."""
with io.open(filename, 'r', encoding=encoding) as stream:
return self.parse_stream(stream, debug)
def parse_string(self, text, debug=False):
"""Parse a string and return the syntax tree."""
tokens = tokenize.generate_tokens(io.StringIO(text).readline)
return self.parse_tokens(tokens, debug)
def _generate_pickle_name(gt):
# type:(str) -> str
"""Get the filepath to write a pickle file to
given the path of a grammar textfile.
The returned filepath should be in a user-specific cache directory.
Args:
gt (str): path to grammar text file
Returns:
str: path to pickle file
"""
grammar_textfile_name = os.path.basename(gt)
head, tail = os.path.splitext(grammar_textfile_name)
if tail == '.txt':
tail = ''
cache_dir = user_cache_dir(
appname='YAPF', appauthor='Google', version=yapf_version)
return cache_dir + os.sep + head + tail + '-py' + '.'.join(
map(str, sys.version_info)) + '.pickle'
def load_grammar(gt='Grammar.txt',
gp=None,
save=True,
force=False,
logger=None):
# type:(str, str | None, bool, bool, logging.Logger | None) -> grammar.Grammar
"""Load the grammar (maybe from a pickle)."""
if logger is None:
logger = logging.getLogger()
gp = _generate_pickle_name(gt) if gp is None else gp
grammar_text = gt
try:
newer = _newer(gp, gt)
except OSError as err:
logger.debug('OSError, could not check if newer: %s', err.args)
newer = True
if not os.path.exists(gt):
# Assume package data
gt_basename = os.path.basename(gt)
pd = pkgutil.get_data('yapf_third_party._ylib2to3', gt_basename)
if pd is None:
raise RuntimeError('Failed to load grammer %s from package' % gt_basename)
grammar_text = io.StringIO(pd.decode(encoding='utf-8'))
if force or not newer:
g = pgen.generate_grammar(grammar_text)
if save:
try:
Path(gp).parent.mkdir(parents=True, exist_ok=True)
g.dump(gp)
except OSError:
# Ignore error, caching is not vital.
pass
else:
g = grammar.Grammar()
g.load(gp)
return g
def _newer(a, b):
"""Inquire whether file a was written since file b."""
if not os.path.exists(a):
return False
if not os.path.exists(b):
return True
return os.path.getmtime(a) >= os.path.getmtime(b)
def load_packaged_grammar(package, grammar_source):
"""Normally, loads a pickled grammar by doing
pkgutil.get_data(package, pickled_grammar)
where *pickled_grammar* is computed from *grammar_source* by adding the
Python version and using a ``.pickle`` extension.
However, if *grammar_source* is an extant file, load_grammar(grammar_source)
is called instead. This facilitates using a packaged grammar file when needed
but preserves load_grammar's automatic regeneration behavior when possible.
""" # noqa: E501
if os.path.isfile(grammar_source):
return load_grammar(grammar_source)
pickled_name = _generate_pickle_name(os.path.basename(grammar_source))
data = pkgutil.get_data(package, pickled_name)
g = grammar.Grammar()
g.loads(data)
return g
def main(*args):
"""Main program, when run as a script: produce grammar pickle files.
Calls load_grammar for each argument, a path to a grammar text file.
"""
if not args:
args = sys.argv[1:]
logging.basicConfig(
level=logging.INFO, stream=sys.stdout, format='%(message)s')
for gt in args:
load_grammar(gt, save=True, force=True)
return True
if __name__ == '__main__':
sys.exit(int(not main()))
================================================
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/grammar.py
================================================
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""This module defines the data structures used to represent a grammar.
These are a bit arcane because they are derived from the data
structures used by Python's 'pgen' parser generator.
gitextract_3wypp44j/
├── .coveragerc
├── .editorconfig
├── .flake8
├── .gitattributes
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ ├── ci.yml
│ ├── pre-commit-autoupdate.yml
│ └── pre-commit.yml
├── .gitignore
├── .isort.cfg
├── .pre-commit-config.yaml
├── .pre-commit-hooks.yaml
├── .python-version
├── .style.yapf
├── .vimrc
├── .vscode/
│ ├── extensions.json
│ └── settings.default.json
├── AUTHORS
├── CHANGELOG.md
├── CONTRIBUTING.md
├── CONTRIBUTORS
├── EDITOR SUPPORT.md
├── HACKING.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── plugins/
│ ├── README.md
│ ├── pre-commit.sh
│ └── vim/
│ ├── autoload/
│ │ └── yapf.vim
│ └── plugin/
│ └── yapf.vim
├── pylintrc
├── pyproject.toml
├── third_party/
│ ├── __init__.py
│ └── yapf_third_party/
│ ├── __init__.py
│ ├── _ylib2to3/
│ │ ├── Grammar.txt
│ │ ├── LICENSE
│ │ ├── PatternGrammar.txt
│ │ ├── README.rst
│ │ ├── __init__.py
│ │ ├── fixer_base.py
│ │ ├── fixer_util.py
│ │ ├── patcomp.py
│ │ ├── pgen2/
│ │ │ ├── __init__.py
│ │ │ ├── conv.py
│ │ │ ├── driver.py
│ │ │ ├── grammar.py
│ │ │ ├── literals.py
│ │ │ ├── parse.py
│ │ │ ├── pgen.py
│ │ │ ├── token.py
│ │ │ └── tokenize.py
│ │ ├── pygram.py
│ │ └── pytree.py
│ └── yapf_diff/
│ ├── LICENSE
│ ├── __init__.py
│ └── yapf_diff.py
├── tox.ini
├── yapf/
│ ├── __init__.py
│ ├── __main__.py
│ ├── _version.py
│ ├── pyparser/
│ │ ├── __init__.py
│ │ ├── pyparser.py
│ │ ├── pyparser_utils.py
│ │ ├── pyparser_visitor.py.tmpl
│ │ └── split_penalty_visitor.py
│ ├── pytree/
│ │ ├── __init__.py
│ │ ├── blank_line_calculator.py
│ │ ├── comment_splicer.py
│ │ ├── continuation_splicer.py
│ │ ├── pytree_unwrapper.py
│ │ ├── pytree_utils.py
│ │ ├── pytree_visitor.py
│ │ ├── split_penalty.py
│ │ └── subtype_assigner.py
│ └── yapflib/
│ ├── __init__.py
│ ├── errors.py
│ ├── file_resources.py
│ ├── format_decision_state.py
│ ├── format_token.py
│ ├── identify_container.py
│ ├── line_joiner.py
│ ├── logical_line.py
│ ├── object_state.py
│ ├── reformatter.py
│ ├── split_penalty.py
│ ├── style.py
│ ├── subtypes.py
│ └── yapf_api.py
└── yapftests/
├── __init__.py
├── blank_line_calculator_test.py
├── comment_splicer_test.py
├── file_resources_test.py
├── format_decision_state_test.py
├── format_token_test.py
├── line_joiner_test.py
├── logical_line_test.py
├── main_test.py
├── pytree_unwrapper_test.py
├── pytree_utils_test.py
├── pytree_visitor_test.py
├── reformatter_basic_test.py
├── reformatter_buganizer_test.py
├── reformatter_facebook_test.py
├── reformatter_pep8_test.py
├── reformatter_python3_test.py
├── reformatter_style_config_test.py
├── split_penalty_test.py
├── style_test.py
├── subtype_assigner_test.py
├── utils.py
├── yapf_test.py
└── yapf_test_helper.py
SYMBOL INDEX (1494 symbols across 60 files)
FILE: third_party/yapf_third_party/_ylib2to3/fixer_base.py
class BaseFix (line 14) | class BaseFix(object):
method __init__ (line 46) | def __init__(self, options, log):
method compile_pattern (line 58) | def compile_pattern(self):
method set_filename (line 69) | def set_filename(self, filename):
method match (line 76) | def match(self, node):
method transform (line 88) | def transform(self, node, results):
method new_name (line 104) | def new_name(self, template='xxx_todo_changeme'):
method log_message (line 115) | def log_message(self, message):
method cannot_convert (line 121) | def cannot_convert(self, node, reason=None):
method warning (line 136) | def warning(self, node, reason):
method start_tree (line 145) | def start_tree(self, tree, filename):
method finish_tree (line 158) | def finish_tree(self, tree, filename):
class ConditionalFix (line 169) | class ConditionalFix(BaseFix):
method start_tree (line 176) | def start_tree(self, *args):
method should_skip (line 180) | def should_skip(self, node):
FILE: third_party/yapf_third_party/_ylib2to3/fixer_util.py
function KeywordArg (line 16) | def KeywordArg(keyword, value):
function LParen (line 20) | def LParen():
function RParen (line 24) | def RParen():
function Assign (line 28) | def Assign(target, source):
function Name (line 39) | def Name(name, prefix=None):
function Attr (line 44) | def Attr(obj, attr):
function Comma (line 49) | def Comma():
function Dot (line 54) | def Dot():
function ArgList (line 59) | def ArgList(args, lparen=LParen(), rparen=RParen()):
function Call (line 67) | def Call(func_name, args=None, prefix=None):
function Newline (line 75) | def Newline():
function BlankLine (line 80) | def BlankLine():
function Number (line 85) | def Number(n, prefix=None):
function Subscript (line 89) | def Subscript(index_node):
function String (line 96) | def String(string, prefix=None):
function ListComp (line 101) | def ListComp(xp, fp, it, test=None):
function FromImport (line 125) | def FromImport(package_name, name_leafs):
function ImportAndCall (line 149) | def ImportAndCall(node, results, names):
function is_tuple (line 178) | def is_tuple(node):
function is_list (line 189) | def is_list(node):
function parenthesize (line 202) | def parenthesize(node):
function attr_chain (line 212) | def attr_chain(obj, attr):
function in_special_context (line 253) | def in_special_context(node):
function is_probably_builtin (line 273) | def is_probably_builtin(node):
function find_indentation (line 293) | def find_indentation(node):
function make_suite (line 309) | def make_suite(node):
function find_root (line 319) | def find_root(node):
function does_tree_import (line 329) | def does_tree_import(package, name, node):
function is_import (line 339) | def is_import(node):
function touch_import (line 344) | def touch_import(package, name, node):
function find_binding (line 393) | def find_binding(name, node, package=None):
function _find (line 443) | def _find(name, node):
function _is_import_binding (line 454) | def _is_import_binding(node, name, package=None):
FILE: third_party/yapf_third_party/_ylib2to3/patcomp.py
class PatternSyntaxError (line 27) | class PatternSyntaxError(Exception):
function tokenize_wrapper (line 31) | def tokenize_wrapper(input):
class PatternCompiler (line 41) | class PatternCompiler(object):
method __init__ (line 43) | def __init__(self, grammar_file=None):
method compile_pattern (line 58) | def compile_pattern(self, input, debug=False, with_tree=False):
method compile_node (line 70) | def compile_node(self, node):
method compile_basic (line 141) | def compile_basic(self, nodes, repeat=None):
method get_int (line 176) | def get_int(self, node):
function _type_of_literal (line 190) | def _type_of_literal(value):
function pattern_convert (line 199) | def pattern_convert(grammar, raw_node_info):
function compile_pattern (line 208) | def compile_pattern(pattern):
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/conv.py
class Converter (line 36) | class Converter(grammar.Grammar):
method run (line 47) | def run(self, graminit_h, graminit_c):
method parse_graminit_h (line 53) | def parse_graminit_h(self, filename):
method parse_graminit_c (line 83) | def parse_graminit_c(self, filename):
method finish_off (line 246) | def finish_off(self):
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/driver.py
class ReleaseRange (line 45) | class ReleaseRange:
method lock (line 50) | def lock(self) -> None:
class TokenProxy (line 55) | class TokenProxy:
method __init__ (line 57) | def __init__(self, generator: Any) -> None:
method release (line 63) | def release(self) -> Iterator['TokenProxy']:
method eat (line 73) | def eat(self, point: int) -> Any:
method __iter__ (line 83) | def __iter__(self) -> 'TokenProxy':
method __next__ (line 86) | def __next__(self) -> Any:
method can_advance (line 102) | def can_advance(self, to: int) -> bool:
class Driver (line 113) | class Driver(object):
method __init__ (line 115) | def __init__(self, grammar, convert=None, logger=None):
method parse_tokens (line 122) | def parse_tokens(self, tokens, debug=False):
method parse_stream_raw (line 170) | def parse_stream_raw(self, stream, debug=False):
method parse_stream (line 175) | def parse_stream(self, stream, debug=False):
method parse_file (line 179) | def parse_file(self, filename, encoding=None, debug=False):
method parse_string (line 184) | def parse_string(self, text, debug=False):
function _generate_pickle_name (line 190) | def _generate_pickle_name(gt):
function load_grammar (line 214) | def load_grammar(gt='Grammar.txt',
function _newer (line 252) | def _newer(a, b):
function load_packaged_grammar (line 261) | def load_packaged_grammar(package, grammar_source):
function main (line 281) | def main(*args):
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/grammar.py
class Grammar (line 23) | class Grammar(object):
method __init__ (line 77) | def __init__(self):
method dump (line 89) | def dump(self, filename):
method load (line 125) | def load(self, filename):
method loads (line 131) | def loads(self, pkl):
method copy (line 135) | def copy(self):
method report (line 148) | def report(self):
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/literals.py
function escape (line 21) | def escape(m):
function evalString (line 43) | def evalString(s):
function test (line 54) | def test():
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/parse.py
function stack_copy (line 38) | def stack_copy(
class Recorder (line 44) | class Recorder:
method __init__ (line 46) | def __init__(self, parser: 'Parser', ilabels: List[int],
method ilabels (line 57) | def ilabels(self) -> Set[int]:
method switch_to (line 61) | def switch_to(self, ilabel: int) -> Iterator[None]:
method backtrack (line 72) | def backtrack(self) -> Iterator[None]:
method add_token (line 88) | def add_token(self, tok_type: int, tok_val: Text, raw: bool = False) -...
method determine_route (line 102) | def determine_route(self,
class ParseError (line 117) | class ParseError(Exception):
method __init__ (line 120) | def __init__(self, msg, type, value, context):
method __reduce__ (line 128) | def __reduce__(self):
class Parser (line 132) | class Parser(object):
method __init__ (line 162) | def __init__(self, grammar, convert=None):
method setup (line 195) | def setup(self, proxy, start=None):
method addtoken (line 220) | def addtoken(self, type, value, context):
method _addtoken (line 269) | def _addtoken(self, ilabel: int, type: int, value: Text,
method classify (line 315) | def classify(self, type, value, context):
method shift (line 338) | def shift(self, type: int, value: Text, newstate: int,
method push (line 352) | def push(self, type: int, newdfa: DFAS, newstate: int,
method pop (line 365) | def pop(self) -> None:
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/pgen.py
class PgenGrammar (line 12) | class PgenGrammar(grammar.Grammar):
class ParserGenerator (line 16) | class ParserGenerator(object):
method __init__ (line 18) | def __init__(self, filename=None, stream=None):
method make_grammar (line 36) | def make_grammar(self):
method make_first (line 61) | def make_first(self, c, name):
method make_label (line 70) | def make_label(self, c, label):
method addfirstsets (line 121) | def addfirstsets(self):
method calcfirst (line 129) | def calcfirst(self, name):
method parse (line 159) | def parse(self):
method make_dfa (line 181) | def make_dfa(self, start, finish):
method dump_nfa (line 220) | def dump_nfa(self, name, start, finish):
method dump_dfa (line 236) | def dump_dfa(self, name, dfa):
method simplify_dfa (line 243) | def simplify_dfa(self, dfa):
method parse_rhs (line 264) | def parse_rhs(self):
method parse_alt (line 281) | def parse_alt(self):
method parse_item (line 290) | def parse_item(self):
method parse_atom (line 310) | def parse_atom(self):
method expect (line 327) | def expect(self, type, value=None):
method gettoken (line 335) | def gettoken(self):
method raise_error (line 342) | def raise_error(self, msg, *args):
class NFAState (line 351) | class NFAState(object):
method __init__ (line 353) | def __init__(self):
method addarc (line 356) | def addarc(self, next, label=None):
class DFAState (line 362) | class DFAState(object):
method __init__ (line 364) | def __init__(self, nfaset, final):
method addarc (line 372) | def addarc(self, next, label):
method unifystate (line 378) | def unifystate(self, old, new):
method __eq__ (line 383) | def __eq__(self, other):
function generate_grammar (line 400) | def generate_grammar(filename_or_stream='Grammar.txt'):
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/token.py
function ISTERMINAL (line 79) | def ISTERMINAL(x):
function ISNONTERMINAL (line 83) | def ISNONTERMINAL(x):
function ISEOF (line 87) | def ISEOF(x):
FILE: third_party/yapf_third_party/_ylib2to3/pgen2/tokenize.py
function group (line 64) | def group(*choices):
function any (line 68) | def any(*choices):
function maybe (line 72) | def maybe(*choices):
function _combinations (line 76) | def _combinations(*l): # noqa: E741
class TokenError (line 164) | class TokenError(Exception):
class StopTokenizing (line 168) | class StopTokenizing(Exception):
function printtoken (line 172) | def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1,
function tokenize (line 180) | def tokenize(readline, tokeneater=printtoken):
function tokenize_loop (line 200) | def tokenize_loop(readline, tokeneater):
class Untokenizer (line 205) | class Untokenizer:
method __init__ (line 207) | def __init__(self):
method add_whitespace (line 212) | def add_whitespace(self, start):
method untokenize (line 219) | def untokenize(self, iterable):
method compat (line 233) | def compat(self, token, iterable):
function _get_normal_name (line 266) | def _get_normal_name(orig_enc):
function detect_encoding (line 278) | def detect_encoding(readline):
function untokenize (line 353) | def untokenize(iterable):
function generate_tokens (line 375) | def generate_tokens(readline):
FILE: third_party/yapf_third_party/_ylib2to3/pygram.py
class Symbols (line 17) | class Symbols(object):
method __init__ (line 19) | def __init__(self, grammar):
FILE: third_party/yapf_third_party/_ylib2to3/pytree.py
function type_repr (line 27) | def type_repr(type_num):
class Base (line 45) | class Base(object):
method __new__ (line 62) | def __new__(cls, *args, **kwds):
method __eq__ (line 67) | def __eq__(self, other):
method _eq (line 79) | def _eq(self, other):
method clone (line 90) | def clone(self):
method post_order (line 98) | def post_order(self):
method pre_order (line 106) | def pre_order(self):
method replace (line 114) | def replace(self, new):
method get_lineno (line 137) | def get_lineno(self):
method changed (line 146) | def changed(self):
method remove (line 151) | def remove(self):
method next_sibling (line 165) | def next_sibling(self):
method prev_sibling (line 182) | def prev_sibling(self):
method leaves (line 197) | def leaves(self):
method depth (line 201) | def depth(self):
method get_suffix (line 206) | def get_suffix(self):
method __str__ (line 218) | def __str__(self):
class Node (line 222) | class Node(Base):
method __init__ (line 225) | def __init__(self,
method __repr__ (line 252) | def __repr__(self):
method __unicode__ (line 257) | def __unicode__(self):
method _eq (line 268) | def _eq(self, other):
method clone (line 272) | def clone(self):
method post_order (line 278) | def post_order(self):
method pre_order (line 284) | def pre_order(self):
method prefix (line 291) | def prefix(self):
method prefix (line 300) | def prefix(self, prefix):
method set_child (line 304) | def set_child(self, i, child):
method insert_child (line 314) | def insert_child(self, i, child):
method append_child (line 323) | def append_child(self, child):
class Leaf (line 333) | class Leaf(Base):
method __init__ (line 341) | def __init__(self, type, value, context=None, prefix=None, fixers_appl...
method __repr__ (line 357) | def __repr__(self):
method __unicode__ (line 361) | def __unicode__(self):
method _eq (line 372) | def _eq(self, other):
method clone (line 376) | def clone(self):
method leaves (line 383) | def leaves(self):
method post_order (line 386) | def post_order(self):
method pre_order (line 390) | def pre_order(self):
method prefix (line 395) | def prefix(self):
method prefix (line 402) | def prefix(self, prefix):
function convert (line 407) | def convert(gr, raw_node):
class BasePattern (line 426) | class BasePattern(object):
method __new__ (line 446) | def __new__(cls, *args, **kwds):
method __repr__ (line 451) | def __repr__(self):
method optimize (line 457) | def optimize(self):
method match (line 465) | def match(self, node, results=None):
method match_seq (line 490) | def match_seq(self, nodes, results=None):
method generate_matches (line 500) | def generate_matches(self, nodes):
class LeafPattern (line 511) | class LeafPattern(BasePattern):
method __init__ (line 513) | def __init__(self, type=None, content=None, name=None):
method match (line 533) | def match(self, node, results=None):
method _submatch (line 539) | def _submatch(self, node, results=None):
class NodePattern (line 555) | class NodePattern(BasePattern):
method __init__ (line 559) | def __init__(self, type=None, content=None, name=None):
method _submatch (line 588) | def _submatch(self, node, results=None):
class WildcardPattern (line 616) | class WildcardPattern(BasePattern):
method __init__ (line 629) | def __init__(self, content=None, min=0, max=HUGE, name=None):
method optimize (line 664) | def optimize(self):
method match (line 681) | def match(self, node, results=None):
method match_seq (line 685) | def match_seq(self, nodes, results=None):
method generate_matches (line 696) | def generate_matches(self, nodes):
method _iterative_matches (line 741) | def _iterative_matches(self, nodes):
method _bare_name_matches (line 770) | def _bare_name_matches(self, nodes):
method _recursive_matches (line 786) | def _recursive_matches(self, nodes, count):
class NegatedPattern (line 801) | class NegatedPattern(BasePattern):
method __init__ (line 803) | def __init__(self, content=None):
method match (line 816) | def match(self, node):
method match_seq (line 820) | def match_seq(self, nodes):
method generate_matches (line 824) | def generate_matches(self, nodes):
function generate_matches (line 836) | def generate_matches(patterns, nodes):
FILE: third_party/yapf_third_party/yapf_diff/yapf_diff.py
function main (line 36) | def main():
FILE: yapf/__init__.py
function _raw_input (line 43) | def _raw_input():
function _removeBOM (line 48) | def _removeBOM(source):
function main (line 57) | def main(argv):
function _PrintHelp (line 150) | def _PrintHelp(args):
function FormatFiles (line 167) | def FormatFiles(filenames,
function _FormatFile (line 220) | def _FormatFile(filename,
function _GetLines (line 258) | def _GetLines(line_strings):
function _BuildParser (line 283) | def _BuildParser():
function run_main (line 375) | def run_main(): # pylint: disable=invalid-name
FILE: yapf/pyparser/pyparser.py
function ParseCode (line 50) | def ParseCode(unformatted_source, filename='<unknown>'):
function _CreateLogicalLines (line 84) | def _CreateLogicalLines(tokens):
FILE: yapf/pyparser/pyparser_utils.py
function GetLogicalLine (line 32) | def GetLogicalLine(logical_lines, node):
function GetTokensInSubRange (line 47) | def GetTokensInSubRange(tokens, node):
function GetTokenIndex (line 61) | def GetTokenIndex(tokens, pos):
function GetNextTokenIndex (line 70) | def GetNextTokenIndex(tokens, pos):
function GetPrevTokenIndex (line 79) | def GetPrevTokenIndex(tokens, pos):
function TokenStart (line 88) | def TokenStart(node):
function TokenEnd (line 92) | def TokenEnd(node):
function AstDump (line 101) | def AstDump(node):
FILE: yapf/pyparser/split_penalty_visitor.py
class SplitPenalty (line 23) | class SplitPenalty(ast.NodeVisitor):
method __init__ (line 26) | def __init__(self, logical_lines):
method _GetTokens (line 36) | def _GetTokens(self, node):
method visit_FunctionDef (line 43) | def visit_FunctionDef(self, node):
method visit_AsyncFunctionDef (line 80) | def visit_AsyncFunctionDef(self, node):
method visit_ClassDef (line 94) | def visit_ClassDef(self, node):
method visit_Return (line 111) | def visit_Return(self, node):
method visit_Delete (line 118) | def visit_Delete(self, node):
method visit_Assign (line 126) | def visit_Assign(self, node):
method visit_AugAssign (line 134) | def visit_AugAssign(self, node):
method visit_AnnAssign (line 140) | def visit_AnnAssign(self, node):
method visit_For (line 147) | def visit_For(self, node):
method visit_AsyncFor (line 154) | def visit_AsyncFor(self, node):
method visit_While (line 161) | def visit_While(self, node):
method visit_If (line 167) | def visit_If(self, node):
method visit_With (line 173) | def visit_With(self, node):
method visit_AsyncWith (line 178) | def visit_AsyncWith(self, node):
method visit_Match (line 183) | def visit_Match(self, node):
method visit_Raise (line 194) | def visit_Raise(self, node):
method visit_Try (line 198) | def visit_Try(self, node):
method visit_Assert (line 205) | def visit_Assert(self, node):
method visit_Import (line 209) | def visit_Import(self, node):
method visit_ImportFrom (line 218) | def visit_ImportFrom(self, node):
method visit_Global (line 229) | def visit_Global(self, node):
method visit_Nonlocal (line 233) | def visit_Nonlocal(self, node):
method visit_Expr (line 237) | def visit_Expr(self, node):
method visit_Pass (line 241) | def visit_Pass(self, node):
method visit_Break (line 245) | def visit_Break(self, node):
method visit_Continue (line 249) | def visit_Continue(self, node):
method visit_BoolOp (line 257) | def visit_BoolOp(self, node):
method visit_NamedExpr (line 277) | def visit_NamedExpr(self, node):
method visit_BinOp (line 285) | def visit_BinOp(self, node):
method visit_UnaryOp (line 305) | def visit_UnaryOp(self, node):
method visit_Lambda (line 314) | def visit_Lambda(self, node):
method visit_IfExp (line 330) | def visit_IfExp(self, node):
method visit_Dict (line 339) | def visit_Dict(self, node):
method visit_Set (line 355) | def visit_Set(self, node):
method visit_ListComp (line 364) | def visit_ListComp(self, node):
method visit_SetComp (line 388) | def visit_SetComp(self, node):
method visit_DictComp (line 412) | def visit_DictComp(self, node):
method visit_GeneratorExp (line 440) | def visit_GeneratorExp(self, node):
method visit_Await (line 464) | def visit_Await(self, node):
method visit_Yield (line 471) | def visit_Yield(self, node):
method visit_YieldFrom (line 478) | def visit_YieldFrom(self, node):
method visit_Compare (line 486) | def visit_Compare(self, node):
method visit_Call (line 508) | def visit_Call(self, node):
method visit_FormattedValue (line 529) | def visit_FormattedValue(self, node):
method visit_JoinedStr (line 534) | def visit_JoinedStr(self, node):
method visit_Constant (line 538) | def visit_Constant(self, node):
method visit_Attribute (line 542) | def visit_Attribute(self, node):
method visit_Subscript (line 556) | def visit_Subscript(self, node):
method visit_Starred (line 568) | def visit_Starred(self, node):
method visit_Name (line 572) | def visit_Name(self, node):
method visit_List (line 579) | def visit_List(self, node):
method visit_Tuple (line 590) | def visit_Tuple(self, node):
method visit_Slice (line 601) | def visit_Slice(self, node):
method visit_Load (line 634) | def visit_Load(self, node):
method visit_Store (line 638) | def visit_Store(self, node):
method visit_Del (line 642) | def visit_Del(self, node):
method visit_And (line 650) | def visit_And(self, node):
method visit_Or (line 654) | def visit_Or(self, node):
method visit_Add (line 662) | def visit_Add(self, node):
method visit_Sub (line 666) | def visit_Sub(self, node):
method visit_Mult (line 670) | def visit_Mult(self, node):
method visit_MatMult (line 674) | def visit_MatMult(self, node):
method visit_Div (line 678) | def visit_Div(self, node):
method visit_Mod (line 682) | def visit_Mod(self, node):
method visit_Pow (line 686) | def visit_Pow(self, node):
method visit_LShift (line 690) | def visit_LShift(self, node):
method visit_RShift (line 694) | def visit_RShift(self, node):
method visit_BitOr (line 698) | def visit_BitOr(self, node):
method visit_BitXor (line 702) | def visit_BitXor(self, node):
method visit_BitAnd (line 706) | def visit_BitAnd(self, node):
method visit_FloorDiv (line 710) | def visit_FloorDiv(self, node):
method visit_Invert (line 718) | def visit_Invert(self, node):
method visit_Not (line 722) | def visit_Not(self, node):
method visit_UAdd (line 726) | def visit_UAdd(self, node):
method visit_USub (line 730) | def visit_USub(self, node):
method visit_Eq (line 738) | def visit_Eq(self, node):
method visit_NotEq (line 742) | def visit_NotEq(self, node):
method visit_Lt (line 746) | def visit_Lt(self, node):
method visit_LtE (line 750) | def visit_LtE(self, node):
method visit_Gt (line 754) | def visit_Gt(self, node):
method visit_GtE (line 758) | def visit_GtE(self, node):
method visit_Is (line 762) | def visit_Is(self, node):
method visit_IsNot (line 766) | def visit_IsNot(self, node):
method visit_In (line 770) | def visit_In(self, node):
method visit_NotIn (line 774) | def visit_NotIn(self, node):
method visit_ExceptionHandler (line 782) | def visit_ExceptionHandler(self, node):
method visit_MatchValue (line 792) | def visit_MatchValue(self, node):
method visit_MatchSingleton (line 796) | def visit_MatchSingleton(self, node):
method visit_MatchSequence (line 800) | def visit_MatchSequence(self, node):
method visit_MatchMapping (line 804) | def visit_MatchMapping(self, node):
method visit_MatchClass (line 810) | def visit_MatchClass(self, node):
method visit_MatchStar (line 817) | def visit_MatchStar(self, node):
method visit_MatchAs (line 821) | def visit_MatchAs(self, node):
method visit_MatchOr (line 826) | def visit_MatchOr(self, node):
method visit_TypeIgnore (line 834) | def visit_TypeIgnore(self, node):
method visit_comprehension (line 842) | def visit_comprehension(self, node):
method visit_arguments (line 849) | def visit_arguments(self, node):
method visit_arg (line 859) | def visit_arg(self, node):
method visit_keyword (line 873) | def visit_keyword(self, node):
method visit_alias (line 878) | def visit_alias(self, node):
method visit_withitem (line 883) | def visit_withitem(self, node):
method visit_match_case (line 888) | def visit_match_case(self, node):
function _IncreasePenalty (line 895) | def _IncreasePenalty(tokens, amt):
function _DecreasePenalty (line 902) | def _DecreasePenalty(tokens, amt):
function _SetPenalty (line 909) | def _SetPenalty(tokens, amt):
FILE: yapf/pytree/blank_line_calculator.py
function CalculateBlankLines (line 44) | def CalculateBlankLines(tree):
class _BlankLineCalculator (line 56) | class _BlankLineCalculator(pytree_visitor.PyTreeVisitor):
method __init__ (line 59) | def __init__(self):
method Visit_simple_stmt (line 66) | def Visit_simple_stmt(self, node): # pylint: disable=invalid-name
method Visit_decorator (line 71) | def Visit_decorator(self, node): # pylint: disable=invalid-name
method Visit_classdef (line 81) | def Visit_classdef(self, node): # pylint: disable=invalid-name
method Visit_funcdef (line 91) | def Visit_funcdef(self, node): # pylint: disable=invalid-name
method DefaultNodeVisit (line 107) | def DefaultNodeVisit(self, node):
method _SetBlankLinesBetweenCommentAndClassFunc (line 123) | def _SetBlankLinesBetweenCommentAndClassFunc(self, node):
method _GetNumNewlines (line 154) | def _GetNumNewlines(self, node):
method _IsTopLevel (line 161) | def _IsTopLevel(self, node):
function _SetNumNewlines (line 166) | def _SetNumNewlines(node, num_newlines):
function _StartsInZerothColumn (line 171) | def _StartsInZerothColumn(node):
function _AsyncFunction (line 176) | def _AsyncFunction(node):
FILE: yapf/pytree/comment_splicer.py
function SpliceComments (line 31) | def SpliceComments(tree):
function _CreateCommentsFromPrefix (line 206) | def _CreateCommentsFromPrefix(comment_prefix,
function _FindNodeWithStandaloneLineParent (line 271) | def _FindNodeWithStandaloneLineParent(node):
function _FindStmtParent (line 295) | def _FindStmtParent(node):
function _FindAncestorAtIndent (line 310) | def _FindAncestorAtIndent(node, indent):
function _AnnotateIndents (line 341) | def _AnnotateIndents(tree):
FILE: yapf/pytree/continuation_splicer.py
function SpliceContinuations (line 27) | def SpliceContinuations(tree):
FILE: yapf/pytree/pytree_unwrapper.py
function UnwrapPyTree (line 47) | def UnwrapPyTree(tree):
class PyTreeUnwrapper (line 70) | class PyTreeUnwrapper(pytree_visitor.PyTreeVisitor):
method __init__ (line 85) | def __init__(self):
method GetLogicalLines (line 96) | def GetLogicalLines(self):
method _StartNewLine (line 108) | def _StartNewLine(self):
method Visit_simple_stmt (line 135) | def Visit_simple_stmt(self, node):
method _VisitCompoundStatement (line 158) | def _VisitCompoundStatement(self, node, substatement_names):
method Visit_if_stmt (line 182) | def Visit_if_stmt(self, node): # pylint: disable=invalid-name
method Visit_while_stmt (line 187) | def Visit_while_stmt(self, node): # pylint: disable=invalid-name
method Visit_for_stmt (line 192) | def Visit_for_stmt(self, node): # pylint: disable=invalid-name
method Visit_try_stmt (line 197) | def Visit_try_stmt(self, node): # pylint: disable=invalid-name
method Visit_except_clause (line 202) | def Visit_except_clause(self, node): # pylint: disable=invalid-name
method Visit_funcdef (line 207) | def Visit_funcdef(self, node): # pylint: disable=invalid-name
method Visit_async_funcdef (line 210) | def Visit_async_funcdef(self, node): # pylint: disable=invalid-name
method Visit_classdef (line 223) | def Visit_classdef(self, node): # pylint: disable=invalid-name
method Visit_async_stmt (line 226) | def Visit_async_stmt(self, node): # pylint: disable=invalid-name
method Visit_decorator (line 239) | def Visit_decorator(self, node): # pylint: disable=invalid-name
method Visit_decorators (line 245) | def Visit_decorators(self, node): # pylint: disable=invalid-name
method Visit_decorated (line 250) | def Visit_decorated(self, node): # pylint: disable=invalid-name
method Visit_with_stmt (line 257) | def Visit_with_stmt(self, node): # pylint: disable=invalid-name
method Visit_match_stmt (line 262) | def Visit_match_stmt(self, node): # pylint: disable=invalid-name
method Visit_case_block (line 268) | def Visit_case_block(self, node):
method Visit_suite (line 274) | def Visit_suite(self, node): # pylint: disable=invalid-name
method Visit_listmaker (line 281) | def Visit_listmaker(self, node): # pylint: disable=invalid-name
method Visit_dictsetmaker (line 285) | def Visit_dictsetmaker(self, node): # pylint: disable=invalid-name
method Visit_import_as_names (line 289) | def Visit_import_as_names(self, node): # pylint: disable=invalid-name
method Visit_testlist_gexp (line 294) | def Visit_testlist_gexp(self, node): # pylint: disable=invalid-name
method Visit_arglist (line 298) | def Visit_arglist(self, node): # pylint: disable=invalid-name
method Visit_typedargslist (line 302) | def Visit_typedargslist(self, node): # pylint: disable=invalid-name
method Visit_subscriptlist (line 306) | def Visit_subscriptlist(self, node): # pylint: disable=invalid-name
method DefaultLeafVisit (line 310) | def DefaultLeafVisit(self, leaf):
function _MatchBrackets (line 329) | def _MatchBrackets(line):
function _IdentifyParameterLists (line 354) | def _IdentifyParameterLists(line):
function _AdjustSplitPenalty (line 387) | def _AdjustSplitPenalty(line):
function _DetermineMustSplitAnnotation (line 408) | def _DetermineMustSplitAnnotation(node):
function _ContainsComments (line 446) | def _ContainsComments(node):
function _SetMustSplitOnFirstLeaf (line 456) | def _SetMustSplitOnFirstLeaf(node):
FILE: yapf/pytree/pytree_utils.py
class Annotation (line 43) | class Annotation(object):
function NodeName (line 52) | def NodeName(node):
function FirstLeafNode (line 70) | def FirstLeafNode(node):
function LastLeafNode (line 76) | def LastLeafNode(node):
function ParseCodeToTree (line 93) | def ParseCodeToTree(code):
function _WrapEndMarker (line 121) | def _WrapEndMarker(tree):
function InsertNodesBefore (line 137) | def InsertNodesBefore(new_nodes, target):
function InsertNodesAfter (line 152) | def InsertNodesAfter(new_nodes, target):
function _InsertNodeAt (line 167) | def _InsertNodeAt(new_node, target, after=False):
function CopyYapfAnnotations (line 210) | def CopyYapfAnnotations(src, dst):
function GetNodeAnnotation (line 222) | def GetNodeAnnotation(node, annotation, default=None):
function SetNodeAnnotation (line 237) | def SetNodeAnnotation(node, annotation, value):
function AppendNodeAnnotation (line 248) | def AppendNodeAnnotation(node, annotation, value):
function RemoveSubtypeAnnotation (line 261) | def RemoveSubtypeAnnotation(node, value):
function GetOpeningBracket (line 274) | def GetOpeningBracket(node):
function SetOpeningBracket (line 286) | def SetOpeningBracket(node, bracket):
function DumpNodeToString (line 296) | def DumpNodeToString(node):
function _PytreeNodeRepr (line 323) | def _PytreeNodeRepr(node):
function IsCommentStatement (line 332) | def IsCommentStatement(node):
FILE: yapf/pytree/pytree_visitor.py
class PyTreeVisitor (line 34) | class PyTreeVisitor(object):
method Visit (line 57) | def Visit(self, node):
method DefaultNodeVisit (line 69) | def DefaultNodeVisit(self, node):
method DefaultLeafVisit (line 80) | def DefaultLeafVisit(self, leaf):
function DumpPyTree (line 91) | def DumpPyTree(tree, target_stream=sys.stdout):
class PyTreeDumper (line 107) | class PyTreeDumper(PyTreeVisitor):
method __init__ (line 113) | def __init__(self, target_stream=sys.stdout):
method _DumpString (line 123) | def _DumpString(self, s):
method DefaultNodeVisit (line 126) | def DefaultNodeVisit(self, node):
method DefaultLeafVisit (line 134) | def DefaultLeafVisit(self, leaf):
FILE: yapf/pytree/split_penalty.py
function ComputeSplitPenalties (line 54) | def ComputeSplitPenalties(tree):
class _SplitPenaltyAssigner (line 63) | class _SplitPenaltyAssigner(pytree_visitor.PyTreeVisitor):
method Visit (line 69) | def Visit(self, node):
method Visit_import_as_names (line 73) | def Visit_import_as_names(self, node): # pyline: disable=invalid-name
method Visit_classdef (line 83) | def Visit_classdef(self, node): # pylint: disable=invalid-name
method Visit_funcdef (line 95) | def Visit_funcdef(self, node): # pylint: disable=invalid-name
method Visit_lambdef (line 120) | def Visit_lambdef(self, node): # pylint: disable=invalid-name
method Visit_parameters (line 136) | def Visit_parameters(self, node): # pylint: disable=invalid-name
method Visit_arglist (line 146) | def Visit_arglist(self, node): # pylint: disable=invalid-name
method Visit_argument (line 165) | def Visit_argument(self, node): # pylint: disable=invalid-name
method Visit_tname (line 177) | def Visit_tname(self, node): # pylint: disable=invalid-name
method Visit_dotted_name (line 189) | def Visit_dotted_name(self, node): # pylint: disable=invalid-name
method Visit_dictsetmaker (line 197) | def Visit_dictsetmaker(self, node): # pylint: disable=invalid-name
method Visit_trailer (line 208) | def Visit_trailer(self, node): # pylint: disable=invalid-name
method Visit_power (line 274) | def Visit_power(self, node): # pylint: disable=invalid-name,missing-d...
method Visit_subscriptlist (line 344) | def Visit_subscriptlist(self, node): # pylint: disable=invalid-name
method Visit_subscript (line 354) | def Visit_subscript(self, node): # pylint: disable=invalid-name
method Visit_comp_for (line 359) | def Visit_comp_for(self, node): # pylint: disable=invalid-name
method Visit_old_comp_for (line 365) | def Visit_old_comp_for(self, node): # pylint: disable=invalid-name
method Visit_comp_if (line 369) | def Visit_comp_if(self, node): # pylint: disable=invalid-name
method Visit_old_comp_if (line 376) | def Visit_old_comp_if(self, node): # pylint: disable=invalid-name
method Visit_test (line 380) | def Visit_test(self, node): # pylint: disable=invalid-name
method Visit_or_test (line 385) | def Visit_or_test(self, node): # pylint: disable=invalid-name
method Visit_and_test (line 399) | def Visit_and_test(self, node): # pylint: disable=invalid-name
method Visit_not_test (line 413) | def Visit_not_test(self, node): # pylint: disable=invalid-name
method Visit_comparison (line 418) | def Visit_comparison(self, node): # pylint: disable=invalid-name
method Visit_star_expr (line 428) | def Visit_star_expr(self, node): # pylint: disable=invalid-name
method Visit_expr (line 433) | def Visit_expr(self, node): # pylint: disable=invalid-name
method Visit_xor_expr (line 439) | def Visit_xor_expr(self, node): # pylint: disable=invalid-name
method Visit_and_expr (line 445) | def Visit_and_expr(self, node): # pylint: disable=invalid-name
method Visit_shift_expr (line 451) | def Visit_shift_expr(self, node): # pylint: disable=invalid-name
method Visit_arith_expr (line 458) | def Visit_arith_expr(self, node): # pylint: disable=invalid-name
method Visit_term (line 466) | def Visit_term(self, node): # pylint: disable=invalid-name
method Visit_factor (line 472) | def Visit_factor(self, node): # pyline: disable=invalid-name
method Visit_atom (line 477) | def Visit_atom(self, node): # pylint: disable=invalid-name
method Visit_testlist_gexp (line 495) | def Visit_testlist_gexp(self, node): # pylint: disable=invalid-name
function _SetUnbreakable (line 508) | def _SetUnbreakable(node):
function _SetStronglyConnected (line 513) | def _SetStronglyConnected(*nodes):
function _SetExpressionPenalty (line 520) | def _SetExpressionPenalty(node, penalty):
function _SetBitwiseOperandPenalty (line 541) | def _SetBitwiseOperandPenalty(node, op):
function _SetExpressionOperandPenalty (line 553) | def _SetExpressionOperandPenalty(node, ops):
function _IncreasePenalty (line 565) | def _IncreasePenalty(node, amt):
function _RecAnnotate (line 585) | def _RecAnnotate(tree, annotate_name, annotate_value):
function _StronglyConnectedCompOp (line 608) | def _StronglyConnectedCompOp(op):
function _DecrementSplitPenalty (line 623) | def _DecrementSplitPenalty(node, amt):
function _SetSplitPenalty (line 630) | def _SetSplitPenalty(node, penalty):
FILE: yapf/pytree/subtype_assigner.py
function AssignSubtypes (line 37) | def AssignSubtypes(tree):
class _SubtypeAssigner (line 56) | class _SubtypeAssigner(pytree_visitor.PyTreeVisitor):
method Visit_dictsetmaker (line 62) | def Visit_dictsetmaker(self, node): # pylint: disable=invalid-name
method Visit_expr_stmt (line 110) | def Visit_expr_stmt(self, node): # pylint: disable=invalid-name
method Visit_or_test (line 118) | def Visit_or_test(self, node): # pylint: disable=invalid-name
method Visit_and_test (line 125) | def Visit_and_test(self, node): # pylint: disable=invalid-name
method Visit_not_test (line 132) | def Visit_not_test(self, node): # pylint: disable=invalid-name
method Visit_comparison (line 139) | def Visit_comparison(self, node): # pylint: disable=invalid-name
method Visit_star_expr (line 151) | def Visit_star_expr(self, node): # pylint: disable=invalid-name
method Visit_expr (line 159) | def Visit_expr(self, node): # pylint: disable=invalid-name
method Visit_xor_expr (line 166) | def Visit_xor_expr(self, node): # pylint: disable=invalid-name
method Visit_and_expr (line 173) | def Visit_and_expr(self, node): # pylint: disable=invalid-name
method Visit_shift_expr (line 180) | def Visit_shift_expr(self, node): # pylint: disable=invalid-name
method Visit_arith_expr (line 187) | def Visit_arith_expr(self, node): # pylint: disable=invalid-name
method Visit_term (line 199) | def Visit_term(self, node): # pylint: disable=invalid-name
method Visit_factor (line 211) | def Visit_factor(self, node): # pylint: disable=invalid-name
method Visit_power (line 218) | def Visit_power(self, node): # pylint: disable=invalid-name
method Visit_lambdef (line 225) | def Visit_lambdef(self, node): # pylint: disable=invalid-name
method Visit_trailer (line 230) | def Visit_trailer(self, node): # pylint: disable=invalid-name
method Visit_subscript (line 236) | def Visit_subscript(self, node): # pylint: disable=invalid-name
method Visit_sliceop (line 243) | def Visit_sliceop(self, node): # pylint: disable=invalid-name
method Visit_argument (line 250) | def Visit_argument(self, node): # pylint: disable=invalid-name
method Visit_arglist (line 255) | def Visit_arglist(self, node): # pylint: disable=invalid-name
method Visit_tname (line 264) | def Visit_tname(self, node): # pylint: disable=invalid-name
method Visit_decorator (line 269) | def Visit_decorator(self, node): # pylint: disable=invalid-name
method Visit_funcdef (line 277) | def Visit_funcdef(self, node): # pylint: disable=invalid-name
method Visit_parameters (line 287) | def Visit_parameters(self, node): # pylint: disable=invalid-name
method Visit_typedargslist (line 294) | def Visit_typedargslist(self, node): # pylint: disable=invalid-name
method Visit_varargslist (line 329) | def Visit_varargslist(self, node): # pylint: disable=invalid-name
method Visit_comp_for (line 341) | def Visit_comp_for(self, node): # pylint: disable=invalid-name
method Visit_old_comp_for (line 355) | def Visit_old_comp_for(self, node): # pylint: disable=invalid-name
method Visit_comp_if (line 359) | def Visit_comp_if(self, node): # pylint: disable=invalid-name
method Visit_old_comp_if (line 364) | def Visit_old_comp_if(self, node): # pylint: disable=invalid-name
method _ProcessArgLists (line 368) | def _ProcessArgLists(self, node):
function _SetArgListSubtype (line 378) | def _SetArgListSubtype(node, node_subtype, list_subtype):
function _AppendTokenSubtype (line 404) | def _AppendTokenSubtype(node, subtype):
function _AppendFirstLeafTokenSubtype (line 410) | def _AppendFirstLeafTokenSubtype(node, subtype):
function _AppendLastLeafTokenSubtype (line 418) | def _AppendLastLeafTokenSubtype(node, subtype):
function _AppendSubtypeRec (line 426) | def _AppendSubtypeRec(node, subtype, force=True):
function _InsertPseudoParentheses (line 435) | def _InsertPseudoParentheses(node):
function _IsAExprOperator (line 497) | def _IsAExprOperator(node):
function _IsMExprOperator (line 501) | def _IsMExprOperator(node):
function _IsSimpleExpression (line 506) | def _IsSimpleExpression(node):
FILE: yapf/yapflib/errors.py
function FormatErrorMsg (line 19) | def FormatErrorMsg(e):
class YapfError (line 40) | class YapfError(Exception):
FILE: yapf/yapflib/file_resources.py
function _GetExcludePatternsFromYapfIgnore (line 41) | def _GetExcludePatternsFromYapfIgnore(filename):
function _GetExcludePatternsFromPyprojectToml (line 56) | def _GetExcludePatternsFromPyprojectToml(filename):
function GetExcludePatternsForDir (line 72) | def GetExcludePatternsForDir(dirname):
function GetDefaultStyleForDir (line 96) | def GetDefaultStyleForDir(dirname, default_style=style.DEFAULT_STYLE):
function GetCommandLineFiles (line 155) | def GetCommandLineFiles(command_line_file_list, recursive, exclude):
function WriteReformattedCode (line 160) | def WriteReformattedCode(filename,
function LineEnding (line 182) | def LineEnding(lines):
function _FindPythonFiles (line 195) | def _FindPythonFiles(filenames, recursive, exclude):
function IsIgnored (line 243) | def IsIgnored(path, exclude):
function IsPythonFile (line 253) | def IsPythonFile(filename):
function FileEncoding (line 282) | def FileEncoding(filename):
FILE: yapf/yapflib/format_decision_state.py
class FormatDecisionState (line 37) | class FormatDecisionState(object):
method __init__ (line 60) | def __init__(self, line, first_indent):
method Clone (line 82) | def Clone(self):
method __eq__ (line 98) | def __eq__(self, other):
method __ne__ (line 112) | def __ne__(self, other):
method __hash__ (line 115) | def __hash__(self):
method __repr__ (line 119) | def __repr__(self):
method CanSplit (line 124) | def CanSplit(self, must_split):
method MustSplit (line 168) | def MustSplit(self):
method AddTokenToState (line 577) | def AddTokenToState(self, newline, dry_run, must_split=False):
method _AddTokenOnCurrentLine (line 605) | def _AddTokenOnCurrentLine(self, dry_run):
method _AddTokenOnNewline (line 643) | def _AddTokenOnNewline(self, dry_run, must_split):
method MoveStateToNextToken (line 712) | def MoveStateToNextToken(self):
method _CalculateComprehensionState (line 769) | def _CalculateComprehensionState(self, newline):
method _PushParameterListState (line 837) | def _PushParameterListState(self, newline):
method _CalculateParameterListState (line 852) | def _CalculateParameterListState(self, newline):
method _IndentWithContinuationAlignStyle (line 936) | def _IndentWithContinuationAlignStyle(self, column):
method _GetNewlineColumn (line 948) | def _GetNewlineColumn(self):
method _FitsOnLine (line 1005) | def _FitsOnLine(self, start, end):
method _EachDictEntryFitsOnOneLine (line 1012) | def _EachDictEntryFitsOnOneLine(self, opening):
method _ArgumentListHasDictionaryEntry (line 1094) | def _ArgumentListHasDictionaryEntry(self, token):
method _ContainerFitsOnStartLine (line 1108) | def _ContainerFitsOnStartLine(self, opening):
function _IsCompoundStatement (line 1126) | def _IsCompoundStatement(token):
function _IsFunctionDef (line 1137) | def _IsFunctionDef(token):
function _IsFunctionCallWithArguments (line 1143) | def _IsFunctionCallWithArguments(token):
function _IsArgumentToFunction (line 1154) | def _IsArgumentToFunction(token):
function _GetOpeningBracket (line 1162) | def _GetOpeningBracket(current):
function _LastTokenInLine (line 1178) | def _LastTokenInLine(current):
function _IsFunctionDefinition (line 1184) | def _IsFunctionDefinition(current):
function _IsLastScopeInLine (line 1189) | def _IsLastScopeInLine(current):
function _IsSingleElementTuple (line 1198) | def _IsSingleElementTuple(token):
function _ScopeHasNoCommas (line 1210) | def _ScopeHasNoCommas(token):
class _ParenState (line 1221) | class _ParenState(object):
method __init__ (line 1241) | def __init__(self, indent, last_space):
method Clone (line 1248) | def Clone(self):
method __repr__ (line 1255) | def __repr__(self):
method __eq__ (line 1259) | def __eq__(self, other):
method __ne__ (line 1262) | def __ne__(self, other):
method __hash__ (line 1265) | def __hash__(self, *args, **kwargs):
FILE: yapf/yapflib/format_token.py
function _TabbedContinuationAlignPadding (line 33) | def _TabbedContinuationAlignPadding(spaces, align_style, tab_width):
class FormatToken (line 51) | class FormatToken(object):
method __init__ (line 87) | def __init__(self, node, name):
method formatted_whitespace_prefix (line 129) | def formatted_whitespace_prefix(self):
method AddWhitespacePrefix (line 137) | def AddWhitespacePrefix(self, newlines_before, spaces=0, indent_level=0):
method AdjustNewlinesBefore (line 171) | def AdjustNewlinesBefore(self, newlines_before):
method RetainHorizontalSpacing (line 176) | def RetainHorizontalSpacing(self, first_column, depth):
method OpensScope (line 214) | def OpensScope(self):
method ClosesScope (line 217) | def ClosesScope(self):
method AddSubtype (line 220) | def AddSubtype(self, subtype):
method __repr__ (line 223) | def __repr__(self):
method node_split_penalty (line 232) | def node_split_penalty(self):
method is_binary_op (line 238) | def is_binary_op(self):
method is_arithmetic_op (line 244) | def is_arithmetic_op(self):
method is_simple_expr (line 263) | def is_simple_expr(self):
method is_subscript_colon (line 268) | def is_subscript_colon(self):
method is_comment (line 273) | def is_comment(self):
method is_continuation (line 277) | def is_continuation(self):
method is_keyword (line 282) | def is_keyword(self):
method is_name (line 290) | def is_name(self):
method is_number (line 294) | def is_number(self):
method is_string (line 298) | def is_string(self):
method is_multiline_string (line 302) | def is_multiline_string(self):
method is_docstring (line 313) | def is_docstring(self):
method is_pylint_comment (line 317) | def is_pylint_comment(self):
method is_pytype_comment (line 322) | def is_pytype_comment(self):
method is_copybara_comment (line 327) | def is_copybara_comment(self):
FILE: yapf/yapflib/identify_container.py
function IdentifyContainers (line 28) | def IdentifyContainers(tree):
class _IdentifyContainers (line 38) | class _IdentifyContainers(pytree_visitor.PyTreeVisitor):
method Visit_trailer (line 41) | def Visit_trailer(self, node): # pylint: disable=invalid-name
method Visit_atom (line 58) | def Visit_atom(self, node): # pylint: disable=invalid-name
FILE: yapf/yapflib/line_joiner.py
function CanMergeMultipleLines (line 42) | def CanMergeMultipleLines(lines, last_was_merged=False):
function _CanMergeLineIntoIfStatement (line 85) | def _CanMergeLineIntoIfStatement(lines, limit):
FILE: yapf/yapflib/logical_line.py
class LogicalLine (line 31) | class LogicalLine(object):
method __init__ (line 40) | def __init__(self, depth, tokens=None):
method CalculateFormattingInformation (line 62) | def CalculateFormattingInformation(self):
method Split (line 103) | def Split(self):
method AppendToken (line 130) | def AppendToken(self, token):
method first (line 138) | def first(self):
method last (line 143) | def last(self):
method AsCode (line 151) | def AsCode(self, indent_per_depth=2):
method __str__ (line 170) | def __str__(self): # pragma: no cover
method __repr__ (line 173) | def __repr__(self): # pragma: no cover
method tokens (line 184) | def tokens(self):
method lineno (line 195) | def lineno(self):
method start (line 204) | def start(self):
method end (line 213) | def end(self):
method is_comment (line 222) | def is_comment(self):
method has_semicolon (line 226) | def has_semicolon(self):
function _IsIdNumberStringToken (line 230) | def _IsIdNumberStringToken(tok):
function _IsUnaryOperator (line 234) | def _IsUnaryOperator(tok):
function _HasPrecedence (line 238) | def _HasPrecedence(tok):
function _PriorityIndicatingNoSpace (line 264) | def _PriorityIndicatingNoSpace(tok):
function _IsSubscriptColonAndValuePair (line 272) | def _IsSubscriptColonAndValuePair(token1, token2):
function _SpaceRequiredBetween (line 276) | def _SpaceRequiredBetween(left, right, is_line_disabled):
function _MustBreakBefore (line 487) | def _MustBreakBefore(prev_token, cur_token):
function _CanBreakBefore (line 503) | def _CanBreakBefore(prev_token, cur_token):
function IsSurroundedByBrackets (line 543) | def IsSurroundedByBrackets(tok):
function _IsDictListTupleDelimiterTok (line 574) | def _IsDictListTupleDelimiterTok(tok, is_opening):
function _SplitPenalty (line 606) | def _SplitPenalty(prev_token, cur_token):
FILE: yapf/yapflib/object_state.py
class ComprehensionState (line 27) | class ComprehensionState(object):
method __init__ (line 44) | def __init__(self, expr_token):
method HasTrivialExpr (line 50) | def HasTrivialExpr(self):
method opening_bracket (line 55) | def opening_bracket(self):
method closing_bracket (line 59) | def closing_bracket(self):
method Clone (line 62) | def Clone(self):
method __repr__ (line 69) | def __repr__(self):
method __eq__ (line 75) | def __eq__(self, other):
method __ne__ (line 78) | def __ne__(self, other):
method __hash__ (line 81) | def __hash__(self, *args, **kwargs):
class ParameterListState (line 86) | class ParameterListState(object):
method __init__ (line 104) | def __init__(self, opening_bracket, newline, opening_column):
method closing_bracket (line 112) | def closing_bracket(self):
method has_typed_return (line 116) | def has_typed_return(self):
method has_default_values (line 121) | def has_default_values(self):
method ends_in_comma (line 126) | def ends_in_comma(self):
method last_token (line 133) | def last_token(self):
method LastParamFitsOnLine (line 140) | def LastParamFitsOnLine(self, indent):
method SplitBeforeClosingBracket (line 152) | def SplitBeforeClosingBracket(self, indent):
method Clone (line 165) | def Clone(self):
method __repr__ (line 173) | def __repr__(self):
method __eq__ (line 179) | def __eq__(self, other):
method __ne__ (line 182) | def __ne__(self, other):
method __hash__ (line 185) | def __hash__(self, *args, **kwargs):
class Parameter (line 191) | class Parameter(object):
method __init__ (line 200) | def __init__(self, first_token, last_token):
method has_default_value (line 206) | def has_default_value(self):
method Clone (line 215) | def Clone(self):
method __repr__ (line 218) | def __repr__(self):
method __eq__ (line 222) | def __eq__(self, other):
method __ne__ (line 225) | def __ne__(self, other):
method __hash__ (line 228) | def __hash__(self, *args, **kwargs):
FILE: yapf/yapflib/reformatter.py
function Reformat (line 36) | def Reformat(llines, lines=None):
function _RetainHorizontalSpacing (line 105) | def _RetainHorizontalSpacing(line):
function _RetainRequiredVerticalSpacing (line 111) | def _RetainRequiredVerticalSpacing(cur_line, prev_line, lines):
function _RetainRequiredVerticalSpacingBetweenTokens (line 127) | def _RetainRequiredVerticalSpacingBetweenTokens(cur_tok, prev_tok, lines):
function _RetainVerticalSpacingBeforeComments (line 164) | def _RetainVerticalSpacingBeforeComments(line):
function _EmitLineUnformatted (line 175) | def _EmitLineUnformatted(state):
function _LineContainsI18n (line 202) | def _LineContainsI18n(line):
function _LineContainsPylintDisableLineTooLong (line 229) | def _LineContainsPylintDisableLineTooLong(line):
function _LineHasContinuationMarkers (line 234) | def _LineHasContinuationMarkers(line):
function _CanPlaceOnSingleLine (line 239) | def _CanPlaceOnSingleLine(line):
function _AlignTrailingComments (line 269) | def _AlignTrailingComments(final_lines):
function _FormatFinalLines (line 398) | def _FormatFinalLines(final_lines):
class _StateNode (line 418) | class _StateNode(object):
method __init__ (line 431) | def __init__(self, state, newline, previous):
method __repr__ (line 436) | def __repr__(self): # pragma: no cover
function _AnalyzeSolutionSpace (line 453) | def _AnalyzeSolutionSpace(initial_state):
function _AddNextStateToQueue (line 509) | def _AddNextStateToQueue(penalty, previous_node, newline, count, p_queue):
function _ReconstructPath (line 541) | def _ReconstructPath(initial_state, current):
function _FormatFirstToken (line 563) | def _FormatFirstToken(first_token, indent_depth, prev_line, final_lines):
function _IsClassOrDef (line 600) | def _IsClassOrDef(tok):
function _CalculateNumberOfNewlines (line 607) | def _CalculateNumberOfNewlines(first_token, indent_depth, prev_line,
function _SingleOrMergedLines (line 718) | def _SingleOrMergedLines(lines):
function _NoBlankLinesBeforeCurrentToken (line 766) | def _NoBlankLinesBeforeCurrentToken(text, cur_token, prev_token):
FILE: yapf/yapflib/style.py
class StyleConfigError (line 30) | class StyleConfigError(errors.YapfError):
function Get (line 35) | def Get(setting_name):
function GetOrDefault (line 40) | def GetOrDefault(setting_name, default_value):
function Help (line 45) | def Help():
function SetGlobalStyle (line 50) | def SetGlobalStyle(style):
function CreatePEP8Style (line 476) | def CreatePEP8Style():
function CreateGoogleStyle (line 543) | def CreateGoogleStyle():
function CreateYapfStyle (line 562) | def CreateYapfStyle():
function CreateFacebookStyle (line 574) | def CreateFacebookStyle():
function _GetStyleFactory (line 608) | def _GetStyleFactory(style):
function _ContinuationAlignStyleStringConverter (line 615) | def _ContinuationAlignStyleStringConverter(s):
function _StringListConverter (line 627) | def _StringListConverter(s):
function _StringSetConverter (line 632) | def _StringSetConverter(s):
function _BoolConverter (line 639) | def _BoolConverter(s):
function _IntListConverter (line 644) | def _IntListConverter(s):
function _IntOrIntListConverter (line 653) | def _IntOrIntListConverter(s):
function CreateStyleFromConfig (line 732) | def CreateStyleFromConfig(style_config):
function _CreateConfigParserFromConfigDict (line 778) | def _CreateConfigParserFromConfigDict(config_dict):
function _CreateConfigParserFromConfigString (line 786) | def _CreateConfigParserFromConfigString(config_string):
function _CreateConfigParserFromConfigFile (line 803) | def _CreateConfigParserFromConfigFile(config_filename):
function _CreateStyleFromConfigParser (line 844) | def _CreateStyleFromConfigParser(config):
FILE: yapf/yapflib/yapf_api.py
function FormatFile (line 53) | def FormatFile(filename,
function FormatTree (line 105) | def FormatTree(tree, style_config=None, lines=None):
function FormatAST (line 142) | def FormatAST(ast, style_config=None, lines=None):
function FormatCode (line 171) | def FormatCode(unformatted_source,
function ReadFile (line 216) | def ReadFile(filename, logger=None):
function _SplitSemicolons (line 257) | def _SplitSemicolons(lines):
function _LineRangesToSet (line 268) | def _LineRangesToSet(line_ranges):
function _MarkLinesToFormat (line 281) | def _MarkLinesToFormat(llines, lines):
function _DisableYAPF (line 309) | def _DisableYAPF(line):
function _EnableYAPF (line 316) | def _EnableYAPF(line):
function _GetUnifiedDiff (line 323) | def _GetUnifiedDiff(before, after, filename='code'):
FILE: yapftests/blank_line_calculator_test.py
class BasicBlankLineCalculatorTest (line 26) | class BasicBlankLineCalculatorTest(yapf_test_helper.YAPFTest):
method setUpClass (line 29) | def setUpClass(cls):
method testDecorators (line 32) | def testDecorators(self):
method testComplexDecorators (line 47) | def testComplexDecorators(self):
method testCodeAfterFunctionsAndClasses (line 83) | def testCodeAfterFunctionsAndClasses(self):
method testCommentSpacing (line 128) | def testCommentSpacing(self):
method testCommentBeforeMethod (line 194) | def testCommentBeforeMethod(self):
method testCommentsBeforeClassDefs (line 205) | def testCommentsBeforeClassDefs(self):
method testCommentsBeforeDecorator (line 218) | def testCommentsBeforeDecorator(self):
method testCommentsAfterDecorator (line 239) | def testCommentsAfterDecorator(self):
method testInnerClasses (line 256) | def testInnerClasses(self):
method testLinesOnRangeBoundary (line 280) | def testLinesOnRangeBoundary(self):
method testLinesRangeBoundaryNotOutside (line 317) | def testLinesRangeBoundaryNotOutside(self):
method testLinesRangeRemove (line 350) | def testLinesRangeRemove(self):
method testLinesRangeRemoveSome (line 384) | def testLinesRangeRemoveSome(self):
FILE: yapftests/comment_splicer_test.py
class CommentSplicerTest (line 25) | class CommentSplicerTest(yapf_test_helper.YAPFTest):
method _AssertNodeType (line 27) | def _AssertNodeType(self, expected_type, node):
method _AssertNodeIsComment (line 30) | def _AssertNodeIsComment(self, node, text_in_comment=None):
method _FindNthChildNamed (line 40) | def _FindNthChildNamed(self, node, name, n=1):
method testSimpleInline (line 47) | def testSimpleInline(self):
method testSimpleSeparateLine (line 62) | def testSimpleSeparateLine(self):
method testTwoLineComment (line 77) | def testTwoLineComment(self):
method testCommentIsFirstChildInCompound (line 91) | def testCommentIsFirstChildInCompound(self):
method testCommentIsLastChildInCompound (line 107) | def testCommentIsLastChildInCompound(self):
method testInlineAfterSeparateLine (line 123) | def testInlineAfterSeparateLine(self):
method testSeparateLineAfterInline (line 141) | def testSeparateLineAfterInline(self):
method testCommentBeforeDedent (line 159) | def testCommentBeforeDedent(self):
method testCommentBeforeDedentTwoLevel (line 174) | def testCommentBeforeDedentTwoLevel(self):
method testCommentBeforeDedentTwoLevelImproperlyIndented (line 191) | def testCommentBeforeDedentTwoLevelImproperlyIndented(self):
method testCommentBeforeDedentThreeLevel (line 211) | def testCommentBeforeDedentThreeLevel(self):
method testCommentsInClass (line 238) | def testCommentsInClass(self):
method testMultipleBlockComments (line 260) | def testMultipleBlockComments(self):
method testCommentsOnDedents (line 279) | def testCommentsOnDedents(self):
method testExprComments (line 303) | def testExprComments(self):
method testMultipleCommentsInOneExpr (line 315) | def testMultipleCommentsInOneExpr(self):
FILE: yapftests/file_resources_test.py
function _restore_working_dir (line 33) | def _restore_working_dir():
function _exists_mocked_in_module (line 42) | def _exists_mocked_in_module(module, mock_implementation):
class GetExcludePatternsForDir (line 51) | class GetExcludePatternsForDir(yapf_test_helper.YAPFTest):
method setUp (line 53) | def setUp(self): # pylint: disable=g-missing-super-call
method tearDown (line 56) | def tearDown(self): # pylint: disable=g-missing-super-call
method test_get_exclude_file_patterns_from_yapfignore (line 59) | def test_get_exclude_file_patterns_from_yapfignore(self):
method test_get_exclude_file_patterns_from_yapfignore_with_wrong_syntax (line 69) | def test_get_exclude_file_patterns_from_yapfignore_with_wrong_syntax(s...
method test_get_exclude_file_patterns_from_pyproject (line 78) | def test_get_exclude_file_patterns_from_pyproject(self):
method test_get_exclude_file_patterns_from_pyproject_no_ignore_section (line 91) | def test_get_exclude_file_patterns_from_pyproject_no_ignore_section(se...
method test_get_exclude_file_patterns_from_pyproject_ignore_section_empty (line 100) | def test_get_exclude_file_patterns_from_pyproject_ignore_section_empty...
method test_get_exclude_file_patterns_with_no_config_files (line 110) | def test_get_exclude_file_patterns_with_no_config_files(self):
class GetDefaultStyleForDirTest (line 118) | class GetDefaultStyleForDirTest(yapf_test_helper.YAPFTest):
method setUp (line 120) | def setUp(self): # pylint: disable=g-missing-super-call
method tearDown (line 123) | def tearDown(self): # pylint: disable=g-missing-super-call
method test_no_local_style (line 126) | def test_no_local_style(self):
method test_no_local_style_custom_default (line 131) | def test_no_local_style_custom_default(self):
method test_with_local_style (line 137) | def test_with_local_style(self):
method test_setup_config (line 150) | def test_setup_config(self):
method test_pyproject_toml (line 165) | def test_pyproject_toml(self):
method test_local_style_at_root (line 179) | def test_local_style_at_root(self):
function _touch_files (line 202) | def _touch_files(filenames):
class GetCommandLineFilesTest (line 207) | class GetCommandLineFilesTest(yapf_test_helper.YAPFTest):
method setUp (line 209) | def setUp(self): # pylint: disable=g-missing-super-call
method tearDown (line 213) | def tearDown(self): # pylint: disable=g-missing-super-call
method _make_test_dir (line 217) | def _make_test_dir(self, name):
method test_find_files_not_dirs (line 222) | def test_find_files_not_dirs(self):
method test_nonrecursive_find_in_dir (line 238) | def test_nonrecursive_find_in_dir(self):
method test_recursive_find_in_dir (line 252) | def test_recursive_find_in_dir(self):
method test_recursive_find_in_dir_with_exclude (line 269) | def test_recursive_find_in_dir_with_exclude(self):
method test_find_with_excluded_hidden_dirs (line 290) | def test_find_with_excluded_hidden_dirs(self):
method test_find_with_excluded_hidden_dirs_relative (line 312) | def test_find_with_excluded_hidden_dirs_relative(self):
method test_find_with_excluded_dirs (line 354) | def test_find_with_excluded_dirs(self):
method test_find_with_excluded_current_dir (line 389) | def test_find_with_excluded_current_dir(self):
class IsPythonFileTest (line 394) | class IsPythonFileTest(yapf_test_helper.YAPFTest):
method setUp (line 396) | def setUp(self): # pylint: disable=g-missing-super-call
method tearDown (line 399) | def tearDown(self): # pylint: disable=g-missing-super-call
method test_with_py_extension (line 402) | def test_with_py_extension(self):
method test_empty_without_py_extension (line 406) | def test_empty_without_py_extension(self):
method test_python_shebang (line 412) | def test_python_shebang(self):
method test_with_latin_encoding (line 423) | def test_with_latin_encoding(self):
method test_with_invalid_encoding (line 429) | def test_with_invalid_encoding(self):
class IsIgnoredTest (line 437) | class IsIgnoredTest(yapf_test_helper.YAPFTest):
method test_root_path (line 439) | def test_root_path(self):
method test_sub_path (line 443) | def test_sub_path(self):
method test_trailing_slash (line 448) | def test_trailing_slash(self):
class BufferedByteStream (line 453) | class BufferedByteStream(object):
method __init__ (line 455) | def __init__(self):
method getvalue (line 458) | def getvalue(self): # pylint: disable=invalid-name
method buffer (line 462) | def buffer(self):
class WriteReformattedCodeTest (line 466) | class WriteReformattedCodeTest(yapf_test_helper.YAPFTest):
method setUpClass (line 469) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method tearDownClass (line 473) | def tearDownClass(cls): # pylint: disable=g-missing-super-call
method test_write_to_file (line 476) | def test_write_to_file(self):
method test_write_to_stdout (line 486) | def test_write_to_stdout(self):
method test_write_encoded_to_stdout (line 494) | def test_write_encoded_to_stdout(self):
class LineEndingTest (line 503) | class LineEndingTest(yapf_test_helper.YAPFTest):
method test_line_ending_linefeed (line 505) | def test_line_ending_linefeed(self):
method test_line_ending_carriage_return (line 510) | def test_line_ending_carriage_return(self):
method test_line_ending_combo (line 515) | def test_line_ending_combo(self):
method test_line_ending_weighted (line 520) | def test_line_ending_weighted(self):
method test_line_ending_empty (line 530) | def test_line_ending_empty(self):
method test_line_ending_no_newline (line 535) | def test_line_ending_no_newline(self):
method test_line_ending_tie (line 540) | def test_line_ending_tie(self):
FILE: yapftests/format_decision_state_test.py
class FormatDecisionStateTest (line 27) | class FormatDecisionStateTest(yapf_test_helper.YAPFTest):
method setUpClass (line 30) | def setUpClass(cls):
method testSimpleFunctionDefWithNoSplitting (line 33) | def testSimpleFunctionDefWithNoSplitting(self):
method testSimpleFunctionDefWithSplitting (line 87) | def testSimpleFunctionDefWithSplitting(self):
function _FilterLine (line 136) | def _FilterLine(lline):
FILE: yapftests/format_token_test.py
class TabbedContinuationAlignPaddingTest (line 26) | class TabbedContinuationAlignPaddingTest(yapf_test_helper.YAPFTest):
method testSpace (line 28) | def testSpace(self):
method testFixed (line 40) | def testFixed(self):
method testVAlignRight (line 52) | def testVAlignRight(self):
class FormatTokenTest (line 68) | class FormatTokenTest(yapf_test_helper.YAPFTest):
method testSimple (line 70) | def testSimple(self):
method testIsMultilineString (line 85) | def testIsMultilineString(self):
FILE: yapftests/line_joiner_test.py
class LineJoinerTest (line 25) | class LineJoinerTest(yapf_test_helper.YAPFTest):
method setUpClass (line 28) | def setUpClass(cls):
method _CheckLineJoining (line 31) | def _CheckLineJoining(self, code, join_lines):
method testSimpleSingleLineStatement (line 41) | def testSimpleSingleLineStatement(self):
method testSimpleMultipleLineStatement (line 47) | def testSimpleMultipleLineStatement(self):
method testSimpleMultipleLineComplexStatement (line 54) | def testSimpleMultipleLineComplexStatement(self):
method testSimpleMultipleLineStatementWithComment (line 62) | def testSimpleMultipleLineStatementWithComment(self):
method testSimpleMultipleLineStatementWithLargeIndent (line 68) | def testSimpleMultipleLineStatementWithLargeIndent(self):
method testOverColumnLimit (line 74) | def testOverColumnLimit(self):
FILE: yapftests/logical_line_test.py
class LogicalLineBasicTest (line 29) | class LogicalLineBasicTest(yapf_test_helper.YAPFTest):
method testConstruction (line 31) | def testConstruction(self):
method testFirstLast (line 38) | def testFirstLast(self):
method testAsCode (line 47) | def testAsCode(self):
method testAppendToken (line 54) | def testAppendToken(self):
class LogicalLineFormattingInformationTest (line 61) | class LogicalLineFormattingInformationTest(yapf_test_helper.YAPFTest):
method testFuncDef (line 63) | def testFuncDef(self):
function _MakeFormatTokenLeaf (line 81) | def _MakeFormatTokenLeaf(token_type, token_value, name):
function _MakeFormatTokenList (line 85) | def _MakeFormatTokenList(token_type_values):
FILE: yapftests/main_test.py
class IO (line 27) | class IO(object):
class Buffer (line 34) | class Buffer(object):
method __init__ (line 36) | def __init__(self):
method write (line 39) | def write(self, s):
method getvalue (line 44) | def getvalue(self):
method __init__ (line 47) | def __init__(self):
method write (line 50) | def write(self, s):
method getvalue (line 53) | def getvalue(self):
function captured_output (line 58) | def captured_output():
function patched_input (line 69) | def patched_input(code):
class RunMainTest (line 88) | class RunMainTest(yapf_test_helper.YAPFTest):
method testShouldHandleYapfError (line 90) | def testShouldHandleYapfError(self):
class MainTest (line 101) | class MainTest(yapf_test_helper.YAPFTest):
method testNoPythonFilesMatched (line 103) | def testNoPythonFilesMatched(self):
method testEchoInput (line 108) | def testEchoInput(self):
method testEchoInputWithStyle (line 116) | def testEchoInputWithStyle(self):
method testEchoBadInput (line 125) | def testEchoBadInput(self):
method testHelp (line 132) | def testHelp(self):
FILE: yapftests/pytree_unwrapper_test.py
class PytreeUnwrapperTest (line 24) | class PytreeUnwrapperTest(yapf_test_helper.YAPFTest):
method _CheckLogicalLines (line 26) | def _CheckLogicalLines(self, llines, list_of_expected):
method testSimpleFileScope (line 45) | def testSimpleFileScope(self):
method testSimpleMultilineStatement (line 58) | def testSimpleMultilineStatement(self):
method testFileScopeWithInlineComment (line 68) | def testFileScopeWithInlineComment(self):
method testSimpleIf (line 79) | def testSimpleIf(self):
method testSimpleIfWithComments (line 92) | def testSimpleIfWithComments(self):
method testIfWithCommentsInside (line 107) | def testIfWithCommentsInside(self):
method testIfElifElse (line 124) | def testIfElifElse(self):
method testNestedCompoundTwoLevel (line 145) | def testNestedCompoundTwoLevel(self):
method testSimpleWhile (line 164) | def testSimpleWhile(self):
method testSimpleTry (line 177) | def testSimpleTry(self):
method testSimpleFuncdef (line 204) | def testSimpleFuncdef(self):
method testTwoFuncDefs (line 217) | def testTwoFuncDefs(self):
method testSimpleClassDef (line 237) | def testSimpleClassDef(self):
method testSingleLineStmtInFunc (line 250) | def testSingleLineStmtInFunc(self):
method testMultipleComments (line 260) | def testMultipleComments(self):
method testSplitListWithComment (line 276) | def testSplitListWithComment(self):
class MatchBracketsTest (line 290) | class MatchBracketsTest(yapf_test_helper.YAPFTest):
method _CheckMatchingBrackets (line 292) | def _CheckMatchingBrackets(self, llines, list_of_expected):
method testFunctionDef (line 319) | def testFunctionDef(self):
method testDecorator (line 330) | def testDecorator(self):
method testClassDef (line 343) | def testClassDef(self):
FILE: yapftests/pytree_utils_test.py
class NodeNameTest (line 38) | class NodeNameTest(yapf_test_helper.YAPFTest):
method testNodeNameForLeaf (line 40) | def testNodeNameForLeaf(self):
method testNodeNameForNode (line 44) | def testNodeNameForNode(self):
class ParseCodeToTreeTest (line 50) | class ParseCodeToTreeTest(yapf_test_helper.YAPFTest):
method testParseCodeToTree (line 52) | def testParseCodeToTree(self):
method testPrintFunctionToTree (line 60) | def testPrintFunctionToTree(self):
method testPrintStatementToTree (line 67) | def testPrintStatementToTree(self):
method testClassNotLocal (line 71) | def testClassNotLocal(self):
class InsertNodesBeforeAfterTest (line 76) | class InsertNodesBeforeAfterTest(yapf_test_helper.YAPFTest):
method _BuildSimpleTree (line 78) | def _BuildSimpleTree(self):
method _MakeNewNodeRPAR (line 95) | def _MakeNewNodeRPAR(self):
method setUp (line 98) | def setUp(self):
method testInsertNodesBefore (line 101) | def testInsertNodesBefore(self):
method testInsertNodesBeforeFirstChild (line 111) | def testInsertNodesBeforeFirstChild(self):
method testInsertNodesAfter (line 121) | def testInsertNodesAfter(self):
method testInsertNodesAfterLastChild (line 131) | def testInsertNodesAfterLastChild(self):
method testInsertNodesWhichHasParent (line 141) | def testInsertNodesWhichHasParent(self):
class AnnotationsTest (line 148) | class AnnotationsTest(yapf_test_helper.YAPFTest):
method setUp (line 150) | def setUp(self):
method testGetWhenNone (line 155) | def testGetWhenNone(self):
method testSetWhenNone (line 158) | def testSetWhenNone(self):
method testSetAgain (line 162) | def testSetAgain(self):
method testMultiple (line 168) | def testMultiple(self):
method testSubtype (line 183) | def testSubtype(self):
method testSetOnNode (line 197) | def testSetOnNode(self):
FILE: yapftests/pytree_visitor_test.py
class _NodeNameCollector (line 25) | class _NodeNameCollector(pytree_visitor.PyTreeVisitor):
method __init__ (line 35) | def __init__(self):
method DefaultNodeVisit (line 39) | def DefaultNodeVisit(self, node):
method DefaultLeafVisit (line 43) | def DefaultLeafVisit(self, leaf):
method Visit_NAME (line 46) | def Visit_NAME(self, leaf):
class PytreeVisitorTest (line 63) | class PytreeVisitorTest(yapf_test_helper.YAPFTest):
method testCollectAllNodeNamesSimpleCode (line 65) | def testCollectAllNodeNamesSimpleCode(self):
method testCollectAllNodeNamesNestedCode (line 80) | def testCollectAllNodeNamesNestedCode(self):
method testDumper (line 97) | def testDumper(self):
method testDumpPyTree (line 109) | def testDumpPyTree(self):
FILE: yapftests/reformatter_basic_test.py
class BasicReformatterTest (line 26) | class BasicReformatterTest(yapf_test_helper.YAPFTest):
method setUpClass (line 29) | def setUpClass(cls):
method testSplittingAllArgs (line 32) | def testSplittingAllArgs(self):
method testSplittingTopLevelAllArgs (line 133) | def testSplittingTopLevelAllArgs(self):
method testSimpleFunctionsWithTrailingComments (line 319) | def testSimpleFunctionsWithTrailingComments(self):
method testParamListWithTrailingComments (line 348) | def testParamListWithTrailingComments(self):
method testBlankLinesBetweenTopLevelImportsAndVariables (line 371) | def testBlankLinesBetweenTopLevelImportsAndVariables(self):
method testBlankLinesAtEndOfFile (line 460) | def testBlankLinesAtEndOfFile(self):
method testIndentBlankLines (line 487) | def testIndentBlankLines(self):
method testMultipleUgliness (line 526) | def testMultipleUgliness(self):
method testComments (line 566) | def testComments(self):
method testSingleComment (line 619) | def testSingleComment(self):
method testCommentsWithTrailingSpaces (line 626) | def testCommentsWithTrailingSpaces(self):
method testCommentsInDataLiteral (line 636) | def testCommentsInDataLiteral(self):
method testEndingWhitespaceAfterSimpleStatement (line 653) | def testEndingWhitespaceAfterSimpleStatement(self):
method testDocstrings (line 662) | def testDocstrings(self):
method testDocstringAndMultilineComment (line 700) | def testDocstringAndMultilineComment(self):
method testMultilineDocstringAndMultilineComment (line 735) | def testMultilineDocstringAndMultilineComment(self):
method testTupleCommaBeforeLastParen (line 788) | def testTupleCommaBeforeLastParen(self):
method testNoBreakOutsideOfBracket (line 798) | def testNoBreakOutsideOfBracket(self):
method testBlankLinesBeforeDecorators (line 814) | def testBlankLinesBeforeDecorators(self):
method testCommentBetweenDecorators (line 835) | def testCommentBetweenDecorators(self):
method testListComprehension (line 853) | def testListComprehension(self):
method testListComprehensionPreferOneLine (line 866) | def testListComprehensionPreferOneLine(self):
method testListComprehensionPreferOneLineOverArithmeticSplit (line 883) | def testListComprehensionPreferOneLineOverArithmeticSplit(self):
method testListComprehensionPreferThreeLinesForLineWrap (line 897) | def testListComprehensionPreferThreeLinesForLineWrap(self):
method testListComprehensionPreferNoBreakForTrivialExpression (line 916) | def testListComprehensionPreferNoBreakForTrivialExpression(self):
method testOpeningAndClosingBrackets (line 934) | def testOpeningAndClosingBrackets(self):
method testSingleLineFunctions (line 952) | def testSingleLineFunctions(self):
method testNoQueueSeletionInMiddleOfLine (line 963) | def testNoQueueSeletionInMiddleOfLine(self):
method testNoSpacesBetweenSubscriptsAndCalls (line 977) | def testNoSpacesBetweenSubscriptsAndCalls(self):
method testNoSpacesBetweenOpeningBracketAndStartingOperator (line 987) | def testNoSpacesBetweenOpeningBracketAndStartingOperator(self):
method testMultilineCommentReformatted (line 1010) | def testMultilineCommentReformatted(self):
method testDictionaryMakerFormatting (line 1026) | def testDictionaryMakerFormatting(self):
method testSimpleMultilineCode (line 1051) | def testSimpleMultilineCode(self):
method testMultilineComment (line 1069) | def testMultilineComment(self):
method testSpaceBetweenStringAndParentheses (line 1082) | def testSpaceBetweenStringAndParentheses(self):
method testMultilineString (line 1089) | def testMultilineString(self):
method testSimpleMultilineWithComments (line 1125) | def testSimpleMultilineWithComments(self):
method testMatchingParenSplittingMatching (line 1137) | def testMatchingParenSplittingMatching(self):
method testContinuationIndent (line 1151) | def testContinuationIndent(self):
method testTrailingCommaAndBracket (line 1177) | def testTrailingCommaAndBracket(self):
method testI18n (line 1195) | def testI18n(self):
method testI18nCommentsInDataLiteral (line 1208) | def testI18nCommentsInDataLiteral(self):
method testClosingBracketIndent (line 1222) | def testClosingBracketIndent(self):
method testClosingBracketsInlinedInCall (line 1235) | def testClosingBracketsInlinedInCall(self):
method testLineWrapInForExpression (line 1267) | def testLineWrapInForExpression(self):
method testFunctionCallContinuationLine (line 1280) | def testFunctionCallContinuationLine(self):
method testI18nNonFormatting (line 1294) | def testI18nNonFormatting(self):
method testNoSpaceBetweenUnaryOpAndOpeningParen (line 1306) | def testNoSpaceBetweenUnaryOpAndOpeningParen(self):
method testCommentBeforeFuncDef (line 1314) | def testCommentBeforeFuncDef(self):
method testExcessLineCountWithDefaultKeywords (line 1332) | def testExcessLineCountWithDefaultKeywords(self):
method testSpaceAfterNotOperator (line 1357) | def testSpaceAfterNotOperator(self):
method testNoPenaltySplitting (line 1365) | def testNoPenaltySplitting(self):
method testExpressionPenalties (line 1378) | def testExpressionPenalties(self):
method testLineDepthOfSingleLineStatement (line 1389) | def testLineDepthOfSingleLineStatement(self):
method testSplitListWithTerminatingComma (line 1412) | def testSplitListWithTerminatingComma(self):
method testSplitListWithInterspersedComments (line 1435) | def testSplitListWithInterspersedComments(self):
method testRelativeImportStatements (line 1454) | def testRelativeImportStatements(self):
method testSingleLineList (line 1461) | def testSingleLineList(self):
method testBlankLinesBeforeFunctionsNotInColumnZero (line 1476) | def testBlankLinesBeforeFunctionsNotInColumnZero(self):
method testNoKeywordArgumentBreakage (line 1510) | def testNoKeywordArgumentBreakage(self):
method testTrailerOnSingleLine (line 1522) | def testTrailerOnSingleLine(self):
method testIfConditionalParens (line 1532) | def testIfConditionalParens(self):
method testContinuationMarkers (line 1545) | def testContinuationMarkers(self):
method testCommentsWithContinuationMarkers (line 1571) | def testCommentsWithContinuationMarkers(self):
method testMultipleContinuationMarkers (line 1582) | def testMultipleContinuationMarkers(self):
method testContinuationMarkerAfterStringWithContinuation (line 1591) | def testContinuationMarkerAfterStringWithContinuation(self):
method testEmptyContainers (line 1600) | def testEmptyContainers(self):
method testSplitStringsIfSurroundedByParens (line 1610) | def testSplitStringsIfSurroundedByParens(self):
method testMultilineShebang (line 1633) | def testMultilineShebang(self):
method testNoSplittingAroundTermOperators (line 1653) | def testNoSplittingAroundTermOperators(self):
method testNoSplittingAroundCompOperators (line 1661) | def testNoSplittingAroundCompOperators(self):
method testNoSplittingWithinSubscriptList (line 1691) | def testNoSplittingWithinSubscriptList(self):
method testExcessCharacters (line 1701) | def testExcessCharacters(self):
method testDictSetGenerator (line 1731) | def testDictSetGenerator(self):
method testUnaryOpInDictionaryValue (line 1754) | def testUnaryOpInDictionaryValue(self):
method testUnaryNotOperator (line 1765) | def testUnaryNotOperator(self):
method testRelaxArraySubscriptAffinity (line 1777) | def testRelaxArraySubscriptAffinity(self):
method testFunctionCallInDict (line 1793) | def testFunctionCallInDict(self):
method testFunctionCallInNestedDict (line 1800) | def testFunctionCallInNestedDict(self):
method testUnbreakableNot (line 1807) | def testUnbreakableNot(self):
method testSplitListWithComment (line 1816) | def testSplitListWithComment(self):
method testOverColumnLimit (line 1827) | def testOverColumnLimit(self):
method testEndingComment (line 1854) | def testEndingComment(self):
method testContinuationSpaceRetention (line 1864) | def testContinuationSpaceRetention(self):
method testIfExpressionWithFunctionCall (line 1875) | def testIfExpressionWithFunctionCall(self):
method testUnformattedAfterMultilineString (line 1887) | def testUnformattedAfterMultilineString(self):
method testNoSpacesAroundKeywordDefaultValues (line 1898) | def testNoSpacesAroundKeywordDefaultValues(self):
method testNoSplittingBeforeEndingSubscriptBracket (line 1909) | def testNoSplittingBeforeEndingSubscriptBracket(self):
method testNoSplittingOnSingleArgument (line 1924) | def testNoSplittingOnSingleArgument(self):
method testSplittingArraysSensibly (line 1946) | def testSplittingArraysSensibly(self):
method testComprehensionForAndIf (line 1964) | def testComprehensionForAndIf(self):
method testFunctionCallArguments (line 1981) | def testFunctionCallArguments(self):
method testBinaryOperators (line 2006) | def testBinaryOperators(self):
method testContiguousList (line 2030) | def testContiguousList(self):
method testArgsAndKwargsFormatting (line 2038) | def testArgsAndKwargsFormatting(self):
method testCommentColumnLimitOverflow (line 2060) | def testCommentColumnLimitOverflow(self):
method testMultilineLambdas (line 2073) | def testMultilineLambdas(self):
method testMultilineDictionaryKeys (line 2108) | def testMultilineDictionaryKeys(self):
method testStableDictionaryFormatting (line 2141) | def testStableDictionaryFormatting(self):
method testStableInlinedDictionaryFormatting (line 2173) | def testStableInlinedDictionaryFormatting(self):
method testDontSplitKeywordValueArguments (line 2200) | def testDontSplitKeywordValueArguments(self):
method testDontAddBlankLineAfterMultilineString (line 2214) | def testDontAddBlankLineAfterMultilineString(self):
method testFormattingListComprehensions (line 2224) | def testFormattingListComprehensions(self):
method testNoSplittingWhenBinPacking (line 2238) | def testNoSplittingWhenBinPacking(self):
method testNotSplittingAfterSubscript (line 2271) | def testNotSplittingAfterSubscript(self):
method testSplittingOneArgumentList (line 2285) | def testSplittingOneArgumentList(self):
method testSplittingBeforeFirstElementListArgument (line 2308) | def testSplittingBeforeFirstElementListArgument(self):
method testSplittingArgumentsTerminatedByComma (line 2337) | def testSplittingArgumentsTerminatedByComma(self):
method testImportAsList (line 2406) | def testImportAsList(self):
method testDictionaryValuesOnOwnLines (line 2415) | def testDictionaryValuesOnOwnLines(self):
method testDictionaryOnOwnLine (line 2467) | def testDictionaryOnOwnLine(self):
method testNestedListsInDictionary (line 2498) | def testNestedListsInDictionary(self):
method testNestedDictionary (line 2565) | def testNestedDictionary(self):
method testDictionaryElementsOnOneLine (line 2593) | def testDictionaryElementsOnOneLine(self):
method testNotInParams (line 2613) | def testNotInParams(self):
method testNamedAssignNotAtEndOfLine (line 2624) | def testNamedAssignNotAtEndOfLine(self):
method testBlankLineBeforeClassDocstring (line 2642) | def testBlankLineBeforeClassDocstring(self):
method testBlankLineBeforeModuleDocstring (line 2702) | def testBlankLineBeforeModuleDocstring(self):
method testTupleCohesion (line 2757) | def testTupleCohesion(self):
method testSubscriptExpression (line 2772) | def testSubscriptExpression(self):
method testSubscriptExpressionTerminatedByComma (line 2779) | def testSubscriptExpressionTerminatedByComma(self):
method testListWithFunctionCalls (line 2792) | def testListWithFunctionCalls(self):
method testEllipses (line 2819) | def testEllipses(self):
method testPseudoParens (line 2831) | def testPseudoParens(self):
method testSplittingBeforeFirstArgumentOnFunctionCall (line 2849) | def testSplittingBeforeFirstArgumentOnFunctionCall(self):
method testSplittingBeforeFirstArgumentOnFunctionDefinition (line 2871) | def testSplittingBeforeFirstArgumentOnFunctionDefinition(self):
method testSplittingBeforeFirstArgumentOnCompoundStatement (line 2895) | def testSplittingBeforeFirstArgumentOnCompoundStatement(self):
method testCoalesceBracketsOnDict (line 2921) | def testCoalesceBracketsOnDict(self):
method testSplitAfterComment (line 2957) | def testSplitAfterComment(self):
method testDisableEndingCommaHeuristic (line 2977) | def testDisableEndingCommaHeuristic(self):
method testDedentClosingBracketsWithTypeAnnotationExceedingLineLength (line 2992) | def testDedentClosingBracketsWithTypeAnnotationExceedingLineLength(self):
method testIndentClosingBracketsWithTypeAnnotationExceedingLineLength (line 3025) | def testIndentClosingBracketsWithTypeAnnotationExceedingLineLength(self):
method testIndentClosingBracketsInFunctionCall (line 3058) | def testIndentClosingBracketsInFunctionCall(self):
method testIndentClosingBracketsInTuple (line 3093) | def testIndentClosingBracketsInTuple(self):
method testIndentClosingBracketsInList (line 3128) | def testIndentClosingBracketsInList(self):
method testIndentClosingBracketsInDict (line 3163) | def testIndentClosingBracketsInDict(self):
method testMultipleDictionariesInList (line 3204) | def testMultipleDictionariesInList(self):
method testForceMultilineDict_True (line 3257) | def testForceMultilineDict_True(self):
method testForceMultilineDict_False (line 3281) | def testForceMultilineDict_False(self):
method testWalrus (line 3296) | def testWalrus(self):
method testStructuredPatternMatching (line 3308) | def testStructuredPatternMatching(self):
method testParenthesizedContextManagers (line 3326) | def testParenthesizedContextManagers(self):
FILE: yapftests/reformatter_buganizer_test.py
class BuganizerFixes (line 25) | class BuganizerFixes(yapf_test_helper.YAPFTest):
method setUpClass (line 28) | def setUpClass(cls):
method testB137580392 (line 31) | def testB137580392(self):
method testB73279849 (line 41) | def testB73279849(self):
method testB122455211 (line 55) | def testB122455211(self):
method testB119300344 (line 68) | def testB119300344(self):
method testB132886019 (line 79) | def testB132886019(self):
method testB26521719 (line 92) | def testB26521719(self):
method testB122541552 (line 103) | def testB122541552(self):
method testB124415889 (line 116) | def testB124415889(self):
method testB73166511 (line 139) | def testB73166511(self):
method testB118624921 (line 149) | def testB118624921(self):
method testB35417079 (line 162) | def testB35417079(self):
method testB120047670 (line 177) | def testB120047670(self):
method testB120245013 (line 201) | def testB120245013(self):
method testB117841880 (line 219) | def testB117841880(self):
method testB111764402 (line 236) | def testB111764402(self):
method testB116825060 (line 250) | def testB116825060(self):
method testB112711217 (line 258) | def testB112711217(self):
method testB112867548 (line 267) | def testB112867548(self):
method testB112651423 (line 289) | def testB112651423(self):
method testB80484938 (line 308) | def testB80484938(self):
method testB120771563 (line 351) | def testB120771563(self):
method testB79462249 (line 378) | def testB79462249(self):
method testB113210278 (line 400) | def testB113210278(self):
method testB77923341 (line 416) | def testB77923341(self):
method testB77329955 (line 426) | def testB77329955(self):
method testB65197969 (line 444) | def testB65197969(self):
method testB65546221 (line 463) | def testB65546221(self):
method testB30500455 (line 490) | def testB30500455(self):
method testB38343525 (line 507) | def testB38343525(self):
method testB37099651 (line 519) | def testB37099651(self):
method testB33228502 (line 540) | def testB33228502(self):
method testB30394228 (line 578) | def testB30394228(self):
method testB65246454 (line 591) | def testB65246454(self):
method testB67935450 (line 611) | def testB67935450(self):
method testB66011084 (line 652) | def testB66011084(self):
method testB67455376 (line 684) | def testB67455376(self):
method testB35210351 (line 695) | def testB35210351(self):
method testB34774905 (line 725) | def testB34774905(self):
method testB65176185 (line 754) | def testB65176185(self):
method testB35210166 (line 761) | def testB35210166(self):
method testB32167774 (line 782) | def testB32167774(self):
method testB66912275 (line 809) | def testB66912275(self):
method testB67312284 (line 833) | def testB67312284(self):
method testB65241516 (line 843) | def testB65241516(self):
method testB37460004 (line 856) | def testB37460004(self):
method testB36806207 (line 864) | def testB36806207(self):
method testB36215507 (line 883) | def testB36215507(self):
method testB35212469 (line 897) | def testB35212469(self):
method testB31063453 (line 919) | def testB31063453(self):
method testB35021894 (line 934) | def testB35021894(self):
method testB34682902 (line 961) | def testB34682902(self):
method testB33842726 (line 972) | def testB33842726(self):
method testB32931780 (line 988) | def testB32931780(self):
method testB33047408 (line 1050) | def testB33047408(self):
method testB32714745 (line 1064) | def testB32714745(self):
method testB32737279 (line 1094) | def testB32737279(self):
method testB32570937 (line 1111) | def testB32570937(self):
method testB31937033 (line 1122) | def testB31937033(self):
method testB31911533 (line 1132) | def testB31911533(self):
method testB31847238 (line 1148) | def testB31847238(self):
method testB30760569 (line 1173) | def testB30760569(self):
method testB26034238 (line 1187) | def testB26034238(self):
method testB30536435 (line 1205) | def testB30536435(self):
method testB30442148 (line 1226) | def testB30442148(self):
method testB26868213 (line 1240) | def testB26868213(self):
method testB30173198 (line 1276) | def testB30173198(self):
method testB29908765 (line 1287) | def testB29908765(self):
method testB30087362 (line 1298) | def testB30087362(self):
method testB30087363 (line 1311) | def testB30087363(self):
method testB29093579 (line 1323) | def testB29093579(self):
method testB26382315 (line 1339) | def testB26382315(self):
method testB27616132 (line 1351) | def testB27616132(self):
method testB27590179 (line 1374) | def testB27590179(self):
method testB27266946 (line 1398) | def testB27266946(self):
method testB25505359 (line 1412) | def testB25505359(self):
method testB25324261 (line 1427) | def testB25324261(self):
method testB25136704 (line 1436) | def testB25136704(self):
method testB25165602 (line 1448) | def testB25165602(self):
method testB25157123 (line 1456) | def testB25157123(self):
method testB25136820 (line 1465) | def testB25136820(self):
method testB25131481 (line 1485) | def testB25131481(self):
method testB23445244 (line 1505) | def testB23445244(self):
method testB20559654 (line 1532) | def testB20559654(self):
method testB23943842 (line 1553) | def testB23943842(self):
method testB20551180 (line 1591) | def testB20551180(self):
method testB23944849 (line 1606) | def testB23944849(self):
method testB23935890 (line 1626) | def testB23935890(self):
method testB28414371 (line 1642) | def testB28414371(self):
method testB20127686 (line 1667) | def testB20127686(self):
method testB20016122 (line 1685) | def testB20016122(self):
method testB22527411 (line 1734) | def testB22527411(self):
method testB20849933 (line 1749) | def testB20849933(self):
method testB20813997 (line 1769) | def testB20813997(self):
method testB20605036 (line 1778) | def testB20605036(self):
method testB20562732 (line 1792) | def testB20562732(self):
method testB20128830 (line 1804) | def testB20128830(self):
method testB20073838 (line 1824) | def testB20073838(self):
method testB19626808 (line 1841) | def testB19626808(self):
method testB19547210 (line 1850) | def testB19547210(self):
method testB19377034 (line 1864) | def testB19377034(self):
method testB19372573 (line 1874) | def testB19372573(self):
method testB19353268 (line 1892) | def testB19353268(self):
method testB19287512 (line 1900) | def testB19287512(self):
method testB19194420 (line 1925) | def testB19194420(self):
method testB19073499 (line 1934) | def testB19073499(self):
method testB18257115 (line 1946) | def testB18257115(self):
method testB18256666 (line 1956) | def testB18256666(self):
method testB18256826 (line 1974) | def testB18256826(self):
method testB18255697 (line 1993) | def testB18255697(self):
method testB17534869 (line 2004) | def testB17534869(self):
method testB17489866 (line 2018) | def testB17489866(self):
method testB17133019 (line 2035) | def testB17133019(self):
method testB17011869 (line 2060) | def testB17011869(self):
method testB16783631 (line 2087) | def testB16783631(self):
method testB16572361 (line 2104) | def testB16572361(self):
method testB15884241 (line 2121) | def testB15884241(self):
method testB15697268 (line 2145) | def testB15697268(self):
method testB15597568 (line 2170) | def testB15597568(self):
method testB15542157 (line 2188) | def testB15542157(self):
method testB15438132 (line 2199) | def testB15438132(self):
method testB14468247 (line 2234) | def testB14468247(self):
method testB14406499 (line 2249) | def testB14406499(self):
method testB13900309 (line 2262) | def testB13900309(self):
method testB67935687 (line 2325) | def testB67935687(self):
FILE: yapftests/reformatter_facebook_test.py
class TestsForFacebookStyle (line 25) | class TestsForFacebookStyle(yapf_test_helper.YAPFTest):
method setUpClass (line 28) | def setUpClass(cls):
method testNoNeedForLineBreaks (line 31) | def testNoNeedForLineBreaks(self):
method testDedentClosingBracket (line 44) | def testDedentClosingBracket(self):
method testBreakAfterOpeningBracketIfContentsTooBig (line 60) | def testBreakAfterOpeningBracketIfContentsTooBig(self):
method testDedentClosingBracketWithComments (line 75) | def testDedentClosingBracketWithComments(self):
method testDedentImportAsNames (line 96) | def testDedentImportAsNames(self):
method testDedentTestListGexp (line 108) | def testDedentTestListGexp(self):
method testBrokenIdempotency (line 146) | def testBrokenIdempotency(self):
method testIfExprHangingIndent (line 176) | def testIfExprHangingIndent(self):
method testSimpleDedenting (line 199) | def testSimpleDedenting(self):
method testDedentingWithSubscripts (line 213) | def testDedentingWithSubscripts(self):
method testDedentingCallsWithInnerLists (line 236) | def testDedentingCallsWithInnerLists(self):
method testDedentingListComprehension (line 247) | def testDedentingListComprehension(self):
method testMustSplitDedenting (line 325) | def testMustSplitDedenting(self):
method testDedentIfConditional (line 337) | def testDedentIfConditional(self):
method testDedentSet (line 351) | def testDedentSet(self):
method testDedentingInnerScope (line 367) | def testDedentingInnerScope(self):
method testCommentWithNewlinesInPrefix (line 385) | def testCommentWithNewlinesInPrefix(self):
method testIfStmtClosingBracket (line 414) | def testIfStmtClosingBracket(self):
FILE: yapftests/reformatter_pep8_test.py
class TestsForPEP8Style (line 25) | class TestsForPEP8Style(yapf_test_helper.YAPFTest):
method setUpClass (line 28) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method testIndent4 (line 31) | def testIndent4(self):
method testSingleLineIfStatements (line 43) | def testSingleLineIfStatements(self):
method testBlankBetweenClassAndDef (line 52) | def testBlankBetweenClassAndDef(self):
method testBlankBetweenDefsInClass (line 67) | def testBlankBetweenDefsInClass(self):
method testSingleWhiteBeforeTrailingComment (line 92) | def testSingleWhiteBeforeTrailingComment(self):
method testSpaceBetweenEndingCommandAndClosingBracket (line 104) | def testSpaceBetweenEndingCommandAndClosingBracket(self):
method testContinuedNonOutdentedLine (line 116) | def testContinuedNonOutdentedLine(self):
method testWrappingPercentExpressions (line 126) | def testWrappingPercentExpressions(self):
method testAlignClosingBracketWithVisualIndentation (line 150) | def testAlignClosingBracketWithVisualIndentation(self):
method testIndentSizeChanging (line 187) | def testIndentSizeChanging(self):
method testHangingIndentCollision (line 200) | def testHangingIndentCollision(self):
method testSplittingBeforeLogicalOperator (line 239) | def testSplittingBeforeLogicalOperator(self):
method testContiguousListEndingWithComment (line 272) | def testContiguousListEndingWithComment(self):
method testSplittingBeforeFirstArgument (line 287) | def testSplittingBeforeFirstArgument(self):
method testSplittingExpressionsInsideSubscripts (line 309) | def testSplittingExpressionsInsideSubscripts(self):
method testSplitListsAndDictSetMakersIfCommaTerminated (line 322) | def testSplitListsAndDictSetMakersIfCommaTerminated(self):
method testSplitAroundNamedAssigns (line 342) | def testSplitAroundNamedAssigns(self):
method testUnaryOperator (line 360) | def testUnaryOperator(self):
method testNoSplitBeforeDictValue (line 376) | def testNoSplitBeforeDictValue(self):
method testBitwiseOperandSplitting (line 464) | def testBitwiseOperandSplitting(self):
method testNoBlankLinesOnlyForFirstNestedObject (line 487) | def testNoBlankLinesOnlyForFirstNestedObject(self):
method testSplitBeforeArithmeticOperators (line 521) | def testSplitBeforeArithmeticOperators(self):
method testListSplitting (line 542) | def testListSplitting(self):
method testNoBlankLineBeforeNestedFuncOrClass (line 556) | def testNoBlankLineBeforeNestedFuncOrClass(self):
method testParamListIndentationCollision1 (line 597) | def testParamListIndentationCollision1(self):
method testParamListIndentationCollision2 (line 625) | def testParamListIndentationCollision2(self):
method testParamListIndentationCollision3 (line 634) | def testParamListIndentationCollision3(self):
method testTwoWordComparisonOperators (line 652) | def testTwoWordComparisonOperators(self):
method testStableInlinedDictionaryFormatting (line 666) | def testStableInlinedDictionaryFormatting(self):
class TestsForSpacesInsideBrackets (line 690) | class TestsForSpacesInsideBrackets(yapf_test_helper.YAPFTest):
method testEnabled (line 721) | def testEnabled(self):
method testDefault (line 760) | def testDefault(self):
class TestsForSpacesAroundSubscriptColon (line 799) | class TestsForSpacesAroundSubscriptColon(yapf_test_helper.YAPFTest):
method testEnabled (line 814) | def testEnabled(self):
method testWithSpaceInsideBrackets (line 832) | def testWithSpaceInsideBrackets(self):
method testDefault (line 851) | def testDefault(self):
FILE: yapftests/reformatter_python3_test.py
class TestsForPython3Code (line 26) | class TestsForPython3Code(yapf_test_helper.YAPFTest):
method setUpClass (line 30) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method testTypedNames (line 33) | def testTypedNames(self):
method testTypedNameWithLongNamedArg (line 48) | def testTypedNameWithLongNamedArg(self):
method testKeywordOnlyArgSpecifier (line 61) | def testKeywordOnlyArgSpecifier(self):
method testAnnotations (line 73) | def testAnnotations(self):
method testExecAsNonKeyword (line 85) | def testExecAsNonKeyword(self):
method testAsyncFunctions (line 91) | def testAsyncFunctions(self):
method testNoSpacesAroundPowerOperator (line 111) | def testNoSpacesAroundPowerOperator(self):
method testSpacesAroundDefaultOrNamedAssign (line 130) | def testSpacesAroundDefaultOrNamedAssign(self):
method testTypeHint (line 150) | def testTypeHint(self):
method testMatrixMultiplication (line 170) | def testMatrixMultiplication(self):
method testNoneKeyword (line 180) | def testNoneKeyword(self):
method testAsyncWithPrecedingComment (line 187) | def testAsyncWithPrecedingComment(self):
method testAsyncFunctionsNested (line 213) | def testAsyncFunctionsNested(self):
method testKeepTypesIntact (line 223) | def testKeepTypesIntact(self):
method testContinuationIndentWithAsync (line 239) | def testContinuationIndentWithAsync(self):
method testSplittingArguments (line 255) | def testSplittingArguments(self):
method testDictUnpacking (line 322) | def testDictUnpacking(self):
method testMultilineFormatString (line 345) | def testMultilineFormatString(self):
method testEllipses (line 356) | def testEllipses(self):
method testFunctionTypedReturnNextLine (line 365) | def testFunctionTypedReturnNextLine(self):
method testFunctionTypedReturnSameLine (line 376) | def testFunctionTypedReturnSameLine(self):
method testAsyncForElseNotIndentedInsideBody (line 385) | def testAsyncForElseNotIndentedInsideBody(self):
method testForElseInAsyncNotMixedWithAsyncFor (line 399) | def testForElseInAsyncNotMixedWithAsyncFor(self):
method testParameterListIndentationConflicts (line 410) | def testParameterListIndentationConflicts(self):
method testTypeHintedYieldExpression (line 429) | def testTypeHintedYieldExpression(self):
method testSyntaxMatch (line 438) | def testSyntaxMatch(self):
method testParenthsizedContextManager (line 462) | def testParenthsizedContextManager(self):
method testUnpackedTuple (line 478) | def testUnpackedTuple(self):
method testTypedTuple (line 496) | def testTypedTuple(self):
method testWalrusOperator (line 506) | def testWalrusOperator(self):
method testCondAssign (line 524) | def testCondAssign(self):
method testCopyDictionary (line 555) | def testCopyDictionary(self):
FILE: yapftests/reformatter_style_config_test.py
class TestsForStyleConfig (line 25) | class TestsForStyleConfig(yapf_test_helper.YAPFTest):
method setUp (line 27) | def setUp(self):
method testSetGlobalStyle (line 30) | def testSetGlobalStyle(self):
method testOperatorNoSpaceStyle (line 59) | def testOperatorNoSpaceStyle(self):
method testOperatorPrecedenceStyle (line 81) | def testOperatorPrecedenceStyle(self):
method testNoSplitBeforeFirstArgumentStyle1 (line 124) | def testNoSplitBeforeFirstArgumentStyle1(self):
method testNoSplitBeforeFirstArgumentStyle2 (line 165) | def testNoSplitBeforeFirstArgumentStyle2(self):
FILE: yapftests/split_penalty_test.py
class SplitPenaltyTest (line 35) | class SplitPenaltyTest(yapf_test_helper.YAPFTest):
method setUpClass (line 38) | def setUpClass(cls):
method _ParseAndComputePenalties (line 41) | def _ParseAndComputePenalties(self, code, dumptree=False):
method _CheckPenalties (line 58) | def _CheckPenalties(self, tree, list_of_expected):
method testUnbreakable (line 81) | def testUnbreakable(self):
method testStronglyConnected (line 164) | def testStronglyConnected(self):
method testFuncCalls (line 215) | def testFuncCalls(self):
FILE: yapftests/style_test.py
class UtilsTest (line 29) | class UtilsTest(yapf_test_helper.YAPFTest):
method testContinuationAlignStyleStringConverter (line 31) | def testContinuationAlignStyleStringConverter(self):
method testStringListConverter (line 56) | def testStringListConverter(self):
method testBoolConverter (line 63) | def testBoolConverter(self):
method testIntListConverter (line 69) | def testIntListConverter(self):
method testIntOrIntListConverter (line 74) | def testIntOrIntListConverter(self):
function _LooksLikeGoogleStyle (line 79) | def _LooksLikeGoogleStyle(cfg):
function _LooksLikePEP8Style (line 83) | def _LooksLikePEP8Style(cfg):
function _LooksLikeFacebookStyle (line 87) | def _LooksLikeFacebookStyle(cfg):
function _LooksLikeYapfStyle (line 91) | def _LooksLikeYapfStyle(cfg):
class PredefinedStylesByNameTest (line 95) | class PredefinedStylesByNameTest(yapf_test_helper.YAPFTest):
method setUpClass (line 98) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method testDefault (line 101) | def testDefault(self):
method testPEP8ByName (line 106) | def testPEP8ByName(self):
method testGoogleByName (line 111) | def testGoogleByName(self):
method testYapfByName (line 116) | def testYapfByName(self):
method testFacebookByName (line 121) | def testFacebookByName(self):
class StyleFromFileTest (line 127) | class StyleFromFileTest(yapf_test_helper.YAPFTest):
method setUpClass (line 130) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method tearDownClass (line 135) | def tearDownClass(cls): # pylint: disable=g-missing-super-call
method testDefaultBasedOnStyle (line 138) | def testDefaultBasedOnStyle(self):
method testDefaultBasedOnPEP8Style (line 148) | def testDefaultBasedOnPEP8Style(self):
method testDefaultBasedOnGoogleStyle (line 159) | def testDefaultBasedOnGoogleStyle(self):
method testDefaultBasedOnFacebookStyle (line 170) | def testDefaultBasedOnFacebookStyle(self):
method testBoolOptionValue (line 181) | def testBoolOptionValue(self):
method testStringListOptionValue (line 194) | def testStringListOptionValue(self):
method testErrorNoStyleFile (line 205) | def testErrorNoStyleFile(self):
method testErrorNoStyleSection (line 210) | def testErrorNoStyleSection(self):
method testErrorUnknownStyleOption (line 220) | def testErrorUnknownStyleOption(self):
method testPyprojectTomlNoYapfSection (line 231) | def testPyprojectTomlNoYapfSection(self):
method testPyprojectTomlParseYapfSection (line 238) | def testPyprojectTomlParseYapfSection(self):
class StyleFromDict (line 253) | class StyleFromDict(yapf_test_helper.YAPFTest):
method setUpClass (line 256) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method testDefaultBasedOnStyle (line 259) | def testDefaultBasedOnStyle(self):
method testDefaultBasedOnStyleBadDict (line 269) | def testDefaultBasedOnStyleBadDict(self):
class StyleFromCommandLine (line 278) | class StyleFromCommandLine(yapf_test_helper.YAPFTest):
method setUpClass (line 281) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method testDefaultBasedOnStyle (line 284) | def testDefaultBasedOnStyle(self):
method testDefaultBasedOnStyleNotStrict (line 292) | def testDefaultBasedOnStyleNotStrict(self):
method testDefaultBasedOnExplicitlyUnicodeTypeString (line 300) | def testDefaultBasedOnExplicitlyUnicodeTypeString(self):
method testDefaultBasedOnDetaultTypeString (line 304) | def testDefaultBasedOnDetaultTypeString(self):
method testDefaultBasedOnStyleBadString (line 308) | def testDefaultBasedOnStyleBadString(self):
class StyleHelp (line 317) | class StyleHelp(yapf_test_helper.YAPFTest):
method testHelpKeys (line 319) | def testHelpKeys(self):
FILE: yapftests/subtype_assigner_test.py
class SubtypeAssignerTest (line 26) | class SubtypeAssignerTest(yapf_test_helper.YAPFTest):
method _CheckFormatTokenSubtypes (line 28) | def _CheckFormatTokenSubtypes(self, llines, list_of_expected):
method testFuncDefDefaultAssign (line 46) | def testFuncDefDefaultAssign(self):
method testFuncCallWithDefaultAssign (line 108) | def testFuncCallWithDefaultAssign(self):
method testSetComprehension (line 132) | def testSetComprehension(self):
method testDictComprehension (line 284) | def testDictComprehension(self):
method testUnaryNotOperator (line 409) | def testUnaryNotOperator(self):
method testBitwiseOperators (line 417) | def testBitwiseOperators(self):
method testArithmeticOperators (line 446) | def testArithmeticOperators(self):
method testSubscriptColon (line 487) | def testSubscriptColon(self):
method testFunctionCallWithStarExpression (line 505) | def testFunctionCallWithStarExpression(self):
FILE: yapftests/utils.py
function stdout_redirector (line 25) | def stdout_redirector(stream): # pylint: disable=invalid-name
function NamedTempFile (line 45) | def NamedTempFile(mode='w+b',
function TempFileContents (line 70) | def TempFileContents(dirname,
FILE: yapftests/yapf_test.py
class FormatCodeTest (line 40) | class FormatCodeTest(yapf_test_helper.YAPFTest):
method _Check (line 42) | def _Check(self, unformatted_code, expected_formatted_code):
method testSimple (line 47) | def testSimple(self):
method testNoEndingNewline (line 53) | def testNoEndingNewline(self):
class FormatFileTest (line 64) | class FormatFileTest(yapf_test_helper.YAPFTest):
method setUp (line 66) | def setUp(self): # pylint: disable=g-missing-super-call
method tearDown (line 69) | def tearDown(self): # pylint: disable=g-missing-super-call
method testFormatFile (line 72) | def testFormatFile(self):
method testDisableLinesPattern (line 92) | def testDisableLinesPattern(self):
method testDisableAndReenableLinesPattern (line 113) | def testDisableAndReenableLinesPattern(self):
method testFmtOnOff (line 136) | def testFmtOnOff(self):
method testDisablePartOfMultilineComment (line 159) | def testDisablePartOfMultilineComment(self):
method testEnabledDisabledSameComment (line 202) | def testEnabledDisabledSameComment(self):
method testFormatFileLinesSelection (line 215) | def testFormatFileLinesSelection(self):
method testFormatFileDiff (line 245) | def testFormatFileDiff(self):
method testFormatFileInPlace (line 254) | def testFormatFileInPlace(self):
method testNoFile (line 270) | def testNoFile(self):
method testCommentsUnformatted (line 278) | def testCommentsUnformatted(self):
method testDisabledHorizontalFormattingOnNewLine (line 290) | def testDisabledHorizontalFormattingOnNewLine(self):
method testSplittingSemicolonStatements (line 301) | def testSplittingSemicolonStatements(self):
method testSemicolonStatementsDisabled (line 320) | def testSemicolonStatementsDisabled(self):
method testDisabledSemiColonSeparatedStatements (line 338) | def testDisabledSemiColonSeparatedStatements(self):
method testDisabledMultilineStringInDictionary (line 347) | def testDisabledMultilineStringInDictionary(self):
method testDisabledWithPrecedingText (line 366) | def testDisabledWithPrecedingText(self):
method testCRLFLineEnding (line 385) | def testCRLFLineEnding(self):
class CommandLineTest (line 392) | class CommandLineTest(yapf_test_helper.YAPFTest):
method setUpClass (line 396) | def setUpClass(cls): # pylint: disable=g-missing-super-call
method tearDownClass (line 400) | def tearDownClass(cls): # pylint: disable=g-missing-super-call
method assertYapfReformats (line 403) | def assertYapfReformats(self,
method testInPlaceReformatting (line 431) | def testInPlaceReformatting(self):
method testInPlaceReformattingBlank (line 448) | def testInPlaceReformattingBlank(self):
method testInPlaceReformattingWindowsNewLine (line 459) | def testInPlaceReformattingWindowsNewLine(self):
method testInPlaceReformattingNoNewLine (line 470) | def testInPlaceReformattingNoNewLine(self):
method testInPlaceReformattingEmpty (line 484) | def testInPlaceReformattingEmpty(self):
method testPrintModified (line 495) | def testPrintModified(self):
method testReadFromStdin (line 505) | def testReadFromStdin(self):
method testReadFromStdinWithEscapedStrings (line 516) | def testReadFromStdinWithEscapedStrings(self):
method testSetYapfStyle (line 525) | def testSetYapfStyle(self):
method testSetCustomStyleBasedOnYapf (line 539) | def testSetCustomStyleBasedOnYapf(self):
method testSetCustomStyleSpacesBeforeComment (line 559) | def testSetCustomStyleSpacesBeforeComment(self):
method testReadSingleLineCodeFromStdin (line 578) | def testReadSingleLineCodeFromStdin(self):
method testEncodingVerification (line 587) | def testEncodingVerification(self):
method testReformattingSpecificLines (line 605) | def testReformattingSpecificLines(self):
method testOmitFormattingLinesBeforeDisabledFunctionComment (line 635) | def testOmitFormattingLinesBeforeDisabledFunctionComment(self):
method testReformattingSkippingLines (line 655) | def testReformattingSkippingLines(self):
method testReformattingSkippingToEndOfFile (line 682) | def testReformattingSkippingToEndOfFile(self):
method testReformattingSkippingSingleLine (line 721) | def testReformattingSkippingSingleLine(self):
method testDisableWholeDataStructure (line 744) | def testDisableWholeDataStructure(self):
method testDisableButAdjustIndentations (line 759) | def testDisableButAdjustIndentations(self):
method testRetainingHorizontalWhitespace (line 776) | def testRetainingHorizontalWhitespace(self):
method testRetainingVerticalWhitespace (line 799) | def testRetainingVerticalWhitespace(self):
method testVerticalSpacingWithCommentWithContinuationMarkers (line 879) | def testVerticalSpacingWithCommentWithContinuationMarkers(self):
method testRetainingSemicolonsWhenSpecifyingLines (line 901) | def testRetainingSemicolonsWhenSpecifyingLines(self):
method testDisabledMultilineStrings (line 919) | def testDisabledMultilineStrings(self):
method testDisableWhenSpecifyingLines (line 945) | def testDisableWhenSpecifyingLines(self):
method testDisableFormattingInDataLiteral (line 975) | def testDisableFormattingInDataLiteral(self):
method testRetainVerticalFormattingBetweenDisabledAndEnabledLines (line 1015) | def testRetainVerticalFormattingBetweenDisabledAndEnabledLines(self):
method testRetainVerticalFormattingBetweenDisabledLines (line 1041) | def testRetainVerticalFormattingBetweenDisabledLines(self):
method testFormatLinesSpecifiedInMiddleOfExpression (line 1065) | def testFormatLinesSpecifiedInMiddleOfExpression(self):
method testCommentFollowingMultilineString (line 1091) | def testCommentFollowingMultilineString(self):
method testDedentClosingBracket (line 1113) | def testDedentClosingBracket(self):
method testCoalesceBrackets (line 1167) | def testCoalesceBrackets(self):
method testPseudoParenSpaces (line 1195) | def testPseudoParenSpaces(self):
method testMultilineCommentFormattingDisabled (line 1211) | def testMultilineCommentFormattingDisabled(self):
method testTrailingCommentsWithDisabledFormatting (line 1245) | def testTrailingCommentsWithDisabledFormatting(self):
method testUseTabs (line 1265) | def testUseTabs(self):
method testUseTabsWith (line 1288) | def testUseTabsWith(self):
method testUseTabsContinuationAlignStyleFixed (line 1312) | def testUseTabsContinuationAlignStyleFixed(self):
method testUseTabsContinuationAlignStyleVAlignRight (line 1340) | def testUseTabsContinuationAlignStyleVAlignRight(self):
method testUseSpacesContinuationAlignStyleFixed (line 1368) | def testUseSpacesContinuationAlignStyleFixed(self):
method testUseSpacesContinuationAlignStyleVAlignRight (line 1395) | def testUseSpacesContinuationAlignStyleVAlignRight(self):
method testStyleOutputRoundTrip (line 1422) | def testStyleOutputRoundTrip(self):
method testSpacingBeforeComments (line 1446) | def testSpacingBeforeComments(self):
method testSpacingBeforeCommentsInDicts (line 1472) | def testSpacingBeforeCommentsInDicts(self):
method testDisableWithLinesOption (line 1508) | def testDisableWithLinesOption(self):
method testDisableWithLineRanges (line 1532) | def testDisableWithLineRanges(self):
class BadInputTest (line 1557) | class BadInputTest(yapf_test_helper.YAPFTest):
method testBadSyntax (line 1560) | def testBadSyntax(self):
method testBadCode (line 1564) | def testBadCode(self):
class DiffIndentTest (line 1569) | class DiffIndentTest(yapf_test_helper.YAPFTest):
method _OwnStyle (line 1572) | def _OwnStyle():
method _Check (line 1578) | def _Check(self, unformatted_code, expected_formatted_code):
method testSimple (line 1583) | def testSimple(self):
class HorizontallyAlignedTrailingCommentsTest (line 1595) | class HorizontallyAlignedTrailingCommentsTest(yapf_test_helper.YAPFTest):
method _OwnStyle (line 1598) | def _OwnStyle():
method _Check (line 1607) | def _Check(self, unformatted_code, expected_formatted_code):
method testSimple (line 1612) | def testSimple(self):
method testBlock (line 1633) | def testBlock(self):
method testBlockWithLongLine (line 1652) | def testBlockWithLongLine(self):
method testBlockFuncSuffix (line 1671) | def testBlockFuncSuffix(self):
method testBlockCommentSuffix (line 1697) | def testBlockCommentSuffix(self):
method testBlockIndentedFuncSuffix (line 1720) | def testBlockIndentedFuncSuffix(self):
method testBlockIndentedCommentSuffix (line 1753) | def testBlockIndentedCommentSuffix(self):
method testBlockMultiIndented (line 1778) | def testBlockMultiIndented(self):
method testArgs (line 1807) | def testArgs(self):
method testDisableBlock (line 1832) | def testDisableBlock(self):
method testDisabledLine (line 1859) | def testDisabledLine(self):
class _SpacesAroundDictListTupleTestImpl (line 1875) | class _SpacesAroundDictListTupleTestImpl(yapf_test_helper.YAPFTest):
method _OwnStyle (line 1878) | def _OwnStyle():
method _Check (line 1885) | def _Check(self, unformatted_code, expected_formatted_code):
method setUp (line 1890) | def setUp(self):
class SpacesAroundDictTest (line 1894) | class SpacesAroundDictTest(_SpacesAroundDictListTupleTestImpl):
method _OwnStyle (line 1897) | def _OwnStyle(cls):
method testStandard (line 1903) | def testStandard(self):
class SpacesAroundListTest (line 1941) | class SpacesAroundListTest(_SpacesAroundDictListTupleTestImpl):
method _OwnStyle (line 1944) | def _OwnStyle(cls):
method testStandard (line 1950) | def testStandard(self):
class SpacesAroundTupleTest (line 1996) | class SpacesAroundTupleTest(_SpacesAroundDictListTupleTestImpl):
method _OwnStyle (line 1999) | def _OwnStyle(cls):
method testStandard (line 2005) | def testStandard(self):
FILE: yapftests/yapf_test_helper.py
class YAPFTest (line 32) | class YAPFTest(unittest.TestCase):
method __init__ (line 34) | def __init__(self, *args):
method assertCodeEqual (line 37) | def assertCodeEqual(self, expected_code, code):
function ParseAndUnwrap (line 63) | def ParseAndUnwrap(code, dumptree=False):
Condensed preview — 112 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,164K chars).
[
{
"path": ".coveragerc",
"chars": 32,
"preview": "[report]\nomit =\n */__main__.py\n"
},
{
"path": ".editorconfig",
"chars": 265,
"preview": "# EditorConfig is awesome: http://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n# Unix-style newlines with"
},
{
"path": ".flake8",
"chars": 408,
"preview": "[flake8]\nignore =\n # 'toml' imported but unused\n F401,\n # closing bracket does not match visual indentation\n "
},
{
"path": ".gitattributes",
"chars": 23,
"preview": ".python-version eol=lf\n"
},
{
"path": ".github/dependabot.yml",
"chars": 220,
"preview": "version: 2\nupdates:\n\n - package-ecosystem: \"github-actions\"\n commit-message:\n include: \"scope\"\n prefix: \"A"
},
{
"path": ".github/workflows/ci.yml",
"chars": 1111,
"preview": "# This workflow will install Python dependencies, run tests and lint with a variety of Python versions\n# For more inform"
},
{
"path": ".github/workflows/pre-commit-autoupdate.yml",
"chars": 2206,
"preview": "# Copyright (c) 2023 Sebastian Pipping <sebastian@pipping.org>\n# Licensed under the Apache License Version 2.0\n\nname: Ke"
},
{
"path": ".github/workflows/pre-commit.yml",
"chars": 986,
"preview": "# Copyright (c) 2023 Sebastian Pipping <sebastian@pipping.org>\n# Licensed under the Apache License Version 2.0\n\nname: Ru"
},
{
"path": ".gitignore",
"chars": 1287,
"preview": "#==============================================================================#\n# This file specifies intentionally unt"
},
{
"path": ".isort.cfg",
"chars": 163,
"preview": "[settings]\nforce_single_line=true\nknown_third_party=yapf_third_party\nknown_yapftests=yapftests\n\nsections=FUTURE,STDLIB,T"
},
{
"path": ".pre-commit-config.yaml",
"chars": 912,
"preview": "# File introduces automated checks triggered on git events\n# to enable run `pip install pre-commit && pre-commit install"
},
{
"path": ".pre-commit-hooks.yaml",
"chars": 602,
"preview": "# File configures YAPF to be used as a git hook with https://github.com/pre-commit/pre-commit\n\n- id: yapf\n name: yapf\n "
},
{
"path": ".python-version",
"chars": 35,
"preview": "3.7.9\n3.8.10\n3.9.13\n3.10.11\n3.11.5\n"
},
{
"path": ".style.yapf",
"chars": 30,
"preview": "[style]\nbased_on_style = yapf\n"
},
{
"path": ".vimrc",
"chars": 167,
"preview": "\" Force indentation styles for this directory\nautocmd FileType python set shiftwidth=2\nautocmd FileType python set tabst"
},
{
"path": ".vscode/extensions.json",
"chars": 451,
"preview": "{\n \"recommendations\": [\n \"eeyore.yapf\",\n \"dangmai.workspace-default-settings\",\n \"ms-python.flake"
},
{
"path": ".vscode/settings.default.json",
"chars": 974,
"preview": "{\n \"editor.codeActionsOnSave\": {\n \"source.organizeImports\": true\n },\n \"files.insertFinalNewline\": true,\n"
},
{
"path": "AUTHORS",
"chars": 307,
"preview": "# This is the official list of YAPF authors for copyright purposes.\n# This file is distinct from the CONTRIBUTORS files."
},
{
"path": "CHANGELOG.md",
"chars": 39291,
"preview": "# Change Log\n# All notable changes to this project will be documented in this file.\n# This project adheres to [Semantic "
},
{
"path": "CONTRIBUTING.md",
"chars": 2035,
"preview": "# How to Contribute\n\nWant to contribute? Great! First, read this page (including the small print at\nthe end).\n\n## Before"
},
{
"path": "CONTRIBUTORS",
"chars": 684,
"preview": "# People who have agreed to one of the CLAs and can contribute patches.\n# The AUTHORS file lists the copyright holders; "
},
{
"path": "EDITOR SUPPORT.md",
"chars": 2984,
"preview": "# Using YAPF with your editor\n\nYAPF is supported by multiple editors via community extensions or plugins.\n\n- [IntelliJ/P"
},
{
"path": "HACKING.md",
"chars": 1728,
"preview": "## Running YAPF on itself\n\n- To run YAPF on all of YAPF:\n\n```bash\n$ pipx run --spec=${PWD} --no-cache yapf -m -i -r yapf"
},
{
"path": "LICENSE",
"chars": 11358,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "MANIFEST.in",
"chars": 259,
"preview": "include HACKING.md LICENSE AUTHORS CHANGELOG.md CONTRIBUTING.md CONTRIBUTORS\ninclude .coveragerc .editorconfig .flake8 p"
},
{
"path": "README.md",
"chars": 32432,
"preview": "# YAPF\n\n<p align=\"center\">\n<a href=\"https://badge.fury.io/py/yapf\"><img alt=\"PyPI Version\" src=\"https://badge.fury.io/py"
},
{
"path": "plugins/README.md",
"chars": 2677,
"preview": "# IDE Plugins\n\n## Emacs\n\nThe `Emacs` plugin is maintained separately. Installation directions can be\nfound here: https:/"
},
{
"path": "plugins/pre-commit.sh",
"chars": 2784,
"preview": "#!/usr/bin/env bash\n\n# Git pre-commit hook to check staged Python files for formatting issues with\n# yapf.\n#\n# INSTALLIN"
},
{
"path": "plugins/vim/autoload/yapf.vim",
"chars": 1673,
"preview": "\" Copyright 2015 Google Inc. All Rights Reserved.\n\"\n\" Licensed under the Apache License, Version 2.0 (the \"License\");\n\" "
},
{
"path": "plugins/vim/plugin/yapf.vim",
"chars": 1019,
"preview": "\" Copyright 2015 Google Inc. All Rights Reserved.\n\"\n\" Licensed under the Apache License, Version 2.0 (the \"License\");\n\" "
},
{
"path": "pylintrc",
"chars": 13137,
"preview": "[MASTER]\n\n# Specify a configuration file.\n#rcfile=\n\n# Python code to execute, usually for sys.path manipulation such as\n"
},
{
"path": "pyproject.toml",
"chars": 2025,
"preview": "[build-system]\nrequires = [\"setuptools>=58.5.0\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"yapf\"\ndescri"
},
{
"path": "third_party/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "third_party/yapf_third_party/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "third_party/yapf_third_party/_ylib2to3/Grammar.txt",
"chars": 11278,
"preview": "# Grammar for 2to3. This grammar supports Python 2.x and 3.x.\n\n# NOTE WELL: You should also follow all the steps listed "
},
{
"path": "third_party/yapf_third_party/_ylib2to3/LICENSE",
"chars": 12762,
"preview": "A. HISTORY OF THE SOFTWARE\n==========================\n\nPython was created in the early 1990s by Guido van Rossum at Stic"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/PatternGrammar.txt",
"chars": 793,
"preview": "# Copyright 2006 Google, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\n# A grammar to desc"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/README.rst",
"chars": 383,
"preview": "A fork of python's lib2to3 with select features backported from black's blib2to3.\n\nReasons for forking:\n\n- black's fork "
},
{
"path": "third_party/yapf_third_party/_ylib2to3/__init__.py",
"chars": 73,
"preview": "\"\"\"fork of python's lib2to3 with some backports from black's blib2to3\"\"\"\n"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/fixer_base.py",
"chars": 6081,
"preview": "# Copyright 2006 Google, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\"Base class for fi"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/fixer_util.py",
"chars": 14005,
"preview": "\"\"\"Utility functions, node construction macros, etc.\"\"\"\n# Author: Collin Winter\n\nfrom . import patcomp\n# Local imports\nf"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/patcomp.py",
"chars": 6374,
"preview": "# Copyright 2006 Google, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\"Pattern compiler."
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/__init__.py",
"chars": 142,
"preview": "# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\""
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/conv.py",
"chars": 8672,
"preview": "# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\""
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/driver.py",
"chars": 8732,
"preview": "# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\n# "
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/grammar.py",
"chars": 6730,
"preview": "# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\""
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/literals.py",
"chars": 1407,
"preview": "# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\""
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/parse.py",
"chars": 13020,
"preview": "# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\""
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/pgen.py",
"chars": 12372,
"preview": "# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\n# "
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/token.py",
"chars": 1288,
"preview": "#! /usr/bin/env python3\n\"\"\"Token constants (from \"token.h\").\"\"\"\n\n# Taken from Python (r53757) and modified to include s"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pgen2/tokenize.py",
"chars": 19037,
"preview": "# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.\n# All rights reserved.\n\"\"\"Tokenization he"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pygram.py",
"chars": 1200,
"preview": "# Copyright 2006 Google, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\"Export the Python"
},
{
"path": "third_party/yapf_third_party/_ylib2to3/pytree.py",
"chars": 25583,
"preview": "# Copyright 2006 Google, Inc. All Rights Reserved.\n# Licensed to PSF under a Contributor Agreement.\n\"\"\"\nPython parse tre"
},
{
"path": "third_party/yapf_third_party/yapf_diff/LICENSE",
"chars": 12262,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "third_party/yapf_third_party/yapf_diff/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "third_party/yapf_third_party/yapf_diff/yapf_diff.py",
"chars": 4657,
"preview": "# Modified copy of clang-format-diff.py that works with yapf.\n#\n# Licensed under the Apache License, Version 2.0 (the \"L"
},
{
"path": "tox.ini",
"chars": 356,
"preview": "[tox]\nrequires =\n tox<4\n tox-pyenv\n tox-wheel\nenvlist = py37,py38,py39,py310,py311,py312\n# tox-wheel alias for "
},
{
"path": "yapf/__init__.py",
"chars": 12967,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/__main__.py",
"chars": 680,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/_version.py",
"chars": 23,
"preview": "__version__ = '0.43.0'\n"
},
{
"path": "yapf/pyparser/__init__.py",
"chars": 596,
"preview": "# Copyright 2022 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pyparser/pyparser.py",
"chars": 5247,
"preview": "# Copyright 2022 Bill Wendling, All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "yapf/pyparser/pyparser_utils.py",
"chars": 3076,
"preview": "# Copyright 2022 Bill Wendling, All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "yapf/pyparser/pyparser_visitor.py.tmpl",
"chars": 18928,
"preview": "# Copyright 2022 Bill Wendling, All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "yapf/pyparser/split_penalty_visitor.py",
"chars": 29136,
"preview": "# Copyright 2022 Bill Wendling, All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "yapf/pytree/__init__.py",
"chars": 596,
"preview": "# Copyright 2021 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/blank_line_calculator.py",
"chars": 6289,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/comment_splicer.py",
"chars": 15310,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/continuation_splicer.py",
"chars": 1795,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/pytree_unwrapper.py",
"chars": 15973,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/pytree_utils.py",
"chars": 10465,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/pytree_visitor.py",
"chars": 4547,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/split_penalty.py",
"chars": 24445,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/pytree/subtype_assigner.py",
"chars": 19564,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/__init__.py",
"chars": 596,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/errors.py",
"chars": 1501,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/file_resources.py",
"chars": 9320,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/format_decision_state.py",
"chars": 48776,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/format_token.py",
"chars": 11203,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/identify_container.py",
"chars": 2334,
"preview": "# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/line_joiner.py",
"chars": 3916,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/logical_line.py",
"chars": 25201,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/object_state.py",
"chars": 7912,
"preview": "# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/reformatter.py",
"chars": 28278,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/split_penalty.py",
"chars": 1252,
"preview": "# Copyright 2022 Bill Wendling, All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");"
},
{
"path": "yapf/yapflib/style.py",
"chars": 32616,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/subtypes.py",
"chars": 1157,
"preview": "# Copyright 2021 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapf/yapflib/yapf_api.py",
"chars": 11973,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/__init__.py",
"chars": 596,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/blank_line_calculator_test.py",
"chars": 9045,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/comment_splicer_test.py",
"chars": 11081,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/file_resources_test.py",
"chars": 18953,
"preview": "# -*- coding: utf-8 -*-\n# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version"
},
{
"path": "yapftests/format_decision_state_test.py",
"chars": 4401,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/format_token_test.py",
"chars": 3123,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/line_joiner_test.py",
"chars": 2590,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/logical_line_test.py",
"chars": 3228,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/main_test.py",
"chars": 3935,
"preview": "# -*- coding: utf-8 -*-\n# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version"
},
{
"path": "yapftests/pytree_unwrapper_test.py",
"chars": 9351,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/pytree_utils_test.py",
"chars": 7973,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/pytree_visitor_test.py",
"chars": 4083,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/reformatter_basic_test.py",
"chars": 116678,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/reformatter_buganizer_test.py",
"chars": 92309,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/reformatter_facebook_test.py",
"chars": 15193,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/reformatter_pep8_test.py",
"chars": 32060,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/reformatter_python3_test.py",
"chars": 18512,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/reformatter_style_config_test.py",
"chars": 7171,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/split_penalty_test.py",
"chars": 7551,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/style_test.py",
"chars": 11404,
"preview": "# -*- coding: utf-8 -*-\n# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version"
},
{
"path": "yapftests/subtype_assigner_test.py",
"chars": 17149,
"preview": "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
},
{
"path": "yapftests/utils.py",
"chars": 2567,
"preview": "# -*- coding: utf-8 -*-\n# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version"
},
{
"path": "yapftests/yapf_test.py",
"chars": 63313,
"preview": "# -*- coding: utf-8 -*-\n# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version"
},
{
"path": "yapftests/yapf_test_helper.py",
"chars": 2910,
"preview": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# "
}
]
About this extraction
This page contains the full source code of the google/yapf GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 112 files (1.1 MB), approximately 273.8k tokens, and a symbol index with 1494 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.