diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py b/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py index 2ac2813602b..c968a058701 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/commands/deploy_commands.py @@ -7,6 +7,7 @@ from azure.cli.core.azclierror import ClientRequestError, RequiredArgumentMissingError from knack.log import get_logger from ..utils._flexible_server_util import ( + resolve_executable, run_cmd, run_subprocess, fill_action_template, @@ -29,7 +30,8 @@ def github_actions_setup(cmd, client, resource_group_name, server_name, database raise RequiredArgumentMissingError("Provide remote branch name to allow pushing the action file to your remote branch.") if action_name is None: action_name = server.name + '_' + database_name + "_deploy" - gitcli_check_and_login() + gh_path = gitcli_check_and_login() + git_path = resolve_executable("git") database_engine = 'postgresql' @@ -41,35 +43,39 @@ def github_actions_setup(cmd, client, resource_group_name, server_name, database administrator_login_password=administrator_login_password, file_name=sql_file_path, repository=repository, - action_name=action_name) + action_name=action_name, + gh_path=gh_path, + git_path=git_path) - action_path = get_git_root_dir() + GITHUB_ACTION_PATH + action_name + '.yml' + action_path = get_git_root_dir(git_path) + GITHUB_ACTION_PATH + action_name + '.yml' logger.warning("Making git commit for file %s", action_path) - run_subprocess(["git", "add", action_path]) - run_subprocess(["git", "commit", "-m", "Add github action file"]) + run_subprocess([git_path, "add", action_path]) + run_subprocess([git_path, "commit", "-m", "Add github action file"]) if allow_push: logger.warning("Pushing the created action file to origin %s branch", branch) - run_subprocess(["git", "push", "origin", branch]) + run_subprocess([git_path, "push", "origin", branch]) else: logger.warning('You did not set --allow-push parameter. Please push the prepared file %s to your remote repo and run "deploy run" command to activate the workflow.', action_path) def github_actions_run(action_name, branch): - gitcli_check_and_login() + gh_path = gitcli_check_and_login() logger.warning("Created an event for %s.yml in branch %s", action_name, branch) - run_subprocess(["gh", "workflow", "run", action_name + ".yml", "--ref", branch]) + run_subprocess([gh_path, "workflow", "run", action_name + ".yml", "--ref", branch]) def gitcli_check_and_login(): try: - output = run_cmd(["gh"], capture_output=True) + gh_path = resolve_executable("gh") + output = run_cmd([gh_path], capture_output=True) except FileNotFoundError as ex: raise ClientRequestError('Please install "Github CLI" to run this command.') from ex if output.returncode: raise ClientRequestError('Please install "Github CLI" to run this command.') - output = run_cmd(["gh", "auth", "status"], capture_output=True) + output = run_cmd([gh_path, "auth", "status"], capture_output=True) if output.returncode: - run_subprocess(["gh", "auth", "login"], stdout_show=True) + run_subprocess([gh_path, "auth", "login"], stdout_show=True) + return gh_path diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py b/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py index 009236a45ae..59d57c393c9 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/tests/latest/test_deploy_commands.py @@ -47,24 +47,25 @@ def test_subprocess_preserves_arguments_in_each_output_mode(self): expected = [executable, *original[1:]] if stdout_show: - popen.assert_called_once_with(expected) + popen.assert_called_once_with(expected, shell=False) else: - popen.assert_called_once_with(expected, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + popen.assert_called_once_with( + expected, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) process.wait.assert_called_once_with() self.assertEqual(arguments, original) - def test_unix_and_explicit_paths_keep_existing_lookup(self): - with mock.patch.object(util.sys, 'platform', 'linux'), \ + def test_unix_lookup_uses_which_for_names_and_explicit_paths(self): + executable = os.path.abspath(os.path.join('installed tools', 'gh')) + with mock.patch.object(util, 'is_windows', return_value=False), \ + mock.patch('shutil.which', return_value=executable) as which, \ mock.patch.object(util, 'get_safe_executable_path') as find: - self.assertEqual(util.resolve_executable('gh'), 'gh') - find.assert_not_called() - - with mock.patch.object(util.sys, 'platform', 'win32'), \ - mock.patch.object(util, 'get_safe_executable_path') as find: - for executable in (os.path.abspath(os.path.join('installed tools', 'gh.exe')), - os.path.join('.', 'gh.exe'), os.path.join('tools', 'gh.exe')): - with self.subTest(executable=executable): - self.assertEqual(util.resolve_executable(executable), executable) + for argument in ('gh', executable, os.path.join('.', 'gh'), os.path.join('tools', 'gh')): + with self.subTest(argument=argument): + self.assertEqual(util.resolve_executable(argument), executable) + which.assert_called_with(argument) + which.return_value = None + with self.assertRaises(FileNotFoundError): + util.resolve_executable('gh') find.assert_not_called() @@ -75,6 +76,7 @@ def setUp(self): self.addCleanup(temporary.cleanup) self.project = temporary.name self.executable = os.path.join(self.project, 'installed tools', 'gh.exe') + self.git_executable = os.path.join(self.project, 'installed tools', 'git.exe') self.workflow = self.project + util.GITHUB_ACTION_PATH + 'deploy database.yml' server = SimpleNamespace( id='/subscriptions/test-subscription/resourceGroups/test-rg/' @@ -99,7 +101,8 @@ def setUp(self): self.upload = mock.Mock(return_value=subprocess.CompletedProcess([], 0, stdout=b'', stderr=b'')) self.git = mock.Mock() patches = ( - (deploy, 'gitcli_check_and_login', mock.Mock()), + (deploy, 'gitcli_check_and_login', mock.Mock(return_value=self.executable)), + (deploy, 'resolve_executable', mock.Mock(return_value=self.git_executable)), (deploy, 'get_git_root_dir', mock.Mock(return_value=self.project)), (deploy, 'run_subprocess', self.git), (util, 'get_git_root_dir', mock.Mock(return_value=self.project)), @@ -133,9 +136,9 @@ def test_setup_uploads_missing_credentials_through_stdin(self): self.assertEqual(json.loads(self.upload.call_args.kwargs['input']), self.credentials) self.files.assert_any_call(self.workflow, 'w', encoding='utf8') self.assertEqual(self.git.call_args_list, [ - mock.call(['git', 'add', self.workflow]), - mock.call(['git', 'commit', '-m', 'Add github action file']), - mock.call(['git', 'push', 'origin', 'feature/database']), + mock.call([self.git_executable, 'add', self.workflow]), + mock.call([self.git_executable, 'commit', '-m', 'Add github action file']), + mock.call([self.git_executable, 'push', 'origin', 'feature/database']), ]) def test_setup_stops_after_credential_upload_failure(self): @@ -159,6 +162,9 @@ def test_setup_stops_after_credential_upload_failure(self): class WindowsDeploymentToolsTest(unittest.TestCase): def setUp(self): + platform = mock.patch.object(util, 'is_windows', return_value=True) + platform.start() + self.addCleanup(platform.stop) temporary = tempfile.TemporaryDirectory() self.addCleanup(temporary.cleanup) self.project = os.path.join(temporary.name, 'project with spaces') @@ -196,7 +202,7 @@ def test_workflow_run_resolves_every_launch(self): ]) popen.assert_called_once_with( [self.gh, 'workflow', 'run', 'deploy database.yml', '--ref', 'feature/database'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) def test_setup_resolves_git_and_preserves_paths(self): client = mock.Mock() @@ -217,13 +223,14 @@ def test_setup_resolves_git_and_preserves_paths(self): action_path = self.project + util.GITHUB_ACTION_PATH + 'deploy database.yml' expected = [ - mock.call([self.git, 'add', action_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE), + mock.call([self.git, 'add', action_path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False), mock.call([self.git, 'commit', '-m', 'Add github action file'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False), ] if allow_push: expected.append(mock.call([self.git, 'push', 'origin', 'feature/database'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE)) + stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)) self.assertEqual(popen.call_args_list, expected) def test_interactive_login_uses_resolved_tool(self): @@ -232,7 +239,7 @@ def test_interactive_login_uses_resolved_tool(self): mock.patch.object(util.subprocess, 'Popen', return_value=mock.MagicMock(returncode=0)) as popen: deploy.gitcli_check_and_login() - popen.assert_called_once_with([self.gh, 'auth', 'login']) + popen.assert_called_once_with([self.gh, 'auth', 'login'], shell=False) def test_git_root_and_secret_queries_use_resolved_tools(self): completed = subprocess.CompletedProcess([], 0, stdout=self.project.encode('utf8')) diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py b/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py new file mode 100644 index 00000000000..6d3ec32accd --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/postgresql/tests/unit/test_deploy_commands.py @@ -0,0 +1,215 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +import os +import json +import tempfile +import unittest +from unittest.mock import Mock, call, mock_open, patch + +from azure.cli.command_modules.postgresql.commands import deploy_commands as custom +from azure.cli.command_modules.postgresql.utils import _flexible_server_util as _util +from azure.cli.core.azclierror import ClientRequestError +from azure.cli.core.util import is_windows + + +class PostgresqlDeployTest(unittest.TestCase): + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.cwd = os.path.join(temporary.name, 'work') + self.tools = os.path.join(temporary.name, 'tools with spaces') + os.mkdir(self.cwd) + os.mkdir(self.tools) + self.gh = os.path.join(self.tools, 'gh.exe' if is_windows() else 'gh') + self.git = os.path.join(self.tools, 'git.exe' if is_windows() else 'git') + self.files = {os.path.normcase(p) for p in (self.gh, self.git)} + self.server = Mock(name='server') + self.server.name = 'server' + self.server.id = '/subscriptions/sub/resourceGroups/rg/providers/Microsoft.DBforPostgreSQL/flexibleServers/server' + self.server.fully_qualified_domain_name = 'server.example' + self.server.network.public_network_access = 'Enabled' + self.run = Mock(side_effect=self.run_result) + self.process = Mock(returncode=0) + self.process.stderr.read.return_value = b'failed' + self.popen = Mock(return_value=self.process) + for patcher in ( + patch.dict('os.environ', {'PATH': self.tools, 'PATHEXT': '.EXE'}), + patch('os.getcwd', return_value=self.cwd), + patch('os.path.isfile', side_effect=lambda p: os.path.normcase(p) in self.files), + patch('os.access', return_value=True), + patch('subprocess.run', self.run), + patch('subprocess.Popen', self.popen), + patch('builtins.open', mock_open()), + patch.object(_util.os.path, 'exists', side_effect=lambda p: os.path.normcase(p) in self.files), + patch.object(_util.os, 'makedirs'), + patch.object(_util.os, 'remove'), + patch.object(_util.yaml, 'safe_load', return_value={ + 'jobs': {'build': {'steps': [{}, {}, {'with': {}}]}}}), + patch.object(_util, 'get_subscription_id', return_value='sub'), + patch.object(_util, 'create_service_principal_for_rbac', return_value={ + 'appId': 'app', 'password': 'unused', 'tenant': 'tenant', 'displayName': 'app', 'name': 'app'})): + patcher.start() + self.addCleanup(patcher.stop) + + @staticmethod + def run_result(args, **kwargs): + if args[1:] == ['auth', 'status']: + return Mock(returncode=1) + if args[1:] == ['rev-parse', '--show-toplevel']: + return Mock(returncode=0, stdout=b'C:/work with spaces\n') + return Mock(returncode=0, stdout=b'') + + def setup_deploy(self): + custom.github_actions_setup( + Mock(), Mock(get=Mock(return_value=self.server)), 'rg', 'server', 'database', + 'user', 'unused', 'file with spaces.sql', 'owner/repo', action_name='deploy action', + branch='topic branch', allow_push=True) + + def test_setup_pins_all_probe_login_secret_and_git_launches(self): + self.setup_deploy() + self.assertEqual([c.args[0] for c in self.run.call_args_list], [ + [self.gh], [self.gh, 'auth', 'status'], + [self.git, 'rev-parse', '--show-toplevel'], + [self.gh, 'secret', 'list', '--repo', 'owner/repo'], + [self.gh, 'secret', 'set', 'AZURE_CREDENTIALS', '--repo', 'owner/repo'], + [self.git, 'rev-parse', '--show-toplevel']]) + credentials = self.run.call_args_list[-2].kwargs + self.assertEqual(json.loads(credentials['input']), { + 'clientId': 'app', 'clientSecret': 'unused', 'tenantId': 'tenant', 'subscriptionId': 'sub'}) + launches = [c.args[0] for c in self.popen.call_args_list] + self.assertEqual(launches[0], [self.gh, 'auth', 'login']) + self.assertEqual(launches[1][:7], [ + self.gh, 'secret', 'set', 'SERVER_DATABASE_POSTGRESQL_CONNECTION_STRING', '--repo', 'owner/repo', '-b']) + self.assertEqual(len(launches[1]), 8) + self.assertEqual(launches[2:], [ + [self.git, 'add', 'C:/work with spaces/.github/workflows/deploy action.yml'], + [self.git, 'commit', '-m', 'Add github action file'], + [self.git, 'push', 'origin', 'topic branch']]) + for invocation in self.popen.call_args_list: + self.assertIs(invocation.kwargs['shell'], False) + + def test_workflow_reuses_checked_path(self): + custom.github_actions_run('deploy action', 'topic branch') + self.assertEqual(self.popen.call_args_list[-1].args[0], + [self.gh, 'workflow', 'run', 'deploy action.yml', '--ref', 'topic branch']) + self.assertEqual([c.args[0][0] for c in self.run.call_args_list], [self.gh, self.gh]) + + def test_probe_path_is_retained_after_path_changes(self): + def probe(args, **kwargs): + os.environ['PATH'] = self.cwd + return self.run_result(args, **kwargs) + self.run.side_effect = probe + self.assertEqual(custom.gitcli_check_and_login(), self.gh) + self.assertEqual(self.popen.call_args.args[0], [self.gh, 'auth', 'login']) + + def test_missing_path_tools_never_launch(self): + for files in (set(), {os.path.normcase(os.path.join(self.cwd, os.path.basename(self.gh)))}): + with self.subTest(files=files): + self.files = files + with self.assertRaisesRegex(ClientRequestError, 'Please install'): + custom.github_actions_run('deploy', 'main') + self.run.assert_not_called() + self.popen.assert_not_called() + + def test_git_helper_requires_path_tool(self): + self.files = {os.path.normcase(os.path.join(self.cwd, os.path.basename(self.git)))} + with self.assertRaises(FileNotFoundError): + _util.get_git_root_dir() + with self.assertRaises(FileNotFoundError): + _util.run_subprocess(['git', 'add', 'file']) + self.run.assert_not_called() + self.popen.assert_not_called() + + def test_missing_gh_stops_secret_creation(self): + self.files = set() + with self.assertRaises(FileNotFoundError): + _util.register_credential_secrets(Mock(), 'postgresql', self.server, 'owner/repo') + _util.create_service_principal_for_rbac.assert_not_called() + self.popen.assert_not_called() + + def test_missing_git_stops_setup_before_secret_creation(self): + self.files = {os.path.normcase(self.gh)} + with self.assertRaises(FileNotFoundError): + self.setup_deploy() + _util.create_service_principal_for_rbac.assert_not_called() + self.assertEqual([c.args[0] for c in self.popen.call_args_list], [[self.gh, 'auth', 'login']]) + + def test_non_windows_lookup_preserves_which_semantics(self): + for executable in ('gh', './tools/gh', '/usr/local/bin/gh'): + with self.subTest(executable=executable), \ + patch.object(_util, 'is_windows', return_value=False), \ + patch('shutil.which', return_value=self.gh) as which: + self.assertEqual(_util.resolve_executable(executable), self.gh) + which.assert_called_once_with(executable) + with patch.object(_util, 'is_windows', return_value=False), \ + patch('shutil.which', return_value=None), self.assertRaises(FileNotFoundError): + _util.resolve_executable('gh') + + def test_probe_nonzero_preserves_install_message(self): + self.run.side_effect = None + self.run.return_value = Mock(returncode=1) + with self.assertRaisesRegex(ClientRequestError, 'Please install'): + custom.gitcli_check_and_login() + self.assertEqual(self.run.call_count, 1) + self.popen.assert_not_called() + + def test_authenticated_does_not_login(self): + self.run.side_effect = None + self.run.return_value = Mock(returncode=0) + self.assertEqual(custom.gitcli_check_and_login(), self.gh) + self.popen.assert_not_called() + + def test_subprocess_preserves_argv_and_nonzero_behavior(self): + self.process.returncode = 1 + arguments = ['gh', 'workflow', 'run', 'name with spaces.yml'] + with patch.object(_util.logger, 'warning') as warning: + _util.run_subprocess(arguments) + warning.assert_called_once_with('failed') + self.assertEqual(arguments[0], 'gh') + self.assertEqual(self.popen.call_args.args[0], [self.gh] + arguments[1:]) + self.process.returncode = 0 + self.process.stderr = None + _util.run_subprocess([self.gh, 'auth', 'login'], stdout_show=True) + self.assertEqual(self.popen.call_args, call([self.gh, 'auth', 'login'], shell=False)) + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_path_entries(self): + self.files.add(os.path.normcase(os.path.join(self.cwd, 'gh.exe'))) + for directory in ('', '.', 'tools', r'C:tools', r'\tools', self.cwd): + with self.subTest(directory=directory), patch.dict( + 'os.environ', {'PATH': directory + os.pathsep + '"' + self.tools + '"'}): + self.assertEqual(_util.resolve_executable('gh'), self.gh) + with patch.dict('os.environ', {'PATH': self.cwd}), self.assertRaises(FileNotFoundError): + _util.resolve_executable('gh') + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_requires_native_executable(self): + self.files = {os.path.normcase(os.path.join(self.tools, 'gh.cmd'))} + with patch.dict('os.environ', {'PATHEXT': '.CMD;.EXE'}): + for executable in ('gh', 'gh.cmd', os.path.join(self.tools, 'gh.cmd')): + with self.subTest(executable=executable), self.assertRaises(FileNotFoundError): + _util.resolve_executable(executable) + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_native_lookup_does_not_depend_on_pathext(self): + for pathext in ('', '.BAT;.CMD', '.CMD;.EXE'): + with self.subTest(pathext=pathext), patch.dict('os.environ', {'PATHEXT': pathext}): + for executable, expected in (('gh', self.gh), ('gh.exe', self.gh), + ('git', self.git), ('git.exe', self.git)): + self.assertEqual(_util.resolve_executable(executable), expected) + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_relative_explicit_paths_are_rejected(self): + for executable in (r'.\gh.exe', r'tools\gh.exe', r'C:gh.exe', r'\tools\gh.exe'): + with self.subTest(executable=executable), self.assertRaises(FileNotFoundError): + _util.resolve_executable(executable) + + @unittest.skipUnless(is_windows(), 'Windows executable lookup') + def test_windows_path_tool_link_to_working_directory_is_rejected(self): + with patch.object(os.path, 'realpath', return_value=os.path.join(self.cwd, 'gh.exe')): + with self.assertRaises(FileNotFoundError): + _util.resolve_executable('gh') diff --git a/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py b/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py index 254be783590..84699a9fa2d 100644 --- a/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py +++ b/src/azure-cli/azure/cli/command_modules/postgresql/utils/_flexible_server_util.py @@ -13,12 +13,11 @@ import subprocess import secrets import string -import sys import yaml from knack.log import get_logger from knack.prompting import prompt_y_n, NoTTYException from azure.mgmt.core.tools import parse_resource_id -from azure.cli.core.util import CLIError, get_safe_executable_path, run_cmd as core_run_cmd +from azure.cli.core.util import CLIError, get_safe_executable_path, is_windows, run_cmd as core_run_cmd from azure.cli.core.azclierror import AuthenticationError, ClientRequestError from azure.core.exceptions import HttpResponseError from azure.core.paging import ItemPaged @@ -256,14 +255,27 @@ def _resolve_api_version(client, provider_namespace, resource_type, parent_path) def resolve_executable(executable): - """Bind Windows tool launches to installed executables without changing Unix lookup.""" - if sys.platform != 'win32' or os.path.dirname(executable): - return executable - name = executable if os.path.splitext(executable)[1] else executable + '.exe' - resolved = get_safe_executable_path(name) - if resolved is None: - raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), executable) - return resolved + """Resolve deployment tools to absolute native executable paths on Windows.""" + import shutil + + if not is_windows(): + resolved = shutil.which(executable) + if resolved: + return os.path.abspath(resolved) + else: + explicit = bool(os.path.dirname(executable)) + name = executable if os.path.splitext(executable)[1] else executable + '.exe' + resolved = executable if explicit else get_safe_executable_path(name) + if resolved: + drive, tail = os.path.splitdrive(resolved) + if (drive and tail.startswith(('\\', '/')) and + os.path.splitext(resolved)[1].lower() in ('.exe', '.com') and + os.path.isfile(resolved) and os.access(resolved, os.X_OK)): + # A PATH entry may contain a link back into the working directory. + if explicit or not os.path.samefile(os.path.dirname(os.path.realpath(resolved)), os.getcwd()): + return os.path.abspath(resolved) + + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), executable) def run_cmd(args, **kwargs): @@ -273,18 +285,18 @@ def run_cmd(args, **kwargs): def run_subprocess(command, stdout_show=None): - commands = list(command) - commands[0] = resolve_executable(commands[0]) + command = [resolve_executable(command[0])] + command[1:] if stdout_show: - process = subprocess.Popen(commands) + process = subprocess.Popen(command, shell=False) else: - process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) process.wait() if process.returncode: logger.warning(process.stderr.read().strip().decode('UTF-8')) -def register_credential_secrets(cmd, database_engine, server, repository): +def register_credential_secrets(cmd, database_engine, server, repository, gh_path=None): + gh_path = resolve_executable(gh_path or "gh") logger.warning('Adding secret "AZURE_CREDENTIALS" to github repository') resource_group = parse_resource_id(server.id)["resource_group"] provider = "DBforPostgreSQL" @@ -297,7 +309,7 @@ def register_credential_secrets(cmd, database_engine, server, repository): app.pop('name') process = subprocess.run( - [resolve_executable('gh'), 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository], + [gh_path, 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository], input=json.dumps(app).encode('UTF-8'), capture_output=True, check=False) if process.returncode: raise ClientRequestError( @@ -306,19 +318,21 @@ def register_credential_secrets(cmd, database_engine, server, repository): recommendation='Check your GitHub CLI authentication and repository permissions, then retry.') -def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name): +def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name, gh_path=None): + gh_path = resolve_executable(gh_path or "gh") logger.warning("Added secret %s to github repository", connection_string_name) connection_string = "host={} port=5432 dbname={} user={} password={} sslmode=require".format(server.fully_qualified_domain_name, database_name, administrator_login, administrator_login_password) - run_subprocess(['gh', 'secret', 'set', connection_string_name, '--repo', repository, '-b', connection_string]) + run_subprocess([gh_path, 'secret', 'set', connection_string_name, '--repo', repository, '-b', connection_string]) -def fill_action_template(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, file_name, action_name, repository): +def fill_action_template(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, file_name, action_name, repository, gh_path=None, git_path=None): - action_dir = get_git_root_dir() + GITHUB_ACTION_PATH + gh_path = resolve_executable(gh_path or "gh") + action_dir = get_git_root_dir(git_path) + GITHUB_ACTION_PATH if not os.path.exists(action_dir): os.makedirs(action_dir) - process = run_cmd(["gh", "secret", "list", "--repo", repository], capture_output=True) + process = run_cmd([gh_path, "secret", "list", "--repo", repository], capture_output=True) github_secrets = process.stdout.strip().decode('UTF-8') # connection_string = AZURE_POSTGRESQL_CONNECTION_STRING @@ -327,7 +341,8 @@ def fill_action_template(cmd, database_engine, server, database_name, administra register_credential_secrets(cmd, database_engine=database_engine, server=server, - repository=repository) + repository=repository, + gh_path=gh_path) except HttpResponseError: raise AuthenticationError('You do not have authorization to create a service principal to run azure service in github actions. \n' 'Please create a service principal that has access to the database server and add "AZURE_CREDENTIALS" secret to your github repository. \n' @@ -342,7 +357,8 @@ def fill_action_template(cmd, database_engine, server, database_name, administra administrator_login=administrator_login, administrator_login_password=administrator_login_password, repository=repository, - connection_string_name=connection_string_name) + connection_string_name=connection_string_name, + gh_path=gh_path) current_location = os.path.dirname(__file__) @@ -359,8 +375,8 @@ def fill_action_template(cmd, database_engine, server, database_name, administra yml_file.write(yaml.dump(template)) -def get_git_root_dir(): - process = run_cmd(["git", "rev-parse", "--show-toplevel"], capture_output=True) +def get_git_root_dir(git_path=None): + process = run_cmd([resolve_executable(git_path or "git"), "rev-parse", "--show-toplevel"], capture_output=True) return process.stdout.strip().decode('UTF-8')