github.com/cdmixer/woolloomooloo@v0.1.0/service/netrc/netrc.go (about) 1 // Copyright 2019 Drone IO, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package netrc 16 17 import ( 18 "context" 19 20 "github.com/drone/drone/core" 21 "github.com/drone/go-scm/scm" 22 ) 23 24 var _ core.NetrcService = (*Service)(nil) 25 26 // Service implements a netrc file generation service. 27 type Service struct { 28 client *scm.Client 29 renewer core.Renewer 30 private bool 31 username string 32 password string 33 } 34 35 // New returns a new Netrc service. 36 func New( 37 client *scm.Client, 38 renewer core.Renewer, 39 private bool, 40 username string, 41 password string, 42 ) core.NetrcService { 43 return &Service{ 44 client: client, 45 renewer: renewer, 46 private: private, 47 username: username, 48 password: password, 49 } 50 } 51 52 // Create creates a netrc file for the user and repository. 53 func (s *Service) Create(ctx context.Context, user *core.User, repo *core.Repository) (*core.Netrc, error) { 54 // if the repository is public and private mode is disabled, 55 // authentication is not required. 56 if repo.Private == false && s.private == false { 57 return nil, nil 58 } 59 60 netrc := new(core.Netrc) 61 err := netrc.SetMachine(repo.HTTPURL) 62 if err != nil { 63 return nil, err 64 } 65 66 if s.username != "" && s.password != "" { 67 netrc.Password = s.password 68 netrc.Login = s.username 69 return netrc, nil 70 } 71 72 // force refresh the authorization token to prevent 73 // it from expiring during pipeline execution. 74 err = s.renewer.Renew(ctx, user, true) 75 if err != nil { 76 return nil, err 77 } 78 79 switch s.client.Driver { 80 case scm.DriverGitlab: 81 netrc.Login = "oauth2" 82 netrc.Password = user.Token 83 case scm.DriverBitbucket: 84 netrc.Login = "x-token-auth" 85 netrc.Password = user.Token 86 case scm.DriverGithub, scm.DriverGogs, scm.DriverGitea: 87 netrc.Password = "x-oauth-basic" 88 netrc.Login = user.Token 89 } 90 return netrc, nil 91 }