Skip to content

Commit

Permalink
Merge pull request #211 from pavoljuhas/update-pylint-copyright-checker
Browse files Browse the repository at this point in the history
Update copyright checker for pylint-3
  • Loading branch information
dstrain115 authored Oct 7, 2024
2 parents 00dbc77 + 391c95d commit b1d23ae
Show file tree
Hide file tree
Showing 118 changed files with 475 additions and 261 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/pylint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ jobs:
python-version: '3.12'
architecture: 'x64'
- name: Install Pylint
# TODO: #210 - install the latest pylint below
run: |
python -m pip install --upgrade pip
pip install 'pylint<3'
pip install pylint
- name: Pylint check
run: dev_tools/pylint
34 changes: 18 additions & 16 deletions dev_tools/.pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,57 +2,59 @@
load-plugins=pylint.extensions.docstyle,pylint.extensions.docparams,pylint_copyright_checker
max-line-length=88
disable=all
#ignore-paths=cirq-google/cirq_google/cloud/.*
ignore-patterns=.*_pb2\.py
output-format=colorized
score=no
reports=no
enable=
anomalous-backslash-in-string,
# anomalous-backslash-in-string, # TODO: #210 - enable and fix
assert-on-tuple,
bad-indentation,
bad-option-value,
bad-reversed-sequence,
bad-super-call,
consider-merging-isinstance,
# consider-using-f-string, # TODO: #210 - enable and fix
continue-in-finally,
dangerous-default-value,
# dangerous-default-value, # TODO: #210 - enable and fix
docstyle,
duplicate-argument-name,
expression-not-assigned,
function-redefined,
# expression-not-assigned, # TODO: #210 - enable and fix
f-string-without-interpolation,
# function-redefined, # TODO: #210 - enable and fix
inconsistent-mro,
init-is-generator,
line-too-long,
# line-too-long, # TODO: #210 - enable and fix
lost-exception,
missing-kwoa,
missing-param-doc,
# missing-param-doc, # TODO: #210 - enable and fix
missing-raises-doc,
mixed-line-endings,
no-value-for-parameter,
# no-value-for-parameter, # TODO: #210 - enable and fix
nonexistent-operator,
not-in-loop,
pointless-statement,
redefined-builtin,
# pointless-statement, # TODO: #210 - enable and fix
# redefined-builtin, # TODO: #210 - enable and fix
return-arg-in-generator,
return-in-init,
return-outside-function,
simplifiable-if-statement,
singleton-comparison,
syntax-error,
too-many-function-args,
# too-many-function-args, # TODO: #210 - enable and fix
trailing-whitespace,
undefined-variable,
unexpected-keyword-arg,
# unexpected-keyword-arg, # TODO: #210 - enable and fix
unhashable-dict-key,
unnecessary-pass,
# unnecessary-pass, # TODO: #210 - enable and fix
unreachable,
unrecognized-inline-option,
unused-import,
unnecessary-semicolon,
unused-variable,
unused-wildcard-import,
wildcard-import,
# unused-variable, # TODO: #210 - enable and fix
# unused-wildcard-import, # TODO: #210 - enable and fix
# wildcard-import, # TODO: #210 - enable and fix
wrong-or-nonexistent-copyright-notice,
wrong-import-order,
wrong-import-position,
yield-outside-function
Expand Down
2 changes: 1 addition & 1 deletion dev_tools/check_notebooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# 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
# https://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,
Expand Down
117 changes: 117 additions & 0 deletions dev_tools/pylint_copyright_checker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Copyright 2024 The Unitary Authors
#
# 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
#
# https://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.

from __future__ import annotations

from typing import TYPE_CHECKING

from astroid import nodes
from pylint.checkers import BaseRawFileChecker

if TYPE_CHECKING:
from pylint.lint import PyLinter


class CopyrightChecker(BaseRawFileChecker):
"""Check for the copyright notices at the beginning of a Python source file.
This checker can be disabled by putting `# pylint: disable=wrong-or-nonexistent-copyright-notice`
at the beginning of a file.
"""

name = "copyright-notice"
msgs = {
"R0001": (
"Missing or wrong copyright notice",
"wrong-or-nonexistent-copyright-notice",
"Consider putting a correct copyright notice at the beginning of a file.",
)
}
options = ()

def process_module(self, node: nodes.Module) -> None:
"""Check whether the copyright notice is correctly placed in the source file of a module.
Compare the first lines of a source file against the standard copyright notice (i.e., the
`golden` variable below). Suffix whitespace (including newline symbols) is not considered
during the comparison. Pylint will report a message if the copyright notice is not
correctly placed.
Args:
node: the module to be checked.
"""
# Exit if the checker is disabled in the source file.
if not self.linter.is_message_enabled("wrong-or-nonexistent-copyright-notice"):
return
golden = [
b'# Copyright 20XX The Unitary Authors',
b'#',
b'# Licensed under the Apache License, Version 2.0 (the "License");',
b'# you may not use this file except in compliance with the License.',
b'# You may obtain a copy of the License at',
b'#',
b'# https://www.apache.org/licenses/LICENSE-2.0',
b'#',
b'# Unless required by applicable law or agreed to in writing, software',
b'# distributed under the License is distributed on an "AS IS" BASIS,',
b'# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
b'# See the License for the specific language governing permissions and',
b'# limitations under the License.',
]
with node.stream() as stream:

def skip_shebang(stream):
"""Skip shebang line if present, and blank lines between shebang and content."""
lines = iter(enumerate(stream))
try:
lineno, line = next(lines)
except StopIteration:
return
if line.startswith(b'#!'):
# skip shebang and blank lines
for lineno, line in lines:
if line.strip():
yield lineno, line
break
else:
# no shebang
yield lineno, line
yield from lines

for expected_line, (i, (lineno, line)) in zip(golden, enumerate(skip_shebang(stream))):
for expected_char, (colno, char) in zip(expected_line, enumerate(line)):
# The text needs to be same as the template except for the year.
if expected_char != char and not (i == 0 and 14 <= colno <= 15):
self.add_message(
"wrong-or-nonexistent-copyright-notice",
line=lineno + 1,
col_offset=colno,
)
return
# The line cannot be shorter than the template or contain extra text.
if len(line) < len(expected_line) or line[len(expected_line) :].strip() != b'':
self.add_message(
"wrong-or-nonexistent-copyright-notice",
line=lineno + 1,
col_offset=min(len(line), len(expected_line)),
)
return


def register(linter: PyLinter):
"""Register this checker to pylint.
The registration is done automatically if this file is in $PYTHONPATH.
"""
linter.register_checker(CopyrightChecker(linter))
2 changes: 1 addition & 1 deletion dev_tools/write-ci-requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# 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
# https://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,
Expand Down
15 changes: 8 additions & 7 deletions examples/fox_in_a_hole/fox_in_a_hole.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@
"""Classical and quantum Fox-in-a-hole game."""

import abc
import argparse
import sys
import enum
import numpy as np
import argparse
from typing import Optional

import numpy as np

from unitary.alpha import (
QuantumObject,
QuantumWorld,
Expand Down Expand Up @@ -357,19 +358,19 @@ def take_random_move(self) -> str:

# Initialize game object

print(f"---------------------------------")
print("---------------------------------")
if args.is_quantum or (args.qprob is not None and args.qprob > 0.0):
game: Game = QuantumGame(qprob=args.qprob, iswap=args.use_iswap)
print(f"Quantum Fox-in-a-hole game.")
print("Quantum Fox-in-a-hole game.")
print(f"Probability of quantum move: {game.qprob}.")
if args.use_iswap:
print(f"Using iSWAP for moves.")
print("Using iSWAP for moves.")
else:
print(f"Using SWAP for moves.")
print("Using SWAP for moves.")
else:
game = ClassicalGame()
print("Classical Fox-in-a-hole game.")
print(f"---------------------------------")
print("---------------------------------")

# Run Fox-in-a-hole
game.run()
2 changes: 0 additions & 2 deletions examples/fox_in_a_hole/fox_in_a_hole_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

"""Tests for ClassicalGame and QuantumGame classes."""

import pytest

from . import fox_in_a_hole as fh


Expand Down
2 changes: 1 addition & 1 deletion examples/quantum_chinese_chess/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# 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
# https://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,
Expand Down
11 changes: 6 additions & 5 deletions examples/quantum_chinese_chess/board.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
# 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.
import numpy as np

from typing import List, Tuple

import numpy as np

import unitary.alpha as alpha
from .enums import (
SquareState,
Expand Down Expand Up @@ -61,8 +64,7 @@ def set_language(self, lang: Language) -> None:

@classmethod
def from_fen(cls, fen: str = _INITIAL_FEN) -> "Board":
"""
Translates FEN (Forsyth-Edwards Notation) symbols into the whole QuantumWorld board.
"""Translates FEN (Forsyth-Edwards Notation) symbols into the whole QuantumWorld board.
FEN rule for Chinese Chess could be found at https://www.wxf-xiangqi.org/images/computer-xiangqi/fen-for-xiangqi-chinese-chess.pdf
"""
chess_board = {}
Expand Down Expand Up @@ -110,8 +112,7 @@ def to_str(
probabilities: List[float] = None,
peek_result: List[int] = None,
) -> str:
"""
Print the board into string.
"""Print the board into string.
Args:
terminal: type of the terminal that the game is currently running on;
Expand Down
14 changes: 7 additions & 7 deletions examples/quantum_chinese_chess/board_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
# 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.
#

import re

from unitary import alpha
from .enums import (
Language,
Color,
Expand All @@ -25,11 +28,8 @@
locations_to_bitboard,
assert_samples_in,
assert_sample_distribution,
get_board_probability_distribution,
set_board,
)
from unitary import alpha
import re


def test_init_with_default_fen():
Expand Down Expand Up @@ -170,16 +170,16 @@ def test_flying_general_check_classical_cases():
board = Board.from_fen()
# If they are in different columns, the check fails.
board.king_locations = ["d0", "e9"]
assert board.flying_general_check() == False
assert not board.flying_general_check()

# If there are classical pieces between two KINGs, the check fails.
board.king_locations = ["e0", "e9"]
assert board.flying_general_check() == False
assert not board.flying_general_check()

# If there are no pieces between two KINGs, the check successes.
board.board["e3"].reset()
board.board["e6"].reset()
assert board.flying_general_check() == True
assert board.flying_general_check()


def test_flying_general_check_quantum_cases():
Expand Down
4 changes: 2 additions & 2 deletions examples/quantum_chinese_chess/chess.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# 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.

from typing import Tuple, List
from .board import Board
from .enums import (
Expand All @@ -31,7 +32,6 @@
MergeSlide,
CannonFire,
)
import readline

# List of acceptable commands.
_HELP_TEXT = """
Expand Down Expand Up @@ -138,7 +138,7 @@ def parse_input_string(str_to_parse: str) -> Tuple[List[str], List[str]]:
for location in sources + targets:
if location[0].lower() not in "abcdefghi" or not location[1].isdigit():
raise ValueError(
f"Invalid location string. Make sure they are from a0 to i9."
"Invalid location string. Make sure they are from a0 to i9."
)
return sources, targets

Expand Down
Loading

0 comments on commit b1d23ae

Please sign in to comment.