forked from googleapis/google-cloud-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1796 lines (1477 loc) · 65 KB
/
cli.py
File metadata and controls
1796 lines (1477 loc) · 65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2025 Google LLC
#
# 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.
import argparse
import glob
import itertools
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import yaml
from datetime import date, datetime
from functools import lru_cache
from pathlib import Path
from typing import Dict, List
import build.util
import parse_googleapis_content
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
import functools
PERF_LOGGING_ENABLED = os.environ.get("ENABLE_PERF_LOGS") == "1"
if PERF_LOGGING_ENABLED:
perf_logger = logging.getLogger("performance_metrics")
perf_logger.setLevel(logging.INFO)
perf_handler = logging.FileHandler("performance_metrics.log", mode='w')
perf_formatter = logging.Formatter('%(asctime)s | %(message)s', datefmt='%H:%M:%S')
perf_handler.setFormatter(perf_formatter)
perf_logger.addHandler(perf_handler)
perf_logger.propagate = False
def track_time(func):
"""
Decorator. Usage: @track_time
If logging is OFF, it returns the original function (Zero Overhead).
If logging is ON, it wraps the function to measure execution time.
"""
if not PERF_LOGGING_ENABLED:
return func
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
duration = time.perf_counter() - start_time
perf_logger.info(f"{func.__name__:<30} | {duration:.4f} seconds")
return wrapper
try:
import synthtool
from synthtool.languages import python, python_mono_repo
SYNTHTOOL_INSTALLED = True
SYNTHTOOL_IMPORT_ERROR = None
except ImportError as e: # pragma: NO COVER
SYNTHTOOL_IMPORT_ERROR = e
SYNTHTOOL_INSTALLED = False
logger = logging.getLogger()
BUILD_REQUEST_FILE = "build-request.json"
GENERATE_REQUEST_FILE = "generate-request.json"
CONFIGURE_REQUEST_FILE = "configure-request.json"
RELEASE_STAGE_REQUEST_FILE = "release-stage-request.json"
STATE_YAML_FILE = "state.yaml"
INPUT_DIR = "input"
LIBRARIAN_DIR = "librarian"
OUTPUT_DIR = "output"
REPO_DIR = "repo"
SOURCE_DIR = "source"
_GITHUB_BASE = "https://github.com"
_GENERATOR_INPUT_HEADER_TEXT = (
"# DO NOT EDIT THIS FILE OUTSIDE OF `.librarian/generator-input`\n"
"# The source of truth for this file is `.librarian/generator-input`\n"
)
def _read_text_file(path: str) -> str:
"""Helper function that reads a text file path and returns the content.
Args:
path(str): The file path to read.
Returns:
str: The contents of the file.
"""
with open(path, "r") as f:
return f.read()
def _write_text_file(path: str, updated_content: str):
"""Helper function that writes a text file path with the given content.
Args:
path(str): The file path to write.
updated_content(str): The contents to write to the file.
"""
os.makedirs(Path(path).parent, exist_ok=True)
with open(path, "w") as f:
f.write(updated_content)
def _read_json_file(path: str) -> Dict:
"""Helper function that reads a json file path and returns the loaded json content.
Args:
path(str): The file path to read.
Returns:
dict: The parsed JSON content.
Raises:
FileNotFoundError: If the file is not found at the specified path.
json.JSONDecodeError: If the file does not contain valid JSON.
IOError: If there is an issue reading the file.
"""
with open(path, "r") as f:
return json.load(f)
def _write_json_file(path: str, updated_content: Dict):
"""Helper function that writes a json file with the given dictionary.
Args:
path(str): The file path to write.
updated_content(Dict): The dictionary to write.
"""
with open(path, "w") as f:
json.dump(updated_content, f, indent=2)
f.write("\n")
def _add_new_library_source_roots(library_config: Dict, library_id: str) -> None:
"""Adds the default source_roots to the library configuration if not present.
Args:
library_config(Dict): The library configuration.
library_id(str): The id of the library.
"""
if library_config["source_roots"] is None:
library_config["source_roots"] = [f"packages/{library_id}"]
def _add_new_library_preserve_regex(library_config: Dict, library_id: str) -> None:
"""Adds the default preserve_regex to the library configuration if not present.
Args:
library_config(Dict): The library configuration.
library_id(str): The id of the library.
"""
if library_config["preserve_regex"] is None:
library_config["preserve_regex"] = [
f"packages/{library_id}/CHANGELOG.md",
"docs/CHANGELOG.md",
"samples/README.txt",
"scripts/client-post-processing",
"samples/snippets/README.rst",
"tests/system",
]
def _add_new_library_remove_regex(library_config: Dict, library_id: str) -> None:
"""Adds the default remove_regex to the library configuration if not present.
Args:
library_config(Dict): The library configuration.
library_id(str): The id of the library.
"""
if library_config["remove_regex"] is None:
library_config["remove_regex"] = [f"packages/{library_id}"]
def _add_new_library_tag_format(library_config: Dict) -> None:
"""Adds the default tag_format to the library configuration if not present.
Args:
library_config(Dict): The library configuration.
"""
if "tag_format" not in library_config:
library_config["tag_format"] = "{id}-v{version}"
def _get_new_library_config(request_data: Dict) -> Dict:
"""Finds and returns the configuration for a new library.
Args:
request_data(Dict): The request data from which to extract the new
library config.
Returns:
Dict: The unmodified configuration of a new library, or an empty
dictionary if not found.
"""
for library_config in request_data.get("libraries", []):
all_apis = library_config.get("apis", [])
for api in all_apis:
if api.get("status") == "new":
return library_config
return {}
def _add_new_library_version(library_config: Dict) -> None:
"""Adds the library version to the configuration if it's not present.
Args:
library_config(Dict): The library configuration.
"""
if "version" not in library_config or not library_config["version"]:
library_config["version"] = "0.0.0"
def _prepare_new_library_config(library_config: Dict) -> Dict:
"""
Prepares the new library's configuration by removing temporary keys and
adding default values.
Args:
library_config (Dict): The raw library configuration.
Returns:
Dict: The prepared library configuration.
"""
# remove status key from new library config.
all_apis = library_config.get("apis", [])
for api in all_apis:
if "status" in api:
del api["status"]
library_id = _get_library_id(library_config)
_add_new_library_source_roots(library_config, library_id)
_add_new_library_preserve_regex(library_config, library_id)
_add_new_library_remove_regex(library_config, library_id)
_add_new_library_tag_format(library_config)
_add_new_library_version(library_config)
return library_config
def _create_new_changelog_for_library(library_id: str, output: str):
"""Creates a new changelog for the library.
Args:
library_id(str): The id of the library.
output(str): Path to the directory in the container where code
should be generated.
"""
package_changelog_path = f"{output}/packages/{library_id}/CHANGELOG.md"
docs_changelog_path = f"{output}/packages/{library_id}/docs/CHANGELOG.md"
changelog_content = f"# Changelog\n\n[PyPI History][1]\n\n[1]: https://pypi.org/project/{library_id}/#history\n"
os.makedirs(os.path.dirname(package_changelog_path), exist_ok=True)
_write_text_file(package_changelog_path, changelog_content)
os.makedirs(os.path.dirname(docs_changelog_path), exist_ok=True)
_write_text_file(docs_changelog_path, changelog_content)
def handle_configure(
librarian: str = LIBRARIAN_DIR,
source: str = SOURCE_DIR,
repo: str = REPO_DIR,
input: str = INPUT_DIR,
output: str = OUTPUT_DIR,
):
"""Onboards a new library by completing its configuration.
This function reads a partial library definition from `configure-request.json`,
fills in missing fields like the version, source roots, and preservation
rules, and writes the complete configuration to `configure-response.json`.
It ensures that new libraries conform to the repository's standard structure.
See https://github.com/googleapis/librarian/blob/main/doc/container-contract.md#configure-container-command
Args:
librarian(str): Path to the directory in the container which contains
the librarian configuration.
source(str): Path to the directory in the container which contains
API protos.
repo(str): This directory will contain all directories that make up a
library, the .librarian folder, and any global file declared in
the config.yaml.
input(str): The path to the directory in the container
which contains additional generator input.
output(str): Path to the directory in the container where code
should be generated.
Raises:
ValueError: If configuring a new library fails.
"""
try:
# configure-request.json contains the library definitions.
request_data = _read_json_file(f"{librarian}/{CONFIGURE_REQUEST_FILE}")
new_library_config = _get_new_library_config(request_data)
_update_global_changelog(
f"{repo}/CHANGELOG.md",
f"{output}/CHANGELOG.md",
[new_library_config],
)
prepared_config = _prepare_new_library_config(new_library_config)
# Create a `CHANGELOG.md` and `docs/CHANGELOG.md` file for the new library
library_id = _get_library_id(prepared_config)
_create_new_changelog_for_library(library_id, output)
# Write the new library configuration to configure-response.json.
_write_json_file(f"{librarian}/configure-response.json", prepared_config)
except Exception as e:
raise ValueError("Configuring a new library failed.") from e
logger.info("'configure' command executed.")
def _get_library_id(request_data: Dict) -> str:
"""Retrieve the library id from the given request dictionary
Args:
request_data(Dict): The contents `generate-request.json`.
Raises:
ValueError: If the key `id` does not exist in `request_data`.
Returns:
str: The id of the library in `generate-request.json`
"""
library_id = request_data.get("id")
if not library_id:
raise ValueError("Request file is missing required 'id' field.")
return library_id
@track_time
def _run_post_processor(output: str, library_id: str, is_mono_repo: bool):
"""Runs the synthtool post-processor on the output directory.
Args:
output(str): Path to the directory in the container where code
should be generated.
library_id(str): The library id to be used for post processing.
is_mono_repo(bool): True if the current repository is a mono-repo.
"""
os.chdir(output)
path_to_library = f"packages/{library_id}" if is_mono_repo else "."
logger.info("Running Python post-processor...")
if SYNTHTOOL_INSTALLED:
if is_mono_repo:
python_mono_repo.owlbot_main(path_to_library)
else:
# Some repositories have customizations in `librarian.py`.
# If this file exists, run those customizations instead of `owlbot_main`
if Path(f"{output}/librarian.py").exists():
subprocess.run(["python3.14", f"{output}/librarian.py"])
else:
python.owlbot_main()
else:
raise SYNTHTOOL_IMPORT_ERROR # pragma: NO COVER
# If there is no noxfile, run `isort`` and `black` on the output.
# This is required for proto-only libraries which are not GAPIC.
if not Path(f"{output}/{path_to_library}/noxfile.py").exists():
subprocess.run(["isort", output])
subprocess.run(["black", output])
logger.info("Python post-processor ran successfully.")
def _add_header_to_files(directory: str) -> None:
"""Adds a 'DO NOT EDIT' header to files in the specified directory.
Skips JSON and YAML files. Attempts to insert the header after any existing
license headers (blocks of comments starting with '#').
Args:
directory (str): The directory containing files to update.
"""
# Files with these extensions should be ignored.
skipped_extensions = {".json", ".yaml"}
for root, _, files in os.walk(directory):
for file_name in files:
file_path = Path(root) / file_name
if file_path.suffix in skipped_extensions:
continue
with open(file_path, "r", encoding="utf-8") as f:
lines = f.readlines()
line_index = 0
# Skip the license header (contiguous block of comments starting with '#').
while line_index < len(lines) and lines[line_index].strip().startswith("#"):
line_index += 1
header_prefix = "\n" if line_index > 0 else ""
lines.insert(line_index, f"{header_prefix}{_GENERATOR_INPUT_HEADER_TEXT}\n")
with open(file_path, "w", encoding="utf-8") as f:
f.writelines(lines)
@track_time
def _copy_files_needed_for_post_processing(
output: str, input: str, library_id: str, is_mono_repo: bool
):
"""Copy files to the output directory whcih are needed during the post processing
step, such as .repo-metadata.json and script/client-post-processing, using
the input directory as the source.
Args:
output(str): Path to the directory in the container where code
should be generated.
input(str): The path to the directory in the container
which contains additional generator input.
library_id(str): The library id to be used for post processing.
is_mono_repo(bool): True if the current repository is a mono-repo.
"""
path_to_library = f"packages/{library_id}" if is_mono_repo else "."
source_dir = f"{input}/{path_to_library}"
destination_dir = f"{output}/{path_to_library}"
if Path(source_dir).exists():
shutil.copytree(
source_dir,
destination_dir,
dirs_exist_ok=True,
)
# Apply headers only to the generator-input files copied above.
_add_header_to_files(destination_dir)
# We need to create these directories so that we can copy files necessary for post-processing.
os.makedirs(
f"{output}/{path_to_library}/scripts/client-post-processing", exist_ok=True
)
# copy post-procesing files
for post_processing_file in glob.glob(
f"{input}/client-post-processing/*.yaml"
): # pragma: NO COVER
with open(post_processing_file, "r") as post_processing:
if f"{path_to_library}/" in post_processing.read():
shutil.copy(
post_processing_file,
f"{output}/{path_to_library}/scripts/client-post-processing",
)
@track_time
def _clean_up_files_after_post_processing(
output: str, library_id: str, is_mono_repo: bool
):
"""
Clean up files which should not be included in the generated client.
This function is idempotent and will not fail if files are already removed.
Args:
output(str): Path to the directory in the container where code
should be generated.
library_id(str): The library id to be used for post processing.
is_mono_repo(bool): True if the current repository is a mono-repo.
"""
path_to_library = f"packages/{library_id}" if is_mono_repo else "."
# Safely remove directories, ignoring errors if they don't exist.
shutil.rmtree(f"{output}/{path_to_library}/.nox", ignore_errors=True)
shutil.rmtree(f"{output}/owl-bot-staging", ignore_errors=True)
# Safely remove specific files if they exist using pathlib.
Path(f"{output}/{path_to_library}/CHANGELOG.md").unlink(missing_ok=True)
Path(f"{output}/{path_to_library}/docs/CHANGELOG.md").unlink(missing_ok=True)
Path(f"{output}/{path_to_library}/librarian.py").unlink(missing_ok=True)
# The glob loops are already safe, as they do nothing if no files match.
for post_processing_file in glob.glob(
f"{output}/{path_to_library}/scripts/client-post-processing/*.yaml"
): # pragma: NO COVER
os.remove(post_processing_file)
def _determine_release_level(api_path: str) -> str:
# TODO(https://github.com/googleapis/librarian/issues/2352): Determine if
# this logic can be used to set the release level.
# For now, we set the release_level as "preview" for newly generated clients.
"""Determines the release level from the API path.
Args:
api_path (str): The path to the API.
Returns:
str: The release level, which can be 'preview' or 'stable'.
"""
version = Path(api_path).name
if "beta" in version or "alpha" in version:
return "preview"
return "stable"
def _create_repo_metadata_from_service_config(
service_config_name: str, api_path: str, source: str, library_id: str
) -> Dict:
"""Creates the .repo-metadata.json content from the service config.
Args:
service_config_name (str): The name of the service config file.
api_path (str): The path to the API.
source (str): The path to the source directory.
library_id (str): The ID of the library.
Returns:
Dict: The content of the .repo-metadata.json file.
"""
full_service_config_path = f"{source}/{api_path}/{service_config_name}"
with open(full_service_config_path, "r") as f:
service_config = yaml.safe_load(f)
api_id = service_config.get("name", {})
publishing = service_config.get("publishing", {})
name_pretty = service_config.get("title", "")
product_documentation = publishing.get("documentation_uri", "")
api_shortname = service_config.get("name", "").split(".")[0]
documentation = service_config.get("documentation", {})
api_description = documentation.get("summary", "")
issue_tracker = publishing.get(
"new_issue_uri", "https://github.com/googleapis/google-cloud-python/issues"
)
# TODO(https://github.com/googleapis/librarian/issues/2352): Determine if
# `_determine_release_level` can be used to
# set the release level. For now, we set the release_level as "preview" for
# newly generated clients.
release_level = "preview"
return {
"name": library_id,
"name_pretty": name_pretty,
"api_description": api_description,
"product_documentation": product_documentation,
"client_documentation": f"https://cloud.google.com/python/docs/reference/{library_id}/latest",
"issue_tracker": issue_tracker,
"release_level": release_level,
"language": "python",
"library_type": "GAPIC_AUTO",
"repo": "googleapis/google-cloud-python",
"distribution_name": library_id,
"api_id": api_id,
# TODO(https://github.com/googleapis/librarian/issues/2369):
# Remove the dependency on `default_version` for Python post processor.
"default_version": Path(api_path).name,
"api_shortname": api_shortname,
}
def _get_repo_metadata_file_path(base: str, library_id: str, is_mono_repo: bool):
"""Constructs the full path to the .repo-metadata.json file.
Args:
base (str): The base directory where the library is located.
library_id (str): The ID of the library.
is_mono_repo (bool): True if the current repository is a mono-repo.
Returns:
str: The absolute path to the .repo-metadata.json file.
"""
path_to_library = f"packages/{library_id}" if is_mono_repo else "."
return f"{base}/{path_to_library}/.repo-metadata.json"
@lru_cache(maxsize=None)
def _get_repo_name_from_repo_metadata(base: str, library_id: str, is_mono_repo: bool):
"""Retrieves the repository name from the .repo-metadata.json file.
This function is cached to avoid redundant file I/O.
Args:
base (str): The base directory where the library is located.
library_id (str): The ID of the library.
is_mono_repo (bool): True if the current repository is a mono-repo.
Returns:
str: The name of the repository (e.g., 'googleapis/google-cloud-python').
Raises:
ValueError: If the '.repo-metadata.json' file is missing the 'repo' field.
"""
if is_mono_repo:
return "googleapis/google-cloud-python"
file_path = _get_repo_metadata_file_path(base, library_id, is_mono_repo)
repo_metadata = _read_json_file(file_path)
repo_name = repo_metadata.get("repo")
if not repo_name:
raise ValueError("`.repo-metadata.json` file is missing required 'repo' field.")
return repo_name
@track_time
def _generate_repo_metadata_file(
output: str, library_id: str, source: str, apis: List[Dict], is_mono_repo: bool
):
"""Generates the .repo-metadata.json file from the primary API service config.
Args:
output (str): The path to the output directory.
library_id (str): The ID of the library.
source (str): The path to the source directory.
apis (List[Dict]): A list of APIs to generate.
is_mono_repo(bool): True if the current repository is a mono-repo.
"""
path_to_library = f"packages/{library_id}" if is_mono_repo else "."
output_repo_metadata = _get_repo_metadata_file_path(
output, library_id, is_mono_repo
)
# TODO(https://github.com/googleapis/librarian/issues/2334)): If `.repo-metadata.json`
# already exists in the `output` dir, then this means that it has been successfully copied
# over from the `input` dir and we can skip the logic here. Remove the following logic
# once we clean up all the `.repo-metadata.json` files from `.librarian/generator-input`.
if os.path.exists(output_repo_metadata):
return
os.makedirs(f"{output}/{path_to_library}", exist_ok=True)
# TODO(https://github.com/googleapis/librarian/issues/2333): Programatically
# determine the primary api to be used to
# to determine the information for metadata. For now, let's use the first
# api in the list.
primary_api = apis[0]
metadata_content = _create_repo_metadata_from_service_config(
primary_api.get("service_config"),
primary_api.get("path"),
source,
library_id,
)
_write_json_file(output_repo_metadata, metadata_content)
@track_time
def _copy_readme_to_docs(output: str, library_id: str, is_mono_repo: bool):
"""Copies the README.rst file for a generated library to docs/README.rst.
This function is robust against various symlink configurations that could
cause `shutil.copy` to fail with a `SameFileError`. It reads the content
from the source and writes it to the destination, ensuring the final
destination is a real file.
Args:
output(str): Path to the directory in the container where code
should be generated.
library_id(str): The library id.
"""
path_to_library = f"packages/{library_id}" if is_mono_repo else "."
source_path = f"{output}/{path_to_library}/README.rst"
docs_path = f"{output}/{path_to_library}/docs"
destination_path = f"{docs_path}/README.rst"
# If the source file doesn't exist (not even as a broken symlink),
# there's nothing to copy.
if not os.path.lexists(source_path):
return
# Read the content from the source, which will resolve any symlinks.
with open(source_path, "r") as f:
content = f.read()
# Remove any symlinks at the destination to prevent errors.
if os.path.islink(destination_path):
os.remove(destination_path)
elif os.path.islink(docs_path):
os.remove(docs_path)
# Ensure the destination directory exists as a real directory.
os.makedirs(docs_path, exist_ok=True)
# Write the content to the destination, creating a new physical file.
with open(destination_path, "w") as f:
f.write(content)
@track_time
def handle_generate(
librarian: str = LIBRARIAN_DIR,
source: str = SOURCE_DIR,
output: str = OUTPUT_DIR,
input: str = INPUT_DIR,
):
"""The main coordinator for the code generation process.
This function orchestrates the generation of a client library by reading a
`librarian/generate-request.json` file, determining the necessary Bazel rule for each API, and
(in future steps) executing the build.
See https://github.com/googleapis/librarian/blob/main/doc/container-contract.md#generate-container-command
Args:
librarian(str): Path to the directory in the container which contains
the librarian configuration.
source(str): Path to the directory in the container which contains
API protos.
output(str): Path to the directory in the container where code
should be generated.
input(str): The path to the directory in the container
which contains additional generator input.
Raises:
ValueError: If the `generate-request.json` file is not found or read.
"""
try:
is_mono_repo = _is_mono_repo(input)
# Read a generate-request.json file
request_data = _read_json_file(f"{librarian}/{GENERATE_REQUEST_FILE}")
library_id = _get_library_id(request_data)
apis_to_generate = request_data.get("apis", [])
version = request_data.get("version")
for api in apis_to_generate:
api_path = api.get("path")
if api_path:
_generate_api(
api_path, library_id, source, output, version, is_mono_repo
)
_copy_files_needed_for_post_processing(output, input, library_id, is_mono_repo)
_generate_repo_metadata_file(
output, library_id, source, apis_to_generate, is_mono_repo
)
_run_post_processor(output, library_id, is_mono_repo)
_copy_readme_to_docs(output, library_id, is_mono_repo)
_clean_up_files_after_post_processing(output, library_id, is_mono_repo)
except Exception as e:
raise ValueError("Generation failed.") from e
logger.info("'generate' command executed.")
def _read_bazel_build_py_rule(api_path: str, source: str) -> Dict:
"""
Reads and parses the BUILD.bazel file to find the Python GAPIC rule content.
Args:
api_path (str): The relative path to the API directory (e.g., 'google/cloud/language/v1').
source (str): Path to the directory containing API protos.
Returns:
Dict: A dictionary containing the parsed attributes of the `_py_gapic` rule, if found.
"""
build_file_path = f"{source}/{api_path}/BUILD.bazel"
content = _read_text_file(build_file_path)
result = parse_googleapis_content.parse_content(content)
py_gapic_entries = [key for key in result.keys() if key.endswith("_py_gapic")]
# Assuming at most one _py_gapic rule per BUILD file for a given language
if len(py_gapic_entries) > 0:
return result[py_gapic_entries[0]]
else:
return {}
def _get_api_generator_options(
api_path: str, py_gapic_config: Dict, gapic_version: str
) -> List[str]:
"""
Extracts generator options from the parsed Python GAPIC rule configuration.
Args:
api_path (str): The relative path to the API directory.
py_gapic_config (Dict): The parsed attributes of the Python GAPIC rule.
gapic_version(str): The desired version number for the GAPIC client library
in a format which follows PEP-440.
Returns:
List[str]: A list of formatted generator options (e.g., ['retry-config=...', 'transport=...']).
"""
generator_options = []
# Mapping of Bazel rule attributes to protoc-gen-python_gapic options
config_key_map = {
"grpc_service_config": "retry-config",
"rest_numeric_enums": "rest-numeric-enums",
"service_yaml": "service-yaml",
"transport": "transport",
}
for bazel_key, protoc_key in config_key_map.items():
config_value = py_gapic_config.get(bazel_key)
if config_value is not None:
if bazel_key in ("service_yaml", "grpc_service_config"):
# These paths are relative to the source root
generator_options.append(f"{protoc_key}={api_path}/{config_value}")
else:
# Other options use the value directly
generator_options.append(f"{protoc_key}={config_value}")
# The value of `opt_args` in the `py_gapic` bazel rule is already a list of strings.
optional_arguments = py_gapic_config.get("opt_args", [])
# Specify `gapic-version` using the version from `state.yaml`
optional_arguments.extend([f"gapic-version={gapic_version}"])
# Add optional arguments
generator_options.extend(optional_arguments)
return generator_options
def _construct_protoc_command(api_path: str, tmp_dir: str) -> str:
"""
Constructs the full protoc command string.
Args:
api_path (str): The relative path to the API directory.
tmp_dir (str): The temporary directory for protoc output.
Returns:
str: The complete protoc command string suitable for shell execution.
"""
command_parts = [
f"protoc {api_path}/*.proto",
f"--python_out={tmp_dir}",
f"--pyi_out={tmp_dir}",
]
return " ".join(command_parts)
def _determine_generator_command(
api_path: str, tmp_dir: str, generator_options: List[str]
) -> str:
"""
Constructs the full protoc command string.
Args:
api_path (str): The relative path to the API directory.
tmp_dir (str): The temporary directory for protoc output.
generator_options (List[str]): Extracted generator options.
Returns:
str: The complete protoc command string suitable for shell execution.
"""
# Start with the protoc base command. The glob pattern requires shell=True.
command_parts = [
f"protoc {api_path}/*.proto",
f"--python_gapic_out={tmp_dir}",
]
if generator_options:
# Protoc options are passed as a comma-separated list to --python_gapic_opt.
option_string = "metadata," + ",".join(generator_options)
command_parts.append(f"--python_gapic_opt={option_string}")
return " ".join(command_parts)
def _run_protoc_command(generator_command: str, source: str):
"""
Executes the protoc generation command using subprocess.
Args:
generator_command (str): The complete protoc command string.
source (str): Path to the directory where the command should be run (API protos root).
"""
# shell=True is required because the command string contains a glob pattern (*.proto)
subprocess.run(
[generator_command],
cwd=source,
shell=True,
check=True,
capture_output=True,
text=True,
)
def _get_staging_child_directory(api_path: str, is_proto_only_library: bool) -> str:
"""
Determines the correct sub-path within 'owl-bot-staging' for the generated code.
For proto-only libraries, the structure is usually just the proto directory,
e.g., 'thing-py/google/thing'.
For GAPIC libraries, it's typically the version segment, e.g., 'v1'.
Args:
api_path (str): The relative path to the API directory (e.g., 'google/cloud/language/v1').
is_proto_only_library(bool): True, if this is a proto-only library.
Returns:
str: The sub-directory name to use for staging.
"""
version_candidate = api_path.split("/")[-1]
if version_candidate.startswith("v") and not is_proto_only_library:
return version_candidate
elif is_proto_only_library:
# Fallback for non-'v' version segment for proto-only library
return f"{os.path.basename(api_path)}-py/{api_path}"
else:
# Fallback for non-'v' version segment for GAPIC
return f"{os.path.basename(api_path)}-py"
def _stage_proto_only_library(
api_path: str, source_dir: str, tmp_dir: str, staging_dir: str
) -> None:
"""
Handles staging for proto-only libraries (e.g., common protos).
This involves copying the generated python files and the original proto files.
Args:
api_path (str): The relative path to the API directory.
source_dir (str): Path to the directory containing API protos.
tmp_dir (str): The temporary directory where protoc output was placed.
staging_dir (str): The final destination for the staged code.
"""
# 1. Copy the generated Python files (e.g., *_pb2.py) from the protoc output
# The generated Python files are placed under a directory corresponding to `api_path`
# inside the temporary directory, since the protoc command ran with `api_path`
# specified.
shutil.copytree(f"{tmp_dir}/{api_path}", staging_dir, dirs_exist_ok=True)
# 2. Copy the original proto files to the staging directory
# This is typically done for proto-only libraries so that the protos are included
# in the distributed package.
proto_glob_path = f"{source_dir}/{api_path}/*.proto"
for proto_file in glob.glob(proto_glob_path):
# The glob is expected to find the file inside the source_dir.
# We copy only the filename to the target staging directory.
shutil.copyfile(proto_file, f"{staging_dir}/{os.path.basename(proto_file)}")
def _stage_gapic_library(tmp_dir: str, staging_dir: str) -> None:
"""
Handles staging for GAPIC client libraries.
This involves copying all contents from the temporary output directory.
Args:
tmp_dir (str): The temporary directory where protoc/GAPIC generator output was placed.
staging_dir (str): The final destination for the staged code.
"""
# For GAPIC, the generator output is flat in `tmp_dir` and includes all
# necessary files like setup.py, client library, etc.
shutil.copytree(tmp_dir, staging_dir, dirs_exist_ok=True)
@track_time
def _generate_api(
api_path: str,
library_id: str,
source: str,
output: str,
gapic_version: str,
is_mono_repo: bool,
):
"""
Handles the generation and staging process for a single API path.
Args:
api_path (str): The relative path to the API directory (e.g., 'google/cloud/language/v1').
library_id (str): The ID of the library being generated.
source (str): Path to the directory containing API protos.
output (str): Path to the output directory where code should be staged.
gapic_version(str): The desired version number for the GAPIC client library
in a format which follows PEP-440.
is_mono_repo(bool): True if the current repository is a mono-repo.
"""
py_gapic_config = _read_bazel_build_py_rule(api_path, source)
is_proto_only_library = len(py_gapic_config) == 0
with tempfile.TemporaryDirectory() as tmp_dir:
# 1. Determine the command for code generation
if is_proto_only_library:
command = _construct_protoc_command(api_path, tmp_dir)
else:
generator_options = _get_api_generator_options(
api_path, py_gapic_config, gapic_version=gapic_version
)