@@ -186,7 +186,7 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
186186 return fmt .Errorf ("generating deploy key failed: %w" , err )
187187 }
188188
189- if err := createGitHubDeployKey (ctx , key , ghHostname , ghOwner , ghRepository , ghToken ); err != nil {
189+ if err := createGitHubDeployKey (ctx , key , ghHostname , ghOwner , ghRepository , ghPath , ghToken ); err != nil {
190190 return err
191191 }
192192 logSuccess ("deploy key configured" )
@@ -521,20 +521,62 @@ func generateGitHubDeployKey(ctx context.Context, kubeClient client.Client, url
521521 return string (pair .PublicKey ), nil
522522}
523523
524- func createGitHubDeployKey (ctx context.Context , key , hostname , owner , name , token string ) error {
524+ func createGitHubDeployKey (ctx context.Context , key , hostname , owner , repository , targetPath , token string ) error {
525525 gh , err := makeGitHubClient (hostname , token )
526526 if err != nil {
527527 return err
528528 }
529- keyName := fmt . Sprintf ( "tk-%s" , namespace )
530- isReadOnly := true
531- _ , _ , err = gh . Repositories . CreateKey ( ctx , owner , name , & github. Key {
532- Title : & keyName ,
533- Key : & key ,
534- ReadOnly : & isReadOnly ,
535- } )
529+ keyName := "tk"
530+ if targetPath != "" {
531+ keyName = fmt . Sprintf ( "tk-%s" , targetPath )
532+ }
533+
534+ // list deploy keys
535+ keys , resp , err := gh . Repositories . ListKeys ( ctx , owner , repository , nil )
536536 if err != nil {
537- return fmt .Errorf ("github create deploy key error: %w" , err )
537+ return fmt .Errorf ("github list deploy keys error: %w" , err )
538+ }
539+ if resp .StatusCode >= 300 {
540+ return fmt .Errorf ("github list deploy keys failed with status code: %s" , resp .Status )
541+ }
542+
543+ // check if the key exists
544+ shouldCreateKey := true
545+ var existingKey * github.Key
546+ for _ , k := range keys {
547+ if k .Title != nil && k .Key != nil && * k .Title == keyName {
548+ if * k .Key != key {
549+ existingKey = k
550+ } else {
551+ shouldCreateKey = false
552+ }
553+ break
554+ }
538555 }
556+
557+ // delete existing key if the value differs
558+ if existingKey != nil {
559+ resp , err := gh .Repositories .DeleteKey (ctx , owner , repository , * existingKey .ID )
560+ if err != nil {
561+ return fmt .Errorf ("github delete deploy key error: %w" , err )
562+ }
563+ if resp .StatusCode >= 300 {
564+ return fmt .Errorf ("github delete deploy key failed with status code: %s" , resp .Status )
565+ }
566+ }
567+
568+ // create key
569+ if shouldCreateKey {
570+ isReadOnly := true
571+ _ , _ , err = gh .Repositories .CreateKey (ctx , owner , repository , & github.Key {
572+ Title : & keyName ,
573+ Key : & key ,
574+ ReadOnly : & isReadOnly ,
575+ })
576+ if err != nil {
577+ return fmt .Errorf ("github create deploy key error: %w" , err )
578+ }
579+ }
580+
539581 return nil
540582}
0 commit comments