id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
162,000
argoproj/argo-cd
util/settings/settings.go
Subscribe
func (mgr *SettingsManager) Subscribe(subCh chan<- *ArgoCDSettings) { mgr.mutex.Lock() defer mgr.mutex.Unlock() mgr.subscribers = append(mgr.subscribers, subCh) log.Infof("%v subscribed to settings updates", subCh) }
go
func (mgr *SettingsManager) Subscribe(subCh chan<- *ArgoCDSettings) { mgr.mutex.Lock() defer mgr.mutex.Unlock() mgr.subscribers = append(mgr.subscribers, subCh) log.Infof("%v subscribed to settings updates", subCh) }
[ "func", "(", "mgr", "*", "SettingsManager", ")", "Subscribe", "(", "subCh", "chan", "<-", "*", "ArgoCDSettings", ")", "{", "mgr", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mgr", ".", "mutex", ".", "Unlock", "(", ")", "\n", "mgr", ".", "subscribers", "=", "append", "(", "mgr", ".", "subscribers", ",", "subCh", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "subCh", ")", "\n", "}" ]
// Subscribe registers a channel in which to subscribe to settings updates
[ "Subscribe", "registers", "a", "channel", "in", "which", "to", "subscribe", "to", "settings", "updates" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/settings/settings.go#L756-L761
162,001
argoproj/argo-cd
util/settings/settings.go
Unsubscribe
func (mgr *SettingsManager) Unsubscribe(subCh chan<- *ArgoCDSettings) { mgr.mutex.Lock() defer mgr.mutex.Unlock() for i, ch := range mgr.subscribers { if ch == subCh { mgr.subscribers = append(mgr.subscribers[:i], mgr.subscribers[i+1:]...) log.Infof("%v unsubscribed from settings updates", subCh) return } } }
go
func (mgr *SettingsManager) Unsubscribe(subCh chan<- *ArgoCDSettings) { mgr.mutex.Lock() defer mgr.mutex.Unlock() for i, ch := range mgr.subscribers { if ch == subCh { mgr.subscribers = append(mgr.subscribers[:i], mgr.subscribers[i+1:]...) log.Infof("%v unsubscribed from settings updates", subCh) return } } }
[ "func", "(", "mgr", "*", "SettingsManager", ")", "Unsubscribe", "(", "subCh", "chan", "<-", "*", "ArgoCDSettings", ")", "{", "mgr", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mgr", ".", "mutex", ".", "Unlock", "(", ")", "\n", "for", "i", ",", "ch", ":=", "range", "mgr", ".", "subscribers", "{", "if", "ch", "==", "subCh", "{", "mgr", ".", "subscribers", "=", "append", "(", "mgr", ".", "subscribers", "[", ":", "i", "]", ",", "mgr", ".", "subscribers", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "subCh", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Unsubscribe unregisters a channel from receiving of settings updates
[ "Unsubscribe", "unregisters", "a", "channel", "from", "receiving", "of", "settings", "updates" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/settings/settings.go#L764-L774
162,002
argoproj/argo-cd
util/settings/settings.go
InitializeSettings
func (mgr *SettingsManager) InitializeSettings() (*ArgoCDSettings, error) { cdSettings, err := mgr.GetSettings() if err != nil && !isIncompleteSettingsError(err) { return nil, err } if cdSettings == nil { cdSettings = &ArgoCDSettings{} } if cdSettings.ServerSignature == nil { // set JWT signature signature, err := util.MakeSignature(32) if err != nil { return nil, err } cdSettings.ServerSignature = signature log.Info("Initialized server signature") } if cdSettings.AdminPasswordHash == "" { defaultPassword, err := os.Hostname() if err != nil { return nil, err } hashedPassword, err := password.HashPassword(defaultPassword) if err != nil { return nil, err } cdSettings.AdminPasswordHash = hashedPassword cdSettings.AdminPasswordMtime = time.Now().UTC() log.Info("Initialized admin password") } if cdSettings.AdminPasswordMtime.IsZero() { cdSettings.AdminPasswordMtime = time.Now().UTC() log.Info("Initialized admin mtime") } if cdSettings.Certificate == nil { // generate TLS cert hosts := []string{ "localhost", "argocd-server", fmt.Sprintf("argocd-server.%s", mgr.namespace), fmt.Sprintf("argocd-server.%s.svc", mgr.namespace), fmt.Sprintf("argocd-server.%s.svc.cluster.local", mgr.namespace), } certOpts := tlsutil.CertOptions{ Hosts: hosts, Organization: "Argo CD", IsCA: true, } cert, err := tlsutil.GenerateX509KeyPair(certOpts) if err != nil { return nil, err } cdSettings.Certificate = cert log.Info("Initialized TLS certificate") } if len(cdSettings.Repositories) == 0 { err = mgr.MigrateLegacyRepoSettings(cdSettings) if err != nil { return nil, err } } err = mgr.SaveSettings(cdSettings) if apierrors.IsConflict(err) { // assume settings are initialized by another instance of api server log.Warnf("conflict when initializing settings. assuming updated by another replica") return mgr.GetSettings() } return cdSettings, nil }
go
func (mgr *SettingsManager) InitializeSettings() (*ArgoCDSettings, error) { cdSettings, err := mgr.GetSettings() if err != nil && !isIncompleteSettingsError(err) { return nil, err } if cdSettings == nil { cdSettings = &ArgoCDSettings{} } if cdSettings.ServerSignature == nil { // set JWT signature signature, err := util.MakeSignature(32) if err != nil { return nil, err } cdSettings.ServerSignature = signature log.Info("Initialized server signature") } if cdSettings.AdminPasswordHash == "" { defaultPassword, err := os.Hostname() if err != nil { return nil, err } hashedPassword, err := password.HashPassword(defaultPassword) if err != nil { return nil, err } cdSettings.AdminPasswordHash = hashedPassword cdSettings.AdminPasswordMtime = time.Now().UTC() log.Info("Initialized admin password") } if cdSettings.AdminPasswordMtime.IsZero() { cdSettings.AdminPasswordMtime = time.Now().UTC() log.Info("Initialized admin mtime") } if cdSettings.Certificate == nil { // generate TLS cert hosts := []string{ "localhost", "argocd-server", fmt.Sprintf("argocd-server.%s", mgr.namespace), fmt.Sprintf("argocd-server.%s.svc", mgr.namespace), fmt.Sprintf("argocd-server.%s.svc.cluster.local", mgr.namespace), } certOpts := tlsutil.CertOptions{ Hosts: hosts, Organization: "Argo CD", IsCA: true, } cert, err := tlsutil.GenerateX509KeyPair(certOpts) if err != nil { return nil, err } cdSettings.Certificate = cert log.Info("Initialized TLS certificate") } if len(cdSettings.Repositories) == 0 { err = mgr.MigrateLegacyRepoSettings(cdSettings) if err != nil { return nil, err } } err = mgr.SaveSettings(cdSettings) if apierrors.IsConflict(err) { // assume settings are initialized by another instance of api server log.Warnf("conflict when initializing settings. assuming updated by another replica") return mgr.GetSettings() } return cdSettings, nil }
[ "func", "(", "mgr", "*", "SettingsManager", ")", "InitializeSettings", "(", ")", "(", "*", "ArgoCDSettings", ",", "error", ")", "{", "cdSettings", ",", "err", ":=", "mgr", ".", "GetSettings", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "isIncompleteSettingsError", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "cdSettings", "==", "nil", "{", "cdSettings", "=", "&", "ArgoCDSettings", "{", "}", "\n", "}", "\n", "if", "cdSettings", ".", "ServerSignature", "==", "nil", "{", "// set JWT signature", "signature", ",", "err", ":=", "util", ".", "MakeSignature", "(", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cdSettings", ".", "ServerSignature", "=", "signature", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cdSettings", ".", "AdminPasswordHash", "==", "\"", "\"", "{", "defaultPassword", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "hashedPassword", ",", "err", ":=", "password", ".", "HashPassword", "(", "defaultPassword", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cdSettings", ".", "AdminPasswordHash", "=", "hashedPassword", "\n", "cdSettings", ".", "AdminPasswordMtime", "=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cdSettings", ".", "AdminPasswordMtime", ".", "IsZero", "(", ")", "{", "cdSettings", ".", "AdminPasswordMtime", "=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cdSettings", ".", "Certificate", "==", "nil", "{", "// generate TLS cert", "hosts", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "mgr", ".", "namespace", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "mgr", ".", "namespace", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "mgr", ".", "namespace", ")", ",", "}", "\n", "certOpts", ":=", "tlsutil", ".", "CertOptions", "{", "Hosts", ":", "hosts", ",", "Organization", ":", "\"", "\"", ",", "IsCA", ":", "true", ",", "}", "\n", "cert", ",", "err", ":=", "tlsutil", ".", "GenerateX509KeyPair", "(", "certOpts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cdSettings", ".", "Certificate", "=", "cert", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "cdSettings", ".", "Repositories", ")", "==", "0", "{", "err", "=", "mgr", ".", "MigrateLegacyRepoSettings", "(", "cdSettings", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "err", "=", "mgr", ".", "SaveSettings", "(", "cdSettings", ")", "\n", "if", "apierrors", ".", "IsConflict", "(", "err", ")", "{", "// assume settings are initialized by another instance of api server", "log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "return", "mgr", ".", "GetSettings", "(", ")", "\n", "}", "\n", "return", "cdSettings", ",", "nil", "\n", "}" ]
// InitializeSettings is used to initialize empty admin password, signature, certificate etc if missing
[ "InitializeSettings", "is", "used", "to", "initialize", "empty", "admin", "password", "signature", "certificate", "etc", "if", "missing" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/settings/settings.go#L793-L864
162,003
argoproj/argo-cd
server/project/project.go
NewServer
func NewServer(ns string, kubeclientset kubernetes.Interface, appclientset appclientset.Interface, enf *rbac.Enforcer, projectLock *util.KeyLock, sessionMgr *session.SessionManager) *Server { auditLogger := argo.NewAuditLogger(ns, kubeclientset, "argocd-server") return &Server{enf: enf, appclientset: appclientset, kubeclientset: kubeclientset, ns: ns, projectLock: projectLock, auditLogger: auditLogger, sessionMgr: sessionMgr} }
go
func NewServer(ns string, kubeclientset kubernetes.Interface, appclientset appclientset.Interface, enf *rbac.Enforcer, projectLock *util.KeyLock, sessionMgr *session.SessionManager) *Server { auditLogger := argo.NewAuditLogger(ns, kubeclientset, "argocd-server") return &Server{enf: enf, appclientset: appclientset, kubeclientset: kubeclientset, ns: ns, projectLock: projectLock, auditLogger: auditLogger, sessionMgr: sessionMgr} }
[ "func", "NewServer", "(", "ns", "string", ",", "kubeclientset", "kubernetes", ".", "Interface", ",", "appclientset", "appclientset", ".", "Interface", ",", "enf", "*", "rbac", ".", "Enforcer", ",", "projectLock", "*", "util", ".", "KeyLock", ",", "sessionMgr", "*", "session", ".", "SessionManager", ")", "*", "Server", "{", "auditLogger", ":=", "argo", ".", "NewAuditLogger", "(", "ns", ",", "kubeclientset", ",", "\"", "\"", ")", "\n", "return", "&", "Server", "{", "enf", ":", "enf", ",", "appclientset", ":", "appclientset", ",", "kubeclientset", ":", "kubeclientset", ",", "ns", ":", "ns", ",", "projectLock", ":", "projectLock", ",", "auditLogger", ":", "auditLogger", ",", "sessionMgr", ":", "sessionMgr", "}", "\n", "}" ]
// NewServer returns a new instance of the Project service
[ "NewServer", "returns", "a", "new", "instance", "of", "the", "Project", "service" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/server/project/project.go#L45-L48
162,004
argoproj/argo-cd
server/project/project.go
CreateToken
func (s *Server) CreateToken(ctx context.Context, q *ProjectTokenCreateRequest) (*ProjectTokenResponse, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionUpdate, q.Project); err != nil { return nil, err } project, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Project, metav1.GetOptions{}) if err != nil { return nil, err } err = projectutil.ValidateProject(project) if err != nil { return nil, err } s.projectLock.Lock(q.Project) defer s.projectLock.Unlock(q.Project) _, index, err := projectutil.GetRoleByName(project, q.Role) if err != nil { return nil, status.Errorf(codes.NotFound, "project '%s' does not have role '%s'", q.Project, q.Role) } tokenName := fmt.Sprintf(JWTTokenSubFormat, q.Project, q.Role) jwtToken, err := s.sessionMgr.Create(tokenName, q.ExpiresIn) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } parser := &jwt.Parser{ SkipClaimsValidation: true, } claims := jwt.StandardClaims{} _, _, err = parser.ParseUnverified(jwtToken, &claims) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } issuedAt := claims.IssuedAt expiresAt := claims.ExpiresAt project.Spec.Roles[index].JWTTokens = append(project.Spec.Roles[index].JWTTokens, v1alpha1.JWTToken{IssuedAt: issuedAt, ExpiresAt: expiresAt}) _, err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Update(project) if err != nil { return nil, err } s.logEvent(project, ctx, argo.EventReasonResourceCreated, "created token") return &ProjectTokenResponse{Token: jwtToken}, nil }
go
func (s *Server) CreateToken(ctx context.Context, q *ProjectTokenCreateRequest) (*ProjectTokenResponse, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionUpdate, q.Project); err != nil { return nil, err } project, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Project, metav1.GetOptions{}) if err != nil { return nil, err } err = projectutil.ValidateProject(project) if err != nil { return nil, err } s.projectLock.Lock(q.Project) defer s.projectLock.Unlock(q.Project) _, index, err := projectutil.GetRoleByName(project, q.Role) if err != nil { return nil, status.Errorf(codes.NotFound, "project '%s' does not have role '%s'", q.Project, q.Role) } tokenName := fmt.Sprintf(JWTTokenSubFormat, q.Project, q.Role) jwtToken, err := s.sessionMgr.Create(tokenName, q.ExpiresIn) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } parser := &jwt.Parser{ SkipClaimsValidation: true, } claims := jwt.StandardClaims{} _, _, err = parser.ParseUnverified(jwtToken, &claims) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } issuedAt := claims.IssuedAt expiresAt := claims.ExpiresAt project.Spec.Roles[index].JWTTokens = append(project.Spec.Roles[index].JWTTokens, v1alpha1.JWTToken{IssuedAt: issuedAt, ExpiresAt: expiresAt}) _, err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Update(project) if err != nil { return nil, err } s.logEvent(project, ctx, argo.EventReasonResourceCreated, "created token") return &ProjectTokenResponse{Token: jwtToken}, nil }
[ "func", "(", "s", "*", "Server", ")", "CreateToken", "(", "ctx", "context", ".", "Context", ",", "q", "*", "ProjectTokenCreateRequest", ")", "(", "*", "ProjectTokenResponse", ",", "error", ")", "{", "if", "err", ":=", "s", ".", "enf", ".", "EnforceErr", "(", "ctx", ".", "Value", "(", "\"", "\"", ")", ",", "rbacpolicy", ".", "ResourceProjects", ",", "rbacpolicy", ".", "ActionUpdate", ",", "q", ".", "Project", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "project", ",", "err", ":=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "Get", "(", "q", ".", "Project", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "projectutil", ".", "ValidateProject", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "projectLock", ".", "Lock", "(", "q", ".", "Project", ")", "\n", "defer", "s", ".", "projectLock", ".", "Unlock", "(", "q", ".", "Project", ")", "\n\n", "_", ",", "index", ",", "err", ":=", "projectutil", ".", "GetRoleByName", "(", "project", ",", "q", ".", "Role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "q", ".", "Project", ",", "q", ".", "Role", ")", "\n", "}", "\n\n", "tokenName", ":=", "fmt", ".", "Sprintf", "(", "JWTTokenSubFormat", ",", "q", ".", "Project", ",", "q", ".", "Role", ")", "\n", "jwtToken", ",", "err", ":=", "s", ".", "sessionMgr", ".", "Create", "(", "tokenName", ",", "q", ".", "ExpiresIn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "parser", ":=", "&", "jwt", ".", "Parser", "{", "SkipClaimsValidation", ":", "true", ",", "}", "\n", "claims", ":=", "jwt", ".", "StandardClaims", "{", "}", "\n", "_", ",", "_", ",", "err", "=", "parser", ".", "ParseUnverified", "(", "jwtToken", ",", "&", "claims", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "status", ".", "Error", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "issuedAt", ":=", "claims", ".", "IssuedAt", "\n", "expiresAt", ":=", "claims", ".", "ExpiresAt", "\n\n", "project", ".", "Spec", ".", "Roles", "[", "index", "]", ".", "JWTTokens", "=", "append", "(", "project", ".", "Spec", ".", "Roles", "[", "index", "]", ".", "JWTTokens", ",", "v1alpha1", ".", "JWTToken", "{", "IssuedAt", ":", "issuedAt", ",", "ExpiresAt", ":", "expiresAt", "}", ")", "\n", "_", ",", "err", "=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "Update", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "s", ".", "logEvent", "(", "project", ",", "ctx", ",", "argo", ".", "EventReasonResourceCreated", ",", "\"", "\"", ")", "\n", "return", "&", "ProjectTokenResponse", "{", "Token", ":", "jwtToken", "}", ",", "nil", "\n\n", "}" ]
// CreateToken creates a new token to access a project
[ "CreateToken", "creates", "a", "new", "token", "to", "access", "a", "project" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/server/project/project.go#L51-L96
162,005
argoproj/argo-cd
server/project/project.go
DeleteToken
func (s *Server) DeleteToken(ctx context.Context, q *ProjectTokenDeleteRequest) (*EmptyResponse, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionDelete, q.Project); err != nil { return nil, err } project, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Project, metav1.GetOptions{}) if err != nil { return nil, err } err = projectutil.ValidateProject(project) if err != nil { return nil, err } s.projectLock.Lock(q.Project) defer s.projectLock.Unlock(q.Project) _, roleIndex, err := projectutil.GetRoleByName(project, q.Role) if err != nil { return &EmptyResponse{}, nil } _, jwtTokenIndex, err := projectutil.GetJWTToken(project, q.Role, q.Iat) if err != nil { return &EmptyResponse{}, nil } project.Spec.Roles[roleIndex].JWTTokens[jwtTokenIndex] = project.Spec.Roles[roleIndex].JWTTokens[len(project.Spec.Roles[roleIndex].JWTTokens)-1] project.Spec.Roles[roleIndex].JWTTokens = project.Spec.Roles[roleIndex].JWTTokens[:len(project.Spec.Roles[roleIndex].JWTTokens)-1] _, err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Update(project) if err != nil { return nil, err } s.logEvent(project, ctx, argo.EventReasonResourceDeleted, "deleted token") return &EmptyResponse{}, nil }
go
func (s *Server) DeleteToken(ctx context.Context, q *ProjectTokenDeleteRequest) (*EmptyResponse, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionDelete, q.Project); err != nil { return nil, err } project, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Project, metav1.GetOptions{}) if err != nil { return nil, err } err = projectutil.ValidateProject(project) if err != nil { return nil, err } s.projectLock.Lock(q.Project) defer s.projectLock.Unlock(q.Project) _, roleIndex, err := projectutil.GetRoleByName(project, q.Role) if err != nil { return &EmptyResponse{}, nil } _, jwtTokenIndex, err := projectutil.GetJWTToken(project, q.Role, q.Iat) if err != nil { return &EmptyResponse{}, nil } project.Spec.Roles[roleIndex].JWTTokens[jwtTokenIndex] = project.Spec.Roles[roleIndex].JWTTokens[len(project.Spec.Roles[roleIndex].JWTTokens)-1] project.Spec.Roles[roleIndex].JWTTokens = project.Spec.Roles[roleIndex].JWTTokens[:len(project.Spec.Roles[roleIndex].JWTTokens)-1] _, err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Update(project) if err != nil { return nil, err } s.logEvent(project, ctx, argo.EventReasonResourceDeleted, "deleted token") return &EmptyResponse{}, nil }
[ "func", "(", "s", "*", "Server", ")", "DeleteToken", "(", "ctx", "context", ".", "Context", ",", "q", "*", "ProjectTokenDeleteRequest", ")", "(", "*", "EmptyResponse", ",", "error", ")", "{", "if", "err", ":=", "s", ".", "enf", ".", "EnforceErr", "(", "ctx", ".", "Value", "(", "\"", "\"", ")", ",", "rbacpolicy", ".", "ResourceProjects", ",", "rbacpolicy", ".", "ActionDelete", ",", "q", ".", "Project", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "project", ",", "err", ":=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "Get", "(", "q", ".", "Project", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "projectutil", ".", "ValidateProject", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "projectLock", ".", "Lock", "(", "q", ".", "Project", ")", "\n", "defer", "s", ".", "projectLock", ".", "Unlock", "(", "q", ".", "Project", ")", "\n\n", "_", ",", "roleIndex", ",", "err", ":=", "projectutil", ".", "GetRoleByName", "(", "project", ",", "q", ".", "Role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "EmptyResponse", "{", "}", ",", "nil", "\n", "}", "\n", "_", ",", "jwtTokenIndex", ",", "err", ":=", "projectutil", ".", "GetJWTToken", "(", "project", ",", "q", ".", "Role", ",", "q", ".", "Iat", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "EmptyResponse", "{", "}", ",", "nil", "\n", "}", "\n", "project", ".", "Spec", ".", "Roles", "[", "roleIndex", "]", ".", "JWTTokens", "[", "jwtTokenIndex", "]", "=", "project", ".", "Spec", ".", "Roles", "[", "roleIndex", "]", ".", "JWTTokens", "[", "len", "(", "project", ".", "Spec", ".", "Roles", "[", "roleIndex", "]", ".", "JWTTokens", ")", "-", "1", "]", "\n", "project", ".", "Spec", ".", "Roles", "[", "roleIndex", "]", ".", "JWTTokens", "=", "project", ".", "Spec", ".", "Roles", "[", "roleIndex", "]", ".", "JWTTokens", "[", ":", "len", "(", "project", ".", "Spec", ".", "Roles", "[", "roleIndex", "]", ".", "JWTTokens", ")", "-", "1", "]", "\n", "_", ",", "err", "=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "Update", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "s", ".", "logEvent", "(", "project", ",", "ctx", ",", "argo", ".", "EventReasonResourceDeleted", ",", "\"", "\"", ")", "\n", "return", "&", "EmptyResponse", "{", "}", ",", "nil", "\n", "}" ]
// DeleteToken deletes a token in a project
[ "DeleteToken", "deletes", "a", "token", "in", "a", "project" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/server/project/project.go#L99-L131
162,006
argoproj/argo-cd
server/project/project.go
List
func (s *Server) List(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProjectList, error) { list, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(metav1.ListOptions{}) if list != nil { newItems := make([]v1alpha1.AppProject, 0) for i := range list.Items { project := list.Items[i] if s.enf.Enforce(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, project.Name) { newItems = append(newItems, project) } } list.Items = newItems } return list, err }
go
func (s *Server) List(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProjectList, error) { list, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).List(metav1.ListOptions{}) if list != nil { newItems := make([]v1alpha1.AppProject, 0) for i := range list.Items { project := list.Items[i] if s.enf.Enforce(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, project.Name) { newItems = append(newItems, project) } } list.Items = newItems } return list, err }
[ "func", "(", "s", "*", "Server", ")", "List", "(", "ctx", "context", ".", "Context", ",", "q", "*", "ProjectQuery", ")", "(", "*", "v1alpha1", ".", "AppProjectList", ",", "error", ")", "{", "list", ",", "err", ":=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "List", "(", "metav1", ".", "ListOptions", "{", "}", ")", "\n", "if", "list", "!=", "nil", "{", "newItems", ":=", "make", "(", "[", "]", "v1alpha1", ".", "AppProject", ",", "0", ")", "\n", "for", "i", ":=", "range", "list", ".", "Items", "{", "project", ":=", "list", ".", "Items", "[", "i", "]", "\n", "if", "s", ".", "enf", ".", "Enforce", "(", "ctx", ".", "Value", "(", "\"", "\"", ")", ",", "rbacpolicy", ".", "ResourceProjects", ",", "rbacpolicy", ".", "ActionGet", ",", "project", ".", "Name", ")", "{", "newItems", "=", "append", "(", "newItems", ",", "project", ")", "\n", "}", "\n", "}", "\n", "list", ".", "Items", "=", "newItems", "\n", "}", "\n", "return", "list", ",", "err", "\n", "}" ]
// List returns list of projects
[ "List", "returns", "list", "of", "projects" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/server/project/project.go#L151-L164
162,007
argoproj/argo-cd
server/project/project.go
Get
func (s *Server) Get(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProject, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, q.Name); err != nil { return nil, err } return s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Name, metav1.GetOptions{}) }
go
func (s *Server) Get(ctx context.Context, q *ProjectQuery) (*v1alpha1.AppProject, error) { if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionGet, q.Name); err != nil { return nil, err } return s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Name, metav1.GetOptions{}) }
[ "func", "(", "s", "*", "Server", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "q", "*", "ProjectQuery", ")", "(", "*", "v1alpha1", ".", "AppProject", ",", "error", ")", "{", "if", "err", ":=", "s", ".", "enf", ".", "EnforceErr", "(", "ctx", ".", "Value", "(", "\"", "\"", ")", ",", "rbacpolicy", ".", "ResourceProjects", ",", "rbacpolicy", ".", "ActionGet", ",", "q", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "Get", "(", "q", ".", "Name", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "}" ]
// Get returns a project by name
[ "Get", "returns", "a", "project", "by", "name" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/server/project/project.go#L167-L172
162,008
argoproj/argo-cd
server/project/project.go
Delete
func (s *Server) Delete(ctx context.Context, q *ProjectQuery) (*EmptyResponse, error) { if q.Name == common.DefaultAppProjectName { return nil, status.Errorf(codes.InvalidArgument, "name '%s' is reserved and cannot be deleted", q.Name) } if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionDelete, q.Name); err != nil { return nil, err } s.projectLock.Lock(q.Name) defer s.projectLock.Unlock(q.Name) p, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Name, metav1.GetOptions{}) if err != nil { return nil, err } appsList, err := s.appclientset.ArgoprojV1alpha1().Applications(s.ns).List(metav1.ListOptions{}) if err != nil { return nil, err } apps := argo.FilterByProjects(appsList.Items, []string{q.Name}) if len(apps) > 0 { return nil, status.Errorf(codes.InvalidArgument, "project is referenced by %d applications", len(apps)) } err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Delete(q.Name, &metav1.DeleteOptions{}) if err == nil { s.logEvent(p, ctx, argo.EventReasonResourceDeleted, "deleted project") } return &EmptyResponse{}, err }
go
func (s *Server) Delete(ctx context.Context, q *ProjectQuery) (*EmptyResponse, error) { if q.Name == common.DefaultAppProjectName { return nil, status.Errorf(codes.InvalidArgument, "name '%s' is reserved and cannot be deleted", q.Name) } if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceProjects, rbacpolicy.ActionDelete, q.Name); err != nil { return nil, err } s.projectLock.Lock(q.Name) defer s.projectLock.Unlock(q.Name) p, err := s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Get(q.Name, metav1.GetOptions{}) if err != nil { return nil, err } appsList, err := s.appclientset.ArgoprojV1alpha1().Applications(s.ns).List(metav1.ListOptions{}) if err != nil { return nil, err } apps := argo.FilterByProjects(appsList.Items, []string{q.Name}) if len(apps) > 0 { return nil, status.Errorf(codes.InvalidArgument, "project is referenced by %d applications", len(apps)) } err = s.appclientset.ArgoprojV1alpha1().AppProjects(s.ns).Delete(q.Name, &metav1.DeleteOptions{}) if err == nil { s.logEvent(p, ctx, argo.EventReasonResourceDeleted, "deleted project") } return &EmptyResponse{}, err }
[ "func", "(", "s", "*", "Server", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "q", "*", "ProjectQuery", ")", "(", "*", "EmptyResponse", ",", "error", ")", "{", "if", "q", ".", "Name", "==", "common", ".", "DefaultAppProjectName", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "q", ".", "Name", ")", "\n", "}", "\n", "if", "err", ":=", "s", ".", "enf", ".", "EnforceErr", "(", "ctx", ".", "Value", "(", "\"", "\"", ")", ",", "rbacpolicy", ".", "ResourceProjects", ",", "rbacpolicy", ".", "ActionDelete", ",", "q", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "projectLock", ".", "Lock", "(", "q", ".", "Name", ")", "\n", "defer", "s", ".", "projectLock", ".", "Unlock", "(", "q", ".", "Name", ")", "\n\n", "p", ",", "err", ":=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "Get", "(", "q", ".", "Name", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "appsList", ",", "err", ":=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "Applications", "(", "s", ".", "ns", ")", ".", "List", "(", "metav1", ".", "ListOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "apps", ":=", "argo", ".", "FilterByProjects", "(", "appsList", ".", "Items", ",", "[", "]", "string", "{", "q", ".", "Name", "}", ")", "\n", "if", "len", "(", "apps", ")", ">", "0", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "len", "(", "apps", ")", ")", "\n", "}", "\n", "err", "=", "s", ".", "appclientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "AppProjects", "(", "s", ".", "ns", ")", ".", "Delete", "(", "q", ".", "Name", ",", "&", "metav1", ".", "DeleteOptions", "{", "}", ")", "\n", "if", "err", "==", "nil", "{", "s", ".", "logEvent", "(", "p", ",", "ctx", ",", "argo", ".", "EventReasonResourceDeleted", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "EmptyResponse", "{", "}", ",", "err", "\n", "}" ]
// Delete deletes a project
[ "Delete", "deletes", "a", "project" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/server/project/project.go#L294-L323
162,009
argoproj/argo-cd
util/swagger/swagger.go
ServeSwaggerUI
func ServeSwaggerUI(mux *http.ServeMux, swaggerJSON string, uiPath string) { prefix := path.Dir(uiPath) specURL := path.Join(prefix, "swagger.json") mux.HandleFunc(specURL, func(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprint(w, swaggerJSON) }) mux.Handle(uiPath, middleware.Redoc(middleware.RedocOpts{ BasePath: prefix, SpecURL: specURL, Path: path.Base(uiPath), }, http.NotFoundHandler())) }
go
func ServeSwaggerUI(mux *http.ServeMux, swaggerJSON string, uiPath string) { prefix := path.Dir(uiPath) specURL := path.Join(prefix, "swagger.json") mux.HandleFunc(specURL, func(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprint(w, swaggerJSON) }) mux.Handle(uiPath, middleware.Redoc(middleware.RedocOpts{ BasePath: prefix, SpecURL: specURL, Path: path.Base(uiPath), }, http.NotFoundHandler())) }
[ "func", "ServeSwaggerUI", "(", "mux", "*", "http", ".", "ServeMux", ",", "swaggerJSON", "string", ",", "uiPath", "string", ")", "{", "prefix", ":=", "path", ".", "Dir", "(", "uiPath", ")", "\n", "specURL", ":=", "path", ".", "Join", "(", "prefix", ",", "\"", "\"", ")", "\n\n", "mux", ".", "HandleFunc", "(", "specURL", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "_", ",", "_", "=", "fmt", ".", "Fprint", "(", "w", ",", "swaggerJSON", ")", "\n", "}", ")", "\n\n", "mux", ".", "Handle", "(", "uiPath", ",", "middleware", ".", "Redoc", "(", "middleware", ".", "RedocOpts", "{", "BasePath", ":", "prefix", ",", "SpecURL", ":", "specURL", ",", "Path", ":", "path", ".", "Base", "(", "uiPath", ")", ",", "}", ",", "http", ".", "NotFoundHandler", "(", ")", ")", ")", "\n", "}" ]
// ServeSwaggerUI serves the Swagger UI and JSON spec.
[ "ServeSwaggerUI", "serves", "the", "Swagger", "UI", "and", "JSON", "spec", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/swagger/swagger.go#L12-L25
162,010
argoproj/argo-cd
pkg/client/clientset/versioned/typed/application/v1alpha1/appproject.go
newAppProjects
func newAppProjects(c *ArgoprojV1alpha1Client, namespace string) *appProjects { return &appProjects{ client: c.RESTClient(), ns: namespace, } }
go
func newAppProjects(c *ArgoprojV1alpha1Client, namespace string) *appProjects { return &appProjects{ client: c.RESTClient(), ns: namespace, } }
[ "func", "newAppProjects", "(", "c", "*", "ArgoprojV1alpha1Client", ",", "namespace", "string", ")", "*", "appProjects", "{", "return", "&", "appProjects", "{", "client", ":", "c", ".", "RESTClient", "(", ")", ",", "ns", ":", "namespace", ",", "}", "\n", "}" ]
// newAppProjects returns a AppProjects
[ "newAppProjects", "returns", "a", "AppProjects" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/clientset/versioned/typed/application/v1alpha1/appproject.go#L40-L45
162,011
argoproj/argo-cd
cmd/argocd/commands/app_actions.go
NewApplicationResourceActionsCommand
func NewApplicationResourceActionsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "actions", Short: "Manage Resource actions", Run: func(c *cobra.Command, args []string) { c.HelpFunc()(c, args) os.Exit(1) }, } command.AddCommand(NewApplicationResourceActionsListCommand(clientOpts)) command.AddCommand(NewApplicationResourceActionsRunCommand(clientOpts)) return command }
go
func NewApplicationResourceActionsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "actions", Short: "Manage Resource actions", Run: func(c *cobra.Command, args []string) { c.HelpFunc()(c, args) os.Exit(1) }, } command.AddCommand(NewApplicationResourceActionsListCommand(clientOpts)) command.AddCommand(NewApplicationResourceActionsRunCommand(clientOpts)) return command }
[ "func", "NewApplicationResourceActionsCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", ",", "}", "\n", "command", ".", "AddCommand", "(", "NewApplicationResourceActionsListCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewApplicationResourceActionsRunCommand", "(", "clientOpts", ")", ")", "\n", "return", "command", "\n", "}" ]
// NewApplicationResourceActionsCommand returns a new instance of an `argocd app actions` command
[ "NewApplicationResourceActionsCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "app", "actions", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/app_actions.go#L20-L32
162,012
argoproj/argo-cd
cmd/argocd/commands/app_actions.go
NewApplicationResourceActionsListCommand
func NewApplicationResourceActionsListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var namespace string var kind string var group string var resourceName string var all bool var command = &cobra.Command{ Use: "list APPNAME", Short: "Lists available actions on a resource", } command.Run = func(c *cobra.Command, args []string) { if len(args) != 1 { c.HelpFunc()(c, args) os.Exit(1) } appName := args[0] conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie() defer util.Close(conn) ctx := context.Background() resources, err := appIf.ManagedResources(ctx, &application.ResourcesQuery{ApplicationName: &appName}) errors.CheckError(err) filteredObjects := filterResources(command, resources.Items, group, kind, namespace, resourceName, all) availableActions := make(map[string][]argoappv1.ResourceAction) for i := range filteredObjects { obj := filteredObjects[i] gvk := obj.GroupVersionKind() availActionsForResource, err := appIf.ListResourceActions(ctx, &application.ApplicationResourceRequest{ Name: &appName, Namespace: obj.GetNamespace(), ResourceName: obj.GetName(), Group: gvk.Group, Kind: gvk.Kind, }) errors.CheckError(err) availableActions[obj.GetName()] = availActionsForResource.Actions } var keys []string for key := range availableActions { keys = append(keys, key) } sort.Strings(keys) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintf(w, "RESOURCE\tACTION\n") fmt.Println() for key := range availableActions { for i := range availableActions[key] { action := availableActions[key][i] fmt.Fprintf(w, "%s\t%s\n", key, action.Name) } } _ = w.Flush() } command.Flags().StringVar(&resourceName, "resource-name", "", "Name of resource") command.Flags().StringVar(&kind, "kind", "", "Kind") err := command.MarkFlagRequired("kind") errors.CheckError(err) command.Flags().StringVar(&group, "group", "", "Group") command.Flags().StringVar(&namespace, "namespace", "", "Namespace") command.Flags().BoolVar(&all, "all", false, "Indicates whether to list actions on multiple matching resources") return command }
go
func NewApplicationResourceActionsListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var namespace string var kind string var group string var resourceName string var all bool var command = &cobra.Command{ Use: "list APPNAME", Short: "Lists available actions on a resource", } command.Run = func(c *cobra.Command, args []string) { if len(args) != 1 { c.HelpFunc()(c, args) os.Exit(1) } appName := args[0] conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie() defer util.Close(conn) ctx := context.Background() resources, err := appIf.ManagedResources(ctx, &application.ResourcesQuery{ApplicationName: &appName}) errors.CheckError(err) filteredObjects := filterResources(command, resources.Items, group, kind, namespace, resourceName, all) availableActions := make(map[string][]argoappv1.ResourceAction) for i := range filteredObjects { obj := filteredObjects[i] gvk := obj.GroupVersionKind() availActionsForResource, err := appIf.ListResourceActions(ctx, &application.ApplicationResourceRequest{ Name: &appName, Namespace: obj.GetNamespace(), ResourceName: obj.GetName(), Group: gvk.Group, Kind: gvk.Kind, }) errors.CheckError(err) availableActions[obj.GetName()] = availActionsForResource.Actions } var keys []string for key := range availableActions { keys = append(keys, key) } sort.Strings(keys) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintf(w, "RESOURCE\tACTION\n") fmt.Println() for key := range availableActions { for i := range availableActions[key] { action := availableActions[key][i] fmt.Fprintf(w, "%s\t%s\n", key, action.Name) } } _ = w.Flush() } command.Flags().StringVar(&resourceName, "resource-name", "", "Name of resource") command.Flags().StringVar(&kind, "kind", "", "Kind") err := command.MarkFlagRequired("kind") errors.CheckError(err) command.Flags().StringVar(&group, "group", "", "Group") command.Flags().StringVar(&namespace, "namespace", "", "Namespace") command.Flags().BoolVar(&all, "all", false, "Indicates whether to list actions on multiple matching resources") return command }
[ "func", "NewApplicationResourceActionsListCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "namespace", "string", "\n", "var", "kind", "string", "\n", "var", "group", "string", "\n", "var", "resourceName", "string", "\n", "var", "all", "bool", "\n", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "}", "\n", "command", ".", "Run", "=", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "1", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "appName", ":=", "args", "[", "0", "]", "\n", "conn", ",", "appIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewApplicationClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "resources", ",", "err", ":=", "appIf", ".", "ManagedResources", "(", "ctx", ",", "&", "application", ".", "ResourcesQuery", "{", "ApplicationName", ":", "&", "appName", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "filteredObjects", ":=", "filterResources", "(", "command", ",", "resources", ".", "Items", ",", "group", ",", "kind", ",", "namespace", ",", "resourceName", ",", "all", ")", "\n", "availableActions", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "argoappv1", ".", "ResourceAction", ")", "\n", "for", "i", ":=", "range", "filteredObjects", "{", "obj", ":=", "filteredObjects", "[", "i", "]", "\n", "gvk", ":=", "obj", ".", "GroupVersionKind", "(", ")", "\n", "availActionsForResource", ",", "err", ":=", "appIf", ".", "ListResourceActions", "(", "ctx", ",", "&", "application", ".", "ApplicationResourceRequest", "{", "Name", ":", "&", "appName", ",", "Namespace", ":", "obj", ".", "GetNamespace", "(", ")", ",", "ResourceName", ":", "obj", ".", "GetName", "(", ")", ",", "Group", ":", "gvk", ".", "Group", ",", "Kind", ":", "gvk", ".", "Kind", ",", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "availableActions", "[", "obj", ".", "GetName", "(", ")", "]", "=", "availActionsForResource", ".", "Actions", "\n", "}", "\n\n", "var", "keys", "[", "]", "string", "\n", "for", "key", ":=", "range", "availableActions", "{", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n\n", "w", ":=", "tabwriter", ".", "NewWriter", "(", "os", ".", "Stdout", ",", "0", ",", "0", ",", "2", ",", "' '", ",", "0", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\n", "\"", ")", "\n", "fmt", ".", "Println", "(", ")", "\n", "for", "key", ":=", "range", "availableActions", "{", "for", "i", ":=", "range", "availableActions", "[", "key", "]", "{", "action", ":=", "availableActions", "[", "key", "]", "[", "i", "]", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\n", "\"", ",", "key", ",", "action", ".", "Name", ")", "\n\n", "}", "\n", "}", "\n", "_", "=", "w", ".", "Flush", "(", ")", "\n", "}", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "resourceName", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "kind", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "err", ":=", "command", ".", "MarkFlagRequired", "(", "\"", "\"", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "group", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "namespace", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "command", ".", "Flags", "(", ")", ".", "BoolVar", "(", "&", "all", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n\n", "return", "command", "\n", "}" ]
// NewApplicationResourceActionsListCommand returns a new instance of an `argocd app actions list` command
[ "NewApplicationResourceActionsListCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "app", "actions", "list", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/app_actions.go#L35-L99
162,013
argoproj/argo-cd
cmd/argocd/commands/app_actions.go
NewApplicationResourceActionsRunCommand
func NewApplicationResourceActionsRunCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var namespace string var kind string var group string var resourceName string var all bool var command = &cobra.Command{ Use: "run APPNAME ACTION", Short: "Runs an available action on resource(s)", } command.Flags().StringVar(&resourceName, "resource-name", "", "Name of resource") command.Flags().StringVar(&kind, "kind", "", "Kind") err := command.MarkFlagRequired("kind") errors.CheckError(err) command.Flags().StringVar(&group, "group", "", "Group") command.Flags().StringVar(&namespace, "namespace", "", "Namespace") command.Flags().BoolVar(&all, "all", false, "Indicates whether to run the action on multiple matching resources") command.Run = func(c *cobra.Command, args []string) { if len(args) != 2 { c.HelpFunc()(c, args) os.Exit(1) } appName := args[0] actionName := args[1] conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie() defer util.Close(conn) ctx := context.Background() resources, err := appIf.ManagedResources(ctx, &application.ResourcesQuery{ApplicationName: &appName}) errors.CheckError(err) filteredObjects := filterResources(command, resources.Items, group, kind, namespace, resourceName, all) for i := range filteredObjects { obj := filteredObjects[i] gvk := obj.GroupVersionKind() objResourceName := obj.GetName() _, err := appIf.RunResourceAction(context.Background(), &application.ResourceActionRunRequest{ Name: &appName, Namespace: obj.GetNamespace(), ResourceName: objResourceName, Group: gvk.Group, Kind: gvk.Kind, Action: actionName, }) errors.CheckError(err) } } return command }
go
func NewApplicationResourceActionsRunCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var namespace string var kind string var group string var resourceName string var all bool var command = &cobra.Command{ Use: "run APPNAME ACTION", Short: "Runs an available action on resource(s)", } command.Flags().StringVar(&resourceName, "resource-name", "", "Name of resource") command.Flags().StringVar(&kind, "kind", "", "Kind") err := command.MarkFlagRequired("kind") errors.CheckError(err) command.Flags().StringVar(&group, "group", "", "Group") command.Flags().StringVar(&namespace, "namespace", "", "Namespace") command.Flags().BoolVar(&all, "all", false, "Indicates whether to run the action on multiple matching resources") command.Run = func(c *cobra.Command, args []string) { if len(args) != 2 { c.HelpFunc()(c, args) os.Exit(1) } appName := args[0] actionName := args[1] conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie() defer util.Close(conn) ctx := context.Background() resources, err := appIf.ManagedResources(ctx, &application.ResourcesQuery{ApplicationName: &appName}) errors.CheckError(err) filteredObjects := filterResources(command, resources.Items, group, kind, namespace, resourceName, all) for i := range filteredObjects { obj := filteredObjects[i] gvk := obj.GroupVersionKind() objResourceName := obj.GetName() _, err := appIf.RunResourceAction(context.Background(), &application.ResourceActionRunRequest{ Name: &appName, Namespace: obj.GetNamespace(), ResourceName: objResourceName, Group: gvk.Group, Kind: gvk.Kind, Action: actionName, }) errors.CheckError(err) } } return command }
[ "func", "NewApplicationResourceActionsRunCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "namespace", "string", "\n", "var", "kind", "string", "\n", "var", "group", "string", "\n", "var", "resourceName", "string", "\n", "var", "all", "bool", "\n", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "}", "\n\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "resourceName", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "kind", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "err", ":=", "command", ".", "MarkFlagRequired", "(", "\"", "\"", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "group", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "namespace", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "command", ".", "Flags", "(", ")", ".", "BoolVar", "(", "&", "all", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n\n", "command", ".", "Run", "=", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "appName", ":=", "args", "[", "0", "]", "\n", "actionName", ":=", "args", "[", "1", "]", "\n", "conn", ",", "appIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewApplicationClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "resources", ",", "err", ":=", "appIf", ".", "ManagedResources", "(", "ctx", ",", "&", "application", ".", "ResourcesQuery", "{", "ApplicationName", ":", "&", "appName", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "filteredObjects", ":=", "filterResources", "(", "command", ",", "resources", ".", "Items", ",", "group", ",", "kind", ",", "namespace", ",", "resourceName", ",", "all", ")", "\n", "for", "i", ":=", "range", "filteredObjects", "{", "obj", ":=", "filteredObjects", "[", "i", "]", "\n", "gvk", ":=", "obj", ".", "GroupVersionKind", "(", ")", "\n", "objResourceName", ":=", "obj", ".", "GetName", "(", ")", "\n", "_", ",", "err", ":=", "appIf", ".", "RunResourceAction", "(", "context", ".", "Background", "(", ")", ",", "&", "application", ".", "ResourceActionRunRequest", "{", "Name", ":", "&", "appName", ",", "Namespace", ":", "obj", ".", "GetNamespace", "(", ")", ",", "ResourceName", ":", "objResourceName", ",", "Group", ":", "gvk", ".", "Group", ",", "Kind", ":", "gvk", ".", "Kind", ",", "Action", ":", "actionName", ",", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "command", "\n", "}" ]
// NewApplicationResourceActionsRunCommand returns a new instance of an `argocd app actions run` command
[ "NewApplicationResourceActionsRunCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "app", "actions", "run", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/app_actions.go#L102-L150
162,014
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
HasIdentity
func (r SyncOperationResource) HasIdentity(name string, gvk schema.GroupVersionKind) bool { if name == r.Name && gvk.Kind == r.Kind && gvk.Group == r.Group { return true } return false }
go
func (r SyncOperationResource) HasIdentity(name string, gvk schema.GroupVersionKind) bool { if name == r.Name && gvk.Kind == r.Kind && gvk.Group == r.Group { return true } return false }
[ "func", "(", "r", "SyncOperationResource", ")", "HasIdentity", "(", "name", "string", ",", "gvk", "schema", ".", "GroupVersionKind", ")", "bool", "{", "if", "name", "==", "r", ".", "Name", "&&", "gvk", ".", "Kind", "==", "r", ".", "Kind", "&&", "gvk", ".", "Group", "==", "r", ".", "Group", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasIdentity determines whether a sync operation is identified by a manifest.
[ "HasIdentity", "determines", "whether", "a", "sync", "operation", "is", "identified", "by", "a", "manifest", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L245-L250
162,015
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
ProjectPoliciesString
func (proj *AppProject) ProjectPoliciesString() string { var policies []string for _, role := range proj.Spec.Roles { projectPolicy := fmt.Sprintf("p, proj:%s:%s, projects, get, %s, allow", proj.ObjectMeta.Name, role.Name, proj.ObjectMeta.Name) policies = append(policies, projectPolicy) policies = append(policies, role.Policies...) for _, groupName := range role.Groups { policies = append(policies, fmt.Sprintf("g, %s, proj:%s:%s", groupName, proj.ObjectMeta.Name, role.Name)) } } return strings.Join(policies, "\n") }
go
func (proj *AppProject) ProjectPoliciesString() string { var policies []string for _, role := range proj.Spec.Roles { projectPolicy := fmt.Sprintf("p, proj:%s:%s, projects, get, %s, allow", proj.ObjectMeta.Name, role.Name, proj.ObjectMeta.Name) policies = append(policies, projectPolicy) policies = append(policies, role.Policies...) for _, groupName := range role.Groups { policies = append(policies, fmt.Sprintf("g, %s, proj:%s:%s", groupName, proj.ObjectMeta.Name, role.Name)) } } return strings.Join(policies, "\n") }
[ "func", "(", "proj", "*", "AppProject", ")", "ProjectPoliciesString", "(", ")", "string", "{", "var", "policies", "[", "]", "string", "\n", "for", "_", ",", "role", ":=", "range", "proj", ".", "Spec", ".", "Roles", "{", "projectPolicy", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "proj", ".", "ObjectMeta", ".", "Name", ",", "role", ".", "Name", ",", "proj", ".", "ObjectMeta", ".", "Name", ")", "\n", "policies", "=", "append", "(", "policies", ",", "projectPolicy", ")", "\n", "policies", "=", "append", "(", "policies", ",", "role", ".", "Policies", "...", ")", "\n", "for", "_", ",", "groupName", ":=", "range", "role", ".", "Groups", "{", "policies", "=", "append", "(", "policies", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "groupName", ",", "proj", ".", "ObjectMeta", ".", "Name", ",", "role", ".", "Name", ")", ")", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "policies", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// ProjectPoliciesString returns Casbin formated string of a project's policies for each role
[ "ProjectPoliciesString", "returns", "Casbin", "formated", "string", "of", "a", "project", "s", "policies", "for", "each", "role" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L859-L870
162,016
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
SetCascadedDeletion
func (app *Application) SetCascadedDeletion(prune bool) { index := app.getFinalizerIndex(common.ResourcesFinalizerName) if prune != (index > -1) { if index > -1 { app.Finalizers[index] = app.Finalizers[len(app.Finalizers)-1] app.Finalizers = app.Finalizers[:len(app.Finalizers)-1] } else { app.Finalizers = append(app.Finalizers, common.ResourcesFinalizerName) } } }
go
func (app *Application) SetCascadedDeletion(prune bool) { index := app.getFinalizerIndex(common.ResourcesFinalizerName) if prune != (index > -1) { if index > -1 { app.Finalizers[index] = app.Finalizers[len(app.Finalizers)-1] app.Finalizers = app.Finalizers[:len(app.Finalizers)-1] } else { app.Finalizers = append(app.Finalizers, common.ResourcesFinalizerName) } } }
[ "func", "(", "app", "*", "Application", ")", "SetCascadedDeletion", "(", "prune", "bool", ")", "{", "index", ":=", "app", ".", "getFinalizerIndex", "(", "common", ".", "ResourcesFinalizerName", ")", "\n", "if", "prune", "!=", "(", "index", ">", "-", "1", ")", "{", "if", "index", ">", "-", "1", "{", "app", ".", "Finalizers", "[", "index", "]", "=", "app", ".", "Finalizers", "[", "len", "(", "app", ".", "Finalizers", ")", "-", "1", "]", "\n", "app", ".", "Finalizers", "=", "app", ".", "Finalizers", "[", ":", "len", "(", "app", ".", "Finalizers", ")", "-", "1", "]", "\n", "}", "else", "{", "app", ".", "Finalizers", "=", "append", "(", "app", ".", "Finalizers", ",", "common", ".", "ResourcesFinalizerName", ")", "\n", "}", "\n", "}", "\n", "}" ]
// SetCascadedDeletion sets or remove resources finalizer
[ "SetCascadedDeletion", "sets", "or", "remove", "resources", "finalizer" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L906-L916
162,017
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
GetErrorConditions
func (status *ApplicationStatus) GetErrorConditions() []ApplicationCondition { result := make([]ApplicationCondition, 0) for i := range status.Conditions { condition := status.Conditions[i] if condition.IsError() { result = append(result, condition) } } return result }
go
func (status *ApplicationStatus) GetErrorConditions() []ApplicationCondition { result := make([]ApplicationCondition, 0) for i := range status.Conditions { condition := status.Conditions[i] if condition.IsError() { result = append(result, condition) } } return result }
[ "func", "(", "status", "*", "ApplicationStatus", ")", "GetErrorConditions", "(", ")", "[", "]", "ApplicationCondition", "{", "result", ":=", "make", "(", "[", "]", "ApplicationCondition", ",", "0", ")", "\n", "for", "i", ":=", "range", "status", ".", "Conditions", "{", "condition", ":=", "status", ".", "Conditions", "[", "i", "]", "\n", "if", "condition", ".", "IsError", "(", ")", "{", "result", "=", "append", "(", "result", ",", "condition", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// GetErrorConditions returns list of application error conditions
[ "GetErrorConditions", "returns", "list", "of", "application", "error", "conditions" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L919-L928
162,018
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
Equals
func (source *ApplicationSource) Equals(other ApplicationSource) bool { return reflect.DeepEqual(*source, other) }
go
func (source *ApplicationSource) Equals(other ApplicationSource) bool { return reflect.DeepEqual(*source, other) }
[ "func", "(", "source", "*", "ApplicationSource", ")", "Equals", "(", "other", "ApplicationSource", ")", "bool", "{", "return", "reflect", ".", "DeepEqual", "(", "*", "source", ",", "other", ")", "\n", "}" ]
// Equals compares two instances of ApplicationSource and return true if instances are equal.
[ "Equals", "compares", "two", "instances", "of", "ApplicationSource", "and", "return", "true", "if", "instances", "are", "equal", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L936-L938
162,019
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
Equals
func (dest ApplicationDestination) Equals(other ApplicationDestination) bool { return reflect.DeepEqual(dest, other) }
go
func (dest ApplicationDestination) Equals(other ApplicationDestination) bool { return reflect.DeepEqual(dest, other) }
[ "func", "(", "dest", "ApplicationDestination", ")", "Equals", "(", "other", "ApplicationDestination", ")", "bool", "{", "return", "reflect", ".", "DeepEqual", "(", "dest", ",", "other", ")", "\n", "}" ]
// Equals compares two instances of ApplicationDestination and return true if instances are equal.
[ "Equals", "compares", "two", "instances", "of", "ApplicationDestination", "and", "return", "true", "if", "instances", "are", "equal", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L972-L974
162,020
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
GetProject
func (spec ApplicationSpec) GetProject() string { if spec.Project == "" { return common.DefaultAppProjectName } return spec.Project }
go
func (spec ApplicationSpec) GetProject() string { if spec.Project == "" { return common.DefaultAppProjectName } return spec.Project }
[ "func", "(", "spec", "ApplicationSpec", ")", "GetProject", "(", ")", "string", "{", "if", "spec", ".", "Project", "==", "\"", "\"", "{", "return", "common", ".", "DefaultAppProjectName", "\n", "}", "\n", "return", "spec", ".", "Project", "\n", "}" ]
// GetProject returns the application's project. This is preferred over spec.Project which may be empty
[ "GetProject", "returns", "the", "application", "s", "project", ".", "This", "is", "preferred", "over", "spec", ".", "Project", "which", "may", "be", "empty" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L977-L982
162,021
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
IsSourcePermitted
func (proj AppProject) IsSourcePermitted(src ApplicationSource) bool { srcNormalized := git.NormalizeGitURL(src.RepoURL) for _, repoURL := range proj.Spec.SourceRepos { normalized := git.NormalizeGitURL(repoURL) if globMatch(normalized, srcNormalized) { return true } } return false }
go
func (proj AppProject) IsSourcePermitted(src ApplicationSource) bool { srcNormalized := git.NormalizeGitURL(src.RepoURL) for _, repoURL := range proj.Spec.SourceRepos { normalized := git.NormalizeGitURL(repoURL) if globMatch(normalized, srcNormalized) { return true } } return false }
[ "func", "(", "proj", "AppProject", ")", "IsSourcePermitted", "(", "src", "ApplicationSource", ")", "bool", "{", "srcNormalized", ":=", "git", ".", "NormalizeGitURL", "(", "src", ".", "RepoURL", ")", "\n", "for", "_", ",", "repoURL", ":=", "range", "proj", ".", "Spec", ".", "SourceRepos", "{", "normalized", ":=", "git", ".", "NormalizeGitURL", "(", "repoURL", ")", "\n", "if", "globMatch", "(", "normalized", ",", "srcNormalized", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsSourcePermitted validates if the provided application's source is a one of the allowed sources for the project.
[ "IsSourcePermitted", "validates", "if", "the", "provided", "application", "s", "source", "is", "a", "one", "of", "the", "allowed", "sources", "for", "the", "project", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L1017-L1026
162,022
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
IsDestinationPermitted
func (proj AppProject) IsDestinationPermitted(dst ApplicationDestination) bool { for _, item := range proj.Spec.Destinations { if globMatch(item.Server, dst.Server) && globMatch(item.Namespace, dst.Namespace) { return true } } return false }
go
func (proj AppProject) IsDestinationPermitted(dst ApplicationDestination) bool { for _, item := range proj.Spec.Destinations { if globMatch(item.Server, dst.Server) && globMatch(item.Namespace, dst.Namespace) { return true } } return false }
[ "func", "(", "proj", "AppProject", ")", "IsDestinationPermitted", "(", "dst", "ApplicationDestination", ")", "bool", "{", "for", "_", ",", "item", ":=", "range", "proj", ".", "Spec", ".", "Destinations", "{", "if", "globMatch", "(", "item", ".", "Server", ",", "dst", ".", "Server", ")", "&&", "globMatch", "(", "item", ".", "Namespace", ",", "dst", ".", "Namespace", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsDestinationPermitted validates if the provided application's destination is one of the allowed destinations for the project
[ "IsDestinationPermitted", "validates", "if", "the", "provided", "application", "s", "destination", "is", "one", "of", "the", "allowed", "destinations", "for", "the", "project" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L1029-L1036
162,023
argoproj/argo-cd
pkg/apis/application/v1alpha1/types.go
RESTConfig
func (c *Cluster) RESTConfig() *rest.Config { var config *rest.Config var err error if c.Server == common.KubernetesInternalAPIServerAddr && os.Getenv(common.EnvVarFakeInClusterConfig) == "true" { config, err = clientcmd.BuildConfigFromFlags("", filepath.Join(os.Getenv("HOME"), ".kube", "config")) } else if c.Server == common.KubernetesInternalAPIServerAddr && c.Config.Username == "" && c.Config.Password == "" && c.Config.BearerToken == "" { config, err = rest.InClusterConfig() } else { tlsClientConfig := rest.TLSClientConfig{ Insecure: c.Config.TLSClientConfig.Insecure, ServerName: c.Config.TLSClientConfig.ServerName, CertData: c.Config.TLSClientConfig.CertData, KeyData: c.Config.TLSClientConfig.KeyData, CAData: c.Config.TLSClientConfig.CAData, } if c.Config.AWSAuthConfig != nil { args := []string{"token", "-i", c.Config.AWSAuthConfig.ClusterName} if c.Config.AWSAuthConfig.RoleARN != "" { args = append(args, "-r", c.Config.AWSAuthConfig.RoleARN) } config = &rest.Config{ Host: c.Server, TLSClientConfig: tlsClientConfig, ExecProvider: &api.ExecConfig{ APIVersion: "client.authentication.k8s.io/v1alpha1", Command: "aws-iam-authenticator", Args: args, }, } } else { config = &rest.Config{ Host: c.Server, Username: c.Config.Username, Password: c.Config.Password, BearerToken: c.Config.BearerToken, TLSClientConfig: tlsClientConfig, } } } if err != nil { panic("Unable to create K8s REST config") } config.QPS = common.K8sClientConfigQPS config.Burst = common.K8sClientConfigBurst return config }
go
func (c *Cluster) RESTConfig() *rest.Config { var config *rest.Config var err error if c.Server == common.KubernetesInternalAPIServerAddr && os.Getenv(common.EnvVarFakeInClusterConfig) == "true" { config, err = clientcmd.BuildConfigFromFlags("", filepath.Join(os.Getenv("HOME"), ".kube", "config")) } else if c.Server == common.KubernetesInternalAPIServerAddr && c.Config.Username == "" && c.Config.Password == "" && c.Config.BearerToken == "" { config, err = rest.InClusterConfig() } else { tlsClientConfig := rest.TLSClientConfig{ Insecure: c.Config.TLSClientConfig.Insecure, ServerName: c.Config.TLSClientConfig.ServerName, CertData: c.Config.TLSClientConfig.CertData, KeyData: c.Config.TLSClientConfig.KeyData, CAData: c.Config.TLSClientConfig.CAData, } if c.Config.AWSAuthConfig != nil { args := []string{"token", "-i", c.Config.AWSAuthConfig.ClusterName} if c.Config.AWSAuthConfig.RoleARN != "" { args = append(args, "-r", c.Config.AWSAuthConfig.RoleARN) } config = &rest.Config{ Host: c.Server, TLSClientConfig: tlsClientConfig, ExecProvider: &api.ExecConfig{ APIVersion: "client.authentication.k8s.io/v1alpha1", Command: "aws-iam-authenticator", Args: args, }, } } else { config = &rest.Config{ Host: c.Server, Username: c.Config.Username, Password: c.Config.Password, BearerToken: c.Config.BearerToken, TLSClientConfig: tlsClientConfig, } } } if err != nil { panic("Unable to create K8s REST config") } config.QPS = common.K8sClientConfigQPS config.Burst = common.K8sClientConfigBurst return config }
[ "func", "(", "c", "*", "Cluster", ")", "RESTConfig", "(", ")", "*", "rest", ".", "Config", "{", "var", "config", "*", "rest", ".", "Config", "\n", "var", "err", "error", "\n", "if", "c", ".", "Server", "==", "common", ".", "KubernetesInternalAPIServerAddr", "&&", "os", ".", "Getenv", "(", "common", ".", "EnvVarFakeInClusterConfig", ")", "==", "\"", "\"", "{", "config", ",", "err", "=", "clientcmd", ".", "BuildConfigFromFlags", "(", "\"", "\"", ",", "filepath", ".", "Join", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "}", "else", "if", "c", ".", "Server", "==", "common", ".", "KubernetesInternalAPIServerAddr", "&&", "c", ".", "Config", ".", "Username", "==", "\"", "\"", "&&", "c", ".", "Config", ".", "Password", "==", "\"", "\"", "&&", "c", ".", "Config", ".", "BearerToken", "==", "\"", "\"", "{", "config", ",", "err", "=", "rest", ".", "InClusterConfig", "(", ")", "\n", "}", "else", "{", "tlsClientConfig", ":=", "rest", ".", "TLSClientConfig", "{", "Insecure", ":", "c", ".", "Config", ".", "TLSClientConfig", ".", "Insecure", ",", "ServerName", ":", "c", ".", "Config", ".", "TLSClientConfig", ".", "ServerName", ",", "CertData", ":", "c", ".", "Config", ".", "TLSClientConfig", ".", "CertData", ",", "KeyData", ":", "c", ".", "Config", ".", "TLSClientConfig", ".", "KeyData", ",", "CAData", ":", "c", ".", "Config", ".", "TLSClientConfig", ".", "CAData", ",", "}", "\n", "if", "c", ".", "Config", ".", "AWSAuthConfig", "!=", "nil", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "c", ".", "Config", ".", "AWSAuthConfig", ".", "ClusterName", "}", "\n", "if", "c", ".", "Config", ".", "AWSAuthConfig", ".", "RoleARN", "!=", "\"", "\"", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "c", ".", "Config", ".", "AWSAuthConfig", ".", "RoleARN", ")", "\n", "}", "\n", "config", "=", "&", "rest", ".", "Config", "{", "Host", ":", "c", ".", "Server", ",", "TLSClientConfig", ":", "tlsClientConfig", ",", "ExecProvider", ":", "&", "api", ".", "ExecConfig", "{", "APIVersion", ":", "\"", "\"", ",", "Command", ":", "\"", "\"", ",", "Args", ":", "args", ",", "}", ",", "}", "\n", "}", "else", "{", "config", "=", "&", "rest", ".", "Config", "{", "Host", ":", "c", ".", "Server", ",", "Username", ":", "c", ".", "Config", ".", "Username", ",", "Password", ":", "c", ".", "Config", ".", "Password", ",", "BearerToken", ":", "c", ".", "Config", ".", "BearerToken", ",", "TLSClientConfig", ":", "tlsClientConfig", ",", "}", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "config", ".", "QPS", "=", "common", ".", "K8sClientConfigQPS", "\n", "config", ".", "Burst", "=", "common", ".", "K8sClientConfigBurst", "\n", "return", "config", "\n", "}" ]
// RESTConfig returns a go-client REST config from cluster
[ "RESTConfig", "returns", "a", "go", "-", "client", "REST", "config", "from", "cluster" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apis/application/v1alpha1/types.go#L1039-L1084
162,024
argoproj/argo-cd
util/session/sessionmanager.go
NewSessionManager
func NewSessionManager(settingsMgr *settings.SettingsManager, dexServerAddr string) *SessionManager { s := SessionManager{ settingsMgr: settingsMgr, } settings, err := settingsMgr.GetSettings() if err != nil { panic(err) } tlsConfig := settings.TLSConfig() if tlsConfig != nil { tlsConfig.InsecureSkipVerify = true } s.client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, } if settings.DexConfig != "" { s.client.Transport = dex.NewDexRewriteURLRoundTripper(dexServerAddr, s.client.Transport) } if os.Getenv(common.EnvVarSSODebug) == "1" { s.client.Transport = httputil.DebugTransport{T: s.client.Transport} } return &s }
go
func NewSessionManager(settingsMgr *settings.SettingsManager, dexServerAddr string) *SessionManager { s := SessionManager{ settingsMgr: settingsMgr, } settings, err := settingsMgr.GetSettings() if err != nil { panic(err) } tlsConfig := settings.TLSConfig() if tlsConfig != nil { tlsConfig.InsecureSkipVerify = true } s.client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, } if settings.DexConfig != "" { s.client.Transport = dex.NewDexRewriteURLRoundTripper(dexServerAddr, s.client.Transport) } if os.Getenv(common.EnvVarSSODebug) == "1" { s.client.Transport = httputil.DebugTransport{T: s.client.Transport} } return &s }
[ "func", "NewSessionManager", "(", "settingsMgr", "*", "settings", ".", "SettingsManager", ",", "dexServerAddr", "string", ")", "*", "SessionManager", "{", "s", ":=", "SessionManager", "{", "settingsMgr", ":", "settingsMgr", ",", "}", "\n", "settings", ",", "err", ":=", "settingsMgr", ".", "GetSettings", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "tlsConfig", ":=", "settings", ".", "TLSConfig", "(", ")", "\n", "if", "tlsConfig", "!=", "nil", "{", "tlsConfig", ".", "InsecureSkipVerify", "=", "true", "\n", "}", "\n", "s", ".", "client", "=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "tlsConfig", ",", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "Dial", ":", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "}", ")", ".", "Dial", ",", "TLSHandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "ExpectContinueTimeout", ":", "1", "*", "time", ".", "Second", ",", "}", ",", "}", "\n", "if", "settings", ".", "DexConfig", "!=", "\"", "\"", "{", "s", ".", "client", ".", "Transport", "=", "dex", ".", "NewDexRewriteURLRoundTripper", "(", "dexServerAddr", ",", "s", ".", "client", ".", "Transport", ")", "\n", "}", "\n", "if", "os", ".", "Getenv", "(", "common", ".", "EnvVarSSODebug", ")", "==", "\"", "\"", "{", "s", ".", "client", ".", "Transport", "=", "httputil", ".", "DebugTransport", "{", "T", ":", "s", ".", "client", ".", "Transport", "}", "\n", "}", "\n", "return", "&", "s", "\n", "}" ]
// NewSessionManager creates a new session manager from Argo CD settings
[ "NewSessionManager", "creates", "a", "new", "session", "manager", "from", "Argo", "CD", "settings" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/session/sessionmanager.go#L43-L74
162,025
argoproj/argo-cd
util/session/sessionmanager.go
Parse
func (mgr *SessionManager) Parse(tokenString string) (jwt.Claims, error) { // Parse takes the token string and a function for looking up the key. The latter is especially // useful if you use multiple keys for your application. The standard is to use 'kid' in the // head of the token to identify which key to use, but the parsed token (head and claims) is provided // to the callback, providing flexibility. var claims jwt.MapClaims settings, err := mgr.settingsMgr.GetSettings() if err != nil { return nil, err } token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) { // Don't forget to validate the alg is what you expect: if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return settings.ServerSignature, nil }) if err != nil { return nil, err } issuedAt := time.Unix(int64(claims["iat"].(float64)), 0) if issuedAt.Before(settings.AdminPasswordMtime) { return nil, fmt.Errorf("Password for superuser has changed since token issued") } return token.Claims, nil }
go
func (mgr *SessionManager) Parse(tokenString string) (jwt.Claims, error) { // Parse takes the token string and a function for looking up the key. The latter is especially // useful if you use multiple keys for your application. The standard is to use 'kid' in the // head of the token to identify which key to use, but the parsed token (head and claims) is provided // to the callback, providing flexibility. var claims jwt.MapClaims settings, err := mgr.settingsMgr.GetSettings() if err != nil { return nil, err } token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) { // Don't forget to validate the alg is what you expect: if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return settings.ServerSignature, nil }) if err != nil { return nil, err } issuedAt := time.Unix(int64(claims["iat"].(float64)), 0) if issuedAt.Before(settings.AdminPasswordMtime) { return nil, fmt.Errorf("Password for superuser has changed since token issued") } return token.Claims, nil }
[ "func", "(", "mgr", "*", "SessionManager", ")", "Parse", "(", "tokenString", "string", ")", "(", "jwt", ".", "Claims", ",", "error", ")", "{", "// Parse takes the token string and a function for looking up the key. The latter is especially", "// useful if you use multiple keys for your application. The standard is to use 'kid' in the", "// head of the token to identify which key to use, but the parsed token (head and claims) is provided", "// to the callback, providing flexibility.", "var", "claims", "jwt", ".", "MapClaims", "\n", "settings", ",", "err", ":=", "mgr", ".", "settingsMgr", ".", "GetSettings", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "token", ",", "err", ":=", "jwt", ".", "ParseWithClaims", "(", "tokenString", ",", "&", "claims", ",", "func", "(", "token", "*", "jwt", ".", "Token", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// Don't forget to validate the alg is what you expect:", "if", "_", ",", "ok", ":=", "token", ".", "Method", ".", "(", "*", "jwt", ".", "SigningMethodHMAC", ")", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ".", "Header", "[", "\"", "\"", "]", ")", "\n", "}", "\n", "return", "settings", ".", "ServerSignature", ",", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "issuedAt", ":=", "time", ".", "Unix", "(", "int64", "(", "claims", "[", "\"", "\"", "]", ".", "(", "float64", ")", ")", ",", "0", ")", "\n", "if", "issuedAt", ".", "Before", "(", "settings", ".", "AdminPasswordMtime", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "token", ".", "Claims", ",", "nil", "\n", "}" ]
// Parse tries to parse the provided string and returns the token claims for local superuser login.
[ "Parse", "tries", "to", "parse", "the", "provided", "string", "and", "returns", "the", "token", "claims", "for", "local", "superuser", "login", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/session/sessionmanager.go#L107-L133
162,026
argoproj/argo-cd
util/session/sessionmanager.go
VerifyToken
func (mgr *SessionManager) VerifyToken(tokenString string) (jwt.Claims, error) { parser := &jwt.Parser{ SkipClaimsValidation: true, } var claims jwt.StandardClaims _, _, err := parser.ParseUnverified(tokenString, &claims) if err != nil { return nil, err } switch claims.Issuer { case SessionManagerClaimsIssuer: // Argo CD signed token return mgr.Parse(tokenString) default: // IDP signed token prov, err := mgr.provider() if err != nil { return nil, err } idToken, err := prov.Verify(claims.Audience, tokenString) if err != nil { return nil, err } var claims jwt.MapClaims err = idToken.Claims(&claims) return claims, err } }
go
func (mgr *SessionManager) VerifyToken(tokenString string) (jwt.Claims, error) { parser := &jwt.Parser{ SkipClaimsValidation: true, } var claims jwt.StandardClaims _, _, err := parser.ParseUnverified(tokenString, &claims) if err != nil { return nil, err } switch claims.Issuer { case SessionManagerClaimsIssuer: // Argo CD signed token return mgr.Parse(tokenString) default: // IDP signed token prov, err := mgr.provider() if err != nil { return nil, err } idToken, err := prov.Verify(claims.Audience, tokenString) if err != nil { return nil, err } var claims jwt.MapClaims err = idToken.Claims(&claims) return claims, err } }
[ "func", "(", "mgr", "*", "SessionManager", ")", "VerifyToken", "(", "tokenString", "string", ")", "(", "jwt", ".", "Claims", ",", "error", ")", "{", "parser", ":=", "&", "jwt", ".", "Parser", "{", "SkipClaimsValidation", ":", "true", ",", "}", "\n", "var", "claims", "jwt", ".", "StandardClaims", "\n", "_", ",", "_", ",", "err", ":=", "parser", ".", "ParseUnverified", "(", "tokenString", ",", "&", "claims", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "switch", "claims", ".", "Issuer", "{", "case", "SessionManagerClaimsIssuer", ":", "// Argo CD signed token", "return", "mgr", ".", "Parse", "(", "tokenString", ")", "\n", "default", ":", "// IDP signed token", "prov", ",", "err", ":=", "mgr", ".", "provider", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "idToken", ",", "err", ":=", "prov", ".", "Verify", "(", "claims", ".", "Audience", ",", "tokenString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "claims", "jwt", ".", "MapClaims", "\n", "err", "=", "idToken", ".", "Claims", "(", "&", "claims", ")", "\n", "return", "claims", ",", "err", "\n", "}", "\n", "}" ]
// VerifyToken verifies if a token is correct. Tokens can be issued either from us or by an IDP. // We choose how to verify based on the issuer.
[ "VerifyToken", "verifies", "if", "a", "token", "is", "correct", ".", "Tokens", "can", "be", "issued", "either", "from", "us", "or", "by", "an", "IDP", ".", "We", "choose", "how", "to", "verify", "based", "on", "the", "issuer", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/session/sessionmanager.go#L156-L183
162,027
argoproj/argo-cd
util/session/sessionmanager.go
Username
func Username(ctx context.Context) string { claims, ok := ctx.Value("claims").(jwt.Claims) if !ok { return "" } mapClaims, err := jwtutil.MapClaims(claims) if err != nil { return "" } switch jwtutil.GetField(mapClaims, "iss") { case SessionManagerClaimsIssuer: return jwtutil.GetField(mapClaims, "sub") default: return jwtutil.GetField(mapClaims, "email") } }
go
func Username(ctx context.Context) string { claims, ok := ctx.Value("claims").(jwt.Claims) if !ok { return "" } mapClaims, err := jwtutil.MapClaims(claims) if err != nil { return "" } switch jwtutil.GetField(mapClaims, "iss") { case SessionManagerClaimsIssuer: return jwtutil.GetField(mapClaims, "sub") default: return jwtutil.GetField(mapClaims, "email") } }
[ "func", "Username", "(", "ctx", "context", ".", "Context", ")", "string", "{", "claims", ",", "ok", ":=", "ctx", ".", "Value", "(", "\"", "\"", ")", ".", "(", "jwt", ".", "Claims", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", "\n", "}", "\n", "mapClaims", ",", "err", ":=", "jwtutil", ".", "MapClaims", "(", "claims", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "switch", "jwtutil", ".", "GetField", "(", "mapClaims", ",", "\"", "\"", ")", "{", "case", "SessionManagerClaimsIssuer", ":", "return", "jwtutil", ".", "GetField", "(", "mapClaims", ",", "\"", "\"", ")", "\n", "default", ":", "return", "jwtutil", ".", "GetField", "(", "mapClaims", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Username is a helper to extract a human readable username from a context
[ "Username", "is", "a", "helper", "to", "extract", "a", "human", "readable", "username", "from", "a", "context" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/session/sessionmanager.go#L201-L216
162,028
argoproj/argo-cd
util/grpc/grpc.go
PanicLoggerUnaryServerInterceptor
func PanicLoggerUnaryServerInterceptor(log *logrus.Entry) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) err = status.Errorf(codes.Internal, "%s", r) } }() return handler(ctx, req) } }
go
func PanicLoggerUnaryServerInterceptor(log *logrus.Entry) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) err = status.Errorf(codes.Internal, "%s", r) } }() return handler(ctx, req) } }
[ "func", "PanicLoggerUnaryServerInterceptor", "(", "log", "*", "logrus", ".", "Entry", ")", "grpc", ".", "UnaryServerInterceptor", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "_", "interface", "{", "}", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "r", ",", "debug", ".", "Stack", "(", ")", ")", "\n", "err", "=", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "handler", "(", "ctx", ",", "req", ")", "\n", "}", "\n", "}" ]
// PanicLoggerUnaryServerInterceptor returns a new unary server interceptor for recovering from panics and returning error
[ "PanicLoggerUnaryServerInterceptor", "returns", "a", "new", "unary", "server", "interceptor", "for", "recovering", "from", "panics", "and", "returning", "error" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/grpc/grpc.go#L19-L29
162,029
argoproj/argo-cd
util/grpc/grpc.go
PanicLoggerStreamServerInterceptor
func PanicLoggerStreamServerInterceptor(log *logrus.Entry) grpc.StreamServerInterceptor { return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) err = status.Errorf(codes.Internal, "%s", r) } }() return handler(srv, stream) } }
go
func PanicLoggerStreamServerInterceptor(log *logrus.Entry) grpc.StreamServerInterceptor { return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { defer func() { if r := recover(); r != nil { log.Errorf("Recovered from panic: %+v\n%s", r, debug.Stack()) err = status.Errorf(codes.Internal, "%s", r) } }() return handler(srv, stream) } }
[ "func", "PanicLoggerStreamServerInterceptor", "(", "log", "*", "logrus", ".", "Entry", ")", "grpc", ".", "StreamServerInterceptor", "{", "return", "func", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "r", ",", "debug", ".", "Stack", "(", ")", ")", "\n", "err", "=", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "handler", "(", "srv", ",", "stream", ")", "\n", "}", "\n", "}" ]
// PanicLoggerStreamServerInterceptor returns a new streaming server interceptor for recovering from panics and returning error
[ "PanicLoggerStreamServerInterceptor", "returns", "a", "new", "streaming", "server", "interceptor", "for", "recovering", "from", "panics", "and", "returning", "error" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/grpc/grpc.go#L32-L42
162,030
argoproj/argo-cd
util/grpc/useragent.go
UserAgentUnaryServerInterceptor
func UserAgentUnaryServerInterceptor(clientName, constraintStr string) grpc.UnaryServerInterceptor { userAgentEnforcer := newUserAgentEnforcer(clientName, constraintStr) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if err := userAgentEnforcer(ctx); err != nil { return nil, err } return handler(ctx, req) } }
go
func UserAgentUnaryServerInterceptor(clientName, constraintStr string) grpc.UnaryServerInterceptor { userAgentEnforcer := newUserAgentEnforcer(clientName, constraintStr) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if err := userAgentEnforcer(ctx); err != nil { return nil, err } return handler(ctx, req) } }
[ "func", "UserAgentUnaryServerInterceptor", "(", "clientName", ",", "constraintStr", "string", ")", "grpc", ".", "UnaryServerInterceptor", "{", "userAgentEnforcer", ":=", "newUserAgentEnforcer", "(", "clientName", ",", "constraintStr", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "err", ":=", "userAgentEnforcer", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "handler", "(", "ctx", ",", "req", ")", "\n", "}", "\n", "}" ]
// UserAgentUnaryServerInterceptor returns a UnaryServerInterceptor which enforces a minimum client // version in the user agent
[ "UserAgentUnaryServerInterceptor", "returns", "a", "UnaryServerInterceptor", "which", "enforces", "a", "minimum", "client", "version", "in", "the", "user", "agent" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/grpc/useragent.go#L16-L24
162,031
argoproj/argo-cd
util/grpc/useragent.go
UserAgentStreamServerInterceptor
func UserAgentStreamServerInterceptor(clientName, constraintStr string) grpc.StreamServerInterceptor { userAgentEnforcer := newUserAgentEnforcer(clientName, constraintStr) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := userAgentEnforcer(stream.Context()); err != nil { return err } return handler(srv, stream) } }
go
func UserAgentStreamServerInterceptor(clientName, constraintStr string) grpc.StreamServerInterceptor { userAgentEnforcer := newUserAgentEnforcer(clientName, constraintStr) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := userAgentEnforcer(stream.Context()); err != nil { return err } return handler(srv, stream) } }
[ "func", "UserAgentStreamServerInterceptor", "(", "clientName", ",", "constraintStr", "string", ")", "grpc", ".", "StreamServerInterceptor", "{", "userAgentEnforcer", ":=", "newUserAgentEnforcer", "(", "clientName", ",", "constraintStr", ")", "\n", "return", "func", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "error", "{", "if", "err", ":=", "userAgentEnforcer", "(", "stream", ".", "Context", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "handler", "(", "srv", ",", "stream", ")", "\n", "}", "\n", "}" ]
// UserAgentStreamServerInterceptor returns a StreamServerInterceptor which enforces a minimum client // version in the user agent
[ "UserAgentStreamServerInterceptor", "returns", "a", "StreamServerInterceptor", "which", "enforces", "a", "minimum", "client", "version", "in", "the", "user", "agent" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/grpc/useragent.go#L28-L36
162,032
argoproj/argo-cd
controller/sync_hooks.go
verifyPermittedHooks
func (sc *syncContext) verifyPermittedHooks(hooks []*unstructured.Unstructured) bool { for _, hook := range hooks { gvk := hook.GroupVersionKind() serverRes, err := kube.ServerResourceForGroupVersionKind(sc.disco, gvk) if err != nil { sc.setOperationPhase(appv1.OperationError, fmt.Sprintf("unable to identify api resource type: %v", gvk)) return false } if !sc.proj.IsResourcePermitted(metav1.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, serverRes.Namespaced) { sc.setOperationPhase(appv1.OperationFailed, fmt.Sprintf("Hook resource %s:%s is not permitted in project %s", gvk.Group, gvk.Kind, sc.proj.Name)) return false } if serverRes.Namespaced && !sc.proj.IsDestinationPermitted(appv1.ApplicationDestination{Namespace: hook.GetNamespace(), Server: sc.server}) { gvk := hook.GroupVersionKind() sc.setResourceDetails(&appv1.ResourceResult{ Name: hook.GetName(), Group: gvk.Group, Version: gvk.Version, Kind: hook.GetKind(), Namespace: hook.GetNamespace(), Message: fmt.Sprintf("namespace %v is not permitted in project '%s'", hook.GetNamespace(), sc.proj.Name), Status: appv1.ResultCodeSyncFailed, }) return false } } return true }
go
func (sc *syncContext) verifyPermittedHooks(hooks []*unstructured.Unstructured) bool { for _, hook := range hooks { gvk := hook.GroupVersionKind() serverRes, err := kube.ServerResourceForGroupVersionKind(sc.disco, gvk) if err != nil { sc.setOperationPhase(appv1.OperationError, fmt.Sprintf("unable to identify api resource type: %v", gvk)) return false } if !sc.proj.IsResourcePermitted(metav1.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, serverRes.Namespaced) { sc.setOperationPhase(appv1.OperationFailed, fmt.Sprintf("Hook resource %s:%s is not permitted in project %s", gvk.Group, gvk.Kind, sc.proj.Name)) return false } if serverRes.Namespaced && !sc.proj.IsDestinationPermitted(appv1.ApplicationDestination{Namespace: hook.GetNamespace(), Server: sc.server}) { gvk := hook.GroupVersionKind() sc.setResourceDetails(&appv1.ResourceResult{ Name: hook.GetName(), Group: gvk.Group, Version: gvk.Version, Kind: hook.GetKind(), Namespace: hook.GetNamespace(), Message: fmt.Sprintf("namespace %v is not permitted in project '%s'", hook.GetNamespace(), sc.proj.Name), Status: appv1.ResultCodeSyncFailed, }) return false } } return true }
[ "func", "(", "sc", "*", "syncContext", ")", "verifyPermittedHooks", "(", "hooks", "[", "]", "*", "unstructured", ".", "Unstructured", ")", "bool", "{", "for", "_", ",", "hook", ":=", "range", "hooks", "{", "gvk", ":=", "hook", ".", "GroupVersionKind", "(", ")", "\n", "serverRes", ",", "err", ":=", "kube", ".", "ServerResourceForGroupVersionKind", "(", "sc", ".", "disco", ",", "gvk", ")", "\n", "if", "err", "!=", "nil", "{", "sc", ".", "setOperationPhase", "(", "appv1", ".", "OperationError", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "gvk", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "!", "sc", ".", "proj", ".", "IsResourcePermitted", "(", "metav1", ".", "GroupKind", "{", "Group", ":", "gvk", ".", "Group", ",", "Kind", ":", "gvk", ".", "Kind", "}", ",", "serverRes", ".", "Namespaced", ")", "{", "sc", ".", "setOperationPhase", "(", "appv1", ".", "OperationFailed", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "gvk", ".", "Group", ",", "gvk", ".", "Kind", ",", "sc", ".", "proj", ".", "Name", ")", ")", "\n", "return", "false", "\n", "}", "\n\n", "if", "serverRes", ".", "Namespaced", "&&", "!", "sc", ".", "proj", ".", "IsDestinationPermitted", "(", "appv1", ".", "ApplicationDestination", "{", "Namespace", ":", "hook", ".", "GetNamespace", "(", ")", ",", "Server", ":", "sc", ".", "server", "}", ")", "{", "gvk", ":=", "hook", ".", "GroupVersionKind", "(", ")", "\n", "sc", ".", "setResourceDetails", "(", "&", "appv1", ".", "ResourceResult", "{", "Name", ":", "hook", ".", "GetName", "(", ")", ",", "Group", ":", "gvk", ".", "Group", ",", "Version", ":", "gvk", ".", "Version", ",", "Kind", ":", "hook", ".", "GetKind", "(", ")", ",", "Namespace", ":", "hook", ".", "GetNamespace", "(", ")", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hook", ".", "GetNamespace", "(", ")", ",", "sc", ".", "proj", ".", "Name", ")", ",", "Status", ":", "appv1", ".", "ResultCodeSyncFailed", ",", "}", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// verifyPermittedHooks verifies all hooks are permitted in the project
[ "verifyPermittedHooks", "verifies", "all", "hooks", "are", "permitted", "in", "the", "project" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L76-L104
162,033
argoproj/argo-cd
controller/sync_hooks.go
runHooks
func (sc *syncContext) runHooks(hooks []*unstructured.Unstructured, hookType appv1.HookType) bool { shouldContinue := true for _, hook := range hooks { if hookType == appv1.HookTypeSync && isHookType(hook, appv1.HookTypeSkip) { // If we get here, we are invoking all sync hooks and reached a resource that is // annotated with the Skip hook. This will update the resource details to indicate it // was skipped due to annotation gvk := hook.GroupVersionKind() sc.setResourceDetails(&appv1.ResourceResult{ Name: hook.GetName(), Group: gvk.Group, Version: gvk.Version, Kind: hook.GetKind(), Namespace: hook.GetNamespace(), Message: "Skipped", }) continue } if !isHookType(hook, hookType) { continue } updated, err := sc.runHook(hook, hookType) if err != nil { sc.setOperationPhase(appv1.OperationError, fmt.Sprintf("%s hook error: %v", hookType, err)) return false } if updated { // If the result of running a hook, caused us to modify hook resource state, we should // not proceed to the next hook phase. This is because before proceeding to the next // phase, we want a full health assessment to happen. By returning early, we allow // the application to get requeued into the controller workqueue, and on the next // process iteration, a new CompareAppState() will be performed to get the most // up-to-date live state. This enables us to accurately wait for an application to // become Healthy before proceeding to run PostSync tasks. shouldContinue = false } } if !shouldContinue { sc.log.Infof("Stopping after %s phase due to modifications to hook resource state", hookType) return false } completed, successful := areHooksCompletedSuccessful(hookType, sc.syncRes.Resources) if !completed { return false } if !successful { sc.setOperationPhase(appv1.OperationFailed, fmt.Sprintf("%s hook failed", hookType)) return false } return true }
go
func (sc *syncContext) runHooks(hooks []*unstructured.Unstructured, hookType appv1.HookType) bool { shouldContinue := true for _, hook := range hooks { if hookType == appv1.HookTypeSync && isHookType(hook, appv1.HookTypeSkip) { // If we get here, we are invoking all sync hooks and reached a resource that is // annotated with the Skip hook. This will update the resource details to indicate it // was skipped due to annotation gvk := hook.GroupVersionKind() sc.setResourceDetails(&appv1.ResourceResult{ Name: hook.GetName(), Group: gvk.Group, Version: gvk.Version, Kind: hook.GetKind(), Namespace: hook.GetNamespace(), Message: "Skipped", }) continue } if !isHookType(hook, hookType) { continue } updated, err := sc.runHook(hook, hookType) if err != nil { sc.setOperationPhase(appv1.OperationError, fmt.Sprintf("%s hook error: %v", hookType, err)) return false } if updated { // If the result of running a hook, caused us to modify hook resource state, we should // not proceed to the next hook phase. This is because before proceeding to the next // phase, we want a full health assessment to happen. By returning early, we allow // the application to get requeued into the controller workqueue, and on the next // process iteration, a new CompareAppState() will be performed to get the most // up-to-date live state. This enables us to accurately wait for an application to // become Healthy before proceeding to run PostSync tasks. shouldContinue = false } } if !shouldContinue { sc.log.Infof("Stopping after %s phase due to modifications to hook resource state", hookType) return false } completed, successful := areHooksCompletedSuccessful(hookType, sc.syncRes.Resources) if !completed { return false } if !successful { sc.setOperationPhase(appv1.OperationFailed, fmt.Sprintf("%s hook failed", hookType)) return false } return true }
[ "func", "(", "sc", "*", "syncContext", ")", "runHooks", "(", "hooks", "[", "]", "*", "unstructured", ".", "Unstructured", ",", "hookType", "appv1", ".", "HookType", ")", "bool", "{", "shouldContinue", ":=", "true", "\n", "for", "_", ",", "hook", ":=", "range", "hooks", "{", "if", "hookType", "==", "appv1", ".", "HookTypeSync", "&&", "isHookType", "(", "hook", ",", "appv1", ".", "HookTypeSkip", ")", "{", "// If we get here, we are invoking all sync hooks and reached a resource that is", "// annotated with the Skip hook. This will update the resource details to indicate it", "// was skipped due to annotation", "gvk", ":=", "hook", ".", "GroupVersionKind", "(", ")", "\n", "sc", ".", "setResourceDetails", "(", "&", "appv1", ".", "ResourceResult", "{", "Name", ":", "hook", ".", "GetName", "(", ")", ",", "Group", ":", "gvk", ".", "Group", ",", "Version", ":", "gvk", ".", "Version", ",", "Kind", ":", "hook", ".", "GetKind", "(", ")", ",", "Namespace", ":", "hook", ".", "GetNamespace", "(", ")", ",", "Message", ":", "\"", "\"", ",", "}", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "isHookType", "(", "hook", ",", "hookType", ")", "{", "continue", "\n", "}", "\n", "updated", ",", "err", ":=", "sc", ".", "runHook", "(", "hook", ",", "hookType", ")", "\n", "if", "err", "!=", "nil", "{", "sc", ".", "setOperationPhase", "(", "appv1", ".", "OperationError", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hookType", ",", "err", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "updated", "{", "// If the result of running a hook, caused us to modify hook resource state, we should", "// not proceed to the next hook phase. This is because before proceeding to the next", "// phase, we want a full health assessment to happen. By returning early, we allow", "// the application to get requeued into the controller workqueue, and on the next", "// process iteration, a new CompareAppState() will be performed to get the most", "// up-to-date live state. This enables us to accurately wait for an application to", "// become Healthy before proceeding to run PostSync tasks.", "shouldContinue", "=", "false", "\n", "}", "\n", "}", "\n", "if", "!", "shouldContinue", "{", "sc", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "hookType", ")", "\n", "return", "false", "\n", "}", "\n", "completed", ",", "successful", ":=", "areHooksCompletedSuccessful", "(", "hookType", ",", "sc", ".", "syncRes", ".", "Resources", ")", "\n", "if", "!", "completed", "{", "return", "false", "\n", "}", "\n", "if", "!", "successful", "{", "sc", ".", "setOperationPhase", "(", "appv1", ".", "OperationFailed", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hookType", ")", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// runHooks iterates & filters the target manifests for resources of the specified hook type, then // creates the resource. Updates the sc.opRes.hooks with the current status. Returns whether or not // we should continue to the next hook phase.
[ "runHooks", "iterates", "&", "filters", "the", "target", "manifests", "for", "resources", "of", "the", "specified", "hook", "type", "then", "creates", "the", "resource", ".", "Updates", "the", "sc", ".", "opRes", ".", "hooks", "with", "the", "current", "status", ".", "Returns", "whether", "or", "not", "we", "should", "continue", "to", "the", "next", "hook", "phase", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L138-L188
162,034
argoproj/argo-cd
controller/sync_hooks.go
syncNonHookTasks
func (sc *syncContext) syncNonHookTasks(syncTasks []syncTask) bool { var nonHookTasks []syncTask for _, task := range syncTasks { if task.targetObj == nil { nonHookTasks = append(nonHookTasks, task) } else { annotations := task.targetObj.GetAnnotations() if annotations != nil && annotations[common.AnnotationKeyHook] != "" { // we are doing a hook sync and this resource is annotated with a hook annotation continue } // if we get here, this resource does not have any hook annotation so we // should perform an `kubectl apply` nonHookTasks = append(nonHookTasks, task) } } return sc.doApplySync(nonHookTasks, false, sc.syncOp.SyncStrategy.Hook.Force, true) }
go
func (sc *syncContext) syncNonHookTasks(syncTasks []syncTask) bool { var nonHookTasks []syncTask for _, task := range syncTasks { if task.targetObj == nil { nonHookTasks = append(nonHookTasks, task) } else { annotations := task.targetObj.GetAnnotations() if annotations != nil && annotations[common.AnnotationKeyHook] != "" { // we are doing a hook sync and this resource is annotated with a hook annotation continue } // if we get here, this resource does not have any hook annotation so we // should perform an `kubectl apply` nonHookTasks = append(nonHookTasks, task) } } return sc.doApplySync(nonHookTasks, false, sc.syncOp.SyncStrategy.Hook.Force, true) }
[ "func", "(", "sc", "*", "syncContext", ")", "syncNonHookTasks", "(", "syncTasks", "[", "]", "syncTask", ")", "bool", "{", "var", "nonHookTasks", "[", "]", "syncTask", "\n", "for", "_", ",", "task", ":=", "range", "syncTasks", "{", "if", "task", ".", "targetObj", "==", "nil", "{", "nonHookTasks", "=", "append", "(", "nonHookTasks", ",", "task", ")", "\n", "}", "else", "{", "annotations", ":=", "task", ".", "targetObj", ".", "GetAnnotations", "(", ")", "\n", "if", "annotations", "!=", "nil", "&&", "annotations", "[", "common", ".", "AnnotationKeyHook", "]", "!=", "\"", "\"", "{", "// we are doing a hook sync and this resource is annotated with a hook annotation", "continue", "\n", "}", "\n", "// if we get here, this resource does not have any hook annotation so we", "// should perform an `kubectl apply`", "nonHookTasks", "=", "append", "(", "nonHookTasks", ",", "task", ")", "\n", "}", "\n", "}", "\n", "return", "sc", ".", "doApplySync", "(", "nonHookTasks", ",", "false", ",", "sc", ".", "syncOp", ".", "SyncStrategy", ".", "Hook", ".", "Force", ",", "true", ")", "\n", "}" ]
// syncNonHookTasks syncs or prunes the objects that are not handled by hooks using an apply sync. // returns true if the sync was successful
[ "syncNonHookTasks", "syncs", "or", "prunes", "the", "objects", "that", "are", "not", "handled", "by", "hooks", "using", "an", "apply", "sync", ".", "returns", "true", "if", "the", "sync", "was", "successful" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L192-L209
162,035
argoproj/argo-cd
controller/sync_hooks.go
enforceHookDeletePolicy
func enforceHookDeletePolicy(hook *unstructured.Unstructured, phase appv1.OperationPhase) bool { annotations := hook.GetAnnotations() if annotations == nil { return false } deletePolicies := strings.Split(annotations[common.AnnotationKeyHookDeletePolicy], ",") for _, dp := range deletePolicies { policy := appv1.HookDeletePolicy(strings.TrimSpace(dp)) if policy == appv1.HookDeletePolicyHookSucceeded && phase == appv1.OperationSucceeded { return true } if policy == appv1.HookDeletePolicyHookFailed && phase == appv1.OperationFailed { return true } } return false }
go
func enforceHookDeletePolicy(hook *unstructured.Unstructured, phase appv1.OperationPhase) bool { annotations := hook.GetAnnotations() if annotations == nil { return false } deletePolicies := strings.Split(annotations[common.AnnotationKeyHookDeletePolicy], ",") for _, dp := range deletePolicies { policy := appv1.HookDeletePolicy(strings.TrimSpace(dp)) if policy == appv1.HookDeletePolicyHookSucceeded && phase == appv1.OperationSucceeded { return true } if policy == appv1.HookDeletePolicyHookFailed && phase == appv1.OperationFailed { return true } } return false }
[ "func", "enforceHookDeletePolicy", "(", "hook", "*", "unstructured", ".", "Unstructured", ",", "phase", "appv1", ".", "OperationPhase", ")", "bool", "{", "annotations", ":=", "hook", ".", "GetAnnotations", "(", ")", "\n", "if", "annotations", "==", "nil", "{", "return", "false", "\n", "}", "\n", "deletePolicies", ":=", "strings", ".", "Split", "(", "annotations", "[", "common", ".", "AnnotationKeyHookDeletePolicy", "]", ",", "\"", "\"", ")", "\n", "for", "_", ",", "dp", ":=", "range", "deletePolicies", "{", "policy", ":=", "appv1", ".", "HookDeletePolicy", "(", "strings", ".", "TrimSpace", "(", "dp", ")", ")", "\n", "if", "policy", "==", "appv1", ".", "HookDeletePolicyHookSucceeded", "&&", "phase", "==", "appv1", ".", "OperationSucceeded", "{", "return", "true", "\n", "}", "\n", "if", "policy", "==", "appv1", ".", "HookDeletePolicyHookFailed", "&&", "phase", "==", "appv1", ".", "OperationFailed", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// enforceHookDeletePolicy examines the hook deletion policy of a object and deletes it based on the status
[ "enforceHookDeletePolicy", "examines", "the", "hook", "deletion", "policy", "of", "a", "object", "and", "deletes", "it", "based", "on", "the", "status" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L272-L288
162,036
argoproj/argo-cd
controller/sync_hooks.go
isHookType
func isHookType(hook *unstructured.Unstructured, hookType appv1.HookType) bool { annotations := hook.GetAnnotations() if annotations == nil { return false } resHookTypes := strings.Split(annotations[common.AnnotationKeyHook], ",") for _, ht := range resHookTypes { if string(hookType) == strings.TrimSpace(ht) { return true } } return false }
go
func isHookType(hook *unstructured.Unstructured, hookType appv1.HookType) bool { annotations := hook.GetAnnotations() if annotations == nil { return false } resHookTypes := strings.Split(annotations[common.AnnotationKeyHook], ",") for _, ht := range resHookTypes { if string(hookType) == strings.TrimSpace(ht) { return true } } return false }
[ "func", "isHookType", "(", "hook", "*", "unstructured", ".", "Unstructured", ",", "hookType", "appv1", ".", "HookType", ")", "bool", "{", "annotations", ":=", "hook", ".", "GetAnnotations", "(", ")", "\n", "if", "annotations", "==", "nil", "{", "return", "false", "\n", "}", "\n", "resHookTypes", ":=", "strings", ".", "Split", "(", "annotations", "[", "common", ".", "AnnotationKeyHook", "]", ",", "\"", "\"", ")", "\n", "for", "_", ",", "ht", ":=", "range", "resHookTypes", "{", "if", "string", "(", "hookType", ")", "==", "strings", ".", "TrimSpace", "(", "ht", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isHookType tells whether or not the supplied object is a hook of the specified type
[ "isHookType", "tells", "whether", "or", "not", "the", "supplied", "object", "is", "a", "hook", "of", "the", "specified", "type" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L291-L303
162,037
argoproj/argo-cd
controller/sync_hooks.go
newHookStatus
func newHookStatus(hook *unstructured.Unstructured, hookType appv1.HookType) appv1.ResourceResult { gvk := hook.GroupVersionKind() hookStatus := appv1.ResourceResult{ Name: hook.GetName(), Kind: hook.GetKind(), Group: gvk.Group, Version: gvk.Version, HookType: hookType, HookPhase: appv1.OperationRunning, Namespace: hook.GetNamespace(), } if isBatchJob(gvk) { updateStatusFromBatchJob(hook, &hookStatus) } else if isArgoWorkflow(gvk) { updateStatusFromArgoWorkflow(hook, &hookStatus) } else if isPod(gvk) { updateStatusFromPod(hook, &hookStatus) } else { hookStatus.HookPhase = appv1.OperationSucceeded hookStatus.Message = fmt.Sprintf("%s created", hook.GetName()) } return hookStatus }
go
func newHookStatus(hook *unstructured.Unstructured, hookType appv1.HookType) appv1.ResourceResult { gvk := hook.GroupVersionKind() hookStatus := appv1.ResourceResult{ Name: hook.GetName(), Kind: hook.GetKind(), Group: gvk.Group, Version: gvk.Version, HookType: hookType, HookPhase: appv1.OperationRunning, Namespace: hook.GetNamespace(), } if isBatchJob(gvk) { updateStatusFromBatchJob(hook, &hookStatus) } else if isArgoWorkflow(gvk) { updateStatusFromArgoWorkflow(hook, &hookStatus) } else if isPod(gvk) { updateStatusFromPod(hook, &hookStatus) } else { hookStatus.HookPhase = appv1.OperationSucceeded hookStatus.Message = fmt.Sprintf("%s created", hook.GetName()) } return hookStatus }
[ "func", "newHookStatus", "(", "hook", "*", "unstructured", ".", "Unstructured", ",", "hookType", "appv1", ".", "HookType", ")", "appv1", ".", "ResourceResult", "{", "gvk", ":=", "hook", ".", "GroupVersionKind", "(", ")", "\n", "hookStatus", ":=", "appv1", ".", "ResourceResult", "{", "Name", ":", "hook", ".", "GetName", "(", ")", ",", "Kind", ":", "hook", ".", "GetKind", "(", ")", ",", "Group", ":", "gvk", ".", "Group", ",", "Version", ":", "gvk", ".", "Version", ",", "HookType", ":", "hookType", ",", "HookPhase", ":", "appv1", ".", "OperationRunning", ",", "Namespace", ":", "hook", ".", "GetNamespace", "(", ")", ",", "}", "\n", "if", "isBatchJob", "(", "gvk", ")", "{", "updateStatusFromBatchJob", "(", "hook", ",", "&", "hookStatus", ")", "\n", "}", "else", "if", "isArgoWorkflow", "(", "gvk", ")", "{", "updateStatusFromArgoWorkflow", "(", "hook", ",", "&", "hookStatus", ")", "\n", "}", "else", "if", "isPod", "(", "gvk", ")", "{", "updateStatusFromPod", "(", "hook", ",", "&", "hookStatus", ")", "\n", "}", "else", "{", "hookStatus", ".", "HookPhase", "=", "appv1", ".", "OperationSucceeded", "\n", "hookStatus", ".", "Message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hook", ".", "GetName", "(", ")", ")", "\n", "}", "\n", "return", "hookStatus", "\n", "}" ]
// newHookStatus returns a hook status from an _live_ unstructured object
[ "newHookStatus", "returns", "a", "hook", "status", "from", "an", "_live_", "unstructured", "object" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L306-L328
162,038
argoproj/argo-cd
controller/sync_hooks.go
isRunnable
func isRunnable(res *appv1.ResourceResult) bool { gvk := res.GroupVersionKind() return isBatchJob(gvk) || isArgoWorkflow(gvk) || isPod(gvk) }
go
func isRunnable(res *appv1.ResourceResult) bool { gvk := res.GroupVersionKind() return isBatchJob(gvk) || isArgoWorkflow(gvk) || isPod(gvk) }
[ "func", "isRunnable", "(", "res", "*", "appv1", ".", "ResourceResult", ")", "bool", "{", "gvk", ":=", "res", ".", "GroupVersionKind", "(", ")", "\n", "return", "isBatchJob", "(", "gvk", ")", "||", "isArgoWorkflow", "(", "gvk", ")", "||", "isPod", "(", "gvk", ")", "\n", "}" ]
// isRunnable returns if the resource object is a runnable type which needs to be terminated
[ "isRunnable", "returns", "if", "the", "resource", "object", "is", "a", "runnable", "type", "which", "needs", "to", "be", "terminated" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L331-L334
162,039
argoproj/argo-cd
controller/sync_hooks.go
updateHookStatus
func (sc *syncContext) updateHookStatus(hookStatus appv1.ResourceResult) bool { sc.lock.Lock() defer sc.lock.Unlock() for i, prev := range sc.syncRes.Resources { if !prev.IsHook() { continue } if hookEqual(prev, hookStatus.Group, hookStatus.Kind, hookStatus.Namespace, hookStatus.Name, hookStatus.HookType) { if reflect.DeepEqual(prev, hookStatus) { return false } if prev.HookPhase != hookStatus.HookPhase { sc.log.Infof("Hook %s %s/%s hookPhase: %s -> %s", hookStatus.HookType, prev.Kind, prev.Name, prev.HookPhase, hookStatus.HookPhase) } if prev.Status != hookStatus.Status { sc.log.Infof("Hook %s %s/%s status: %s -> %s", hookStatus.HookType, prev.Kind, prev.Name, prev.Status, hookStatus.Status) } if prev.Message != hookStatus.Message { sc.log.Infof("Hook %s %s/%s message: '%s' -> '%s'", hookStatus.HookType, prev.Kind, prev.Name, prev.Message, hookStatus.Message) } sc.syncRes.Resources[i] = &hookStatus return true } } sc.syncRes.Resources = append(sc.syncRes.Resources, &hookStatus) sc.log.Infof("Set new hook %s %s/%s. phase: %s, message: %s", hookStatus.HookType, hookStatus.Kind, hookStatus.Name, hookStatus.HookPhase, hookStatus.Message) return true }
go
func (sc *syncContext) updateHookStatus(hookStatus appv1.ResourceResult) bool { sc.lock.Lock() defer sc.lock.Unlock() for i, prev := range sc.syncRes.Resources { if !prev.IsHook() { continue } if hookEqual(prev, hookStatus.Group, hookStatus.Kind, hookStatus.Namespace, hookStatus.Name, hookStatus.HookType) { if reflect.DeepEqual(prev, hookStatus) { return false } if prev.HookPhase != hookStatus.HookPhase { sc.log.Infof("Hook %s %s/%s hookPhase: %s -> %s", hookStatus.HookType, prev.Kind, prev.Name, prev.HookPhase, hookStatus.HookPhase) } if prev.Status != hookStatus.Status { sc.log.Infof("Hook %s %s/%s status: %s -> %s", hookStatus.HookType, prev.Kind, prev.Name, prev.Status, hookStatus.Status) } if prev.Message != hookStatus.Message { sc.log.Infof("Hook %s %s/%s message: '%s' -> '%s'", hookStatus.HookType, prev.Kind, prev.Name, prev.Message, hookStatus.Message) } sc.syncRes.Resources[i] = &hookStatus return true } } sc.syncRes.Resources = append(sc.syncRes.Resources, &hookStatus) sc.log.Infof("Set new hook %s %s/%s. phase: %s, message: %s", hookStatus.HookType, hookStatus.Kind, hookStatus.Name, hookStatus.HookPhase, hookStatus.Message) return true }
[ "func", "(", "sc", "*", "syncContext", ")", "updateHookStatus", "(", "hookStatus", "appv1", ".", "ResourceResult", ")", "bool", "{", "sc", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "sc", ".", "lock", ".", "Unlock", "(", ")", "\n", "for", "i", ",", "prev", ":=", "range", "sc", ".", "syncRes", ".", "Resources", "{", "if", "!", "prev", ".", "IsHook", "(", ")", "{", "continue", "\n", "}", "\n", "if", "hookEqual", "(", "prev", ",", "hookStatus", ".", "Group", ",", "hookStatus", ".", "Kind", ",", "hookStatus", ".", "Namespace", ",", "hookStatus", ".", "Name", ",", "hookStatus", ".", "HookType", ")", "{", "if", "reflect", ".", "DeepEqual", "(", "prev", ",", "hookStatus", ")", "{", "return", "false", "\n", "}", "\n", "if", "prev", ".", "HookPhase", "!=", "hookStatus", ".", "HookPhase", "{", "sc", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "hookStatus", ".", "HookType", ",", "prev", ".", "Kind", ",", "prev", ".", "Name", ",", "prev", ".", "HookPhase", ",", "hookStatus", ".", "HookPhase", ")", "\n", "}", "\n", "if", "prev", ".", "Status", "!=", "hookStatus", ".", "Status", "{", "sc", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "hookStatus", ".", "HookType", ",", "prev", ".", "Kind", ",", "prev", ".", "Name", ",", "prev", ".", "Status", ",", "hookStatus", ".", "Status", ")", "\n", "}", "\n", "if", "prev", ".", "Message", "!=", "hookStatus", ".", "Message", "{", "sc", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "hookStatus", ".", "HookType", ",", "prev", ".", "Kind", ",", "prev", ".", "Name", ",", "prev", ".", "Message", ",", "hookStatus", ".", "Message", ")", "\n", "}", "\n", "sc", ".", "syncRes", ".", "Resources", "[", "i", "]", "=", "&", "hookStatus", "\n", "return", "true", "\n", "}", "\n", "}", "\n", "sc", ".", "syncRes", ".", "Resources", "=", "append", "(", "sc", ".", "syncRes", ".", "Resources", ",", "&", "hookStatus", ")", "\n", "sc", ".", "log", ".", "Infof", "(", "\"", "\"", ",", "hookStatus", ".", "HookType", ",", "hookStatus", ".", "Kind", ",", "hookStatus", ".", "Name", ",", "hookStatus", ".", "HookPhase", ",", "hookStatus", ".", "Message", ")", "\n", "return", "true", "\n", "}" ]
// updateHookStatus updates the status of a hook. Returns true if the hook was modified
[ "updateHookStatus", "updates", "the", "status", "of", "a", "hook", ".", "Returns", "true", "if", "the", "hook", "was", "modified" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L473-L500
162,040
argoproj/argo-cd
controller/sync_hooks.go
areHooksCompletedSuccessful
func areHooksCompletedSuccessful(hookType appv1.HookType, hookStatuses []*appv1.ResourceResult) (bool, bool) { isSuccessful := true for _, hookStatus := range hookStatuses { if !hookStatus.IsHook() { continue } if hookStatus.HookType != hookType { continue } if !hookStatus.HookPhase.Completed() { return false, false } if !hookStatus.HookPhase.Successful() { isSuccessful = false } } return true, isSuccessful }
go
func areHooksCompletedSuccessful(hookType appv1.HookType, hookStatuses []*appv1.ResourceResult) (bool, bool) { isSuccessful := true for _, hookStatus := range hookStatuses { if !hookStatus.IsHook() { continue } if hookStatus.HookType != hookType { continue } if !hookStatus.HookPhase.Completed() { return false, false } if !hookStatus.HookPhase.Successful() { isSuccessful = false } } return true, isSuccessful }
[ "func", "areHooksCompletedSuccessful", "(", "hookType", "appv1", ".", "HookType", ",", "hookStatuses", "[", "]", "*", "appv1", ".", "ResourceResult", ")", "(", "bool", ",", "bool", ")", "{", "isSuccessful", ":=", "true", "\n", "for", "_", ",", "hookStatus", ":=", "range", "hookStatuses", "{", "if", "!", "hookStatus", ".", "IsHook", "(", ")", "{", "continue", "\n", "}", "\n", "if", "hookStatus", ".", "HookType", "!=", "hookType", "{", "continue", "\n", "}", "\n", "if", "!", "hookStatus", ".", "HookPhase", ".", "Completed", "(", ")", "{", "return", "false", ",", "false", "\n", "}", "\n", "if", "!", "hookStatus", ".", "HookPhase", ".", "Successful", "(", ")", "{", "isSuccessful", "=", "false", "\n", "}", "\n", "}", "\n", "return", "true", ",", "isSuccessful", "\n", "}" ]
// areHooksCompletedSuccessful checks if all the hooks of the specified type are completed and successful
[ "areHooksCompletedSuccessful", "checks", "if", "all", "the", "hooks", "of", "the", "specified", "type", "are", "completed", "and", "successful" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/controller/sync_hooks.go#L503-L520
162,041
argoproj/argo-cd
pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go
Get
func (c *FakeApplications) Get(name string, options v1.GetOptions) (result *v1alpha1.Application, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(applicationsResource, c.ns, name), &v1alpha1.Application{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Application), err }
go
func (c *FakeApplications) Get(name string, options v1.GetOptions) (result *v1alpha1.Application, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(applicationsResource, c.ns, name), &v1alpha1.Application{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Application), err }
[ "func", "(", "c", "*", "FakeApplications", ")", "Get", "(", "name", "string", ",", "options", "v1", ".", "GetOptions", ")", "(", "result", "*", "v1alpha1", ".", "Application", ",", "err", "error", ")", "{", "obj", ",", "err", ":=", "c", ".", "Fake", ".", "Invokes", "(", "testing", ".", "NewGetAction", "(", "applicationsResource", ",", "c", ".", "ns", ",", "name", ")", ",", "&", "v1alpha1", ".", "Application", "{", "}", ")", "\n\n", "if", "obj", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "obj", ".", "(", "*", "v1alpha1", ".", "Application", ")", ",", "err", "\n", "}" ]
// Get takes name of the application, and returns the corresponding application object, and an error if there is any.
[ "Get", "takes", "name", "of", "the", "application", "and", "returns", "the", "corresponding", "application", "object", "and", "an", "error", "if", "there", "is", "any", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go#L26-L34
162,042
argoproj/argo-cd
pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go
List
func (c *FakeApplications) List(opts v1.ListOptions) (result *v1alpha1.ApplicationList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(applicationsResource, applicationsKind, c.ns, opts), &v1alpha1.ApplicationList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1alpha1.ApplicationList{ListMeta: obj.(*v1alpha1.ApplicationList).ListMeta} for _, item := range obj.(*v1alpha1.ApplicationList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err }
go
func (c *FakeApplications) List(opts v1.ListOptions) (result *v1alpha1.ApplicationList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(applicationsResource, applicationsKind, c.ns, opts), &v1alpha1.ApplicationList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1alpha1.ApplicationList{ListMeta: obj.(*v1alpha1.ApplicationList).ListMeta} for _, item := range obj.(*v1alpha1.ApplicationList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err }
[ "func", "(", "c", "*", "FakeApplications", ")", "List", "(", "opts", "v1", ".", "ListOptions", ")", "(", "result", "*", "v1alpha1", ".", "ApplicationList", ",", "err", "error", ")", "{", "obj", ",", "err", ":=", "c", ".", "Fake", ".", "Invokes", "(", "testing", ".", "NewListAction", "(", "applicationsResource", ",", "applicationsKind", ",", "c", ".", "ns", ",", "opts", ")", ",", "&", "v1alpha1", ".", "ApplicationList", "{", "}", ")", "\n\n", "if", "obj", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "label", ",", "_", ",", "_", ":=", "testing", ".", "ExtractFromListOptions", "(", "opts", ")", "\n", "if", "label", "==", "nil", "{", "label", "=", "labels", ".", "Everything", "(", ")", "\n", "}", "\n", "list", ":=", "&", "v1alpha1", ".", "ApplicationList", "{", "ListMeta", ":", "obj", ".", "(", "*", "v1alpha1", ".", "ApplicationList", ")", ".", "ListMeta", "}", "\n", "for", "_", ",", "item", ":=", "range", "obj", ".", "(", "*", "v1alpha1", ".", "ApplicationList", ")", ".", "Items", "{", "if", "label", ".", "Matches", "(", "labels", ".", "Set", "(", "item", ".", "Labels", ")", ")", "{", "list", ".", "Items", "=", "append", "(", "list", ".", "Items", ",", "item", ")", "\n", "}", "\n", "}", "\n", "return", "list", ",", "err", "\n", "}" ]
// List takes label and field selectors, and returns the list of Applications that match those selectors.
[ "List", "takes", "label", "and", "field", "selectors", "and", "returns", "the", "list", "of", "Applications", "that", "match", "those", "selectors", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go#L37-L56
162,043
argoproj/argo-cd
pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go
Watch
func (c *FakeApplications) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(applicationsResource, c.ns, opts)) }
go
func (c *FakeApplications) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(applicationsResource, c.ns, opts)) }
[ "func", "(", "c", "*", "FakeApplications", ")", "Watch", "(", "opts", "v1", ".", "ListOptions", ")", "(", "watch", ".", "Interface", ",", "error", ")", "{", "return", "c", ".", "Fake", ".", "InvokesWatch", "(", "testing", ".", "NewWatchAction", "(", "applicationsResource", ",", "c", ".", "ns", ",", "opts", ")", ")", "\n\n", "}" ]
// Watch returns a watch.Interface that watches the requested applications.
[ "Watch", "returns", "a", "watch", ".", "Interface", "that", "watches", "the", "requested", "applications", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go#L59-L63
162,044
argoproj/argo-cd
pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go
Delete
func (c *FakeApplications) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(applicationsResource, c.ns, name), &v1alpha1.Application{}) return err }
go
func (c *FakeApplications) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(applicationsResource, c.ns, name), &v1alpha1.Application{}) return err }
[ "func", "(", "c", "*", "FakeApplications", ")", "Delete", "(", "name", "string", ",", "options", "*", "v1", ".", "DeleteOptions", ")", "error", "{", "_", ",", "err", ":=", "c", ".", "Fake", ".", "Invokes", "(", "testing", ".", "NewDeleteAction", "(", "applicationsResource", ",", "c", ".", "ns", ",", "name", ")", ",", "&", "v1alpha1", ".", "Application", "{", "}", ")", "\n\n", "return", "err", "\n", "}" ]
// Delete takes name of the application and deletes it. Returns an error if one occurs.
[ "Delete", "takes", "name", "of", "the", "application", "and", "deletes", "it", ".", "Returns", "an", "error", "if", "one", "occurs", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go#L88-L93
162,045
argoproj/argo-cd
pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go
Patch
func (c *FakeApplications) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Application, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(applicationsResource, c.ns, name, data, subresources...), &v1alpha1.Application{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Application), err }
go
func (c *FakeApplications) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Application, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(applicationsResource, c.ns, name, data, subresources...), &v1alpha1.Application{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Application), err }
[ "func", "(", "c", "*", "FakeApplications", ")", "Patch", "(", "name", "string", ",", "pt", "types", ".", "PatchType", ",", "data", "[", "]", "byte", ",", "subresources", "...", "string", ")", "(", "result", "*", "v1alpha1", ".", "Application", ",", "err", "error", ")", "{", "obj", ",", "err", ":=", "c", ".", "Fake", ".", "Invokes", "(", "testing", ".", "NewPatchSubresourceAction", "(", "applicationsResource", ",", "c", ".", "ns", ",", "name", ",", "data", ",", "subresources", "...", ")", ",", "&", "v1alpha1", ".", "Application", "{", "}", ")", "\n\n", "if", "obj", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "obj", ".", "(", "*", "v1alpha1", ".", "Application", ")", ",", "err", "\n", "}" ]
// Patch applies the patch and returns the patched application.
[ "Patch", "applies", "the", "patch", "and", "returns", "the", "patched", "application", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/clientset/versioned/typed/application/v1alpha1/fake/fake_application.go#L104-L112
162,046
argoproj/argo-cd
pkg/client/listers/application/v1alpha1/application.go
List
func (s *applicationLister) List(selector labels.Selector) (ret []*v1alpha1.Application, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Application)) }) return ret, err }
go
func (s *applicationLister) List(selector labels.Selector) (ret []*v1alpha1.Application, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Application)) }) return ret, err }
[ "func", "(", "s", "*", "applicationLister", ")", "List", "(", "selector", "labels", ".", "Selector", ")", "(", "ret", "[", "]", "*", "v1alpha1", ".", "Application", ",", "err", "error", ")", "{", "err", "=", "cache", ".", "ListAll", "(", "s", ".", "indexer", ",", "selector", ",", "func", "(", "m", "interface", "{", "}", ")", "{", "ret", "=", "append", "(", "ret", ",", "m", ".", "(", "*", "v1alpha1", ".", "Application", ")", ")", "\n", "}", ")", "\n", "return", "ret", ",", "err", "\n", "}" ]
// List lists all Applications in the indexer.
[ "List", "lists", "all", "Applications", "in", "the", "indexer", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/listers/application/v1alpha1/application.go#L32-L37
162,047
argoproj/argo-cd
pkg/client/listers/application/v1alpha1/application.go
Applications
func (s *applicationLister) Applications(namespace string) ApplicationNamespaceLister { return applicationNamespaceLister{indexer: s.indexer, namespace: namespace} }
go
func (s *applicationLister) Applications(namespace string) ApplicationNamespaceLister { return applicationNamespaceLister{indexer: s.indexer, namespace: namespace} }
[ "func", "(", "s", "*", "applicationLister", ")", "Applications", "(", "namespace", "string", ")", "ApplicationNamespaceLister", "{", "return", "applicationNamespaceLister", "{", "indexer", ":", "s", ".", "indexer", ",", "namespace", ":", "namespace", "}", "\n", "}" ]
// Applications returns an object that can list and get Applications.
[ "Applications", "returns", "an", "object", "that", "can", "list", "and", "get", "Applications", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/listers/application/v1alpha1/application.go#L40-L42
162,048
argoproj/argo-cd
pkg/client/listers/application/v1alpha1/application.go
List
func (s applicationNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Application, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Application)) }) return ret, err }
go
func (s applicationNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Application, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Application)) }) return ret, err }
[ "func", "(", "s", "applicationNamespaceLister", ")", "List", "(", "selector", "labels", ".", "Selector", ")", "(", "ret", "[", "]", "*", "v1alpha1", ".", "Application", ",", "err", "error", ")", "{", "err", "=", "cache", ".", "ListAllByNamespace", "(", "s", ".", "indexer", ",", "s", ".", "namespace", ",", "selector", ",", "func", "(", "m", "interface", "{", "}", ")", "{", "ret", "=", "append", "(", "ret", ",", "m", ".", "(", "*", "v1alpha1", ".", "Application", ")", ")", "\n", "}", ")", "\n", "return", "ret", ",", "err", "\n", "}" ]
// List lists all Applications in the indexer for a given namespace.
[ "List", "lists", "all", "Applications", "in", "the", "indexer", "for", "a", "given", "namespace", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/listers/application/v1alpha1/application.go#L61-L66
162,049
argoproj/argo-cd
pkg/apiclient/grpcproxy.go
useGRPCProxy
func (c *client) useGRPCProxy() (net.Addr, io.Closer, error) { c.proxyMutex.Lock() defer c.proxyMutex.Unlock() if c.proxyListener == nil { var err error c.proxyServer, c.proxyListener, err = c.startGRPCProxy() if err != nil { return nil, nil, err } } c.proxyUsersCount = c.proxyUsersCount + 1 return c.proxyListener.Addr(), &inlineCloser{close: func() error { c.proxyMutex.Lock() defer c.proxyMutex.Unlock() c.proxyUsersCount = c.proxyUsersCount - 1 if c.proxyUsersCount == 0 { c.proxyServer.Stop() c.proxyListener = nil c.proxyServer = nil return nil } return nil }}, nil }
go
func (c *client) useGRPCProxy() (net.Addr, io.Closer, error) { c.proxyMutex.Lock() defer c.proxyMutex.Unlock() if c.proxyListener == nil { var err error c.proxyServer, c.proxyListener, err = c.startGRPCProxy() if err != nil { return nil, nil, err } } c.proxyUsersCount = c.proxyUsersCount + 1 return c.proxyListener.Addr(), &inlineCloser{close: func() error { c.proxyMutex.Lock() defer c.proxyMutex.Unlock() c.proxyUsersCount = c.proxyUsersCount - 1 if c.proxyUsersCount == 0 { c.proxyServer.Stop() c.proxyListener = nil c.proxyServer = nil return nil } return nil }}, nil }
[ "func", "(", "c", "*", "client", ")", "useGRPCProxy", "(", ")", "(", "net", ".", "Addr", ",", "io", ".", "Closer", ",", "error", ")", "{", "c", ".", "proxyMutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "proxyMutex", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "proxyListener", "==", "nil", "{", "var", "err", "error", "\n", "c", ".", "proxyServer", ",", "c", ".", "proxyListener", ",", "err", "=", "c", ".", "startGRPCProxy", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "c", ".", "proxyUsersCount", "=", "c", ".", "proxyUsersCount", "+", "1", "\n\n", "return", "c", ".", "proxyListener", ".", "Addr", "(", ")", ",", "&", "inlineCloser", "{", "close", ":", "func", "(", ")", "error", "{", "c", ".", "proxyMutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "proxyMutex", ".", "Unlock", "(", ")", "\n", "c", ".", "proxyUsersCount", "=", "c", ".", "proxyUsersCount", "-", "1", "\n", "if", "c", ".", "proxyUsersCount", "==", "0", "{", "c", ".", "proxyServer", ".", "Stop", "(", ")", "\n", "c", ".", "proxyListener", "=", "nil", "\n", "c", ".", "proxyServer", "=", "nil", "\n", "return", "nil", "\n", "}", "\n", "return", "nil", "\n", "}", "}", ",", "nil", "\n", "}" ]
// useGRPCProxy ensures that grpc proxy server is started and return closer which stops server when no one uses it
[ "useGRPCProxy", "ensures", "that", "grpc", "proxy", "server", "is", "started", "and", "return", "closer", "which", "stops", "server", "when", "no", "one", "uses", "it" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/apiclient/grpcproxy.go#L175-L200
162,050
argoproj/argo-cd
server/settings/settings.pb.gw.go
RegisterSettingsServiceHandler
func RegisterSettingsServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterSettingsServiceHandlerClient(ctx, mux, NewSettingsServiceClient(conn)) }
go
func RegisterSettingsServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterSettingsServiceHandlerClient(ctx, mux, NewSettingsServiceClient(conn)) }
[ "func", "RegisterSettingsServiceHandler", "(", "ctx", "context", ".", "Context", ",", "mux", "*", "runtime", ".", "ServeMux", ",", "conn", "*", "grpc", ".", "ClientConn", ")", "error", "{", "return", "RegisterSettingsServiceHandlerClient", "(", "ctx", ",", "mux", ",", "NewSettingsServiceClient", "(", "conn", ")", ")", "\n", "}" ]
// RegisterSettingsServiceHandler registers the http handlers for service SettingsService to "mux". // The handlers forward requests to the grpc endpoint over "conn".
[ "RegisterSettingsServiceHandler", "registers", "the", "http", "handlers", "for", "service", "SettingsService", "to", "mux", ".", "The", "handlers", "forward", "requests", "to", "the", "grpc", "endpoint", "over", "conn", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/server/settings/settings.pb.gw.go#L67-L69
162,051
argoproj/argo-cd
util/grpc/errors.go
ErrorCodeUnaryServerInterceptor
func ErrorCodeUnaryServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { resp, err = handler(ctx, req) return resp, kubeErrToGRPC(err) } }
go
func ErrorCodeUnaryServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { resp, err = handler(ctx, req) return resp, kubeErrToGRPC(err) } }
[ "func", "ErrorCodeUnaryServerInterceptor", "(", ")", "grpc", ".", "UnaryServerInterceptor", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "resp", "interface", "{", "}", ",", "err", "error", ")", "{", "resp", ",", "err", "=", "handler", "(", "ctx", ",", "req", ")", "\n", "return", "resp", ",", "kubeErrToGRPC", "(", "err", ")", "\n", "}", "\n", "}" ]
// ErrorCodeUnaryServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any.
[ "ErrorCodeUnaryServerInterceptor", "replaces", "Kubernetes", "errors", "with", "relevant", "gRPC", "equivalents", "if", "any", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/grpc/errors.go#L62-L67
162,052
argoproj/argo-cd
util/grpc/errors.go
ErrorCodeStreamServerInterceptor
func ErrorCodeStreamServerInterceptor() grpc.StreamServerInterceptor { return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) return kubeErrToGRPC(err) } }
go
func ErrorCodeStreamServerInterceptor() grpc.StreamServerInterceptor { return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { err := handler(srv, ss) return kubeErrToGRPC(err) } }
[ "func", "ErrorCodeStreamServerInterceptor", "(", ")", "grpc", ".", "StreamServerInterceptor", "{", "return", "func", "(", "srv", "interface", "{", "}", ",", "ss", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "error", "{", "err", ":=", "handler", "(", "srv", ",", "ss", ")", "\n", "return", "kubeErrToGRPC", "(", "err", ")", "\n", "}", "\n", "}" ]
// ErrorCodeStreamServerInterceptor replaces Kubernetes errors with relevant gRPC equivalents, if any.
[ "ErrorCodeStreamServerInterceptor", "replaces", "Kubernetes", "errors", "with", "relevant", "gRPC", "equivalents", "if", "any", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/grpc/errors.go#L70-L75
162,053
argoproj/argo-cd
reposerver/repository/repository.go
NewService
func NewService(gitFactory git.ClientFactory, cache *cache.Cache, parallelismLimit int64) *Service { var parallelismLimitSemaphore *semaphore.Weighted if parallelismLimit > 0 { parallelismLimitSemaphore = semaphore.NewWeighted(parallelismLimit) } return &Service{ parallelismLimitSemaphore: parallelismLimitSemaphore, repoLock: util.NewKeyLock(), gitFactory: gitFactory, cache: cache, } }
go
func NewService(gitFactory git.ClientFactory, cache *cache.Cache, parallelismLimit int64) *Service { var parallelismLimitSemaphore *semaphore.Weighted if parallelismLimit > 0 { parallelismLimitSemaphore = semaphore.NewWeighted(parallelismLimit) } return &Service{ parallelismLimitSemaphore: parallelismLimitSemaphore, repoLock: util.NewKeyLock(), gitFactory: gitFactory, cache: cache, } }
[ "func", "NewService", "(", "gitFactory", "git", ".", "ClientFactory", ",", "cache", "*", "cache", ".", "Cache", ",", "parallelismLimit", "int64", ")", "*", "Service", "{", "var", "parallelismLimitSemaphore", "*", "semaphore", ".", "Weighted", "\n", "if", "parallelismLimit", ">", "0", "{", "parallelismLimitSemaphore", "=", "semaphore", ".", "NewWeighted", "(", "parallelismLimit", ")", "\n", "}", "\n", "return", "&", "Service", "{", "parallelismLimitSemaphore", ":", "parallelismLimitSemaphore", ",", "repoLock", ":", "util", ".", "NewKeyLock", "(", ")", ",", "gitFactory", ":", "gitFactory", ",", "cache", ":", "cache", ",", "}", "\n", "}" ]
// NewService returns a new instance of the Manifest service
[ "NewService", "returns", "a", "new", "instance", "of", "the", "Manifest", "service" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L50-L62
162,054
argoproj/argo-cd
reposerver/repository/repository.go
ListDir
func (s *Service) ListDir(ctx context.Context, q *ListDirRequest) (*FileList, error) { gitClient, commitSHA, err := s.newClientResolveRevision(q.Repo, q.Revision) if err != nil { return nil, err } if files, err := s.cache.GetGitListDir(commitSHA, q.Path); err == nil { log.Infof("listdir cache hit: %s/%s", commitSHA, q.Path) return &FileList{Items: files}, nil } s.repoLock.Lock(gitClient.Root()) defer s.repoLock.Unlock(gitClient.Root()) commitSHA, err = checkoutRevision(gitClient, commitSHA) if err != nil { return nil, err } lsFiles, err := gitClient.LsFiles(q.Path) if err != nil { return nil, err } res := FileList{Items: lsFiles} err = s.cache.SetListDir(commitSHA, q.Path, res.Items) if err != nil { log.Warnf("listdir cache set error %s/%s: %v", commitSHA, q.Path, err) } return &res, nil }
go
func (s *Service) ListDir(ctx context.Context, q *ListDirRequest) (*FileList, error) { gitClient, commitSHA, err := s.newClientResolveRevision(q.Repo, q.Revision) if err != nil { return nil, err } if files, err := s.cache.GetGitListDir(commitSHA, q.Path); err == nil { log.Infof("listdir cache hit: %s/%s", commitSHA, q.Path) return &FileList{Items: files}, nil } s.repoLock.Lock(gitClient.Root()) defer s.repoLock.Unlock(gitClient.Root()) commitSHA, err = checkoutRevision(gitClient, commitSHA) if err != nil { return nil, err } lsFiles, err := gitClient.LsFiles(q.Path) if err != nil { return nil, err } res := FileList{Items: lsFiles} err = s.cache.SetListDir(commitSHA, q.Path, res.Items) if err != nil { log.Warnf("listdir cache set error %s/%s: %v", commitSHA, q.Path, err) } return &res, nil }
[ "func", "(", "s", "*", "Service", ")", "ListDir", "(", "ctx", "context", ".", "Context", ",", "q", "*", "ListDirRequest", ")", "(", "*", "FileList", ",", "error", ")", "{", "gitClient", ",", "commitSHA", ",", "err", ":=", "s", ".", "newClientResolveRevision", "(", "q", ".", "Repo", ",", "q", ".", "Revision", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "files", ",", "err", ":=", "s", ".", "cache", ".", "GetGitListDir", "(", "commitSHA", ",", "q", ".", "Path", ")", ";", "err", "==", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "commitSHA", ",", "q", ".", "Path", ")", "\n", "return", "&", "FileList", "{", "Items", ":", "files", "}", ",", "nil", "\n", "}", "\n\n", "s", ".", "repoLock", ".", "Lock", "(", "gitClient", ".", "Root", "(", ")", ")", "\n", "defer", "s", ".", "repoLock", ".", "Unlock", "(", "gitClient", ".", "Root", "(", ")", ")", "\n", "commitSHA", ",", "err", "=", "checkoutRevision", "(", "gitClient", ",", "commitSHA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "lsFiles", ",", "err", ":=", "gitClient", ".", "LsFiles", "(", "q", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ":=", "FileList", "{", "Items", ":", "lsFiles", "}", "\n", "err", "=", "s", ".", "cache", ".", "SetListDir", "(", "commitSHA", ",", "q", ".", "Path", ",", "res", ".", "Items", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "commitSHA", ",", "q", ".", "Path", ",", "err", ")", "\n", "}", "\n", "return", "&", "res", ",", "nil", "\n", "}" ]
// ListDir lists the contents of a GitHub repo
[ "ListDir", "lists", "the", "contents", "of", "a", "GitHub", "repo" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L65-L93
162,055
argoproj/argo-cd
reposerver/repository/repository.go
tempRepoPath
func tempRepoPath(repo string) string { return filepath.Join(os.TempDir(), strings.Replace(repo, "/", "_", -1)) }
go
func tempRepoPath(repo string) string { return filepath.Join(os.TempDir(), strings.Replace(repo, "/", "_", -1)) }
[ "func", "tempRepoPath", "(", "repo", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "os", ".", "TempDir", "(", ")", ",", "strings", ".", "Replace", "(", "repo", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", ")", "\n", "}" ]
// tempRepoPath returns a formulated temporary directory location to clone a repository
[ "tempRepoPath", "returns", "a", "formulated", "temporary", "directory", "location", "to", "clone", "a", "repository" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L282-L284
162,056
argoproj/argo-cd
reposerver/repository/repository.go
GetAppSourceType
func GetAppSourceType(source *v1alpha1.ApplicationSource, appDirPath string) (v1alpha1.ApplicationSourceType, error) { appSourceType, err := source.ExplicitType() if err != nil { return "", err } if appSourceType != nil { return *appSourceType, nil } if pathExists(appDirPath, "app.yaml") { return v1alpha1.ApplicationSourceTypeKsonnet, nil } if pathExists(appDirPath, "Chart.yaml") { return v1alpha1.ApplicationSourceTypeHelm, nil } for _, kustomization := range kustomize.KustomizationNames { if pathExists(appDirPath, kustomization) { return v1alpha1.ApplicationSourceTypeKustomize, nil } } return v1alpha1.ApplicationSourceTypeDirectory, nil }
go
func GetAppSourceType(source *v1alpha1.ApplicationSource, appDirPath string) (v1alpha1.ApplicationSourceType, error) { appSourceType, err := source.ExplicitType() if err != nil { return "", err } if appSourceType != nil { return *appSourceType, nil } if pathExists(appDirPath, "app.yaml") { return v1alpha1.ApplicationSourceTypeKsonnet, nil } if pathExists(appDirPath, "Chart.yaml") { return v1alpha1.ApplicationSourceTypeHelm, nil } for _, kustomization := range kustomize.KustomizationNames { if pathExists(appDirPath, kustomization) { return v1alpha1.ApplicationSourceTypeKustomize, nil } } return v1alpha1.ApplicationSourceTypeDirectory, nil }
[ "func", "GetAppSourceType", "(", "source", "*", "v1alpha1", ".", "ApplicationSource", ",", "appDirPath", "string", ")", "(", "v1alpha1", ".", "ApplicationSourceType", ",", "error", ")", "{", "appSourceType", ",", "err", ":=", "source", ".", "ExplicitType", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "appSourceType", "!=", "nil", "{", "return", "*", "appSourceType", ",", "nil", "\n", "}", "\n\n", "if", "pathExists", "(", "appDirPath", ",", "\"", "\"", ")", "{", "return", "v1alpha1", ".", "ApplicationSourceTypeKsonnet", ",", "nil", "\n", "}", "\n", "if", "pathExists", "(", "appDirPath", ",", "\"", "\"", ")", "{", "return", "v1alpha1", ".", "ApplicationSourceTypeHelm", ",", "nil", "\n", "}", "\n", "for", "_", ",", "kustomization", ":=", "range", "kustomize", ".", "KustomizationNames", "{", "if", "pathExists", "(", "appDirPath", ",", "kustomization", ")", "{", "return", "v1alpha1", ".", "ApplicationSourceTypeKustomize", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "v1alpha1", ".", "ApplicationSourceTypeDirectory", ",", "nil", "\n", "}" ]
// GetAppSourceType returns explicit application source type or examines a directory and determines its application source type
[ "GetAppSourceType", "returns", "explicit", "application", "source", "type", "or", "examines", "a", "directory", "and", "determines", "its", "application", "source", "type" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L287-L308
162,057
argoproj/argo-cd
reposerver/repository/repository.go
checkoutRevision
func checkoutRevision(gitClient git.Client, commitSHA string) (string, error) { err := gitClient.Init() if err != nil { return "", status.Errorf(codes.Internal, "Failed to initialize git repo: %v", err) } err = gitClient.Fetch() if err != nil { return "", status.Errorf(codes.Internal, "Failed to fetch git repo: %v", err) } err = gitClient.Checkout(commitSHA) if err != nil { return "", status.Errorf(codes.Internal, "Failed to checkout %s: %v", commitSHA, err) } return gitClient.CommitSHA() }
go
func checkoutRevision(gitClient git.Client, commitSHA string) (string, error) { err := gitClient.Init() if err != nil { return "", status.Errorf(codes.Internal, "Failed to initialize git repo: %v", err) } err = gitClient.Fetch() if err != nil { return "", status.Errorf(codes.Internal, "Failed to fetch git repo: %v", err) } err = gitClient.Checkout(commitSHA) if err != nil { return "", status.Errorf(codes.Internal, "Failed to checkout %s: %v", commitSHA, err) } return gitClient.CommitSHA() }
[ "func", "checkoutRevision", "(", "gitClient", "git", ".", "Client", ",", "commitSHA", "string", ")", "(", "string", ",", "error", ")", "{", "err", ":=", "gitClient", ".", "Init", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "gitClient", ".", "Fetch", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "gitClient", ".", "Checkout", "(", "commitSHA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "commitSHA", ",", "err", ")", "\n", "}", "\n", "return", "gitClient", ".", "CommitSHA", "(", ")", "\n", "}" ]
// checkoutRevision is a convenience function to initialize a repo, fetch, and checkout a revision // Returns the 40 character commit SHA after the checkout has been performed
[ "checkoutRevision", "is", "a", "convenience", "function", "to", "initialize", "a", "repo", "fetch", "and", "checkout", "a", "revision", "Returns", "the", "40", "character", "commit", "SHA", "after", "the", "checkout", "has", "been", "performed" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L332-L346
162,058
argoproj/argo-cd
reposerver/repository/repository.go
ksShow
func ksShow(appLabelKey, appPath string, ksonnetOpts *v1alpha1.ApplicationSourceKsonnet) ([]*unstructured.Unstructured, *v1alpha1.ApplicationDestination, error) { ksApp, err := ksonnet.NewKsonnetApp(appPath) if err != nil { return nil, nil, status.Errorf(codes.FailedPrecondition, "unable to load application from %s: %v", appPath, err) } if ksonnetOpts == nil { return nil, nil, status.Errorf(codes.InvalidArgument, "Ksonnet environment not set") } for _, override := range ksonnetOpts.Parameters { err = ksApp.SetComponentParams(ksonnetOpts.Environment, override.Component, override.Name, override.Value) if err != nil { return nil, nil, err } } dest, err := ksApp.Destination(ksonnetOpts.Environment) if err != nil { return nil, nil, status.Errorf(codes.InvalidArgument, err.Error()) } targetObjs, err := ksApp.Show(ksonnetOpts.Environment) if err == nil && appLabelKey == common.LabelKeyLegacyApplicationName { // Address https://github.com/ksonnet/ksonnet/issues/707 for _, d := range targetObjs { kube.UnsetLabel(d, "ksonnet.io/component") } } if err != nil { return nil, nil, err } return targetObjs, dest, nil }
go
func ksShow(appLabelKey, appPath string, ksonnetOpts *v1alpha1.ApplicationSourceKsonnet) ([]*unstructured.Unstructured, *v1alpha1.ApplicationDestination, error) { ksApp, err := ksonnet.NewKsonnetApp(appPath) if err != nil { return nil, nil, status.Errorf(codes.FailedPrecondition, "unable to load application from %s: %v", appPath, err) } if ksonnetOpts == nil { return nil, nil, status.Errorf(codes.InvalidArgument, "Ksonnet environment not set") } for _, override := range ksonnetOpts.Parameters { err = ksApp.SetComponentParams(ksonnetOpts.Environment, override.Component, override.Name, override.Value) if err != nil { return nil, nil, err } } dest, err := ksApp.Destination(ksonnetOpts.Environment) if err != nil { return nil, nil, status.Errorf(codes.InvalidArgument, err.Error()) } targetObjs, err := ksApp.Show(ksonnetOpts.Environment) if err == nil && appLabelKey == common.LabelKeyLegacyApplicationName { // Address https://github.com/ksonnet/ksonnet/issues/707 for _, d := range targetObjs { kube.UnsetLabel(d, "ksonnet.io/component") } } if err != nil { return nil, nil, err } return targetObjs, dest, nil }
[ "func", "ksShow", "(", "appLabelKey", ",", "appPath", "string", ",", "ksonnetOpts", "*", "v1alpha1", ".", "ApplicationSourceKsonnet", ")", "(", "[", "]", "*", "unstructured", ".", "Unstructured", ",", "*", "v1alpha1", ".", "ApplicationDestination", ",", "error", ")", "{", "ksApp", ",", "err", ":=", "ksonnet", ".", "NewKsonnetApp", "(", "appPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ",", "appPath", ",", "err", ")", "\n", "}", "\n", "if", "ksonnetOpts", "==", "nil", "{", "return", "nil", ",", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "override", ":=", "range", "ksonnetOpts", ".", "Parameters", "{", "err", "=", "ksApp", ".", "SetComponentParams", "(", "ksonnetOpts", ".", "Environment", ",", "override", ".", "Component", ",", "override", ".", "Name", ",", "override", ".", "Value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "dest", ",", "err", ":=", "ksApp", ".", "Destination", "(", "ksonnetOpts", ".", "Environment", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "targetObjs", ",", "err", ":=", "ksApp", ".", "Show", "(", "ksonnetOpts", ".", "Environment", ")", "\n", "if", "err", "==", "nil", "&&", "appLabelKey", "==", "common", ".", "LabelKeyLegacyApplicationName", "{", "// Address https://github.com/ksonnet/ksonnet/issues/707", "for", "_", ",", "d", ":=", "range", "targetObjs", "{", "kube", ".", "UnsetLabel", "(", "d", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "targetObjs", ",", "dest", ",", "nil", "\n", "}" ]
// ksShow runs `ks show` in an app directory after setting any component parameter overrides
[ "ksShow", "runs", "ks", "show", "in", "an", "app", "directory", "after", "setting", "any", "component", "parameter", "overrides" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L349-L378
162,059
argoproj/argo-cd
reposerver/repository/repository.go
findManifests
func findManifests(appPath string, directory v1alpha1.ApplicationSourceDirectory) ([]*unstructured.Unstructured, error) { var objs []*unstructured.Unstructured err := filepath.Walk(appPath, func(path string, f os.FileInfo, err error) error { if err != nil { return err } if f.IsDir() { if path != appPath && !directory.Recurse { return filepath.SkipDir } else { return nil } } if !manifestFile.MatchString(f.Name()) { return nil } out, err := utfutil.ReadFile(path, utfutil.UTF8) if err != nil { return err } if strings.HasSuffix(f.Name(), ".json") { var obj unstructured.Unstructured err = json.Unmarshal(out, &obj) if err != nil { return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal %q: %v", f.Name(), err) } objs = append(objs, &obj) } else if strings.HasSuffix(f.Name(), ".jsonnet") { vm := makeJsonnetVm(directory.Jsonnet) vm.Importer(&jsonnet.FileImporter{ JPaths: []string{appPath}, }) jsonStr, err := vm.EvaluateSnippet(f.Name(), string(out)) if err != nil { return status.Errorf(codes.FailedPrecondition, "Failed to evaluate jsonnet %q: %v", f.Name(), err) } // attempt to unmarshal either array or single object var jsonObjs []*unstructured.Unstructured err = json.Unmarshal([]byte(jsonStr), &jsonObjs) if err == nil { objs = append(objs, jsonObjs...) } else { var jsonObj unstructured.Unstructured err = json.Unmarshal([]byte(jsonStr), &jsonObj) if err != nil { return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal generated json %q: %v", f.Name(), err) } objs = append(objs, &jsonObj) } } else { yamlObjs, err := kube.SplitYAML(string(out)) if err != nil { if len(yamlObjs) > 0 { // If we get here, we had a multiple objects in a single YAML file which had some // valid k8s objects, but errors parsing others (within the same file). It's very // likely the user messed up a portion of the YAML, so report on that. return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal %q: %v", f.Name(), err) } // Otherwise, it might be a unrelated YAML file which we will ignore return nil } objs = append(objs, yamlObjs...) } return nil }) if err != nil { return nil, err } return objs, nil }
go
func findManifests(appPath string, directory v1alpha1.ApplicationSourceDirectory) ([]*unstructured.Unstructured, error) { var objs []*unstructured.Unstructured err := filepath.Walk(appPath, func(path string, f os.FileInfo, err error) error { if err != nil { return err } if f.IsDir() { if path != appPath && !directory.Recurse { return filepath.SkipDir } else { return nil } } if !manifestFile.MatchString(f.Name()) { return nil } out, err := utfutil.ReadFile(path, utfutil.UTF8) if err != nil { return err } if strings.HasSuffix(f.Name(), ".json") { var obj unstructured.Unstructured err = json.Unmarshal(out, &obj) if err != nil { return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal %q: %v", f.Name(), err) } objs = append(objs, &obj) } else if strings.HasSuffix(f.Name(), ".jsonnet") { vm := makeJsonnetVm(directory.Jsonnet) vm.Importer(&jsonnet.FileImporter{ JPaths: []string{appPath}, }) jsonStr, err := vm.EvaluateSnippet(f.Name(), string(out)) if err != nil { return status.Errorf(codes.FailedPrecondition, "Failed to evaluate jsonnet %q: %v", f.Name(), err) } // attempt to unmarshal either array or single object var jsonObjs []*unstructured.Unstructured err = json.Unmarshal([]byte(jsonStr), &jsonObjs) if err == nil { objs = append(objs, jsonObjs...) } else { var jsonObj unstructured.Unstructured err = json.Unmarshal([]byte(jsonStr), &jsonObj) if err != nil { return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal generated json %q: %v", f.Name(), err) } objs = append(objs, &jsonObj) } } else { yamlObjs, err := kube.SplitYAML(string(out)) if err != nil { if len(yamlObjs) > 0 { // If we get here, we had a multiple objects in a single YAML file which had some // valid k8s objects, but errors parsing others (within the same file). It's very // likely the user messed up a portion of the YAML, so report on that. return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal %q: %v", f.Name(), err) } // Otherwise, it might be a unrelated YAML file which we will ignore return nil } objs = append(objs, yamlObjs...) } return nil }) if err != nil { return nil, err } return objs, nil }
[ "func", "findManifests", "(", "appPath", "string", ",", "directory", "v1alpha1", ".", "ApplicationSourceDirectory", ")", "(", "[", "]", "*", "unstructured", ".", "Unstructured", ",", "error", ")", "{", "var", "objs", "[", "]", "*", "unstructured", ".", "Unstructured", "\n", "err", ":=", "filepath", ".", "Walk", "(", "appPath", ",", "func", "(", "path", "string", ",", "f", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "f", ".", "IsDir", "(", ")", "{", "if", "path", "!=", "appPath", "&&", "!", "directory", ".", "Recurse", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "else", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "if", "!", "manifestFile", ".", "MatchString", "(", "f", ".", "Name", "(", ")", ")", "{", "return", "nil", "\n", "}", "\n", "out", ",", "err", ":=", "utfutil", ".", "ReadFile", "(", "path", ",", "utfutil", ".", "UTF8", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "f", ".", "Name", "(", ")", ",", "\"", "\"", ")", "{", "var", "obj", "unstructured", ".", "Unstructured", "\n", "err", "=", "json", ".", "Unmarshal", "(", "out", ",", "&", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "objs", "=", "append", "(", "objs", ",", "&", "obj", ")", "\n", "}", "else", "if", "strings", ".", "HasSuffix", "(", "f", ".", "Name", "(", ")", ",", "\"", "\"", ")", "{", "vm", ":=", "makeJsonnetVm", "(", "directory", ".", "Jsonnet", ")", "\n", "vm", ".", "Importer", "(", "&", "jsonnet", ".", "FileImporter", "{", "JPaths", ":", "[", "]", "string", "{", "appPath", "}", ",", "}", ")", "\n", "jsonStr", ",", "err", ":=", "vm", ".", "EvaluateSnippet", "(", "f", ".", "Name", "(", ")", ",", "string", "(", "out", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "// attempt to unmarshal either array or single object", "var", "jsonObjs", "[", "]", "*", "unstructured", ".", "Unstructured", "\n", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "jsonStr", ")", ",", "&", "jsonObjs", ")", "\n", "if", "err", "==", "nil", "{", "objs", "=", "append", "(", "objs", ",", "jsonObjs", "...", ")", "\n", "}", "else", "{", "var", "jsonObj", "unstructured", ".", "Unstructured", "\n", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "jsonStr", ")", ",", "&", "jsonObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "objs", "=", "append", "(", "objs", ",", "&", "jsonObj", ")", "\n", "}", "\n", "}", "else", "{", "yamlObjs", ",", "err", ":=", "kube", ".", "SplitYAML", "(", "string", "(", "out", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "len", "(", "yamlObjs", ")", ">", "0", "{", "// If we get here, we had a multiple objects in a single YAML file which had some", "// valid k8s objects, but errors parsing others (within the same file). It's very", "// likely the user messed up a portion of the YAML, so report on that.", "return", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "// Otherwise, it might be a unrelated YAML file which we will ignore", "return", "nil", "\n", "}", "\n", "objs", "=", "append", "(", "objs", ",", "yamlObjs", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "objs", ",", "nil", "\n", "}" ]
// findManifests looks at all yaml files in a directory and unmarshals them into a list of unstructured objects
[ "findManifests", "looks", "at", "all", "yaml", "files", "in", "a", "directory", "and", "unmarshals", "them", "into", "a", "list", "of", "unstructured", "objects" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L383-L454
162,060
argoproj/argo-cd
reposerver/repository/repository.go
pathExists
func pathExists(ss ...string) bool { name := filepath.Join(ss...) if _, err := os.Stat(name); err != nil { if os.IsNotExist(err) { return false } } return true }
go
func pathExists(ss ...string) bool { name := filepath.Join(ss...) if _, err := os.Stat(name); err != nil { if os.IsNotExist(err) { return false } } return true }
[ "func", "pathExists", "(", "ss", "...", "string", ")", "bool", "{", "name", ":=", "filepath", ".", "Join", "(", "ss", "...", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "name", ")", ";", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// pathExists reports whether the file or directory at the named concatenation of paths exists.
[ "pathExists", "reports", "whether", "the", "file", "or", "directory", "at", "the", "named", "concatenation", "of", "paths", "exists", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L478-L486
162,061
argoproj/argo-cd
reposerver/repository/repository.go
newClientResolveRevision
func (s *Service) newClientResolveRevision(repo *v1alpha1.Repository, revision string) (git.Client, string, error) { repoURL := git.NormalizeGitURL(repo.Repo) appRepoPath := tempRepoPath(repoURL) gitClient, err := s.gitFactory.NewClient(repo.Repo, appRepoPath, repo.Username, repo.Password, repo.SSHPrivateKey, repo.InsecureIgnoreHostKey) if err != nil { return nil, "", err } commitSHA, err := gitClient.LsRemote(revision) if err != nil { return nil, "", err } return gitClient, commitSHA, nil }
go
func (s *Service) newClientResolveRevision(repo *v1alpha1.Repository, revision string) (git.Client, string, error) { repoURL := git.NormalizeGitURL(repo.Repo) appRepoPath := tempRepoPath(repoURL) gitClient, err := s.gitFactory.NewClient(repo.Repo, appRepoPath, repo.Username, repo.Password, repo.SSHPrivateKey, repo.InsecureIgnoreHostKey) if err != nil { return nil, "", err } commitSHA, err := gitClient.LsRemote(revision) if err != nil { return nil, "", err } return gitClient, commitSHA, nil }
[ "func", "(", "s", "*", "Service", ")", "newClientResolveRevision", "(", "repo", "*", "v1alpha1", ".", "Repository", ",", "revision", "string", ")", "(", "git", ".", "Client", ",", "string", ",", "error", ")", "{", "repoURL", ":=", "git", ".", "NormalizeGitURL", "(", "repo", ".", "Repo", ")", "\n", "appRepoPath", ":=", "tempRepoPath", "(", "repoURL", ")", "\n", "gitClient", ",", "err", ":=", "s", ".", "gitFactory", ".", "NewClient", "(", "repo", ".", "Repo", ",", "appRepoPath", ",", "repo", ".", "Username", ",", "repo", ".", "Password", ",", "repo", ".", "SSHPrivateKey", ",", "repo", ".", "InsecureIgnoreHostKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "commitSHA", ",", "err", ":=", "gitClient", ".", "LsRemote", "(", "revision", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "gitClient", ",", "commitSHA", ",", "nil", "\n", "}" ]
// newClientResolveRevision is a helper to perform the common task of instantiating a git client // and resolving a revision to a commit SHA
[ "newClientResolveRevision", "is", "a", "helper", "to", "perform", "the", "common", "task", "of", "instantiating", "a", "git", "client", "and", "resolving", "a", "revision", "to", "a", "commit", "SHA" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/reposerver/repository/repository.go#L490-L502
162,062
argoproj/argo-cd
util/webhook/webhook.go
HandleEvent
func (a *ArgoCDWebhookHandler) HandleEvent(payload interface{}, header webhooks.Header) { webURL, revision, touchedHead := affectedRevisionInfo(payload) // NOTE: the webURL does not include the .git extension if webURL == "" { log.Info("Ignoring webhook event") return } log.Infof("Received push event repo: %s, revision: %s, touchedHead: %v", webURL, revision, touchedHead) appIf := a.appClientset.ArgoprojV1alpha1().Applications(a.ns) apps, err := appIf.List(metav1.ListOptions{}) if err != nil { log.Warnf("Failed to list applications: %v", err) return } urlObj, err := url.Parse(webURL) if err != nil { log.Warnf("Failed to parse repoURL '%s'", webURL) return } regexpStr := "(?i)(http://|https://|git@)" + urlObj.Host + "[:/]" + urlObj.Path[1:] + "(\\.git)?" repoRegexp, err := regexp.Compile(regexpStr) if err != nil { log.Warn("Failed to compile repoURL regexp") return } for _, app := range apps.Items { if !repoRegexp.MatchString(app.Spec.Source.RepoURL) { log.Debugf("%s does not match", app.Spec.Source.RepoURL) continue } targetRev := app.Spec.Source.TargetRevision if targetRev == "HEAD" || targetRev == "" { if !touchedHead { continue } } else if targetRev != revision { continue } _, err = argo.RefreshApp(appIf, app.ObjectMeta.Name, v1alpha1.RefreshTypeNormal) if err != nil { log.Warnf("Failed to refresh app '%s' for controller reprocessing: %v", app.ObjectMeta.Name, err) continue } } }
go
func (a *ArgoCDWebhookHandler) HandleEvent(payload interface{}, header webhooks.Header) { webURL, revision, touchedHead := affectedRevisionInfo(payload) // NOTE: the webURL does not include the .git extension if webURL == "" { log.Info("Ignoring webhook event") return } log.Infof("Received push event repo: %s, revision: %s, touchedHead: %v", webURL, revision, touchedHead) appIf := a.appClientset.ArgoprojV1alpha1().Applications(a.ns) apps, err := appIf.List(metav1.ListOptions{}) if err != nil { log.Warnf("Failed to list applications: %v", err) return } urlObj, err := url.Parse(webURL) if err != nil { log.Warnf("Failed to parse repoURL '%s'", webURL) return } regexpStr := "(?i)(http://|https://|git@)" + urlObj.Host + "[:/]" + urlObj.Path[1:] + "(\\.git)?" repoRegexp, err := regexp.Compile(regexpStr) if err != nil { log.Warn("Failed to compile repoURL regexp") return } for _, app := range apps.Items { if !repoRegexp.MatchString(app.Spec.Source.RepoURL) { log.Debugf("%s does not match", app.Spec.Source.RepoURL) continue } targetRev := app.Spec.Source.TargetRevision if targetRev == "HEAD" || targetRev == "" { if !touchedHead { continue } } else if targetRev != revision { continue } _, err = argo.RefreshApp(appIf, app.ObjectMeta.Name, v1alpha1.RefreshTypeNormal) if err != nil { log.Warnf("Failed to refresh app '%s' for controller reprocessing: %v", app.ObjectMeta.Name, err) continue } } }
[ "func", "(", "a", "*", "ArgoCDWebhookHandler", ")", "HandleEvent", "(", "payload", "interface", "{", "}", ",", "header", "webhooks", ".", "Header", ")", "{", "webURL", ",", "revision", ",", "touchedHead", ":=", "affectedRevisionInfo", "(", "payload", ")", "\n", "// NOTE: the webURL does not include the .git extension", "if", "webURL", "==", "\"", "\"", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "webURL", ",", "revision", ",", "touchedHead", ")", "\n", "appIf", ":=", "a", ".", "appClientset", ".", "ArgoprojV1alpha1", "(", ")", ".", "Applications", "(", "a", ".", "ns", ")", "\n", "apps", ",", "err", ":=", "appIf", ".", "List", "(", "metav1", ".", "ListOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "urlObj", ",", "err", ":=", "url", ".", "Parse", "(", "webURL", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "webURL", ")", "\n", "return", "\n", "}", "\n", "regexpStr", ":=", "\"", "\"", "+", "urlObj", ".", "Host", "+", "\"", "\"", "+", "urlObj", ".", "Path", "[", "1", ":", "]", "+", "\"", "\\\\", "\"", "\n", "repoRegexp", ",", "err", ":=", "regexp", ".", "Compile", "(", "regexpStr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "for", "_", ",", "app", ":=", "range", "apps", ".", "Items", "{", "if", "!", "repoRegexp", ".", "MatchString", "(", "app", ".", "Spec", ".", "Source", ".", "RepoURL", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "app", ".", "Spec", ".", "Source", ".", "RepoURL", ")", "\n", "continue", "\n", "}", "\n", "targetRev", ":=", "app", ".", "Spec", ".", "Source", ".", "TargetRevision", "\n", "if", "targetRev", "==", "\"", "\"", "||", "targetRev", "==", "\"", "\"", "{", "if", "!", "touchedHead", "{", "continue", "\n", "}", "\n", "}", "else", "if", "targetRev", "!=", "revision", "{", "continue", "\n", "}", "\n", "_", ",", "err", "=", "argo", ".", "RefreshApp", "(", "appIf", ",", "app", ".", "ObjectMeta", ".", "Name", ",", "v1alpha1", ".", "RefreshTypeNormal", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "app", ".", "ObjectMeta", ".", "Name", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// HandleEvent handles webhook events for repo push events
[ "HandleEvent", "handles", "webhook", "events", "for", "repo", "push", "events" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/webhook/webhook.go#L98-L143
162,063
argoproj/argo-cd
cmd/argocd/commands/relogin.go
NewReloginCommand
func NewReloginCommand(globalClientOpts *argocdclient.ClientOptions) *cobra.Command { var ( password string ssoPort int ) var command = &cobra.Command{ Use: "relogin", Short: "Refresh an expired authenticate token", Long: "Refresh an expired authenticate token", Run: func(c *cobra.Command, args []string) { if len(args) != 0 { c.HelpFunc()(c, args) os.Exit(1) } localCfg, err := localconfig.ReadLocalConfig(globalClientOpts.ConfigPath) errors.CheckError(err) if localCfg == nil { log.Fatalf("No context found. Login using `argocd login`") } configCtx, err := localCfg.ResolveContext(localCfg.CurrentContext) errors.CheckError(err) var tokenString string var refreshToken string clientOpts := argocdclient.ClientOptions{ ConfigPath: "", ServerAddr: configCtx.Server.Server, Insecure: configCtx.Server.Insecure, GRPCWeb: globalClientOpts.GRPCWeb, PlainText: configCtx.Server.PlainText, } acdClient := argocdclient.NewClientOrDie(&clientOpts) claims, err := configCtx.User.Claims() errors.CheckError(err) if claims.Issuer == session.SessionManagerClaimsIssuer { fmt.Printf("Relogging in as '%s'\n", claims.Subject) tokenString = passwordLogin(acdClient, claims.Subject, password) } else { fmt.Println("Reinitiating SSO login") setConn, setIf := acdClient.NewSettingsClientOrDie() defer util.Close(setConn) ctx := context.Background() httpClient, err := acdClient.HTTPClient() errors.CheckError(err) ctx = oidc.ClientContext(ctx, httpClient) acdSet, err := setIf.Get(ctx, &settings.SettingsQuery{}) errors.CheckError(err) oauth2conf, provider, err := acdClient.OIDCConfig(ctx, acdSet) errors.CheckError(err) tokenString, refreshToken = oauth2Login(ctx, ssoPort, oauth2conf, provider) } localCfg.UpsertUser(localconfig.User{ Name: localCfg.CurrentContext, AuthToken: tokenString, RefreshToken: refreshToken, }) err = localconfig.WriteLocalConfig(*localCfg, globalClientOpts.ConfigPath) errors.CheckError(err) fmt.Printf("Context '%s' updated\n", localCfg.CurrentContext) }, } command.Flags().StringVar(&password, "password", "", "the password of an account to authenticate") command.Flags().IntVar(&ssoPort, "sso-port", DefaultSSOLocalPort, "port to run local OAuth2 login application") return command }
go
func NewReloginCommand(globalClientOpts *argocdclient.ClientOptions) *cobra.Command { var ( password string ssoPort int ) var command = &cobra.Command{ Use: "relogin", Short: "Refresh an expired authenticate token", Long: "Refresh an expired authenticate token", Run: func(c *cobra.Command, args []string) { if len(args) != 0 { c.HelpFunc()(c, args) os.Exit(1) } localCfg, err := localconfig.ReadLocalConfig(globalClientOpts.ConfigPath) errors.CheckError(err) if localCfg == nil { log.Fatalf("No context found. Login using `argocd login`") } configCtx, err := localCfg.ResolveContext(localCfg.CurrentContext) errors.CheckError(err) var tokenString string var refreshToken string clientOpts := argocdclient.ClientOptions{ ConfigPath: "", ServerAddr: configCtx.Server.Server, Insecure: configCtx.Server.Insecure, GRPCWeb: globalClientOpts.GRPCWeb, PlainText: configCtx.Server.PlainText, } acdClient := argocdclient.NewClientOrDie(&clientOpts) claims, err := configCtx.User.Claims() errors.CheckError(err) if claims.Issuer == session.SessionManagerClaimsIssuer { fmt.Printf("Relogging in as '%s'\n", claims.Subject) tokenString = passwordLogin(acdClient, claims.Subject, password) } else { fmt.Println("Reinitiating SSO login") setConn, setIf := acdClient.NewSettingsClientOrDie() defer util.Close(setConn) ctx := context.Background() httpClient, err := acdClient.HTTPClient() errors.CheckError(err) ctx = oidc.ClientContext(ctx, httpClient) acdSet, err := setIf.Get(ctx, &settings.SettingsQuery{}) errors.CheckError(err) oauth2conf, provider, err := acdClient.OIDCConfig(ctx, acdSet) errors.CheckError(err) tokenString, refreshToken = oauth2Login(ctx, ssoPort, oauth2conf, provider) } localCfg.UpsertUser(localconfig.User{ Name: localCfg.CurrentContext, AuthToken: tokenString, RefreshToken: refreshToken, }) err = localconfig.WriteLocalConfig(*localCfg, globalClientOpts.ConfigPath) errors.CheckError(err) fmt.Printf("Context '%s' updated\n", localCfg.CurrentContext) }, } command.Flags().StringVar(&password, "password", "", "the password of an account to authenticate") command.Flags().IntVar(&ssoPort, "sso-port", DefaultSSOLocalPort, "port to run local OAuth2 login application") return command }
[ "func", "NewReloginCommand", "(", "globalClientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "(", "password", "string", "\n", "ssoPort", "int", "\n", ")", "\n", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Long", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "0", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "localCfg", ",", "err", ":=", "localconfig", ".", "ReadLocalConfig", "(", "globalClientOpts", ".", "ConfigPath", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "if", "localCfg", "==", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ")", "\n", "}", "\n", "configCtx", ",", "err", ":=", "localCfg", ".", "ResolveContext", "(", "localCfg", ".", "CurrentContext", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n\n", "var", "tokenString", "string", "\n", "var", "refreshToken", "string", "\n", "clientOpts", ":=", "argocdclient", ".", "ClientOptions", "{", "ConfigPath", ":", "\"", "\"", ",", "ServerAddr", ":", "configCtx", ".", "Server", ".", "Server", ",", "Insecure", ":", "configCtx", ".", "Server", ".", "Insecure", ",", "GRPCWeb", ":", "globalClientOpts", ".", "GRPCWeb", ",", "PlainText", ":", "configCtx", ".", "Server", ".", "PlainText", ",", "}", "\n", "acdClient", ":=", "argocdclient", ".", "NewClientOrDie", "(", "&", "clientOpts", ")", "\n", "claims", ",", "err", ":=", "configCtx", ".", "User", ".", "Claims", "(", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "if", "claims", ".", "Issuer", "==", "session", ".", "SessionManagerClaimsIssuer", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "claims", ".", "Subject", ")", "\n", "tokenString", "=", "passwordLogin", "(", "acdClient", ",", "claims", ".", "Subject", ",", "password", ")", "\n", "}", "else", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "setConn", ",", "setIf", ":=", "acdClient", ".", "NewSettingsClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "setConn", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "httpClient", ",", "err", ":=", "acdClient", ".", "HTTPClient", "(", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "ctx", "=", "oidc", ".", "ClientContext", "(", "ctx", ",", "httpClient", ")", "\n", "acdSet", ",", "err", ":=", "setIf", ".", "Get", "(", "ctx", ",", "&", "settings", ".", "SettingsQuery", "{", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "oauth2conf", ",", "provider", ",", "err", ":=", "acdClient", ".", "OIDCConfig", "(", "ctx", ",", "acdSet", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "tokenString", ",", "refreshToken", "=", "oauth2Login", "(", "ctx", ",", "ssoPort", ",", "oauth2conf", ",", "provider", ")", "\n", "}", "\n\n", "localCfg", ".", "UpsertUser", "(", "localconfig", ".", "User", "{", "Name", ":", "localCfg", ".", "CurrentContext", ",", "AuthToken", ":", "tokenString", ",", "RefreshToken", ":", "refreshToken", ",", "}", ")", "\n", "err", "=", "localconfig", ".", "WriteLocalConfig", "(", "*", "localCfg", ",", "globalClientOpts", ".", "ConfigPath", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "localCfg", ".", "CurrentContext", ")", "\n", "}", ",", "}", "\n", "command", ".", "Flags", "(", ")", ".", "StringVar", "(", "&", "password", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "command", ".", "Flags", "(", ")", ".", "IntVar", "(", "&", "ssoPort", ",", "\"", "\"", ",", "DefaultSSOLocalPort", ",", "\"", "\"", ")", "\n", "return", "command", "\n", "}" ]
// NewReloginCommand returns a new instance of `argocd relogin` command
[ "NewReloginCommand", "returns", "a", "new", "instance", "of", "argocd", "relogin", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/relogin.go#L21-L86
162,064
argoproj/argo-cd
pkg/client/informers/externalversions/application/v1alpha1/interface.go
AppProjects
func (v *version) AppProjects() AppProjectInformer { return &appProjectInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
go
func (v *version) AppProjects() AppProjectInformer { return &appProjectInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
[ "func", "(", "v", "*", "version", ")", "AppProjects", "(", ")", "AppProjectInformer", "{", "return", "&", "appProjectInformer", "{", "factory", ":", "v", ".", "factory", ",", "namespace", ":", "v", ".", "namespace", ",", "tweakListOptions", ":", "v", ".", "tweakListOptions", "}", "\n", "}" ]
// AppProjects returns a AppProjectInformer.
[ "AppProjects", "returns", "a", "AppProjectInformer", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/informers/externalversions/application/v1alpha1/interface.go#L29-L31
162,065
argoproj/argo-cd
pkg/client/informers/externalversions/application/v1alpha1/interface.go
Applications
func (v *version) Applications() ApplicationInformer { return &applicationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
go
func (v *version) Applications() ApplicationInformer { return &applicationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
[ "func", "(", "v", "*", "version", ")", "Applications", "(", ")", "ApplicationInformer", "{", "return", "&", "applicationInformer", "{", "factory", ":", "v", ".", "factory", ",", "namespace", ":", "v", ".", "namespace", ",", "tweakListOptions", ":", "v", ".", "tweakListOptions", "}", "\n", "}" ]
// Applications returns a ApplicationInformer.
[ "Applications", "returns", "a", "ApplicationInformer", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/pkg/client/informers/externalversions/application/v1alpha1/interface.go#L34-L36
162,066
argoproj/argo-cd
util/util.go
DeleteFile
func DeleteFile(path string) { if _, err := os.Stat(path); os.IsNotExist(err) { return } _ = os.Remove(path) }
go
func DeleteFile(path string) { if _, err := os.Stat(path); os.IsNotExist(err) { return } _ = os.Remove(path) }
[ "func", "DeleteFile", "(", "path", "string", ")", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "\n", "}", "\n", "_", "=", "os", ".", "Remove", "(", "path", ")", "\n", "}" ]
// DeleteFile is best effort deletion of a file
[ "DeleteFile", "is", "best", "effort", "deletion", "of", "a", "file" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/util.go#L42-L47
162,067
argoproj/argo-cd
util/util.go
MakeSignature
func MakeSignature(size int) ([]byte, error) { b := make([]byte, size) _, err := rand.Read(b) if err != nil { b = nil } // base64 encode it so signing key can be typed into validation utilities b = []byte(base64.StdEncoding.EncodeToString(b)) return b, err }
go
func MakeSignature(size int) ([]byte, error) { b := make([]byte, size) _, err := rand.Read(b) if err != nil { b = nil } // base64 encode it so signing key can be typed into validation utilities b = []byte(base64.StdEncoding.EncodeToString(b)) return b, err }
[ "func", "MakeSignature", "(", "size", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "_", ",", "err", ":=", "rand", ".", "Read", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "b", "=", "nil", "\n", "}", "\n", "// base64 encode it so signing key can be typed into validation utilities", "b", "=", "[", "]", "byte", "(", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "b", ")", ")", "\n", "return", "b", ",", "err", "\n", "}" ]
// MakeSignature generates a cryptographically-secure pseudo-random token, based on a given number of random bytes, for signing purposes.
[ "MakeSignature", "generates", "a", "cryptographically", "-", "secure", "pseudo", "-", "random", "token", "based", "on", "a", "given", "number", "of", "random", "bytes", "for", "signing", "purposes", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/util.go#L74-L83
162,068
argoproj/argo-cd
util/util.go
RetryUntilSucceed
func RetryUntilSucceed(action func() error, desc string, ctx context.Context, timeout time.Duration) { ctxCompleted := false stop := make(chan bool) defer close(stop) go func() { select { case <-ctx.Done(): ctxCompleted = true case <-stop: } }() for { log.Debugf("Start %s", desc) err := action() if err == nil { log.Debugf("Completed %s", desc) return } if ctxCompleted { log.Debugf("Stop retrying %s", desc) return } log.Debugf("Failed to %s: %+v, retrying in %v", desc, err, timeout) time.Sleep(timeout) } }
go
func RetryUntilSucceed(action func() error, desc string, ctx context.Context, timeout time.Duration) { ctxCompleted := false stop := make(chan bool) defer close(stop) go func() { select { case <-ctx.Done(): ctxCompleted = true case <-stop: } }() for { log.Debugf("Start %s", desc) err := action() if err == nil { log.Debugf("Completed %s", desc) return } if ctxCompleted { log.Debugf("Stop retrying %s", desc) return } log.Debugf("Failed to %s: %+v, retrying in %v", desc, err, timeout) time.Sleep(timeout) } }
[ "func", "RetryUntilSucceed", "(", "action", "func", "(", ")", "error", ",", "desc", "string", ",", "ctx", "context", ".", "Context", ",", "timeout", "time", ".", "Duration", ")", "{", "ctxCompleted", ":=", "false", "\n", "stop", ":=", "make", "(", "chan", "bool", ")", "\n", "defer", "close", "(", "stop", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "ctxCompleted", "=", "true", "\n", "case", "<-", "stop", ":", "}", "\n", "}", "(", ")", "\n", "for", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "desc", ")", "\n", "err", ":=", "action", "(", ")", "\n", "if", "err", "==", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "desc", ")", "\n", "return", "\n", "}", "\n", "if", "ctxCompleted", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "desc", ")", "\n", "return", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "desc", ",", "err", ",", "timeout", ")", "\n", "time", ".", "Sleep", "(", "timeout", ")", "\n\n", "}", "\n", "}" ]
// RetryUntilSucceed keep retrying given action with specified timeout until action succeed or specified context is done.
[ "RetryUntilSucceed", "keep", "retrying", "given", "action", "with", "specified", "timeout", "until", "action", "succeed", "or", "specified", "context", "is", "done", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/util.go#L86-L112
162,069
argoproj/argo-cd
util/lua/lua.go
ExecuteHealthLua
func (vm VM) ExecuteHealthLua(obj *unstructured.Unstructured, script string) (*appv1.HealthStatus, error) { l, err := vm.runLua(obj, script) if err != nil { return nil, err } returnValue := l.Get(-1) if returnValue.Type() == lua.LTTable { jsonBytes, err := luajson.Encode(returnValue) if err != nil { return nil, err } healthStatus := &appv1.HealthStatus{} err = json.Unmarshal(jsonBytes, healthStatus) if err != nil { return nil, err } if !isValidHealthStatusCode(healthStatus.Status) { return &appv1.HealthStatus{ Status: appv1.HealthStatusUnknown, Message: invalidHealthStatus, }, nil } return healthStatus, nil } return nil, fmt.Errorf(incorrectReturnType, "table", returnValue.Type().String()) }
go
func (vm VM) ExecuteHealthLua(obj *unstructured.Unstructured, script string) (*appv1.HealthStatus, error) { l, err := vm.runLua(obj, script) if err != nil { return nil, err } returnValue := l.Get(-1) if returnValue.Type() == lua.LTTable { jsonBytes, err := luajson.Encode(returnValue) if err != nil { return nil, err } healthStatus := &appv1.HealthStatus{} err = json.Unmarshal(jsonBytes, healthStatus) if err != nil { return nil, err } if !isValidHealthStatusCode(healthStatus.Status) { return &appv1.HealthStatus{ Status: appv1.HealthStatusUnknown, Message: invalidHealthStatus, }, nil } return healthStatus, nil } return nil, fmt.Errorf(incorrectReturnType, "table", returnValue.Type().String()) }
[ "func", "(", "vm", "VM", ")", "ExecuteHealthLua", "(", "obj", "*", "unstructured", ".", "Unstructured", ",", "script", "string", ")", "(", "*", "appv1", ".", "HealthStatus", ",", "error", ")", "{", "l", ",", "err", ":=", "vm", ".", "runLua", "(", "obj", ",", "script", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "returnValue", ":=", "l", ".", "Get", "(", "-", "1", ")", "\n", "if", "returnValue", ".", "Type", "(", ")", "==", "lua", ".", "LTTable", "{", "jsonBytes", ",", "err", ":=", "luajson", ".", "Encode", "(", "returnValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "healthStatus", ":=", "&", "appv1", ".", "HealthStatus", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "jsonBytes", ",", "healthStatus", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "isValidHealthStatusCode", "(", "healthStatus", ".", "Status", ")", "{", "return", "&", "appv1", ".", "HealthStatus", "{", "Status", ":", "appv1", ".", "HealthStatusUnknown", ",", "Message", ":", "invalidHealthStatus", ",", "}", ",", "nil", "\n", "}", "\n\n", "return", "healthStatus", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "incorrectReturnType", ",", "\"", "\"", ",", "returnValue", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "}" ]
// ExecuteHealthLua runs the lua script to generate the health status of a resource
[ "ExecuteHealthLua", "runs", "the", "lua", "script", "to", "generate", "the", "health", "status", "of", "a", "resource" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/lua/lua.go#L76-L102
162,070
argoproj/argo-cd
util/lua/lua.go
GetHealthScript
func (vm VM) GetHealthScript(obj *unstructured.Unstructured) (string, error) { key := getConfigMapKey(obj) if script, ok := vm.ResourceOverrides[key]; ok && script.HealthLua != "" { return script.HealthLua, nil } return vm.getPredefinedLuaScripts(key, healthScriptFile) }
go
func (vm VM) GetHealthScript(obj *unstructured.Unstructured) (string, error) { key := getConfigMapKey(obj) if script, ok := vm.ResourceOverrides[key]; ok && script.HealthLua != "" { return script.HealthLua, nil } return vm.getPredefinedLuaScripts(key, healthScriptFile) }
[ "func", "(", "vm", "VM", ")", "GetHealthScript", "(", "obj", "*", "unstructured", ".", "Unstructured", ")", "(", "string", ",", "error", ")", "{", "key", ":=", "getConfigMapKey", "(", "obj", ")", "\n", "if", "script", ",", "ok", ":=", "vm", ".", "ResourceOverrides", "[", "key", "]", ";", "ok", "&&", "script", ".", "HealthLua", "!=", "\"", "\"", "{", "return", "script", ".", "HealthLua", ",", "nil", "\n", "}", "\n", "return", "vm", ".", "getPredefinedLuaScripts", "(", "key", ",", "healthScriptFile", ")", "\n", "}" ]
// GetHealthScript attempts to read lua script from config and then filesystem for that resource
[ "GetHealthScript", "attempts", "to", "read", "lua", "script", "from", "config", "and", "then", "filesystem", "for", "that", "resource" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/lua/lua.go#L105-L111
162,071
argoproj/argo-cd
util/lua/lua.go
cleanReturnedObj
func cleanReturnedObj(newObj, obj map[string]interface{}) map[string]interface{} { mapToReturn := newObj for key := range obj { if newValueInterface, ok := newObj[key]; ok { oldValueInterface, ok := obj[key] if !ok { continue } switch newValue := newValueInterface.(type) { case map[string]interface{}: if oldValue, ok := oldValueInterface.(map[string]interface{}); ok { convertedMap := cleanReturnedObj(newValue, oldValue) mapToReturn[key] = convertedMap } case []interface{}: switch oldValue := oldValueInterface.(type) { case map[string]interface{}: if len(newValue) == 0 { mapToReturn[key] = oldValue } case []interface{}: newArray := cleanReturnedArray(newValue, oldValue) mapToReturn[key] = newArray } } } } return mapToReturn }
go
func cleanReturnedObj(newObj, obj map[string]interface{}) map[string]interface{} { mapToReturn := newObj for key := range obj { if newValueInterface, ok := newObj[key]; ok { oldValueInterface, ok := obj[key] if !ok { continue } switch newValue := newValueInterface.(type) { case map[string]interface{}: if oldValue, ok := oldValueInterface.(map[string]interface{}); ok { convertedMap := cleanReturnedObj(newValue, oldValue) mapToReturn[key] = convertedMap } case []interface{}: switch oldValue := oldValueInterface.(type) { case map[string]interface{}: if len(newValue) == 0 { mapToReturn[key] = oldValue } case []interface{}: newArray := cleanReturnedArray(newValue, oldValue) mapToReturn[key] = newArray } } } } return mapToReturn }
[ "func", "cleanReturnedObj", "(", "newObj", ",", "obj", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "mapToReturn", ":=", "newObj", "\n", "for", "key", ":=", "range", "obj", "{", "if", "newValueInterface", ",", "ok", ":=", "newObj", "[", "key", "]", ";", "ok", "{", "oldValueInterface", ",", "ok", ":=", "obj", "[", "key", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "switch", "newValue", ":=", "newValueInterface", ".", "(", "type", ")", "{", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "if", "oldValue", ",", "ok", ":=", "oldValueInterface", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "convertedMap", ":=", "cleanReturnedObj", "(", "newValue", ",", "oldValue", ")", "\n", "mapToReturn", "[", "key", "]", "=", "convertedMap", "\n", "}", "\n\n", "case", "[", "]", "interface", "{", "}", ":", "switch", "oldValue", ":=", "oldValueInterface", ".", "(", "type", ")", "{", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "if", "len", "(", "newValue", ")", "==", "0", "{", "mapToReturn", "[", "key", "]", "=", "oldValue", "\n", "}", "\n", "case", "[", "]", "interface", "{", "}", ":", "newArray", ":=", "cleanReturnedArray", "(", "newValue", ",", "oldValue", ")", "\n", "mapToReturn", "[", "key", "]", "=", "newArray", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "mapToReturn", "\n", "}" ]
// cleanReturnedObj Lua cannot distinguish an empty table as an array or map, and the library we are using choose to // decoded an empty table into an empty array. This function prevents the lua scripts from unintentionally changing an // empty struct into empty arrays
[ "cleanReturnedObj", "Lua", "cannot", "distinguish", "an", "empty", "table", "as", "an", "array", "or", "map", "and", "the", "library", "we", "are", "using", "choose", "to", "decoded", "an", "empty", "table", "into", "an", "empty", "array", ".", "This", "function", "prevents", "the", "lua", "scripts", "from", "unintentionally", "changing", "an", "empty", "struct", "into", "empty", "arrays" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/lua/lua.go#L138-L167
162,072
argoproj/argo-cd
util/lua/lua.go
cleanReturnedArray
func cleanReturnedArray(newObj, obj []interface{}) []interface{} { arrayToReturn := newObj for i := range newObj { switch newValue := newObj[i].(type) { case map[string]interface{}: if oldValue, ok := obj[i].(map[string]interface{}); ok { convertedMap := cleanReturnedObj(newValue, oldValue) arrayToReturn[i] = convertedMap } case []interface{}: if oldValue, ok := obj[i].([]interface{}); ok { convertedMap := cleanReturnedArray(newValue, oldValue) arrayToReturn[i] = convertedMap } } } return arrayToReturn }
go
func cleanReturnedArray(newObj, obj []interface{}) []interface{} { arrayToReturn := newObj for i := range newObj { switch newValue := newObj[i].(type) { case map[string]interface{}: if oldValue, ok := obj[i].(map[string]interface{}); ok { convertedMap := cleanReturnedObj(newValue, oldValue) arrayToReturn[i] = convertedMap } case []interface{}: if oldValue, ok := obj[i].([]interface{}); ok { convertedMap := cleanReturnedArray(newValue, oldValue) arrayToReturn[i] = convertedMap } } } return arrayToReturn }
[ "func", "cleanReturnedArray", "(", "newObj", ",", "obj", "[", "]", "interface", "{", "}", ")", "[", "]", "interface", "{", "}", "{", "arrayToReturn", ":=", "newObj", "\n", "for", "i", ":=", "range", "newObj", "{", "switch", "newValue", ":=", "newObj", "[", "i", "]", ".", "(", "type", ")", "{", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "if", "oldValue", ",", "ok", ":=", "obj", "[", "i", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "convertedMap", ":=", "cleanReturnedObj", "(", "newValue", ",", "oldValue", ")", "\n", "arrayToReturn", "[", "i", "]", "=", "convertedMap", "\n", "}", "\n", "case", "[", "]", "interface", "{", "}", ":", "if", "oldValue", ",", "ok", ":=", "obj", "[", "i", "]", ".", "(", "[", "]", "interface", "{", "}", ")", ";", "ok", "{", "convertedMap", ":=", "cleanReturnedArray", "(", "newValue", ",", "oldValue", ")", "\n", "arrayToReturn", "[", "i", "]", "=", "convertedMap", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "arrayToReturn", "\n", "}" ]
// cleanReturnedArray allows Argo CD to recurse into nested arrays when checking for unintentional empty struct to // empty array conversions.
[ "cleanReturnedArray", "allows", "Argo", "CD", "to", "recurse", "into", "nested", "arrays", "when", "checking", "for", "unintentional", "empty", "struct", "to", "empty", "array", "conversions", "." ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/lua/lua.go#L171-L188
162,073
argoproj/argo-cd
util/lua/lua.go
GetResourceAction
func (vm VM) GetResourceAction(obj *unstructured.Unstructured, actionName string) (appv1.ResourceActionDefinition, error) { key := getConfigMapKey(obj) override, ok := vm.ResourceOverrides[key] if ok && override.Actions != "" { actions, err := override.GetActions() if err != nil { return appv1.ResourceActionDefinition{}, err } for _, action := range actions.Definitions { if action.Name == actionName { return action, nil } } } actionKey := fmt.Sprintf("%s/actions/%s", key, actionName) actionScript, err := vm.getPredefinedLuaScripts(actionKey, actionScriptFile) if err != nil { return appv1.ResourceActionDefinition{}, err } return appv1.ResourceActionDefinition{ Name: actionName, ActionLua: actionScript, }, nil }
go
func (vm VM) GetResourceAction(obj *unstructured.Unstructured, actionName string) (appv1.ResourceActionDefinition, error) { key := getConfigMapKey(obj) override, ok := vm.ResourceOverrides[key] if ok && override.Actions != "" { actions, err := override.GetActions() if err != nil { return appv1.ResourceActionDefinition{}, err } for _, action := range actions.Definitions { if action.Name == actionName { return action, nil } } } actionKey := fmt.Sprintf("%s/actions/%s", key, actionName) actionScript, err := vm.getPredefinedLuaScripts(actionKey, actionScriptFile) if err != nil { return appv1.ResourceActionDefinition{}, err } return appv1.ResourceActionDefinition{ Name: actionName, ActionLua: actionScript, }, nil }
[ "func", "(", "vm", "VM", ")", "GetResourceAction", "(", "obj", "*", "unstructured", ".", "Unstructured", ",", "actionName", "string", ")", "(", "appv1", ".", "ResourceActionDefinition", ",", "error", ")", "{", "key", ":=", "getConfigMapKey", "(", "obj", ")", "\n", "override", ",", "ok", ":=", "vm", ".", "ResourceOverrides", "[", "key", "]", "\n", "if", "ok", "&&", "override", ".", "Actions", "!=", "\"", "\"", "{", "actions", ",", "err", ":=", "override", ".", "GetActions", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "appv1", ".", "ResourceActionDefinition", "{", "}", ",", "err", "\n", "}", "\n", "for", "_", ",", "action", ":=", "range", "actions", ".", "Definitions", "{", "if", "action", ".", "Name", "==", "actionName", "{", "return", "action", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "actionKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ",", "actionName", ")", "\n", "actionScript", ",", "err", ":=", "vm", ".", "getPredefinedLuaScripts", "(", "actionKey", ",", "actionScriptFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "appv1", ".", "ResourceActionDefinition", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "appv1", ".", "ResourceActionDefinition", "{", "Name", ":", "actionName", ",", "ActionLua", ":", "actionScript", ",", "}", ",", "nil", "\n", "}" ]
// GetResourceAction attempts to read lua script from config and then filesystem for that resource
[ "GetResourceAction", "attempts", "to", "read", "lua", "script", "from", "config", "and", "then", "filesystem", "for", "that", "resource" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/lua/lua.go#L265-L290
162,074
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectCommand
func NewProjectCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "proj", Short: "Manage projects", Run: func(c *cobra.Command, args []string) { c.HelpFunc()(c, args) os.Exit(1) }, } command.AddCommand(NewProjectRoleCommand(clientOpts)) command.AddCommand(NewProjectCreateCommand(clientOpts)) command.AddCommand(NewProjectGetCommand(clientOpts)) command.AddCommand(NewProjectDeleteCommand(clientOpts)) command.AddCommand(NewProjectListCommand(clientOpts)) command.AddCommand(NewProjectSetCommand(clientOpts)) command.AddCommand(NewProjectEditCommand(clientOpts)) command.AddCommand(NewProjectAddDestinationCommand(clientOpts)) command.AddCommand(NewProjectRemoveDestinationCommand(clientOpts)) command.AddCommand(NewProjectAddSourceCommand(clientOpts)) command.AddCommand(NewProjectRemoveSourceCommand(clientOpts)) command.AddCommand(NewProjectAllowClusterResourceCommand(clientOpts)) command.AddCommand(NewProjectDenyClusterResourceCommand(clientOpts)) command.AddCommand(NewProjectAllowNamespaceResourceCommand(clientOpts)) command.AddCommand(NewProjectDenyNamespaceResourceCommand(clientOpts)) return command }
go
func NewProjectCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "proj", Short: "Manage projects", Run: func(c *cobra.Command, args []string) { c.HelpFunc()(c, args) os.Exit(1) }, } command.AddCommand(NewProjectRoleCommand(clientOpts)) command.AddCommand(NewProjectCreateCommand(clientOpts)) command.AddCommand(NewProjectGetCommand(clientOpts)) command.AddCommand(NewProjectDeleteCommand(clientOpts)) command.AddCommand(NewProjectListCommand(clientOpts)) command.AddCommand(NewProjectSetCommand(clientOpts)) command.AddCommand(NewProjectEditCommand(clientOpts)) command.AddCommand(NewProjectAddDestinationCommand(clientOpts)) command.AddCommand(NewProjectRemoveDestinationCommand(clientOpts)) command.AddCommand(NewProjectAddSourceCommand(clientOpts)) command.AddCommand(NewProjectRemoveSourceCommand(clientOpts)) command.AddCommand(NewProjectAllowClusterResourceCommand(clientOpts)) command.AddCommand(NewProjectDenyClusterResourceCommand(clientOpts)) command.AddCommand(NewProjectAllowNamespaceResourceCommand(clientOpts)) command.AddCommand(NewProjectDenyNamespaceResourceCommand(clientOpts)) return command }
[ "func", "NewProjectCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", ",", "}", "\n", "command", ".", "AddCommand", "(", "NewProjectRoleCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectCreateCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectGetCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectDeleteCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectListCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectSetCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectEditCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectAddDestinationCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectRemoveDestinationCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectAddSourceCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectRemoveSourceCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectAllowClusterResourceCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectDenyClusterResourceCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectAllowNamespaceResourceCommand", "(", "clientOpts", ")", ")", "\n", "command", ".", "AddCommand", "(", "NewProjectDenyNamespaceResourceCommand", "(", "clientOpts", ")", ")", "\n", "return", "command", "\n", "}" ]
// NewProjectCommand returns a new instance of an `argocd proj` command
[ "NewProjectCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L58-L83
162,075
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectCreateCommand
func NewProjectCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var ( opts projectOpts ) var command = &cobra.Command{ Use: "create PROJECT", Short: "Create a project", Run: func(c *cobra.Command, args []string) { if len(args) == 0 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] proj := v1alpha1.AppProject{ ObjectMeta: v1.ObjectMeta{Name: projName}, Spec: v1alpha1.AppProjectSpec{ Description: opts.description, Destinations: opts.GetDestinations(), SourceRepos: opts.sources, }, } conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) _, err := projIf.Create(context.Background(), &project.ProjectCreateRequest{Project: &proj}) errors.CheckError(err) }, } addProjFlags(command, &opts) return command }
go
func NewProjectCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var ( opts projectOpts ) var command = &cobra.Command{ Use: "create PROJECT", Short: "Create a project", Run: func(c *cobra.Command, args []string) { if len(args) == 0 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] proj := v1alpha1.AppProject{ ObjectMeta: v1.ObjectMeta{Name: projName}, Spec: v1alpha1.AppProjectSpec{ Description: opts.description, Destinations: opts.GetDestinations(), SourceRepos: opts.sources, }, } conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) _, err := projIf.Create(context.Background(), &project.ProjectCreateRequest{Project: &proj}) errors.CheckError(err) }, } addProjFlags(command, &opts) return command }
[ "func", "NewProjectCreateCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "(", "opts", "projectOpts", "\n", ")", "\n", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "==", "0", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "projName", ":=", "args", "[", "0", "]", "\n", "proj", ":=", "v1alpha1", ".", "AppProject", "{", "ObjectMeta", ":", "v1", ".", "ObjectMeta", "{", "Name", ":", "projName", "}", ",", "Spec", ":", "v1alpha1", ".", "AppProjectSpec", "{", "Description", ":", "opts", ".", "description", ",", "Destinations", ":", "opts", ".", "GetDestinations", "(", ")", ",", "SourceRepos", ":", "opts", ".", "sources", ",", "}", ",", "}", "\n", "conn", ",", "projIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewProjectClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n\n", "_", ",", "err", ":=", "projIf", ".", "Create", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectCreateRequest", "{", "Project", ":", "&", "proj", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "}", ",", "}", "\n", "addProjFlags", "(", "command", ",", "&", "opts", ")", "\n", "return", "command", "\n", "}" ]
// NewProjectCreateCommand returns a new instance of an `argocd proj create` command
[ "NewProjectCreateCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "create", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L104-L134
162,076
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectSetCommand
func NewProjectSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var ( opts projectOpts ) var command = &cobra.Command{ Use: "set PROJECT", Short: "Set project parameters", Run: func(c *cobra.Command, args []string) { if len(args) == 0 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) proj, err := projIf.Get(context.Background(), &project.ProjectQuery{Name: projName}) errors.CheckError(err) visited := 0 c.Flags().Visit(func(f *pflag.Flag) { visited++ switch f.Name { case "description": proj.Spec.Description = opts.description case "dest": proj.Spec.Destinations = opts.GetDestinations() case "src": proj.Spec.SourceRepos = opts.sources } }) if visited == 0 { log.Error("Please set at least one option to update") c.HelpFunc()(c, args) os.Exit(1) } _, err = projIf.Update(context.Background(), &project.ProjectUpdateRequest{Project: proj}) errors.CheckError(err) }, } addProjFlags(command, &opts) return command }
go
func NewProjectSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var ( opts projectOpts ) var command = &cobra.Command{ Use: "set PROJECT", Short: "Set project parameters", Run: func(c *cobra.Command, args []string) { if len(args) == 0 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) proj, err := projIf.Get(context.Background(), &project.ProjectQuery{Name: projName}) errors.CheckError(err) visited := 0 c.Flags().Visit(func(f *pflag.Flag) { visited++ switch f.Name { case "description": proj.Spec.Description = opts.description case "dest": proj.Spec.Destinations = opts.GetDestinations() case "src": proj.Spec.SourceRepos = opts.sources } }) if visited == 0 { log.Error("Please set at least one option to update") c.HelpFunc()(c, args) os.Exit(1) } _, err = projIf.Update(context.Background(), &project.ProjectUpdateRequest{Project: proj}) errors.CheckError(err) }, } addProjFlags(command, &opts) return command }
[ "func", "NewProjectSetCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "(", "opts", "projectOpts", "\n", ")", "\n", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "==", "0", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "projName", ":=", "args", "[", "0", "]", "\n", "conn", ",", "projIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewProjectClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n\n", "proj", ",", "err", ":=", "projIf", ".", "Get", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectQuery", "{", "Name", ":", "projName", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n\n", "visited", ":=", "0", "\n", "c", ".", "Flags", "(", ")", ".", "Visit", "(", "func", "(", "f", "*", "pflag", ".", "Flag", ")", "{", "visited", "++", "\n", "switch", "f", ".", "Name", "{", "case", "\"", "\"", ":", "proj", ".", "Spec", ".", "Description", "=", "opts", ".", "description", "\n", "case", "\"", "\"", ":", "proj", ".", "Spec", ".", "Destinations", "=", "opts", ".", "GetDestinations", "(", ")", "\n", "case", "\"", "\"", ":", "proj", ".", "Spec", ".", "SourceRepos", "=", "opts", ".", "sources", "\n", "}", "\n", "}", ")", "\n", "if", "visited", "==", "0", "{", "log", ".", "Error", "(", "\"", "\"", ")", "\n", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "projIf", ".", "Update", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectUpdateRequest", "{", "Project", ":", "proj", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "}", ",", "}", "\n", "addProjFlags", "(", "command", ",", "&", "opts", ")", "\n", "return", "command", "\n", "}" ]
// NewProjectSetCommand returns a new instance of an `argocd proj set` command
[ "NewProjectSetCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "set", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L137-L180
162,077
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectAddDestinationCommand
func NewProjectAddDestinationCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "add-destination PROJECT SERVER NAMESPACE", Short: "Add project destination", Run: func(c *cobra.Command, args []string) { if len(args) != 3 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] server := args[1] namespace := args[2] conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) proj, err := projIf.Get(context.Background(), &project.ProjectQuery{Name: projName}) errors.CheckError(err) for _, dest := range proj.Spec.Destinations { if dest.Namespace == namespace && dest.Server == server { log.Fatal("Specified destination is already defined in project") } } proj.Spec.Destinations = append(proj.Spec.Destinations, v1alpha1.ApplicationDestination{Server: server, Namespace: namespace}) _, err = projIf.Update(context.Background(), &project.ProjectUpdateRequest{Project: proj}) errors.CheckError(err) }, } return command }
go
func NewProjectAddDestinationCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "add-destination PROJECT SERVER NAMESPACE", Short: "Add project destination", Run: func(c *cobra.Command, args []string) { if len(args) != 3 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] server := args[1] namespace := args[2] conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) proj, err := projIf.Get(context.Background(), &project.ProjectQuery{Name: projName}) errors.CheckError(err) for _, dest := range proj.Spec.Destinations { if dest.Namespace == namespace && dest.Server == server { log.Fatal("Specified destination is already defined in project") } } proj.Spec.Destinations = append(proj.Spec.Destinations, v1alpha1.ApplicationDestination{Server: server, Namespace: namespace}) _, err = projIf.Update(context.Background(), &project.ProjectUpdateRequest{Project: proj}) errors.CheckError(err) }, } return command }
[ "func", "NewProjectAddDestinationCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "3", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "projName", ":=", "args", "[", "0", "]", "\n", "server", ":=", "args", "[", "1", "]", "\n", "namespace", ":=", "args", "[", "2", "]", "\n", "conn", ",", "projIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewProjectClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n\n", "proj", ",", "err", ":=", "projIf", ".", "Get", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectQuery", "{", "Name", ":", "projName", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n\n", "for", "_", ",", "dest", ":=", "range", "proj", ".", "Spec", ".", "Destinations", "{", "if", "dest", ".", "Namespace", "==", "namespace", "&&", "dest", ".", "Server", "==", "server", "{", "log", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "proj", ".", "Spec", ".", "Destinations", "=", "append", "(", "proj", ".", "Spec", ".", "Destinations", ",", "v1alpha1", ".", "ApplicationDestination", "{", "Server", ":", "server", ",", "Namespace", ":", "namespace", "}", ")", "\n", "_", ",", "err", "=", "projIf", ".", "Update", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectUpdateRequest", "{", "Project", ":", "proj", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "}", ",", "}", "\n", "return", "command", "\n", "}" ]
// NewProjectAddDestinationCommand returns a new instance of an `argocd proj add-destination` command
[ "NewProjectAddDestinationCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "add", "-", "destination", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L183-L212
162,078
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectAllowNamespaceResourceCommand
func NewProjectAllowNamespaceResourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { use := "allow-namespace-resource PROJECT GROUP KIND" desc := "Removes a namespaced API resource from the blacklist" return modifyProjectResourceCmd(use, desc, clientOpts, func(proj *v1alpha1.AppProject, group string, kind string) bool { index := -1 for i, item := range proj.Spec.NamespaceResourceBlacklist { if item.Group == group && item.Kind == kind { index = i break } } if index == -1 { fmt.Printf("Group '%s' and kind '%s' not in blacklisted namespaced resources\n", group, kind) return false } proj.Spec.NamespaceResourceBlacklist = append(proj.Spec.NamespaceResourceBlacklist[:index], proj.Spec.NamespaceResourceBlacklist[index+1:]...) return true }) }
go
func NewProjectAllowNamespaceResourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { use := "allow-namespace-resource PROJECT GROUP KIND" desc := "Removes a namespaced API resource from the blacklist" return modifyProjectResourceCmd(use, desc, clientOpts, func(proj *v1alpha1.AppProject, group string, kind string) bool { index := -1 for i, item := range proj.Spec.NamespaceResourceBlacklist { if item.Group == group && item.Kind == kind { index = i break } } if index == -1 { fmt.Printf("Group '%s' and kind '%s' not in blacklisted namespaced resources\n", group, kind) return false } proj.Spec.NamespaceResourceBlacklist = append(proj.Spec.NamespaceResourceBlacklist[:index], proj.Spec.NamespaceResourceBlacklist[index+1:]...) return true }) }
[ "func", "NewProjectAllowNamespaceResourceCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "use", ":=", "\"", "\"", "\n", "desc", ":=", "\"", "\"", "\n", "return", "modifyProjectResourceCmd", "(", "use", ",", "desc", ",", "clientOpts", ",", "func", "(", "proj", "*", "v1alpha1", ".", "AppProject", ",", "group", "string", ",", "kind", "string", ")", "bool", "{", "index", ":=", "-", "1", "\n", "for", "i", ",", "item", ":=", "range", "proj", ".", "Spec", ".", "NamespaceResourceBlacklist", "{", "if", "item", ".", "Group", "==", "group", "&&", "item", ".", "Kind", "==", "kind", "{", "index", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "index", "==", "-", "1", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "group", ",", "kind", ")", "\n", "return", "false", "\n", "}", "\n", "proj", ".", "Spec", ".", "NamespaceResourceBlacklist", "=", "append", "(", "proj", ".", "Spec", ".", "NamespaceResourceBlacklist", "[", ":", "index", "]", ",", "proj", ".", "Spec", ".", "NamespaceResourceBlacklist", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// NewProjectAllowNamespaceResourceCommand returns a new instance of an `deny-cluster-resources` command
[ "NewProjectAllowNamespaceResourceCommand", "returns", "a", "new", "instance", "of", "an", "deny", "-", "cluster", "-", "resources", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L314-L332
162,079
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectDenyNamespaceResourceCommand
func NewProjectDenyNamespaceResourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { use := "deny-namespace-resource PROJECT GROUP KIND" desc := "Adds a namespaced API resource to the blacklist" return modifyProjectResourceCmd(use, desc, clientOpts, func(proj *v1alpha1.AppProject, group string, kind string) bool { for _, item := range proj.Spec.NamespaceResourceBlacklist { if item.Group == group && item.Kind == kind { fmt.Printf("Group '%s' and kind '%s' already present in blacklisted namespaced resources\n", group, kind) return false } } proj.Spec.NamespaceResourceBlacklist = append(proj.Spec.NamespaceResourceBlacklist, v1.GroupKind{Group: group, Kind: kind}) return true }) }
go
func NewProjectDenyNamespaceResourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { use := "deny-namespace-resource PROJECT GROUP KIND" desc := "Adds a namespaced API resource to the blacklist" return modifyProjectResourceCmd(use, desc, clientOpts, func(proj *v1alpha1.AppProject, group string, kind string) bool { for _, item := range proj.Spec.NamespaceResourceBlacklist { if item.Group == group && item.Kind == kind { fmt.Printf("Group '%s' and kind '%s' already present in blacklisted namespaced resources\n", group, kind) return false } } proj.Spec.NamespaceResourceBlacklist = append(proj.Spec.NamespaceResourceBlacklist, v1.GroupKind{Group: group, Kind: kind}) return true }) }
[ "func", "NewProjectDenyNamespaceResourceCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "use", ":=", "\"", "\"", "\n", "desc", ":=", "\"", "\"", "\n", "return", "modifyProjectResourceCmd", "(", "use", ",", "desc", ",", "clientOpts", ",", "func", "(", "proj", "*", "v1alpha1", ".", "AppProject", ",", "group", "string", ",", "kind", "string", ")", "bool", "{", "for", "_", ",", "item", ":=", "range", "proj", ".", "Spec", ".", "NamespaceResourceBlacklist", "{", "if", "item", ".", "Group", "==", "group", "&&", "item", ".", "Kind", "==", "kind", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "group", ",", "kind", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "proj", ".", "Spec", ".", "NamespaceResourceBlacklist", "=", "append", "(", "proj", ".", "Spec", ".", "NamespaceResourceBlacklist", ",", "v1", ".", "GroupKind", "{", "Group", ":", "group", ",", "Kind", ":", "kind", "}", ")", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// NewProjectDenyNamespaceResourceCommand returns a new instance of an `argocd proj deny-namespace-resource` command
[ "NewProjectDenyNamespaceResourceCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "deny", "-", "namespace", "-", "resource", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L335-L348
162,080
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectRemoveSourceCommand
func NewProjectRemoveSourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "remove-source PROJECT URL", Short: "Remove project source repository", Run: func(c *cobra.Command, args []string) { if len(args) != 2 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] url := args[1] conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) proj, err := projIf.Get(context.Background(), &project.ProjectQuery{Name: projName}) errors.CheckError(err) index := -1 for i, item := range proj.Spec.SourceRepos { if item == url { index = i break } } if index == -1 { fmt.Printf("Source repository '%s' does not exist in project\n", url) } else { proj.Spec.SourceRepos = append(proj.Spec.SourceRepos[:index], proj.Spec.SourceRepos[index+1:]...) _, err = projIf.Update(context.Background(), &project.ProjectUpdateRequest{Project: proj}) errors.CheckError(err) } }, } return command }
go
func NewProjectRemoveSourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "remove-source PROJECT URL", Short: "Remove project source repository", Run: func(c *cobra.Command, args []string) { if len(args) != 2 { c.HelpFunc()(c, args) os.Exit(1) } projName := args[0] url := args[1] conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) proj, err := projIf.Get(context.Background(), &project.ProjectQuery{Name: projName}) errors.CheckError(err) index := -1 for i, item := range proj.Spec.SourceRepos { if item == url { index = i break } } if index == -1 { fmt.Printf("Source repository '%s' does not exist in project\n", url) } else { proj.Spec.SourceRepos = append(proj.Spec.SourceRepos[:index], proj.Spec.SourceRepos[index+1:]...) _, err = projIf.Update(context.Background(), &project.ProjectUpdateRequest{Project: proj}) errors.CheckError(err) } }, } return command }
[ "func", "NewProjectRemoveSourceCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "projName", ":=", "args", "[", "0", "]", "\n", "url", ":=", "args", "[", "1", "]", "\n", "conn", ",", "projIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewProjectClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n\n", "proj", ",", "err", ":=", "projIf", ".", "Get", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectQuery", "{", "Name", ":", "projName", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n\n", "index", ":=", "-", "1", "\n", "for", "i", ",", "item", ":=", "range", "proj", ".", "Spec", ".", "SourceRepos", "{", "if", "item", "==", "url", "{", "index", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "index", "==", "-", "1", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "url", ")", "\n", "}", "else", "{", "proj", ".", "Spec", ".", "SourceRepos", "=", "append", "(", "proj", ".", "Spec", ".", "SourceRepos", "[", ":", "index", "]", ",", "proj", ".", "Spec", ".", "SourceRepos", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "_", ",", "err", "=", "projIf", ".", "Update", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectUpdateRequest", "{", "Project", ":", "proj", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "}", "\n", "}", ",", "}", "\n\n", "return", "command", "\n", "}" ]
// NewProjectRemoveSourceCommand returns a new instance of an `argocd proj remove-src` command
[ "NewProjectRemoveSourceCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "remove", "-", "src", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L388-L423
162,081
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectDeleteCommand
func NewProjectDeleteCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "delete PROJECT", Short: "Delete project", Run: func(c *cobra.Command, args []string) { if len(args) == 0 { c.HelpFunc()(c, args) os.Exit(1) } conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) for _, name := range args { _, err := projIf.Delete(context.Background(), &project.ProjectQuery{Name: name}) errors.CheckError(err) } }, } return command }
go
func NewProjectDeleteCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "delete PROJECT", Short: "Delete project", Run: func(c *cobra.Command, args []string) { if len(args) == 0 { c.HelpFunc()(c, args) os.Exit(1) } conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) for _, name := range args { _, err := projIf.Delete(context.Background(), &project.ProjectQuery{Name: name}) errors.CheckError(err) } }, } return command }
[ "func", "NewProjectDeleteCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "==", "0", "{", "c", ".", "HelpFunc", "(", ")", "(", "c", ",", "args", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "conn", ",", "projIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewProjectClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n", "for", "_", ",", "name", ":=", "range", "args", "{", "_", ",", "err", ":=", "projIf", ".", "Delete", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectQuery", "{", "Name", ":", "name", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "}", "\n", "}", ",", "}", "\n", "return", "command", "\n", "}" ]
// NewProjectDeleteCommand returns a new instance of an `argocd proj delete` command
[ "NewProjectDeleteCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "delete", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L426-L444
162,082
argoproj/argo-cd
cmd/argocd/commands/project.go
NewProjectListCommand
func NewProjectListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "list", Short: "List projects", Run: func(c *cobra.Command, args []string) { conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) projects, err := projIf.List(context.Background(), &project.ProjectQuery{}) errors.CheckError(err) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintf(w, "NAME\tDESCRIPTION\tDESTINATIONS\tSOURCES\tCLUSTER-RESOURCE-WHITELIST\tNAMESPACE-RESOURCE-BLACKLIST\n") for _, p := range projects.Items { printProjectLine(w, &p) } _ = w.Flush() }, } return command }
go
func NewProjectListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command { var command = &cobra.Command{ Use: "list", Short: "List projects", Run: func(c *cobra.Command, args []string) { conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie() defer util.Close(conn) projects, err := projIf.List(context.Background(), &project.ProjectQuery{}) errors.CheckError(err) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintf(w, "NAME\tDESCRIPTION\tDESTINATIONS\tSOURCES\tCLUSTER-RESOURCE-WHITELIST\tNAMESPACE-RESOURCE-BLACKLIST\n") for _, p := range projects.Items { printProjectLine(w, &p) } _ = w.Flush() }, } return command }
[ "func", "NewProjectListCommand", "(", "clientOpts", "*", "argocdclient", ".", "ClientOptions", ")", "*", "cobra", ".", "Command", "{", "var", "command", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Run", ":", "func", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "conn", ",", "projIf", ":=", "argocdclient", ".", "NewClientOrDie", "(", "clientOpts", ")", ".", "NewProjectClientOrDie", "(", ")", "\n", "defer", "util", ".", "Close", "(", "conn", ")", "\n", "projects", ",", "err", ":=", "projIf", ".", "List", "(", "context", ".", "Background", "(", ")", ",", "&", "project", ".", "ProjectQuery", "{", "}", ")", "\n", "errors", ".", "CheckError", "(", "err", ")", "\n", "w", ":=", "tabwriter", ".", "NewWriter", "(", "os", ".", "Stdout", ",", "0", ",", "0", ",", "2", ",", "' '", ",", "0", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\n", "\"", ")", "\n", "for", "_", ",", "p", ":=", "range", "projects", ".", "Items", "{", "printProjectLine", "(", "w", ",", "&", "p", ")", "\n", "}", "\n", "_", "=", "w", ".", "Flush", "(", ")", "\n", "}", ",", "}", "\n", "return", "command", "\n", "}" ]
// NewProjectListCommand returns a new instance of an `argocd proj list` command
[ "NewProjectListCommand", "returns", "a", "new", "instance", "of", "an", "argocd", "proj", "list", "command" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/cmd/argocd/commands/project.go#L447-L465
162,083
argoproj/argo-cd
util/argo/diff_normalizer.go
NewDiffNormalizer
func NewDiffNormalizer(ignore []v1alpha1.ResourceIgnoreDifferences, overrides map[string]v1alpha1.ResourceOverride) (diff.Normalizer, error) { for key, override := range overrides { parts := strings.Split(key, "/") if len(parts) < 2 { continue } group := parts[0] kind := parts[1] if override.IgnoreDifferences != "" { ignoreSettings := overrideIgnoreDiff{} err := yaml.Unmarshal([]byte(override.IgnoreDifferences), &ignoreSettings) if err != nil { return nil, err } ignore = append(ignore, v1alpha1.ResourceIgnoreDifferences{ Group: group, Kind: kind, JSONPointers: ignoreSettings.JSONPointers, }) } } patches := make([]normalizerPatch, 0) for i := range ignore { for _, path := range ignore[i].JSONPointers { patchData, err := json.Marshal([]map[string]string{{"op": "remove", "path": path}}) if err != nil { return nil, err } patch, err := jsonpatch.DecodePatch(patchData) if err != nil { return nil, err } patches = append(patches, normalizerPatch{ groupKind: schema.GroupKind{Group: ignore[i].Group, Kind: ignore[i].Kind}, name: ignore[i].Name, namespace: ignore[i].Namespace, patch: patch, }) } } return &normalizer{patches: patches}, nil }
go
func NewDiffNormalizer(ignore []v1alpha1.ResourceIgnoreDifferences, overrides map[string]v1alpha1.ResourceOverride) (diff.Normalizer, error) { for key, override := range overrides { parts := strings.Split(key, "/") if len(parts) < 2 { continue } group := parts[0] kind := parts[1] if override.IgnoreDifferences != "" { ignoreSettings := overrideIgnoreDiff{} err := yaml.Unmarshal([]byte(override.IgnoreDifferences), &ignoreSettings) if err != nil { return nil, err } ignore = append(ignore, v1alpha1.ResourceIgnoreDifferences{ Group: group, Kind: kind, JSONPointers: ignoreSettings.JSONPointers, }) } } patches := make([]normalizerPatch, 0) for i := range ignore { for _, path := range ignore[i].JSONPointers { patchData, err := json.Marshal([]map[string]string{{"op": "remove", "path": path}}) if err != nil { return nil, err } patch, err := jsonpatch.DecodePatch(patchData) if err != nil { return nil, err } patches = append(patches, normalizerPatch{ groupKind: schema.GroupKind{Group: ignore[i].Group, Kind: ignore[i].Kind}, name: ignore[i].Name, namespace: ignore[i].Namespace, patch: patch, }) } } return &normalizer{patches: patches}, nil }
[ "func", "NewDiffNormalizer", "(", "ignore", "[", "]", "v1alpha1", ".", "ResourceIgnoreDifferences", ",", "overrides", "map", "[", "string", "]", "v1alpha1", ".", "ResourceOverride", ")", "(", "diff", ".", "Normalizer", ",", "error", ")", "{", "for", "key", ",", "override", ":=", "range", "overrides", "{", "parts", ":=", "strings", ".", "Split", "(", "key", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "<", "2", "{", "continue", "\n", "}", "\n", "group", ":=", "parts", "[", "0", "]", "\n", "kind", ":=", "parts", "[", "1", "]", "\n", "if", "override", ".", "IgnoreDifferences", "!=", "\"", "\"", "{", "ignoreSettings", ":=", "overrideIgnoreDiff", "{", "}", "\n", "err", ":=", "yaml", ".", "Unmarshal", "(", "[", "]", "byte", "(", "override", ".", "IgnoreDifferences", ")", ",", "&", "ignoreSettings", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ignore", "=", "append", "(", "ignore", ",", "v1alpha1", ".", "ResourceIgnoreDifferences", "{", "Group", ":", "group", ",", "Kind", ":", "kind", ",", "JSONPointers", ":", "ignoreSettings", ".", "JSONPointers", ",", "}", ")", "\n", "}", "\n", "}", "\n", "patches", ":=", "make", "(", "[", "]", "normalizerPatch", ",", "0", ")", "\n", "for", "i", ":=", "range", "ignore", "{", "for", "_", ",", "path", ":=", "range", "ignore", "[", "i", "]", ".", "JSONPointers", "{", "patchData", ",", "err", ":=", "json", ".", "Marshal", "(", "[", "]", "map", "[", "string", "]", "string", "{", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "path", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "patch", ",", "err", ":=", "jsonpatch", ".", "DecodePatch", "(", "patchData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "patches", "=", "append", "(", "patches", ",", "normalizerPatch", "{", "groupKind", ":", "schema", ".", "GroupKind", "{", "Group", ":", "ignore", "[", "i", "]", ".", "Group", ",", "Kind", ":", "ignore", "[", "i", "]", ".", "Kind", "}", ",", "name", ":", "ignore", "[", "i", "]", ".", "Name", ",", "namespace", ":", "ignore", "[", "i", "]", ".", "Namespace", ",", "patch", ":", "patch", ",", "}", ")", "\n", "}", "\n\n", "}", "\n", "return", "&", "normalizer", "{", "patches", ":", "patches", "}", ",", "nil", "\n", "}" ]
// NewDiffNormalizer creates diff normalizer which removes ignored fields according to given application spec and resource overrides
[ "NewDiffNormalizer", "creates", "diff", "normalizer", "which", "removes", "ignored", "fields", "according", "to", "given", "application", "spec", "and", "resource", "overrides" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/argo/diff_normalizer.go#L33-L76
162,084
argoproj/argo-cd
util/argo/diff_normalizer.go
Normalize
func (n *normalizer) Normalize(un *unstructured.Unstructured) error { matched := make([]normalizerPatch, 0) for _, patch := range n.patches { groupKind := un.GroupVersionKind().GroupKind() if groupKind == patch.groupKind && (patch.name == "" || patch.name == un.GetName()) && (patch.namespace == "" || patch.namespace == un.GetNamespace()) { matched = append(matched, patch) } } if len(matched) == 0 { return nil } docData, err := json.Marshal(un) if err != nil { return err } for _, patch := range matched { patchedData, err := patch.patch.Apply(docData) if err != nil { // bug? if strings.HasPrefix(err.Error(), "Unable to remove nonexistent key") { continue } return err } docData = patchedData } err = json.Unmarshal(docData, un) if err != nil { return err } return nil }
go
func (n *normalizer) Normalize(un *unstructured.Unstructured) error { matched := make([]normalizerPatch, 0) for _, patch := range n.patches { groupKind := un.GroupVersionKind().GroupKind() if groupKind == patch.groupKind && (patch.name == "" || patch.name == un.GetName()) && (patch.namespace == "" || patch.namespace == un.GetNamespace()) { matched = append(matched, patch) } } if len(matched) == 0 { return nil } docData, err := json.Marshal(un) if err != nil { return err } for _, patch := range matched { patchedData, err := patch.patch.Apply(docData) if err != nil { // bug? if strings.HasPrefix(err.Error(), "Unable to remove nonexistent key") { continue } return err } docData = patchedData } err = json.Unmarshal(docData, un) if err != nil { return err } return nil }
[ "func", "(", "n", "*", "normalizer", ")", "Normalize", "(", "un", "*", "unstructured", ".", "Unstructured", ")", "error", "{", "matched", ":=", "make", "(", "[", "]", "normalizerPatch", ",", "0", ")", "\n", "for", "_", ",", "patch", ":=", "range", "n", ".", "patches", "{", "groupKind", ":=", "un", ".", "GroupVersionKind", "(", ")", ".", "GroupKind", "(", ")", "\n", "if", "groupKind", "==", "patch", ".", "groupKind", "&&", "(", "patch", ".", "name", "==", "\"", "\"", "||", "patch", ".", "name", "==", "un", ".", "GetName", "(", ")", ")", "&&", "(", "patch", ".", "namespace", "==", "\"", "\"", "||", "patch", ".", "namespace", "==", "un", ".", "GetNamespace", "(", ")", ")", "{", "matched", "=", "append", "(", "matched", ",", "patch", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "matched", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "docData", ",", "err", ":=", "json", ".", "Marshal", "(", "un", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "patch", ":=", "range", "matched", "{", "patchedData", ",", "err", ":=", "patch", ".", "patch", ".", "Apply", "(", "docData", ")", "\n", "if", "err", "!=", "nil", "{", "// bug?", "if", "strings", ".", "HasPrefix", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "docData", "=", "patchedData", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "docData", ",", "un", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize removes fields from supplied resource using json paths from matching items of specified resources ignored differences list
[ "Normalize", "removes", "fields", "from", "supplied", "resource", "using", "json", "paths", "from", "matching", "items", "of", "specified", "resources", "ignored", "differences", "list" ]
5c353a12f2c67d8ab0d5d9aa619c9059c5261640
https://github.com/argoproj/argo-cd/blob/5c353a12f2c67d8ab0d5d9aa619c9059c5261640/util/argo/diff_normalizer.go#L79-L116
162,085
blevesearch/bleve
index/scorch/snapshot_index.go
subtractStrings
func subtractStrings(a, b []string) []string { if len(b) == 0 { return a } rv := make([]string, 0, len(a)) OUTER: for _, as := range a { for _, bs := range b { if as == bs { continue OUTER } } rv = append(rv, as) } return rv }
go
func subtractStrings(a, b []string) []string { if len(b) == 0 { return a } rv := make([]string, 0, len(a)) OUTER: for _, as := range a { for _, bs := range b { if as == bs { continue OUTER } } rv = append(rv, as) } return rv }
[ "func", "subtractStrings", "(", "a", ",", "b", "[", "]", "string", ")", "[", "]", "string", "{", "if", "len", "(", "b", ")", "==", "0", "{", "return", "a", "\n", "}", "\n\n", "rv", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "a", ")", ")", "\n", "OUTER", ":", "for", "_", ",", "as", ":=", "range", "a", "{", "for", "_", ",", "bs", ":=", "range", "b", "{", "if", "as", "==", "bs", "{", "continue", "OUTER", "\n", "}", "\n", "}", "\n", "rv", "=", "append", "(", "rv", ",", "as", ")", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// subtractStrings returns set a minus elements of set b.
[ "subtractStrings", "returns", "set", "a", "minus", "elements", "of", "set", "b", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/snapshot_index.go#L679-L695
162,086
blevesearch/bleve
index/scorch/segment/zap/build.go
PersistSegmentBase
func PersistSegmentBase(sb *SegmentBase, path string) error { flag := os.O_RDWR | os.O_CREATE f, err := os.OpenFile(path, flag, 0600) if err != nil { return err } cleanup := func() { _ = f.Close() _ = os.Remove(path) } br := bufio.NewWriter(f) _, err = br.Write(sb.mem) if err != nil { cleanup() return err } err = persistFooter(sb.numDocs, sb.storedIndexOffset, sb.fieldsIndexOffset, sb.docValueOffset, sb.chunkFactor, sb.memCRC, br) if err != nil { cleanup() return err } err = br.Flush() if err != nil { cleanup() return err } err = f.Sync() if err != nil { cleanup() return err } err = f.Close() if err != nil { cleanup() return err } return nil }
go
func PersistSegmentBase(sb *SegmentBase, path string) error { flag := os.O_RDWR | os.O_CREATE f, err := os.OpenFile(path, flag, 0600) if err != nil { return err } cleanup := func() { _ = f.Close() _ = os.Remove(path) } br := bufio.NewWriter(f) _, err = br.Write(sb.mem) if err != nil { cleanup() return err } err = persistFooter(sb.numDocs, sb.storedIndexOffset, sb.fieldsIndexOffset, sb.docValueOffset, sb.chunkFactor, sb.memCRC, br) if err != nil { cleanup() return err } err = br.Flush() if err != nil { cleanup() return err } err = f.Sync() if err != nil { cleanup() return err } err = f.Close() if err != nil { cleanup() return err } return nil }
[ "func", "PersistSegmentBase", "(", "sb", "*", "SegmentBase", ",", "path", "string", ")", "error", "{", "flag", ":=", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", "\n\n", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "flag", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cleanup", ":=", "func", "(", ")", "{", "_", "=", "f", ".", "Close", "(", ")", "\n", "_", "=", "os", ".", "Remove", "(", "path", ")", "\n", "}", "\n\n", "br", ":=", "bufio", ".", "NewWriter", "(", "f", ")", "\n\n", "_", ",", "err", "=", "br", ".", "Write", "(", "sb", ".", "mem", ")", "\n", "if", "err", "!=", "nil", "{", "cleanup", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "err", "=", "persistFooter", "(", "sb", ".", "numDocs", ",", "sb", ".", "storedIndexOffset", ",", "sb", ".", "fieldsIndexOffset", ",", "sb", ".", "docValueOffset", ",", "sb", ".", "chunkFactor", ",", "sb", ".", "memCRC", ",", "br", ")", "\n", "if", "err", "!=", "nil", "{", "cleanup", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "err", "=", "br", ".", "Flush", "(", ")", "\n", "if", "err", "!=", "nil", "{", "cleanup", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "err", "=", "f", ".", "Sync", "(", ")", "\n", "if", "err", "!=", "nil", "{", "cleanup", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "err", "=", "f", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "cleanup", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PersistSegmentBase persists SegmentBase in the zap file format.
[ "PersistSegmentBase", "persists", "SegmentBase", "in", "the", "zap", "file", "format", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/build.go#L31-L78
162,087
blevesearch/bleve
search/query/term_range.go
NewTermRangeQuery
func NewTermRangeQuery(min, max string) *TermRangeQuery { return NewTermRangeInclusiveQuery(min, max, nil, nil) }
go
func NewTermRangeQuery(min, max string) *TermRangeQuery { return NewTermRangeInclusiveQuery(min, max, nil, nil) }
[ "func", "NewTermRangeQuery", "(", "min", ",", "max", "string", ")", "*", "TermRangeQuery", "{", "return", "NewTermRangeInclusiveQuery", "(", "min", ",", "max", ",", "nil", ",", "nil", ")", "\n", "}" ]
// NewTermRangeQuery creates a new Query for ranges // of text term values. // Either, but not both endpoints can be nil. // The minimum value is inclusive. // The maximum value is exclusive.
[ "NewTermRangeQuery", "creates", "a", "new", "Query", "for", "ranges", "of", "text", "term", "values", ".", "Either", "but", "not", "both", "endpoints", "can", "be", "nil", ".", "The", "minimum", "value", "is", "inclusive", ".", "The", "maximum", "value", "is", "exclusive", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/query/term_range.go#L40-L42
162,088
blevesearch/bleve
search/query/term_range.go
NewTermRangeInclusiveQuery
func NewTermRangeInclusiveQuery(min, max string, minInclusive, maxInclusive *bool) *TermRangeQuery { return &TermRangeQuery{ Min: min, Max: max, InclusiveMin: minInclusive, InclusiveMax: maxInclusive, } }
go
func NewTermRangeInclusiveQuery(min, max string, minInclusive, maxInclusive *bool) *TermRangeQuery { return &TermRangeQuery{ Min: min, Max: max, InclusiveMin: minInclusive, InclusiveMax: maxInclusive, } }
[ "func", "NewTermRangeInclusiveQuery", "(", "min", ",", "max", "string", ",", "minInclusive", ",", "maxInclusive", "*", "bool", ")", "*", "TermRangeQuery", "{", "return", "&", "TermRangeQuery", "{", "Min", ":", "min", ",", "Max", ":", "max", ",", "InclusiveMin", ":", "minInclusive", ",", "InclusiveMax", ":", "maxInclusive", ",", "}", "\n", "}" ]
// NewTermRangeInclusiveQuery creates a new Query for ranges // of numeric values. // Either, but not both endpoints can be nil. // Control endpoint inclusion with inclusiveMin, inclusiveMax.
[ "NewTermRangeInclusiveQuery", "creates", "a", "new", "Query", "for", "ranges", "of", "numeric", "values", ".", "Either", "but", "not", "both", "endpoints", "can", "be", "nil", ".", "Control", "endpoint", "inclusion", "with", "inclusiveMin", "inclusiveMax", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/query/term_range.go#L48-L55
162,089
blevesearch/bleve
search/levenshtein.go
LevenshteinDistanceMax
func LevenshteinDistanceMax(a, b string, max int) (int, bool) { v, wasMax, _ := LevenshteinDistanceMaxReuseSlice(a, b, max, nil) return v, wasMax }
go
func LevenshteinDistanceMax(a, b string, max int) (int, bool) { v, wasMax, _ := LevenshteinDistanceMaxReuseSlice(a, b, max, nil) return v, wasMax }
[ "func", "LevenshteinDistanceMax", "(", "a", ",", "b", "string", ",", "max", "int", ")", "(", "int", ",", "bool", ")", "{", "v", ",", "wasMax", ",", "_", ":=", "LevenshteinDistanceMaxReuseSlice", "(", "a", ",", "b", ",", "max", ",", "nil", ")", "\n", "return", "v", ",", "wasMax", "\n", "}" ]
// LevenshteinDistanceMax same as LevenshteinDistance but // attempts to bail early once we know the distance // will be greater than max // in which case the first return val will be the max // and the second will be true, indicating max was exceeded
[ "LevenshteinDistanceMax", "same", "as", "LevenshteinDistance", "but", "attempts", "to", "bail", "early", "once", "we", "know", "the", "distance", "will", "be", "greater", "than", "max", "in", "which", "case", "the", "first", "return", "val", "will", "be", "the", "max", "and", "the", "second", "will", "be", "true", "indicating", "max", "was", "exceeded" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/levenshtein.go#L59-L62
162,090
blevesearch/bleve
search/sort.go
Compare
func (so SortOrder) Compare(cachedScoring, cachedDesc []bool, i, j *DocumentMatch) int { // compare the documents on all search sorts until a differences is found for x := range so { c := 0 if cachedScoring[x] { if i.Score < j.Score { c = -1 } else if i.Score > j.Score { c = 1 } } else { iVal := i.Sort[x] jVal := j.Sort[x] c = strings.Compare(iVal, jVal) } if c == 0 { continue } if cachedDesc[x] { c = -c } return c } // if they are the same at this point, impose order based on index natural sort order if i.HitNumber == j.HitNumber { return 0 } else if i.HitNumber > j.HitNumber { return 1 } return -1 }
go
func (so SortOrder) Compare(cachedScoring, cachedDesc []bool, i, j *DocumentMatch) int { // compare the documents on all search sorts until a differences is found for x := range so { c := 0 if cachedScoring[x] { if i.Score < j.Score { c = -1 } else if i.Score > j.Score { c = 1 } } else { iVal := i.Sort[x] jVal := j.Sort[x] c = strings.Compare(iVal, jVal) } if c == 0 { continue } if cachedDesc[x] { c = -c } return c } // if they are the same at this point, impose order based on index natural sort order if i.HitNumber == j.HitNumber { return 0 } else if i.HitNumber > j.HitNumber { return 1 } return -1 }
[ "func", "(", "so", "SortOrder", ")", "Compare", "(", "cachedScoring", ",", "cachedDesc", "[", "]", "bool", ",", "i", ",", "j", "*", "DocumentMatch", ")", "int", "{", "// compare the documents on all search sorts until a differences is found", "for", "x", ":=", "range", "so", "{", "c", ":=", "0", "\n", "if", "cachedScoring", "[", "x", "]", "{", "if", "i", ".", "Score", "<", "j", ".", "Score", "{", "c", "=", "-", "1", "\n", "}", "else", "if", "i", ".", "Score", ">", "j", ".", "Score", "{", "c", "=", "1", "\n", "}", "\n", "}", "else", "{", "iVal", ":=", "i", ".", "Sort", "[", "x", "]", "\n", "jVal", ":=", "j", ".", "Sort", "[", "x", "]", "\n", "c", "=", "strings", ".", "Compare", "(", "iVal", ",", "jVal", ")", "\n", "}", "\n\n", "if", "c", "==", "0", "{", "continue", "\n", "}", "\n", "if", "cachedDesc", "[", "x", "]", "{", "c", "=", "-", "c", "\n", "}", "\n", "return", "c", "\n", "}", "\n", "// if they are the same at this point, impose order based on index natural sort order", "if", "i", ".", "HitNumber", "==", "j", ".", "HitNumber", "{", "return", "0", "\n", "}", "else", "if", "i", ".", "HitNumber", ">", "j", ".", "HitNumber", "{", "return", "1", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Compare will compare two document matches using the specified sort order // if both are numbers, we avoid converting back to term
[ "Compare", "will", "compare", "two", "document", "matches", "using", "the", "specified", "sort", "order", "if", "both", "are", "numbers", "we", "avoid", "converting", "back", "to", "term" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/sort.go#L221-L252
162,091
blevesearch/bleve
search/sort.go
UpdateVisitor
func (s *SortField) UpdateVisitor(field string, term []byte) { if field == s.Field { s.values = append(s.values, term) } }
go
func (s *SortField) UpdateVisitor(field string, term []byte) { if field == s.Field { s.values = append(s.values, term) } }
[ "func", "(", "s", "*", "SortField", ")", "UpdateVisitor", "(", "field", "string", ",", "term", "[", "]", "byte", ")", "{", "if", "field", "==", "s", ".", "Field", "{", "s", ".", "values", "=", "append", "(", "s", ".", "values", ",", "term", ")", "\n", "}", "\n", "}" ]
// UpdateVisitor notifies this sort field that in this document // this field has the specified term
[ "UpdateVisitor", "notifies", "this", "sort", "field", "that", "in", "this", "document", "this", "field", "has", "the", "specified", "term" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/sort.go#L352-L356
162,092
blevesearch/bleve
search/sort.go
filterTermsByType
func (s *SortField) filterTermsByType(terms [][]byte) [][]byte { stype := s.Type if stype == SortFieldAuto { allTermsPrefixCoded := true termsWithShiftZero := s.tmp[:0] for _, term := range terms { valid, shift := numeric.ValidPrefixCodedTermBytes(term) if valid && shift == 0 { termsWithShiftZero = append(termsWithShiftZero, term) } else if !valid { allTermsPrefixCoded = false } } if allTermsPrefixCoded { terms = termsWithShiftZero s.tmp = termsWithShiftZero[:0] } } else if stype == SortFieldAsNumber || stype == SortFieldAsDate { termsWithShiftZero := s.tmp[:0] for _, term := range terms { valid, shift := numeric.ValidPrefixCodedTermBytes(term) if valid && shift == 0 { termsWithShiftZero = append(termsWithShiftZero, term) } } terms = termsWithShiftZero s.tmp = termsWithShiftZero[:0] } return terms }
go
func (s *SortField) filterTermsByType(terms [][]byte) [][]byte { stype := s.Type if stype == SortFieldAuto { allTermsPrefixCoded := true termsWithShiftZero := s.tmp[:0] for _, term := range terms { valid, shift := numeric.ValidPrefixCodedTermBytes(term) if valid && shift == 0 { termsWithShiftZero = append(termsWithShiftZero, term) } else if !valid { allTermsPrefixCoded = false } } if allTermsPrefixCoded { terms = termsWithShiftZero s.tmp = termsWithShiftZero[:0] } } else if stype == SortFieldAsNumber || stype == SortFieldAsDate { termsWithShiftZero := s.tmp[:0] for _, term := range terms { valid, shift := numeric.ValidPrefixCodedTermBytes(term) if valid && shift == 0 { termsWithShiftZero = append(termsWithShiftZero, term) } } terms = termsWithShiftZero s.tmp = termsWithShiftZero[:0] } return terms }
[ "func", "(", "s", "*", "SortField", ")", "filterTermsByType", "(", "terms", "[", "]", "[", "]", "byte", ")", "[", "]", "[", "]", "byte", "{", "stype", ":=", "s", ".", "Type", "\n", "if", "stype", "==", "SortFieldAuto", "{", "allTermsPrefixCoded", ":=", "true", "\n", "termsWithShiftZero", ":=", "s", ".", "tmp", "[", ":", "0", "]", "\n", "for", "_", ",", "term", ":=", "range", "terms", "{", "valid", ",", "shift", ":=", "numeric", ".", "ValidPrefixCodedTermBytes", "(", "term", ")", "\n", "if", "valid", "&&", "shift", "==", "0", "{", "termsWithShiftZero", "=", "append", "(", "termsWithShiftZero", ",", "term", ")", "\n", "}", "else", "if", "!", "valid", "{", "allTermsPrefixCoded", "=", "false", "\n", "}", "\n", "}", "\n", "if", "allTermsPrefixCoded", "{", "terms", "=", "termsWithShiftZero", "\n", "s", ".", "tmp", "=", "termsWithShiftZero", "[", ":", "0", "]", "\n", "}", "\n", "}", "else", "if", "stype", "==", "SortFieldAsNumber", "||", "stype", "==", "SortFieldAsDate", "{", "termsWithShiftZero", ":=", "s", ".", "tmp", "[", ":", "0", "]", "\n", "for", "_", ",", "term", ":=", "range", "terms", "{", "valid", ",", "shift", ":=", "numeric", ".", "ValidPrefixCodedTermBytes", "(", "term", ")", "\n", "if", "valid", "&&", "shift", "==", "0", "{", "termsWithShiftZero", "=", "append", "(", "termsWithShiftZero", ",", "term", ")", "\n", "}", "\n", "}", "\n", "terms", "=", "termsWithShiftZero", "\n", "s", ".", "tmp", "=", "termsWithShiftZero", "[", ":", "0", "]", "\n", "}", "\n", "return", "terms", "\n", "}" ]
// filterTermsByType attempts to make one pass on the terms // if we are in auto-mode AND all the terms look like prefix-coded numbers // return only the terms which had shift of 0 // if we are in explicit number or date mode, return only valid // prefix coded numbers with shift of 0
[ "filterTermsByType", "attempts", "to", "make", "one", "pass", "on", "the", "terms", "if", "we", "are", "in", "auto", "-", "mode", "AND", "all", "the", "terms", "look", "like", "prefix", "-", "coded", "numbers", "return", "only", "the", "terms", "which", "had", "shift", "of", "0", "if", "we", "are", "in", "explicit", "number", "or", "date", "mode", "return", "only", "valid", "prefix", "coded", "numbers", "with", "shift", "of", "0" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/sort.go#L405-L434
162,093
blevesearch/bleve
search/sort.go
NewSortGeoDistance
func NewSortGeoDistance(field, unit string, lon, lat float64, desc bool) ( *SortGeoDistance, error) { rv := &SortGeoDistance{ Field: field, Desc: desc, Unit: unit, Lon: lon, Lat: lat, } var err error rv.unitMult, err = geo.ParseDistanceUnit(unit) if err != nil { return nil, err } return rv, nil }
go
func NewSortGeoDistance(field, unit string, lon, lat float64, desc bool) ( *SortGeoDistance, error) { rv := &SortGeoDistance{ Field: field, Desc: desc, Unit: unit, Lon: lon, Lat: lat, } var err error rv.unitMult, err = geo.ParseDistanceUnit(unit) if err != nil { return nil, err } return rv, nil }
[ "func", "NewSortGeoDistance", "(", "field", ",", "unit", "string", ",", "lon", ",", "lat", "float64", ",", "desc", "bool", ")", "(", "*", "SortGeoDistance", ",", "error", ")", "{", "rv", ":=", "&", "SortGeoDistance", "{", "Field", ":", "field", ",", "Desc", ":", "desc", ",", "Unit", ":", "unit", ",", "Lon", ":", "lon", ",", "Lat", ":", "lat", ",", "}", "\n", "var", "err", "error", "\n", "rv", ".", "unitMult", ",", "err", "=", "geo", ".", "ParseDistanceUnit", "(", "unit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "rv", ",", "nil", "\n", "}" ]
// NewSortGeoDistance creates SearchSort instance for sorting documents by // their distance from the specified point.
[ "NewSortGeoDistance", "creates", "SearchSort", "instance", "for", "sorting", "documents", "by", "their", "distance", "from", "the", "specified", "point", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/sort.go#L581-L596
162,094
blevesearch/bleve
search/sort.go
filterTermsByType
func (s *SortGeoDistance) filterTermsByType(terms []string) []string { var termsWithShiftZero []string for _, term := range terms { valid, shift := numeric.ValidPrefixCodedTerm(term) if valid && shift == 0 { termsWithShiftZero = append(termsWithShiftZero, term) } } return termsWithShiftZero }
go
func (s *SortGeoDistance) filterTermsByType(terms []string) []string { var termsWithShiftZero []string for _, term := range terms { valid, shift := numeric.ValidPrefixCodedTerm(term) if valid && shift == 0 { termsWithShiftZero = append(termsWithShiftZero, term) } } return termsWithShiftZero }
[ "func", "(", "s", "*", "SortGeoDistance", ")", "filterTermsByType", "(", "terms", "[", "]", "string", ")", "[", "]", "string", "{", "var", "termsWithShiftZero", "[", "]", "string", "\n", "for", "_", ",", "term", ":=", "range", "terms", "{", "valid", ",", "shift", ":=", "numeric", ".", "ValidPrefixCodedTerm", "(", "term", ")", "\n", "if", "valid", "&&", "shift", "==", "0", "{", "termsWithShiftZero", "=", "append", "(", "termsWithShiftZero", ",", "term", ")", "\n", "}", "\n", "}", "\n", "return", "termsWithShiftZero", "\n", "}" ]
// filterTermsByType attempts to make one pass on the terms // return only valid prefix coded numbers with shift of 0
[ "filterTermsByType", "attempts", "to", "make", "one", "pass", "on", "the", "terms", "return", "only", "valid", "prefix", "coded", "numbers", "with", "shift", "of", "0" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/sort.go#L664-L673
162,095
blevesearch/bleve
numeric/bin.go
Deinterleave
func Deinterleave(b uint64) uint64 { b &= interleaveMagic[0] b = (b ^ (b >> interleaveShift[0])) & interleaveMagic[1] b = (b ^ (b >> interleaveShift[1])) & interleaveMagic[2] b = (b ^ (b >> interleaveShift[2])) & interleaveMagic[3] b = (b ^ (b >> interleaveShift[3])) & interleaveMagic[4] b = (b ^ (b >> interleaveShift[4])) & interleaveMagic[5] return b }
go
func Deinterleave(b uint64) uint64 { b &= interleaveMagic[0] b = (b ^ (b >> interleaveShift[0])) & interleaveMagic[1] b = (b ^ (b >> interleaveShift[1])) & interleaveMagic[2] b = (b ^ (b >> interleaveShift[2])) & interleaveMagic[3] b = (b ^ (b >> interleaveShift[3])) & interleaveMagic[4] b = (b ^ (b >> interleaveShift[4])) & interleaveMagic[5] return b }
[ "func", "Deinterleave", "(", "b", "uint64", ")", "uint64", "{", "b", "&=", "interleaveMagic", "[", "0", "]", "\n", "b", "=", "(", "b", "^", "(", "b", ">>", "interleaveShift", "[", "0", "]", ")", ")", "&", "interleaveMagic", "[", "1", "]", "\n", "b", "=", "(", "b", "^", "(", "b", ">>", "interleaveShift", "[", "1", "]", ")", ")", "&", "interleaveMagic", "[", "2", "]", "\n", "b", "=", "(", "b", "^", "(", "b", ">>", "interleaveShift", "[", "2", "]", ")", ")", "&", "interleaveMagic", "[", "3", "]", "\n", "b", "=", "(", "b", "^", "(", "b", ">>", "interleaveShift", "[", "3", "]", ")", ")", "&", "interleaveMagic", "[", "4", "]", "\n", "b", "=", "(", "b", "^", "(", "b", ">>", "interleaveShift", "[", "4", "]", ")", ")", "&", "interleaveMagic", "[", "5", "]", "\n", "return", "b", "\n", "}" ]
// Deinterleave the 32-bit value starting at position 0 // to get the other 32-bit value, shift it by 1 first
[ "Deinterleave", "the", "32", "-", "bit", "value", "starting", "at", "position", "0", "to", "get", "the", "other", "32", "-", "bit", "value", "shift", "it", "by", "1", "first" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/numeric/bin.go#L35-L43
162,096
blevesearch/bleve
mapping/document.go
analyzerNameForPath
func (dm *DocumentMapping) analyzerNameForPath(path string) string { field := dm.fieldDescribedByPath(path) if field != nil { return field.Analyzer } return "" }
go
func (dm *DocumentMapping) analyzerNameForPath(path string) string { field := dm.fieldDescribedByPath(path) if field != nil { return field.Analyzer } return "" }
[ "func", "(", "dm", "*", "DocumentMapping", ")", "analyzerNameForPath", "(", "path", "string", ")", "string", "{", "field", ":=", "dm", ".", "fieldDescribedByPath", "(", "path", ")", "\n", "if", "field", "!=", "nil", "{", "return", "field", ".", "Analyzer", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// analyzerNameForPath attempts to first find the field // described by this path, then returns the analyzer // configured for that field
[ "analyzerNameForPath", "attempts", "to", "first", "find", "the", "field", "described", "by", "this", "path", "then", "returns", "the", "analyzer", "configured", "for", "that", "field" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/document.go#L90-L96
162,097
blevesearch/bleve
mapping/document.go
documentMappingForPath
func (dm *DocumentMapping) documentMappingForPath(path string) *DocumentMapping { pathElements := decodePath(path) current := dm OUTER: for i, pathElement := range pathElements { for name, subDocMapping := range current.Properties { if name == pathElement { current = subDocMapping continue OUTER } } // no subDocMapping matches this pathElement // only if this is the last element check for field name if i == len(pathElements)-1 { for _, field := range current.Fields { if field.Name == pathElement { break } } } return nil } return current }
go
func (dm *DocumentMapping) documentMappingForPath(path string) *DocumentMapping { pathElements := decodePath(path) current := dm OUTER: for i, pathElement := range pathElements { for name, subDocMapping := range current.Properties { if name == pathElement { current = subDocMapping continue OUTER } } // no subDocMapping matches this pathElement // only if this is the last element check for field name if i == len(pathElements)-1 { for _, field := range current.Fields { if field.Name == pathElement { break } } } return nil } return current }
[ "func", "(", "dm", "*", "DocumentMapping", ")", "documentMappingForPath", "(", "path", "string", ")", "*", "DocumentMapping", "{", "pathElements", ":=", "decodePath", "(", "path", ")", "\n", "current", ":=", "dm", "\n", "OUTER", ":", "for", "i", ",", "pathElement", ":=", "range", "pathElements", "{", "for", "name", ",", "subDocMapping", ":=", "range", "current", ".", "Properties", "{", "if", "name", "==", "pathElement", "{", "current", "=", "subDocMapping", "\n", "continue", "OUTER", "\n", "}", "\n", "}", "\n", "// no subDocMapping matches this pathElement", "// only if this is the last element check for field name", "if", "i", "==", "len", "(", "pathElements", ")", "-", "1", "{", "for", "_", ",", "field", ":=", "range", "current", ".", "Fields", "{", "if", "field", ".", "Name", "==", "pathElement", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "return", "current", "\n", "}" ]
// documentMappingForPath only returns EXACT matches for a sub document // or for an explicitly mapped field, if you want to find the // closest document mapping to a field not explicitly mapped // use closestDocMapping
[ "documentMappingForPath", "only", "returns", "EXACT", "matches", "for", "a", "sub", "document", "or", "for", "an", "explicitly", "mapped", "field", "if", "you", "want", "to", "find", "the", "closest", "document", "mapping", "to", "a", "field", "not", "explicitly", "mapped", "use", "closestDocMapping" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/document.go#L143-L167
162,098
blevesearch/bleve
mapping/document.go
closestDocMapping
func (dm *DocumentMapping) closestDocMapping(path string) *DocumentMapping { pathElements := decodePath(path) current := dm OUTER: for _, pathElement := range pathElements { for name, subDocMapping := range current.Properties { if name == pathElement { current = subDocMapping continue OUTER } } break } return current }
go
func (dm *DocumentMapping) closestDocMapping(path string) *DocumentMapping { pathElements := decodePath(path) current := dm OUTER: for _, pathElement := range pathElements { for name, subDocMapping := range current.Properties { if name == pathElement { current = subDocMapping continue OUTER } } break } return current }
[ "func", "(", "dm", "*", "DocumentMapping", ")", "closestDocMapping", "(", "path", "string", ")", "*", "DocumentMapping", "{", "pathElements", ":=", "decodePath", "(", "path", ")", "\n", "current", ":=", "dm", "\n", "OUTER", ":", "for", "_", ",", "pathElement", ":=", "range", "pathElements", "{", "for", "name", ",", "subDocMapping", ":=", "range", "current", ".", "Properties", "{", "if", "name", "==", "pathElement", "{", "current", "=", "subDocMapping", "\n", "continue", "OUTER", "\n", "}", "\n", "}", "\n", "break", "\n", "}", "\n", "return", "current", "\n", "}" ]
// closestDocMapping findest the most specific document mapping that matches // part of the provided path
[ "closestDocMapping", "findest", "the", "most", "specific", "document", "mapping", "that", "matches", "part", "of", "the", "provided", "path" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/document.go#L171-L185
162,099
blevesearch/bleve
mapping/document.go
AddSubDocumentMapping
func (dm *DocumentMapping) AddSubDocumentMapping(property string, sdm *DocumentMapping) { if dm.Properties == nil { dm.Properties = make(map[string]*DocumentMapping) } dm.Properties[property] = sdm }
go
func (dm *DocumentMapping) AddSubDocumentMapping(property string, sdm *DocumentMapping) { if dm.Properties == nil { dm.Properties = make(map[string]*DocumentMapping) } dm.Properties[property] = sdm }
[ "func", "(", "dm", "*", "DocumentMapping", ")", "AddSubDocumentMapping", "(", "property", "string", ",", "sdm", "*", "DocumentMapping", ")", "{", "if", "dm", ".", "Properties", "==", "nil", "{", "dm", ".", "Properties", "=", "make", "(", "map", "[", "string", "]", "*", "DocumentMapping", ")", "\n", "}", "\n", "dm", ".", "Properties", "[", "property", "]", "=", "sdm", "\n", "}" ]
// AddSubDocumentMapping adds the provided DocumentMapping as a sub-mapping // for the specified named subsection.
[ "AddSubDocumentMapping", "adds", "the", "provided", "DocumentMapping", "as", "a", "sub", "-", "mapping", "for", "the", "specified", "named", "subsection", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/document.go#L213-L218