Open-source SEO, GEO, and marketing skills for AI agents.
fix: resolve gcloud cmd on Windows
Tong Chene49ae98330fe
diff --git a/seo/seo-analysis/scripts/_gcloud.py b/seo/seo-analysis/scripts/_gcloud.pynew file mode 100644index 00000000..a9d50953--- /dev/null+++ b/seo/seo-analysis/scripts/_gcloud.py@@ -0,0 +1,27 @@+"""Helpers for invoking the gcloud CLI portably."""++import shutil+import subprocess+import sys+++def gcloud_command(args):+ """Return a subprocess argument list for a gcloud command.++ On Windows, the Google Cloud SDK installs gcloud as gcloud.cmd. Python's+ shell=False path resolution does not expand PATHEXT for CreateProcess, so+ invoke the resolved batch file through cmd.exe.+ """+ if not args or args[0] != "gcloud":+ raise ValueError("gcloud_command expects args starting with 'gcloud'")++ gcloud = shutil.which("gcloud")+ if sys.platform == "win32" and gcloud and gcloud.lower().endswith((".cmd", ".bat")):+ return ["cmd", "/c", gcloud, *args[1:]]++ return [gcloud or "gcloud", *args[1:]]+++def gcloud_run(args, *run_args, **run_kwargs):+ """Run gcloud with subprocess.run using the portable command wrapper."""+ return subprocess.run(gcloud_command(args), *run_args, **run_kwargs)diff --git a/seo/seo-analysis/scripts/analyze_gsc.py b/seo/seo-analysis/scripts/analyze_gsc.pyindex 0470ba6f..64c0287f 100644--- a/seo/seo-analysis/scripts/analyze_gsc.py+++ b/seo/seo-analysis/scripts/analyze_gsc.py@@ -21,6 +21,7 @@ import urllib.errorfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import date, timedelta+from _gcloud import gcloud_runfrom _uid import portable_uid, secure_write_json@@ -56,7 +57,7 @@ def get_quota_project():def get_access_token():try:- result = subprocess.run(+ result = gcloud_run(["gcloud", "auth", "application-default", "print-access-token"],capture_output=True, text=True, timeout=15)diff --git a/seo/seo-analysis/scripts/list_gsc_sites.py b/seo/seo-analysis/scripts/list_gsc_sites.pyindex 1e16fe1f..2277c380 100644--- a/seo/seo-analysis/scripts/list_gsc_sites.py+++ b/seo/seo-analysis/scripts/list_gsc_sites.py@@ -9,6 +9,7 @@ import tempfileimport urllib.requestimport urllib.error+from _gcloud import gcloud_runfrom _uid import portable_uid, secure_write_json@@ -30,7 +31,7 @@ def get_quota_project():def get_access_token():try:- result = subprocess.run(+ result = gcloud_run(["gcloud", "auth", "application-default", "print-access-token"],capture_output=True, text=True, timeout=15)diff --git a/seo/seo-analysis/scripts/preflight.py b/seo/seo-analysis/scripts/preflight.pyindex 3bb51e8d..b6475cd2 100644--- a/seo/seo-analysis/scripts/preflight.py+++ b/seo/seo-analysis/scripts/preflight.py@@ -18,6 +18,8 @@ import subprocessimport sysimport urllib.request+from _gcloud import gcloud_run+def check_python_version():if sys.version_info < (3, 8):@@ -75,7 +77,7 @@ def check_gcloud():def check_gcloud_project():"""Ensure gcloud has an active project. Run gcloud init if not."""try:- result = subprocess.run(+ result = gcloud_run(["gcloud", "config", "get-value", "project"],capture_output=True, text=True, timeout=15,)@@ -100,7 +102,7 @@ def check_gcloud_project():print("Running 'gcloud init' to set up your project...", file=sys.stderr)print("", file=sys.stderr)- init_result = subprocess.run(["gcloud", "init"])+ init_result = gcloud_run(["gcloud", "init"])if init_result.returncode != 0:print("", file=sys.stderr)print("ERROR: gcloud init failed or was cancelled.", file=sys.stderr)@@ -108,7 +110,7 @@ def check_gcloud_project():sys.exit(1)# Verify project was set- verify = subprocess.run(+ verify = gcloud_run(["gcloud", "config", "get-value", "project"],capture_output=True, text=True, timeout=15,)@@ -124,7 +126,7 @@ def check_gcloud_project():def check_search_console_api():"""Ensure the Search Console API is enabled in the active project."""try:- result = subprocess.run(+ result = gcloud_run(["gcloud", "services", "list", "--enabled","--filter=config.name:searchconsole.googleapis.com","--format=value(config.name)"],@@ -142,7 +144,7 @@ def check_search_console_api():# API not enabled — try to enable it automaticallyprint("Search Console API is not enabled. Enabling it now...", file=sys.stderr)- enable_result = subprocess.run(+ enable_result = gcloud_run(["gcloud", "services", "enable", "searchconsole.googleapis.com"],capture_output=True, text=True, timeout=60,)@@ -196,7 +198,7 @@ def check_adc_credentials():the correct scopes."""try:- result = subprocess.run(+ result = gcloud_run(["gcloud", "auth", "application-default", "print-access-token"],capture_output=True, text=True, timeout=15,)@@ -234,7 +236,7 @@ def check_adc_credentials():print("Opening browser for Google authentication...", file=sys.stderr)print("(Log in with the Google account that has access to Search Console.)", file=sys.stderr)print("", file=sys.stderr)- auth_result = subprocess.run(+ auth_result = gcloud_run(["gcloud", "auth", "application-default", "login",f"--scopes={_GSC_SCOPES_ARG}"],)@@ -280,7 +282,7 @@ def check_quota_project():# Look up the active gcloud projecttry:- result = subprocess.run(+ result = gcloud_run(["gcloud", "config", "get-value", "project"],capture_output=True, text=True, timeout=15,)@@ -296,7 +298,7 @@ def check_quota_project():print(f"Setting ADC quota project to '{project}'...", file=sys.stderr)try:- set_result = subprocess.run(+ set_result = gcloud_run(["gcloud", "auth", "application-default", "set-quota-project", project],capture_output=True, text=True, timeout=30,)@@ -320,7 +322,7 @@ def check_pagespeed_api():"""Ensure the PageSpeed Insights API is enabled in the active project.Non-fatal — PageSpeed is optional but recommended."""try:- result = subprocess.run(+ result = gcloud_run(["gcloud", "services", "list", "--enabled","--filter=config.name:pagespeedonline.googleapis.com","--format=value(config.name)"],@@ -341,7 +343,7 @@ def check_pagespeed_api():print("PageSpeed Insights API is not enabled. Enabling it now...", file=sys.stderr)try:- enable_result = subprocess.run(+ enable_result = gcloud_run(["gcloud", "services", "enable", "pagespeedonline.googleapis.com"],capture_output=True, text=True, timeout=60,)diff --git a/seo/seo-analysis/scripts/url_inspection.py b/seo/seo-analysis/scripts/url_inspection.pyindex ee2560b1..7b418663 100644--- a/seo/seo-analysis/scripts/url_inspection.py+++ b/seo/seo-analysis/scripts/url_inspection.py@@ -33,6 +33,7 @@ import urllib.requestimport urllib.errorfrom concurrent.futures import ThreadPoolExecutor, as_completed+from _gcloud import gcloud_runfrom _uid import portable_uid, secure_write_json@@ -54,7 +55,7 @@ def get_quota_project():def get_access_token():try:- result = subprocess.run(+ result = gcloud_run(["gcloud", "auth", "application-default", "print-access-token"],capture_output=True, text=True, timeout=15)diff --git a/test/unit/test_gcloud_helper.py b/test/unit/test_gcloud_helper.pynew file mode 100644index 00000000..b3d2d9f2--- /dev/null+++ b/test/unit/test_gcloud_helper.py@@ -0,0 +1,57 @@+"""Unit tests for the portable gcloud subprocess helper."""++import importlib.util+import os+import sys+import unittest+from unittest.mock import patch+++_SCRIPTS_DIR = os.path.join(+ os.path.dirname(__file__), "..", "..", "seo", "seo-analysis", "scripts"+)+_SCRIPT_PATH = os.path.join(_SCRIPTS_DIR, "_gcloud.py")+spec = importlib.util.spec_from_file_location("_gcloud", _SCRIPT_PATH)+gcloud = importlib.util.module_from_spec(spec)+spec.loader.exec_module(gcloud)+++class TestGcloudCommand(unittest.TestCase):+ def test_non_windows_uses_resolved_binary_directly(self):+ with (+ patch.object(gcloud.sys, "platform", "darwin"),+ patch.object(gcloud.shutil, "which", return_value="/opt/bin/gcloud"),+ ):+ self.assertEqual(+ gcloud.gcloud_command(["gcloud", "config", "list"]),+ ["/opt/bin/gcloud", "config", "list"],+ )++ def test_windows_cmd_file_runs_through_cmd(self):+ path = r"C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\gcloud.cmd"+ with (+ patch.object(gcloud.sys, "platform", "win32"),+ patch.object(gcloud.shutil, "which", return_value=path),+ ):+ self.assertEqual(+ gcloud.gcloud_command(["gcloud", "auth", "application-default", "print-access-token"]),+ ["cmd", "/c", path, "auth", "application-default", "print-access-token"],+ )++ def test_missing_gcloud_preserves_existing_error_behavior(self):+ with (+ patch.object(gcloud.sys, "platform", "linux"),+ patch.object(gcloud.shutil, "which", return_value=None),+ ):+ self.assertEqual(+ gcloud.gcloud_command(["gcloud", "version"]),+ ["gcloud", "version"],+ )++ def test_rejects_non_gcloud_commands(self):+ with self.assertRaises(ValueError):+ gcloud.gcloud_command(["python", "--version"])+++if __name__ == "__main__":+ unittest.main()