Skip to content

Commit 807b3f7

Browse files
authored
feat(release): Set gitconfig before git write operations (#32277)
1 parent fa9884f commit 807b3f7

File tree

5 files changed

+51
-30
lines changed

5 files changed

+51
-30
lines changed

tasks/collector.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ def update(self):
509509

510510

511511
@task(post=[tidy])
512-
def update(ctx):
512+
def update(_):
513513
updater = CollectorVersionUpdater()
514514
updater.update()
515515
print("Update complete.")
@@ -518,12 +518,12 @@ def update(ctx):
518518
@task()
519519
def pull_request(ctx):
520520
# Save current Git configuration
521-
original_config = {'user.name': get_git_config('user.name'), 'user.email': get_git_config('user.email')}
521+
original_config = {'user.name': get_git_config(ctx, 'user.name'), 'user.email': get_git_config(ctx, 'user.email')}
522522

523523
try:
524524
# Set new Git configuration
525-
set_git_config('user.name', 'github-actions[bot]')
526-
set_git_config('user.email', 'github-actions[bot]@users.noreply.github.com')
525+
set_git_config(ctx, 'user.name', 'github-actions[bot]')
526+
set_git_config(ctx, 'user.email', 'github-actions[bot]@users.noreply.github.com')
527527

528528
# Perform Git operations
529529
ctx.run('git add .')
@@ -554,4 +554,4 @@ def pull_request(ctx):
554554
print("No changes detected, skipping PR creation.")
555555
finally:
556556
# Revert to original Git configuration
557-
revert_git_config(original_config)
557+
revert_git_config(ctx, original_config)

tasks/libs/common/git.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from __future__ import annotations
22

33
import os
4-
import subprocess
54
import sys
65
import tempfile
76
from contextlib import contextmanager
@@ -304,18 +303,21 @@ def get_last_release_tag(ctx, repo, pattern):
304303
return last_tag_commit, last_tag_name
305304

306305

307-
def get_git_config(key):
308-
result = subprocess.run(['git', 'config', '--get', key], capture_output=True, text=True)
309-
return result.stdout.strip() if result.returncode == 0 else None
306+
def get_git_config(ctx, key):
307+
try:
308+
result = ctx.run(f'git config --get {key}')
309+
except Exit:
310+
return None
311+
return result.stdout.strip() if result.return_code == 0 else None
310312

311313

312-
def set_git_config(key, value):
313-
subprocess.run(['git', 'config', key, value])
314+
def set_git_config(ctx, key, value):
315+
ctx.run(f'git config {key} {value}')
314316

315317

316-
def revert_git_config(original_config):
318+
def revert_git_config(ctx, original_config):
317319
for key, value in original_config.items():
318320
if value is None:
319-
subprocess.run(['git', 'config', '--unset', key])
321+
ctx.run(f'git config --unset {key}', hide=True)
320322
else:
321-
subprocess.run(['git', 'config', key, value])
323+
ctx.run(f'git config {key} {value}', hide=True)

tasks/libs/common/utils.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
from tasks.libs.common.color import Color, color_message
2525
from tasks.libs.common.constants import ALLOWED_REPO_ALL_BRANCHES, REPO_PATH
26-
from tasks.libs.common.git import get_commit_sha, get_default_branch
26+
from tasks.libs.common.git import get_commit_sha, get_default_branch, set_git_config
2727
from tasks.libs.releasing.version import get_version
2828
from tasks.libs.types.arch import Arch
2929

@@ -501,6 +501,15 @@ def is_pr_context(branch, pr_id, test_name):
501501
return True
502502

503503

504+
def set_gitconfig_in_ci(ctx):
505+
"""
506+
Set username and email when runing git "write" commands in CI
507+
"""
508+
if running_in_ci():
509+
set_git_config(ctx, 'user.name', 'github-actions[bot]')
510+
set_git_config(ctx, 'user.email', 'github-actions[bot]@users.noreply.github.com')
511+
512+
504513
@contextmanager
505514
def gitlab_section(section_name, collapsed=False, echo=False):
506515
"""

tasks/release.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@
3636
get_last_commit,
3737
get_last_release_tag,
3838
is_agent6,
39-
set_git_config,
4039
try_git_command,
4140
)
4241
from tasks.libs.common.gomodules import get_default_modules
4342
from tasks.libs.common.user_interactions import yes_no_question
43+
from tasks.libs.common.utils import running_in_github_actions, set_gitconfig_in_ci
4444
from tasks.libs.common.worktree import agent_context
4545
from tasks.libs.pipeline.notifications import (
4646
DEFAULT_JIRA_PROJECT,
@@ -206,6 +206,7 @@ def tag_modules(
206206

207207
if push:
208208
tags_list = ' '.join(tags)
209+
set_gitconfig_in_ci(ctx)
209210
for idx in range(0, len(tags), TAG_BATCH_SIZE):
210211
batch_tags = tags[idx : idx + TAG_BATCH_SIZE]
211212
ctx.run(f"git push origin {' '.join(batch_tags)}{force_option}")
@@ -250,6 +251,7 @@ def tag_version(
250251
with agent_context(ctx, release_branch, skip_checkout=release_branch is None):
251252
tags = __tag_single_module(ctx, get_default_modules()["."], agent_version, commit, force_option, devel)
252253

254+
set_gitconfig_in_ci(ctx)
253255
# create or update the qualification tag using the force option (points tag to next RC)
254256
if is_agent6(ctx) and (start_qual or is_qualification(ctx, "6.53.x")):
255257
if FINAL_VERSION_RE.match(agent_version):
@@ -323,6 +325,7 @@ def finish(ctx, release_branch, upstream="origin"):
323325

324326
commit_message = f"'Final updates for release.json and Go modules for {new_version} release'"
325327

328+
set_gitconfig_in_ci(ctx)
326329
ok = try_git_command(ctx, f"git commit -m {commit_message}")
327330
if not ok:
328331
raise Exit(
@@ -394,12 +397,6 @@ def create_rc(ctx, release_branch, patch_version=False, upstream="origin", slack
394397

395398
with agent_context(ctx, release_branch):
396399
github = GithubAPI(repository=GITHUB_REPO_NAME)
397-
github_action = os.environ.get("GITHUB_ACTIONS")
398-
399-
if github_action:
400-
set_git_config('user.name', 'github-actions[bot]')
401-
set_git_config('user.email', 'github-actions[bot]@users.noreply.github.com')
402-
upstream = f"https://x-access-token:{os.environ.get('GITHUB_TOKEN')}@github.com/{GITHUB_REPO_NAME}.git"
403400

404401
# Get the version of the highest major: useful for some logging & to get
405402
# the version to use for Go submodules updates
@@ -454,10 +451,10 @@ def create_rc(ctx, release_branch, patch_version=False, upstream="origin", slack
454451
ctx.run("git add release.json")
455452
ctx.run("git ls-files . | grep 'go.mod$' | xargs git add")
456453

454+
set_gitconfig_in_ci(ctx)
457455
ok = try_git_command(
458456
ctx,
459457
f"git commit --no-verify -m 'Update release.json and Go modules for {new_highest_version}'",
460-
github_action,
461458
)
462459
if not ok:
463460
raise Exit(
@@ -673,6 +670,7 @@ def _main():
673670
# Step 2 - Push newly created release branch to the remote repository
674671

675672
print(color_message("Pushing new branch to the upstream repository", "bold"))
673+
set_gitconfig_in_ci(ctx)
676674
res = ctx.run(f"git push --set-upstream {upstream} {release_branch}", warn=True)
677675
if res.exited is None or res.exited > 0:
678676
raise Exit(
@@ -863,6 +861,7 @@ def cleanup(ctx, release_branch):
863861
ctx.run("git add release.json")
864862

865863
commit_message = f"Update last_stable to {version}"
864+
set_gitconfig_in_ci(ctx)
866865
ok = try_git_command(ctx, f"git commit -m '{commit_message}'")
867866
if not ok:
868867
raise Exit(
@@ -1175,6 +1174,7 @@ def check_for_changes(ctx, release_branch, warning_mode=False):
11751174
with clone(ctx, repo_name, repo['branch'], options="--filter=blob:none --no-checkout"):
11761175
# We can add the new commit now to be used by release candidate creation
11771176
print(f"Creating new tag {next_version} on {repo_name}", file=sys.stderr)
1177+
set_gitconfig_in_ci(ctx)
11781178
ctx.run(f"git tag {next_version}")
11791179
ctx.run(f"git push origin tag {next_version}")
11801180
# This repo has changes, the next check is not needed
@@ -1350,13 +1350,10 @@ def bump_integrations_core(ctx, slack_webhook=None):
13501350
Create a PR to bump the integrations core fields in the release.json file
13511351
"""
13521352
github_workflow_url = ""
1353-
if os.environ.get("GITHUB_ACTIONS"):
1354-
set_git_config('user.name', 'github-actions[bot]')
1355-
set_git_config('user.email', 'github-actions[bot]@users.noreply.github.com')
1356-
github_server_url = os.environ.get("GITHUB_SERVER_URL")
1357-
github_run_id = os.environ.get("GITHUB_RUN_ID")
1358-
github_workflow_url = f"{github_server_url}/{GITHUB_REPO_NAME}/actions/runs/{github_run_id}"
1359-
1353+
if running_in_github_actions():
1354+
github_workflow_url = (
1355+
f"{os.environ.get('GITHUB_SERVER_URL')}/{GITHUB_REPO_NAME}/actions/runs/{os.environ.get('GITHUB_RUN_ID')}"
1356+
)
13601357
commit_hash = get_git_references(ctx, "integrations-core", "HEAD").split()[0]
13611358

13621359
rj = load_release_json()
@@ -1372,6 +1369,7 @@ def bump_integrations_core(ctx, slack_webhook=None):
13721369
ctx.run("git add release.json")
13731370

13741371
commit_message = "bump integrations core to HEAD"
1372+
set_gitconfig_in_ci(ctx)
13751373
ok = try_git_command(ctx, f"git commit -m '{commit_message}'")
13761374
if not ok:
13771375
raise Exit(

tasks/unit_tests/release_tests.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import os
34
import re
45
import sys
56
import unittest
@@ -786,6 +787,7 @@ def test_no_changes(self, version_mock, print_mock, _):
786787
}
787788
),
788789
)
790+
@patch.dict(os.environ, {'GITLAB_CI': 'true'})
789791
@patch('os.chdir', new=MagicMock())
790792
def test_changes_new_commit_first_repo(self, version_mock, print_mock, _):
791793
with mock_git_clone():
@@ -796,6 +798,8 @@ def test_changes_new_commit_first_repo(self, version_mock, print_mock, _):
796798
c = MockContext(
797799
run={
798800
'git rev-parse --abbrev-ref HEAD': Result("main"),
801+
'git config user.name github-actions[bot]': Result(""),
802+
'git config user.email github-actions[bot]@users.noreply.github.com': Result(""),
799803
'git ls-remote -h https://github.com/DataDog/omnibus-software "refs/heads/main"': Result(
800804
"4n0th3rc0mm1t9 refs/heads/main"
801805
),
@@ -867,6 +871,7 @@ def test_changes_new_commit_first_repo(self, version_mock, print_mock, _):
867871
),
868872
)
869873
@patch('os.chdir', new=MagicMock())
874+
@patch.dict(os.environ, {'GITLAB_CI': 'false'})
870875
def test_changes_new_commit_all_repo(self, version_mock, print_mock, _):
871876
with mock_git_clone():
872877
next = MagicMock()
@@ -1018,6 +1023,7 @@ def test_changes_new_release_one_repo(self, version_mock, print_mock, _):
10181023
}
10191024
),
10201025
)
1026+
@patch.dict(os.environ, {'GITLAB_CI': 'true'})
10211027
@patch('os.chdir', new=MagicMock())
10221028
def test_changes_new_commit_second_repo_branch_out(self, version_mock, print_mock, _):
10231029
with mock_git_clone():
@@ -1028,6 +1034,8 @@ def test_changes_new_commit_second_repo_branch_out(self, version_mock, print_moc
10281034
c = MockContext(
10291035
run={
10301036
'git rev-parse --abbrev-ref HEAD': Result("main"),
1037+
'git config user.name github-actions[bot]': Result(""),
1038+
'git config user.email github-actions[bot]@users.noreply.github.com': Result(""),
10311039
'git ls-remote -h https://github.com/DataDog/omnibus-software "refs/heads/7.55.x"': Result(
10321040
"4n0th3rc0mm1t0 refs/heads/main"
10331041
),
@@ -1264,6 +1272,7 @@ def test_update_module_optional_in_agent_7(self):
12641272
class TestTagModules(unittest.TestCase):
12651273
@patch('tasks.release.__tag_single_module', new=MagicMock(side_effect=[[str(i)] for i in range(2)]))
12661274
@patch('tasks.release.agent_context', new=MagicMock())
1275+
@patch.dict(os.environ, {'GITLAB_CI': 'false'})
12671276
def test_2_tags(self):
12681277
c = MockContext(run=Result("yolo"))
12691278
with patch('tasks.release.get_default_modules') as mock_modules:
@@ -1276,6 +1285,7 @@ def test_2_tags(self):
12761285

12771286
@patch('tasks.release.__tag_single_module', new=MagicMock(side_effect=[[str(i)] for i in range(3)]))
12781287
@patch('tasks.release.agent_context', new=MagicMock())
1288+
@patch.dict(os.environ, {'GITLAB_CI': 'false'})
12791289
def test_3_tags(self):
12801290
c = MockContext(run=Result("yolo"))
12811291
with patch('tasks.release.get_default_modules') as mock_modules:
@@ -1288,6 +1298,7 @@ def test_3_tags(self):
12881298

12891299
@patch('tasks.release.__tag_single_module', new=MagicMock(side_effect=[[str(i)] for i in range(4)]))
12901300
@patch('tasks.release.agent_context', new=MagicMock())
1301+
@patch.dict(os.environ, {'GITLAB_CI': 'false'})
12911302
def test_4_tags(self):
12921303
c = MockContext(run=Result("yolo"))
12931304
with patch('tasks.release.get_default_modules') as mock_modules:
@@ -1304,6 +1315,7 @@ def test_4_tags(self):
13041315

13051316
@patch('tasks.release.__tag_single_module', new=MagicMock(side_effect=[[str(i)] for i in range(100)]))
13061317
@patch('tasks.release.agent_context', new=MagicMock())
1318+
@patch.dict(os.environ, {'GITLAB_CI': 'false'})
13071319
def test_100_tags(self):
13081320
c = MockContext(run=Result("yolo"))
13091321
with patch('tasks.release.get_default_modules') as mock_modules:

0 commit comments

Comments
 (0)