-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgit.go
More file actions
678 lines (583 loc) · 20.8 KB
/
Copy pathgit.go
File metadata and controls
678 lines (583 loc) · 20.8 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
// SPDX-License-Identifier: Apache-2.0
// Package git provides Git repository operations and abstractions for the GitOps Reverser controller.
package git
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
billyutil "github.com/go-git/go-billy/v6/util"
"github.com/go-git/go-git/v6"
"github.com/go-git/go-git/v6/config"
"github.com/go-git/go-git/v6/plumbing"
gitclient "github.com/go-git/go-git/v6/plumbing/client"
"github.com/go-git/go-git/v6/plumbing/format/index"
"github.com/go-git/go-git/v6/plumbing/transport"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/yaml"
"github.com/ConfigButler/gitops-reverser/internal/git/manifestedit"
"github.com/ConfigButler/gitops-reverser/internal/sanitize"
"github.com/ConfigButler/gitops-reverser/internal/types"
)
var (
ErrRemoteRefNotFound = errors.New("remote ref not found")
ErrRemoteRefNotFoundEmptyRepo = errors.New("remote ref not found (empty repo)")
)
// CheckRepo performs lightweight connectivity checks and gathers repository metadata.
func CheckRepo(ctx context.Context, repoURL string, auth []gitclient.Option) (*RepoInfo, error) {
logger := log.FromContext(ctx)
logger.V(1).Info("Checking repository connectivity and metadata", "url", repoURL)
// Use remote.List() for lightweight connectivity check
remote := git.NewRemote(nil, &config.RemoteConfig{
Name: "origin",
URLs: []string{repoURL},
})
refs, err := remote.List(&git.ListOptions{
ClientOptions: auth,
})
if err != nil {
// Check if this is an empty repository error
if errors.Is(err, transport.ErrEmptyRemoteRepository) {
logger.Info("Repository is empty", "url", repoURL)
return &RepoInfo{
DefaultBranch: nil, // No way to know what the default branch is until it's there
RemoteBranchCount: 0,
}, nil
}
return nil, fmt.Errorf("failed to list remote references: %w", err)
}
repoInfo := &RepoInfo{}
// Map to store branch refs for SHA lookup
refLookup := make(map[string]*plumbing.Reference)
var headRef *plumbing.Reference
// Scan refs for branches and HEAD
for _, ref := range refs {
if ref.Name() == plumbing.HEAD { // || ref.Name().String() == "refs/remotes/origin/HEAD" {
headRef = ref
}
if ref.Name().IsBranch() {
repoInfo.RemoteBranchCount++
branchName := ref.Name().Short()
refLookup[branchName] = ref
}
}
if headRef != nil {
repoInfo.DefaultBranch = resolveDefaultBranch(headRef, refLookup, logger)
} else {
logger.Info("Failed to find HEAD in List output")
}
logger.V(1).Info("Repository check completed",
"remoteBranches", repoInfo.RemoteBranchCount)
return repoInfo, nil
}
// PrepareBranch clones repository immediately when GitDestination is created, optimized for single branch usage. It tries to fetch the useful branch: either target or default.
func PrepareBranch(
ctx context.Context,
repoURL, repoPath, targetBranchName string,
auth []gitclient.Option,
) (*PullReport, error) {
logger := log.FromContext(ctx)
logger.Info("Preparing branch for operations", "url", repoURL, "path", repoPath, "branch", targetBranchName)
// Ensure the directory exists
if err := os.MkdirAll(filepath.Dir(repoPath), 0750); err != nil {
return nil, fmt.Errorf("failed to create repo dir: %w", err)
}
var repo *git.Repository
var err error
// Check if repository already exists
existingRepo := tryOpenExistingRepo(repoPath, logger)
if existingRepo != nil {
logger.Info("Reusing existing repository", "path", repoPath)
repo = existingRepo
} else {
// Clean up corrupted repository if exists
repo, err = initializeCleanRepository(repoPath, logger)
if err != nil {
return nil, err
}
}
// Both paths, not just the fresh one: a repository from a persistent volume, or one created
// before this pin existed, needs the same policy or its next commit fails under an ambient
// commit.gpgSign. See PinExplicitSigningPolicy.
if err := PinExplicitSigningPolicy(repo); err != nil {
return nil, err
}
// Ensure the remote origin is set correctly
if err := ensureRemoteOrigin(ctx, repo, repoURL); err != nil {
return nil, fmt.Errorf("failed to ensure remote origin: %w", err)
}
targetBranch := plumbing.NewBranchReferenceName(targetBranchName)
pullReport, err := syncToRemote(ctx, repo, targetBranch, auth)
if err != nil {
return nil, err
}
return pullReport, nil
}
func switchOrCreateBranch(
repo *git.Repository,
targetBranch plumbing.ReferenceName,
logger logr.Logger,
targetBranchName string,
baseHash plumbing.Hash,
) error {
w, err := repo.Worktree()
if err != nil {
return fmt.Errorf("failed to get worktree: %w", err)
}
// Strategy: "git checkout -B targetBranch"
// 1. Try to switch to it (assuming it exists locally)
err = w.Checkout(&git.CheckoutOptions{
Branch: targetBranch,
Force: true,
})
if err == nil {
// CASE A: Local branch existed.
// We successfully switched to it, BUT it might point to old history.
// We want to start fresh from 'baseHash' (the default branch tip we were just on).
// So we Hard Reset the existing branch to match baseHash.
logger.Info("Resetting existing local branch to start fresh", "branch", targetBranchName)
err = w.Reset(&git.ResetOptions{
Commit: baseHash,
Mode: git.HardReset,
})
} else if errors.Is(err, plumbing.ErrReferenceNotFound) {
// CASE B: Local branch did not exist.
// Create it pointing to baseHash.
logger.Info("Creating new local branch", "branch", targetBranchName)
err = w.Checkout(&git.CheckoutOptions{
Hash: baseHash,
Branch: targetBranch,
Create: true,
Force: true,
})
}
if err != nil {
return fmt.Errorf("failed to prepare branch %s: %w", targetBranchName, err)
}
return nil
}
// ensureRemoteOrigin ensures the remote "origin" exists with the correct URL, updating if necessary.
func ensureRemoteOrigin(ctx context.Context, repo *git.Repository, repoURL string) error {
logger := log.FromContext(ctx)
remote, err := repo.Remote("origin")
if err != nil {
// Remote doesn't exist, create it
logger.Info("Creating remote origin", "url", repoURL)
_, err = repo.CreateRemote(&config.RemoteConfig{
Name: "origin",
URLs: []string{repoURL},
})
return err
}
// Remote exists, check if URL matches
cfg := remote.Config()
if len(cfg.URLs) > 0 && cfg.URLs[0] == repoURL {
logger.Info("Remote origin URL is correct")
return nil
}
// URL is different, delete and recreate
logger.Info("Updating remote origin URL", "old", cfg.URLs, "new", repoURL)
err = repo.DeleteRemote("origin")
if err != nil {
return fmt.Errorf("failed to delete remote: %w", err)
}
_, err = repo.CreateRemote(&config.RemoteConfig{
Name: "origin",
URLs: []string{repoURL},
})
return err
}
// GetCurrentBranch gets the branch that is active.
func GetCurrentBranch(r *git.Repository) (plumbing.ReferenceName, plumbing.Hash, error) {
symbolicRef, err := r.Reference(plumbing.HEAD, false)
if err != nil {
return "", plumbing.ZeroHash, err
}
if symbolicRef.Type() != plumbing.SymbolicReference {
return "", plumbing.ZeroHash, errors.New("HEAD is not symbolic")
}
// Try if a commit exists for the reference
commitRef, err := r.Reference(symbolicRef.Target(), false)
if err != nil {
// If the branch reference doesn't exist, this is an unborn branch (no commits yet)
// This is expected when HEAD points to a branch with no commits
if errors.Is(err, plumbing.ErrReferenceNotFound) {
return symbolicRef.Target(), plumbing.ZeroHash, nil
}
return "", plumbing.ZeroHash, fmt.Errorf("unexpected error getting branch reference: %w", err)
}
if commitRef.Type() != plumbing.HashReference {
return "", plumbing.ZeroHash, errors.New("HEAD does not point at hash reference")
}
return symbolicRef.Target(), commitRef.Hash(), nil
}
// sanitizePath validates and normalizes a path value to a safe POSIX-like relative path.
// Returns empty string when the input is unsafe or empty.
func sanitizePath(base string) string {
trimmed := strings.TrimSpace(base)
if trimmed == "" {
return ""
}
// Reject absolute paths and backslashes (Windows separators)
if strings.HasPrefix(trimmed, "/") || strings.ContainsAny(trimmed, "\\") {
return ""
}
// Reject path traversal
if strings.Contains(trimmed, "..") {
return ""
}
// Normalize and strip leading/trailing slashes
cleaned := path.Clean(trimmed)
cleaned = strings.Trim(cleaned, "/")
if cleaned == "" || cleaned == "." {
return ""
}
return cleaned
}
// IsValidTargetPath reports whether p is a path the writer can safely materialize
// into: the repository root (empty or "."), or a clean relative path. Paths the
// writer rejects as unsafe — absolute (leading "/"), Windows separators, or ".."
// traversal — are invalid and can own nothing. It mirrors sanitizePath, the
// write-path guard, so the overlap/admission check and the writer agree on what a
// target legitimately owns.
func IsValidTargetPath(p string) bool {
trimmed := strings.TrimSpace(p)
if trimmed == "" || trimmed == "." {
return true // repository root
}
return sanitizePath(trimmed) != ""
}
// tryOpenExistingRepo attempts to open and validate an existing repository.
func tryOpenExistingRepo(path string, logger logr.Logger) *git.Repository {
// Check if .git directory exists
gitDir := filepath.Join(path, ".git")
if _, err := os.Stat(gitDir); os.IsNotExist(err) {
return nil
}
// Try to open the repository
repo, err := git.PlainOpen(path)
if err != nil {
logger.Info(
"Failed to open existing repository, will clone fresh",
"path",
path,
"error",
err,
)
return nil
}
headRef, err := repo.Storer.Reference(plumbing.HEAD)
if err != nil {
logger.Info("Existing repository is invalid, will clone fresh", "path", path, "error", err)
return nil
}
if headRef.Type() == plumbing.SymbolicReference {
if _, refErr := repo.Reference(headRef.Target(), false); refErr == nil ||
errors.Is(refErr, plumbing.ErrReferenceNotFound) {
return repo
}
logger.Info(
"Existing repository has invalid HEAD target, will clone fresh",
"path",
path,
"target",
headRef.Target(),
)
return nil
}
return repo
}
func createPullReport(targetBranch string, before, after plumbing.Hash, remoteExists, unborn bool) *PullReport {
return &PullReport{
ExistsOnRemote: remoteExists,
IncomingChanges: before != after,
HEAD: BranchInfo{
ShortName: targetBranch,
Sha: printSha(after),
Unborn: unborn,
},
}
}
// printSha makes sure than an empty hash returns "" instead of a lot of zeros.
func printSha(after plumbing.Hash) string {
printedSha := ""
if !plumbing.Hash.IsZero(after) {
printedSha = after.String()
}
return printedSha
}
// syncToRemote does everything it can to bring the repo in a state where you can push events (checking different remotes, creating feature branches or even create a root/orphaned branch). It depends on the HEAD of the repo, it must be configure to your working branch.
func syncToRemote(
ctx context.Context,
repo *git.Repository,
branch plumbing.ReferenceName,
auth []gitclient.Option,
) (*PullReport, error) {
_, currentHash, err := GetCurrentBranch(repo)
if err != nil {
return nil, fmt.Errorf("unexpected fail to read HEAD: %w", err)
}
availableBranch, err := SmartFetch(ctx, repo, branch, auth)
if err != nil {
return nil, fmt.Errorf("failed to fetch: %w", err)
}
if availableBranch != "" {
newHash, err := checkoutAndReset(ctx, repo, availableBranch)
if err != nil {
return nil, fmt.Errorf("failed to checkoutAndReset: %w", err)
}
remoteExists := availableBranch.Short() == branch.Short()
return createPullReport(branch.Short(), currentHash, newHash, remoteExists, false), nil
}
// Failed to fetch from both sources, so let's configure head to be unborn at targetbranch.
err = makeHeadUnborn(ctx, repo, branch)
if err != nil {
return nil, fmt.Errorf("failed to create root branch: %w", err)
}
return createPullReport(branch.Short(), currentHash, plumbing.ZeroHash, false, true), nil
}
// makeHeadUnborn is called when there are no remote branches to base upon, all is cleared and new commits are created as orphaned branch.
func makeHeadUnborn(ctx context.Context, r *git.Repository, branch plumbing.ReferenceName) error {
logger := log.FromContext(ctx)
logger.Info("Only a computer can do this: undoing birth")
err := setHead(r, branch.Short())
if err != nil {
return fmt.Errorf("failed set HEAD: %w", err)
}
err = r.Storer.RemoveReference(branch)
if err != nil && !errors.Is(err, plumbing.ErrReferenceNotFound) {
return fmt.Errorf("failed to remove branch reference: %w", err)
}
if !errors.Is(err, plumbing.ErrReferenceNotFound) {
logger.Info("makeHeadUnborn removed branch reference")
}
logger.Info("cleaning index and worktree")
if err := clearIndex(r); err != nil {
return err
}
if err := cleanWorktree(r); err != nil {
return err
}
return nil
}
// clearIndex empties the staging area.
func clearIndex(r *git.Repository) error {
// Get the index
idx, err := r.Storer.Index()
if err != nil {
return fmt.Errorf("failed to get index: %w", err)
}
// Clear its entries
idx.Entries = []*index.Entry{}
// Write the empty index back
if err := r.Storer.SetIndex(idx); err != nil {
return fmt.Errorf("failed to save empty index: %w", err)
}
return nil
}
// cleanWorktree removes all files from the working directory.
func cleanWorktree(r *git.Repository) error {
w, err := r.Worktree()
if err != nil {
return fmt.Errorf("failed to get worktree: %w", err)
}
entries, err := w.Filesystem().ReadDir(".")
if err != nil {
return fmt.Errorf("failed to read worktree root: %w", err)
}
for _, entry := range entries {
name := entry.Name()
if name == ".git" {
continue
}
if err := billyutil.RemoveAll(w.Filesystem(), name); err != nil {
return fmt.Errorf("failed to remove %q from worktree: %w", name, err)
}
}
return nil
}
func checkoutAndReset(ctx context.Context, repo *git.Repository, branch plumbing.ReferenceName) (plumbing.Hash, error) {
logger := log.FromContext(ctx)
// Resolve the hash that we want to checkout
branchRemote := plumbing.NewRemoteReferenceName("origin", branch.Short())
branchRemoteRef, err := repo.Reference(branchRemote, true)
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("failed to get branch reference: %w", err)
}
logger.Info("Switching worktree to match remote", "branch", branchRemote)
w, err := repo.Worktree()
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("failed to get worktree: %w", err)
}
// --- Step A: Ensure HEAD points to the correct Branch Name ---
// We try to Checkout. If the branch exists, this switches HEAD to it.
// If we are already on it, it's a no-op for HEAD, but Force cleans dirty files.
err = w.Checkout(&git.CheckoutOptions{
Branch: branch,
Force: true,
})
if err != nil && !errors.Is(err, plumbing.ErrReferenceNotFound) {
return plumbing.ZeroHash, fmt.Errorf("checkout failed for %s: %w", branchRemote, err)
}
// Handle case: Local branch does not exist yet
if errors.Is(err, plumbing.ErrReferenceNotFound) {
// Create the branch and point it immediately to the target Hash
logger.Info("Branch does not exist locally, creating it", "branch", branch, "hash", branchRemoteRef.Hash())
err = w.Checkout(&git.CheckoutOptions{
Hash: branchRemoteRef.Hash(), // Initialize at the correct commit
Branch: branch, // Name it correctly
Create: true, // Create it
Force: true, // Force clean files
})
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("create branch failed: %w", err)
}
} else {
logger.Info("Reset hard to match remote", "branch", branch, "hash", branchRemoteRef.Hash())
err = w.Reset(&git.ResetOptions{
Commit: branchRemoteRef.Hash(),
Mode: git.HardReset,
})
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("reset failed: %w", err)
}
}
return branchRemoteRef.Hash(), nil
}
// resolveDefaultBranch uses the List output to find out all the required info of the default branch.
func resolveDefaultBranch(
head *plumbing.Reference,
refLookup map[string]*plumbing.Reference,
logger logr.Logger,
) *BranchInfo {
branchName := head.Target().Short()
if branchRef, exists := refLookup[branchName]; exists {
return &BranchInfo{
ShortName: branchName,
Sha: branchRef.Hash().String(),
Unborn: false,
}
}
logger.Info("HEAD points to branch not in refs, marking as unborn", "branch", branchName)
return &BranchInfo{
ShortName: branchName,
Sha: "",
Unborn: true,
}
}
// setHead adjusts the HEAD, is used to create unborn branches. Note that the worktree is not adjusted!
func setHead(r *git.Repository, branchName string) error {
newHeadRef := plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName(branchName))
return r.Storer.SetReference(newHeadRef)
}
// manifestIdentity reads the content identity (GVK + namespace + name) from a live
// object, matching how manifestedit derives identity from YAML. ok is false when
// there is no object or it lacks the fields needed to identify it.
func manifestIdentity(obj *unstructured.Unstructured) (manifestedit.Identity, bool) {
if obj == nil {
return manifestedit.Identity{}, false
}
id := manifestedit.Identity{
APIVersion: obj.GetAPIVersion(),
Kind: obj.GetKind(),
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
}
if id.APIVersion == "" || id.Kind == "" || id.Name == "" {
return manifestedit.Identity{}, false
}
return id, true
}
// removeFileFromWorktree deletes a file from disk and stages the removal in git.
func removeFileFromWorktree(
logger logr.Logger,
filePath, fullPath string,
worktree *git.Worktree,
) (bool, error) {
if err := os.Remove(fullPath); err != nil {
return false, fmt.Errorf("failed to delete file %s: %w", filePath, err)
}
if _, err := worktree.Remove(filePath); err != nil {
return false, fmt.Errorf("failed to remove file %s from git: %w", filePath, err)
}
logger.Info("Deleted file from repository", "file", filePath)
return true, nil
}
func manifestsAreSemanticallyEqual(existingContent, desiredContent []byte) bool {
existingCanonical, err := canonicalizeManifestForComparison(existingContent)
if err != nil {
return false
}
desiredCanonical, err := canonicalizeManifestForComparison(desiredContent)
if err != nil {
return false
}
return bytes.Equal(existingCanonical, desiredCanonical)
}
func canonicalizeManifestForComparison(content []byte) ([]byte, error) {
var raw map[string]interface{}
if err := yaml.Unmarshal(content, &raw); err != nil {
return nil, fmt.Errorf("unmarshal manifest: %w", err)
}
obj := &unstructured.Unstructured{Object: raw}
return sanitize.MarshalToOrderedYAML(sanitize.Sanitize(obj))
}
func generateFilePath(id types.ResourceIdentifier, sensitiveResources types.SensitiveResourcePolicy) string {
defaultPath := id.ToGitPath()
if !sensitiveResources.IsSensitive(id.Group, id.Resource) {
return defaultPath
}
if strings.HasSuffix(defaultPath, ".yaml") {
return strings.TrimSuffix(defaultPath, ".yaml") + ".sops.yaml"
}
return defaultPath + ".sops.yaml"
}
// initializeCleanRepository removes corrupted repos and initializes a fresh one.
func initializeCleanRepository(repoPath string, logger logr.Logger) (*git.Repository, error) {
// If directory exists but repo is invalid, remove it
gitDir := filepath.Join(repoPath, ".git")
if _, err := os.Stat(gitDir); err == nil {
logger.Info("Removing corrupted repository", "path", repoPath)
if err := os.RemoveAll(repoPath); err != nil {
logger.Info("Warning: failed to remove existing directory", "path", repoPath, "error", err)
}
}
// Initialize the repository
repo, err := git.PlainInit(repoPath, false)
if err != nil {
return nil, fmt.Errorf("failed to initialize repository: %w", err)
}
return repo, nil
}
// PinExplicitSigningPolicy records in the repository's own config that commits are not signed
// unless this operator signs them.
//
// go-git v6 consults commit.gpgSign — merged across system, global and local scope — whenever
// CommitOptions.Signer is nil, and refuses the commit outright when the setting is true and no
// signer is registered ("cannot auto-sign commit"). v5 ignored the setting entirely.
//
// Our signing policy comes from the GitProvider's signing Secret and is passed as
// CommitOptions.Signer, so an ambient commit.gpgSign — a developer's ~/.gitconfig, a mounted
// config, a future base image — must not be able to decide it for us. Writing the local value
// false makes the intent explicit and takes precedence over the wider scopes. Where we do sign,
// Signer is non-nil and this setting is never consulted.
func PinExplicitSigningPolicy(repo *git.Repository) error {
cfg, err := repo.Config()
if err != nil {
return fmt.Errorf("read repository config: %w", err)
}
if cfg.Commit.GpgSign == config.OptBoolFalse {
return nil
}
cfg.Commit.GpgSign = config.NewOptBool(false)
if err := repo.SetConfig(cfg); err != nil {
return fmt.Errorf("pin commit signing policy: %w", err)
}
return nil
}