Skip to content

Commit 70dc132

Browse files
chore: remove 'pip install' statements from python_library templates [autoapprove] (googleapis#106)
Source-Link: googleapis/synthtool@1f37ce7 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:8e84e0e0d71a0d681668461bba02c9e1394c785f31a10ae3470660235b673086
1 parent 474fed2 commit 70dc132

File tree

6 files changed

+786
-9
lines changed

6 files changed

+786
-9
lines changed

.github/.OwlBot.lock.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,5 @@
1313
# limitations under the License.
1414
docker:
1515
image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest
16-
digest: sha256:c6c965a4bf40c19011b11f87dbc801a66d3a23fbc6704102be064ef31c51f1c3
17-
# created: 2022-08-09T15:58:56.463048506Z
16+
digest: sha256:8e84e0e0d71a0d681668461bba02c9e1394c785f31a10ae3470660235b673086
17+
# created: 2022-08-24T15:24:05.205983455Z

.kokoro/noxfile.py

Lines changed: 310 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,310 @@
1+
# Copyright 2019 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import print_function
16+
17+
import glob
18+
import os
19+
from pathlib import Path
20+
import sys
21+
from typing import Callable, Dict, List, Optional
22+
23+
import nox
24+
25+
# WARNING - WARNING - WARNING - WARNING - WARNING
26+
# WARNING - WARNING - WARNING - WARNING - WARNING
27+
# DO NOT EDIT THIS FILE EVER!
28+
# WARNING - WARNING - WARNING - WARNING - WARNING
29+
# WARNING - WARNING - WARNING - WARNING - WARNING
30+
31+
BLACK_VERSION = "black==22.3.0"
32+
ISORT_VERSION = "isort==5.10.1"
33+
34+
# Copy `noxfile_config.py` to your directory and modify it instead.
35+
36+
# `TEST_CONFIG` dict is a configuration hook that allows users to
37+
# modify the test configurations. The values here should be in sync
38+
# with `noxfile_config.py`. Users will copy `noxfile_config.py` into
39+
# their directory and modify it.
40+
41+
TEST_CONFIG = {
42+
# You can opt out from the test for specific Python versions.
43+
"ignored_versions": [],
44+
# Old samples are opted out of enforcing Python type hints
45+
# All new samples should feature them
46+
"enforce_type_hints": False,
47+
# An envvar key for determining the project id to use. Change it
48+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
49+
# build specific Cloud project. You can also use your own string
50+
# to use your own Cloud project.
51+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
52+
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
53+
# If you need to use a specific version of pip,
54+
# change pip_version_override to the string representation
55+
# of the version number, for example, "20.2.4"
56+
"pip_version_override": None,
57+
# A dictionary you want to inject into your test. Don't put any
58+
# secrets here. These values will override predefined values.
59+
"envs": {},
60+
}
61+
62+
63+
try:
64+
# Ensure we can import noxfile_config in the project's directory.
65+
sys.path.append(".")
66+
from noxfile_config import TEST_CONFIG_OVERRIDE
67+
except ImportError as e:
68+
print("No user noxfile_config found: detail: {}".format(e))
69+
TEST_CONFIG_OVERRIDE = {}
70+
71+
# Update the TEST_CONFIG with the user supplied values.
72+
TEST_CONFIG.update(TEST_CONFIG_OVERRIDE)
73+
74+
75+
def get_pytest_env_vars() -> Dict[str, str]:
76+
"""Returns a dict for pytest invocation."""
77+
ret = {}
78+
79+
# Override the GCLOUD_PROJECT and the alias.
80+
env_key = TEST_CONFIG["gcloud_project_env"]
81+
# This should error out if not set.
82+
ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key]
83+
84+
# Apply user supplied envs.
85+
ret.update(TEST_CONFIG["envs"])
86+
return ret
87+
88+
89+
# DO NOT EDIT - automatically generated.
90+
# All versions used to test samples.
91+
ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"]
92+
93+
# Any default versions that should be ignored.
94+
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]
95+
96+
TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS])
97+
98+
INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in (
99+
"True",
100+
"true",
101+
)
102+
103+
# Error if a python version is missing
104+
nox.options.error_on_missing_interpreters = True
105+
106+
#
107+
# Style Checks
108+
#
109+
110+
111+
def _determine_local_import_names(start_dir: str) -> List[str]:
112+
"""Determines all import names that should be considered "local".
113+
114+
This is used when running the linter to insure that import order is
115+
properly checked.
116+
"""
117+
file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)]
118+
return [
119+
basename
120+
for basename, extension in file_ext_pairs
121+
if extension == ".py"
122+
or os.path.isdir(os.path.join(start_dir, basename))
123+
and basename not in ("__pycache__")
124+
]
125+
126+
127+
# Linting with flake8.
128+
#
129+
# We ignore the following rules:
130+
# E203: whitespace before ‘:’
131+
# E266: too many leading ‘#’ for block comment
132+
# E501: line too long
133+
# I202: Additional newline in a section of imports
134+
#
135+
# We also need to specify the rules which are ignored by default:
136+
# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121']
137+
FLAKE8_COMMON_ARGS = [
138+
"--show-source",
139+
"--builtin=gettext",
140+
"--max-complexity=20",
141+
"--import-order-style=google",
142+
"--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py",
143+
"--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202",
144+
"--max-line-length=88",
145+
]
146+
147+
148+
@nox.session
149+
def lint(session: nox.sessions.Session) -> None:
150+
if not TEST_CONFIG["enforce_type_hints"]:
151+
session.install("flake8", "flake8-import-order")
152+
else:
153+
session.install("flake8", "flake8-import-order", "flake8-annotations")
154+
155+
local_names = _determine_local_import_names(".")
156+
args = FLAKE8_COMMON_ARGS + [
157+
"--application-import-names",
158+
",".join(local_names),
159+
".",
160+
]
161+
session.run("flake8", *args)
162+
163+
164+
#
165+
# Black
166+
#
167+
168+
169+
@nox.session
170+
def blacken(session: nox.sessions.Session) -> None:
171+
"""Run black. Format code to uniform standard."""
172+
session.install(BLACK_VERSION)
173+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
174+
175+
session.run("black", *python_files)
176+
177+
178+
#
179+
# format = isort + black
180+
#
181+
182+
183+
@nox.session
184+
def format(session: nox.sessions.Session) -> None:
185+
"""
186+
Run isort to sort imports. Then run black
187+
to format code to uniform standard.
188+
"""
189+
session.install(BLACK_VERSION, ISORT_VERSION)
190+
python_files = [path for path in os.listdir(".") if path.endswith(".py")]
191+
192+
# Use the --fss option to sort imports using strict alphabetical order.
193+
# See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections
194+
session.run("isort", "--fss", *python_files)
195+
session.run("black", *python_files)
196+
197+
198+
#
199+
# Sample Tests
200+
#
201+
202+
203+
PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"]
204+
205+
206+
def _session_tests(
207+
session: nox.sessions.Session, post_install: Callable = None
208+
) -> None:
209+
# check for presence of tests
210+
test_list = glob.glob("*_test.py") + glob.glob("test_*.py")
211+
test_list.extend(glob.glob("tests"))
212+
213+
if len(test_list) == 0:
214+
print("No tests found, skipping directory.")
215+
return
216+
217+
if TEST_CONFIG["pip_version_override"]:
218+
pip_version = TEST_CONFIG["pip_version_override"]
219+
session.install(f"pip=={pip_version}")
220+
"""Runs py.test for a particular project."""
221+
concurrent_args = []
222+
if os.path.exists("requirements.txt"):
223+
if os.path.exists("constraints.txt"):
224+
session.install("-r", "requirements.txt", "-c", "constraints.txt")
225+
else:
226+
session.install("-r", "requirements.txt")
227+
with open("requirements.txt") as rfile:
228+
packages = rfile.read()
229+
230+
if os.path.exists("requirements-test.txt"):
231+
if os.path.exists("constraints-test.txt"):
232+
session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt")
233+
else:
234+
session.install("-r", "requirements-test.txt")
235+
with open("requirements-test.txt") as rtfile:
236+
packages += rtfile.read()
237+
238+
if INSTALL_LIBRARY_FROM_SOURCE:
239+
session.install("-e", _get_repo_root())
240+
241+
if post_install:
242+
post_install(session)
243+
244+
if "pytest-parallel" in packages:
245+
concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"])
246+
elif "pytest-xdist" in packages:
247+
concurrent_args.extend(["-n", "auto"])
248+
249+
session.run(
250+
"pytest",
251+
*(PYTEST_COMMON_ARGS + session.posargs + concurrent_args),
252+
# Pytest will return 5 when no tests are collected. This can happen
253+
# on travis where slow and flaky tests are excluded.
254+
# See http://doc.pytest.org/en/latest/_modules/_pytest/main.html
255+
success_codes=[0, 5],
256+
env=get_pytest_env_vars(),
257+
)
258+
259+
260+
@nox.session(python=ALL_VERSIONS)
261+
def py(session: nox.sessions.Session) -> None:
262+
"""Runs py.test for a sample using the specified version of Python."""
263+
if session.python in TESTED_VERSIONS:
264+
_session_tests(session)
265+
else:
266+
session.skip(
267+
"SKIPPED: {} tests are disabled for this sample.".format(session.python)
268+
)
269+
270+
271+
#
272+
# Readmegen
273+
#
274+
275+
276+
def _get_repo_root() -> Optional[str]:
277+
"""Returns the root folder of the project."""
278+
# Get root of this repository. Assume we don't have directories nested deeper than 10 items.
279+
p = Path(os.getcwd())
280+
for i in range(10):
281+
if p is None:
282+
break
283+
if Path(p / ".git").exists():
284+
return str(p)
285+
# .git is not available in repos cloned via Cloud Build
286+
# setup.py is always in the library's root, so use that instead
287+
# https://github.com/googleapis/synthtool/issues/792
288+
if Path(p / "setup.py").exists():
289+
return str(p)
290+
p = p.parent
291+
raise Exception("Unable to detect repository root.")
292+
293+
294+
GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")])
295+
296+
297+
@nox.session
298+
@nox.parametrize("path", GENERATED_READMES)
299+
def readmegen(session: nox.sessions.Session, path: str) -> None:
300+
"""(Re-)generates the readme for a sample."""
301+
session.install("jinja2", "pyyaml")
302+
dir_ = os.path.dirname(path)
303+
304+
if os.path.exists(os.path.join(dir_, "requirements.txt")):
305+
session.install("-r", os.path.join(dir_, "requirements.txt"))
306+
307+
in_file = os.path.join(dir_, "README.rst.in")
308+
session.run(
309+
"python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file
310+
)

.kokoro/publish-docs.sh

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,12 @@ export PYTHONUNBUFFERED=1
2121
export PATH="${HOME}/.local/bin:${PATH}"
2222

2323
# Install nox
24-
python3 -m pip install --user --upgrade --quiet nox
24+
python3 -m pip install --require-hashes -r .kokoro/requirements.txt
2525
python3 -m nox --version
2626

2727
# build docs
2828
nox -s docs
2929

30-
python3 -m pip install --user gcp-docuploader
31-
3230
# create metadata
3331
python3 -m docuploader create-metadata \
3432
--name=$(jq --raw-output '.name // empty' .repo-metadata.json) \

.kokoro/release.sh

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,9 @@
1616
set -eo pipefail
1717

1818
# Start the releasetool reporter
19-
python3 -m pip install gcp-releasetool
19+
python3 -m pip install --require-hashes -r .kokoro/requirements.txt
2020
python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script
2121

22-
# Ensure that we have the latest versions of Twine, Wheel, and Setuptools.
23-
python3 -m pip install --upgrade twine wheel setuptools
24-
2522
# Disable buffering, so that the logs stream through.
2623
export PYTHONUNBUFFERED=1
2724

.kokoro/requirements.in

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
gcp-docuploader
2+
gcp-releasetool
3+
importlib-metadata
4+
typing-extensions
5+
twine
6+
wheel
7+
setuptools
8+
nox

0 commit comments

Comments
 (0)